Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, June 21, 2016

How to check the validity of a WSDL

Java JDK has provided a way to validate the WSDL and is done in the below way,

Command to use to validate the wsdl : 

wsimport <<WSDL Url>>

I have a WSDL at the below given url :

http://localhost/wsdls/Sample.wsdl


Now the browser will not be able to validate the wsdl hence needing a validating step. There can be online validator's or even eclipse plug in can also validate the wsdl. If any of the both steps are possible please go ahead with it, this is the third way of validating where in the guy does not have any access to internet nor does he has an eclipse installed in the machine and in need of validating the wsdl.

Java jdk has provided a way to go ahead with this and the command is shown below,


Note : The above command must be executed from bin directory of a java jdk. Yes, you must be having java jdk for it.

The result of the above command is shown here,


Now if you check the above result, the "parsing WSDL..." is completed without any errors giving us the information that the wsdl is perfectly valid.

Thursday, July 16, 2015

Serialize manually using faster jackson library in spring

I am trying to get a JSON Structure for my object Order which internally has OrderDetails as oneToMany mapping,

@Entity
public class Order {    
    /*
        All the fields associated with this class
    */      
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "orderId")
    private Set<OrderDetails> orderDetails;

    //Getters for all properties defined in this class as jackson would depend on this thing
}
In my case I am using a textWebSocket which is expecting a message only in String format so I need to serialize the objects and push to the client, I am depending on faster jackson to do it and here it goes,

public String getObjectAsString()
{

    //orderObjs : Considering this is the list of objects of class Order

    ObjectMapper objMapper = new ObjectMapper();
            returnValue = objMapper.writerWithType(
                    objMapper.getTypeFactory().constructCollectionType(
                            List.class, Order.class)).writeValueAsString(
                    orderObjs);
    return returnValue;
}

objMapper.writerWithType(objMapper.getTypeFactory().constructCollectionType(List.class,Order.class)).writeValueAsString(orderObjs);

Sunday, March 15, 2015

Padding 0's in XSLT

I want a string to be fixed to 10 digits and pad 0's if it is less than length 10. This I have to achieve in XSLT here is how we can do it,

