Example usage for java.lang Integer decode

List of usage examples for java.lang Integer decode

Introduction

In this page you can find the example usage for java.lang Integer decode.

Prototype

public static Integer decode(String nm) throws NumberFormatException 

Source Link

Document

Decodes a String into an Integer .

Usage

From source file:gobblin.source.extractor.extract.jdbc.JdbcProvider.java

public void connect(String driver, String connectionUrl, String user, String password, int numconn, int timeout,
        String type, String proxyHost, int proxyPort) {

    if (proxyHost != null && proxyPort > 0) {
        String remoteHost = "";
        int remotePort = 0;
        // TODO make connection Url parsing much more robust -- some connections URLs can have colons and slashes in the
        // weirdest places
        int hostStart = connectionUrl.indexOf("://") + 3;
        int portStart = connectionUrl.indexOf(":", hostStart);
        remoteHost = connectionUrl.substring(hostStart, portStart);
        remotePort = Integer
                .decode(connectionUrl.substring(portStart + 1, connectionUrl.indexOf("/", portStart)));

        try {//from w w  w.  j a v  a 2s . c o  m
            this.tunnel = Tunnel.build(remoteHost, remotePort, proxyHost, proxyPort);
            int tunnelPort = this.tunnel.getPort();
            //mangle connectionUrl, replace hostname with localhost -- hopefully the hostname is not needed!!!
            String newConnectionUrl = connectionUrl.replaceFirst(remoteHost, "127.0.0.1")
                    .replaceFirst(":" + remotePort, ":" + tunnelPort);
            connectionUrl = newConnectionUrl;
        } catch (IOException ioe) {
            throw new IllegalStateException("Failed to open tunnel to remote host " + remoteHost + ":"
                    + remotePort + " via proxy " + proxyHost + ":" + proxyPort, ioe);
        }
    }

    this.setDriverClassName(driver);
    this.setUsername(user);
    this.setPassword(password);
    this.setUrl(connectionUrl);
    this.setInitialSize(0);
    this.setMaxIdle(numconn);
    this.setMaxWait(timeout);
}

From source file:org.languagetool.dev.dumpcheck.DatabaseHandler.java

