Search in sources :

Example 26 with UnexpectedServerException

use of com.pratilipi.common.exception.UnexpectedServerException in project pratilipi by Pratilipi.

the class FreeMarkerUtil method processString.

@SuppressWarnings("deprecation")
public static String processString(Object model, String template) throws UnexpectedServerException {
    Configuration cfg = new Configuration();
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    try {
        Template t = new Template("templateName", new StringReader(template), cfg);
        Writer out = new StringWriter();
        t.process(model, out);
        return out.toString();
    } catch (TemplateException | IOException e) {
        logger.log(Level.SEVERE, "Template processing failed.", e);
        throw new UnexpectedServerException();
    }
}
Also used : UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) Configuration(freemarker.template.Configuration) StringWriter(java.io.StringWriter) TemplateException(freemarker.template.TemplateException) StringReader(java.io.StringReader) DefaultObjectWrapper(freemarker.template.DefaultObjectWrapper) IOException(java.io.IOException) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Template(freemarker.template.Template)

Example 27 with UnexpectedServerException

use of com.pratilipi.common.exception.UnexpectedServerException in project pratilipi by Pratilipi.

the class FreeMarkerUtil method getConfiguration.

private static Configuration getConfiguration() throws UnexpectedServerException {
    if (cfg == null) {
        FileTemplateLoader ftl;
        try {
            ftl = new FileTemplateLoader(new File("."));
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Failed to set template directory.", e);
            throw new UnexpectedServerException();
        }
        ClassTemplateLoader ctl = new ClassTemplateLoader(FreeMarkerUtil.class.getClassLoader(), "");
        MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] { ftl, ctl });
        cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setTemplateLoader(mtl);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    }
    return cfg;
}
Also used : MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) Configuration(freemarker.template.Configuration) ClassTemplateLoader(freemarker.cache.ClassTemplateLoader) IOException(java.io.IOException) FileTemplateLoader(freemarker.cache.FileTemplateLoader) File(java.io.File)

Example 28 with UnexpectedServerException

use of com.pratilipi.common.exception.UnexpectedServerException in project pratilipi by Pratilipi.

the class GoogleAnalyticsApi method getPratilipiReadCount.

public static Map<Long, Long> getPratilipiReadCount(List<Long> pratilipiIdList) throws UnexpectedServerException {
    int idsPerRequest = 80;
    Map<Long, Long> idCountMap = new HashMap<Long, Long>();
    for (int i = 0; i < pratilipiIdList.size(); i = i + idsPerRequest) {
        String filters = "";
        for (int j = 0; i + j < pratilipiIdList.size() && j < idsPerRequest; j++) filters = filters + "ga:pagePath=~^/read\\?id=" + pratilipiIdList.get(i + j) + ".*,";
        filters = filters.substring(0, filters.length() - 1);
        try {
            Get apiQuery = getAnalytics().data().ga().get(// Table Id.
            "ga:89762686", // Start Date.
            "2015-01-01", // End Date.
            "today", // Metrics.
            "ga:pageviews").setDimensions("ga:pagePath").setFilters(filters);
            GaData gaData = apiQuery.execute();
            if (gaData.getRows() != null) {
                for (List<String> row : gaData.getRows()) {
                    String pagePath = row.get(0);
                    if (pagePath.indexOf('&') != -1)
                        pagePath = pagePath.substring(0, pagePath.indexOf('&'));
                    Long pratilipiId = Long.parseLong(pagePath.substring(pagePath.indexOf('=') + 1));
                    long readCount = Long.parseLong(row.get(1));
                    if (idCountMap.containsKey(pratilipiId))
                        idCountMap.put(pratilipiId, readCount + idCountMap.get(pratilipiId));
                    else
                        idCountMap.put(pratilipiId, readCount);
                }
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Failed to fetch data from Google Analytics.", e);
            throw new UnexpectedServerException();
        }
    }
    return idCountMap;
}
Also used : UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) HashMap(java.util.HashMap) Get(com.google.api.services.analytics.Analytics.Data.Ga.Get) GaData(com.google.api.services.analytics.model.GaData) IOException(java.io.IOException)

Example 29 with UnexpectedServerException

use of com.pratilipi.common.exception.UnexpectedServerException in project pratilipi by Pratilipi.

the class GoogleApi method getUserData.

