It's kinda frustating me... I tried to create httpPost
code :
private void makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("www.example.com");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
But always ended Can't resolve symbol. I used Android Studio latest update, I already downloaded http://mirror.metrocast.net/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5-bin.zip from hc.apache.org and copy jar file (httpclient-4.5.jar and httpcore-4.4.1.jar) to library and add it as a library but somehow it doesn't work.
It gives error :
Error:Execution failed for task ':app:packageDebug'.
Duplicate files copied in APK META-INF/DEPENDENCIES File 1: Z:\Learning\Android-2\Live-code-AS\SendLocation\app\libs\httpcore-4.4.1.jar
File 2:
Z:\Learning\Android-2\Live-code-AS\SendLocation\app\libs\httpclient-4.5.jar
if I delete one of the jar file then I'll get "can't resolve HttpClient or NameValuePair"
Please help.... Thanks before.
You have some duplicate files in your dependencies. To solve it, open your build.gradle in which you define your dependencies and add the packagingOptions-section within the android-section:
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
}
Related
I'm trying to write files to smb folder, it works fine for the first write but when the same file is written again it throws error
Caused by: org.springframework.core.NestedIOException: Failed to rename [/remote-target-dir/smbTest.test.writing] to [/remote-target-dir/smbTest.test].; nested exception is jcifs.smb.SmbException: Cannot create a file when that file already exists.
Im' using the FileTransferringMessageHandler which has FileExistsMode.REPLACE as default file exists mode but still it fails to replace.
I debugged into the SmbSession class, when flow reaches to this code in rename(String _pathFrom, String _pathTo) method
if (this.smbShare.isReplaceFile() && smbFileTo.exists()) {
smbFileTo.delete();
}
I see that the smbShare's isReplaceFile() is false, which is why I assume it is unable to delete the previous file with the same name
Here is the full code:
Connection:
#Bean
public SmbSessionFactory smbSessionFactory() {
SmbSessionFactory smbSession = new SmbSessionFactory();
smbSession.setHost("localhost");
smbSession.setPort(445);
smbSession.setDomain("DESKTOP-07O79IT");
smbSession.setUsername("Dell");
smbSession.setPassword("changeIt");
smbSession.setShareAndDir("Users\\DELL\\Desktop\\Shared");
smbSession.setSmbMinVersion(DialectVersion.SMB210);
smbSession.setSmbMaxVersion(DialectVersion.SMB311);
return smbSession;
}
Outbound to send files to smb:
#ServiceActivator(inputChannel = "storeToSmb")
#Bean
public MessageHandler smbMessageHandler(SmbSessionFactory smbSessionFactory) {
FileTransferringMessageHandler<SmbFile> handler =
new FileTransferringMessageHandler<>(smbSessionFactory);
handler.setRemoteDirectoryExpression(
new LiteralExpression("/remote-target-dir"));
handler.setFileNameGenerator(m -> "smbTest.test");
handler.setAutoCreateDirectory(true);
return handler;
}
Gateway:
#Override
public void run(ApplicationArguments args) throws Exception {
File file = new File("smbFile.txt");
try(FileWriter writer = new FileWriter(file)){
writer.write("This is sample smb write");
messageGateway.storeToSmb(file);
}catch (IOException e){
System.out.println("Error: "+e);
}
}
Can you please help with this issue?
The SmbSessionFactory must come with the setReplaceFile(true). The FileTransferringMessageHandler does nothing about its dependency and can't mutate it although it has its own logic about that FileExistsMode.REPLACE.
I have looked in so many places on a lead on how or if it is possible to view images uploaded to cloudinary, by a specific tag through Android studio app i am trying to build.
I was able to implement the upload option by user, with adding a tag to the images, and public id, also retrieving these information, but i cant find anything on how to view these images, for example i want the app to be able to view all images with a specific tag ( username ) to the user that uploaded the pictures, and could delete them ? and also view other images uploaded by other user with no other permission.
Is it possible and how !?
I ended up with this code, and i encountered a problem;
#Override
public void onClick(View v) {
new JsonTask().execute("http://res.cloudinary.com/cloudNAme/video/list/xxxxxxxxxxxxxxxxxxx.json");
// uploadExtract();
}
});
public class JsonTask extends AsyncTask<String ,String,String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
In the log i get the following;
03-28 12:36:14.726 20333-21459/net.we4x4.we4x4 W/System.err: java.io.FileNotFoundException: http://res.cloudinary.com/we4x4/video/list/3c42f867-8c3a-423b-89e8-3fb777ab76f8.json
i am not sure if my understanding is correct of the method or i am doing something wrong ? since in the Admin API Docs. or cloudinary the syntax for the HTML request and also in the suggested page by Nadav:
https://support.cloudinary.com/hc/en-us/articles/203189031-How-to-retrieve-a-list-of-all-resources-sharing-the-same-tag-
this should've returned a JSON ?
The following feature allows you to retrieve a JSON formatted list of resources that which share a common tag:
https://support.cloudinary.com/hc/en-us/articles/203189031-How-to-retrieve-a-list-of-all-resources-sharing-the-same-tag-
Note that image removal will coerce you to use server-side code (e.g. JAVA), since deleting via Cloudinary requires a signature that is based on your API_SECRET.
I am trying to use NetSuite's suiteTalk java api for writing an interface between our lotus notes system and NetSuite.
The first error thrown by the code was a class def not found error.
for :
sun/security.provider/sun.class
sun/security.provider/sun$1.class
sun/security.provider/NativePRNG.class
I figured out that rt.jar in lotus notes was actually missing this files. So I added these class files from the jdk1.6 i had downloaded separately. Once I fixed that I started getting axis.Faults error.
Here is the simple login code that I am trying to execute from lotus note agent:
public void loginTest(){
NetSuitePortType _port=null;
// In order to use SSL forwarding for SOAP message. Refer to FAQ for details
System.setProperty("axis.socketSecureFactory","org.apache.axis.components.net.SunFakeTrustSocketFactory");
// Locate the NetSuite web service
NetSuiteServiceLocator serviceLocator= new NetSuiteServiceLocator();
//Get the service port
try {
_port=serviceLocator.getNetSuitePort();
} catch (ServiceException e) {
System.out.println("Error in intializing GlobalSuiteTalkSetup");
e.printStackTrace();
}
// Setting client timeout to 2 hours for long running operatotions
((NetSuiteBindingStub) _port).setTimeout(60*60*1000*2);
try {
// Populate Passport object with all login information
Passport passport = new Passport();
RecordRef role = new RecordRef();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
passport.setEmail("username");
passport.setPassword("password.");
role.setInternalId("3");
passport.setRole(role);
passport.setAccount("111111");
// Login to NetSuite
System.out.print("\nLogging into NetSuite");
System.out.print(" Username: " + passport.getEmail());
System.out.print(" Account: " + passport.getAccount());
System.out.print(" password: " + passport.getPassword());
System.out.print(" role: " + passport.getRole());
Status status;
status = (_port.login(passport)).getStatus();
// Process the response
if (status.isIsSuccess() == true)
{
System.out.print("\nThe login was successful and a new session has been created.");
} else
{
// Should never get here since any problems with the
// login should have resulted in a SOAP fault
System.out.print("Login failed");
//System.out.print(getStatusDetails(status));
}
} catch (InvalidVersionFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidCredentialsFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InsufficientPermissionFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExceededRequestLimitFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnexpectedErrorFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAccountFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Error thrown by code:
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.io.IOException
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:java.io.IOException
at org.apache.axis.components.net.SunJSSESocketFactory.initFactory(SunJSSESocketFactory.java:88)
at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:79)
at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.netsuite.webservices.platform_2015_1.NetSuiteBindingStub.login(NetSuiteBindingStub.java:12799)
at Login.loginTest(Unknown Source)
at JavaAgent.NotesMain(Unknown Source)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(Unknown Source)
{http://xml.apache.org/axis/}hostname:
java.io.IOException
at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.netsuite.webservices.platform_2015_1.NetSuiteBindingStub.login(NetSuiteBindingStub.java:12799)
at Login.loginTest(Unknown Source)
at JavaAgent.NotesMain(Unknown Source)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(Unknown Source)
Caused by: java.io.IOException
at org.apache.axis.components.net.SunJSSESocketFactory.initFactory(SunJSSESocketFactory.java:88)
at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:79)
at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138)
... 14 more
I found the solution for this issue. For anyone who might get similar issue can get some clue from this solution :
The issue was because of the following statement that I had put in the code.
System.setProperty("axis.socketSecureFactory","org.apache.axis.components.net.SunFakeTrustSocketFactory");
This statement is necessary when using Sun' JVM but since Lotus Notes uses IBM's JVM, setting axis.socketSecureFactory to org.apache.axis.components.net.SunFakeTrustSocketFactory made the system to look for Sun classes which not absent in IBM's JVM.
No need to add the missing classes from Sun JVM to rt.jat as I had done before. Just comment that statement and use the axis path available frpm NetSuite
Don't forget to put the patch in Note's /JVM/Lib/EXT folder and restart Lotus Notes before trying to run the code..
i have the ambitious goal to get 100% test coverage in cobertura. How can i achieve this on this code? There will never be an exception because the file is on the classpath. Can i remove files fropm classpath with junit?
try {
InputStreamReader reader = new InputStreamReader(WsdlSource.class.getClassLoader().getResourceAsStream("stringresources/stringresources.properties"), "UTF-8");
try {
p.load(reader);
} finally {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
First of all, to be able to test things right you have to learn what what loose coupling is and what Mock Objects are.
Basically, it is never a good idea to create an object with new because you create a hard dependency between the class InputStreamReader and your logic.
If your object p implements some kind of an interface, it would be good if you pass the instance of it from outside of your logic. Some implementations of Mock Objects also allow you to mock a class but I would not recommend that.
For example if you write your code like that:
public myMethod(SomeKindOfInterface p, InputStreamReader reader) {
try {
p.load(reader);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch(IOException e) {
//intentionally left blank, nothing could be done upon exception on closing
}
}
}
Then in your JUnit you could use Mockito to mock the IOException.
InputStreamReader reader = new InputStreamReader(WsdlSource.class.getClassLoader().getResourceAsStream("stringresources/stringresources.properties"), "UTF-8");
SomeKindOfInterface mock = Mockito.mock(SomeKindOfInterface.class);
Mockito.when(mock.load(reader)).thenThrow(new IOException());
myInstance.myMethod(mock, reader);
This way you would have your catch block covered.
I want loading screen in my application such that it appear when the internet connection starts and loading screen get hide when I got the data from webservice.
I had tried to use .gif file. It is working properly in the simple application which I made which shows only .gif file. But when I integrate this code with my applicationj it is showing the error.
The error is:
TRACE: <at java.lang.IllegalArgumentException>, Exception caught in Display class
java.lang.IllegalArgumentException
at javax.microedition.media.Manager.createPlayer(), bci=8
at com.semaphore.GifCanvas.<init>(GifCanvas.java:41)
at com.semaphore.CompanySplashScreen.dismiss(CompanySplashScreen.java:89)
at com.semaphore.CompanySplashScreen.keyPressed(CompanySplashScreen.java:78)
at javax.microedition.lcdui.CanvasLFImpl.uCallKeyPressed(), bci=19
at javax.microedition.lcdui.DisplayableLFImpl.uCallKeyEvent(), bci=146
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=30
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:619)
the code which i am using to for executing .gif file is:-
InputStream ins = getClass().getResourceAsStream("/loading.gif");
try {
player = Manager.createPlayer(ins, "image/gif");
player.prefetch();
player.setLoopCount(10);
player.start();
} catch (IOException ex) {
ex.printStackTrace();
} catch (MediaException ex) {
ex.printStackTrace();
}
if ((vidc = (VideoControl) player.getControl("VideoControl")) != null)
vidc.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
vidc.setDisplayLocation(2, 2);
vidc.setDisplaySize(getWidth()/2,getHeight()/2);
}
catch (MediaException me) {}
vidc.setVisible(true);
How can I resolve this?
According to the documentation, your InputStream is null.
Check if you have your resource properly placed. With that path, it should be on the root dir of your project (or the src dir, I'm not sure). But just check it.