Example usage for java.lang Integer decode

List of usage examples for java.lang Integer decode

Introduction

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

Prototype

public static Integer decode(String nm) throws NumberFormatException 

Source Link

Document

Decodes a String into an Integer .

Usage

From source file:com.l2jfree.gameserver.model.skills.conditions.ConditionParser.java

private Condition parseUsingCondition(String nodeName, String nodeValue) {
    if ("kind".equalsIgnoreCase(nodeName)) {
        int mask = 0;
        StringTokenizer st = new StringTokenizer(nodeValue, ",");
        while (st.hasMoreTokens()) {
            String item = st.nextToken().trim();
            for (L2WeaponType wt : L2WeaponType.values()) {
                if (wt.toString().equalsIgnoreCase(item)) {
                    mask |= wt.mask();/*from  ww  w .ja v a2  s.c o m*/
                    break;
                }
            }
            for (L2ArmorType at : L2ArmorType.values()) {
                if (at.toString().equalsIgnoreCase(item)) {
                    mask |= at.mask();
                    break;
                }
            }
        }
        return new ConditionUsingItemType(mask);
    } else if ("skill".equalsIgnoreCase(nodeName)) {
        StringTokenizer st = new StringTokenizer(nodeValue, ",");
        int skillId = Integer.decode(st.nextToken());
        int minSkillLvl = st.hasMoreTokens() ? Integer.decode(st.nextToken()) : -1;
        int maxSkillLvl = st.hasMoreTokens() ? Integer.decode(st.nextToken()) : minSkillLvl;
        return new ConditionUsingSkill(skillId, minSkillLvl, maxSkillLvl);
    } else if ("slotitem".equalsIgnoreCase(nodeName)) {
        StringTokenizer st = new StringTokenizer(nodeValue, ";");
        int id = Integer.decode(st.nextToken().trim());
        int slot = Integer.decode(st.nextToken().trim());
        int enchant = 0;
        if (st.hasMoreTokens())
            enchant = Integer.decode(st.nextToken().trim());
        return new ConditionSlotItemId(slot, id, enchant);
    } else if ("weaponChange".equalsIgnoreCase(nodeName)) {
        boolean val = Boolean.parseBoolean(nodeValue);
        return new ConditionChangeWeapon(val);
    }

    throw new IllegalStateException("Invalid attribute at <using>: " + nodeName + "='" + nodeValue + "'");
}

From source file:org.rhq.bundle.ant.AntMain.java

/** Handle the -nice argument. */
private int handleArgNice(String[] args, int pos) {
    try {/*from  w w w. j a va 2 s .  co  m*/
        threadPriority = Integer.decode(args[++pos]);
    } catch (ArrayIndexOutOfBoundsException aioobe) {
        throw new BuildException("You must supply a niceness value (1-10)" + " after the -nice option");
    } catch (NumberFormatException e) {
        throw new BuildException("Unrecognized niceness value: " + args[pos]);
    }

    if (threadPriority.intValue() < Thread.MIN_PRIORITY || threadPriority.intValue() > Thread.MAX_PRIORITY) {
        throw new BuildException("Niceness value is out of the range 1-10");
    }
    return pos;
}

From source file:org.apache.flex.compiler.internal.projects.FlexProject.java

/**
 * Convert a color to an integer value./*from ww w  . ja  v a  2s.c om*/
 * 
 * @param colorValue may be a named color, or a String in 
 * any format supported by Integer.decode(). May not be null.
 * @return the color as an integer.
 * @throws NumberFormatException if the value is not a named color and is not
 * properly formatted for Integer.decode(). 
 * @throws NullPointerException is colorValue is null.
 */
public int getColorAsInt(String colorValue) throws NumberFormatException {
    if (colorValue == null)
        throw new NullPointerException("colorValue may not be null");

    if (namedColors != null) {
        Integer value = namedColors.get(colorValue);
        if (value != null)
            return value.intValue();
    }

    return Integer.decode(colorValue).intValue();
}

From source file:org.rdfhdt.hdt.impl.BufferedCompressedStreamingNoDictionary.java

/**
 * Process a molecule, i.e., set of triples around a common element (typically a subject)
 * //from   w ww.j ava2s  . co m
 * @param elements
 */
