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.treeNodes.SectionsNode.java

protected TreeNode listChildrenById(String id) {
    try {/* w ww.  j a v a 2s  .  co  m*/
        Section section = ((WorkspaceImpl) getWorkspace()).getSection(Long.decode(id));
        if (section.isRoot())
            return getNewSectionNode(section);
    } catch (Exception e) {
        log.error("Error: ", e);
    }
    return null;
}

From source file:com.example.getstarted.basicactions.UpdateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");

    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;// w  w w .j  av a 2 s. c  o  m
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    try {
        Book oldBook = dao.readBook(Long.decode(params.get("id")));

        Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
                .publishedDate(params.get("publishedDate")).title(params.get("title"))
                .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl)
                .id(Long.decode(params.get("id"))).createdBy(oldBook.getCreatedBy())
                .createdById(oldBook.getCreatedById()).build();

        dao.updateBook(book);
        resp.sendRedirect("/read?id=" + params.get("id"));
    } catch (Exception e) {
        throw new ServletException("Error updating book", e);
    }
}

From source file:fr.gael.dhus.datastore.IncomingManager.java

public boolean isAnIncomingElement(File file) {
    int maxfileno = cfgManager.getArchiveConfiguration().getIncomingConfiguration().getMaxFileNo();

    boolean is_digit = true;
    try {/*  w  w  w  . j  av a2  s. c o  m*/
        // Incoming folders are "X5F" can be parse "0X5F" by decode
        // Warning '09' means octal value that raise error because 9>8...
        String filename = file.getName();
        if (filename.toUpperCase().startsWith("X"))
            filename = "0" + filename;

        if (Long.decode(filename) > maxfileno)
            throw new NumberFormatException("Expected value exceeded.");
    } catch (NumberFormatException e) {
        is_digit = false;
    }

    return isInIncoming(file) && (is_digit
            || file.getName().equals(HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME)
            || (file.getName().equals(INCOMING_PRODUCT_DIR)
                    && file.getParentFile().getName().equals(HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME)));
}

From source file:org.energy_home.jemma.javagal.rest.resources.ServicesResource.java

