So I have a script file we are using in house for testing. I want to use the script for testing over the internet but when I give it a url instead of a ip address it throws a java.lang.NoClassDefFoundError,
Why is this and what can I do to fix it
this is the script file:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class SOAPClient4XG
{
public static void main(String[] paramArrayOfString)
throws Exception
{
if (paramArrayOfString.length < 2) {
System.err.println("Usage: java SOAPClient4XG http://soapURL soapEnvelopefile.xml [SOAPAction]");
System.err.println("SOAPAction is optional.");
System.exit(1);
}
String str1 = paramArrayOfString[0];
String str2 = paramArrayOfString[1];
String str3 = "";
if (paramArrayOfString.length > 2) {
str3 = paramArrayOfString[2];
}
URL localURL = new URL(str1);
URLConnection localURLConnection = localURL.openConnection();
HttpURLConnection localHttpURLConnection = (HttpURLConnection)localURLConnection;
FileInputStream localFileInputStream = new FileInputStream(str2);
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
copy(localFileInputStream, localByteArrayOutputStream);
localFileInputStream.close();
byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
localHttpURLConnection.setRequestProperty("Content-Length", String.valueOf(arrayOfByte.length));
localHttpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
localHttpURLConnection.setRequestProperty("SOAPAction", str3);
localHttpURLConnection.setRequestMethod("POST");
localHttpURLConnection.setDoOutput(true);
localHttpURLConnection.setDoInput(true);
OutputStream localOutputStream = localHttpURLConnection.getOutputStream();
localOutputStream.write(arrayOfByte);
localOutputStream.close();
InputStreamReader localInputStreamReader = new InputStreamReader(localHttpURLConnection.getInputStream());
BufferedReader localBufferedReader = new BufferedReader(localInputStreamReader);
String str4;
while ((str4 = localBufferedReader.readLine()) != null) {
System.out.println(str4);
}
localBufferedReader.close();
}
public static void copy(InputStream paramInputStream, OutputStream paramOutputStream)
throws IOException
{
synchronized ()
{
synchronized (paramOutputStream)
{
byte[] arrayOfByte = new byte['Ā'];
for (;;) {
int i = paramInputStream.read(arrayOfByte);
if (i == -1) break;
paramOutputStream.write(arrayOfByte, 0, i);
}
}
}
}
}
and the bat file used to run it is this:
echo Check in inquiry sending:
java -cp .SOAPClient4XG http://foobar/gotdns/com:8080/axis2/services/HTNGListener checkininquiry.sms http://htng.org/1.1/Listener.Wsdl#ReceiveMessageAsync
here is the stack trace:
C:\Documents and Settings\accounting\Desktop\springer_miller_docs>java -cp .SOAP
Client4XG http://foobar.gotdns.com:8080/axis2/services/HTNGListener checkinin
quiry.sms http://htng.org/1.1/Listener.Wsdl#ReceiveMessageAsync
Exception in thread "main" java.lang.NoClassDefFoundError: http://foobar/gotd
ns/com:8080/axis2/services/HTNGListener
Your problem has nothing to do with your code but how you're executing it.
Your command line says put the main file onto the class path and then execute main in a class named the first URL.
Leave off -cp and you should be fine (at least from this stack trace).
For reference: http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html
This line of code
URL localURL = new URL(str1);
will throw a java.net.MalformedURLException: no protocol: 192.168.0.127 for the argument you're giving it.
URL is protocol aware, and you should give it something like http://soapURL (as advised by your program itself) instead of a plain IP address.
edit
not relevant after you changed your question.
Related
I have spring boot app. I am trying to read json file which is located in my resource folder (using class loader). I have deployed my app on azure its giving me error no such file exist and when i print path it is giving me null.
I tried to create a simple Maven project to fix your issue.
My source code structure is like below.
simpleMavenProj
|-src/main/java/Hello.java
|-src/main/resources/hello.json
The content of Hello.java is as below.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class Hello {
public static void main(String[] args) throws IOException {
InputStream resourceInputStream = null;
URL resourceURL = Hello.class.getClassLoader().getResource("resources/hello.json");
if(resourceURL == null) {
System.out.println("Get the InputStream of hello.json in IDE");
resourceInputStream = new FileInputStream(Hello.class.getClassLoader().getResource("").getPath()+"../../src/main/resources/hello.json");
} else {
System.out.println("Get the InputStream of hello.json from runnable jar");
resourceInputStream = Hello.class.getClassLoader().getResourceAsStream("resources/hello.json");
}
System.out.println();
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(resourceInputStream));
String line = null;
while((line = br.readLine()) != null) {
builder.append(line+"\n");
}
br.close();
System.out.println(builder.toString());
}
}
And hello.json:
{
"hello":"world"
}
If you are developing in an IDE, run the code and the result is:
Get the InputStream of hello.json in IDE
{
"hello":"world"
}
Else for generating a runable jar file, then to run the jar file via java -jar simpleMavenProj.jar and the result is:
Get the InputStream of hello.json from runnable jar
{
"hello":"world"
}
Hope it helps. Any concern, please feel free to let me know.
I have this sample code written in Java that explains how to call a method of a REST Api:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apac he.commons.io.FileUtils;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
public class Test {
public static void main(String[] args) {
String alias = "ABCD";
String pin = "012345";
String originFileName = "C:\file.pdf";
String destinationFilename = "C:\file2.pdf";
String urlService = "https://serviceUrl";
Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
FormDataMultiPart form = new FormDataMultiPart();
form.field("pin", pin);
form.bodyPart(new FileDataBodyPart("content", new File(originFileName)));
Response response = client.target(urlService).path("/auto/action/name/" + alias).request(MediaType.MULTIPART_FORM_DATA).post(Entity.entity(form, form.getMediaType()));
if (response.getStatus() == 200) {
InputStream file = response.readEntity(InputStream.class);
File targetFile = new File(destinationFilename);
try {
FileUtils.copyInputStreamToFile(file, targetFile);
System.out.print("Success");
} catch (IOException e) {
e.printStackTrace();
System.out.print("Error");
}
} else {
System.out.print("Error:" + response.readEntity(String.class));
}
}
}
In my application I've converted it to something like this:
Dim userAlias As String = "ABCD"
Dim pin As HttpContent = New StringContent("012345")
Dim content As HttpContent = New StreamContent(File.OpenRead(originFileName))
Using client = New HttpClient()
client.BaseAddress = New Uri(urlService)
Using formData = New MultipartFormDataContent()
formData.Add(pinCode, "pin", "pin")
formData.Add(content, "test", "test")
Dim response = client.PostAsync("/auto/sign/pades/" + userAlias, formData).Result
If response.StatusCode = 200 Then
Return response.Content.ReadAsStreamAsync().Result
Else
MessageBox.Show(response.ReasonPhrase)
Return Nothing
End If
End Using
End Using
As a result I get a 500 Internal Server Error.
I checked the service url and it's correct, so I guess I'm doing something wrong in the MultipartFormDataContent creation.
I found out that the error was caused by a typo in the name of the parameter I was uploading.
The way I created the MultipartFormDataContent was actually correct.
Thanks to #Chillzy for the suggestion that made me rewrite my code finding the typo.
I am working with the ETrade Java API. I was able to use most of the functions but I am having trouble with the previewEquityOrder and the previewOptionOrder functions. Here are the error messages/ exceptions I get when I call these functions:
URL : https://etwssandbox.etrade.com/order/sandbox/rest/previewequityorder
? Java exception occurred:
com.etrade.etws.sdk.common.ETWSException
at com.etrade.etws.sdk.common.ETWSUtil.constructException(ETWSUtil.java:9)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:90)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:32)
at com.etrade.etws.sdk.client.OrderClient.previewEquityOrder(OrderClient.java:145)
For the previewOptionOrder:
URL : https://etwssandbox.etrade.com/order/sandbox/rest/previewoptionorder
? Java exception occurred:
com.etrade.etws.sdk.common.ETWSException
at com.etrade.etws.sdk.common.ETWSUtil.constructException(ETWSUtil.java:9)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:90)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:32)
at com.etrade.etws.sdk.client.OrderClient.previewOptionOrder(OrderClient.java:167)
The following Java code can reproduce the problem. You can compile this code on a Mac using the following command. On windows machine, replace the " : " with " ; " as the separator.
javac -classpath "./commons-codec-1.3.jar:./commons-httpclient-3.1.jar:./commons-httpclient-contrib-ssl-3.1.jar:./commons-lang-2.4-javadoc.jar:./commons-lang-2.4-sources.jar:./commons-lang-2.4.jar:./commons-logging-api.jar:./commons-logging.jar:./etws-accounts-sdk-1.0.jar:./etws-common-connections-1.0.jar:./etws-market-sdk-1.0.jar:./etws-oauth-sdk-1.0.jar:./etws-order-sdk-1.0.jar:./log4j-1.2.15.jar:./xstream-1.3.1.jar:" test.java
You can run the compiled class from command line using the following command:
java -classpath "./commons-codec-1.3.jar:./commons-httpclient-3.1.jar:./commons-httpclient-contrib-ssl-3.1.jar:./commons-lang-2.4-javadoc.jar:./commons-lang-2.4-sources.jar:./commons-lang-2.4.jar:./commons-logging-api.jar:./commons-logging.jar:./etws-accounts-sdk-1.0.jar:./etws-common-connections-1.0.jar:./etws-market-sdk-1.0.jar:./etws-oauth-sdk-1.0.jar:./etws-order-sdk-1.0.jar:./log4j-1.2.15.jar:./xstream-1.3.1.jar:" test <consumer_key> <consumer_secret>
You will need to pass in the ETrade consumer key and consumer secret as command line arguments to run this.
Notice that the authentication part works which is verified by getting the accounts list.
import com.etrade.etws.account.Account;
import com.etrade.etws.account.AccountListResponse;
import com.etrade.etws.oauth.sdk.client.IOAuthClient;
import com.etrade.etws.oauth.sdk.client.OAuthClientImpl;
import com.etrade.etws.oauth.sdk.common.Token;
import com.etrade.etws.sdk.client.ClientRequest;
import com.etrade.etws.sdk.client.Environment;
import com.etrade.etws.sdk.common.ETWSException;
import com.etrade.etws.sdk.client.AccountsClient;
import com.etrade.*;
import com.etrade.etws.order.PreviewEquityOrder;
import com.etrade.etws.order.PreviewEquityOrderResponse;
import com.etrade.etws.order.EquityOrderRequest;
import com.etrade.etws.order.EquityOrderTerm;
import com.etrade.etws.order.EquityOrderAction;
import com.etrade.etws.order.MarketSession;
import com.etrade.etws.order.EquityPriceType;
import com.etrade.etws.order.EquityOrderRoutingDestination;
import com.etrade.etws.sdk.client.OrderClient;
import java.math.BigInteger;
import java.awt.Desktop;
import java.net.URI;
import java.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class test
{
public static void main(String[] args) throws IOException, ETWSException
{
//Variables
if(args.length<2){
System.out.println("Class test needs two input argument as follows:");
System.out.println("test <consumer_key> <consumer_secret>");
return;
}
String oauth_consumer_key = args[0]; // Your consumer key
String oauth_consumer_secret = args[1]; // Your consumer secret
String oauth_request_token = null; // Request token
String oauth_request_token_secret = null; // Request token secret
String oauth_verify_code = null;
String oauth_access_token = null;
String oauth_access_token_secret = null;
ClientRequest request = new ClientRequest();
System.out.println("HERE");
IOAuthClient client = OAuthClientImpl.getInstance(); // Instantiate IOAUthClient
// Instantiate ClientRequest
request.setEnv(Environment.SANDBOX); // Use sandbox environment
request.setConsumerKey(oauth_consumer_key); //Set consumer key
request.setConsumerSecret(oauth_consumer_secret);
Token token = client.getRequestToken(request); // Get request-token object
oauth_request_token = token.getToken(); // Get token string
oauth_request_token_secret = token.getSecret(); // Get token secret
request.setToken(oauth_request_token);
request.setTokenSecret(oauth_request_token_secret);
String authorizeURL = null;
authorizeURL = client.getAuthorizeUrl(request);
System.out.println(authorizeURL);
System.out.println("Copy the URL into your browser. Get the verification code and type here");
oauth_verify_code = get_verification_code();
//oauth_verify_code = Verification(client,request);
request.setVerifierCode(oauth_verify_code);
token = client.getAccessToken(request);
oauth_access_token = token.getToken();
oauth_access_token_secret = token.getSecret();
request.setToken(oauth_access_token);
request.setTokenSecret(oauth_access_token_secret);
// Get Account List
AccountsClient account_client = new AccountsClient(request);
AccountListResponse response = account_client.getAccountList();
List<Account> alist = response.getResponse();
Iterator<Account> al = alist.iterator();
while (al.hasNext()) {
Account a = al.next();
System.out.println("===================");
System.out.println("Account: " + a.getAccountId());
System.out.println("===================");
}
// Preview Equity Order
OrderClient order_client = new OrderClient(request);
PreviewEquityOrder orderRequest = new PreviewEquityOrder();
EquityOrderRequest eor = new EquityOrderRequest();
eor.setAccountId("83405188"); // sample values
eor.setSymbol("AAPL");
eor.setAllOrNone("FALSE");
eor.setClientOrderId("asdf1234");
eor.setOrderTerm(EquityOrderTerm.GOOD_FOR_DAY);
eor.setOrderAction(EquityOrderAction.BUY);
eor.setMarketSession(MarketSession.REGULAR);
eor.setPriceType(EquityPriceType.MARKET);
eor.setQuantity(new BigInteger("100"));
eor.setRoutingDestination(EquityOrderRoutingDestination.AUTO.value());
eor.setReserveOrder("TRUE");
orderRequest.setEquityOrderRequest(eor);
PreviewEquityOrderResponse order_response = order_client.previewEquityOrder(orderRequest);
}
public static String get_verification_code() {
try{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String input;
input=br.readLine();
return input;
}catch(IOException io){
io.printStackTrace();
return "";
}
}
}
I posted this on the ETrade community forum but that forum is not very active. I also sent a request to ETrade and haven't gotten a reply yet. If I get a solution from them, I will come back and post it here. In the mean time any help is greatly appreciated.
After debugging my above code, I figured out that the problem is that I was setting the ReserveOrder to TRUE but I wasn't providing the required ReserveOrderQuantity. I got the above code from the Java code snippet in the ETrade Developer Platform Guide. This is clearly a bug in their documentation.
May I ask a question please, I get Pig installed and configured, but it says "error package org.apache.pig.FilterFunc not exist" while I am trying to compile a very simple java source file by using javac command.
The CLASSPATH variable is set as listed below:
/usr/local/hadoop/share/hadoop/common/hadoop-common-2.7.0.jar:/usr/local/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.7.0.jar:/usr/local/hadoop/share/hadoop/common/lib/commons-cli-1.2.jar:/usr/local/hadoop/etc/hadoop/:/usr/local/pig/lib/:.:/usr/java/jdk1.8.0_45/jre/lib/rt.jar:/usr/java/jdk1.8.0_45/lib/dt.jar:/usr/java/jdk1.8.0_45/lib/tools.jar:/usr/share/ant/lib/ant-launcher.jar
and these two environment variables set as below:
export PIG_INSTALL=/usr/local/pig
export PIG_CLASSPATH=$HADOOP_INSTALL/etc/hadoop
The source code of file IsUseragentBot.java is listed as below:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.pig.FilterFunc;
import org.apache.pig.data.Tuple;
public class IsUseragentBot extends FilterFunc {
private Set<String> blacklist = null;
private void loadBlacklist() throws IOException {
blacklist = new HashSet<String>();
BufferedReader in = new BufferedReader(new FileReader("blacklist"));
String userAgent = null;
while ((userAgent = in.readLine()) != null) {
blacklist.add(userAgent);
}
}
#Override
public Boolean exec(Tuple tuple) throws IOException {
if (blacklist == null) {
loadBlacklist();
}
if (tuple == null || tuple.size() == 0) {
return null;
}
String ua = (String)tuple.get(0);
if (blacklist.contains(ua)) {
return true;
}
return false;
}
}
While I am going to compile source file by executing javac IsUseragentBot.java,it always fails and says that "error package org.apache.pig not exist",could any buddy help me please,thanks a lot!
I have solved this problem, it is related to compatibility between pig and hadoop, besides the compilation of pig
I tried to execute a small hive query from Java, but it is failing with below error, bur when I copy the same query and run on terminal it is giving me the result.
Can someone help me on this.
Java Code:
Runtime.getRuntime().exec("hive -e 'show databases;'");
Error thrown:
FAILED: ParseException line 1:5 cannot recognize input near '<EOF>' '<EOF>' '<EOF>' in ddl statement
Regards,
GHK.
I have been working with this Java problem for a while, and I believe I have solved this problem. Basically the reason you are failing is because the environment variables are not ser up properly. put the following in your /home/<username>/.bash_profile file and restart your machine to fix this.
HIVE_HOME=/usr/lib/hive
export HIVE_HOME
PATH=$PATH:$HIVE_HOME/bin/hive
export PATH
This will ensure that they get set up properly.
However while this will get rid of the error it still won't show you a list of databases because the process that runs the hive command will run in the background, not on the console the main program is running from. The following code will let you redirect the outputs of the program to the console that the main program is running from.
package testing.console;
import java.io.IOException;
import java.lang.ProcessBuilder;
import java.util.Map;
import testing.console.OutputRedirector;
//This Works
public class ConsoleTester {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
ProcessBuilder hiveProcessBuilder = new ProcessBuilder("hive", "-e",
"show databases");
String path = processEnv.get("PATH");
Process hiveProcess = hiveProcessBuilder.start();
OutputRedirector outRedirect = new OutputRedirector(
hiveProcess.getInputStream(), "HIVE_OUTPUT");
OutputRedirector outToConsole = new OutputRedirector(
hiveProcess.getErrorStream(), "HIVE_LOG");
outRedirect.start();
outToConsole.start();
}
}
And the OutputRedirector class used to get the output to console.
package testing.console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class OutputRedirector extends Thread {
InputStream is;
String type;
public OutputRedirector(InputStream is, String type){
this.is = is;
this.type = type;
}
#Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(type + "> " + line);
}
} catch (IOException ioE) {
}
}
}