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:tema11.GUI.java

private void RootButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RootButton2MouseClicked

    TxRes.setText(" ");

    String p1 = new String();
    p1 = TxPol2.getText();//from   w  w w.java 2s.  co m
    int g1;
    int[] pol;
    double init;

    try {
        init = Double.parseDouble(TxInitVal.getText());
        g1 = Integer.parseInt(TxGrad2.getText());

        pol = PolinomOperations.parseString(p1, g1);

        Func f = new Func(pol);
        double x;
        x = PolinomOperations.findRoots(f, init);
        if (x != NaN) {
            String s = String.valueOf(x);
            //s = s.substring(0, 4);
            TxRes.setText(s);
        }
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(this, "Introduceti o valoare initiala numerica", "Polinom Error",
                JOptionPane.ERROR_MESSAGE);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "Polinom Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:tema11.GUI.java

private void RootButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RootButton1MouseClicked

    TxRes.setText(" ");

    String p1 = new String();
    p1 = TxPol1.getText();/* www  .ja  v  a2s .  c o  m*/
    int g1;
    int[] pol;
    double init;

    try {
        init = Double.parseDouble(TxInitVal.getText());

        g1 = Integer.parseInt(TxGrad1.getText());

        pol = PolinomOperations.parseString(p1, g1);

        Func f = new Func(pol);
        double x;
        x = PolinomOperations.findRoots(f, init);
        if (x != NaN) {
            String s = String.valueOf(x);
            // s = s.substring(0, 4);
            TxRes.setText(s);
        }
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(this, "Introduceti o valoare initiala numerica", "Polinom Error",
                JOptionPane.ERROR_MESSAGE);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "Polinom Error", JOptionPane.ERROR_MESSAGE);
    }

    // System.out.println(PolinomOperations.findValue(pol, init));
}

From source file:com.amazonaws.services.glacier.transfer.ArchiveTransferManager.java

/**
 * Downloads the job output for the specified job (which must be ready to
 * download already, and must be a complete archive retrieval, not a partial
 * range retrieval), into the specified file. This method will request
 * individual chunks of the data, one at a time, in order to handle any
 * transient errors along the way. You can also add an optional progress
 * listener for receiving updates about the download status.
 *
 * @param accountId//www .  j  a  v  a  2s.c  o  m
 *            The account ID containing the job output to download (or null
 *            if the current account shoudl be used).
 * @param vaultName
 *            The name of the vault from where the job was initiated.
 * @param jobId
 *            The ID of the job whose output is to be downloaded. This job
 *            must be a complete archive retrieval, not a range retrieval.
 * @param file
 *            The file to download the job output into.
 * @param progressListener
 *            The optional progress listener for receiving updates about the
 *            download status.
 */
public void downloadJobOutput(String accountId, String vaultName, String jobId, File file,
        ProgressListener progressListener) {
    long archiveSize = 0;
    long chunkSize = DEFAULT_DOWNLOAD_CHUNK_SIZE;
    long currentPosition = 0;
    long endPosition = 0;

    RandomAccessFile output = null;
    String customizedChunkSize = null;
    customizedChunkSize = System.getProperty("com.amazonaws.services.glacier.transfer.downloadChunkSizeInMB");

    DescribeJobResult describeJobResult = glacier
            .describeJob(new DescribeJobRequest(accountId, vaultName, jobId));
    archiveSize = describeJobResult.getArchiveSizeInBytes();

    if (customizedChunkSize != null) {
        try {
            chunkSize = Long.parseLong(customizedChunkSize) * 1024 * 1024;
        } catch (NumberFormatException e) {
            publishProgress(progressListener, ProgressEventType.TRANSFER_FAILED_EVENT);
            throw new AmazonClientException("Invalid chunk size: " + e.getMessage());
        }
        validateChunkSize(chunkSize);
    }

    try {
        output = new RandomAccessFile(file, "rw");
    } catch (FileNotFoundException e) {
        publishProgress(progressListener, ProgressEventType.TRANSFER_FAILED_EVENT);
        throw new AmazonClientException("Unable to open the output file " + file.getPath(), e);
    }

    try {
        publishProgress(progressListener, ProgressEventType.TRANSFER_STARTED_EVENT);
        while (currentPosition < archiveSize) {
            if (currentPosition + chunkSize > archiveSize) {
                endPosition = archiveSize - 1;
            } else {
                endPosition = currentPosition + chunkSize - 1;
            }

            // Download the chunk
            try {
                downloadOneChunk(accountId, vaultName, jobId, output, currentPosition, endPosition,
                        progressListener);
            } catch (Throwable t) {
                publishProgress(progressListener, ProgressEventType.TRANSFER_FAILED_EVENT);
                throw failure(t);
            }
            currentPosition += chunkSize;
        }
        publishProgress(progressListener, ProgressEventType.TRANSFER_COMPLETED_EVENT);
    } finally {
        closeQuietly(output, log);
    }
}