public void processMolecule(ArrayList<TripleString> elements) {
    int tempIDSubject = 0;
    int tempIDPredicate = 0;
    int tempIDObject = 0;
    int tempIDStructure = 0;

    String subject = (String) elements.get(0).getSubject(); // could also be passed by argument
    MoleculeNoDictionary mol = new MoleculeNoDictionary();

    if (!store_subj_dictionary) {
        // check prefix and replace it if present
        Entry<String, Integer> entry = prefixes.getEntryShared(subject);
        if (entry != null) { // put only suffix
            mol.newSubject_prefix = entry.getValue();
            mol.newSubject = subject.substring(entry.getKey().length());
        } else {
            mol.newSubject_prefix = 0;
            mol.newSubject = subject;
        }
    } else { // store subject dictionary
        // Convert Subject-String to Subject-ID
        if (subjects.containsKey(subject)) {
            tempIDSubject = subjects.get(subject);
        } else {
            try {
                tempIDSubject = subjects.insert(subject);
            } catch (DictionaryException e) {
                System.err.println("LRU Dictionary exception");
                e.printStackTrace();
            }
            if (usePrefixes) {
                // check prefix and replace it if present
                Entry<String, Integer> entry = prefixes.getEntryShared(subject);

                if (entry != null) { // put only suffix
                    mol.newSubject_prefix = entry.getValue();
                    mol.newSubject = subject.substring(entry.getKey().length());
                } else {
                    mol.newSubject_prefix = 0;
                    mol.newSubject = subject;

                }
            } else {
                mol.newSubject_prefix = -1;
            }
        }
        // set molecule subject
        mol.subject = tempIDSubject;
    }

    String predicateStructure = "";
    String objectsDiscrete = "";
    Integer currPredicate = -1;

    Boolean isDiscretePredicate = false;
    String obj = "";
    for (int i = 0; i < elements.size(); i++) {

        obj = elements.get(i).getObject().toString();
        isDiscretePredicate = predicateDiscrete.get(elements.get(i).getPredicate().toString());
        if (predicates.containsKey(elements.get(i).getPredicate().toString())) {
            tempIDPredicate = predicates.get(elements.get(i).getPredicate().toString());
            // check dictionary of objects for this predicate

            // check discrete predicate
            if (isDiscretePredicate == null) {

                try {

                    // erase object suffix
                    obj = elements.get(i).getObject().toString();

                    if (predicateLiterals.get(tempIDPredicate - 1)) {
                        // offset_tag=1 by default or it is =0 if disabled_consistent_predicates=true
                        obj = obj.substring(offset_tag,
                                obj.length() - sizeofTags.get(tempIDPredicate - 1) - offset_tag);

                        mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                    } else {
                        if (usePrefixes) {
                            // replace predicate of URI
                            Integer newPreffixURI = 0;
                            // check prefix
                            Entry<String, Integer> entry = prefixes.getEntryShared(obj);

                            if (entry != null) { // put only suffix
                                newPreffixURI = entry.getValue();
                                obj = obj.substring(entry.getKey().length());
                            }
                            mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                        } else {
                            mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj);
                        }
                    }

                } catch (BlockException e) {
                    System.err.println("Block exception");
                    e.printStackTrace();
                }

            }

        } else {
            // insert new Predicate and create LRUDictionary for it
            tempIDPredicate = predicates.size() + 1;

            predicates.put(elements.get(i).getPredicate().toString(), predicates.size() + 1);

            // store the literal tag if present

            String tag = "";
            Boolean isliteral = false;
            Boolean detectedType = false;

            // check discrete predicate
            if (isDiscretePredicate == null) {

                if (!disable_consistent_predicates) {

                    if (obj.charAt(0) == '"') {
                        isliteral = true;

                        int pos_end = obj.lastIndexOf('"'); // tag after last '"'
                        if (obj.length() > (pos_end + 1)) {
                            tag = obj.substring(pos_end + 1);
                            obj = obj.substring(1, pos_end); // replace obj erasing tag

                        } else {
                            obj = obj.substring(1, pos_end); // replace obj erasing '"'
                            // trying to infer embedded tag before last '"'
                            int pos_tag = obj.indexOf("^^");
                            if (pos_tag > 0) {
                                tag = obj.substring(pos_tag) + '"'; // we maintain the last quote to distinguish the inference
                                obj = obj.substring(0, pos_tag); // replace obj erasing quotes '"'

                                detectedType = true;

                            }

                        }
                    }

                } else {
                    isliteral = true; // consider all literals to avoid change much code
                }

                predicateLiterals.set(tempIDPredicate - 1, isliteral);
                literalTagsByPredicate.add(tag); // set tag TODO it could be not needed, the sizeofTags is used instead.
                if (detectedType == false) {
                    sizeofTags.add(tag.length());

                } else {
                    sizeofTags.add(tag.length() - 1); // speed up processing for replacing, -1 to erase last quote character
                }

                try {

                    mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral,
                            tag);

                    if (isliteral) {
                        mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                    } else {
                        // check prefix
                        Entry<String, Integer> entry = prefixes.getEntryShared(obj);
                        Integer newPreffixURI = 0;
                        if (entry != null) { // put only suffix
                            newPreffixURI = entry.getValue();
                            obj = obj.substring(entry.getKey().length());
                        }
                        mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                    }

                } catch (BlockException e) {
                    System.err.println("Block exception");
                    e.printStackTrace();
                }
            } else {
                // insert void properties: a void dictionary of objects and no tags

                sizeofTags.add(0);
                isliteral = (obj.charAt(0) == '"');
                mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral, "");
            }

        }
        if (currPredicate != tempIDPredicate) {
            if (currPredicate == -1) // first
                predicateStructure += tempIDPredicate;
            else
                predicateStructure += ";" + tempIDPredicate;
        } else {

            predicateStructure += ",";

        }
        // check discrete predicate and append objects
        if (isDiscretePredicate != null) {
            objectsDiscrete = objectsDiscrete + "$" + obj;
        }
        currPredicate = tempIDPredicate;

    }
    predicateStructure = predicateStructure + objectsDiscrete;
    // Insert structure
    if (structures.containsKey(predicateStructure)) {
        tempIDStructure = structures.get(predicateStructure);

        mol.addStructure(tempIDStructure); // add structure of the molecule
    } else {
        try {
            tempIDStructure = structures.insert(predicateStructure);

        } catch (DictionaryException e) {
            System.err.println("LRU Dictionary exception");
            e.printStackTrace();
        }

        // store new structure in compact way (list of predicate-ID and its
        // repetitions and objects discrete
        ArrayList<Integer> listPredsinStructure = new ArrayList<Integer>(5);
        ArrayList<String> allObjectsDiscrete = null;
        if (objectsDiscrete != "") {
            allObjectsDiscrete = new ArrayList<String>(Arrays.asList(objectsDiscrete.split("\\$")));
            allObjectsDiscrete.remove(0); // erase first void element

            predicateStructure = predicateStructure.substring(0,
                    predicateStructure.length() - objectsDiscrete.length());
        }
        String[] partsPredicates = predicateStructure.split(";");
        String currPred = "";
        Integer currPredID = 0;
        for (int j = 0; j < partsPredicates.length; j++) {
            // count if predicate is repeated several times
            int numRepeatedPredicates = StringUtils.countMatches(partsPredicates[j], ",");
            currPred = partsPredicates[j];

            if (numRepeatedPredicates > 0) {
                currPred = partsPredicates[j].substring(0, partsPredicates[j].indexOf(','));
            }
            currPredID = Integer.decode(currPred);
            // store predicate ID and number of repetitions
            listPredsinStructure.add(currPredID);
            listPredsinStructure.add(numRepeatedPredicates + 1); // +1 to count the initial triple (without ',').
        }

        mol.addNewStructure(tempIDStructure, listPredsinStructure, allObjectsDiscrete); // add new string structure
    }

    currentBlock.processMolecule(mol);
}

