Example usage for java.lang Long decode

List of usage examples for java.lang Long decode

Introduction

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

Prototype

public static Long decode(String nm) throws NumberFormatException 

Source Link

Document

Decodes a String into a Long .

Usage

From source file:org.jboss.dashboard.ui.config.components.sections.SectionsPropertiesHandler.java

/**
 * Duplicates Section in workspace//from   w  w  w .ja v a 2  s.c o  m
 */
public void actionDuplicateSection(final CommandRequest request) {
    try {
        if (action != null && action.equals(ACTION_SAVE)) {
            final Long selectedSectionId = Long.decode(getSelectedSectionId());
            if (selectedSectionId != null && selectedSectionId.longValue() != 0L) {
                HibernateTxFragment txFragment = new HibernateTxFragment() {
                    protected void txFragment(Session session) throws Exception {
                        log.debug("Duplicating section " + selectedSectionId.toString());
                        WorkspaceImpl workspace = (WorkspaceImpl) getWorkspace();
                        Section section = null;
                        section = workspace.getSection(selectedSectionId);
                        if (section != null) {
                            // Security check.
                            WorkspacePermission sectionPerm = WorkspacePermission.newInstance(workspace,
                                    WorkspacePermission.ACTION_CREATE_PAGE);
                            getUserStatus().checkPermission(sectionPerm);

                            // Duplicate
                            SectionCopyOption sco = getCopyOptions(request);
                            Section sectionCopy = getCopyManager().copy(section, workspace, sco);
                            Map title = section.getTitle();
                            for (Iterator it = title.keySet().iterator(); it.hasNext();) {
                                String lang = (String) it.next();
                                String desc = (String) title.get(lang);
                                String prefix = "Copia de ";
                                prefix = lang.equals("en") ? "Copy of " : prefix;
                                sectionCopy.setTitle(prefix + desc, lang);
                            }
                            UIServices.lookup().getSectionsManager().store(sectionCopy);
                        }
                    }
                };

                txFragment.execute();
                getMessagesComponentHandler().addMessage("ui.alert.sectionCopy.OK");
            }
        }
        this.setDuplicateSection(Boolean.FALSE);
        this.setCreateSection(Boolean.FALSE);
        this.setSelectedSectionId(null);
        defaultValues();
    } catch (Exception e) {
        log.error("Error: " + e.getMessage());
        getMessagesComponentHandler().clearAll();
        getMessagesComponentHandler().addError("ui.alert.sectionCopy.KO");
    }
}

From source file:com.android.tools.lint.checks.GradleDetector.java

protected void checkOctal(@NonNull Context context, @NonNull String value, @NonNull Object cookie) {
    if (value.length() >= 2 && value.charAt(0) == '0'
            && (value.length() > 2 || value.charAt(1) >= '8' && isInteger(value))
            && context.isEnabled(ACCIDENTAL_OCTAL)) {
        String message = "The leading 0 turns this number into octal which is probably "
                + "not what was intended";
        try {// www  .j a  v a  2s .  com
            long numericValue = Long.decode(value);
            message += " (interpreted as " + numericValue + ")";
        } catch (NumberFormatException nufe) {
            message += " (and it is not a valid octal number)";
        }
        report(context, cookie, ACCIDENTAL_OCTAL, message);
    }
}

From source file:jenkins.util.SystemProperties.java

/**
  * Determines the integer value of the system property with the
  * specified name, or a default value./*from ww w.j a va 2  s .  com*/
  * 
  * This behaves just like <code>Long.getLong(String,Long)</code>, except that it
  * also consults the <code>ServletContext</code>'s "init" parameters. If neither exist,
  * return the default value. 
  * 
  * @param   name property name.
  * @param   def   a default value.
  * @param   logLevel the level of the log if the provided system property name cannot be decoded into Long.
  * @return  the {@code Long} value of the property.
  *          If the property is missing, return the default value.
  *          Result may be {@code null} only if the default value is {@code null}.
  */
public static Long getLong(String name, Long def, Level logLevel) {
    String v = getString(name);

    if (v != null) {
        try {
            return Long.decode(v);
        } catch (NumberFormatException e) {
            // Ignore, fallback to default
            if (LOGGER.isLoggable(logLevel)) {
                LOGGER.log(logLevel, "Property. Value is not long: {0} => {1}", new Object[] { name, v });
            }
        }
    }
    return def;
}