From source file:com.novartis.opensource.yada.adaptor.JDBCAdaptor.java

/**
* Sets a {@code ?i} parameter value mapped to the correct {@link java.sql.Types#INTEGER} JDBC setter.
* @param pstmt the statement in which to set the parameter values
* @param index the current parameter//  w w w  .ja  v a 2s . c o  m
* @param type the data type of the parameter (retained here for logging)
* @param val the value to set
* @throws SQLException when a parameter cannot be set, for instance if the data type is wrong or unsupported
* @since 5.1.0
*/
protected void setIntegerParameter(PreparedStatement pstmt, int index, char type, String val)
        throws SQLException {
    try {
        int ival = Integer.parseInt(val);
        pstmt.setInt(index, ival);
    } catch (NumberFormatException e) {
        l.warn("Error: " + e.getMessage() + " caused by " + e.getClass());
        l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                + "] to: null");
        pstmt.setNull(index, java.sql.Types.INTEGER);
    } catch (NullPointerException e) {
        l.warn("Error: " + e.getMessage() + " caused by " + e.getClass());
        l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                + "] to: null");
        pstmt.setNull(index, java.sql.Types.INTEGER);
    }
}

From source file:com.sfs.whichdoctor.search.http.RotationInputHandler.java

/**
 * Process the incoming HttpRequest for search parameters.
 *
 * @param request the request/*from   ww  w. j av  a 2 s  .co  m*/
 * @param user the user
 *
 * @return the search bean
 */
