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.lnicholls.galleon.util.Tools.java

public static String hexToDate(String hex) {
    Date date = new Date();
    try {//from  w ww  .  j ava2  s.  c  om
        Long time = Long.decode(hex);
        date = new Date(time.longValue() * 1000);
    } catch (NumberFormatException ex) {
    }
    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.applyPattern("EEE MMM d yyyy, hh:mm:ss a");
    return sdf.format(date);
}

From source file:org.jboss.dashboard.ui.controller.requestChain.FriendlyUrlProcessor.java

/**
 * Make required processing of request./*from w ww. j  av a2  s  . co  m*/
 *
 * @return true if processing must continue, false otherwise.
 */
public boolean processRequest() throws Exception {
    HttpServletRequest request = getHttpRequest();
    String servletPath = request.getServletPath();
    NavigationManager navigationManager = NavigationManager.lookup();
    UserStatus userStatus = UserStatus.lookup();
    RequestContext requestContext = RequestContext.lookup();

    // ---- Apply locale information, --------------
    LocaleManager localeManager = LocaleManager.lookup();
    // First check if a locale parameter is present in the URI query string.
    Locale localeToSet = null;
    String localeParam = request.getParameter(LOCALE_PARAMETER);
    if (localeParam != null && localeParam.trim().length() > 0) {
        localeToSet = localeManager.getLocaleById(localeParam);
        if (localeToSet != null) {
            localeManager.setCurrentLocale(localeToSet);
        }
    }

    // No friendly -> nothing to do.
    if (!servletPath.startsWith(FRIENDLY_MAPPING))
        return true;

    String contextPath = request.getContextPath();
    requestContext.consumeURIPart(FRIENDLY_MAPPING);
    navigationManager.setShowingConfig(false);
    String requestUri = request.getRequestURI();
    String relativeUri = requestUri.substring(contextPath == null ? 0 : (contextPath.length()));
    relativeUri = relativeUri.substring(servletPath == null ? 0 : (servletPath.length()));

    // Empty URI -> nothing to do.
    if (StringUtils.isBlank(relativeUri))
        return true;

    /*
    * Check if the locale information is in the URI value in order to consume it.
    * Locale information is expected in the URI after "/workspace".
    * Examples:
    * - /workspace/en/....
    * - /workspace/es/....
    * - /workspace/en_ES/....
    * NOTES:
    * - Available locales matched in the URI parameter are obtained from JVM available locales.
    * - If the locale is found as platform available, the locale is set.
    * - Otherwise, do nothing, the locale used will be the last one set or default.
    * - In both cases URI locale parameter will be consumed.
    */
    int startLocaleUri = relativeUri.indexOf("/");
    int endLocaleUri = relativeUri.indexOf("/", startLocaleUri + 1);
    endLocaleUri = endLocaleUri > 0 ? endLocaleUri : relativeUri.length();
    String localeUri = relativeUri.substring(startLocaleUri + 1, endLocaleUri);
    Locale uriLocale = localeManager.getLocaleById(localeUri);
    if (uriLocale != null) {
        requestContext.consumeURIPart("/" + localeUri);
        relativeUri = relativeUri.substring(localeUri.length() + 1);
        // Use the locale specified in the URI value only if no locale specified in the qeury string.
        if (localeToSet == null)
            localeManager.setCurrentLocale(uriLocale);
    }

    // Tokenize the friendly URI.
    StringTokenizer tokenizer = new StringTokenizer(relativeUri, "/", false);
    List tokens = new ArrayList();
    int i = 0;
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if (i < 2) {
            tokens.add(token);
            i++;
        } else if (tokens.size() == 2) {
            tokens.add("/" + token);
        } else {
            tokens.set(2, tokens.get(2) + "/" + token);
        }
    }
    try {
        // Get the target workspace/section spcified.
        log.debug("Tokens=" + tokens);
        String workspaceCandidate = null;
        String sectionCandidate = null;
        if (tokens.size() > 0)
            workspaceCandidate = (String) tokens.get(0);
        if (tokens.size() > 1)
            sectionCandidate = (String) tokens.get(1);
        if (log.isDebugEnabled()) {
            log.debug("workspaceCandidate=" + workspaceCandidate);
            log.debug("sectionCandidate=" + sectionCandidate);
        }
        WorkspaceImpl workspace = null;
        Section section = null;
        if (workspaceCandidate != null) {
            workspace = (WorkspaceImpl) UIServices.lookup().getWorkspacesManager()
                    .getWorkspace(workspaceCandidate);
            if (workspace == null)
                workspace = (WorkspaceImpl) UIServices.lookup().getWorkspacesManager()
                        .getWorkspaceByUrl(workspaceCandidate);
        }
        if (workspace != null && sectionCandidate != null) {
            try {
                section = workspace.getSection(Long.decode(sectionCandidate));
            } catch (NumberFormatException nfe) {
                section = workspace.getSectionByUrl(sectionCandidate);
            }
        }
        // Check the user has access permissions to the target workspace.
        if (workspace != null && section == null) {
            try {
                Workspace currentWorkspace = navigationManager.getCurrentWorkspace();
                log.debug("currentWorkspace = " + (currentWorkspace == null ? "null" : currentWorkspace.getId())
                        + " workspaceCandidate = " + workspaceCandidate);
                if (!workspace.equals(currentWorkspace)) {

                    WorkspacePermission workspacePerm = WorkspacePermission.newInstance(workspace,
                            WorkspacePermission.ACTION_LOGIN);
                    if (userStatus.hasPermission(workspacePerm)) {
                        navigationManager.setCurrentWorkspace(workspace);
                        log.debug("SessionManager.setWorkspace(" + workspace.getId() + ")");
                    } else {
                        if (log.isDebugEnabled())
                            log.debug("User has no " + WorkspacePermission.ACTION_LOGIN
                                    + " permission in workspace " + workspaceCandidate);
                        if (isShowLoginBackDoorOnPermissionDenied()) {
                            navigationManager.setUserRequiresLoginBackdoor(true);
                            navigationManager.setCurrentWorkspace(workspace);
                        }
                    }
                }
                requestContext.consumeURIPart("/" + workspaceCandidate);
            } catch (Exception e) {
                log.error("Cannot set current workspace.", e);
            }
        }
        // Check the user has access permissions to the target section.
        else if (section != null) {
            try {
                if (!section.equals(navigationManager.getCurrentSection())) {

                    WorkspacePermission workspacePerm = WorkspacePermission.newInstance(section.getWorkspace(),
                            WorkspacePermission.ACTION_LOGIN);
                    SectionPermission sectionPerm = SectionPermission.newInstance(section,
                            SectionPermission.ACTION_VIEW);
                    if (userStatus.hasPermission(workspacePerm) && userStatus.hasPermission(sectionPerm)) {
                        if (log.isDebugEnabled())
                            log.debug("SessionManager.setSection(" + section.getId() + ")");
                        navigationManager.setCurrentSection(section);
                    } else {
                        if (log.isDebugEnabled())
                            log.debug("User has no " + WorkspacePermission.ACTION_LOGIN
                                    + " permission in workspace " + workspaceCandidate);
                        if (isShowLoginBackDoorOnPermissionDenied()) {
                            navigationManager.setUserRequiresLoginBackdoor(true);
                            navigationManager.setCurrentSection(section);
                        }
                    }
                }
                requestContext.consumeURIPart("/" + workspaceCandidate);
                requestContext.consumeURIPart("/" + sectionCandidate);
            } catch (Exception e) {
                log.error("Cannot set current section.", e);
            }
        }
    } catch (Exception e) {
        log.error("Exception processing friendly URI", e);
    }
    return true;
}

