java.lang.RuntimeException: Failed : HTTP error code : 404 - docusignapi

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("https://demo.docusign.net/restapi/v2/login_information");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.ops.tiaa-cref.org", 8080));
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(proxy);
conn.setRequestMethod("GET");
conn.setRequestProperty("content-type", "application/json");
conn.setRequestProperty("Username", "puviars#gmail.com");
conn.setRequestProperty("Password", "*******");
conn.setRequestProperty("IntegratorKey", "TIAC-e30cd896-cd8b-4cca-8551-86b8c51ea85a");
//conn.setRequestProperty("X-DocuSign-Authentication","{\"Username\":\"puviars#gmail.com\",\"Password\":\"********\",\"IntegratorKey\":\"TIAC-e30cd896-cd8b-4cca-8551-86b8c51ea85a\"}");
//String input = "{\"api_password\":\"false\",\"include_account_id_guid\":\"false\",\"login_settings\":\"none\"}";
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("api_password", "true"));
params.add(new BasicNameValuePair("include_account_id_guid", "false"));
params.add(new BasicNameValuePair("login_settings", "all"));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
//conn.setDoOutput(true);
//OutputStream os = conn.getOutputStream();
//os.write(input.getBytes());
//os.flush();
//conn.setRequestProperty("api_password","false");
//conn.setRequestProperty("include_account_id_guid","false");
//conn.setRequestProperty("login_settings","none");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
//
while invoking rest url via httpsurlconnection, the below code in eclispe IDE using run as java program.i am getting the below error:
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 404
at NetClientGet.main(NetClientGet.java:71)
Please help me to resolve it. This code is just to hit demo url to login & fetch the details & then i will proceed to send the pdf documents to esign it.But if am using their interactive website i could get the response in JSON.
//

Related

Header not showing in PDF document

I am trying to add a header to each page in my document.
I am using OpenPDF 1.3.29 installed through Maven.
Here is a test program:
package test;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
public class HeaderTest {
public static void main(String[] args)
throws Exception {
Document doc = null;
PdfWriter writer = null;
try {
doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
writer = PdfWriter.getInstance(doc, new FileOutputStream("C:\\Tmp\\test.pdf"));
doc.open();
Font headerFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD,18);
HeaderFooter header = new HeaderFooter(new Phrase("Test Header",headerFont), false);
doc.setHeader(header);
doc.add(new Paragraph("Test Content"));
} finally {
try { doc.close(); } catch( Exception e ) { }
try { writer.close(); } catch( Exception e ) { }
}
}
}
The resulting PDF contains the content paragraph, but not the header.
Looking at the sample code, this seems like it should work.
Any idea what I did wrong?
I figured it out.
I needed to set the header and footer before calling open() on the document.
Also, I changed the header and footer to use Paragraph instead of Phrase. This is strange because the JavaDocs use Phrase.
Anyway, this code works as expected:
package test;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
public class HeaderTest {
public static void main(String[] args)
throws Exception {
Document doc = null;
PdfWriter writer = null;
try {
doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
writer = PdfWriter.getInstance(doc, new FileOutputStream("C:\\Tmp\\test.pdf"));
HeaderFooter header = new HeaderFooter(new Paragraph("Test Header"), false);
header.setAlignment(HeaderFooter.ALIGN_CENTER);
header.setBorder(Rectangle.NO_BORDER);
doc.setHeader(header);
HeaderFooter footer = new HeaderFooter(new Paragraph("This is page: "), true);
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_RIGHT);
doc.setFooter(footer);
doc.open();
doc.add(new Paragraph("Test Content"));
} finally {
try { doc.close(); } catch( Exception e ) { }
try { writer.close(); } catch( Exception e ) { }
}
}
}

Java web app trying trying to download info from API not working