public final SearchBean process(final HttpServletRequest request, final UserBean user) {

    SearchBean search = rotationSqlHandler.initiate(user);

    RotationBean searchCriteria = (RotationBean) search.getSearchCriteria();
    RotationBean searchConstraints = (RotationBean) search.getSearchConstraints();

    String firstName = DataFilter.getHtml(request.getParameter("firstName"));
    String lastName = DataFilter.getHtml(request.getParameter("lastName"));
    String strIdentifier = DataFilter.getHtml(request.getParameter("identifier"));
    String strDivision = DataFilter.getHtml(request.getParameter("division"));
    String trainingType = DataFilter.getHtml(request.getParameter("trainingType"));

    String strGUIDList = DataFilter.getHtml(request.getParameter("guidList"));
    String strIncludeGUIDList = DataFilter.getHtml(request.getParameter("includeGUIDList"));
    final String strIdentifierList = DataFilter.getHtml(request.getParameter("identifierList"));

    String strTrainingTimeA = DataFilter.getHtml(request.getParameter("trainingTimeA"));
    String strTrainingTimeB = DataFilter.getHtml(request.getParameter("trainingTimeB"));

    String description = DataFilter.getHtml(request.getParameter("description"));
    String rotationType = DataFilter.getHtml(request.getParameter("rotationType"));
    String rotationTrainingClass = DataFilter.getHtml(request.getParameter("rotationTrainingClass"));
    String rotationTrainingType = DataFilter.getHtml(request.getParameter("rotationTrainingType"));
    String strTrainingOrganisation = DataFilter.getHtml(request.getParameter("specialtyTrainingOrganisation"));
    String strTrainingProgram = DataFilter.getHtml(request.getParameter("specialtyTrainingProgram"));
    String trainingProgramYearA = DataFilter.getHtml(request.getParameter("specialtyTrainingProgramYearA"));
    String trainingProgramYearB = DataFilter.getHtml(request.getParameter("specialtyTrainingProgramYearB"));
    String strSpecialtyStatus = DataFilter.getHtml(request.getParameter("specialtyStatus"));

    String strOrganisation = DataFilter.getHtml(request.getParameter("organisation"));
    String strCity = DataFilter.getHtml(request.getParameter("city"));
    String strCountry = DataFilter.getHtml(request.getParameter("country"));

    String strYearA = DataFilter.getHtml(request.getParameter("yearA"));
    String strYearB = DataFilter.getHtml(request.getParameter("yearB"));
    String strStartDateA = DataFilter.getHtml(request.getParameter("startDateA"));
    String strStartDateB = DataFilter.getHtml(request.getParameter("startDateB"));
    String strEndDateA = DataFilter.getHtml(request.getParameter("endDateA"));
    String strEndDateB = DataFilter.getHtml(request.getParameter("endDateB"));
    String strApproved = DataFilter.getHtml(request.getParameter("approved"));
    String strApprovedCondition = DataFilter.getHtml(request.getParameter("approvedCondition"));
    String strStatus = DataFilter.getHtml(request.getParameter("status"));
    String strStatusReason = DataFilter.getHtml(request.getParameter("statusReason"));

    String strAssessmentTrainingOrganisation = DataFilter
            .getHtml(request.getParameter("assessmentTrainingOrganisation"));
    String strAssessmentTrainingProgram = DataFilter.getHtml(request.getParameter("assessmentTrainingProgram"));
    String strCommitteeSpecialty = DataFilter.getHtml(request.getParameter("committeeSpecialty"));

    String strCreatedA = DataFilter.getHtml(request.getParameter("createdA"));
    String strCreatedB = DataFilter.getHtml(request.getParameter("createdB"));
    String strUpdatedA = DataFilter.getHtml(request.getParameter("updatedA"));
    String strUpdatedB = DataFilter.getHtml(request.getParameter("updatedB"));

    PersonBean personSearch = new PersonBean();
    PersonBean personConstraints = new PersonBean();

    boolean findPerson = false;
    /* Set first and last name requirements */
    if (StringUtils.isNotBlank(firstName)) {
        personSearch.setFirstName(firstName.trim());
        findPerson = true;
    }
    if (StringUtils.isNotBlank(lastName)) {
        personSearch.setLastName(lastName.trim());
        findPerson = true;
    }
    int identifier = 0;
    try {
        identifier = Integer.parseInt(strIdentifier);
    } catch (NumberFormatException nfe) {
        dataLogger.debug("Error parsing identifier: " + nfe.getMessage());
    }
    if (identifier > 0) {
        personSearch.setPersonIdentifier(identifier);
        findPerson = true;
    }

    if (StringUtils.isNotBlank(strGUIDList)) {
        // Parse the GUID list string into a collection of strings
        searchCriteria.setGUIDList(DataFilter.parseTextDataToCollection(strGUIDList));
    }

    if (StringUtils.isNotBlank(strIncludeGUIDList)) {
        // Parse the GUID list string into a collection of strings
        searchCriteria.setIncludeGUIDList(DataFilter.parseTextDataToCollection(strIncludeGUIDList));
    }

    if (StringUtils.isNotBlank(strIdentifierList)) {
        // Parse the identifier list string into a collection of strings
        searchCriteria.setIdentifierList(DataFilter.parseTextDataToCollection(strIdentifierList));
    }

    /* Tag searches */
    searchCriteria.setTags(this.setTagArray(request, user));

    /* Set membership details */
    MembershipBean mCriteria = this.membershipDAO.getDefaultInstance();
    MembershipBean mConstraints = this.membershipDAO.getDefaultInstance();
    boolean membershipSet = true;

    if (StringUtils.isNotBlank(strDivision)) {
        if (!StringUtils.equalsIgnoreCase(strDivision, "Null")) {
            ObjectTypeBean object = new ObjectTypeBean();
            object.setClassName(strDivision);
            mCriteria.setField("Division", object);
            membershipSet = true;
            findPerson = true;
        }
    }

    if (StringUtils.isNotBlank(trainingType)) {
        if (!StringUtils.equalsIgnoreCase(trainingType, "Null")) {
            ObjectTypeBean object = new ObjectTypeBean();
            object.setClassName(trainingType);
            mCriteria.setField("Training Type", object);
            membershipSet = true;
            findPerson = true;
        }
    }

    if (membershipSet) {
        Collection<MembershipBean> membershipA = new ArrayList<MembershipBean>();
        Collection<MembershipBean> membershipB = new ArrayList<MembershipBean>();
        membershipA.add(mCriteria);
        membershipB.add(mConstraints);
        personSearch.setMembershipDetails(membershipA);
        personConstraints.setMembershipDetails(membershipB);
    }

    /* Set training time */
    if (strTrainingTimeA != null) {
        double trainingTime = 0;
        try {
            trainingTime = Double.parseDouble(strTrainingTimeA) / 100;
        } catch (NumberFormatException nfe) {
            // Error parsing training time A
            trainingTime = 0;
        }
        searchCriteria.setTrainingTime(trainingTime);
    }
    if (StringUtils.isNotBlank(strTrainingTimeB)) {
        double trainingTime = 0;
        try {
            trainingTime = Double.parseDouble(strTrainingTimeB) / 100;
        } catch (NumberFormatException nfe) {
            // Error parsing training time A
            trainingTime = 0;
        }
        if (StringUtils.equalsIgnoreCase(strTrainingTimeB, "+")) {
            /* All training times above trainingTimeA requested */
            trainingTime = 1.0;
        }
        if (StringUtils.equalsIgnoreCase(strTrainingTimeB, "-")) {
            /* All training times below trainingTimeA requested */
            trainingTime = 0.01;
        }
        searchConstraints.setTrainingTime(trainingTime);
    }

    /* Check if specialty details were set */
    boolean specialty = false;
    SpecialtyBean specialtyCriteria = new SpecialtyBean();
    SpecialtyBean specialtyConstraints = new SpecialtyBean();

    if (StringUtils.isNotBlank(strTrainingOrganisation)
            && !StringUtils.equals(strTrainingOrganisation, "Null")) {
        specialtyCriteria.setTrainingOrganisation(strTrainingOrganisation);

        if (StringUtils.isNotBlank(strTrainingProgram) && !StringUtils.equals(strTrainingProgram, "Any")) {
            specialtyCriteria.setTrainingProgram(strTrainingProgram);
        }
        specialty = true;
    }

    if (StringUtils.isNotBlank(trainingProgramYearA)) {
        int trainingProgramYear = 0;
        try {
            trainingProgramYear = Integer.parseInt(trainingProgramYearA);
        } catch (NumberFormatException nfe) {
            dataLogger.debug("Error parsing training year A: " + nfe.getMessage());
        }
        if (StringUtils.equalsIgnoreCase(trainingProgramYearA, "+")) {
            trainingProgramYear = MAXIMUM_YEAR;
        }
        if (StringUtils.equalsIgnoreCase(trainingProgramYearA, "-")) {
            trainingProgramYear = MINIMUM_YEAR;
        }
        specialtyCriteria.setTrainingProgramYear(trainingProgramYear);
    }
    if (StringUtils.isNotBlank(trainingProgramYearB)) {
        int trainingProgramYear = 0;
        try {
            trainingProgramYear = Integer.parseInt(trainingProgramYearB);
        } catch (NumberFormatException nfe) {
            dataLogger.debug("Error parsing training program B: " + nfe.getMessage());
        }
        if (StringUtils.equalsIgnoreCase(trainingProgramYearB, "+")) {
            trainingProgramYear = MAXIMUM_YEAR;
        }
        if (StringUtils.equalsIgnoreCase(trainingProgramYearB, "-")) {
            trainingProgramYear = MINIMUM_YEAR;
        }
        specialtyConstraints.setTrainingProgramYear(trainingProgramYear);
    }

    if (strSpecialtyStatus != null) {
        if (strSpecialtyStatus.compareTo("Null") != 0) {
            specialtyCriteria.setStatus(strSpecialtyStatus);
            specialty = true;
        }
    }
    if (specialty) {
        ArrayList<SpecialtyBean> spCriteria = new ArrayList<SpecialtyBean>();
        ArrayList<SpecialtyBean> spConstraints = new ArrayList<SpecialtyBean>();
        spCriteria.add(specialtyCriteria);
        spConstraints.add(specialtyConstraints);

        personSearch.setSpecialtyList(spCriteria);
        personConstraints.setSpecialtyList(spConstraints);

        findPerson = true;
    }

    /* Determine if Member criteria have been set */
    if (findPerson) {
        searchCriteria.setPersonSearch(personSearch);
        searchConstraints.setPersonSearch(personConstraints);
    }

    /* Set the organisation details */
    OrganisationBean organisationCriteria = new OrganisationBean();
    AddressBean addressCriteria = new AddressBean();
    boolean organisation = false;
    boolean address = false;

    if (StringUtils.isNotBlank(strOrganisation)) {
        organisationCriteria.setName(strOrganisation);
        organisation = true;
    }
    if (StringUtils.isNotBlank(strCity)) {
        addressCriteria.setAddressField(strCity);
        organisation = true;
        address = true;
    }
    if (StringUtils.isNotBlank(strCountry)) {
        addressCriteria.setCountry(strCountry);
        organisation = true;
        address = true;
    }

    if (organisation) {
        if (address) {
            Collection<AddressBean> addresses = new ArrayList<AddressBean>();
            addresses.add(addressCriteria);
            organisationCriteria.setAddress(addresses);
        }
        searchCriteria.setOrganisation1(organisationCriteria);
    }

    if (StringUtils.isNotBlank(description)) {
        searchCriteria.setDescription(description);
    }

    if (StringUtils.isNotBlank(rotationType) && !StringUtils.equals(rotationType, "Null")) {
        searchCriteria.setRotationType(rotationType);
    }

    if (StringUtils.isNotBlank(rotationTrainingClass) && !StringUtils.equals(rotationTrainingClass, "Null")) {
        searchCriteria.setTrainingClass(rotationTrainingClass);
    }

    if (StringUtils.isNotBlank(rotationTrainingType) && !StringUtils.equals(rotationTrainingType, "Any")) {
        searchCriteria.setTrainingType(rotationTrainingType);
    }

    if (StringUtils.isNotBlank(strYearA)) {
        int year = 0;
        try {
            year = Integer.parseInt(strYearA);
        } catch (NumberFormatException nfe) {
            dataLogger.debug("Error parsing year A: " + nfe.getMessage());
        }
        if (StringUtils.equalsIgnoreCase(strYearA, "+")) {
            year = MAXIMUM_YEAR;
        }
        if (StringUtils.equalsIgnoreCase(strYearA, "-")) {
            year = MINIMUM_YEAR;
        }
        searchCriteria.setYear(year);
    }
    if (StringUtils.isNotBlank(strYearB)) {
        int year = 0;
        try {
            year = Integer.parseInt(strYearB);
        } catch (NumberFormatException nfe) {
            dataLogger.debug("Error parsing year B: " + nfe.getMessage());
        }
        if (StringUtils.equalsIgnoreCase(strYearB, "+")) {
            year = MAXIMUM_YEAR;
        }
        if (StringUtils.equalsIgnoreCase(strYearB, "-")) {
            year = MINIMUM_YEAR;
        }
        searchConstraints.setYear(year);
    }

    /* Set StartDate */
    if (StringUtils.isNotBlank(strStartDateA)) {
        searchCriteria.setStartDate(DataFilter.parseDate(strStartDateA, false));
    }
    if (StringUtils.isNotBlank(strStartDateB)) {
        searchConstraints.setStartDate(DataFilter.parseDate(strStartDateB, false));

        if (StringUtils.equalsIgnoreCase(strStartDateB, "+")) {
            /* All dates above Date A requested */
            searchConstraints.setStartDate(getMaximumDate());
        }
        if (StringUtils.equalsIgnoreCase(strStartDateB, "-")) {
            /* Add dates below Date A requested */
            searchConstraints.setStartDate(getMinimumDate());
        }
    }

    /* Set EndDate */
    if (StringUtils.isNotBlank(strEndDateA)) {
        searchCriteria.setEndDate(DataFilter.parseDate(strEndDateA, false));
    }
    if (StringUtils.isNotBlank(strEndDateB)) {
        searchConstraints.setEndDate(DataFilter.parseDate(strEndDateB, false));

        if (StringUtils.equalsIgnoreCase(strEndDateB, "+")) {
            /* All dates above Date A requested */
            searchConstraints.setEndDate(getMaximumDate());
        }
        if (StringUtils.equalsIgnoreCase(strEndDateB, "-")) {
            /* Add dates below Date A requested */
            searchConstraints.setEndDate(getMinimumDate());
        }
    }

    boolean assessmentRequested = false;
    AssessmentBean assessment = new AssessmentBean();

    if (StringUtils.isNotBlank(strAssessmentTrainingOrganisation)
            && !StringUtils.equals(strAssessmentTrainingOrganisation, "Null")) {
        assessment.setTrainingOrganisation(strAssessmentTrainingOrganisation);

        if (StringUtils.isNotBlank(strAssessmentTrainingProgram)
                && !StringUtils.equals(strAssessmentTrainingProgram, "Any")) {
            assessment.setTrainingProgram(strAssessmentTrainingProgram);
        }
        assessmentRequested = true;
    }

    if (StringUtils.isNotBlank(strCommitteeSpecialty) && !StringUtils.equals(strCommitteeSpecialty, "Null")) {
        assessment.setCommitteeSpecialty(strCommitteeSpecialty);
        assessmentRequested = true;
    }

    /* Set Rotation Approved */
    if (StringUtils.isNotBlank(strApproved) && !StringUtils.equals(strApproved, "Null")) {
        assessment.setApproved(strApproved);
        assessmentRequested = true;
    }

    /* Set Rotation Approved Condition */
    if (StringUtils.isNotBlank(strApprovedCondition) && !StringUtils.equals(strApprovedCondition, "Any")) {
        assessment.setApprovedCondition(strApprovedCondition);
        assessmentRequested = true;
    }

    /* Set Rotation Status */
    if (StringUtils.isNotBlank(strStatus) && !StringUtils.equals(strStatus, "Null")) {
        assessment.setStatus(strStatus);
        assessmentRequested = true;
    }
    /* Set Rotation Status Reason */
    if (StringUtils.isNotBlank(strStatusReason) && !StringUtils.equals(strStatusReason, "Any")) {
        assessment.setStatusReason(strStatusReason);
        assessmentRequested = true;
    }

    if (assessmentRequested) {
        /* Add the assessment bean to the rotation */
        ArrayList<AssessmentBean> assessments = new ArrayList<AssessmentBean>();
        assessments.add(assessment);
        searchCriteria.setAssessment(assessments);
    }

    if (StringUtils.isNotBlank(strCreatedA)) {
        searchCriteria.setCreatedDate(DataFilter.parseDate(strCreatedA, false));
    }
    if (StringUtils.isNotBlank(strCreatedB)) {
        searchConstraints.setCreatedDate(DataFilter.parseDate(strCreatedB, false));

        if (StringUtils.equalsIgnoreCase(strCreatedB, "+")) {
            /* All dates above Date A requested */
            searchConstraints.setCreatedDate(getMaximumDate());
        }
        if (StringUtils.equalsIgnoreCase(strCreatedB, "-")) {
            /* Add dates below Date A requested */
            searchConstraints.setCreatedDate(getMinimumDate());
        }
    }
    if (StringUtils.isNotBlank(strUpdatedA)) {
        searchCriteria.setModifiedDate(DataFilter.parseDate(strUpdatedA, false));
    }
    if (StringUtils.isNotBlank(strUpdatedB)) {
        searchConstraints.setModifiedDate(DataFilter.parseDate(strUpdatedB, false));

        if (StringUtils.equalsIgnoreCase(strUpdatedB, "+")) {
            /* All dates above Date A requested */
            searchConstraints.setModifiedDate(getMaximumDate());
        }
        if (StringUtils.equalsIgnoreCase(strUpdatedB, "-")) {
            /* Add dates below Date A requested */
            searchConstraints.setModifiedDate(getMinimumDate());
        }
    }

    search.setSearchCriteria(searchCriteria);
    search.setSearchConstraints(searchConstraints);

    return search;
}

