Java tutorial
/* * Copyright 2014 Dmytro Titov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.autsia.crowly.services.sentiment.impl; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import io.github.autsia.crowly.services.sentiment.Sentiment; import io.github.autsia.crowly.services.sentiment.SentimentAnalyzer; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; /** * Created by Dmytro on 06.12.13 at 1:20 * Project: crowly */ @Service public class CrowlySentimentAnalyzer implements SentimentAnalyzer { public static final String URL = "http://sentiment.vivekn.com/api/text/"; public static final String RESULT = "result"; public static final String SENTIMENT = "sentiment"; public static final String CONFIDENCE = "confidence"; private static final Logger logger = Logger.getLogger(CrowlySentimentAnalyzer.class); @Value("500") private long connectionTimeout; @Value("500") private long socketTimeout; @PostConstruct public void init() { Unirest.setTimeouts(connectionTimeout, socketTimeout); } @Override public Pair<Sentiment, Float> analyze(String text) { try { HttpResponse<JsonNode> request = Unirest.post(URL).field("txt", text).asJson(); JSONObject result = request.getBody().getObject().getJSONObject(RESULT); String sentiment = result.getString(SENTIMENT); Float confidence = Float.parseFloat(result.getString(CONFIDENCE)); return new ImmutablePair<>(Sentiment.get(sentiment), confidence); } catch (Exception e) { logger.error(e.getMessage(), e); return new ImmutablePair<>(Sentiment.NEUTRAL, 0.5f); } } }