在PHP代码中运行Java程序[重复]
This question already has an answer here:
I am trying to make a simple recommender system, and I found that with mahout it is pretty easy to make one. I have the following code (I am running it on eclipse and everything works great:
package com.predictionmarketing.RecommenderApp;
import java.io.File;
import java.io.IOException;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.UserBasedRecommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
/**
* Java's application, user based recommender system
*
*/
public class App
{
public static void main( String[] args )
{
// Modelo
DataModel model = null;
// Inicializar similaridad
UserSimilarity similarity = null;
// Leer .cv userID, itemID, value
try {
model = new FileDataModel(new File("data/dataset.csv"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Encontrar matriz de similaridad
try {
similarity = new PearsonCorrelationSimilarity(model);
} catch (TasteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model);
UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);
java.util.List<RecommendedItem> recommendations = null;
try {
recommendations = recommender.recommend(2, 3);
} catch (TasteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Mostrar Recomendaciones
for (RecommendedItem recommendation : recommendations) {
System.out.println(recommendation.getItemID());
}
}
}
However, I need to run this code online because I am making the application on PHP and that is where my problem arises. Is there a way to run this code on PHP, so I can use the "recommendation" variable?
</div>
You can run this java code (compiled first) from php code with shell_exec.
But is a better solution build a REST service (or another) to do it language agnostic.
There is no simple solution for this. To make it work and communicate with PHP you have to create some interface for it. For example create java servlet, and put it on Servlet container (Java web server). This is simplest I see now.
Other solution you could consider also REST or SOAP service, to exchange data between this Java code and your PHP application. This also will need JavaEE container.