From source file:gsn.http.restapi.RequestHandler.java

public RestResponse getMeasurementsForSensorField(User user, String sensor, String field, String from,
        String to, String size) {
    RestResponse restResponse = userHasAccessToVirtualSensor(user, sensor);
    if (restResponse != null) { //error occured
        return restResponse;
    }//w  w  w.j a va 2  s.  c  o  m

    restResponse = new RestResponse();

    String filename = String.format(stringConstantsProperties.getProperty("FILENAME_SENSOR_FIELD"), sensor,
            field, datetime);
    setRestResponseParams(restResponse, filename);

    long fromAsLong = 0;
    long toAsLong = 0;
    int window = -1;
    try {
        fromAsLong = new java.text.SimpleDateFormat(stringConstantsProperties.getProperty("ISO_FORMAT"))
                .parse(from).getTime();
        toAsLong = new java.text.SimpleDateFormat(stringConstantsProperties.getProperty("ISO_FORMAT")).parse(to)
                .getTime();
        if (size != null)
            window = Integer.parseInt(size);
    } catch (NumberFormatException e) {
        logger.error(e.getMessage(), e);
        restResponse = errorResponse(ErrorType.MALFORMED_SIZE, user, sensor);
        return restResponse;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        restResponse = errorResponse(ErrorType.MALFORMED_DATE_FROM_TO, user, sensor);
        return restResponse;
    }

    VSensorConfig sensorConfig = Mappings.getConfig(sensor);
    VirtualSensor sensorObj = new VirtualSensor();

    sensorObj.setMetadata(createHeaderMap(sensorConfig));
    sensorObj.appendField(new DataField(stringConstantsProperties.getProperty("TIME"), "Time"));
    sensorObj.appendField(new DataField(stringConstantsProperties.getProperty("TIMESTAMP"), "BigInt"));
    for (DataField df : sensorConfig.getOutputStructure()) {
        if (df.getName().equals(field)) {
            sensorObj.appendField(df);
            break;
        }
    }

    ArrayList<Vector<Double>> elements = new ArrayList<Vector<Double>>();
    Vector<Long> timestamps = new Vector<Long>();

    ArrayList<String> fieldList = new ArrayList<String>();
    fieldList.add(field);

    boolean errorFlag = !getData(sensor, fieldList, fromAsLong, toAsLong, window, elements, timestamps);

    if (errorFlag) {
        return errorResponse(ErrorType.ERROR_IN_REQUEST, user, sensor);
    }

    sensorObj.setValues(elements, timestamps);

    List<VirtualSensor> listSens = new LinkedList<VirtualSensor>();
    listSens.add(sensorObj);

    restResponse.setResponse(VirtualSensor.generateFileContent(listSens, format));

    return restResponse;
}