From source file:ispyb.client.common.shipping.UploadShipmentAction.java

/**
 * DownloadFile//from   w w  w  . j a v a2s .  c  o  m
 * 
 * @param mapping
 * @param actForm
 * @param request
 * @param response
 * @return
 */
public ActionForward DownloadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse response) {

    ActionMessages errors = new ActionMessages();
    String fileType = request.getParameter(Constants.TEMPLATE_FILE_TYPE);

    if (fileType == null)
        fileType = this.mFileType;
    try {
        String targetUpload = new String("");
        String attachmentFilename = new String("");
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_TEMPLATE)) {
            targetUpload = Constants.TEMPLATE_RELATIVE_PATH;
            targetUpload = request.getRealPath(targetUpload);
            attachmentFilename = Constants.TEMPLATE_XLS_FILENAME;
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_ADVANCED)) {
            targetUpload = PopulateTemplate(request, true, false, true, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, true, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_EXPORT_SHIPPING)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_FROM_SHIPMENT)) {
            Integer _shippingId = Integer.decode(request.getParameter(Constants.SHIPPING_ID));
            int shippingId = (_shippingId != null) ? _shippingId.intValue() : 0;
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, true,
                    shippingId);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, true,
                    shippingId);
        }

        try {

            byte[] imageBytes = FileUtil.readBytes(targetUpload);
            response.setContentLength(imageBytes.length);
            ServletOutputStream out = response.getOutputStream();
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=0");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

            out.write(imageBytes);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
        LOG.error(e.toString());
        saveErrors(request, errors);
        return mapping.findForward("error");
    }

    return null;
}

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

/**
 * Replace the specified parameters from the submitted parameters and then execute the filter  
 * The filter can be an encoded query a saved query (directly executed or after a possible instant modification) 
 * @return/*from w  ww  . jav  a  2 s. c  o m*/
 */