@Get
public void processGet() {
    String addrString = (String) getRequest().getAttributes().get("addr");
    Address address = new Address();
    if (addrString.length() > 4) {
        BigInteger addressBigInteger = BigInteger.valueOf(Long.parseLong(addrString, 16));
        address.setIeeeAddress(addressBigInteger);
    } else {//from w w w.  j  a v a2s  .com
        Integer addressInteger = Integer.parseInt(addrString, 16);
        address.setNetworkAddress(addressInteger);
    }

    Parameter timeoutParam = getRequest().getResourceRef().getQueryAsForm()
            .getFirst(Resources.URI_PARAM_TIMEOUT);
    if (timeoutParam != null) {
        timeoutString = timeoutParam.getValue().trim();
        try {
            timeout = Long.decode(Resources.HEX_PREFIX + timeoutString);
            // if (timeout < 0 || timeout > 0xffff) {
            if (!Util.isUnsigned32(timeout)) {

                Info info = new Info();
                Status _st = new Status();
                _st.setCode((short) GatewayConstants.GENERAL_ERROR);
                _st.setMessage("Error: optional '" + ResourcePathURIs.TIMEOUT_PARAM
                        + "' parameter's value invalid. You provided: " + timeoutString);
                info.setStatus(_st);
                Info.Detail detail = new Info.Detail();
                info.setDetail(detail);
                getResponse().setEntity(Util.marshal(info), MediaType.APPLICATION_XML);
                return;

            }
        } catch (NumberFormatException nfe) {

            Info info = new Info();
            Status _st = new Status();
            _st.setCode((short) GatewayConstants.GENERAL_ERROR);
            _st.setMessage("Error: optional '" + ResourcePathURIs.TIMEOUT_PARAM
                    + "' parameter's value invalid. You provided: " + timeoutString);
            info.setStatus(_st);
            Info.Detail detail = new Info.Detail();
            info.setDetail(detail);
            getResponse().setEntity(Util.marshal(info), MediaType.APPLICATION_XML);
            return;

        }
    }

    // Urilistener parameter
    String urilistener = null;
    Parameter urilistenerParam = getRequest().getResourceRef().getQueryAsForm()
            .getFirst(Resources.URI_PARAM_URILISTENER);
    // Urilistener is mandatory
    if (urilistenerParam != null) {
        // TODO Marco why getSecond() and not getValue()?
        // urilistener = urilistenerParam.getSecond();
        urilistener = urilistenerParam.getValue();
    }

    try {
        if (urilistener == null) {
            // Synch StartServiceDiscovery
            proxyGalInterface = getRestManager().getClientObjectKey(-1, getClientInfo().getAddress())
                    .getGatewayInterface();
            NodeServices node = proxyGalInterface.startServiceDiscoverySync(timeout, address);

            Info.Detail detail = new Info.Detail();
            detail.setNodeServices(node);
            Info infoToReturn = new Info();
            Status status = new Status();
            status.setCode((short) GatewayConstants.SUCCESS);
            infoToReturn.setStatus(status);
            infoToReturn.setDetail(detail);
            getResponse().setEntity(Util.marshal(infoToReturn), MediaType.TEXT_XML);

            return;
        } else {
            // Asynch
            ClientResources rcmal = getRestManager()
                    .getClientObjectKey(Util.getPortFromUriListener(urilistener), getClientInfo().getAddress());
            proxyGalInterface = rcmal.getGatewayInterface();
            if (!urilistener.equals("")) {
                rcmal.getClientEventListener().setNodeServicesDestination(urilistener);
            }
            proxyGalInterface.startServiceDiscovery(timeout, address);
            Info.Detail detail = new Info.Detail();
            Info infoToReturn = new Info();
            Status status = new Status();
            status.setCode((short) GatewayConstants.SUCCESS);
            infoToReturn.setStatus(status);
            infoToReturn.setRequestIdentifier(Util.getRequestIdentifier());
            infoToReturn.setDetail(detail);
            getResponse().setEntity(Util.marshal(infoToReturn), MediaType.TEXT_XML);
            return;
        }

    } catch (NullPointerException npe) {
        Info info = new Info();
        Status _st = new Status();
        _st.setCode((short) GatewayConstants.GENERAL_ERROR);
        _st.setMessage(npe.getMessage());
        info.setStatus(_st);
        Info.Detail detail = new Info.Detail();
        info.setDetail(detail);
        getResponse().setEntity(Util.marshal(info), MediaType.APPLICATION_XML);
        return;

    } catch (Exception e) {
        Info info = new Info();
        Status _st = new Status();
        _st.setCode((short) GatewayConstants.GENERAL_ERROR);
        _st.setMessage(e.getMessage());
        info.setStatus(_st);
        Info.Detail detail = new Info.Detail();
        info.setDetail(detail);
        getResponse().setEntity(Util.marshal(info), MediaType.APPLICATION_XML);
        return;
    }
}

From source file:org.energyos.espi.common.repositories.jpa.ResourceRepositoryImpl.java

@SuppressWarnings("unchecked")
@Override//from w  w w.  j  a v a  2s  . c  om
public List<IdentifiedObject> findAllParentsByRelatedHref(String href, Linkable linkable) {
    String queryString = linkable.getParentQuery();
    List<IdentifiedObject> result = em.createNamedQuery(queryString).setParameter("href", href).getResultList();
    if (result.isEmpty()) {
        // we did not find one, so now try to parse the URL and find the
        // parent that way
        // this needed only b/c we are not storing the up and self hrefs
        // in
        // the underlying db but rather
        // relying upon a structured URL for resources that we have
        // exported.
        //
        Boolean usagePointFlag = false;
        Boolean meterReadingFlag = false;

        Long usagePointId = null;
        Long meterReadingId = null;

        try {
            for (String token : href.split("/")) {
                if (usagePointFlag) {
                    if (token.length() != 0) {
                        usagePointId = Long.decode(token);
                    }
                    usagePointFlag = false;
                }

                if (meterReadingFlag) {
                    if (token.length() != 0) {
                        meterReadingId = Long.decode(token);
                    }
                    meterReadingFlag = false;
                }

                if (token.equals("UsagePoint")) {
                    usagePointFlag = true;
                }

                if (token.equals("MeterReading")) {
                    meterReadingFlag = true;
                }

            }

            if (meterReadingId != null) {
                result.add(findById(meterReadingId, MeterReading.class));
            } else {
                if (usagePointId != null) {
                    result.add(findById(usagePointId, UsagePoint.class));
                }

            }

        } catch (NoResultException e) {
            // nothing to do, just return the empty result and
            // we'll find it later.
            System.out.printf(
                    "**** findAllParentsByRelatedHref(String href) NoResultException: %s\n     usagePointId: %s   meterReadingId: %s\n     href: %s\n",
                    e.toString(), usagePointId, meterReadingId, href);

        } catch (Exception e) {
            // nothing to do, just return the empty result and
            // we'll find it later.
            System.out.printf("**** findAllParentsByRelatedHref(String href) Exception: %s\n     href: %s\n",
                    e.toString(), href);
        }

    }
    return result;
}