From source file:uk.co.markfrimston.tasktree.TaskTree.java

public void loadConfig() throws Exception {
    try {//from w  w  w  .j a va  2 s.c om
        File file = new File(filePath + CONFIG_FILENAME);
        if (!file.exists()) {
            saveConfig();
        }
        DocumentBuilder builder = builderFact.newDocumentBuilder();
        Document doc = builder.parse(file);
        Element root = doc.getDocumentElement();
        if (root == null || !root.getNodeName().equals("config")) {
            throw new Exception("Missing root element \"config\"");
        }
        Iterator<Element> i = getElementChildren(root);

        loadUrl = null;
        saveUrl = null;
        mergeCommand = null;
        lastSyncTime = 0L;
        unsynchedChanges = true;

        while (i.hasNext()) {
            Element el = i.next();

            if (el.getNodeName().equals("load-url")) {
                loadUrl = el.getTextContent();
                if (loadUrl != null && loadUrl.length() == 0) {
                    loadUrl = null;
                }
            } else if (el.getNodeName().equals("save-url")) {
                saveUrl = el.getTextContent();
                if (saveUrl != null && saveUrl.length() == 0) {
                    saveUrl = null;
                }
            } else if (el.getNodeName().equals("merge-command")) {
                mergeCommand = el.getTextContent();
                if (mergeCommand != null && mergeCommand.length() == 0) {
                    mergeCommand = null;
                }
            } else if (el.getNodeName().equals("last-sync")) {
                try {
                    lastSyncTime = Long.parseLong(el.getTextContent());
                } catch (NumberFormatException e) {
                }
            } else if (el.getNodeName().equals("unsynched-changes")) {
                unsynchedChanges = Boolean.parseBoolean(el.getTextContent());
            }
        }
    } catch (Exception e) {
        throw new Exception("Failed to load config file: " + e.getClass().getName() + " - " + e.getMessage());
    }
}