DatabaseHandler(File propertiesFile, int maxSentences, int maxErrors) {
    super(maxSentences, maxErrors);

    String insertSql = "INSERT INTO corpus_match "
            + "(version, language_code, ruleid, rule_category, rule_subid, rule_description, message, error_context, small_error_context, corpus_date, "
            + "check_date, sourceuri, source_type, is_visible) "
            + "VALUES (0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)";

    Properties dbProperties = new Properties();
    try (FileInputStream inStream = new FileInputStream(propertiesFile)) {
        dbProperties.load(inStream);//w w w. ja  v  a2 s . co  m
        String dbUrl = getProperty(dbProperties, "dbUrl");
        String dbUser = getProperty(dbProperties, "dbUser");
        String dbPassword = getProperty(dbProperties, "dbPassword");
        batchSize = Integer.decode(dbProperties.getProperty("batchSize", "1"));
        conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
        insertSt = conn.prepareStatement(insertSql);
    } catch (SQLException | IOException e) {
        throw new RuntimeException(e);
    }
    contextTools = new ContextTools();
    contextTools.setContextSize(MAX_CONTEXT_LENGTH);
    contextTools.setErrorMarkerStart(MARKER_START);
    contextTools.setErrorMarkerEnd(MARKER_END);
    contextTools.setEscapeHtml(false);
    smallContextTools = new ContextTools();
    smallContextTools.setContextSize(SMALL_CONTEXT_LENGTH);
    smallContextTools.setErrorMarkerStart(MARKER_START);
    smallContextTools.setErrorMarkerEnd(MARKER_END);
    smallContextTools.setEscapeHtml(false);
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.multiple.MultipleInputFieldHandler.java

@Override
public Object getValue(Field field, String inputName, Map parametersMap, Map filesMap, String desiredClassName,
        Object previousValue) throws Exception {
    List value = (List) previousValue;

    if (value == null)
        value = new ArrayList();

    FieldHandler handler = getFieldHandler(field);

    String[] newValue = (String[]) parametersMap
            .get(inputName + FormProcessor.CUSTOM_NAMESPACE_SEPARATOR + "addItem");
    String[] deleteValue = (String[]) parametersMap
            .get(inputName + FormProcessor.CUSTOM_NAMESPACE_SEPARATOR + "deleteItem");

    if (newValue != null && newValue.length == 1 && newValue[0].equals("true")) {
        try {//ww w .ja  v a  2s . c o m
            Object valueToAdd = handler.getValue(field, inputName, parametersMap, filesMap, field.getBag(),
                    null);
            value.add(valueToAdd);
        } catch (Exception ex) {
            log.debug("Unable to add value to list '{}': {}", field.getFieldName(), ex);
            throw new Exception("Unable to add value");
        }
    } else if (deleteValue != null && deleteValue.length == 1 && !deleteValue[0].equals("-1")) {
        int index = Integer.decode(deleteValue[0]);
        if (index <= value.size())
            value.remove(index);
    } else {
        if (!value.isEmpty()) {
            for (int i = 0; i < value.size(); i++) {
                try {
                    value.set(i,
                            handler.getValue(field, inputName + FormProcessor.CUSTOM_NAMESPACE_SEPARATOR + i,
                                    parametersMap, filesMap, field.getBag(), value.get(i)));
                } catch (Exception ex) {
                    log.debug("Unable to edit value '{}' on list '{}': {}", i, field.getFieldName(), ex);
                    throw new Exception("Unable to edit value");
                }
            }
        }
    }
    return value;
}

From source file:org.nuxeo.ecm.platform.pictures.tiles.restlets.PictureTilesRestlets.java

@Override
public void handle(Request req, Response res) {
    HttpServletRequest request = getHttpRequest(req);
    HttpServletResponse response = getHttpResponse(res);

    String repo = (String) req.getAttributes().get("repoId");
    String docid = (String) req.getAttributes().get("docId");
    Integer tileWidth = Integer.decode((String) req.getAttributes().get("tileWidth"));
    Integer tileHeight = Integer.decode((String) req.getAttributes().get("tileHeight"));
    Integer maxTiles = Integer.decode((String) req.getAttributes().get("maxTiles"));

    Form form = req.getResourceRef().getQueryAsForm();
    String xpath = (String) form.getFirstValue("fieldPath");
    String x = form.getFirstValue("x");
    String y = form.getFirstValue("y");
    String format = form.getFirstValue("format");

    String test = form.getFirstValue("test");
    if (test != null) {
        try {/* w  w w  . j a  va 2  s .c  o m*/
            handleSendTest(res, repo, docid, tileWidth, tileHeight, maxTiles);
            return;
        } catch (IOException e) {
            handleError(res, e);
            return;
        }
    }

    if (repo == null || repo.equals("*")) {
        handleError(res, "you must specify a repository");
        return;
    }
    if (docid == null || repo.equals("*")) {
        handleError(res, "you must specify a documentId");
        return;
    }
    Boolean init = initRepositoryAndTargetDocument(res, repo, docid);

    if (!init) {
        handleError(res, "unable to init repository connection");
        return;
    }

    PictureTilesAdapter adapter;
    try {
        adapter = getFromCache(targetDocument, xpath);
        if (adapter == null) {
            adapter = targetDocument.getAdapter(PictureTilesAdapter.class);
            if ((xpath != null) && (!"".equals(xpath))) {
                adapter.setXPath(xpath);
            }
            updateCache(targetDocument, adapter, xpath);
        }
    } catch (NuxeoException e) {
        handleError(res, e);
        return;
    }

    if (adapter == null) {
        handleNoTiles(res, null);
        return;
    }

    PictureTiles tiles = null;
    try {
        tiles = adapter.getTiles(tileWidth, tileHeight, maxTiles);
    } catch (NuxeoException e) {
        handleError(res, e);
    }

    if ((x == null) || (y == null)) {
        handleSendInfo(res, tiles, format);
        return;
    }

    final Blob image;
    try {
        image = tiles.getTile(Integer.decode(x), Integer.decode(y));
    } catch (NuxeoException | IOException e) {
        handleError(res, e);
        return;
    }

    String reason = "tile";
    Boolean inline = Boolean.TRUE;
    Map<String, Serializable> extendedInfos = new HashMap<>();
    extendedInfos.put("x", x);
    extendedInfos.put("y", y);
    DownloadService downloadService = Framework.getService(DownloadService.class);
    try {
        downloadService.downloadBlob(request, response, targetDocument, xpath, image, image.getFilename(),
                reason, extendedInfos, inline, byteRange -> setEntityToBlobOutput(image, byteRange, res));
    } catch (IOException e) {
        handleError(res, e);
    }
}

From source file:org.patientview.patientview.patiententry.PatientResultAddAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String year = BeanUtils.getProperty(form, "year");
    String month = BeanUtils.getProperty(form, "month");
    String day = BeanUtils.getProperty(form, "day");
    String hour = BeanUtils.getProperty(form, "hour");
    String minute = BeanUtils.getProperty(form, "minute");
    String resultName = BeanUtils.getProperty(form, "patientResultName");
    String resultCode1 = BeanUtils.getProperty(form, "patientResultCode1");
    String resultValue1 = BeanUtils.getProperty(form, "patientResultValue1");
    String resultCode2 = (BeanUtils.getProperty(form, "patientResultCode2") != null)
            ? BeanUtils.getProperty(form, "patientResultCode2")
            : "";
    String resultValue2 = (BeanUtils.getProperty(form, "patientResultValue2") != null)
            ? BeanUtils.getProperty(form, "patientResultValue2")
            : "";

    HttpSession session = request.getSession();
    Map<Long, PatientEnteredResult> results = (Map<Long, PatientEnteredResult>) session
            .getAttribute(resultName);//from www .j  av  a  2 s. co  m

    if (null == results) {
        results = new TreeMap<Long, PatientEnteredResult>();
    }

    int intMonth = Integer.decode(month).intValue() - 1;

    if ("".equals(resultCode2)) {
        PatientEnteredResult result = new PatientEnteredResult(year, intMonth + "", day, hour, minute,
                resultCode1, resultValue1);
        results.put((new Date()).getTime(), result);
    } else {
        PatientEnteredResult result = new PatientEnteredResult(year, intMonth + "", day, hour, minute,
                resultCode1, resultValue1, resultCode2, resultValue2);
        results.put((new Date()).getTime(), result);
    }

    session.setAttribute(resultName, results);

    BeanUtils.setProperty(form, "patientResultCode1", null);
    BeanUtils.setProperty(form, "patientResultCode2", null);
    BeanUtils.setProperty(form, "patientResultValue1", null);
    BeanUtils.setProperty(form, "patientResultValue2", null);

    return mapping.findForward("success");
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.dialcharts.BulletGraph.java

public void configureChart(SourceBean content) {
    logger.debug("IN");
    super.configureChart(content);

    String target = (String) confParameters.get("target");
    if (target != null)
        this.target = new Double(target);

    SourceBean confSB = (SourceBean) content.getAttribute("INTERVALS");
    if (confSB == null) {
        confSB = (SourceBean) content.getAttribute("CONF.INTERVALS");
    }//from w  w  w.  j  a v a 2s .co m
    List confAttrsList = confSB.getAttributeAsList(INTERVAL);
    if (!confAttrsList.isEmpty()) {
        Iterator it = confAttrsList.iterator();
        while (it.hasNext()) {
            SourceBean param = (SourceBean) it.next();
            KpiInterval interval = new KpiInterval();
            String min = (String) param.getAttribute(MIN_INTERVAL);
            String max = (String) param.getAttribute(MAX_INTERVAL);
            String col = (String) param.getAttribute(COLOR_INTERVAL);
            interval.setMin(Double.valueOf(min).doubleValue());
            interval.setMax(Double.valueOf(max).doubleValue());
            Color color = new Color(Integer.decode(col).intValue());
            interval.setColor(color);
            this.intervals.add(interval);
        }
    }
    logger.debug("OUT");
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler.java

public Object getTheValue(Field field, String[] paramValue, String desiredClassName) throws Exception {
    if (paramValue == null || paramValue.length == 0)
        return null;

    if (desiredClassName.equals("byte")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Byte((byte) 0);
        else//from   w w  w  .jav  a2  s.co  m
            return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals("short")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Short((short) 0);
        else
            return Short.decode(paramValue[0]);
    } else if (desiredClassName.equals("int")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Integer(0);
        else
            return Integer.decode(paramValue[0]);
    } else if (desiredClassName.equals("long")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Long(0L);
        else
            return Long.decode(paramValue[0]);
    } else if (desiredClassName.equals(Byte.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals(Short.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Short.decode(paramValue[0]);

    } else if (desiredClassName.equals(Integer.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Integer.decode(paramValue[0]);

    } else if (desiredClassName.equals(Long.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Long.decode(paramValue[0]);

    } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")
            || desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")
            || desiredClassName.equals(BigDecimal.class.getName())) {

        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale(LocaleManager.currentLang()));
        if (desiredClassName.equals(BigDecimal.class.getName()))
            df.setParseBigDecimal(true);
        String pattern = getFieldPattern(field);
        if (pattern != null && !"".equals(pattern)) {
            df.applyPattern(pattern);
        } else {
            df.applyPattern("###.##");
        }
        ParsePosition pp = new ParsePosition(0);
        Number num = df.parse(paramValue[0], pp);
        if (paramValue[0].length() != pp.getIndex() || num == null) {
            log.debug("Error on parsing value");
            throw new ParseException("Error parsing value", pp.getIndex());
        }

        if (desiredClassName.equals(BigDecimal.class.getName())) {
            return num;
        } else if (desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")) {
            return new Float(num.floatValue());
        } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")) {
            return new Double(num.doubleValue());
        }
    } else if (desiredClassName.equals(BigInteger.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return new BigInteger(paramValue[0]);

    }
    throw new IllegalArgumentException("Invalid class for NumericFieldHandler: " + desiredClassName);
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.VersionRedirect.java

/**
 * Checks the bucket to see if versioning is enabled or not.
 *
 * @param nnHostAddress/*w ww. j  av  a 2s  .com*/
 * @param userName
 * @return
 */
public boolean check(String nnHostAddress, String userName) throws IOException {
    String[] nnHost = nnHostAddress.split(":");

    String uri = (path != null) ? path.getFullHdfsObjPath() : request.getPathInfo();
    List<String> bucketPath = Arrays.asList(uri.split("/")).subList(0, 4);
    String bucketMetaPath = StringUtils.join("/", bucketPath) + "/" + BUCKET_META_FILE_NAME;

    GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
            "OPEN", userName, bucketMetaPath, GET);

    httpClient.executeMethod(httpGet);

    String versionConfXml = readInputStream(httpGet.getResponseBodyAsStream());
    httpGet.releaseConnection();

    if (versionConfXml.contains("<Status>Enabled</Status>")) {
        return true;
    } else if (versionConfXml.contains("<Status>Suspended</Status>")) {
        return false;
    } else {
        return false;
    }
}

From source file:com.aurel.track.admin.customize.category.filter.execute.SavedFilterExecuteBL.java

/**
 * Execute a saved filter//w  w  w.j a  v a2  s .  co  m
 * @return
 */
static IntegerStringBean encodedQueryContainsNotSpecifiedParameter(String query, TPersonBean personBean,
        Locale locale) {
    IntegerStringBean integerStringBean = new IntegerStringBean(null, Integer.valueOf(NO_PARAMETER));
    if (query != null && query.length() > 0) {
        String linkReport = ReportQueryBL.b(query);
        Map<String, String> queryEncodedMap = ReportQueryBL.decodeMapFromUrl(linkReport);
        //keepMeLogged=keepMeLoggedStr!=null && keepMeLoggedStr.equalsIgnoreCase("true");
        boolean clear = false;
        String queryIDStr = queryEncodedMap.get("queryID");
        Integer filterID = null;
        if (queryIDStr != null) {
            filterID = Integer.decode(queryIDStr);
            if (filterID != null) {
                TQueryRepositoryBean queryRepositoryBean = (TQueryRepositoryBean) TreeFilterFacade.getInstance()
                        .getByKey(filterID);
                if (queryRepositoryBean != null) {
                    Integer queryType = queryRepositoryBean.getQueryType();
                    String filterExpression = FilterBL.getFilterExpression(queryRepositoryBean);
                    if (queryType != null) {
                        switch (queryType.intValue()) {
                        case QUERY_PURPOSE.TREE_FILTER:
                            HttpServletRequest request = null;
                            QNode extendedRootNode = TreeFilterReader.getInstance()
                                    .readQueryTree(filterExpression);
                            FilterUpperTO filterUpperTO = FilterUpperFromQNodeTransformer
                                    .getFilterSelectsFromTree(extendedRootNode, true, true, personBean, locale,
                                            true);
                            QNode rootNode = TreeFilterLoaderBL.getOriginalTree(extendedRootNode);
                            boolean hasListWithParameter = false;
                            if (FilterSelectsParametersUtil.containsParameter(filterUpperTO)) {
                                hasListWithParameter = true;
                                //replace the corresponding query parameters with corresponding request parameters
                                request = ServletActionContext.getRequest();
                                integerStringBean.setValue(Integer.valueOf(CONTAINS_PARAMETER_ORIGINAL));
                                try {
                                    //uncomment the "if" (and keepMeLogged initialization above) if we want to handle the case when
                                    //by executing a parameterized query the not all parameters are specified in as request parameters
                                    //and the user should be prompted to a new page to specify the parameters
                                    //this new page would mean a new tile (the track+ system menus should not be available)
                                    clear = true;

                                    FilterSelectsParametersUtil.replaceFilterSelectsParameters(filterUpperTO,
                                            request, personBean, locale, clear);
                                } catch (NotExistingBeanException e) {
                                    LOGGER.warn(e.getMessage());
                                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                                }
                            }
                            if ((FilterSelectsParametersUtil.containsParameter(filterUpperTO)
                                    || QNodeParametersUtil.containsParameter(rootNode))) {
                                //if there are parameters from an encoded query but with keepMeLogged
                                //and not all parameters were set with request parameters
                                //go to parameters specifying page
                                integerStringBean
                                        .setValue(Integer.valueOf(CONTAINS_PARAMETER_AFTER_REQUEST_REPLACE));
                            } else {
                                if (hasListWithParameter) {
                                    try {
                                        QNode extendedNode = TreeFilterSaverBL
                                                .createQNodeWithQueryListsTO(rootNode, filterUpperTO, locale);
                                        filterExpression = TreeFilterWriter.getInstance().toXML(extendedNode);
                                    } catch (Exception e) {
                                        String errorKey = e.getMessage();
                                        String errorMessage = LocalizeUtil
                                                .getLocalizedTextFromApplicationResources(errorKey, locale);
                                        LOGGER.warn("Transforming the instant query to expression failed with "
                                                + errorMessage);
                                    }
                                    integerStringBean.setLabel(filterExpression);
                                }
                            }
                            break;
                        case QUERY_PURPOSE.TQLPLUS_FILTER:
                        case QUERY_PURPOSE.TQL_FILTER:
                            return integerStringBean;
                        }
                    }
                }
            }
        }
    }
    return integerStringBean;
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.MetadataFileRedirect.java

/**
 * Sends a PUT command to create an empty file inside of HDFS.
 * It uses the URL from the original request to do so.
 * It will then consume the 307 response and write to the DataNode as well.
 * The data is "small" in hopes that this will be relatively quick.
 *
 * @throws IOException//w ww. j av a 2 s . c  o m
 * @throws ServletException
 */
public void sendCreate(String nnHostAddress, String userName) throws IOException, ServletException {
    // Set up HttpPut
    String[] nnHost = nnHostAddress.split(":");
    String metapath = replaceUri(request.getRequestURI(), OBJECT_FILE_NAME, META_FILE_NAME);

    PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
            "CREATE&overwrite=true", userName, metapath, PUT);
    Enumeration headers = request.getHeaderNames();
    Properties metadata = new Properties();

    // Set custom metadata headers
    while (headers.hasMoreElements()) {
        String key = (String) headers.nextElement();
        if (key.startsWith("x-amz-meta-")) {
            String value = request.getHeader(key);
            metadata.setProperty(key, value);
        }
    }
    // Include lastModified header
    SimpleDateFormat rc228 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    String modTime = rc228.format(Calendar.getInstance().getTime());
    metadata.setProperty("Last-Modified", modTime);

    // Store metadata headers into serialized HashMap in HttpPut entity.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    metadata.store(baos, null);

    httpPut.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
    httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE);

    httpClient.executeMethod(httpPut);
    LOG.debug("1st response: " + httpPut.getStatusLine().toString());

    boolean containsRedirect = (httpPut.getResponseHeader("Location") != null);

    if (!containsRedirect) {
        httpPut.releaseConnection();
        LOG.error("1st response did not contain redirect. " + "No metadata will be created.");
        return;
    }

    // Handle redirect header transition
    assert httpPut.getStatusCode() == 307;
    Header locationHeader = httpPut.getResponseHeader("Location");
    httpPut.setURI(new URI(locationHeader.getValue(), true));

    // Consume response and re-allocate connection for redirect
    httpPut.releaseConnection();
    httpClient.executeMethod(httpPut);

    LOG.debug("2nd response: " + httpPut.getStatusLine().toString());

    if (httpPut.getStatusCode() != 200) {
        LOG.debug("Response not 200: " + httpPut.getResponseBodyAsString());
        return;
    }

    assert httpPut.getStatusCode() == 200;
}