From source file:org.crazydog.util.spring.NumberUtils.java

/**
 * Parse the given text into a number instance of the given target class,
 * using the corresponding {@code decode} / {@code valueOf} methods.
 * <p>Trims the input {@code String} before attempting to parse the number.
 * Supports numbers in hex format (with leading "0x", "0X" or "#") as well.
 *
 * @param text        the text to convert
 * @param targetClass the target class to parse into
 * @return the parsed number/*from  www .j av  a  2s .  com*/
 * @throws IllegalArgumentException if the target class is not supported
 *                                  (i.e. not a standard Number subclass as included in the JDK)
 * @see Byte#decode
 * @see Short#decode
 * @see Integer#decode
 * @see Long#decode
 * @see #decodeBigInteger(String)
 * @see Float#valueOf
 * @see Double#valueOf
 * @see BigDecimal#BigDecimal(String)
 */
@SuppressWarnings("unchecked")
public static <T extends Number> T parseNumber(String text, Class<T> targetClass) {
    org.springframework.util.Assert.notNull(text, "Text must not be null");
    org.springframework.util.Assert.notNull(targetClass, "Target class must not be null");
    String trimmed = StringUtils.trimAllWhitespace(text);

    if (Byte.class == targetClass) {
        return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte.valueOf(trimmed));
    } else if (Short.class == targetClass) {
        return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short.valueOf(trimmed));
    } else if (Integer.class == targetClass) {
        return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed));
    } else if (Long.class == targetClass) {
        return (T) (isHexNumber(trimmed) ? Long.decode(trimmed) : Long.valueOf(trimmed));
    } else if (BigInteger.class == targetClass) {
        return (T) (isHexNumber(trimmed) ? decodeBigInteger(trimmed) : new BigInteger(trimmed));
    } else if (Float.class == targetClass) {
        return (T) Float.valueOf(trimmed);
    } else if (Double.class == targetClass) {
        return (T) Double.valueOf(trimmed);
    } else if (BigDecimal.class == targetClass || Number.class == targetClass) {
        return (T) new BigDecimal(trimmed);
    } else {
        throw new IllegalArgumentException(
                "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
    }
}

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Converts a string to an object of a particular class.
 *///from www . j  a  v  a 2s . c  om