public static UserData getUserData(String googleIdToken) throws InvalidArgumentException, UnexpectedServerException {
    try {
        GoogleIdToken idToken = UxModeFilter.isAndroidApp() ? getAndroidIdTokenVerifier().verify(googleIdToken) : getWebIdTokenVerifier().verify(googleIdToken);
        String authorisedParty = UxModeFilter.isAndroidApp() ? getAppClientId() : getWebClientId();
        if (idToken == null || idToken.getPayload() == null || !idToken.getPayload().getAuthorizedParty().equals(authorisedParty)) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("googleIdToken", "Invalid GoogleIdToken !");
            throw new InvalidArgumentException(jsonObject);
        }
        Payload payload = idToken.getPayload();
        logger.log(Level.INFO, "GoogleApi Payload : " + new Gson().toJson(payload));
        if (payload.get("given_name") == null || ((String) payload.get("given_name")).isEmpty()) {
            logger.log(Level.SEVERE, "Google given_name is missing for GoogleUser: " + payload.getSubject());
            throw new UnexpectedServerException();
        }
        UserData userData = new UserData();
        userData.setGoogleId(payload.getSubject());
        userData.setFirstName((String) payload.get("given_name"));
        userData.setLastName((String) payload.get("family_name"));
        userData.setEmail(payload.getEmail());
        return userData;
    } catch (GeneralSecurityException | IOException e) {
        logger.log(Level.SEVERE, "Google id token verification failed: " + e);
        throw new UnexpectedServerException();
    }
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) UserData(com.pratilipi.data.client.UserData) GeneralSecurityException(java.security.GeneralSecurityException) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) Payload(com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload) IOException(java.io.IOException) GoogleIdToken(com.google.api.client.googleapis.auth.oauth2.GoogleIdToken)

Example 30 with UnexpectedServerException

use of com.pratilipi.common.exception.UnexpectedServerException in project pratilipi by Pratilipi.

the class FacebookApi method getUserData.

public static UserData getUserData(String fbUserAccessToken) throws InvalidArgumentException, UnexpectedServerException {
    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put("access_token", fbUserAccessToken);
    paramsMap.put("fields", "id,first_name,last_name,gender,birthday,email");
    String responsePayload = HttpUtil.doGet(GRAPH_API_2p6_URL + "/me", paramsMap);
    JsonObject responseJson = new Gson().fromJson(responsePayload, JsonElement.class).getAsJsonObject();
    if (responseJson.get("error") != null) {
        logger.log(Level.SEVERE, "Error response from Graph Api.");
        // Facebook returns code 190 if access-token is expired
        if (responseJson.get("error").getAsJsonObject().get("code").getAsInt() == 190)
            throw new InvalidArgumentException("Facebook AccessToken is expired.");
        else
            throw new UnexpectedServerException();
    } else {
        if (responseJson.get("first_name") == null || responseJson.get("first_name").getAsString().isEmpty()) {
            logger.log(Level.INFO, "HTTP Response : " + responseJson);
            logger.log(Level.SEVERE, "Facebook first_name is missing for FacebookUser: " + responseJson.get("id").getAsString());
            throw new UnexpectedServerException();
        }
        UserData userData = new UserData();
        userData.setFacebookId(responseJson.get("id").getAsString());
        userData.setFirstName(responseJson.get("first_name").getAsString());
        userData.setLastName(responseJson.get("last_name").getAsString());
        if (responseJson.get("gender") != null)
            userData.setGender(Gender.valueOf(responseJson.get("gender").getAsString().toUpperCase()));
        if (responseJson.get("birthday") != null) {
            String dob = responseJson.get("birthday").getAsString();
            String year = dob.substring(6);
            String month = dob.substring(0, 2);
            String date = dob.substring(3, 5);
            userData.setDateOfBirth(year + "-" + month + "-" + date);
        }
        if (responseJson.get("email") != null)
            userData.setEmail(responseJson.get("email").getAsString());
        return userData;
    }
}
Also used : InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) HashMap(java.util.HashMap) UserData(com.pratilipi.data.client.UserData) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson)

Aggregations

UnexpectedServerException (com.pratilipi.common.exception.UnexpectedServerException)46 IOException (java.io.IOException)19 JsonObject (com.google.gson.JsonObject)12 InvalidArgumentException (com.pratilipi.common.exception.InvalidArgumentException)12 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 HashMap (java.util.HashMap)12 Gson (com.google.gson.Gson)10 DataAccessor (com.pratilipi.data.DataAccessor)10 InsufficientAccessException (com.pratilipi.common.exception.InsufficientAccessException)6 BlobEntry (com.pratilipi.data.type.BlobEntry)6 Date (java.util.Date)6 File (java.io.File)5 JsonElement (com.google.gson.JsonElement)4 Get (com.pratilipi.api.annotation.Get)4 Post (com.pratilipi.api.annotation.Post)4 GenericResponse (com.pratilipi.api.shared.GenericResponse)4 OutputStream (java.io.OutputStream)4 URL (java.net.URL)4 GcsFilename (com.google.appengine.tools.cloudstorage.GcsFilename)3 Page (com.pratilipi.data.type.Page)3