From source file:org.duniter.core.client.service.bma.BlockchainRemoteServiceImpl.java

private int[] getBlocksWithUD(String currencyId) {
    log.debug("Getting blocks with UD");

    String json = executeRequest(currencyId, URL_BLOCK_WITH_UD, String.class);

    int startIndex = json.indexOf("[");
    int endIndex = json.lastIndexOf(']');

    if (startIndex == -1 || endIndex == -1) {
        return null;
    }// w  ww  . j  a va2  s. co m

    String blockNumbersStr = json.substring(startIndex + 1, endIndex).trim();

    if (StringUtils.isBlank(blockNumbersStr)) {
        return null;
    }

    String[] blockNumbers = blockNumbersStr.split(",");
    int[] result = new int[blockNumbers.length];
    try {
        int i = 0;
        for (String blockNumber : blockNumbers) {
            result[i++] = Integer.parseInt(blockNumber.trim());
        }
    } catch (NumberFormatException e) {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Bad format of the response '%s'.", URL_BLOCK_WITH_UD));
        }
        throw new TechnicalException("Unable to read block with UD numbers: " + e.getMessage(), e);
    }

    return result;
}

From source file:net.iponweb.hadoop.streaming.parquet.TextRecordWriterWrapper.java

@Override
public void write(Text key, Text value) throws IOException {

    Group grp = factory.newGroup();

    String[] strK = key.toString().split(TAB, -1);
    String[] strV = value == null ? new String[0] : value.toString().split(TAB, -1);
    String kv_combined[] = (String[]) ArrayUtils.addAll(strK, strV);

    Iterator<PathAction> ai = recorder.iterator();

    Stack<Group> groupStack = new Stack<>();
    groupStack.push(grp);/*w  w  w.  j av  a 2 s.c o  m*/
    int i = 0;

    try {
        while (ai.hasNext()) {

            PathAction a = ai.next();
            switch (a.getAction()) {
            case GROUPEND:
                grp = groupStack.pop();
                break;

            case GROUPSTART:
                groupStack.push(grp);
                grp = grp.addGroup(a.getName());
                break;

            case FIELD:
                String s = null;
                PrimitiveType.PrimitiveTypeName primType = a.getType();
                String colName = a.getName();

                if (i < kv_combined.length)
                    s = kv_combined[i++];

                if (s == null) {
                    if (a.getRepetition() == Type.Repetition.OPTIONAL) {
                        i++;
                        continue;
                    }
                    s = primType == PrimitiveType.PrimitiveTypeName.BINARY ? "" : "0";
                }

                // If we have 'repeated' field, assume that we should expect JSON-encoded array
                // Convert array and append all values
                int repetition = 1;
                boolean repeated = false;
                ArrayList<String> s_vals = null;
                if (a.getRepetition() == Type.Repetition.REPEATED) {
                    repeated = true;
                    s_vals = new ArrayList<>();
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode node = mapper.readTree(s);
                    Iterator<JsonNode> itr = node.iterator();
                    repetition = 0;
                    while (itr.hasNext()) {

                        String o;
                        switch (primType) {
                        case BINARY:
                            o = itr.next().getTextValue(); // No array-of-objects!
                            break;
                        case BOOLEAN:
                            o = String.valueOf(itr.next().getBooleanValue());
                            break;
                        default:
                            o = String.valueOf(itr.next().getNumberValue());
                        }

                        s_vals.add(o);
                        repetition++;
                    }
                }

                for (int j = 0; j < repetition; j++) {

                    if (repeated)
                        // extract new s
                        s = s_vals.get(j);

                    try {
                        switch (primType) {

                        case INT32:
                            grp.append(colName, new Double(Double.parseDouble(s)).intValue());
                            break;
                        case INT64:
                        case INT96:
                            grp.append(colName, new Double(Double.parseDouble(s)).longValue());
                            break;
                        case DOUBLE:
                            grp.append(colName, Double.parseDouble(s));
                            break;
                        case FLOAT:
                            grp.append(colName, Float.parseFloat(s));
                            break;
                        case BOOLEAN:
                            grp.append(colName, s.equalsIgnoreCase("true") || s.equals("1"));
                            break;
                        case BINARY:
                            grp.append(colName, Binary.fromString(s));
                            break;
                        default:
                            throw new RuntimeException("Can't handle type " + primType);
                        }
                    } catch (NumberFormatException e) {

                        grp.append(colName, 0);
                    }
                }
            }
        }

        realWriter.write(null, (SimpleGroup) grp);

    } catch (InterruptedException e) {
        Thread.interrupted();
        throw new IOException(e);
    } catch (Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(out));
        throw new RuntimeException("Failed on record " + grp + ", schema=" + schema + ", path action="
                + recorder + " exception = " + e.getClass() + ", msg=" + e.getMessage() + ", cause="
                + e.getCause() + ", trace=" + out.toString());
    }

}

