I am trying to write a java program which for loop the image files in a folder and
do reverse image search on google (just trying to do with one image in this question)
I find some example like below and the result will give me a url that preformed the reverse image search.
While I am wondering how can I download one of the image from the result site.
Some things to add is that I have read the new google api(?) and I find that it only allow me to do search 100/day, hence I choose to use the old version(?) although it warn me the method are deprecated.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class ReverseImageSearch{
public static void main(String args[]){
try {
HttpClient client = new DefaultHttpClient();
String url="https://www.google.co.in/searchbyimage/upload";
String imageFile="C:\\Users\\Chan\\Desktop\\pixiv29706591.jpg";
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart("encoded_image", new FileBody(new File(imageFile)));
entity.addPart("image_url",new StringBody(""));
entity.addPart("image_content",new StringBody(""));
entity.addPart("filename",new StringBody(""));
entity.addPart("h1",new StringBody("en"));
entity.addPart("bih",new StringBody("179"));
entity.addPart("biw",new StringBody("1600"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
if (line.indexOf("HREF")>0)
System.out.println(line.substring(8));
//Problem:
// get one of the result image from the sites
// and store it in my PC
}
}catch (ClientProtocolException cpx){
cpx.printStackTrace();
}catch (IOException ioex){
ioex.printStackTrace();
}
}
}
Related
I tried to get NexmoClient object without success.
I Fill in API_KEY and API_SECRET with the values I copied from the Nexmo Dashboard.
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.SmsSubmissionResult;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(1111,22222);
NexmoClient client = new NexmoClient(auth);
}
}
"
After the Gradle run, I was expected to NexmoClient object as they wrote in the docs https://www.nexmo.com/blog/2017/05/03/send-sms-messages-with-java-dr/
for continue to the next step, but I didn't know where to insert the following info
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from
Nexmo!");
SmsSubmissionResult[] responses =
client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
You can put that code below where you initialize the client. Your whole class will then look like this:
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
private static final String FROM_NUMBER = "";
private static final String TO_NUMBER = "";
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(1111, 22222);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo !");
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
This blog post is actually a bit old and suggests using an older version of the server SDK. There's an updated example on the developer portal as some things have changed in the newer versions of the SDK: https://developer.nexmo.com/messaging/sms/code-snippets/send-an-sms
I want to use Liferay Message bus in DXP. I have written the following code.
DemoSender.java
package demo.sender.portlet;
import demo.sender.constants.DemoSenderPortletKeys;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBus;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* #author parth.ghiya
*/
#Component(
immediate = true,
property = {
"com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true",
"javax.portlet.display-name=demo-sender Portlet",
"javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp",
"javax.portlet.name=" + DemoSenderPortletKeys.DemoSender,
"javax.portlet.resource-bundle=content.Language",
"javax.portlet.security-role-ref=power-user,user"
},
service = Portlet.class
)
public class DemoSenderPortlet extends MVCPortlet {
#Activate
protected void activate(BundleContext bundleContext) {
_bundleContext = bundleContext;
}
public void sendMessage(
ActionRequest actionRequest, ActionResponse actionResponse) {
if (_log.isInfoEnabled()) {
_log.info("Sending message to DE Echo service");
}
Message message = new Message();
message.setDestinationName("MyEchoDestination");
message.setPayload("Hello World!");
message.setResponseDestinationName("MyEchoResponse");
_messageBus.sendMessage(message.getDestinationName(), message);
}
private static final Log _log = LogFactoryUtil.getLog(DemoSenderPortlet.class);
private BundleContext _bundleContext;
#Reference
private MessageBus _messageBus;
}
DemoReceiver.java
package demo.receiver.portlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.BaseMessageListener;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBus;
import com.liferay.portal.kernel.messaging.MessageListener;
#Component(
immediate = true, property = {"destination.name=MyEchoDestination"},
service = MessageListener.class
)
public class DemoReceiverPortlet extends BaseMessageListener {
#Override
protected void doReceive(Message message) throws Exception {
if (_log.isInfoEnabled()) {
_log.info("Received: " + message);
}
String payload = (String)message.getPayload();
if (_log.isInfoEnabled()) {
_log.info("Message payload: " + payload);
}
/*
String responseDestinationName = message.getResponseDestinationName();
if ((responseDestinationName != null) &&
(responseDestinationName.length() > 0)) {
Message responseMessage = new Message();
responseMessage.setDestinationName(responseDestinationName);
responseMessage.setResponseId(message.getResponseId());
//This is just for demo purposes
responseMessage.setPayload(payload);
_messageBus.sendMessage(
message.getResponseDestinationName(), responseMessage);
}
*/
}
private static final Log _log = LogFactoryUtil.getLog(DemoReceiverPortlet.class);
#Reference
private volatile MessageBus _messageBus;
}
The problem is that my doReceive method is never getting called.
What configuration needs to be further added?
Regards
P.S : in DemoSender, i send some message on click of button
Edit # 1
I did added configurator code as follows.
package demo.receiver.portlet;
import java.util.Dictionary;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import com.liferay.portal.kernel.concurrent.DiscardOldestPolicy;
import com.liferay.portal.kernel.concurrent.RejectedExecutionHandler;
import com.liferay.portal.kernel.concurrent.ThreadPoolExecutor;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Destination;
import com.liferay.portal.kernel.messaging.DestinationConfiguration;
import com.liferay.portal.kernel.messaging.DestinationFactory;
import com.liferay.portal.kernel.messaging.MessageBus;
import com.liferay.portal.kernel.util.HashMapDictionary;
#Component(
enabled = false, immediate = true,
service = DemoReceiverConfigurator.class
)
public class DemoReceiverConfigurator {
#Activate
protected void activate(ComponentContext componentContext) {
_bundleContext = componentContext.getBundleContext();
System.out.println("===demo===");
Dictionary<String, Object> properties =
componentContext.getProperties();
DestinationConfiguration destinationConfiguration =
new DestinationConfiguration(DestinationConfiguration.DESTINATION_TYPE_PARALLEL,"MyEchoDestination");
destinationConfiguration.setMaximumQueueSize(200);
RejectedExecutionHandler rejectedExecutionHandler =
new DiscardOldestPolicy() {
#Override
public void rejectedExecution(
Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
if (_log.isWarnEnabled()) {
_log.warn(
"The current thread will handle the request " +
"because the audit router's task queue is at " +
"its maximum capacity");
}
super.rejectedExecution(runnable, threadPoolExecutor);
}
};
destinationConfiguration.setRejectedExecutionHandler(
rejectedExecutionHandler);
Destination destination = _destinationFactory.createDestination(
destinationConfiguration);
Dictionary<String, Object> destinationProperties =
new HashMapDictionary<>();
destinationProperties.put("destination.name", destination.getName());
_destinationServiceRegistration = _bundleContext.registerService(
Destination.class, destination, destinationProperties);
}
#Deactivate
protected void deactivate() {
if (_destinationServiceRegistration != null) {
Destination destination = _bundleContext.getService(
_destinationServiceRegistration.getReference());
_destinationServiceRegistration.unregister();
destination.destroy();
}
_bundleContext = null;
}
#Reference(unbind = "-")
protected void setMessageBus(MessageBus messageBus) {
}
private static final Log _log = LogFactoryUtil.getLog(
DemoReceiverConfigurator.class);
private volatile BundleContext _bundleContext;
#Reference
private DestinationFactory _destinationFactory;
private volatile ServiceRegistration<Destination>
_destinationServiceRegistration;
}
But my Activate method aint getting called, i have enabledfalse in my message listener class and enabled = false, immediate = true in my Configurator class.
Dont know what i am missing.
Often in OSGi, this seemingly obvious configuration is enough. In this case though, it obviously isn't, because Liferay now knows about the message you're sending and that you're interested to receive, but the Messagebus doesn't know about this destination to be created.
It seems obvious - if there is a listener to a particular message, there probably needs to be a destination. But what type will it be? Parallel processing? How many parallel handlers? Synchronous? Queued? This is what you'll need to do.
While a quick search didn't find a documentation on how to do this, you can use this configurator as an example for creating the missing link.
MessageBus documentation was improved a few days ago, have a look to following page https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/message-bus
I am trying on my own to implement a useful trip planner application using android studio with the help of goolge and some open sources
I have android application with no gradle.build. when it try to run it i get the error.
Error:(20, 28) java: package org.apache.http.util does not exist
Here is the part of the code that has the error.
How to solve the error ?
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public static String queryUrl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
Log.i(TAG, "Url:" + url + "");
Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]");
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(instream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
instream.close();
String result = total.toString();
return result;
}
} catch (ClientProtocolException e) {
Log.e(TAG, "There was a protocol based error", e);
} catch (Exception e) {
Log.e(TAG, "There was some error", e);
}
return null;
}
See following answer, HttpClient won't import in Android Studio
I don't know how your module's build.gradle looks like, but I assume you are including apache libraries some wrong way.
Also, I would not reccomend using apache HTTP libraries in new android applications. Have look at OkHttp or Volley
I would post this in comments, but I don't have enough reputation yet.
How do i convert a .doc file to FO using hwpf.converter.WordToFo class? I have tried searching but i could only get a word to html conversion.
I have also read the WordToFO manual at the apache-poi site, but could not get it.
Convert Word to HTML with Apache POI
I have tried to convert .doc to .fo using the following code, but after using apache-fop to convert the .fo file to .png, i am not able to get the images present in the word file.
package word2fo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.text.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.WordToFoConverter;
import org.apache.poi.hwpf.converter.WordToFoUtils;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.w3c.dom.Node;
public class Doc2Fo{
public static void main(String[] args) throws Exception {
System.out.println("reached 1");
HWPFDocumentCore wordDocument = WordToFoUtils.loadDoc(new FileInputStream("D:\\Magna.doc"));
System.out.println("reached 2");
WordToFoConverter wordToFoConverter = new WordToFoConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
System.out.println("reached 3");
wordToFoConverter.processDocument(wordDocument);
org.w3c.dom.Document htmlDocument = wordToFoConverter.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource((Node) htmlDocument);
StreamResult streamResult = new StreamResult(out);
System.out.println("reached 4");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer;
try {
serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
//serializer.setOutputProperty(OutputKeys.METHOD, "xml-fo");
serializer.transform(domSource, streamResult);
out.close();
String result = new String(out.toByteArray());
System.out.println(result);
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
HWPFDocument hwpfDocument = new HWPFDocument(POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName));
WordToFoConverter wordToFoConverter = new WordToFoConverter(XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument());
wordToFoConverter.processDocument(hwpfDocument);
StringWriter stringWriter = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(wordToFoConverter.getDocument()), new StreamResult(stringWriter));
String result = stringWriter.toString();
return result;
I just started to develop a simple Blackberry app which shows a text sequence in a RichTextField on a MainScreen. When I define the String directly in the sourcecode, then I have no problem to display it. But if I try to read it in from a .txt file which is located in the res folder, then I get a NullPointerException.
The code below is what I did so far.
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen{
String str = readFile("Testfile.txt");
public MyScreen(){
setTitle("Read Files");
add(new RichTextField(str));
}
public String readFile(String filename){
InputStream is = this.getClass().getResourceAsStream("/"+filename);
try {
byte[] filebytes = IOUtilities.streamToBytes(is);
is.close();
return new String(filebytes);
}
catch (IOException e){
System.out.println(e.getMessage());
}
return "";
}
}
Parts of this code I found in this forum but my problem is that I don't understand when I have to open a connection and when to close it.
And when do I need a Buffer?
And why do I have to convert a InputStream to a byte[] and then the byte[] to a String?
All I need is one method, where I can type in the Filename and get back a String-Object with the text which is in my .txt file.
And of course the method should save resources...
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen {
public MyScreen() throws IOException {
setTitle("Read Files");
add(new RichTextField(readFileToString("Testfile.txt")));
}
public String readFileToString(String path) throws IOException {
InputStream is = getClass().getResourceAsStream("/"+path);
byte[] content = IOUtilities.streamToBytes(is);
is.close();
return new String(content);
}
}
Yes!!! I found a way to solve my problem.
I don't know why my previous code didn't work but this one works...
The only thing I've changed is that I've added the throws IOException instead of surrounding it with a try - catch block...