From source file:org.jboss.dashboard.ui.panel.parameters.PanelSupplier.java

/**
 * Given a key like panelId@sectionId@workspaceId, return the panel if any, that
 * matches this pattern/*from  w ww.j ava 2  s  . c o  m*/
 *
 * @param key    Encoded form of panel id.
 * @param workspace The workspace where the panel is expected to be.
 * @return the panel matching this pattern, or null if not found, or key is wrong.
 */
public static Panel getPanelForKey(WorkspaceImpl workspace, String key) {
    try {
        int first = key.indexOf('@');
        String panelId = key.substring(0, first);
        String sectionId = key.substring(first + 1);
        Section section = workspace.getSection(Long.decode(sectionId));
        Panel panel = section.getPanel(panelId);
        return panel;
    } catch (Exception e) {
        log.error("Invalid panel key " + key);
    }
    return null;
}

From source file:org.ossie.properties.AnyUtils.java

/**
 * Attempts to convert the string value to the appropriate Java type.
 * /*  w  ww  .  java2s  . co m*/
 * @param stringValue the string form of the value
 * @param type the string form of the TypeCode
 * @return A Java object of theString corresponding to the typecode
 */
public static Object convertString(final String stringValue, final String type) {
    if (stringValue == null) {
        return null;
    }
    if (type.equals("string")) {
        return stringValue;
    } else if (type.equals("wstring")) {
        return stringValue;
    } else if (type.equals("boolean")) {
        if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) {
            return Boolean.parseBoolean(stringValue);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid boolean value");
    } else if (type.equals("char")) {
        if (stringValue.length() == 1) {
            return stringValue.charAt(0);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid char value");
    } else if (type.equals("wchar")) {
        return stringValue.charAt(0);
    } else if (type.equals("double")) {
        return Double.parseDouble(stringValue);
    } else if (type.equals("float")) {
        return Float.parseFloat(stringValue);
    } else if (type.equals("short")) {
        return Short.decode(stringValue);
    } else if (type.equals("long")) {
        return Integer.decode(stringValue);
    } else if (type.equals("longlong")) {
        return Long.decode(stringValue);
    } else if (type.equals("ulong")) {
        final long MAX_UINT = 2L * Integer.MAX_VALUE + 1L;
        final Long retVal = Long.decode(stringValue);
        if (retVal < 0 || retVal > MAX_UINT) {
            throw new IllegalArgumentException(
                    "ulong value must be greater than '0' and less than " + MAX_UINT);
        }
        return retVal;
    } else if (type.equals("ushort")) {
        final int MAX_USHORT = 2 * Short.MAX_VALUE + 1;
        final Integer retVal = Integer.decode(stringValue);
        if (retVal < 0 || retVal > MAX_USHORT) {
            throw new IllegalArgumentException(
                    "ushort value must be greater than '0' and less than " + MAX_USHORT);
        }
        return retVal;
    } else if (type.equals("ulonglong")) {
        final BigInteger MAX_ULONG_LONG = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2))
                .add(BigInteger.ONE);
        final BigInteger retVal = bigIntegerDecode(stringValue);
        if (retVal.compareTo(BigInteger.ZERO) < 0 || retVal.compareTo(MAX_ULONG_LONG) > 0) {
            throw new IllegalArgumentException(
                    "ulonglong value must be greater than '0' and less than " + MAX_ULONG_LONG.toString());
        }
        return retVal;
    } else if (type.equals("objref")) {
        List<String> objrefPrefix = Arrays.asList("IOR:", "corbaname:", "corbaloc:");
        for (String prefix : objrefPrefix) {
            if (stringValue.startsWith(prefix)) {
                return stringValue;
            }
        }
        throw new IllegalArgumentException(stringValue + " is not a valid objref value");
    } else if (type.equals("octet")) {
        final short MIN_OCTET = 0;
        final short MAX_OCTET = 0xFF;
        short val = Short.valueOf(stringValue);
        if (val <= MAX_OCTET && val >= MIN_OCTET) {
            return Short.valueOf(val).byteValue();
        }
        throw new IllegalArgumentException(stringValue + " is not a valid octet value");
    } else {
        throw new IllegalArgumentException("Unknown CORBA Type: " + type);
    }
}