I have a Java web app made in JSF that connects to a API fills a datatable with info and every row has download button. When I press download button it does another get request with an id taken from the row the button was clicked. But when I press the download button I get this message :
emptyResponse: An empty response was received from the server. Check server error logs.
The server log doesn`t show any error.
This is the code:
package com.serban;
import com.google.common.io.ByteStreams;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import static java.lang.System.out;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#ManagedBean(name = "logic", eager = true)
#SessionScoped
public class Logic implements Serializable {
static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;
private ArrayList<Mesaj> logics;
StringBuilder sb = new StringBuilder();
String cif2;
String data_creare2;
String id_solicitare2;
String tip2;
String id2;
String detalii2;
String numar2;
/**
*
* #throws ParseException
*/
public void apelareApi() {
try {
URL url = new URL("xxx");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
sb.append(inputLine+"\n");
}
in.close();
}catch(Exception e) {System.out.println(e);}
}
public void incarcareLista() throws ParseException {
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
logics = new ArrayList<Mesaj>();
for(int i = 0; i < cat.size(); i++) {
Mesaj m = new Mesaj();
jo = (JSONObject) cat.get(i);
cif2 = jo.get("cif").toString();
data_creare2 = jo.get("data_creare").toString();
id_solicitare2 = jo.get("id_solicitare").toString();
tip2 = jo.get("tip").toString();
id2 = jo.get("id").toString();
detalii2 = jo.get("detalii").toString();
numar2 = Integer.toString(i+1);
m.setCif(cif2);
m.setData_creare(data_creare2);
m.setId_solicitare(id_solicitare2);
m.setTip(tip2);
m.setId(id2);
m.setDetalii(detalii2);
m.setNumar(numar2);
logics.add(m);
}
}
/**
*
* #throws ParseException
*/
#PostConstruct
public void apelareSiIncarcare() {
apelareApi();
try {
incarcareLista();
} catch (ParseException ex) {
Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<Mesaj> getLogics() {
return logics;
}
public Logic() {
}
String x;
String id;
byte[] rasp;
public void printNumar(String x) throws IOException {
this.x = x;
//System.out.println(x);
int y = Integer.parseInt(x);
jo = (JSONObject) cat.get(y-1);
System.out.println(jo.get("id"));
id = jo.get("id").toString();
rasp = apelareApi2(id);
startDownload(rasp);
}
byte[] byteChunk;
public byte[] apelareApi2(String z) throws IOException {
URL url = new URL("xxx"+z);
URLConnection yc = url.openConnection();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byteChunk = new byte[is.available()]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(),e.getMessage());e.printStackTrace ();}finally {
if (is != null) { is.close(); }
}
return byteChunk;
}
private void startDownload(byte[] continut)
throws IOException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
// externalContext.responseReset();
externalContext.setResponseHeader("Cache-Control", "public");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-Type", "application/pdf");
externalContext.setResponseHeader("Content-Length",
Integer.toString(continut.length));
externalContext.setResponseHeader("Content-Disposition",
"attachment;filename=\"" + "id.pdf" + "\"");
externalContext.getResponseOutputStream().write(continut);
facesContext.responseComplete();
}
}
The error message is thrown by Mojarra JSF if an AJAX response is received which does not contain XML as pointed out here and here in the jsf-uncompressed.js:
* Receive an Ajax response
* from the server.
* Usage:
*
* jsf.ajax.response(request, context);
*
* Implementation Requirements:
* This function must evaluate the markup returned in the
* request.responseXML object and perform the following action:
*
* If there is no XML response returned, signal an "emptyResponse"
* error.
...
} else if (status == "emptyResponse") {
data.description = "An empty response was received from the server. Check server error logs.";
This shows you are using AJAX. As BalusC stated, JavaScript is not permitted to launch the Save document dialog here: How to provide a file download from a JSF backing bean?
So the solution bringing you one step closer is: turn off AJAX.

how to validate an xml string in java?

I have seen some examples here, which show how to validate an xml File (It´s workking), but my question is: How can I modify this code to validate an String
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.util.List;
import java.io.*;
import java.util.LinkedList;
import java.net.URL;
import java.sql.Clob;
import java.sql.SQLException;
public class Validate {
public String validaXML(){
try {
Source xmlFile = new StreamSource(new File("C:\\Users\\Desktop\\info.xml"));
URL schemaFile = new URL("https://www.w3.org/2001/XMLSchema.xsd");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
final List exceptions = new LinkedList();
validator.setErrorHandler(new ErrorHandler()
{
#Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
#Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
#Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
validator.validate(xmlFile);
} catch (SAXException ex) {
System.out.println( ex.getMessage());
return ex.getMessage().toString();
} catch (IOException e) {
System.out.println( e.getMessage());
return e.getMessage().toString();
}
return "Valid";
}
public static void main(String[] args) {
String res;
Validate val = new Validate();
res=val.validaXML();
System.out.println(res);
}
}
I have tried with this:
Source xmlFile = new StreamSource("<Project><Name>sample</Name></Project>");
It compiles, but I got this:
"no protocol: sample"
Thanks for reading I´ll apreciate you opinion
The reason why that doesnt work is the constructor your using is StreamSource(String systemId). The String constructor on StreamSource doesnt take xml.
Use the constructor StreamSource(Reader reader) and make an reader, such as
new StreamSource(new StringReader("xml here"))
or you can use the constructor StreamSource(InputStream inputStream) as
new StreamSource(new ByteArrayInputStream("xml here".getBytes()))

Run appium test with Testng and logj4,Get err instantiating class org.apache.logging.log4j.spi.Provider

I'm trying to run an appium test on a real ios device using java, testng, and log4j. I am not too familiar with log4j. I am getting the following error in eclipse.
org.testng.TestNGException:
An error occurred while instantiating class MobileTests.AppiumIOSTestAppTest1: org.apache.logging.log4j.spi.Provider: Provider org.apache.logging.slf4j.SLF4JProvider not found
package MobileTests;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import org.apache.log4j.Logger;
import Base.TestBase;
import Common.ScreenshotURL;
import Locators.LocatorMethods;
public class AppiumIOSTestAppTest1 extends TestBase{
static SoftAssert softAssert = new SoftAssert();
static Logger log = Logger.getLogger(AppiumIOSTestAppTest1.class);
String className = this.getClass().getSimpleName();
Date date1= new Date();
String originaltimestamp = new Timestamp(date1.getTime()).toString();
String timestamp = originaltimestamp.replace(':', 'x').substring(11);
String foldername = folderpath+className+timestamp;
String error = "";
String errorname = "";
#Test
public void iosTestAppTest1 () throws IOException, InterruptedException
{
try
{
LocatorMethods.clickByXpath(driver, "textfield1.xpath");
LocatorMethods.sendKeysIntoElementByXpath(driver, "textfield1.xpath", Integer.toString(8));
LocatorMethods.clickByXpath(driver, "textfield2.xpath");
LocatorMethods.sendKeysIntoElementByXpath(driver, "textfield2.xpath", Integer.toString(9));
LocatorMethods.clickByXpath(driver, "compute.xpath");
String answer = LocatorMethods.getTextByXpath(driver, "answer.xpath");
try
{
Assert.assertTrue(answer.equalsIgnoreCase(Integer.toString(17)), "Answer is wrong.");
}
catch(AssertionError e)
{
log.debug("Wrong answer was calculated.");
log.error("This is an exception", e);
//error = e.toString();
//System.out.println(error);
errorname = "wronganswer";
ScreenshotURL.screenshotURL(driver, foldername, errorname, error);
softAssert.fail();
}
}
catch(AssertionError e)
{
System.out.println(e);
}
softAssert.assertAll();
}
#AfterMethod
public static void OnFailure(ITestResult testResult) throws IOException {
if (testResult.getStatus() == ITestResult.FAILURE)
{
System.out.println(testResult.getStatus());
}
}
}

how to convert java multipart file upload program to groovy

Below is my code and log of the cast Exception
Getting the castException if i run the same code in groovy IDE (intelli idea)
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.http.impl.client.DefaultHttpClient;
public class File2 {
private static String paramNameCobSessionToken = "03172014_0:78bf85ca1f";
private static String paramNameUserSessionToken = "dvsdfsdff8d7";
public String verifyAndUpdateBridgetApp(String cobrandSessionToken,String userSessionToken) {
DefaultHttpClient httpclient = new DefaultHttpClient();
String response = null;
System.out.println("hello");
String HOST_URI3 = "https://192.168:10443/srest/v1.0/";
String url = HOST_URI3 + "/updateBridgetData";
try {
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
PostMethod pm = new PostMethod(url);
NameValuePair[] params = new NameValuePair[4];
params[0] = new NameValuePair("cobSessionToken", paramNameCobSessionToken);
params[1] = new NameValuePair("userSessionToken", paramNameUserSessionToken);
params[2] = new NameValuePair("bridgetMetaData.bridgetKeyData.bridgetAppId", "10009959");
params[3] = new NameValuePair("bridgetMetaData.bridgetSource.fileName", "bundle.zip");
pm.setQueryString(params);
String sourceFile = "D:\\bundle\\bundle\\bundle.zip";
File f = new File(sourceFile);
Part[] parts = {new FilePart("bridgetMetaData.bridgetSource.bundledZipFile", f)};
pm.setRequestEntity(new MultipartRequestEntity(parts, pm.getParams()));
HttpClient hc = new HttpClient();
int RC = hc.executeMethod(pm);
System.out.println("Response Status Code : " + RC);
response = pm.getResponseBodyAsString();
System.out.println("The response is " + response);
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return response;
}
static class NullHostnameVerifier implements HostnameVerifier
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
public static void main(String[] args){
File2 upload=new File2();
upload.verifyAndUpdateBridgetApp(paramNameCobSessionToken, paramNameUserSessionToken);
}
}
Error log
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'File2$_verifyAndUpdateBridgetApp_closure1#189f854' with class
'File2$_verifyAndUpdateBridgetApp_closure1' to class 'org.apache.commons.httpclient.methods.multipart.Part'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:371)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.asArray(DefaultTypeTransformation.java:445)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:204)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:599)
at File2.verifyAndUpdateBridgetApp(File2.groovy:48)
at File2$verifyAndUpdateBridgetApp.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at File2.main(File2.groovy:75)
You need to use [] not {} when defining your Part[]
Part[] parts = [new FilePart("bridgetMetaData.bridgetSource.bundledZipFile", f)]

Resources