Example usage for java.lang NumberFormatException getMessage

List of usage examples for java.lang NumberFormatException getMessage

Introduction

In this page you can find the example usage for java.lang NumberFormatException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:dk.netarkivet.wayback.NetarchiveResourceStore.java

/**
 * Transforms search result into a resource, according to the ResourceStore interface.
 *
 * @param captureSearchResult the search result.
 * @return a valid resource containing metadata and a link to the ARC record.
 * @throws ResourceNotAvailableException if something went wrong fetching record.
 *//*from  ww  w.j av a2  s  . co m*/
public Resource retrieveResource(CaptureSearchResult captureSearchResult) throws ResourceNotAvailableException {
    long offset;
    String responseCode = null;
    Map<String, Object> metadata = new HashMap<String, Object>();
    ARCRecord arcRecord;
    ArchiveRecordHeader header;

    String arcfile = captureSearchResult.getFile();
    try {
        offset = captureSearchResult.getOffset();
    } catch (NumberFormatException e) {
        logger.error("Error looking for non existing resource", e);
        throw new ResourceNotAvailableException(
                "NetarchiveResourceStore " + "thows NumberFormatException when reading offset.");
    } catch (NullPointerException e) {
        logger.error("Error looking for non existing resource", e);
        throw new ResourceNotAvailableException("NetarchiveResourceStore "
                + "throws NullPointerException when accessing " + "CaptureResult given from Wayback.");
    }
    logger.info("Received request for resource from file '" + arcfile + "' at offset '" + offset + "'");
    BitarchiveRecord bitarchiveRecord = client.get(arcfile, offset);
    if (bitarchiveRecord == null) {
        throw new ResourceNotAvailableException(
                "NetarchiveResourceStore: " + "Bitarchive didn't return the requested record.");
    }
    logger.info("Retrieved resource from file '" + arcfile + "' at offset '" + offset + "'");

    InputStream is = bitarchiveRecord.getData();
    // Match header-lines (until empty line).
    try {
        for (String line = InputStreamUtils.readLine(is); line != null
                && line.length() > 0; line = InputStreamUtils.readLine(is)) {
            Matcher m = HTTP_HEADER_PATTERN.matcher(line);
            if (m.matches()) {
                responseCode = m.group(1);
                logger.debug("Setting response code '" + responseCode + "'");

            } else {
                String[] parts = line.split(":", 2);
                if (parts.length != 2) {
                    logger.debug("Malformed header line '" + line + "'");
                } else {
                    String name = parts[0];
                    String contents = parts[1].trim();
                    if (contents != null) {
                        if (name.equals("Content-Length")) {
                            logger.info("Setting length header to '" + contents + "'");
                            metadata.put(ARCRecordMetaData.LENGTH_FIELD_KEY, contents);
                        } else if (name.equals("Content-Type")) {
                            logger.info("Setting Content-Type header to '" + contents + "'");
                            metadata.put(ARCRecordMetaData.MIMETYPE_FIELD_KEY, contents);
                        } else if (name.equals("Location")) {
                            logger.info("Setting redirect Location header to '" + contents + "'");
                            metadata.put("Location", contents);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.error("Error looking for empty line", e);
        throw new ResourceNotAvailableException(e.getMessage());
    }
    // fill metadata for ARC record.
    metadata.put(ARCRecordMetaData.URL_FIELD_KEY, captureSearchResult.getUrlKey());
    // TODO the following is the correct way to set the URL. If we do
    // things this way then we should be able to get arcrecord to parse
    // the headers for us.
    /*
     * metadata.put(ARCRecordMetaData.URL_FIELD_KEY, captureSearchResult.getOriginalUrl());
     */
    try {
        metadata.put(ARCRecordMetaData.IP_HEADER_FIELD_KEY, captureSearchResult.getOriginalHost());
    } catch (NullPointerException ex) {
        metadata.put(ARCRecordMetaData.IP_HEADER_FIELD_KEY, "");
    }
    metadata.put(ARCRecordMetaData.DATE_FIELD_KEY, captureSearchResult.getCaptureDate().toString());
    metadata.put(ARCRecordMetaData.MIMETYPE_FIELD_KEY, captureSearchResult.getMimeType());
    metadata.put(ARCRecordMetaData.VERSION_FIELD_KEY, captureSearchResult.getHttpCode());
    metadata.put(ARCRecordMetaData.ABSOLUTE_OFFSET_KEY, "" + offset);
    metadata.put(ARCRecordMetaData.LENGTH_FIELD_KEY, "" + bitarchiveRecord.getLength());
    if (responseCode != null) {
        metadata.put(ARCRecordMetaData.STATUSCODE_FIELD_KEY, responseCode);
    }

    // create header.
    try {
        header = new ARCRecordMetaData(arcfile, metadata);
    } catch (IOException e) {
        logger.error("Could not create header", e);
        throw new ResourceNotAvailableException(e.getMessage());
    }

    // create ARCRecord.
    try {
        arcRecord = new ARCRecord(is, header, 0, false, false, true);
        int code = arcRecord.getStatusCode();
        logger.debug("ARCRecord created with code '" + code + "'");
        arcRecord.skipHttpHeader();
    } catch (NullPointerException e) {
        logger.error("Could not create ARCRecord", e);
        throw new ResourceNotAvailableException("ARC record doesn't contain" + " valid http URL");
    } catch (IOException e) {
        logger.error("Could not create ARCRecord", e);
        throw new ResourceNotAvailableException(e.getMessage());
    }
    final String statusCode = responseCode;
    final Map<String, Object> metadataF = metadata;
    // TODO This the sleaziest thing in this class. Why does the
    // ARCRecord give the wrong status code if we don't override this method?
    Resource resource = new ArcResource(arcRecord, (ArchiveReader) null) {
        public int getStatusCode() {
            return Integer.parseInt(statusCode);
        }
        // FIXME incompatible, needed?
        /*
        @Override
        public Map<String, String> getHttpHeaders() {
        return metadataF;
        }
        */
    };
    logger.info("Returning resource '" + resource + "'");
    return resource;
}

From source file:com.kenshoo.freemarker.util.DataModelParser.java

private static Object parseValue(String value, TimeZone timeZone) throws DataModelParsingException {
    // Note: Because we fall back to interpret the input as a literal string value when it doesn't look like
    // anything else (like a number, boolean, etc.), it's important to avoid misunderstandings, and throw exception
    // in suspicious situations. The user can always quote the string value if we are "too smart". But he will
    // be confused about the rules of FreeMarker if what he believes to be a non-string is misinterpreted by this
    // parser as a string. Getting sometimes an error and then quoting the string is better than that.

    if (value.endsWith(";")) { // Tolerate this habit of Java and JavaScript programmers
        value = value.substring(value.length() - 1).trim();
    }/*w ww . ja v  a  2  s . c om*/

    if (NUMBER_LIKE.matcher(value).matches()) {
        try {
            return new BigDecimal(value);
        } catch (NumberFormatException e) {
            // Maybe it's a ISO 8601 Date/time/datetime
            CalendarFieldsToDateConverter calToDateConverter = new TrivialCalendarFieldsToDateConverter();

            DateParseException attemptedTemportalPExc = null;
            String attemptedTemporalType = null;
            final int dashIdx = value.indexOf('-');
            final int colonIdx = value.indexOf(':');
            if (value.indexOf('T') > 1 || (dashIdx > 1 && colonIdx > dashIdx)) {
                try {
                    return new Timestamp(
                            DateUtil.parseISO8601DateTime(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date-time";
                    attemptedTemportalPExc = pExc;
                }
            } else if (dashIdx > 1) {
                try {
                    return new java.sql.Date(
                            DateUtil.parseISO8601Date(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date";
                    attemptedTemportalPExc = pExc;
                }
            } else if (colonIdx > 1) {
                try {
                    return new Time(DateUtil.parseISO8601Time(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "time";
                    attemptedTemportalPExc = pExc;
                }
            }
            if (attemptedTemportalPExc == null) {
                throw new DataModelParsingException("Malformed number: " + value, e);
            } else {
                throw new DataModelParsingException("Malformed ISO 8601 " + attemptedTemporalType
                        + " (or malformed number): " + attemptedTemportalPExc.getMessage(), e.getCause());
            }
        }
    } else if (value.startsWith("\"")) {
        try {
            return JSON_MAPPER.readValue(value, String.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed quoted string (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("\'")) {
        throw new DataModelParsingException(
                "Malformed quoted string (using JSON syntax): Use \" character for quotation, not \' character.");
    } else if (value.startsWith("[")) {
        try {
            return JSON_MAPPER.readValue(value, List.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("{")) {
        try {
            return JSON_MAPPER.readValue(value, LinkedHashMap.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("<")) {
        try {
            DocumentBuilder builder = NodeModel.getDocumentBuilderFactory().newDocumentBuilder();
            ErrorHandler errorHandler = NodeModel.getErrorHandler();
            if (errorHandler != null)
                builder.setErrorHandler(errorHandler);
            final Document doc = builder.parse(new InputSource(new StringReader(value)));
            NodeModel.simplify(doc);
            return doc;
        } catch (SAXException e) {
            final String saxMsg = e.getMessage();
            throw new DataModelParsingException("Malformed XML: " + (saxMsg != null ? saxMsg : e), e);
        } catch (Exception e) {
            throw new DataModelParsingException("XML parsing has failed with internal error: " + e, e);
        }
    } else if (value.equalsIgnoreCase(KEYWORD_TRUE)) {
        checkKeywordCase(value, KEYWORD_TRUE);
        return Boolean.TRUE;
    } else if (value.equalsIgnoreCase(KEYWORD_FALSE)) {
        checkKeywordCase(value, KEYWORD_FALSE);
        return Boolean.FALSE;
    } else if (value.equalsIgnoreCase(KEYWORD_NULL)) {
        checkKeywordCase(value, KEYWORD_NULL);
        return null;
    } else if (value.equalsIgnoreCase(KEYWORD_NAN)) {
        checkKeywordCase(value, KEYWORD_NAN);
        return Double.NaN;
    } else if (value.equalsIgnoreCase(KEYWORD_INFINITY)) {
        checkKeywordCase(value, KEYWORD_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_POSITIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_POSITIVE_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_NEGATIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_NEGATIVE_INFINITY);
        return Double.NEGATIVE_INFINITY;
    } else if (value.length() == 0) {
        throw new DataModelParsingException(
                "Empty value. (If you indeed wanted a 0 length string, quote it, like \"\".)");
    } else {
        return value;
    }
}

From source file:com.megaeyes.web.controller.UserController.java

/**
 * @Title: createUser//  w  ww  .  ja  v  a 2 s  . c  o  m
 * @Description: 
 * @param request
 * @param response
 *            
 * @return void 
 * @throws
 */
@ControllerDescription(description = "", isLog = true, isCheckSession = true)
@RequestMapping("/createUser.json")
public void createUser(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    BaseResponse resp = new BaseResponse();
    request.setCharacterEncoding("UTF-8");
    // License
    resp.setCode(checkUserLicence());

    String logonName = (String) request.getAttribute("logonName");
    String password = (String) request.getAttribute("password");
    String organId = (String) request.getAttribute("organId");
    String accessServerId = (String) request.getAttribute("accessServerId");
    String note = (String) request.getAttribute("note");
    String name = (String) request.getAttribute("name");
    String sex = (String) request.getAttribute("sex");
    Long age = (long) 20;
    String age1 = (String) request.getAttribute("age");
    if (StringUtils.isNotBlank(age1)) {
        try {
            age = Long.parseLong(age1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("age");
        }
    }
    String mobile = (String) request.getAttribute("mobile");
    String phone = (String) request.getAttribute("phone");
    String email = (String) request.getAttribute("email");
    Short isSuspend = 0;
    Long maxSession = (long) 4;
    String maxSession1 = (String) request.getAttribute("maxSession");
    if (StringUtils.isNotBlank(maxSession1)) {
        try {
            maxSession = Long.parseLong(maxSession1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("maxSession");
        }
    }
    String userAccount = "0";
    Short priority = 1;
    String priority1 = (String) request.getAttribute("priority");
    if (StringUtils.isNotBlank(priority1)) {
        try {
            priority = Short.parseShort(priority1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("priority");
        }
    }
    String sipCode = (String) request.getAttribute("sipCode");
    String dispatchServerId = (String) request.getAttribute("dispatchServerId");
    if ("null".equals(dispatchServerId)) {
        dispatchServerId = "";
    }
    // ?
    Short isInnerUser = 1;
    String isInnerUserString = request.getParameter("isInnerUser");
    if (StringUtils.isNotBlank(isInnerUserString)) {
        try {
            isInnerUser = Short.parseShort(isInnerUserString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("isInnerUser");
        }
    }
    if (resp.getCode().equals(ErrorCode.SUCCESS)) {
        try {
            String id = userManager.createUser(logonName, password, organId, accessServerId, note, name, sex,
                    age, mobile, phone, email, isSuspend, maxSession, userAccount, priority, sipCode,
                    dispatchServerId, isInnerUser);
            // System.out.println("---------------"+id);
            resp.setCode(ErrorCode.SUCCESS);
            resp.setMessage(id);
        } catch (BusinessException be) {
            resp.setCode(be.getCode());
            resp.setMessage(be.getMessage());
        }
    }
    writePageNoZip(response, resp);
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java

public HttpResponse fetch(org.apache.shindig.gadgets.http.HttpRequest request) throws GadgetException {
    HttpUriRequest httpMethod = null;// ww w  .  j  ava  2  s  .c o m
    Preconditions.checkNotNull(request);
    final String methodType = request.getMethod();

    final org.apache.http.HttpResponse response;
    final long started = System.currentTimeMillis();

    // Break the request Uri to its components:
    Uri uri = request.getUri();
    if (StringUtils.isEmpty(uri.getAuthority())) {
        throw new GadgetException(GadgetException.Code.INVALID_USER_DATA,
                "Missing domain name for request: " + uri, HttpServletResponse.SC_BAD_REQUEST);
    }
    if (StringUtils.isEmpty(uri.getScheme())) {
        throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Missing schema for request: " + uri,
                HttpServletResponse.SC_BAD_REQUEST);
    }
    String[] hostparts = StringUtils.splitPreserveAllTokens(uri.getAuthority(), ':');
    int port = -1; // default port
    if (hostparts.length > 2) {
        throw new GadgetException(GadgetException.Code.INVALID_USER_DATA,
                "Bad host name in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST);
    }
    if (hostparts.length == 2) {
        try {
            port = Integer.parseInt(hostparts[1]);
        } catch (NumberFormatException e) {
            throw new GadgetException(GadgetException.Code.INVALID_USER_DATA,
                    "Bad port number in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    String requestUri = uri.getPath();
    // Treat path as / if set as null.
    if (uri.getPath() == null) {
        requestUri = "/";
    }
    if (uri.getQuery() != null) {
        requestUri += '?' + uri.getQuery();
    }

    // Get the http host to connect to.
    HttpHost host = new HttpHost(hostparts[0], port, uri.getScheme());

    try {
        if ("POST".equals(methodType) || "PUT".equals(methodType)) {
            HttpEntityEnclosingRequestBase enclosingMethod = ("POST".equals(methodType))
                    ? new HttpPost(requestUri)
                    : new HttpPut(requestUri);

            if (request.getPostBodyLength() > 0) {
                enclosingMethod
                        .setEntity(new InputStreamEntity(request.getPostBody(), request.getPostBodyLength()));
            }
            httpMethod = enclosingMethod;
        } else if ("GET".equals(methodType)) {
            httpMethod = new HttpGet(requestUri);
        } else if ("HEAD".equals(methodType)) {
            httpMethod = new HttpHead(requestUri);
        } else if ("DELETE".equals(methodType)) {
            httpMethod = new HttpDelete(requestUri);
        }
        for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
            httpMethod.addHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
        }

        // Disable following redirects.
        if (!request.getFollowRedirects()) {
            httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        }

        // HttpClient doesn't handle all cases when breaking url (specifically '_' in domain)
        // So lets pass it the url parsed:
        response = FETCHER.execute(host, httpMethod);

        if (response == null) {
            throw new IOException("Unknown problem with request");
        }

        long now = System.currentTimeMillis();
        if (now - started > slowResponseWarning) {
            slowResponseWarning(request, started, now);
        }

        return makeResponse(response);

    } catch (Exception e) {
        long now = System.currentTimeMillis();

        // Find timeout exceptions, respond accordingly
        if (TIMEOUT_EXCEPTIONS.contains(e.getClass())) {
            LOG.info("Timeout for " + request.getUri() + " Exception: " + e.getClass().getName() + " - "
                    + e.getMessage() + " - " + (now - started) + "ms");
            return HttpResponse.timeout();
        }

        LOG.log(Level.INFO, "Got Exception fetching " + request.getUri() + " - " + (now - started) + "ms", e);

        // Separate shindig error from external error
        throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        // cleanup any outstanding resources..
        if (httpMethod != null)
            try {
                httpMethod.abort();
            } catch (UnsupportedOperationException e) {
                // ignore
            }
    }
}

From source file:org.ala.dao.TaxonConceptSHDaoImpl.java

/**
 * Populate a TaxonConcept from the data in the lucene index.
 * //  w w  w.  jav a  2 s .  co  m
 * @param doc
 * @return
 */
private SearchTaxonConceptDTO createTaxonConceptFromIndex(Document doc, float score) {
    SearchTaxonConceptDTO taxonConcept = new SearchTaxonConceptDTO();
    taxonConcept.setGuid(doc.get("guid"));
    taxonConcept.setParentGuid(doc.get("parentGuid"));
    if (doc.get("parentId") != null) {
        taxonConcept.setParentId(doc.get("parentId"));
    }
    taxonConcept.setName(doc.get("scientificNameRaw"));
    taxonConcept.setAcceptedConceptName(doc.get("acceptedConceptName"));
    String hasChildrenAsString = doc.get("hasChildren");

    String[] commonNames = doc.getValues("commonName");
    if (commonNames.length > 0) {
        taxonConcept.setCommonName(commonNames[0]);
    }

    taxonConcept.setHasChildren(Boolean.parseBoolean(hasChildrenAsString));
    taxonConcept.setScore(score);
    taxonConcept.setRank(doc.get("rank"));
    try {
        taxonConcept.setLeft(Integer.parseInt(doc.get("left")));
        taxonConcept.setRight(Integer.parseInt(doc.get("right")));
    } catch (NumberFormatException e) {
        // expected if left and right values are unavailable
    }

    try {
        if (doc.get("rankId") != null) {
            taxonConcept.setRankId(Integer.parseInt(doc.get("rankId")));
        }
    } catch (NumberFormatException ex) {
        logger.error(
                "Error parsing rankId: " + ex.getMessage() + " for taxon concept : " + taxonConcept.getGuid());
    }
    taxonConcept.setPestStatus(doc.get(StatusType.PEST.toString()));
    taxonConcept.setConservationStatus(doc.get(StatusType.CONSERVATION.toString()));

    // add image detais
    taxonConcept.setImage(doc.get("image"));
    taxonConcept.setThumbnail(doc.get("thumbnail"));
    return taxonConcept;
}

From source file:Controller.ProviderController.java

@RequestMapping(value = "/SaveSetting", method = RequestMethod.POST)
public String saveSetting(HttpServletRequest request) {
    try {//from w w  w . j  a  v a2s.  c om
        int providerID;
        try {
            providerID = Integer.parseInt(request.getParameter("providerID"));
        } catch (NumberFormatException e) {
            providerID = 0;
        }
        providerService.saveSetting(providerID, request.getParameter("settingJson"));
        if (request.getParameter("language") != null) {
            return "redirect:/Provider/Notification" + "?language=" + request.getParameter("language");
        } else {
            return "redirect:/Provider/Notification";
        }

    } catch (Exception e) {
        HttpSession session = request.getSession();
        String content = "Function: ProviderController - saveSetting\n" + "***Input***\n" + "providerID: "
                + request.getParameter("providerID") + "\n" + "settingJson: "
                + request.getParameter("settingJson") + "\n" + "**********\n" + "****Error****\n"
                + e.getMessage() + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:org.exoplatform.clouddrive.box.BoxAPI.java

/**
 * Update link to the drive's long-polling changes notification service. This kind of service optional and
 * may not be supported. If long-polling changes notification not supported then this method will do
 * nothing./*from w  ww.java 2s.c o  m*/
 * 
 */
void updateChangesLink() throws BoxException, RefreshAccessException {
    BoxDefaultRequestObject obj = new BoxDefaultRequestObject();
    try {
        BoxCollection changesPoll = client.getEventsManager().getEventOptions(obj);
        ArrayList<BoxTypedObject> ce = changesPoll.getEntries();
        if (ce.size() > 0) {
            BoxTypedObject c = ce.get(0);

            Object urlObj = c.getValue("url");
            String url = urlObj != null ? urlObj.toString() : null;

            Object typeObj = c.getValue("type");
            String type = typeObj != null ? typeObj.toString() : null;

            Object ttlObj = c.getValue("ttl");
            if (ttlObj == null) {
                ttlObj = c.getExtraData("ttl");
            }
            long ttl;
            try {
                ttl = ttlObj != null ? Long.parseLong(ttlObj.toString()) : 10;
            } catch (NumberFormatException e) {
                LOG.warn("Error parsing ttl value in Events response [" + ttlObj + "]: " + e);
                ttl = 10; // 10? What is it ttl? The number from Box docs.
            }

            Object maxRetriesObj = c.getValue("max_retries");
            if (maxRetriesObj == null) {
                maxRetriesObj = c.getExtraData("max_retries");
            }
            long maxRetries;
            try {
                maxRetries = maxRetriesObj != null ? Long.parseLong(maxRetriesObj.toString()) : 0;
            } catch (NumberFormatException e) {
                LOG.warn("Error parsing max_retries value in Events response [" + maxRetriesObj + "]: " + e);
                maxRetries = 2; // assume two possible attempts to try use the link
            }

            Object retryTimeoutObj = c.getValue("retry_timeout");
            if (retryTimeoutObj == null) {
                retryTimeoutObj = c.getExtraData("retry_timeout");
            }
            long retryTimeout; // it is in milliseconds
            try {
                retryTimeout = retryTimeoutObj != null ? Long.parseLong(retryTimeoutObj.toString()) * 1000
                        : 600000;
            } catch (NumberFormatException e) {
                LOG.warn(
                        "Error parsing retry_timeout value in Events response [" + retryTimeoutObj + "]: " + e);
                retryTimeout = 600000; // 600 sec = 10min (as mentioned in Box docs)
            }

            this.changesLink = new ChangesLink(type, url, ttl, maxRetries, retryTimeout);
        } else {
            throw new BoxException("Empty entries from Events service.");
        }
    } catch (BoxRestException e) {
        throw new BoxException("Error requesting changes long poll URL: " + e.getMessage(), e);
    } catch (BoxServerException e) {
        throw new BoxException("Error reading changes long poll URL: " + e.getMessage(), e);
    } catch (AuthFatalFailureException e) {
        checkTokenState();
        throw new BoxException("Authentication error for changes long poll URL: " + e.getMessage(), e);
    }
}

From source file:ai.ilikeplaces.logic.Listeners.ListenerMain.java

/**
 * @param request__/*from w  w  w.  j  a  v a  2  s.c om*/
 * @param response__
 */
@Override
public void processRequest(final ItsNatServletRequest request__, final ItsNatServletResponse response__) {
    new AbstractListener(request__, response__) {
        protected String location;

        protected String superLocation;

        protected Long WOEID;

        /**
         * Initialize your document here by appending fragments
         */
        @Override
        @SuppressWarnings("unchecked")
        @_todo(task = "If location is not available, it should be added through a w" + "id"
                + "get(or fragment maybe?)")
        protected final void init(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__,
                final Object... initArgs) {
            final SmartLogger sl = SmartLogger.start(Loggers.LEVEL.DEBUG, "Location Page.", 60000, null, true);

            //this.location = (String) request_.getServletRequest().getAttribute(RBGet.config.getString("HttpSessionAttr.location"));
            getLocationSuperLocation: {
                final String[] attr = ((String) request__.getServletRequest()
                        .getAttribute(RBGet.globalConfig.getString(HTTP_SESSION_ATTR_LOCATION))).split("_");
                location = attr[0];
                if (attr.length == 3) {
                    superLocation = attr[2];
                } else {
                    superLocation = EMPTY;
                }
                tryLocationId: {
                    try {
                        final String w = request__.getServletRequest().getParameter(Location.WOEID);
                        if (w != null) {
                            WOEID = Long.parseLong(request__.getServletRequest().getParameter(Location.WOEID));
                        }
                    } catch (final NumberFormatException e) {
                        Loggers.USER_EXCEPTION.error(WRONG_WOEID_FORMAT, e);
                    }
                }
            }

            sl.appendToLogMSG(RETURNING_LOCATION + location + TO_USER);

            final ResourceBundle gUI = ResourceBundle.getBundle(AI_ILIKEPLACES_RBS_GUI);

            layoutNeededForAllPages: {
                setLoginWidget: {
                    try {
                        new SignInOn(request__, $(Main_login_widget),
                                new SignInOnCriteria().setHumanId(new HumanId(getUsername()))
                                        .setSignInOnDisplayComponent(
                                                SignInOnCriteria.SignInOnDisplayComponent.MOMENTS)) {
                        };
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOGIN_WIDGET, t);
                    }
                }

                SEO: {
                    try {
                        setMainTitle: {
                            $(mainTitle).setTextContent(
                                    MessageFormat.format(gUI.getString("woeidpage.title"), location));
                        }
                        setMetaDescription: {
                            $(mainMetaDesc).setAttribute(MarkupTag.META.content(),
                                    MessageFormat.format(gUI.getString("woeidpage.desc"), location));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SEO, t);
                    }
                }
                signOnDisplayLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0004)
                                            + getUsernameAsValid());
                        } else {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0005)
                                            + location);
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SIGN_ON_DISPLAY_LINK, t);
                    }
                }
                setProfileLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.Profile.getURL());
                        } else {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.signup.getURL());
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_LINK, t);
                    }
                }
                setProfilePhotoLink: {
                    try {
                        if (getUsername() != null) {
                            /**
                             * TODO check for db failure
                             */
                            String url = DB.getHumanCRUDHumanLocal(true)
                                    .doDirtyRHumansProfilePhoto(new HumanId(getUsernameAsValid()))
                                    .returnValueBadly();
                            url = url == null ? null : RBGet.globalConfig.getString(PROFILE_PHOTOS) + url;
                            if (url != null) {
                                $(Main_profile_photo).setAttribute(MarkupTag.IMG.src(), url);
                                //displayBlock($(Main_profile_photo));
                            } else {
                                //displayNone($(Main_profile_photo));
                            }
                        } else {
                            //displayNone($(Main_profile_photo));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_PHOTO_LINK, t);
                    }
                }
            }

            final Return<Location> r;
            if (WOEID != null) {
                r = DB.getHumanCRUDLocationLocal(true).doRLocation(WOEID, REFRESH_SPEC);
            } else {
                r = new ReturnImpl<Location>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION,
                        "Search Unavailable", false);
                //r = DB.getHumanCRUDLocationLocal(true).dirtyRLocation(location, superLocation);
            }

            if (r.returnStatus() == 0 && r.returnValue() != null) {
                final Location existingLocation_ = r.returnValue();

                GEO: {
                    if (existingLocation_.getLocationGeo1() == null
                            || existingLocation_.getLocationGeo2() == null) {
                        final Client ygpClient = YAHOO_GEO_PLANET_FACTORY
                                .getInstance(RBGet.globalConfig.getString("where.yahooapis.com.v1.place"));
                        final Place place = ygpClient.getPlace(existingLocation_.getLocationId().toString());
                        existingLocation_.setLocationGeo1(Double.toString(place.getCoordinates().getY()));
                        existingLocation_.setLocationGeo2(Double.toString(place.getCoordinates().getX()));

                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                DB.getHumanCRUDLocationLocal(true).doULocationLatLng(
                                        new Obj<Long>(existingLocation_.getLocationId()),
                                        new Obj<Double>(place.getCoordinates().getY()),
                                        new Obj<Double>(place.getCoordinates().getX()));
                            }
                        }).run();
                    }
                }

                final Location locationSuperSet = existingLocation_.getLocationSuperSet();
                GEO_WIDGET: {
                    new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Comment(request__,
                            new CommentCriteria(), $(Controller.Page.Main_right_column)) {
                        @Override
                        protected void init(CommentCriteria commentCriteria) {
                            final ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place place = new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place(
                                    request__, new PlaceCriteria()
                                            //This Place
                                            .setPlaceNamePre("Exciting events in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(existingLocation_.getLocationGeo1())
                                            .setPlaceLng(existingLocation_.getLocationGeo2())
                            //Parent Place
                            //.setPlaceSuperName(locationSuperSet.getLocationName())
                            //.setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                            //.setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                            //Parent WOEID
                            //.setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())
                            , $$(CommentIds.commentPerson));
                            place.$$displayNone(place.$$(
                                    ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place.PlaceIds.placeWidget));
                        }
                    };
                }

                final List<String> titleManifest = new ArrayList<String>();

                EVENTS_WIDGETS: {
                    try {
                        /* final JSONObject jsonObject = Modules.getModules().getYahooUplcomingFactory()
                            .getInstance("http://upcoming.yahooapis.com/services/rest/")
                            .get("",
                                    new HashMap<String, String>() {
                                        {//Don't worry, this is a static initializer of this map :)
                                            put("method", "event.search");
                                            put("woeid", WOEID.toString());
                                            put("format", "json");
                                        }
                                    }
                                
                            );
                         final JSONArray events = jsonObject.getJSONObject("rsp").getJSONArray("event");*/

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("http://api.eventful.com/json/events/search/")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("location", "" + existingLocation_.getLocationGeo1() + ","
                                                + existingLocation_.getLocationGeo2());
                                        put("within", "" + 100);
                                    }
                                }

                        );

                        Loggers.debug("Eventful Reply:" + jsonObject.toString());

                        //                            final String eventName = eventJSONObject.getString("title");
                        //                            final String eventUrl = eventJSONObject.getString("url");
                        //                            final String eventDate = eventJSONObject.getString("start_time");
                        //                            final String eventVenue = eventJSONObject.getString("venue_name");

                        final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event");

                        for (int i = 0; i < events.length(); i++) {
                            final JSONObject eventJSONObject = new JSONObject(events.get(i).toString());

                            titleManifest.add(eventJSONObject.get("title").toString());

                            final String photoUrl;
                            String temp = null;
                            try {
                                temp = eventJSONObject.getJSONObject("image").get("url").toString();
                            } catch (final Throwable e) {
                                SmartLogger.g().l(e.getMessage());
                            } finally {
                                photoUrl = temp;
                            }
                            //The pain I go through to make variables final :D

                            new Event(request__, new EventCriteria()
                                    .setEventName(eventJSONObject.get("title").toString())
                                    .setEventStartDate(eventJSONObject.get("start_time").toString())
                                    .setEventPhoto(photoUrl)
                                    .setPlaceCriteria(new PlaceCriteria()
                                            .setPlaceNamePre("This event is taking place in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(eventJSONObject.get("latitude").toString())
                                            .setPlaceLng(eventJSONObject.get("longitude").toString())
                                            //Parent Place
                                            .setPlaceSuperNamePre(
                                                    existingLocation_.getLocationName() + " is located in ")
                                            .setPlaceSuperName(locationSuperSet.getLocationName())
                                            .setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                                            .setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                                            //Parent WOEID
                                            .setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())

                            ), $(Controller.Page.Main_right_column));
                        }
                    } catch (final JSONException e) {
                        sl.l("Error fetching data from Yahoo Upcoming: " + e.getMessage());
                    }
                }

                TWITTER_WIDGETS: {
                    try {
                        final Query _query = new Query(
                                "fun OR happening OR enjoy OR nightclub OR restaurant OR party OR travel :)");
                        _query.geoCode(
                                new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()),
                                        Double.parseDouble(existingLocation_.getLocationGeo2())),
                                40, Query.MILES);
                        _query.setResultType(Query.MIXED);
                        final QueryResult result = TWITTER.search(_query);

                        //final QueryResult result = TWITTER.search(new Query("Happy").geoCode(new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()), Double.parseDouble(existingLocation_.getLocationGeo2())), 160, Query.MILES));
                        for (Status tweet : result.getTweets()) {
                            new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Person(request__,
                                    new PersonCriteria().setPersonName(tweet.getUser().getName())
                                            .setPersonPhoto(tweet.getUser().getProfileImageURL())
                                            .setPersonData(tweet.getText()),
                                    $(Main_right_column));
                            titleManifest.add(tweet.getText());
                        }
                        if (result.getTweets().size() == 0) {
                            sl.l("No twitter results found");
                        }
                    } catch (final Throwable t) {
                        sl.l("An error occurred during twitter fetch:" + t.getMessage());
                    }
                }

                SEO: {
                    setMetaGEOData: {
                        $(Main_ICBM).setAttribute(MarkupTag.META.content(), existingLocation_.getLocationGeo1()
                                + COMMA + existingLocation_.getLocationGeo2());
                        $(Main_geoposition).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationGeo1() + COMMA
                                        + existingLocation_.getLocationGeo2());
                        $(Main_geoplacename).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationName());
                        $(Main_georegion).setAttribute(MarkupTag.META.content(),
                                locationSuperSet.getLocationName());
                    }
                }

                setLocationIdForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationId);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationId().toString());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);

                        $(Main_location_name).setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + "");
                        $(Main_super_location_name).setAttribute(INPUT.value(),
                                locationSuperSet.getLocationName() + "");
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_ID_FOR_JSREFERENCE, t);
                    }
                }

                setLocationNameForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationName);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + OF + locationSuperSet.getLocationName());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_NAME_FOR_JSREFERENCE, t);
                    }
                }

                setLocationAsPageTopic: {
                    try {

                        final StringBuilder title = new StringBuilder();

                        for (final String titleGuest : titleManifest) {
                            title.append(titleGuest);
                        }

                        final String finalTitle = title.toString();

                        $(Main_center_main_location_title).setTextContent(finalTitle.isEmpty()
                                ? (THIS_IS + existingLocation_.getLocationName() + OF + locationSuperSet)
                                : finalTitle);

                        for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true)
                                .doDirtyRLocationsBySuperLocation(existingLocation_))) {
                            $(Main_location_list).appendChild(element);
                            displayBlock($(Main_notice_sh));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_AS_PAGE_TOPIC, t);
                    }
                }
            } else {
                noSupportForNewLocations: {
                    try {
                        //                            $(Main_notice).appendChild(($(P).appendChild(
                        //                                    hTMLDocument__.createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")
                        //                                            + " Were you looking for "
                        //                                    ))));
                        //                            for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true).dirtyRLikeLocations(location))) {
                        //                                $(Main_notice).appendChild(element);
                        //                                displayBlock($(Main_notice_sh));
                        //                            }
                        NotSupportingLikeSearchTooForNow: {
                            $(Main_notice).appendChild(($(P).appendChild(hTMLDocument__
                                    .createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")))));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_NO_SUPPORT_FOR_NEW_LOCATIONS, t);
                    }
                }
            }
            sl.complete(Loggers.LEVEL.SERVER_STATUS, Loggers.DONE);
        }

        /**
         * Use ItsNatHTMLDocument variable stored in the AbstractListener class
         */
        @Override
        protected void registerEventListeners(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__) {
        }

        private List<Element> generateLocationLinks(final List<Location> locationList) {
            final ElementComposer UList = ElementComposer.compose($(UL)).$ElementSetAttribute(MarkupTag.UL.id(),
                    PLACE_LIST);

            for (Location location : locationList) {
                final Element link = $(A);

                link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.href(),
                        PAGE + location.getLocationName() + _OF_
                                + location.getLocationSuperSet().getLocationName()
                                + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

                link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.title(), CLICK_TO_EXPLORE + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.classs(), VTIP);

                final Element linkDiv = $(DIV);

                linkDiv.appendChild(link);

                UList.wrapThis(ElementComposer.compose($(LI)).wrapThis(linkDiv).get());
            }

            final List<Element> elements = new ArrayList<Element>();
            elements.add(UList.get());
            return elements;
        }

        private Element generateLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                    + location.getLocationSuperSet().getLocationName());
            link.setAttribute(A.href(),
                    PAGE + location.getLocationName() + _OF_ + location.getLocationSuperSet().getLocationName()
                            + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                    + location.getLocationSuperSet().getLocationName());
            return link;
        }

        private Element generateSimpleLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(location.getLocationName());
            link.setAttribute(A.href(), PAGE + location.getLocationName()
                    + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName());
            return link;
        }
    };//Listener
}