From source file:org.onosproject.rest.resources.IntentsWebResource.java

/**
 * Get intent by application and key./*from   w ww .java  2  s .  c  om*/
 * Returns details of the specified intent.
 *
 * @param appId application identifier
 * @param key   intent key
 * @return intent data
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{appId}/{key}")
public Response getIntentById(@PathParam("appId") String appId, @PathParam("key") String key) {
    final ApplicationId app = get(CoreService.class).getAppId(appId);

    Intent intent = get(IntentService.class).getIntent(Key.of(key, app));
    if (intent == null) {
        long numericalKey = Long.decode(key);
        intent = get(IntentService.class).getIntent(Key.of(numericalKey, app));
    }
    nullIsNotFound(intent, INTENT_NOT_FOUND);

    final ObjectNode root;
    if (intent instanceof HostToHostIntent) {
        root = codec(HostToHostIntent.class).encode((HostToHostIntent) intent, this);
    } else if (intent instanceof PointToPointIntent) {
        root = codec(PointToPointIntent.class).encode((PointToPointIntent) intent, this);
    } else if (intent instanceof OpticalConnectivityIntent) { //Edited
        root = codec(OpticalConnectivityIntent.class).encode((OpticalConnectivityIntent) intent, this);
    } else {
        root = codec(Intent.class).encode(intent, this);
    }
    return ok(root).build();
}

From source file:controllers.Service.java

public static void allToKML(String surveyId) {
    Survey survey = Survey.findById(Long.decode(surveyId));
    Collection<NdgResult> results = new ArrayList<NdgResult>();
    Collection<NdgResult> removalResults = new ArrayList<NdgResult>();
    results = survey.resultCollection;//from  w  w  w.j  a v  a  2  s  .co  m

    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(); //TODO Include image, right
                                                    byte[] buf = new byte[1024];                                //now it adds base64 to the img
                                                    InputStream in = answer.binaryData.get();                   //tag but it doesn't show on
                                                    int n = 0;                                                  //the map
                                                    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:org.jboss.dashboard.ui.config.components.panels.PanelsPropertiesHandler.java

public void actionDeletePanel(final CommandRequest request) {
    try {/*  w w  w .j a v a2 s . co  m*/
        HibernateTxFragment txFragment = new HibernateTxFragment() {
            protected void txFragment(Session session) throws Exception {
                final WorkspaceImpl workspace = (WorkspaceImpl) getWorkspace();

                Long dbid = Long.decode(request.getParameter("dbid"));
                Long sectionId = request.getParameter("sectionId").equals(PARAM_NO_SECTION) ? null
                        : Long.decode(request.getParameter("sectionId"));

                if (workspace == null) {
                    log.error("Error getting workspace");
                    return;
                }

                final Section section;
                if (sectionId == null)
                    section = ((WorkspaceImpl) getWorkspace()).getSection(getSectionId());
                else
                    section = workspace.getSection(sectionId);

                if (section == null) {
                    log.error("Error getting panel section");
                    return;
                }

                Panel panel = null;
                Panel[] panels = section.getAllPanels();

                for (int i = 0; i < panels.length; i++) {
                    if (panels[i].getDbid().equals(dbid))
                        panel = panels[i];
                }
                section.removePanel(panel);
                SessionManager.setCurrentPanel(panel);

                UIServices.lookup().getPanelsManager().delete(panel);
                //section.removePanel(panel);
                UIServices.lookup().getSectionsManager().store(section);
            }
        };

        txFragment.execute();
    } catch (Exception e) {
        PanelsPropertiesHandler.log.error("Error: " + e.getMessage());
    }
}