private static Object convert(final Class toClass, final String value) throws Exception {
    if (value == null) {
        return null;
    }
    if (toClass.isInstance(value)) {
        return value;
    }
    if (toClass == Long.class || toClass == Long.TYPE) {
        return Long.decode(value);
    }
    if (toClass == Integer.class || toClass == Integer.TYPE) {
        return Integer.decode(value);
    }
    if (toClass == Boolean.class || toClass == Boolean.TYPE) {
        return Boolean.valueOf(value);
    }
    throw new Exception("Cannot convert attribute value to class " + toClass.getName());
}

From source file:org.lnicholls.galleon.util.Tools.java

public static Date hexDate(String hex) {
    try {/*from  ww  w  .j a va 2s  .c om*/
        Long time = Long.decode(hex);
        Date date = new Date(time.longValue() * 1000);
        return date;
    } catch (NumberFormatException ex) {
    }
    return null;
}

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

/**
 * This method saves a folder related with a group
 * /*from   www . ja  v  a  2s.  co  m*/
 * @param group
 */
@RequestMapping(value = "/persistenceGeo/saveFolderByGroup/{groupId}", method = RequestMethod.POST)
public @ResponseBody FolderDto saveFolderByGroup(@PathVariable String groupId,
        @RequestParam("name") String name, @RequestParam("enabled") String enabled,
        @RequestParam("isChannel") String isChannel, @RequestParam("isPlain") String isPlain,
        @RequestParam(value = "parentFolder", required = false) String parentFolder) {
    try {
        /*
         * //TODO: Secure with logged user String username = ((UserDetails)
         * SecurityContextHolder.getContext()
         * .getAuthentication().getPrincipal()).getUsername();
         */
        Long idGroup = Long.decode(groupId);
        FolderDto rootFolder = foldersAdminService.getRootGroupFolder(idGroup);
        if (StringUtils.isEmpty(parentFolder) || !StringUtils.isNumeric(parentFolder)) {
            return saveFolderBy(name, enabled, isChannel, isPlain,
                    rootFolder != null ? rootFolder.getId() : null, null, idGroup);
        } else {
            return saveFolderBy(name, enabled, isChannel, isPlain, Long.decode(parentFolder), null, idGroup);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.ohmage.validator.MobilityValidators.java

/**
 * Validates that the duration is a valid number.
 * //from   w  w  w . j av  a 2  s.com
 * @param duration The duration to be validated.
 * 
 * @return The duration as a long value or null if the duration was null or
 *          an empty string.
 * 
 * @throws ValidationException Thrown if there is an error.
 */
public static Long validateAggregateDuration(final String duration) throws ValidationException {

    LOGGER.info("Validating the aggregate duration.");

    if (StringUtils.isEmptyOrWhitespaceOnly(duration)) {
        return null;
    }

    try {
        return Long.decode(duration);
    } catch (NumberFormatException e) {
        throw new ValidationException(ErrorCode.MOBILITY_INVALID_AGGREGATE_DURATION,
                "The aggregate duration is invalid: " + duration);
    }
}

From source file:com.abiquo.nodecollector.domain.collectors.HyperVCollector.java

@Override
public HostDto getHostInfo() throws CollectorException {
    LOGGER.info("Getting physical information in HyperV collector...");
    final HostDto hostInfo = new HostDto();
    try {//from   w  ww .j a  v a2s .  c om
        final List<IJIDispatch> results = HyperVUtils.execQuery("Select * from Win32_ComputerSystem",
                cimService);
        final IJIDispatch dispatch = results.get(0);

        // Must produce only one result final
        JIVariant name = dispatch.get("DNSHostName");
        final JIVariant memory = dispatch.get("TotalPhysicalMemory");
        hostInfo.setName(name.getObjectAsString2());
        hostInfo.setRam(Long.decode(memory.getObjectAsString2()));
        hostInfo.setCpu(getNumberOfCores());
        hostInfo.setHypervisor(getHypervisorType().getValue());
        hostInfo.setVersion(getVersion());
        hostInfo.setInitiatorIQN(getInitiatorIQN(name.getObjectAsString2()));

        // Uncomment if you want to return physical
        // interfaces
        // final List<IJIDispatch> resultsIfaces =
        // HyperVUtils.execQuery("Select * from Win32_NetworkAdapter", cimService);
        // final List<IJIDispatch> resultsIfaces
        // =HyperVUtils.execQuery("Select * from Msvm_ExternalEthernetPort", cimService);
        // hostInfo.getResources().addAll(filterInterfaceList(resultsIfaces));

        URL urlAddress = new URL("http://" + getIpAddress());
        SWbemLocator loc = new SWbemLocator();
        virtService = loc.connect(urlAddress.getHost(), "127.0.0.1", HyperVConstants.VIRTUALIZATION_NS,
                hyperVuser, hyperVpassword);

        hostInfo.getResources().addAll(getHostResources());

        try {
            checkPhysicalState();
            hostInfo.setStatus(HostStatusEnumType.MANAGED);
        } catch (NoManagedException e) {
            hostInfo.setStatus(HostStatusEnumType.NOT_MANAGED);
            hostInfo.setStatusInfo(e.getMessage());
        }
    } catch (Exception ex) {
        if (ex.getCause() instanceof SmbException) {
            LOGGER.error(MessageValues.COLL_EXCP_SMB);
            throw new CollectorException(MessageValues.COLL_EXCP_SMB, ex);
        }
        LOGGER.error(MessageValues.COLL_EXCP_PH);
        throw new CollectorException(MessageValues.COLL_EXCP_PH, ex);
    }
    return hostInfo;
}

From source file:controllers.Service.java

public static void selectedToKML(String surveyId, String resultIDs) {
    Survey survey = Survey.findById(Long.decode(surveyId));
    String[] resultsIds = resultIDs.split(",");

    Collection<NdgResult> results = new ArrayList<NdgResult>();
    Collection<NdgResult> removalResults = new ArrayList<NdgResult>();
    NdgResult result = null;//w ww  . j  a va 2 s  .  c  om

    if (resultsIds.length > 0) {
        for (int i = 0; i < resultsIds.length; i++) {
            result = NdgResult.find("byId", Long.parseLong(resultsIds[i])).first();
            if (result != null) {
                results.add(result);
            }
        }
    }

    for (NdgResult current : results) {
        if (current.latitude == null || current.longitude == null) {
            removalResults.add(current);
        }
    }
    results.removeAll(removalResults);

    ByteArrayOutputStream arqExport = new ByteArrayOutputStream();
    String fileName = surveyId + ".kml";

    try {
        final Kml kml = new Kml();
        final Document document = kml.createAndSetDocument();

        for (NdgResult current : results) {
            //                String description = "<![CDATA[ ";
            String description = "";
            int i = 0;

            List<Question> questions = new ArrayList<Question>();
            questions = survey.getQuestions();

            if (questions.isEmpty()) {
                description += "<b> NO QUESTION </b> <br><br>";
            }

            for (Question question : questions) {
                i++;
                description += "<h3><b>" + i + " - " + question.label + "</b></h3><br>";

                Collection<Answer> answers = CollectionUtils.intersection(question.answerCollection,
                        current.answerCollection);
                if (answers.isEmpty()) {
                    description += "<br><br>";
                } else if (answers.size() == 1) {
                    Answer answer = answers.iterator().next();

                    if (answer.question.questionType.typeName.equalsIgnoreCase(QuestionTypesConsts.IMAGE)) {
                        /*                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                                    byte[] buf = new byte[1024];
                                                    InputStream in = answer.binaryData.get();
                                                    int n = 0;
                                                    try {
                        while( (n = in.read(buf) ) >= 0) {
                            baos.write(buf, 0, n);
                        }
                        in.close();
                                                    } catch(IOException ex) {
                        System.out.println("IO");
                                                    }
                                
                                                    byte[] bytes = baos.toByteArray();
                                                    System.out.println("image = " + Base64.encodeBase64String(bytes));
                                                    description += "<img src='data:image/jpeg;base64," + Base64.encodeBase64String(bytes)
                                + "'/> <br><br>"; */
                        description += "<b> #image</b> <br><br>";
                    } else {
                        description += "<h4 style='color:#3a77ca'><b>" + answer.textData + "</b></h4><br>";
                    }
                }
            }
            //                description += " ]]>";

            document.createAndAddPlacemark().withName(current.title).withOpen(Boolean.TRUE)
                    .withDescription(description).createAndSetPoint()
                    .addToCoordinates(current.longitude + ", " + current.latitude);
        }

        kml.marshal(arqExport);
        send(fileName, arqExport.toByteArray());
    } catch (FileNotFoundException ex) {
    }
}

From source file:de.geeksfactory.opacclient.frontend.OpacActivity.java

protected void setupDrawer() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawerLayout != null) {
        hasDrawer = true;//from w w w .java  2  s  .  c  o m
        drawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
                drawerLayout, /* DrawerLayout object */
                R.drawable.ic_navigation_drawer, /*
                                                 * nav drawer icon to replace 'Up'
                                                 * caret
                                                 */
                R.string.drawer_open, /* "open drawer" description */
                R.string.drawer_close /* "close drawer" description */
        ) {

            /**
             * Called when a drawer has settled in a completely closed
             * state.
             */
            @Override
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle(app.getResources().getString(R.string.app_name));
                if (getCurrentFocus() != null) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(
                            Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                }
            }
        };

        // Set the drawer toggle as the DrawerListener
        drawerLayout.setDrawerListener(drawerToggle);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        drawerList = (ListView) findViewById(R.id.drawer_list);
        navAdapter = new NavigationAdapter(this);
        drawerList.setAdapter(navAdapter);
        navAdapter.addSeperatorItem(getString(R.string.nav_hl_library));
        navAdapter.addTextItemWithIcon(getString(R.string.nav_search), R.drawable.ic_action_search, "search");
        navAdapter.addTextItemWithIcon(getString(R.string.nav_account), R.drawable.ic_action_account,
                "account");
        navAdapter.addTextItemWithIcon(getString(R.string.nav_starred), R.drawable.ic_action_star_1, "starred");
        navAdapter.addTextItemWithIcon(getString(R.string.nav_info), R.drawable.ic_action_info, "info");

        aData.open();
        accounts = aData.getAllAccounts();
        if (accounts.size() > 1) {
            navAdapter.addSeperatorItem(getString(R.string.nav_hl_accountlist));

            long tolerance = Long.decode(sp.getString("notification_warning", "367200000"));
            int selected = -1;
            for (final Account account : accounts) {
                Library library;
                try {
                    library = ((OpacClient) getApplication()).getLibrary(account.getLibrary());
                    int expiring = aData.getExpiring(account, tolerance);
                    String expiringText = "";
                    if (expiring > 0) {
                        expiringText = String.valueOf(expiring);
                    }
                    if (getString(R.string.default_account_name).equals(account.getLabel())) {
                        navAdapter.addLibraryItem(library.getCity(), library.getTitle(), expiringText,
                                account.getId());
                    } else {
                        navAdapter.addLibraryItem(account.getLabel(),
                                library.getCity() + "  " + library.getTitle(), expiringText, account.getId());
                    }
                    if (account.getId() == app.getAccount().getId()) {
                        selected = navAdapter.getCount() - 1;
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (selected > 0) {
                drawerList.setItemChecked(selected, true);
            }
        }

        navAdapter.addSeperatorItem(getString(R.string.nav_hl_other));
        navAdapter.addTextItemWithIcon(getString(R.string.nav_settings), R.drawable.ic_action_settings,
                "settings");
        navAdapter.addTextItemWithIcon(getString(R.string.nav_about), R.drawable.ic_action_help, "about");

        drawerList.setOnItemClickListener(new DrawerItemClickListener());

        if (!sp.getBoolean("version2.0.0-introduced", false) && app.getSlidingMenuEnabled()) {
            final Handler handler = new Handler();
            // Just show the menu to explain that is there if people start
            // version 2 for the first time.
            // We need a handler because if we just put this in onCreate
            // nothing
            // happens. I don't have any idea, why.
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(OpacActivity.this);
                    drawerLayout.openDrawer(drawerList);
                    sp.edit().putBoolean("version2.0.0-introduced", true).commit();
                }
            }, 500);

        }
    }
}