From source file:gsn.http.restapi.RequestHandler.java

public RestResponse getPreviewMeasurementsForSensorField(User user, String sensor, String field, String from,
        String to, String size) {
    /* open//from   www.jav a  2s.c  om
    RestResponse restResponse = userHasAccessToVirtualSensor(user, sensor);
    if (restResponse != null) { //error occured
    return restResponse;
    }
    */
    RestResponse restResponse = new RestResponse();

    String filename = String.format(stringConstantsProperties.getProperty("FILENAME_PREVIEW_SENSOR_FIELD"),
            sensor, field, datetime);
    setRestResponseParams(restResponse, filename);

    List<Vector<Double>> elements = new ArrayList<Vector<Double>>();
    Vector<Long> timestamps = new Vector<Long>();

    boolean errorFlag = false;

    long n = -1;
    long fromAsLong = -1;
    long toAsLong = -1;

    if (size == null)
        n = DEFAULT_PREVIEW_SIZE;
    else
        try {
            n = Long.parseLong(size);
        } catch (NumberFormatException e) {
            logger.error(e.getMessage(), e);
        }

    if (n < 1)
        n = DEFAULT_PREVIEW_SIZE; // size should be strictly larger than 0

    if (from == null) { // no lower bound provided
        fromAsLong = getMinTimestampForSensorField(sensor, field);
    } else
        try {
            fromAsLong = new java.text.SimpleDateFormat(stringConstantsProperties.getProperty("ISO_FORMAT"))
                    .parse(from).getTime();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            errorFlag = true;
        }

    if (to == null) { // no lower bound provided
        toAsLong = getMaxTimestampForSensorField(sensor, field);
    } else
        try {
            toAsLong = new java.text.SimpleDateFormat(stringConstantsProperties.getProperty("ISO_FORMAT"))
                    .parse(to).getTime();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            errorFlag = true;
        }

    if (errorFlag) {
        return errorResponse(ErrorType.MALFORMED_DATE_FROM_TO, user, sensor);
    }

    errorFlag = !getDataPreview(sensor, field, fromAsLong, toAsLong, elements, timestamps, n);

    if (errorFlag) {
        return errorResponse(ErrorType.ERROR_IN_REQUEST, user, sensor);
    }

    VSensorConfig sensorConfig = Mappings.getConfig(sensor);
    VirtualSensor sensorObj = new VirtualSensor();

    sensorObj.setMetadata(createHeaderMap(sensorConfig));
    sensorObj.appendField(new DataField(stringConstantsProperties.getProperty("TIME"), "Time"));
    sensorObj.appendField(new DataField(stringConstantsProperties.getProperty("TIMESTAMP"), "BigInt"));
    for (DataField df : sensorConfig.getOutputStructure()) {
        if (df.getName().equals(field)) {
            sensorObj.appendField(df);
            break;
        }
    }

    sensorObj.setValues(elements, timestamps);

    List<VirtualSensor> listSens = new LinkedList<VirtualSensor>();
    listSens.add(sensorObj);

    restResponse.setResponse(VirtualSensor.generateFileContent(listSens, format));

    return restResponse;
}