substring(concat("0000000000",string(//b/text())),string-length(//b/text())+1)

Assuming //b will have the string which is to be formatted.

Where as the same can be achieved using String functions in java,

String.format("%010d", 1236)




Friday, March 13, 2015

Change default program from command line

Sometime we wont be able to open an executable jar using default program after some infinite attempts using "open with". I have faced similar problem as there is a jar which I have to open using javaw.exe and somehow I was unable to. So here is what I have did,

I have changed the default program of jarfile using command line and awesome thing is "IT WORKED" :P

here is the command,

 
And then I opened the jar and It worked,


Tuesday, November 11, 2014

How to trigger a web service from stand alone java

/*
Class EndPoint
*/

package better.faster.smarter.development;

public class EndPoint {
private String hostName="";
public void setHostName(String hostName){
this.hostName=hostName;
}
public String getHostName(){
return this.hostName;
}
}

------------------------------------------------------------------------------------------
/*
Class ExecuteWebService
*/

package better.faster.smarter.development;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class ExecuteWebService {
//soapRequest is a string which is used for executing the web service
@SuppressWarnings("deprecation")
protected static String executeWebService(String soapRequest,EndPoint endPt,String signature)
{
String responseString="";
String hostName="";
URL url=null;
URLConnection urlC=null;
DataOutputStream out =null;
DataInputStream in = null;
String str="";
try{
//Validate the endPoint
if(null==endPt)
throw new RuntimeException("Cannot proceed with executing the web service as the end point is null");
//Get the hostName
hostName=endPt.getHostName();
//Validate the endPoint here as well
if("".equalsIgnoreCase(hostName))
throw new RuntimeException("Cannot proceed with executing the web service as the end point is empty");
//Validate the soap Request
if("".equalsIgnoreCase(soapRequest))
throw new RuntimeException("Cannot proceed with executing the web service as the soap request is invalid");
//Get the header value if header is present then add SOAPHeader else trigger direct soap request
if(signature==null)
signature="";
if(!"".equalsIgnoreCase(signature))
{
soapRequest = "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<SOAP:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
                   signature + "</wsse:Security></SOAP:Header><SOAP:Body>" + soapRequest + "</SOAP:Body></SOAP:Envelope>";
}
//Both soap request and end point are valid if the control comes here
//Initialize url and also urlConnection and all the related parameters. Hard coded few of them as 
//they are rarely used in our application
url = new URL(hostName);
urlC = url.openConnection();
urlC.setRequestProperty("Content-Type", "text/xml");
urlC.setDoInput(true);
urlC.setDoOutput(true);
urlC.setUseCaches(false);
out = new DataOutputStream(urlC.getOutputStream());
out.writeBytes(soapRequest);
in = new DataInputStream(urlC.getInputStream());
responseString="";
while(null!=((str=in.readLine())))
responseString+= str+"\n";
}
catch(Exception e)
{
CustomLogger.logEntry("Exception while executing the soap request with details "+e.getMessage());
}
finally{
hostName=null;
url=null;
urlC=null;
}
return responseString;
}
}
------------------------------------------------------------------------------------
/*
Class TriggerAssertion
*/

package better.faster.smarter.development;

public class TriggerAssertion {

public static void main(String[] args) {
// TODO Auto-generated method stub
EndPoint endPt = new EndPoint();
endPt.setHostName("http://192.168.1.10/cordys/com.eibus.web.soap.Gateway.wcp?");
String userName="icici";
String userPass="icici";
String requestString =
               "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
               "<SOAP:Header>" +
               "<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
               "<wsse:UsernameToken xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
               "<wsse:Username>" + userName + "</wsse:Username>" +
               "<wsse:Password>" + userPass + "</wsse:Password>" +
               "</wsse:UsernameToken>" +
               "</wsse:Security>" +
               "</SOAP:Header>" +
               "<SOAP:Body>" +
               "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" MajorVersion=\"1\" MinorVersion=\"1\">" +
               "<samlp:AuthenticationQuery>" +
               "<saml:Subject xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\">" +
               "<saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\">" + userName + "</saml:NameIdentifier>" +
               "</saml:Subject>" +
               "</samlp:AuthenticationQuery>" +
               "</samlp:Request>" +
               "</SOAP:Body>" +
               "</SOAP:Envelope>";
String responseString = ExecuteWebService.executeWebService(requestString,endPt,"");
String getUserDetails="<GetUserDetails xmlns=\"http://schemas.cordys.com/notification/workflow/1.0\"></GetUserDetails>";
String sos= "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<SOAP:Body>" + getUserDetails + "</SOAP:Body></SOAP:Envelope>";
int ssss = responseString.indexOf("<Signature");
        int k = responseString.indexOf("</samlp:AssertionArtifact>");
        String sigresponse = responseString.substring(ssss, k+26);
responseString=ExecuteWebService.executeWebService(getUserDetails,endPt,sigresponse);
System.out.println(responseString);
}

}


Monday, November 10, 2014

How to get the current working directory from Java

package better.faster.smarter.development;

public class HowToFireWebServiceFromJava {

public static void main(String[] args) {
try{
String curWorkingDir = HowToFireWebServiceFromJava.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println(curWorkingDir);
}
catch(Exception e)
{

}
}
}

Custom Logging from stand alone Java

This post shows how to log manually in a file system from Java without involving cordys.

---------------------------------------------------------------------------------------------------------------

package better.faster.smarter.development;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class CustomLogger {
private static Logger logger = Logger.getLogger("IsureTransUtil");
private static FileHandler fh=null;
protected static void logEntry(String message)
{
try{
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
       Calendar cal = Calendar.getInstance();          
    String logFile="IsureTransUtil_"+dateFormat.format(cal.getTime())+".log"; 
//FileHandler takes two parameter 1st one being the fileName and the second one being append mode. If set to true then it will append to the existing log file else will create new one.
    fh = new FileHandler(logFile,true);        
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();  
       fh.setFormatter(formatter); 
       logger.log(Level.SEVERE, message);        
}
catch(Exception e)
{

}
finally{
//Until you close the file handler the bytes which were written will not get reflected.
fh.close();
}
}
}

-----------------------------------------------------------------------------------------------
Usage of the above class
----------------------------------------------------------

package better.faster.smarter.development;

public class HowToLog{

public static void main(String[] args) {
try{
CustomLogger.logEntry("Started custom Logging");
}
catch(Exception e)
{

}
}
}


Friday, October 31, 2014

How to style a row using POI

/*To style a row a cellStyle instance to be used in POI API and below steps are to be performed*/

/*Create an instance of HSSFCellStyle and it can be created as below
Below wb corresponds to HSSFWorkbook() class
wb = new HSSFWorkbook();
 */

HSSFCellStyle cellStyle = wb.createCellStyle();

/*Then a setFillForegroundColor method to be called using the color index. The color index is a short variable and defined as below*/

cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

/*A setFillPattern method is to be called with another short variable to be sent as a variable*/

cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

/*Finally a cellStyle variable is ready and can be used to apply style but note that this style will be over written when you try to write value in the cell*/
/*The same style should be applied when writing the cellValue as shown further in the code*/

header.setRowStyle(cellStyle);

/*This creates a cell with value as 'Sample value' not this will remove the styling applied to the row and hence the styling should be applied again*/ 

header.createCell(1).setCellValue("Sample value");

/*As explained before the styling pattern is applied again*/

header.getCell(1).setCellStyle(cellStyle);
fileOutputStream = new FileOutputStream(filePath +"\\ExcelUtilities.xls");
wb.write(fileOutputStream);
fileOutputStream.close();


Friday, October 17, 2014

Sample function on how to generate an excel

Advantages of below method is Query and the template columns are dynamic
----------------------------------------------------------------------------------------------------

public static int generateTemplateDashboard(String MONTH,String YEAR,String TEMPLATE_NAME)
{
int response=0;
String responseStr="<OperationResult><Status/><StatusMessage/><FilePath/></OperationResult>";
Document doc = new Document();
String queryText="";
QueryObject query = null;
BusObjectIterator wholsaleItems=null;
int templateData=0;
int queryTemplateConfig=0;
int temptableHeaderData=0;
String excelHeaders[]=null;
String columnNames[]=null;
String dataTypes[]=null;
String columnData[]=null;
int responseData=0;
try{
oDoc=BSF.getXMLDocument();
response = doc.parseString(responseStr);
//Loading Query Template from configuration
queryTemplateConfig = oDoc.load(installDir + "\\com\\vw\\mars\\ExportXLQueriesConfig.xml");
queryText = Node.getData(XPath.getFirstMatch(".//QUERY[@TEMPLATE_NAME='"+TEMPLATE_NAME+"']", null, queryTemplateConfig));
logger.log(Severity.WARN, "Logging the query text as "+queryText);
if(queryText==null || queryText.equalsIgnoreCase(""))
throw new BsfRuntimeException("Query Template not found from the configuration");
query = new QueryObject(queryText);
query.addParameter("MONTH", "MARS_WHOLSALE_FORECASTS.MONTH", QueryObject.PARAM_STRING, MONTH);
query.addParameter("YEAR", "MARS_WHOLSALE_FORECASTS.YEAR", QueryObject.PARAM_STRING, YEAR);
wholsaleItems = query.getObjects();
if(logger.isWarningEnabled())
logger.log(Severity.WARN, "Query got executed with data "+Node.writeToString(query.execute().getDatasetNode(), true));
//Write the header of the excel
HSSFWorkbook wb = null;
HSSFSheet marsSheet = null;
Row header = null;
String filePath = props.getProperty("mars.download.directory");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String currentTimeStamp = sdf.format(getCurrentDate());
String fileName = "Dashboard_"+YEAR + "_" + MONTH + "_" + currentTimeStamp + ".xls";
String abPth = "";
abPth = filePath + "\\"+TEMPLATE_NAME;
logger.log(Severity.WARN, "Logging absolute path as "+abPth);
//Creating the directory if it is not present
File createFolders = new File(filePath + "\\" + YEAR + "\\" + MONTH);
createFolders.mkdirs();
logger.log(Severity.WARN,"Directory created");
wb = new HSSFWorkbook(); // new HSSFWorkbook();
marsSheet = wb.createSheet(TEMPLATE_NAME);
header = marsSheet.createRow(0);

//Read the header columns from ExportConfig.xml
templateData = oDoc.load(installDir+ "\\com\\vw\\mars\\ExportXLConfig.xml");
logger.log(Severity.WARN, "Logging Export XL Config file "+Node.writeToString(templateData,true));
temptableHeaderData = XPath.getFirstMatch(".//*[local-name()='filetype'][@name='"+TEMPLATE_NAME+"']", null, templateData);
logger.log(Severity.WARN, "Logging template header data node "+Node.writeToString(temptableHeaderData,true));

int length = XPath.getMatchingNodes(".//*[local-name()='field']", null, temptableHeaderData).length;
excelHeaders = new String[length];
columnNames = new String[length];
dataTypes = new String[length];
columnData = new String[length];
for (int i = 0; i < length; i++) {
excelHeaders[i] = Node.getAttribute(XPath.getFirstMatch(".//*[local-name()='field'][@cell='" + i + "']",null, temptableHeaderData), "header_name", "");
columnNames[i] = Node.getAttribute(XPath.getFirstMatch(".//*[local-name()='field'][@cell='" + i + "']",null, temptableHeaderData), "name", "");
dataTypes[i] = Node.getAttribute(XPath.getFirstMatch(".//*[local-name()='field'][@cell='" + i + "']",null, temptableHeaderData), "datatype", "");
}
logger.log(Severity.WARN,"Finished reading the template and stored all the headers with datatypes into string arrays ");
for (int i = 0; i < excelHeaders.length; i++)
header.createCell(i).setCellValue(excelHeaders[i]);
logger.log(Severity.WARN, "Finished writing headers of the dashboard excel");
responseData = TupleHandling.makeTupleSet(wholsaleItems, null);
int tupleRecords[] = XPath.getMatchingNodes(
".//*[local-name()='tuple']", null, responseData);
for (int i = 0; i < tupleRecords.length; i++) {
header = marsSheet.createRow(i + 1);
for (int j = 0; j < columnNames.length; j++) {
columnData[j] = Node.getData(Node.getFirstChild(XPath.getFirstMatch(".//*[local-name()='"+ columnNames[j]+ "']", null,tupleRecords[i])));
logger.log(Severity.WARN, "Reading Column value as "+columnData[j]);
}
if (tupleRecords[i] > 0)
Node.delete(tupleRecords[i]);
logger.log(Severity.WARN,"Deleted the tupleRecord[i]");
for (int j = 0; j < columnData.length; j++)
{
if(dataTypes[j].equalsIgnoreCase("NUMERIC"))
{
header.createCell(j).setCellValue(Integer.valueOf(columnData[j]));
header.getCell(j).setCellType(Cell.CELL_TYPE_NUMERIC);
}
else if(dataTypes[j].equalsIgnoreCase("STRING"))
{
header.createCell(j).setCellValue(columnData[j]);
header.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
}
}
}
for (int i = 0; i < excelHeaders.length; i++)
marsSheet.autoSizeColumn(i);
FileOutputStream fileOutputStream = new FileOutputStream(filePath + "\\" + YEAR + "\\" + MONTH + "\\"+ fileName);
wb.write(fileOutputStream);
fileOutputStream.close();
logger.log(Severity.WARN, "Successfully written the excel template at "+filePath);
Node.setDataElement(response, "Status", "SUCCESS");
Node.setDataElement(response, "StatusMessage", "Application is successful in generating zonal allocation dashboard excel");
Node.setDataElement(response, "FilePath", filePath);
}
catch(Exception e)
{
Node.setDataElement(response, "Status", "FAILED");
Node.setDataElement(response, "StatusMessage", "Application has encountered exception while generating dashboard with details "+e.getMessage());
logger.log(Severity.ERROR,"Exception in generateTemplateDashboard ",e);
}
finally{
if(Node.isValidNode(templateData))
Node.delete(templateData);
if(Node.isValidNode(temptableHeaderData))
Node.delete(temptableHeaderData);
if(Node.isValidNode(queryTemplateConfig))
Node.delete(queryTemplateConfig);
if(Node.isValidNode(responseData))
Node.delete(responseData);
query = null;
wholsaleItems = null;
}
return response;
}

Thursday, August 28, 2014

Change the version of Java to 1.7 when 1.6 is already installed

This post is to get knowledge on how to change the versions of java when there are multiple versions installed in any machine.

Platform : Windows 7
Java Versions installed : 1.6 and 1.7

We were facing an error when we tried to check the version of java from command prompt using the command "Java -version" the error seemed something like this,


One has to do the below steps to change the version of java to 1.7


  1. Open registry editor from Run window

  2. Go to the Java Run time environment from the tree of registry editor

  3. Check the current version

  4. Update the current version to 1.7

  5. Check the version from command prompt


Monday, July 21, 2014

How to execute a window command from Java

This java code will show how can we execute a windows command from Java

package commons.utilities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExecuteCommandFromJava {
public static void main(String[] args) throws IOException {
   String[] command = new String[3];
        command[0] = "cmd";
        command[1] = "/c";
        command[2] = "E: && dir && cd snap";
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String Error;
        while ((Error = stdError.readLine()) != null) {
            System.out.println(Error);
        }
        while ((Error = stdInput.readLine()) != null) {
            System.out.println(Error);
        }
}
}

Monday, May 26, 2014

Log from Java method in WSO2 Framework

Pre-Requisites :

  Ø 
Application server should be up and running.
   Ø  Should be able to write a simple java method using eclipse.
   Ø  One should have knowledge on how to deploy the service from java methods.
   Ø  Should be able to test the service after deployment.

Steps :

    Ø Write a simple Custom Java method by following syntax.


  import org.apache.commons.logging.Log;
      import org.apache.commons.logging.LogFactory;

 private static Log eventLogger = LogFactory.getLog(HelloDH.class);

   Ø  Create a jar and deploy it in the application server (Or Any other way of deploying the java methods onto application server).

   Ø  Test and check for the logs.

o   Test the service by searching for the web service and once tested,You can check for the log as shown in the below screenshot.


You can even find the logs in file system. For ex., "
E:\Kiran\Softwares DH\WSO2\WSO2\wso2as-5.2.1\wso2as-5.2.1\repository\logs"

Tuesday, April 8, 2014

Write a file from Java with Encoding "UTF-8 Without BOM"

The ultimate goal is to write the file with different encoding types (ANSI/UTF-8/UTF-8 without BOM):

The Code which I will be referring through out this post would be below
public static void main(String[] args) throws IOException {
OutputStreamWriter osw = null;
try{
//Example to write a file into file system
//Charset windows1252 = Charset.forName("windows-1252");
String filePath="D:\\temp\\";
filePath = filePath.concat(String.valueOf(new Date().getTime())).concat(".txt");
FileOutputStream fos = new FileOutputStream(filePath,false);
osw = new OutputStreamWriter(fos,"UTF-8");
osw.write("Sample");
osw.write("\uFEFF");
osw.write("File");
//osw.write(Charset.forName("UTF-8").encode("Sample"));
osw.close();
System.out.println("Success");
fos.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
osw.close();
}
}
Scenario 1: (You want to write a file with "ANSI" encoding) Below url helps


Writing straight forwardly(Simple plain text) would save the file in ANSI format even though your output stream reader has a character set "UTF-8". It is because there are no UTF-8 characters that you are writing. Unless you write UTF-8 characters the file will not change from ANSI. 


But if your requirement is not this, You have simple plain text but you have to write a file in UTF-8 Encoding you have to go through below,

Scenario 2: UTF-8 Encoding is divided into two types 1. With BOM and 2. Without BOM

Following piece of code helps to write a file with BOM,
Here adding \uFEFF character at initial block would make this file as UTF-8 with BOM,

The result of above code is shown below
Now your requirement is still not this, You have a simple plain text but you want to write the file with encoding as "Encoding in UTF-8 without BOM". Please refer scenario 3.

Scenario 3: (Write file using UTF-8 without BOM).

You just have to make sure you write "\uFEFF" character to make the file as "UTF-8" and write it after some simple text to make the encoding as "UTF-8 without BOM".

The result would be as shown below
Note : The encoding what this post is talking about all are taken from Notepad++