Search in sources :

Example 41 with UnexpectedServerException

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

the class RtdbAccessorFirebaseImpl method getUserPreference.

// PREFERENCE Table
@Override
public UserPreferenceRtdb getUserPreference(Long userId) throws UnexpectedServerException {
    try {
        BlobEntry blobEntry = HttpUtil.doGet(_getUserPreferenceDbUrl(userId), headersMap, null);
        String jsonStr = new String(blobEntry.getData(), "UTF-8");
        return _getUserPreferenceRtdb(jsonStr);
    } catch (UnsupportedEncodingException e) {
        logger.log(Level.SEVERE, "Failed to parse response from Firebase.", e);
        throw new UnexpectedServerException();
    }
}
Also used : UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) BlobEntry(com.pratilipi.data.type.BlobEntry) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 42 with UnexpectedServerException

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

the class AccessTokenFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    String requestUri = request.getRequestURI();
    String userAgent = request.getHeader("user-agent");
    String accessTokenId = null;
    // Get from Header: Access-Token
    if (request.getHeader(RequestHeader.ACCESS_TOKEN_PAG.getName()) != null)
        accessTokenId = request.getHeader(RequestHeader.ACCESS_TOKEN_PAG.getName());
    else // Get from Header: AccessToken
    if (request.getHeader(RequestHeader.ACCESS_TOKEN.getName()) != null)
        accessTokenId = request.getHeader(RequestHeader.ACCESS_TOKEN.getName());
    else // Get from Cookie: access_token
    if (getCookieValue(RequestCookie.ACCESS_TOKEN.getName(), request) != null)
        accessTokenId = getCookieValue(RequestCookie.ACCESS_TOKEN.getName(), request);
    else // Get from param: accessToken
    if (request.getParameter(RequestParameter.ACCESS_TOKEN.getName()) != null)
        accessTokenId = request.getParameter(RequestParameter.ACCESS_TOKEN.getName());
    // trim
    accessTokenId = (accessTokenId == null || accessTokenId.trim().isEmpty()) ? null : accessTokenId.trim();
    // AccessToken
    AccessToken accessToken;
    // Appengine start request
    if (requestUri.equals("/remote_api") || (userAgent != null && userAgent.equals("Amazon CloudFront"))) {
        accessToken = null;
    // local testing
    } else if (UxModeFilter.getWebsite() == Website.ALPHA) {
        accessToken = AccessTokenDataUtil.newUserAccessToken(request);
        try {
            Map<String, String> paramsMap = new HashMap<>();
            if (accessTokenId != null)
                paramsMap.put("accessToken", accessTokenId);
            String responsePayload = HttpUtil.doGet("https://gamma.pratilipi.com/user/accesstoken", paramsMap.size() == 0 ? null : paramsMap);
            JsonObject responseJson = new Gson().fromJson(responsePayload, JsonElement.class).getAsJsonObject();
            accessToken.setId(responseJson.get("accessToken").getAsString());
        } catch (UnexpectedServerException e) {
        // Do Nothing
        }
        if (!accessToken.getId().equals(accessTokenId)) {
            accessTokenId = accessToken.getId();
            setCookieValue(RequestCookie.ACCESS_TOKEN.getName(), accessTokenId, 30, response);
        }
    } else if (autoGenerate) {
        // Used by gamma, default & api modules.
        accessToken = AccessTokenDataUtil.newUserAccessToken(request);
        accessToken.setId(accessTokenId != null ? accessTokenId : "0");
        setCookieValue(RequestCookie.ACCESS_TOKEN.getName(), accessTokenId, 30, response);
    } else if (isWorker) {
        // Used by worker module.
        accessTokenId = dataAccessor.getAppProperty(AppProperty.WORKER_ACCESS_TOKEN_ID).getValue();
        accessToken = dataAccessor.getAccessToken(accessTokenId);
    } else {
        if (accessTokenId == null) {
            dispatchResponse(response, new InvalidArgumentException("Access Token is missing."));
            return;
        }
        accessToken = AccessTokenDataUtil.newUserAccessToken(request);
        accessToken.setId(accessTokenId);
    }
    threadLocalAccessToken.set(accessToken);
    chain.doFilter(request, response);
    threadLocalAccessToken.remove();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) DataAccessor(com.pratilipi.data.DataAccessor) AccessToken(com.pratilipi.data.type.AccessToken) HttpServletResponse(javax.servlet.http.HttpServletResponse) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) HashMap(java.util.HashMap) Map(java.util.Map)

Example 43 with UnexpectedServerException

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

the class EmailUtil method sendMail.