public String replaceSubmittedParameters() {
    FilterUpperTO originalFilterUpperTO = null;
    QNode rootNodeOriginal = null;
    if (query != null && query.length() > 0) {
        //parameters for encoded query URL
        String linkReport = ReportQueryBL.b(query);
        Map<String, String> queryEncodedMap = ReportQueryBL.decodeMapFromUrl(linkReport);
        String queryIDStr = queryEncodedMap.get("queryID");
        Integer filterID = null;
        if (queryIDStr != null) {
            filterID = Integer.decode(queryIDStr);
            if (filterID != null) {
                TQueryRepositoryBean queryRepositoryBean = (TQueryRepositoryBean) TreeFilterFacade.getInstance()
                        .getByKey(filterID);
                if (queryRepositoryBean != null) {
                    String filterExpression = FilterBL.getFilterExpression(queryRepositoryBean);
                    HttpServletRequest request = null;
                    QNode extendedRootNode = TreeFilterReader.getInstance().readQueryTree(filterExpression);
                    originalFilterUpperTO = FilterUpperFromQNodeTransformer
                            .getFilterSelectsFromTree(extendedRootNode, true, true, personBean, locale, true);
                    rootNodeOriginal = TreeFilterLoaderBL.getOriginalTree(extendedRootNode);
                    if (FilterSelectsParametersUtil.containsParameter(originalFilterUpperTO)) {
                        //set the request 
                        request = ServletActionContext.getRequest();
                        //replace the corresponding query parameters with corresponding request parameters 
                        try {
                            FilterSelectsParametersUtil.replaceFilterSelectsParameters(originalFilterUpperTO,
                                    request, personBean, locale, false);
                        } catch (NotExistingBeanException e) {
                        }
                    }
                }
            }
        }
    } else {
        if (filterID == null) {
            //from an eventually "instantly" modified filter (put into the session in the FilterAction)
            originalFilterUpperTO = (FilterUpperTO) session.get(FILTER_UPPER_WITH_PARAM);
            rootNodeOriginal = (QNode) session.get(TREE_WITH_PARAM);
        } else {
            //directly executed (not opened for edit)
            FilterFacade filterFacade = TreeFilterFacade.getInstance();
            TQueryRepositoryBean queryRepositoryBean = (TQueryRepositoryBean) filterFacade.getByKey(filterID);
            if (queryRepositoryBean != null) {
                String filterExpression = FilterBL.getFilterExpression(queryRepositoryBean);
                QNode extendedRootNode = TreeFilterReader.getInstance().readQueryTree(filterExpression);
                originalFilterUpperTO = FilterUpperFromQNodeTransformer
                        .getFilterSelectsFromTree(extendedRootNode, true, true, personBean, locale, true);
                rootNodeOriginal = TreeFilterLoaderBL.getOriginalTree(extendedRootNode);
            }
        }
    }
    if (originalFilterUpperTO == null && rootNodeOriginal == null) {
        //no parameters at all. Should never happen
        return null;
    }
    if (originalFilterUpperTO == null) {
        //in the original upper part was nothing selected.
        originalFilterUpperTO = new FilterUpperTO();
    }
    if (filterUpperTO == null) {
        //nothing was submitted to parameterized selects (or none of the selects were parameterized)
        filterUpperTO = new FilterUpperTO();
    }
    //1. replace the upper select parameters  
    FilterUpperTO replacedFilterSelectsTO = FilterSelectsParametersUtil.replaceParameters(originalFilterUpperTO,
            filterUpperTO, locale);

    //2. replace the matchers and values in FieldExpressionSimple fields
    List<FieldExpressionSimpleTO> originalFieldExpressionSimpleList = originalFilterUpperTO
            .getFieldExpressionSimpleList();
    List<FieldExpressionSimpleTO> parameterizedFieldExpressionSimpleList = FilterSubmitHandler
            .createFieldExpressionSimpleListAfterSubmit(simpleMatcherRelationMap, simpleDisplayValueMap,
                    locale);
    Map<Integer, FieldExpressionSimpleTO> fieldBasedFieldExpressionSimpleMap = new HashMap<Integer, FieldExpressionSimpleTO>();
    for (FieldExpressionSimpleTO fieldExpressionSimpleTO : parameterizedFieldExpressionSimpleList) {
        Integer fieldID = fieldExpressionSimpleTO.getField();
        fieldBasedFieldExpressionSimpleMap.put(fieldID, fieldExpressionSimpleTO);
    }
    if (originalFieldExpressionSimpleList != null) {
        for (FieldExpressionSimpleTO fieldExpressionSimpleTO : originalFieldExpressionSimpleList) {
            Integer fieldID = fieldExpressionSimpleTO.getField();
            Integer matcherID = fieldExpressionSimpleTO.getSelectedMatcher();
            if (fieldID != null && matcherID != null && matcherID.equals(MatcherContext.PARAMETER)) {
                FieldExpressionSimpleTO parameterFieldExpressionSimpleTO = fieldBasedFieldExpressionSimpleMap
                        .get(fieldID);
                if (parameterFieldExpressionSimpleTO != null) {
                    fieldExpressionSimpleTO
                            .setSelectedMatcher(parameterFieldExpressionSimpleTO.getSelectedMatcher());
                    fieldExpressionSimpleTO.setValue(parameterFieldExpressionSimpleTO.getValue());
                }
            }
        }
    }
    //3. replace the matchers and values in the tree part
    List<FieldExpressionSimpleTO> treePartFieldExpressionSimpleList = FilterSubmitHandler
            .createFieldExpressionSimpleListAfterSubmit(fieldMap, inTreeMatcherRelationMap,
                    inTreeDisplayValueMap, locale);
    QNode replacedTree = QNodeParametersUtil.replaceParameters(rootNodeOriginal,
            treePartFieldExpressionSimpleList);
    String filterExpression = null;
    try {
        QNode extendedNode = TreeFilterSaverBL.createQNodeWithQueryListsTO(replacedTree,
                replacedFilterSelectsTO, null);
        filterExpression = TreeFilterWriter.getInstance().toXML(extendedNode);
    } catch (Exception e) {
        String errorKey = e.getMessage();
        String errorMessage = LocalizeUtil.getLocalizedTextFromApplicationResources(errorKey, locale);
        LOGGER.warn("Transforming the instant query to expression failed with " + errorMessage);
    }
    QueryContext queryContext = new QueryContext();
    //although a parameterized filter is a saved filter, it is saved in QueryContext as INSTANT_REPORT_FILTER 
    //independently whether it was executed from edit mode (possibly "instantly" modified)  
    //or directly because the parameters have to be replaced anyway and then the resulting expression should be saved in QueryContext   
    queryContext.setQueryType(ItemNavigatorBL.QUERY_TYPE.INSTANT);
    queryContext.setQueryID(TQueryRepositoryBean.QUERY_PURPOSE.TREE_FILTER);
    queryContext.setFilterExpression(filterExpression);
    LastExecutedBL.storeLastExecutedQuery(personBean.getObjectID(), queryContext);
    if (ajax) {
        JSONUtility.encodeJSONSuccess(servletResponse);
        return null;
    } else {
        return "itemNavigator";
    }
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

protected String processResponseData(byte[] data) throws Exception {

    char START_MESSAGE, END_MESSAGE, END_OF_RECORD, END_OF_SEGMENT;

    if (connector.getCharEncoding().equals("hex")) {
        START_MESSAGE = (char) Integer.decode(connector.getMessageStart()).intValue();
        END_MESSAGE = (char) Integer.decode(connector.getMessageEnd()).intValue();
        END_OF_RECORD = (char) Integer.decode(connector.getRecordSeparator()).intValue();
        END_OF_SEGMENT = (char) Integer.decode(connector.getSegmentEnd()).intValue();
    } else {//from w w w .  j a v a 2s .  c  om
        START_MESSAGE = connector.getMessageStart().charAt(0);
        END_MESSAGE = connector.getMessageEnd().charAt(0);
        END_OF_RECORD = connector.getRecordSeparator().charAt(0);
        END_OF_SEGMENT = connector.getSegmentEnd().charAt(0);
    }

    // The next lines, removes any '\n' (decimal code 10 or 0x0A) in the
    // message
    byte[] bites = data;
    int destPointer = 0, srcPointer = 0;
    for (destPointer = 0, srcPointer = 0; srcPointer < bites.length; srcPointer++) {
        if (bites[srcPointer] != 10) {
            bites[destPointer] = bites[srcPointer];
            destPointer++;
        }
    }
    data = bites;
    // ast: use the user's encoding
    String str_data = new String(data, 0, destPointer, connector.getCharsetEncoding());

    BatchMessageProcessor batchProcessor = new BatchMessageProcessor();
    batchProcessor.setEndOfMessage((byte) END_MESSAGE);
    batchProcessor.setStartOfMessage((byte) START_MESSAGE);
    batchProcessor.setEndOfRecord((byte) END_OF_RECORD);
    Iterator<String> it = batchProcessor.processHL7Messages(str_data).iterator();
    if (it.hasNext()) {
        data = (it.next()).getBytes();
        return new String(data);
    }
    return null;
}

From source file:org.kchine.r.server.http.RHttpProxy.java

public static SpreadsheetModelDevice newSpreadsheetModelDevice(String url, String sessionId, String id,
        String rowcount, String colcount) throws TunnelingException {
    GetMethod getNewDevice = null;/*from  w  w w. ja  va 2 s .c  o  m*/
    try {
        Object result = null;
        mainHttpClient = new HttpClient();
        if (System.getProperty("proxy_host") != null && !System.getProperty("proxy_host").equals("")) {
            mainHttpClient.getHostConfiguration().setProxy(System.getProperty("proxy_host"),
                    Integer.decode(System.getProperty("proxy_port")));
        }
        getNewDevice = new GetMethod(url + "?method=newspreadsheetmodeldevice&id=" + id + "&rowcount="
                + rowcount + "&colcount=" + colcount);

        try {
            if (sessionId != null && !sessionId.equals("")) {
                getNewDevice.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
                getNewDevice.setRequestHeader("Cookie", "JSESSIONID=" + sessionId);
            }
            mainHttpClient.executeMethod(getNewDevice);
            result = new ObjectInputStream(getNewDevice.getResponseBodyAsStream()).readObject();
        } catch (ConnectException e) {
            throw new ConnectionFailedException();
        } catch (Exception e) {
            throw new TunnelingException("", e);
        }
        if (result != null && result instanceof TunnelingException) {
            throw (TunnelingException) result;
        }

        String deviceName = (String) result;
        return (SpreadsheetModelDevice) RHttpProxy.getDynamicProxy(url, sessionId, deviceName,
                new Class[] { SpreadsheetModelDevice.class },
                new HttpClient(new MultiThreadedHttpConnectionManager()));

    } finally {
        if (getNewDevice != null) {
            getNewDevice.releaseConnection();
        }
        if (mainHttpClient != null) {
        }
    }
}

From source file:org.rdfhdt.hdt.impl.BufferedCompressedStreaming.java

/**
 * Process a molecule, i.e., set of triples around a common element (typically a subject)
 * /*from   w ww .j  a  va  2s  . c  o  m*/
 * @param elements
 */
public void processMolecule(ArrayList<TripleString> elements) {
    int tempIDSubject = 0;
    int tempIDPredicate = 0;
    int tempIDObject = 0;
    int tempIDStructure = 0;

    String subject = (String) elements.get(0).getSubject(); // could also be passed by argument
    Molecule mol = new Molecule();

    if (!store_subj_dictionary) {
        // check prefix and replace it if present
        Entry<String, Integer> entry = prefixes.getEntryShared(subject);
        if (entry != null) { // put only suffix
            mol.newSubject_prefix = entry.getValue();
            mol.newSubject = subject.substring(entry.getKey().length());
        } else {
            mol.newSubject_prefix = 0;
            mol.newSubject = subject;
        }
    } else { // store subject dictionary
        // Convert Subject-String to Subject-ID
        if (subjects.containsKey(subject)) {
            tempIDSubject = subjects.get(subject);
        } else {
            try {
                tempIDSubject = subjects.insert(subject);
            } catch (DictionaryException e) {
                System.err.println("LRU Dictionary exception");
                e.printStackTrace();
            }
            if (usePrefixes) {
                // check prefix and replace it if present
                Entry<String, Integer> entry = prefixes.getEntryShared(subject);

                if (entry != null) { // put only suffix
                    mol.newSubject_prefix = entry.getValue();
                    mol.newSubject = subject.substring(entry.getKey().length());
                } else {
                    mol.newSubject_prefix = 0;
                    mol.newSubject = subject;

                }
            } else {
                mol.newSubject_prefix = -1;
            }
        }
        // set molecule subject
        mol.subject = tempIDSubject;
    }

    String predicateStructure = "";
    String objectsDiscrete = "";
    Integer currPredicate = -1;

    Boolean isDiscretePredicate = false;
    String obj = "";
    for (int i = 0; i < elements.size(); i++) {

        obj = elements.get(i).getObject().toString();
        isDiscretePredicate = predicateDiscrete.get(elements.get(i).getPredicate().toString());
        if (predicates.containsKey(elements.get(i).getPredicate().toString())) {
            tempIDPredicate = predicates.get(elements.get(i).getPredicate().toString());
            // check dictionary of objects for this predicate

            // check discrete predicate
            if (isDiscretePredicate == null) {

                tempDictionary = objects.get(predicates.get(elements.get(i).getPredicate()) - 1);

                if (tempDictionary.containsKey(obj)) {
                    tempIDObject = tempDictionary.get(obj);
                    try {

                        mol.addObject(tempIDPredicate, tempIDObject);
                    } catch (BlockException e) {
                        System.err.println("Block exception");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        tempIDObject = tempDictionary.insert(obj);

                        // erase object suffix
                        obj = elements.get(i).getObject().toString();

                        if (predicateLiterals.get(tempIDPredicate - 1)) {
                            // offset_tag=1 by default or it is =0 if disabled_consistent_predicates=true
                            obj = obj.substring(offset_tag,
                                    obj.length() - sizeofTags.get(tempIDPredicate - 1) - offset_tag);

                            mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                        } else {
                            if (usePrefixes) {
                                // replace predicate of URI
                                Integer newPreffixURI = 0;
                                // check prefix
                                Entry<String, Integer> entry = prefixes.getEntryShared(obj);

                                if (entry != null) { // put only suffix
                                    newPreffixURI = entry.getValue();
                                    obj = obj.substring(entry.getKey().length());
                                }
                                mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                            } else {
                                mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj);
                            }
                        }

                    } catch (DictionaryException e) {
                        System.err.println("LRU Dictionary exception");
                        e.printStackTrace();
                    } catch (BlockException e) {
                        System.err.println("Block exception");
                        e.printStackTrace();
                    }
                }

            }

        } else {
            // insert new Predicate and create LRUDictionary for it
            tempIDPredicate = predicates.size() + 1;
            predicates.put(elements.get(i).getPredicate().toString(), predicates.size() + 1);
            LRUDictionary<String, Integer> newObjects = new LRUDictionary<String, Integer>(
                    CSVocabulary.DEFAULT_MAX_SIZE_DICTIONARY);
            // store the literal tag if present

            String tag = "";
            Boolean isliteral = false;
            Boolean detectedType = false;

            // check discrete predicate
            if (isDiscretePredicate == null) {

                if (!disable_consistent_predicates) {

                    if (obj.charAt(0) == '"') {
                        isliteral = true;

                        int pos_end = obj.lastIndexOf('"'); // tag after last '"'
                        if (obj.length() > (pos_end + 1)) {
                            tag = obj.substring(pos_end + 1);
                            obj = obj.substring(1, pos_end); // replace obj erasing tag

                        } else {
                            obj = obj.substring(1, pos_end); // replace obj erasing '"'
                            // trying to infer embedded tag before last '"'
                            int pos_tag = obj.indexOf("^^");
                            if (pos_tag > 0) {
                                tag = obj.substring(pos_tag) + '"'; // we maintain the last quote to distinguish the inference
                                obj = obj.substring(0, pos_tag); // replace obj erasing quotes '"'

                                detectedType = true;

                            }

                        }
                    }

                } else {
                    isliteral = true; // consider all literals to avoid change much code
                }

                predicateLiterals.set(tempIDPredicate - 1, isliteral);
                literalTagsByPredicate.add(tag); // set tag TODO it could be not needed, the sizeofTags is used instead.
                if (detectedType == false) {
                    sizeofTags.add(tag.length());

                } else {
                    sizeofTags.add(tag.length() - 1); // speed up processing for replacing, -1 to erase last quote character
                }

                try {
                    // replace erasing tags
                    tempIDObject = newObjects.insert(obj);

                    objects.add(newObjects);

                    mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral,
                            tag);

                    if (isliteral) {
                        mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                    } else {
                        // check prefix
                        Entry<String, Integer> entry = prefixes.getEntryShared(obj);
                        Integer newPreffixURI = 0;
                        if (entry != null) { // put only suffix
                            newPreffixURI = entry.getValue();
                            obj = obj.substring(entry.getKey().length());
                        }
                        mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                    }
                } catch (DictionaryException e) {
                    System.err.println("LRU Dictionary exception");
                    e.printStackTrace();
                } catch (BlockException e) {
                    System.err.println("Block exception");
                    e.printStackTrace();
                }
            } else {
                // insert void properties: a void dictionary of objects andno tags
                objects.add(newObjects);
                sizeofTags.add(0);
                isliteral = (obj.charAt(0) == '"');
                mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral, "");
            }

        }
        if (currPredicate != tempIDPredicate) {
            if (currPredicate == -1) // first
                predicateStructure += tempIDPredicate;
            else
                predicateStructure += ";" + tempIDPredicate;
        } else {

            predicateStructure += ",";

        }
        // check discrete predicate and append objects
        if (isDiscretePredicate != null) {
            objectsDiscrete = objectsDiscrete + "$" + obj;
        }
        currPredicate = tempIDPredicate;

    }
    predicateStructure = predicateStructure + objectsDiscrete;
    // Insert structure
    if (structures.containsKey(predicateStructure)) {
        tempIDStructure = structures.get(predicateStructure);

        mol.addStructure(tempIDStructure); // add structure of the molecule
    } else {
        try {
            tempIDStructure = structures.insert(predicateStructure);

        } catch (DictionaryException e) {
            System.err.println("LRU Dictionary exception");
            e.printStackTrace();
        }

        // store new structure in compact way (list of predicate-ID and its
        // repetitions and objects discrete
        ArrayList<Integer> listPredsinStructure = new ArrayList<Integer>(5);
        ArrayList<String> allObjectsDiscrete = null;
        if (objectsDiscrete != "") {
            allObjectsDiscrete = new ArrayList<String>(Arrays.asList(objectsDiscrete.split("\\$")));
            allObjectsDiscrete.remove(0); // erase first void element

            predicateStructure = predicateStructure.substring(0,
                    predicateStructure.length() - objectsDiscrete.length());
        }
        String[] partsPredicates = predicateStructure.split(";");
        String currPred = "";
        Integer currPredID = 0;
        for (int j = 0; j < partsPredicates.length; j++) {
            // count if predicate is repeated several times
            int numRepeatedPredicates = StringUtils.countMatches(partsPredicates[j], ",");
            currPred = partsPredicates[j];

            if (numRepeatedPredicates > 0) {
                currPred = partsPredicates[j].substring(0, partsPredicates[j].indexOf(','));
            }
            currPredID = Integer.decode(currPred);
            // store predicate ID and number of repetitions
            listPredsinStructure.add(currPredID);
            listPredsinStructure.add(numRepeatedPredicates + 1); // +1 to count the initial triple (without ',').
        }

        mol.addNewStructure(tempIDStructure, listPredsinStructure, allObjectsDiscrete); // add new string structure
    }

    currentBlock.processMolecule(mol);
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.StackedBarGroup.java