From source file:com.emergya.persistenceGeo.web.RestFoldersAdminController.java

/**
 * Load folder tree by user or group styled
 * //www.j  a  v  a2 s.  c  om
 * @param type
 *            user or group, default group
 * @param style
 *            tree or string, default string
 * @param userOrGroup
 *            id group or username
 * 
 * @see FoldersUtils
 * @see FolderStyle
 * 
 * @return List of user or group folders parsed with style
 */
@RequestMapping(value = "/persistenceGeo/loadFolders/{type}/{style}/{userOrGroup}", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody Map<String, Object> loadFolders(@PathVariable String type, @PathVariable String style,
        @PathVariable String userOrGroup) {
    Map<String, Object> result = new HashMap<String, Object>();
    List<FolderDto> folders = null;
    try {
        /*
         * //TODO: Secure with logged user String username = ((UserDetails)
         * SecurityContextHolder.getContext()
         * .getAuthentication().getPrincipal()).getUsername();
         */
        FolderDto rootFolder;
        folders = new LinkedList<FolderDto>();
        if (LOAD_FOLDERS_BY_USER.equals(type)) {
            UserDto user = userAdminService.obtenerUsuario(userOrGroup);
            rootFolder = foldersAdminService.getRootFolder(user.getId());
        } else {
            rootFolder = foldersAdminService.getRootGroupFolder(Long.decode(userOrGroup));
        }
        if (LOAD_FOLDERS_STYLE_TREE.equals(style)) {
            FoldersUtils.getFolderTree(rootFolder, folders, FolderStyle.TREE, null);
        } else {
            FoldersUtils.getFolderTree(rootFolder, folders);
        }
        result.put(SUCCESS, true);
    } catch (Exception e) {
        e.printStackTrace();
        result.put(SUCCESS, false);
    }

    result.put(RESULTS, folders != null ? folders.size() : 0);
    result.put(ROOT, folders);

    return result;
}

From source file:com.emergya.persistenceGeo.web.RestLayersAdminController.java

/**
 * This method loads layers.json related with a folder
 * //from  w  ww.j  a  va  2  s. co m
 * @param username
 * 
 * @return JSON file with layers
 */
@RequestMapping(value = "/persistenceGeo/moveLayerTo", method = RequestMethod.POST, produces = {
        MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody Map<String, Object> moveLayerTo(@RequestParam("layerId") String layerId,
        @RequestParam("toFolder") String toFolder,
        @RequestParam(value = "toOrder", required = false) String toOrder) {
    Map<String, Object> result = new HashMap<String, Object>();
    LayerDto layer = null;
    try {
        /*
        //TODO: Secure with logged user
        String username = ((UserDetails) SecurityContextHolder.getContext()
              .getAuthentication().getPrincipal()).getUsername(); 
         */
        Long idLayer = Long.decode(layerId);
        layer = (LayerDto) layerAdminService.getById(idLayer);
        layer.setFolderId(Long.decode(toFolder));

        if (toOrder != null) {
            Map<String, String> properties = layer.getProperties() != null ? layer.getProperties()
                    : new HashMap<String, String>();
            properties.put("order", toOrder);
            layer.setProperties(properties);
        }

        layer = (LayerDto) layerAdminService.update(layer);

        //Must already loaded in RestLayerAdminController
        if (layer.getId() != null && layer.getData() != null) {
            layer.setData(null);
            layer.setServer_resource("rest/persistenceGeo/getLayerResource/" + layer.getId());
        }

        result.put(SUCCESS, true);
    } catch (Exception e) {
        e.printStackTrace();
        result.put(SUCCESS, false);
    }

    result.put(RESULTS, layer != null ? 1 : 0);
    result.put(ROOT, layer);

    return result;
}

From source file:com.emergya.persistenceGeo.web.RestFoldersAdminController.java

/**
 * Remove a folder and her children//w  w  w  .  j av a2 s .c o m
 * 
 * @param folderId
 * 
 * @return JSON file with success
 */
@RequestMapping(value = "/persistenceGeo/deleteFolder", produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody Map<String, Object> deleteFolder(@RequestParam("folderId") String folderId) {
    Map<String, Object> result = new HashMap<String, Object>();
    FolderDto folder = null;
    try {
        /*
         * //TODO: Secure with logged user String username = ((UserDetails)
         * SecurityContextHolder.getContext()
         * .getAuthentication().getPrincipal()).getUsername();
         */
        Long idFolder = Long.decode(folderId);
        folder = (FolderDto) foldersAdminService.getById(idFolder);
        foldersAdminService.delete(folder);
        result.put(SUCCESS, true);
        result.put(RESULTS, 1);
        result.put(ROOT, "");
    } catch (Exception e) {
        e.printStackTrace();
        result.put(SUCCESS, false);
        result.put(RESULTS, 0);
        result.put(ROOT, null);
    }

    return result;
}

From source file:AltiConsole.AltiConsoleMainScreen.java

public AltiConfigData retrieveAltiConfig() {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    AltiConfigData Alticonfig = null;//from  w ww . j a va2  s .c o m
    Alticonfig = new AltiConfigData();

    if (Serial.getConnected() == false) {
        boolean ret = false;
        ret = ConnectToAlti();
        if (!ret) {
            System.out.println("retrieveAltiConfig - Data retrieval timed out1\n");
            this.setCursor(Cursor.getDefaultCursor());
            return null;
        }
    }
    Serial.clearInput();
    //Serial.DataReady = false;
    Serial.setDataReady(false);
    // send command to switch off the continuity test
    Serial.writeData("b;\n");
    System.out.println("b;\n");
    long timeOut = 10000;
    if (UserPref.getRetrievalTimeout() != null && UserPref.getRetrievalTimeout() != "")
        timeOut = Long.decode(UserPref.getRetrievalTimeout());
    long startTime = System.currentTimeMillis();
    //while (!Serial.getDataReady()) {
    while (true) {
        long currentTime = System.currentTimeMillis();
        if (Serial.getDataReady())
            break;
        if ((currentTime - startTime) > timeOut) {
            // This is some sort of data retrieval timeout
            System.out.println("retrieveAltiConfig - Data retrieval timed out2\n");
            if (Serial.getDataReady())
                System.out.println("Data is true\n");
            else
                System.out.println("Data is false\n");
            JOptionPane.showMessageDialog(null, trans.get("AltiConsoleMainScreen.dataTimeOut") + "0",
                    trans.get("AltiConsoleMainScreen.ConnectionError"), JOptionPane.ERROR_MESSAGE);
            this.setCursor(Cursor.getDefaultCursor());

            return null;
        }
    }
    if (Serial.AltiCfg != null) {
        System.out.println("Reading altimeter config\n");
        System.out.println(Serial.AltiCfg.getUnits() + "\n");
        Alticonfig = Serial.AltiCfg;

    }
    this.setCursor(Cursor.getDefaultCursor());
    return Alticonfig;
}

From source file:org.soaplab.clients.BatchTestClient.java

/*************************************************************************
 * Call service as define in 'locator' (which also has an input
 * data for the service) and report results into a new entry in
 * 'reports'./* ww  w  .j a  v a2s .  c  om*/
 *
 * It also returns its own report.
 *************************************************************************/
private static Properties callService(MyLocator locator, List<Properties> reports) {

    Properties report = new Properties();
    reports.add(report);
    String serviceName = locator.getServiceName();
    String inputLine = locator.getInputLine();
    report.setProperty(REPORT_SERVICE_NAME, serviceName);
    report.setProperty(REPORT_INPUT_LINE, inputLine);

    try {
        SoaplabBaseClient client = new SoaplabBaseClient(locator);

        // collect inputs from the input line
        BaseCmdLine cmd = null;
        if (StringUtils.isBlank(inputLine)) {
            cmd = new BaseCmdLine(new String[] {}, true);
        } else {
            cmd = new BaseCmdLine(
                    new StrTokenizer(inputLine, StrMatcher.charSetMatcher(" \t\f"), StrMatcher.quoteMatcher())
                            .getTokenArray(),
                    true);
        }
        SoaplabMap inputs = SoaplabMap
                .fromMap(InputUtils.collectInputs(cmd, SoaplabMap.toMaps(client.getInputSpec())));

        // any unrecognized inputs on the command-line?
        if (cmd.params.length > 0) {
            StringBuilder buf = new StringBuilder();
            buf.append("Unrecognized inputs: ");
            for (String arg : cmd.params)
                buf.append(arg + " ");
            report.setProperty(REPORT_ERROR_MESSAGE, buf.toString());
            report.setProperty(REPORT_JOB_STATUS, "NOT STARTED");
            return report;
        }

        // start service and wait for its completion
        String jobId = client.createAndRun(inputs);
        report.setProperty(REPORT_JOB_ID, jobId);
        client.waitFor(jobId);

        // save all info about just finished job
        String status = client.getStatus(jobId);
        report.setProperty(REPORT_JOB_STATUS, status);

        SoaplabMap times = client.getCharacteristics(jobId);
        Object elapsed = times.get(SoaplabConstants.TIME_ELAPSED);
        if (elapsed != null) {
            try {
                report.setProperty(REPORT_ELAPSED_TIME,
                        DurationFormatUtils.formatDurationHMS(Long.decode(elapsed.toString())));
            } catch (NumberFormatException e) {
            }
        }

        String lastEvent = client.getLastEvent(jobId);
        if (lastEvent != null)
            report.setProperty(REPORT_LAST_EVENT, lastEvent);

        if (!client.getLocator().getProtocol().equals(ClientConfig.PROTOCOL_AXIS1)) {
            // get result infos (about all available results)
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ResultUtils.formatResultInfo(SoaplabMap.toStringMaps(client.getResultsInfo(jobId)),
                    new PrintStream(bos));
            report.setProperty(REPORT_RESULTS_INFO, bos.toString());
        }
        // get results (but ignore them - except the special ones)
        client.getResults(jobId);
        Map<String, Object> results = SoaplabMap.toMap(client.getSomeResults(jobId,
                new String[] { SoaplabConstants.RESULT_REPORT, SoaplabConstants.RESULT_DETAILED_STATUS }));
        for (Iterator<String> it = results.keySet().iterator(); it.hasNext();) {
            String resultName = it.next();
            report.setProperty(resultName, results.get(resultName).toString());
        }

        // clean the job
        if (!locator.isEnabledKeepResults()) {
            client.destroy(jobId);
            report.remove(REPORT_JOB_ID);
        }

    } catch (Throwable e) {
        reportError(report, e);
    }
    return report;
}

From source file:org.ohmage.request.survey.SurveyResponseReadRequest.java

/**
 * Creates a survey response read request. The 'httpRequest', 'parameters',
 * and 'campaignId' parameters are required. The rest are optional and will
 * limit the results.//from  w  ww .j ava  2  s.co  m
 * 
 * @param httpRequest The HTTP request.
 * 
 * @param parameters The parameters from the HTTP request.
 * 
 * @param callClientRequester Refers to the "client" parameter as the
 *                        "requester".
 * 
 * @param campaignId The campaign's unique identifier. Required.
 * 
 * @param usernames A set of usernames.
 * 
 * @param surveyIds A set of survey IDs.
 * 
 * @param promptIds A set of prompt IDs.
 * 
 * @param surveyResponseIds A set of survey response IDs.
 * 
 * @param startDate Limits the responses to only those on or after this
 *                date.
 * 
 * @param endDate Limits the responses to only those on or before this 
 *               date.
 * 
 * @param privacyState A survey response privacy state.
 * 
 * @param promptResponseSearchTokens A set of tokens which must match the
 *                             prompt responses.
 * 
 * @param columns The columns of data to return.
 * 
 * @param outputFormat The format of the output.
 * 
 * @param sortOrder How to sort the parameters.
 * 
 * @param collapse Whether or not to collapse the results.
 * 
 * @param prettyPrint Whether or not to format the results with whitespace.
 * 
 * @param returnId Whether or not to return the response's unique 
 *                identifier with the data.
 * 
 * @param suppressMetadata Whether or not to suppress the metadata section.
 * 
 * @param numResponsesToSkip The number of survey responses to skip.
 * 
 * @param numResponsesToReturn The number of survey responses to return.
 * 
 * @throws InvalidRequestException Thrown if the parameters cannot be 
 *                            parsed.
 * 
 * @throws IOException There was an error reading from the request.
 * 
 * @throws IllegalArgumentException Thrown if a required parameter is 
 *                            missing.
 */
public SurveyResponseReadRequest(final HttpServletRequest httpRequest, final Map<String, String[]> parameters,
        boolean callClientRequester, final String campaignId, final Collection<String> usernames,
        final Collection<String> surveyIds, final Collection<String> promptIds,
        final Set<UUID> surveyResponseIds, final DateTime startDate, final DateTime endDate,
        final SurveyResponse.PrivacyState privacyState, final Set<String> promptResponseSearchTokens,
        final Collection<SurveyResponse.ColumnKey> columns, final SurveyResponse.OutputFormat outputFormat,
        final List<SortParameter> sortOrder, final Boolean collapse, final Boolean prettyPrint,
        final Boolean returnId, final Boolean suppressMetadata, final Long numResponsesToSkip,
        final Long numResponsesToReturn) throws IOException, InvalidRequestException {

    super(httpRequest, parameters, callClientRequester, campaignId, usernames, surveyIds, promptIds,
            surveyResponseIds, startDate, endDate, privacyState, promptResponseSearchTokens);

    this.columns = columns;
    this.outputFormat = outputFormat;
    this.sortOrder = sortOrder;
    this.collapse = collapse;
    this.prettyPrint = prettyPrint;
    this.returnId = returnId;
    this.suppressMetadata = suppressMetadata;

    if (numResponsesToSkip == null) {
        this.surveyResponsesToSkip = 0;
    } else {
        this.surveyResponsesToSkip = numResponsesToSkip;
    }

    if (numResponsesToReturn == null) {
        long tNumResponsesToReturn = 0;
        try {
            tNumResponsesToReturn = Long.decode(
                    PreferenceCache.instance().lookup(PreferenceCache.KEY_MAX_SURVEY_RESPONSE_PAGE_SIZE));

            if (tNumResponsesToReturn == -1) {
                tNumResponsesToReturn = Long.MAX_VALUE;
            }
        } catch (CacheMissException e) {
            LOGGER.error("The cache is missing the max page size.", e);
            setFailed();
        } catch (NumberFormatException e) {
            LOGGER.error("The max page size is not a number.", e);
            setFailed();
        }
        this.surveyResponsesToProcess = tNumResponsesToReturn;
    } else {
        this.surveyResponsesToProcess = numResponsesToReturn;
    }
}

From source file:controllers.Service.java

public static void prepare(String surveyId, String fileFormat, Boolean exportWithImages) {
    String fileType = "";
    byte[] fileContent = null;

    Survey survey = Survey.findById(Long.decode(surveyId));

    if (exportWithImages == true) {
        new File(survey.surveyId).mkdir();
        new File(survey.surveyId + File.separator + "photos").mkdir();
    }// w  w  w .  jav a  2  s .c  om

    if (FileUtilities.CSV.equalsIgnoreCase(fileFormat)) {
        CSVTransformer transformer = new CSVTransformer(survey, exportWithImages);
        fileContent = transformer.getBytes();//this is export all functionality
        fileType = FileUtilities.CSV;
    } else if (FileUtilities.XLS.equalsIgnoreCase(fileFormat)) {
        ExcelTransformer transformer = new ExcelTransformer(survey, exportWithImages);
        fileContent = transformer.getBytes();//this is export all functionality
        fileType = FileUtilities.XLS;
    }

    if (exportWithImages == true) {
        FileUtilities.zipSurvey(survey.surveyId, fileContent, fileType,
                FileUtilities.SURVEY + survey.surveyId + FileUtilities.ZIP);
        File zipFile = new File(FileUtilities.SURVEY + survey.surveyId + FileUtilities.ZIP);
        File zipDir = new File(survey.surveyId);
        try {
            fileContent = FileUtilities.getBytesFromFile(zipFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileType = FileUtilities.ZIP;
        zipFile.delete();
        FileUtilities.deleteDir(zipDir);
    }

    String fileName = FileUtilities.SURVEY + survey.surveyId + fileType;
    send(fileName, fileContent);
}