public static void sendMail(String senderName, String senderEmail, String recipientName, String recipientEmail, String subject, String body) throws UnexpectedServerException {
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senderEmail, senderName));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail, MimeUtility.encodeText(recipientName, "UTF-8", "B")));
        // TODO: Uncomment when we migrate to other email service providers
        // msg.addRecipient( Message.RecipientType.BCC, new InternetAddress( "mail-archive@pratilipi.com", "Mail Archive" ) );
        msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
        msg.setContent(body, "text/html");
        Transport.send(msg);
        logger.log(Level.INFO, "Successfully sent mail to " + recipientEmail + ".");
    } catch (UnsupportedEncodingException | MessagingException e) {
        logger.log(Level.SEVERE, "Failed to send mail to " + recipientEmail + ".", e);
        throw new UnexpectedServerException();
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 44 with UnexpectedServerException

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

the class EcsCuratedApi method get.

@Get
public GetResponse get(GetRequest request) throws InvalidArgumentException, UnexpectedServerException {
    if (request.type == CuratedType.LIST && request.name == null) {
        throw new InvalidArgumentException("name required");
    }
    if (request.type == CuratedType.LIST) {
        Map<String, JsonObject> dataMap = new HashMap<>();
        for (String name : Arrays.asList(request.name.split(","))) {
            List<String> uriList;
            String listName = "list." + request.language.getCode() + "." + name;
            try {
                String fileName = "curated/" + listName;
                InputStream inputStream = DataAccessor.class.getResource(fileName).openStream();
                uriList = IOUtils.readLines(inputStream, "UTF-8");
                inputStream.close();
            } catch (NullPointerException e) {
                uriList = new ArrayList<>();
            } catch (IOException e) {
                throw new UnexpectedServerException();
            }
            // JsonElement
            JsonObject jsonObject = new JsonObject();
            // Setting title and titleEn
            if (!uriList.isEmpty()) {
                String firstLine = uriList.get(0);
                if (firstLine.contains("|")) {
                    jsonObject.addProperty("title", firstLine.substring(0, firstLine.indexOf("|")).trim());
                    jsonObject.addProperty("titleEn", firstLine.substring(firstLine.indexOf("|") + 1).trim());
                } else {
                    jsonObject.addProperty("title", firstLine);
                    jsonObject.addProperty("titleEn", "");
                }
            }
            // JsonArray
            JsonArray uriArray = new JsonArray();
            for (int i = 1; i < uriList.size(); i++) if (!uriList.get(i).trim().isEmpty())
                uriArray.add(uriList.get(i));
            jsonObject.add("uriList", uriArray);
            // Main JsonArray
            dataMap.put(name, jsonObject);
        }
        return new GetResponse(dataMap);
    } else if (request.type == CuratedType.HOME) {
        List<String> uriList;
        try {
            String fileName = "curated/home." + request.language.getCode();
            InputStream inputStream = DataAccessor.class.getResource(fileName).openStream();
            uriList = IOUtils.readLines(inputStream, "UTF-8");
            inputStream.close();
        } catch (IOException e) {
            throw new UnexpectedServerException();
        }
        // JsonArray
        JsonArray uriArray = new JsonArray();
        for (int i = 0; i < uriList.size(); i++) if (!uriList.get(i).trim().isEmpty())
            uriArray.add(uriList.get(i));
        return new GetResponse(uriArray);
    }
    throw new InvalidArgumentException("type not supported yet");
}
Also used : InputStream(java.io.InputStream) DataAccessor(com.pratilipi.data.DataAccessor) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) Get(com.pratilipi.api.annotation.Get)

Example 45 with UnexpectedServerException

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

the class EcsEmailReportApi method get.

@Post
public GenericResponse get(PostRequest request) throws InvalidArgumentException, UnexpectedServerException {
    boolean invalidRequest = false;
    for (String email : request.getReceievers()) if (!email.endsWith("@pratilipi.com"))
        invalidRequest = true;
    for (String email : request.getCc()) if (!email.endsWith("@pratilipi.com"))
        invalidRequest = true;
    if (invalidRequest)
        throw new InvalidArgumentException("Nopes. Not this time.");
    try {
        // CONVERTING LIST TO ARRAY
        InternetAddress[] receivers = createInternetAddressArray(request.getReceievers());
        InternetAddress[] ccs = createInternetAddressArray(request.getCc());
        com.pratilipi.common.util.EmailUtil.sendMail("Team Pratilipi", "contact@pratilipi.com", receivers, ccs, request.getSubject(), request.getBody());
    } catch (UnsupportedEncodingException e) {
        Logger.getLogger(EcsEmailReportApi.class.getName()).log(Level.SEVERE, "Error while create internetaddess array for conversation email", e);
        throw new UnexpectedServerException();
    }
    return new GenericResponse();
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) GenericResponse(com.pratilipi.api.shared.GenericResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Post(com.pratilipi.api.annotation.Post)

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