/**
 * Inherited by IChart.//w w  w . j a v  a  2s  . c  o m
 * 
 * @param chartTitle the chart title
 * @param dataset the dataset
 * 
 * @return the j free chart
 */

public JFreeChart createChart(DatasetMap datasets) {

    logger.debug("IN");
    CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1");

    logger.debug("Get plot orientaton");
    PlotOrientation plotOrientation = PlotOrientation.VERTICAL;
    if (horizontalView) {
        plotOrientation = PlotOrientation.HORIZONTAL;
    }

    JFreeChart chart = ChartFactory.createStackedBarChart(name, // chart title
            categoryLabel, // domain axis label
            valueLabel, // range axis label
            dataset, // data
            plotOrientation, // the plot orientation
            legend, // legend
            true, // tooltips
            false // urls
    );

    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(color);
    plot.setRangeGridlinePaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);

    GroupedStackedBarRenderer renderer = new GroupedStackedBarRenderer();
    KeyToGroupMap map = new KeyToGroupMap("G1");
    int numElForGroup = 0;
    for (int idx = 0; idx < numGroups.intValue(); idx++) {
        for (int j = 0; j < numSerieForGroup.intValue(); j++) {
            try {
                String tmpSubCat = (String) subCategoryNames.get(j + idx * numSerieForGroup.intValue());
                map.mapKeyToGroup(tmpSubCat, "G" + (idx + 1));

            } catch (Exception e) {
                logger.error("out of range error in inserting in stacked bar group: continue anayway", e);
            }
        }
    }

    renderer.setSeriesToGroupMap(map);
    renderer.setItemMargin(0.0);
    renderer.setDrawBarOutline(false);
    renderer.setBaseItemLabelsVisible(true);
    if (percentageValue)
        renderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("#,##.#%")));
    else
        renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

    if (maxBarWidth != null) {
        renderer.setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    boolean document_composition = false;
    if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
        document_composition = true;

    /*
    MyCategoryUrlGenerator mycatUrl=new MyCategoryUrlGenerator(rootUrl);
    mycatUrl.setDocument_composition(document_composition);
    mycatUrl.setCategoryUrlLabel(categoryUrlName);
    mycatUrl.setSerieUrlLabel(serieUrlname);
            
    renderer.setItemURLGenerator(mycatUrl);
     */

    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    chart.setBackgroundPaint(color);

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setNumberFormatOverride(nf);
    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }
    if (rangeAxisLocation != null) {
        if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);
        } else if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
        }
    }

    int seriesN = dataset.getRowCount();
    int numSerieColored = 0;

    if (orderColorVector != null && orderColorVector.size() > 0) {
        logger.debug("color serie by SERIES_ORDER_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            if (orderColorVector.get(i) != null) {
                Color color = orderColorVector.get(i);
                renderer.setSeriesPaint(i, color);
            }
        }
    } else if (colorMap != null) {
        while (numSerieColored < seriesN) {
            for (int i = 1; i <= colorMap.size(); i++) {
                Color color = (Color) colorMap.get("SER" + i);
                Color gradient = new Color(Integer.decode("#FFFFFF").intValue());
                if (gradientMap != null)
                    gradient = (Color) gradientMap.get("SER" + i);

                if (color != null) {
                    Paint p = new GradientPaint(0.0f, 0.0f, color, 0.0f, 0.0f, gradient);

                    //renderer.setSeriesPaint(numSerieColored, color);
                    renderer.setSeriesPaint(numSerieColored, p);
                }
                numSerieColored++;
            }
        }
    }
    renderer.setGradientPaintTransformer(
            new StandardGradientPaintTransformer(GradientPaintTransformType.HORIZONTAL));

    MyStandardCategoryItemLabelGenerator generator = null;
    if (additionalLabels) {
        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());

        double orient = (-Math.PI / 2.0);
        if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
            orient = 0.0;
        }
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        renderer.setBaseItemLabelGenerator(generator);
        renderer.setBaseItemLabelsVisible(true);
        //vertical labels          
        renderer.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        renderer.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient));

        //horizontal labels
        /*
        renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
           ItemLabelAnchor.CENTER, TextAnchor.CENTER));
        renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
           ItemLabelAnchor.CENTER, TextAnchor.CENTER));
         */

    }

    SubCategoryAxis domainAxis = new SubCategoryAxis(categoryLabel + " / " + subCategoryLabel);
    String subCatLabel = "";
    for (int j = 1; j <= numGroups.intValue(); j++) {
        if (subCatLabelsMap != null)
            subCatLabel = (String) subCatLabelsMap.get("CAT" + j);
        else
            subCatLabel = subCategoryLabel;

        domainAxis.addSubCategory(subCatLabel);
        domainAxis
                .setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
        domainAxis.setLabelPaint(styleYaxesLabels.getColor());
        domainAxis.setTickLabelFont(
                new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
        domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());
    }
    plot.setDomainAxis(domainAxis);
    plot.setRenderer(renderer);

    /*
    domainAxis.setCategoryLabelPositions(
    CategoryLabelPositions.createUpRotationLabelPositions(
          Math.PI / 6.0));
     */
    if (legend == true)
        drawLegend(chart);
    logger.debug("OUT");
    return chart;

}