Example usage for java.lang StringBuffer indexOf

List of usage examples for java.lang StringBuffer indexOf

Introduction

In this page you can find the example usage for java.lang StringBuffer indexOf.

Prototype

@Override
public int indexOf(String str) 

Source Link

Usage

From source file:org.pentaho.di.core.Const.java

/**
 * Replaces environment variables in a string. For example if you set KETTLE_HOME as an environment variable, you can
 * use %%KETTLE_HOME%% in dialogs etc. to refer to this value. This procedures looks for %%...%% pairs and replaces
 * them including the name of the environment variable with the actual value. In case the variable was not set,
 * nothing is replaced!//from  w w w.  j a v  a 2s  . c om
 *
 * @param string
 *          The source string where text is going to be replaced.
 *
 * @return The expanded string.
 * @deprecated use StringUtil.environmentSubstitute(): handles both Windows and unix conventions
 */
@Deprecated
public static final String replEnv(String string) {
    if (string == null) {
        return null;
    }
    StringBuffer str = new StringBuffer(string);

    int idx = str.indexOf("%%");
    while (idx >= 0) {
        // OK, so we found a marker, look for the next one...
        int to = str.indexOf("%%", idx + 2);
        if (to >= 0) {
            // OK, we found the other marker also...
            String marker = str.substring(idx, to + 2);
            String var = str.substring(idx + 2, to);

            if (var != null && var.length() > 0) {
                // Get the environment variable
                String newval = getEnvironmentVariable(var, null);

                if (newval != null) {
                    // Replace the whole bunch
                    str.replace(idx, to + 2, newval);
                    // System.out.println("Replaced ["+marker+"] with ["+newval+"]");

                    // The last position has changed...
                    to += newval.length() - marker.length();
                }
            }

        } else {
            // We found the start, but NOT the ending %% without closing %%
            to = idx;
        }

        // Look for the next variable to replace...
        idx = str.indexOf("%%", to + 1);
    }

    return str.toString();
}

From source file:org.infoglue.deliver.invokers.PageInvoker.java

private void generateExtensionBundles(Map<String, Set<String>> extensionBundles, String contentType,
        String targetElement) {/* w w w  .  java  2  s.c o m*/
    Timer t = new Timer();

    Set<String> bundledSignatures = new HashSet<String>();

    Iterator<String> scriptExtensionBundlesIterator = extensionBundles.keySet().iterator();
    while (scriptExtensionBundlesIterator.hasNext()) {
        String bundleName = scriptExtensionBundlesIterator.next();
        if (logger.isInfoEnabled())
            logger.info("bundleName:" + bundleName);

        Set<String> scriptExtensionFileNames = extensionBundles.get(bundleName);

        if (scriptExtensionFileNames != null && scriptExtensionFileNames.size() > 0) {
            String scriptBundle = "";

            int i = 0;
            String filePath = CmsPropertyHandler.getDigitalAssetPath0();
            while (filePath != null) {
                try {
                    File extensionsDirectory = new File(filePath + File.separator + "extensions");
                    extensionsDirectory.mkdirs();

                    File extensionsBundleFile = new File(
                            filePath + File.separator + "extensions" + File.separator + bundleName + ".js");
                    if (contentType.equalsIgnoreCase("text/css"))
                        extensionsBundleFile = new File(filePath + File.separator + "extensions"
                                + File.separator + bundleName + ".css");

                    if (!extensionsBundleFile.exists()) {
                        if (logger.isInfoEnabled())
                            logger.info("No script - generating:" + bundleName);
                        if (scriptBundle.equals("")) {
                            Iterator<String> scriptExtensionFileNamesIterator = scriptExtensionFileNames
                                    .iterator();
                            while (scriptExtensionFileNamesIterator.hasNext()) {
                                String scriptExtensionFileName = scriptExtensionFileNamesIterator.next();
                                if (logger.isInfoEnabled())
                                    logger.info("scriptExtensionFileName:" + scriptExtensionFileName);
                                try {
                                    File file = new File(filePath + File.separator + scriptExtensionFileName);
                                    String signature = "" + file.getName() + "_" + file.length();
                                    if (logger.isInfoEnabled())
                                        logger.info("Checking file:" + filePath + File.separator
                                                + scriptExtensionFileName);

                                    if (file.exists() && !bundledSignatures.contains(signature)) {
                                        StringBuffer content = new StringBuffer(
                                                FileHelper.getFileAsStringOpt(file));
                                        //Wonder what is the best signature..
                                        bundledSignatures.add(signature);

                                        //If CSS we should change url:s to point to the original folder
                                        if (contentType.equalsIgnoreCase("text/css")) {
                                            if (logger.isInfoEnabled())
                                                logger.info("contentType:" + contentType);
                                            String extensionPath = file.getPath().substring(
                                                    extensionsDirectory.getPath().length() + 1,
                                                    file.getPath().lastIndexOf("/") + 1);
                                            if (logger.isInfoEnabled())
                                                logger.info("extensionPath:" + extensionPath);

                                            int urlStartIndex = content.indexOf("url(");
                                            while (urlStartIndex > -1) {
                                                if (content.charAt(urlStartIndex + 4) == '"'
                                                        || content.charAt(urlStartIndex + 4) == '\'')
                                                    content.insert(urlStartIndex + 5, extensionPath);
                                                else
                                                    content.insert(urlStartIndex + 4, extensionPath);
                                                urlStartIndex = content.indexOf("url(",
                                                        urlStartIndex + extensionPath.length());
                                            }
                                        }
                                        //logger.info("transformed content:" + content.substring(0, 500));

                                        scriptBundle = scriptBundle + "\n\n" + content;
                                    } else {
                                        if (logger.isInfoEnabled())
                                            logger.info("Not adding:" + signature + " as " + file.exists() + ":"
                                                    + bundledSignatures.contains(signature));
                                    }
                                } catch (Exception e) {
                                    logger.warn("Error trying to parse file and bundle it ("
                                            + scriptExtensionFileName + "):" + e.getMessage());
                                }
                            }
                        }

                        if (logger.isInfoEnabled())
                            logger.info("scriptBundle:" + scriptBundle.length());
                        if (scriptBundle != null && !scriptBundle.equals("")) {
                            if (contentType.equalsIgnoreCase("text/javascript")) {
                                try {
                                    JSMin jsmin = new JSMin(new ByteArrayInputStream(scriptBundle.getBytes()),
                                            new FileOutputStream(extensionsBundleFile));
                                    jsmin.jsmin();
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                FileHelper.writeToFile(extensionsBundleFile, scriptBundle, false);
                            }
                            if (logger.isInfoEnabled())
                                logger.info("extensionsBundleFile:" + extensionsBundleFile.length());
                        }
                    }

                    i++;
                    filePath = CmsPropertyHandler.getProperty("digitalAssetPath." + i);
                } catch (Exception e) {
                    logger.warn("Error trying to write bundled scripts:" + e.getMessage());
                }
            }
            try {
                SiteNodeVO siteNodeVO = NodeDeliveryController.getNodeDeliveryController(deliveryContext)
                        .getSiteNodeVO(getDatabase(), getTemplateController().getSiteNodeId());
                String dnsName = CmsPropertyHandler.getWebServerAddress();
                if (siteNodeVO != null) {
                    RepositoryVO repositoryVO = RepositoryController.getController()
                            .getRepositoryVOWithId(siteNodeVO.getRepositoryId(), getDatabase());
                    if (repositoryVO.getDnsName() != null && !repositoryVO.getDnsName().equals(""))
                        dnsName = repositoryVO.getDnsName();
                }

                String bundleUrl = "";
                String bundleUrlTag = "";

                if (contentType.equalsIgnoreCase("text/javascript")) {
                    bundleUrl = URLComposer.getURLComposer().composeDigitalAssetUrl(dnsName, "extensions",
                            bundleName + ".js", deliveryContext);
                    bundleUrlTag = "<script type=\"text/javascript\" src=\"" + bundleUrl + "\"></script>";
                } else if (contentType.equalsIgnoreCase("text/css")) {
                    bundleUrl = URLComposer.getURLComposer().composeDigitalAssetUrl(dnsName, "extensions",
                            bundleName + ".css", deliveryContext);
                    bundleUrlTag = "<link href=\"" + bundleUrl + "\" rel=\"stylesheet\" type=\"text/css\" />";
                }

                if (targetElement.equalsIgnoreCase("head"))
                    this.getTemplateController().getDeliveryContext().getHtmlHeadItems().add(bundleUrlTag);
                else
                    this.getTemplateController().getDeliveryContext().getHtmlBodyEndItems().add(bundleUrlTag);
            } catch (Exception e) {
                logger.warn("Error trying  get assetBaseUrl:" + e.getMessage());
            }
        }

    }
    if (logger.isInfoEnabled())
        t.printElapsedTime("Generating bundles took");
}

From source file:com.lp.server.artikel.fastlanereader.ArtikellisteHandler.java

/**
 * builds the HQL (Hibernate Query Language) order by clause using the sort
 * criterias contained in the current query.
 * //  w  w w  .ja v a2  s  . co  m
 * @return the HQL order by clause.
 */
private String buildOrderByClause() {
    StringBuffer orderBy = new StringBuffer("");
    if (getQuery() != null) {
        SortierKriterium[] kriterien = getQuery().getSortKrit();
        boolean sortAdded = false;
        if (kriterien != null && kriterien.length > 0) {
            for (int i = 0; i < kriterien.length; i++) {
                if (!kriterien[i].kritName.endsWith(Facade.NICHT_SORTIERBAR)) {
                    if (kriterien[i].isKrit) {
                        if (sortAdded) {
                            orderBy.append(", ");
                        }
                        sortAdded = true;
                        orderBy.append(kriterien[i].kritName);
                        orderBy.append(" ");
                        orderBy.append(kriterien[i].value);
                    }
                }
            }
        } else {
            // no sort criteria found, add default sort
            if (sortAdded) {
                orderBy.append(", ");
            }
            orderBy.append("artikelliste.c_nr ASC ");
            sortAdded = true;
        }
        if (orderBy.indexOf("artikelliste.i_id") < 0) {
            // unique sort required because otherwise rowNumber of
            // selectedId
            // within sort() method may be different from the position of
            // selectedId
            // as returned in the page of getPageAt().
            if (sortAdded) {
                orderBy.append(", ");
            }
            orderBy.append(" artikelliste.i_id ");
            sortAdded = true;
        }
        if (sortAdded) {
            orderBy.insert(0, " ORDER BY ");
        }
    }
    return orderBy.toString();
}

From source file:org.pentaho.di.job.entries.dtdvalidator.DTDValidator.java

public boolean validate() {

    boolean retval = false;

    FileObject xmlfile = null;/*  w  w w  .  ja va2s .co  m*/
    FileObject DTDfile = null;

    ByteArrayInputStream ba = null;
    try {
        if (xmlfilename != null && ((getDTDFilename() != null && !isInternDTD()) || (isInternDTD()))) {
            xmlfile = KettleVFS.getFileObject(getXMLFilename());

            if (xmlfile.exists()) {

                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();
                StringBuffer xmlStringbuffer = new StringBuffer("");

                BufferedReader xmlBufferedReader = null;
                InputStreamReader is = null;
                try {
                    // open XML File
                    is = new InputStreamReader(xmlFile.openStream());
                    xmlBufferedReader = new BufferedReader(is);

                    char[] buffertXML = new char[1024];
                    int LenXML = -1;
                    while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1) {
                        xmlStringbuffer.append(buffertXML, 0, LenXML);
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (xmlBufferedReader != null) {
                        xmlBufferedReader.close();
                    }
                }

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding

                DocBuilderFactory.setValidating(false);
                ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8"));
                Document xmlDocDTD = DocBuilder.parse(ba);
                if (ba != null) {
                    ba.close();
                }

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (isInternDTD()) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFound.Label",
                                getXMLFilename()));
                    } else {
                        setErrorMessage(BaseMessages.getString(PKG,
                                "JobEntryDTDValidator.ERRORDTDNotFound.Label", getXMLFilename()));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(getDTDFilename());

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            // String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");
                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(
                                BaseMessages.getString(PKG,
                                        "JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        getDTDFilename()));
                    }
                }

                if (!(isInternDTD() && xmlStartDTD == -1 || (!isInternDTD() && !DTDfile.exists()))) {

                    // Let's parse now ...
                    MyErrorHandler error = new MyErrorHandler();
                    DocBuilderFactory.setValidating(true);
                    DocBuilder = DocBuilderFactory.newDocumentBuilder();
                    DocBuilder.setErrorHandler(error);

                    ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding));
                    xmlDocDTD = DocBuilder.parse(ba);

                    if (error.errorMessage == null) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Label",
                                        getXMLFilename()));

                        // Everything is OK
                        retval = true;
                    } else {
                        // Invalid DTD
                        setNrErrors(error.nrErrors);
                        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorKO",
                                getXMLFilename(), error.nrErrors, error.errorMessage));
                    }
                }

            } else {
                if (!xmlfile.exists()) {
                    setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.FileDoesNotExist.Label",
                            getXMLFilename()));
                }
            }
        } else {
            setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.AllFilesNotNull.Label"));
        }
    } catch (Exception e) {
        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.ErrorDTDValidator.Label",
                getXMLFilename(), getDTDFilename(), e.getMessage()));
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }
            if (DTDfile != null) {
                DTDfile.close();
            }
            if (ba != null) {
                ba.close();
            }
        } catch (IOException e) {
            // Ignore close errors
        }
    }
    return retval;
}

From source file:com.sap.research.connectivity.gw.GWOperationsUtils.java

private void addRelationshipInPersistenceMethods(JavaSourceFileEditor entityClassFile, String nav,
        String javaType, String associationType) {
    // TODO Auto-generated method stub
    ArrayList<JavaSourceMethod> globalMethodList = entityClassFile.getGlobalMethodList();
    String pluralRemoteEntity = GwUtils.getInflectorPlural(entityClassFile.CLASS_NAME, Locale.ENGLISH);
    String smallRemoteEntity = StringUtils.uncapitalize(entityClassFile.CLASS_NAME);

    for (JavaSourceMethod method : globalMethodList) {
        String methodName = method.getMethodName();
        /*//from  w ww.  j a  v  a 2s  .  co  m
         * We insert the relation in the persist and merge methods
         */
        if (methodName.endsWith("persist")) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            methodBody.insert(methodBody.lastIndexOf("newEntity = newEntityRequest"),
                    makeGWPersistRelationshipCode(nav, javaType, associationType, "\t\t"));
            method.setMethodBody(methodBody.toString());
        } else if (methodName.endsWith("merge")) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            methodBody.insert(methodBody.lastIndexOf("boolean modifyRequest = modifyEntityRequest"),
                    makeGWMergeRelationshipCode(nav, javaType, associationType, "\t\t"));
            method.setMethodBody(methodBody.toString());
        }

        /*
         * We insert the relation in the findAll and find<Entity>Entries methods
         */
        else if (methodName.endsWith("findAll" + pluralRemoteEntity)
                || methodName.endsWith("find" + entityClassFile.CLASS_NAME + "Entries")) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            int insertPosition = methodBody.indexOf("} catch (Exception relationshipsException)");
            boolean isFirstManyToMany = true;
            if ("OneToMany ManyToMany".contains(associationType)) {
                String manyToManyInsertReferenceString = StringUtils.uncapitalize(entityClassFile.CLASS_NAME)
                        + "Link.isCollection()) {";
                if (methodBody.indexOf(manyToManyInsertReferenceString) > -1) {
                    insertPosition = methodBody.indexOf(manyToManyInsertReferenceString);
                    isFirstManyToMany = false;
                }
            }
            methodBody.insert(insertPosition,
                    makeGWShowRelationshipCode(entityClassFile.CLASS_NAME, smallRemoteEntity + "Instance",
                            smallRemoteEntity + "Item", ODATA_KEY, nav, javaType, associationType, "\t\t",
                            isFirstManyToMany));
            method.setMethodBody(methodBody.toString());
        }
        /*
         * We insert the relation in the find<Entity> method
         */
        else if (methodName.endsWith("find" + entityClassFile.CLASS_NAME)) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            int insertPosition = methodBody.indexOf("} catch (Exception relationshipsException)");
            boolean isFirstManyToMany = true;
            if ("OneToMany ManyToMany".contains(associationType)) {
                String manyToManyInsertReferenceString = StringUtils.uncapitalize(entityClassFile.CLASS_NAME)
                        + "Link.isCollection()) {";
                if (methodBody.indexOf(manyToManyInsertReferenceString) > -1) {
                    insertPosition = methodBody.indexOf(manyToManyInsertReferenceString);
                    isFirstManyToMany = false;
                }
            }
            methodBody.insert(insertPosition,
                    makeGWShowRelationshipCode(entityClassFile.CLASS_NAME,
                            "virtual" + entityClassFile.CLASS_NAME, smallRemoteEntity,
                            "OEntityKey.parse(" + GwUtils.GW_CONNECTION_FIELD_NAME
                                    + ".getDecodedRemoteKey(Id))",
                            nav, javaType, associationType, "\t\t\t", isFirstManyToMany));
            method.setMethodBody(methodBody.toString());
        }
    }
}

From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java

public String replaceSystemValues(String string, Map beans) {

    StringBuffer buffer = new StringBuffer(string);
    Set beanNames = beans.keySet();
    for (Iterator it = beanNames.iterator(); it.hasNext();) {
        String beanName = (String) it.next();
        // see if the string contains reference(s) to the supported beans
        for (int i = buffer.indexOf(beanName), j = beanName.length(); i != -1; i = buffer.indexOf(beanName)) {
            // if it does, parse the property of the bean the report query references
            int k = buffer.indexOf("}", i + j);
            if (k == -1)
                throw new RuntimeException("Missing closing brace \"}\" in report query: " + string);
            String property = buffer.substring(i + j, k);

            // construct the bean property's corresponding "getter" method
            String getter = null;
            String param = null;/*w  w w .  j a  va 2 s.c o  m*/
            if (beanName.indexOf(".attribute.") != -1) {
                getter = "getAttribute";
                param = property;
            } else if (beanName.indexOf(".property.") != -1) {
                getter = "getProperties";
                param = null;
            } else {
                getter = "get" + Character.toUpperCase(property.charAt(0)) + property.substring(1);
                param = null;
            }

            try {
                // use reflection to invoke the method on the bean
                Object bean = beans.get(beanName);
                Class clasz = bean.getClass();
                Class[] args = param == null ? (Class[]) null : new Class[] { String.class };
                Method method = clasz.getMethod(getter, args);
                Object result = method.invoke(bean, (param == null ? (Object[]) null : new Object[] { param }));

                if (beanName.indexOf(".property.") != -1) {
                    clasz = org.sakaiproject.entity.api.ResourceProperties.class;
                    getter = "getProperty";
                    args = new Class[] { String.class };
                    param = property;
                    method = clasz.getMethod(getter, args);
                    result = method.invoke(result, new Object[] { param });
                }

                // replace the bean expression in the report query with the actual value of calling the bean's corresponding getter method
                buffer.delete(i, k + 1);
                buffer.insert(i,
                        (result == null ? "null"
                                : result instanceof Time ? ((Time) result).toStringSql()
                                        : result.toString().replaceAll("'", "''")));
            } catch (Exception ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            }
        }
    }
    return buffer.toString();
}

From source file:com.isecpartners.gizmo.HttpResponse.java

public void processResponse(InputStream in) throws FailedRequestException {
    StringBuffer content = new StringBuffer();
    DataInputStream inputStream = new DataInputStream(in);
    ArrayByteList blist = new ArrayByteList();
    String header = null;/*www  .j  av a2s .  c  o  m*/
    int contentLength = 0;
    boolean isChunked = false;
    String line;
    try {
        line = readline(inputStream);
        while (line != null && !line.equals(ENDL)) {
            content.append(line);
            if (line.toUpperCase().contains(CONTENT_LENGTH)
                    && line.toUpperCase().indexOf(CONTENT_LENGTH) == 0) {
                String value = line.substring(line.indexOf(CONTENT_LENGTH) + CONTENT_LENGTH.length() + 2,
                        line.indexOf('\r'));
                contentLength = Integer.parseInt(value.trim());
            } else if (line.toUpperCase().contains(TRANSFER_ENCODING)) {
                if (line.toUpperCase()
                        .substring(
                                line.toUpperCase().indexOf(TRANSFER_ENCODING) + "Transfer-Encoding:".length())
                        .contains("CHUNKED")) {
                    isChunked = true;
                }
            } else if (line.toUpperCase().contains(CONTENT_ENCODING)) {
                String value = line.substring(line.indexOf(CONTENT_ENCODING) + CONTENT_ENCODING.length() + 2,
                        line.indexOf('\r'));
                value = value.trim();
                if (value.toUpperCase().equals("GZIP")) {
                    this.gzip = true;
                } else if (value.toUpperCase().equals("DEFLATE")) {
                    this.deflate = true;
                }
            }
            line = readline(inputStream);
        }
        if (line == null) {
            GizmoView.log(content.toString());
            throw new FailedRequestException();
        }

        content.append("\r\n");
        header = content.substring(0, content.indexOf("\r\n"));
        append(blist, content);

        if (contentLength != 0) {
            for (int ii = 0; ii < contentLength; ii++) {
                blist.add(inputStream.readByte());
            }
        }

        if (isChunked) {
            boolean isDone = false;
            while (!isDone) {
                byte current = inputStream.readByte();
                blist.add(current);

                int size = 0;
                while (current != '\n') {
                    if (current != '\r') {
                        size *= 16;
                        if (Character.isLetter((char) current)) {
                            current = (byte) Character.toLowerCase((char) current);
                        }
                        if ((current >= '0') && (current <= '9')) {
                            size += (current - 48);
                        } else if ((current >= 'a') && (current <= 'f')) {
                            size += (10 + current - 97);
                        }
                    }
                    current = inputStream.readByte();

                    while ((char) current == ' ') {
                        current = inputStream.readByte();
                    }
                    blist.add(current);
                }

                if (size != 0) {
                    for (int ii = 0; ii < size; ii++) {
                        int byte1 = inputStream.readByte();
                        byte blah = (byte) byte1;
                        blist.add(blah);
                    }
                    blist.add(inputStream.readByte());
                    blist.add(inputStream.readByte());
                } else {
                    byte ch = (byte) inputStream.read();
                    StringBuffer endstuff = new StringBuffer();
                    blist.add(ch);
                    endstuff.append((char) ch);
                    while (ch != '\n') {
                        ch = inputStream.readByte();
                        endstuff.append((char) ch);
                        blist.add(ch);
                    }

                    isDone = true;
                }

            }
        }

        if (inputStream.available() > 0) {
            try {
                while (true) {
                    blist.add(inputStream.readByte());
                }
            } catch (EOFException e) {
                System.out.println(e);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(HttpResponse.class.getName()).log(Level.SEVERE, null, ex);
    }

    setBlist(blist);
    setHeader(header);
    if (this.gzip) {
        addContents(unzipData(blist.toArray()));
    } else if (this.deflate) {
        addContents(deflateData(blist.toArray()));
    } else {
        addContents(content.toString());
    }
}

From source file:dk.defxws.fedoragsearch.server.Config.java

private void checkConfig() throws ConfigException {

    if (logger.isDebugEnabled())
        logger.debug("fedoragsearch.properties=" + fgsProps.toString());

    //     Check for unknown properties, indicating typos or wrong property names
    String[] propNames = { "fedoragsearch.deployFile", "fedoragsearch.soapBase", "fedoragsearch.soapUser",
            "fedoragsearch.soapPass", "fedoragsearch.defaultNoXslt",
            "fedoragsearch.defaultGfindObjectsRestXslt", "fedoragsearch.defaultUpdateIndexRestXslt",
            "fedoragsearch.defaultBrowseIndexRestXslt", "fedoragsearch.defaultGetRepositoryInfoRestXslt",
            "fedoragsearch.defaultGetIndexInfoRestXslt", "fedoragsearch.mimeTypes", "fedoragsearch.maxPageSize",
            "fedoragsearch.defaultBrowseIndexTermPageSize", "fedoragsearch.defaultGfindObjectsHitPageSize",
            "fedoragsearch.defaultGfindObjectsSnippetsMax", "fedoragsearch.defaultGfindObjectsFieldMaxLength",
            "fedoragsearch.repositoryNames", "fedoragsearch.indexNames", "fedoragsearch.updaterNames",
            "fedoragsearch.searchResultFilteringModule", "fedoragsearch.searchResultFilteringType" };
    //checkPropNames("fedoragsearch.properties", fgsProps, propNames);

    //     Check rest stylesheets
    checkRestStylesheet("fedoragsearch.defaultNoXslt");
    checkRestStylesheet("fedoragsearch.defaultGfindObjectsRestXslt");
    checkRestStylesheet("fedoragsearch.defaultUpdateIndexRestXslt");
    checkRestStylesheet("fedoragsearch.defaultBrowseIndexRestXslt");
    checkRestStylesheet("fedoragsearch.defaultGetRepositoryInfoRestXslt");
    checkRestStylesheet("fedoragsearch.defaultGetIndexInfoRestXslt");

    //     Check mimeTypes  
    checkMimeTypes("fedoragsearch", fgsProps, "fedoragsearch.mimeTypes");

    //     Check resultPage properties
    try {//from w  w  w  . j  a va  2s.  c om
        maxPageSize = Integer.parseInt(fgsProps.getProperty("fedoragsearch.maxPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** maxPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultBrowseIndexTermPageSize = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultBrowseIndexTermPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultBrowseIndexTermPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsHitPageSize = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsHitPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsHitPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsSnippetsMax = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsSnippetsMax"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsSnippetsMax is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsFieldMaxLength = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsFieldMaxLength"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsFieldMaxLength is not valid:\n" + e.toString());
    }

    // Check updater properties
    String updaterProperty = fgsProps.getProperty("fedoragsearch.updaterNames");
    if (updaterProperty == null) {
        updaterNameToProps = null; // No updaters will be created
    } else {
        updaterNameToProps = new Hashtable();
        StringTokenizer updaterNames = new StringTokenizer(updaterProperty);
        while (updaterNames.hasMoreTokens()) {
            String updaterName = updaterNames.nextToken();
            try {
                InputStream propStream = null;
                try {
                    propStream = getResourceInputStream("/updater/" + updaterName + "/updater.properties");
                } catch (ConfigException e) {
                    errors.append("\n" + e.getMessage());
                }
                Properties props = new Properties();
                props.load(propStream);
                propStream.close();

                //MIH
                convertProperties(props);
                if (logger.isInfoEnabled()) {
                    logger.info(
                            configName + "/updater/" + updaterName + "/updater.properties=" + props.toString());
                }

                // Check properties
                String propsNamingFactory = props.getProperty("java.naming.factory.initial");
                String propsProviderUrl = props.getProperty("java.naming.provider.url");
                String propsConnFactory = props.getProperty("connection.factory.name");
                String propsClientId = props.getProperty("client.id");

                if (propsNamingFactory == null) {
                    errors.append("\n*** java.naming.factory.initial not provided in " + configName
                            + "/updater/" + updaterName + "/updater.properties");
                }
                if (propsProviderUrl == null) {
                    errors.append("\n*** java.naming.provider.url not provided in " + configName + "/updater/"
                            + updaterName + "/updater.properties");
                }
                if (propsConnFactory == null) {
                    errors.append("\n*** connection.factory.name not provided in " + configName + "/updater/"
                            + updaterName + "/updater.properties");
                }
                if (propsClientId == null) {
                    errors.append("\n*** client.id not provided in " + configName + "/updater/" + updaterName
                            + "/updater.properties");
                }

                updaterNameToProps.put(updaterName, props);
            } catch (IOException e) {
                errors.append("\n*** Error loading " + configName + "/updater/" + updaterName + ".properties:\n"
                        + e.toString());
            }
        }
    }

    // Check searchResultFilteringModule property
    searchResultFilteringModuleProperty = fgsProps.getProperty("fedoragsearch.searchResultFilteringModule");
    if (searchResultFilteringModuleProperty != null && searchResultFilteringModuleProperty.length() > 0) {
        try {
            getSearchResultFiltering();
        } catch (ConfigException e) {
            errors.append(e.getMessage());
        }
        String searchResultFilteringTypeProperty = fgsProps
                .getProperty("fedoragsearch.searchResultFilteringType");
        StringTokenizer srft = new StringTokenizer("");
        if (searchResultFilteringTypeProperty != null) {
            srft = new StringTokenizer(searchResultFilteringTypeProperty);
        }
        int countTokens = srft.countTokens();
        if (searchResultFilteringTypeProperty == null || countTokens == 0 || countTokens > 1) {
            errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType="
                    + searchResultFilteringTypeProperty
                    + ": one and only one of 'presearch', 'insearch', 'postsearch' must be stated.\n");
        } else {
            for (int i = 0; i < countTokens; i++) {
                String token = srft.nextToken();
                if (!("presearch".equals(token) || "insearch".equals(token) || "postsearch".equals(token))) {
                    errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType="
                            + searchResultFilteringTypeProperty
                            + ": only 'presearch', 'insearch', 'postsearch' may be stated, not '" + token
                            + "'.\n");
                }
            }
        }
    }

    //     Check repository properties
    Enumeration repositoryNames = repositoryNameToProps.keys();
    while (repositoryNames.hasMoreElements()) {
        String repositoryName = (String) repositoryNames.nextElement();
        Properties props = (Properties) repositoryNameToProps.get(repositoryName);
        if (logger.isDebugEnabled())
            logger.debug(configName + "/repository/" + repositoryName + "/repository.properties="
                    + props.toString());

        //        Check for unknown properties, indicating typos or wrong property names
        String[] reposPropNames = { "fgsrepository.repositoryName", "fgsrepository.fedoraSoap",
                "fgsrepository.fedoraUser", "fgsrepository.fedoraPass", "fgsrepository.fedoraObjectDir",
                "fgsrepository.fedoraVersion", "fgsrepository.defaultGetRepositoryInfoResultXslt",
                "fgsrepository.trustStorePath", "fgsrepository.trustStorePass" };
        //checkPropNames(configName+"/repository/"+repositoryName+"/repository.properties", props, reposPropNames);

        //        Check repositoryName
        String propsRepositoryName = props.getProperty("fgsrepository.repositoryName");
        if (!repositoryName.equals(propsRepositoryName)) {
            errors.append("\n*** " + configName + "/repository/" + repositoryName
                    + ": fgsrepository.repositoryName must be=" + repositoryName);
        }

        //        Check fedoraObjectDir
        //          String fedoraObjectDirName = insertSystemProperties(props.getProperty("fgsrepository.fedoraObjectDir"));
        //          File fedoraObjectDir = new File(fedoraObjectDirName);
        //          if (fedoraObjectDir == null) {
        //             errors.append("\n*** "+configName+"/repository/" + repositoryName
        //                   + ": fgsrepository.fedoraObjectDir="
        //                   + fedoraObjectDirName + " not found");
        //          }

        //        Check result stylesheets
        checkResultStylesheet("/repository/" + repositoryName, props,
                "fgsrepository.defaultGetRepositoryInfoResultXslt");
    }

    //     Check index properties
    Enumeration indexNames = indexNameToProps.keys();
    while (indexNames.hasMoreElements()) {
        String indexName = (String) indexNames.nextElement();
        Properties props = (Properties) indexNameToProps.get(indexName);
        if (logger.isDebugEnabled())
            logger.debug(configName + "/index/" + indexName + "/index.properties=" + props.toString());

        //        Check for unknown properties, indicating typos or wrong property names
        String[] indexPropNames = { "fgsindex.indexName", "fgsindex.indexBase", "fgsindex.indexUser",
                "fgsindex.indexPass", "fgsindex.operationsImpl", "fgsindex.defaultUpdateIndexDocXslt",
                "fgsindex.defaultUpdateIndexResultXslt", "fgsindex.defaultGfindObjectsResultXslt",
                "fgsindex.defaultBrowseIndexResultXslt", "fgsindex.defaultGetIndexInfoResultXslt",
                "fgsindex.indexDir", "fgsindex.analyzer", "fgsindex.untokenizedFields",
                "fgsindex.defaultQueryFields", "fgsindex.snippetBegin", "fgsindex.snippetEnd",
                "fgsindex.maxBufferedDocs", "fgsindex.mergeFactor", "fgsindex.ramBufferSizeMb",
                "fgsindex.defaultWriteLockTimeout", "fgsindex.defaultSortFields", "fgsindex.uriResolver" };
        //checkPropNames(configName+"/index/"+indexName+"/index.properties", props, indexPropNames);

        //        Check indexName
        String propsIndexName = props.getProperty("fgsindex.indexName");
        if (!indexName.equals(propsIndexName)) {
            errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.indexName must be="
                    + indexName);
        }

        //        Check operationsImpl class
        String operationsImpl = props.getProperty("fgsindex.operationsImpl");
        if (operationsImpl == null || operationsImpl.equals("")) {
            errors.append(
                    "\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl must be set in "
                            + configName + "/index/ " + indexName + ".properties");
        }
        try {
            Class operationsImplClass = Class.forName(operationsImpl);
            try {
                GenericOperationsImpl ops = (GenericOperationsImpl) operationsImplClass
                        .getConstructor(new Class[] {}).newInstance(new Object[] {});
            } catch (InstantiationException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (IllegalAccessException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (InvocationTargetException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (NoSuchMethodException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            }
        } catch (ClassNotFoundException e) {
            errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                    + operationsImpl + ": class not found.\n" + e);
        }

        //        Check result stylesheets
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexDocXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGfindObjectsResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultBrowseIndexResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGetIndexInfoResultXslt");

        //        Check indexDir
        String indexDir = insertSystemProperties(props.getProperty("fgsindex.indexDir"));
        File indexDirFile = new File(indexDir);
        if (indexDirFile == null) {
            errors.append("\n*** " + configName + "/index/" + indexName + " fgsindex.indexDir=" + indexDir
                    + " must exist as a directory");
        }

        //        Check analyzer class for lucene and solr
        if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) {
            String analyzer = props.getProperty("fgsindex.analyzer");
            if (analyzer == null || analyzer.equals("")) {
                analyzer = defaultAnalyzer;
            }
            try {
                Class analyzerClass = Class.forName(analyzer);
                try {
                    Analyzer a = (Analyzer) analyzerClass.getConstructor(new Class[] {})
                            .newInstance(new Object[] {});
                } catch (InstantiationException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (IllegalAccessException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (InvocationTargetException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (NoSuchMethodException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error:\n" + e.toString());
                }
            } catch (ClassNotFoundException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.analyzer=" + analyzer
                        + ": class not found:\n" + e.toString());
            }
        }

        //        Add untokenizedFields property for lucene
        if (operationsImpl.indexOf("fgslucene") > -1) {
            String defaultUntokenizedFields = props.getProperty("fgsindex.untokenizedFields");
            if (defaultUntokenizedFields == null)
                props.setProperty("fgsindex.untokenizedFields", "");
            if (indexDirFile != null) {
                StringBuffer untokenizedFields = new StringBuffer(
                        props.getProperty("fgsindex.untokenizedFields"));
                IndexReader ir = null;
                try {
                    ir = IndexReader.open(FSDirectory.open(new File(indexDir)), true);
                    int max = ir.numDocs();
                    if (max > 10)
                        max = 10;
                    for (int i = 0; i < max; i++) {
                        Document doc = ir.document(i);
                        for (ListIterator li = doc.getFields().listIterator(); li.hasNext();) {
                            Field f = (Field) li.next();
                            if (!f.isTokenized() && f.isIndexed() && untokenizedFields.indexOf(f.name()) < 0) {
                                untokenizedFields.append(" " + f.name());
                            }
                        }
                    }
                } catch (Exception e) {
                }
                props.setProperty("fgsindex.untokenizedFields", untokenizedFields.toString());
                if (logger.isDebugEnabled())
                    logger.debug("indexName=" + indexName + " fgsindex.untokenizedFields=" + untokenizedFields);
            }
        }

        //        Check defaultQueryFields - how can we check this?
        String defaultQueryFields = props.getProperty("fgsindex.defaultQueryFields");

        //        Use custom URIResolver if given
        //MIH: also check for solr
        if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) {
            Class uriResolverClass = null;
            String uriResolver = props.getProperty("fgsindex.uriResolver");
            if (!(uriResolver == null || uriResolver.equals(""))) {
                try {
                    uriResolverClass = Class.forName(uriResolver);
                    try {
                        URIResolverImpl ur = (URIResolverImpl) uriResolverClass.getConstructor(new Class[] {})
                                .newInstance(new Object[] {});
                        if (ur != null) {
                            ur.setConfig(this);
                            indexNameToUriResolvers.put(indexName, ur);
                        }
                    } catch (InstantiationException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (IllegalAccessException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (InvocationTargetException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (NoSuchMethodException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error:\n"
                                + e.toString());
                    }
                } catch (ClassNotFoundException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.uriResolver="
                            + uriResolver + ": class not found:\n" + e.toString());
                }
            }
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("configCheck configName=" + configName + " errors=" + errors.toString());
    if (errors.length() > 0)
        throw new ConfigException(errors.toString());
}

From source file:cx.fbn.nevernote.sql.NoteTable.java

public Note mapNoteFromQuery(NSqlQuery query, boolean loadContent, boolean loadResources,
        boolean loadRecognition, boolean loadBinary, boolean loadTags) {
    DateFormat indfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    //      indfm = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");

    Note n = new Note();
    NoteAttributes na = new NoteAttributes();
    n.setAttributes(na);//  w w  w.j a  va2 s.  c  o  m

    n.setGuid(query.valueString(0));
    n.setUpdateSequenceNum(new Integer(query.valueString(1)));
    n.setTitle(query.valueString(2));

    try {
        n.setCreated(indfm.parse(query.valueString(3)).getTime());
        n.setUpdated(indfm.parse(query.valueString(4)).getTime());
        n.setDeleted(indfm.parse(query.valueString(5)).getTime());
    } catch (ParseException e) {
        e.printStackTrace();
    }

    n.setActive(query.valueBoolean(6, true));
    n.setNotebookGuid(query.valueString(7));

    try {
        String attributeSubjectDate = query.valueString(8);
        if (!attributeSubjectDate.equals(""))
            na.setSubjectDate(indfm.parse(attributeSubjectDate).getTime());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    na.setLatitude(new Float(query.valueString(9)));
    na.setLongitude(new Float(query.valueString(10)));
    na.setAltitude(new Float(query.valueString(11)));
    na.setAuthor(query.valueString(12));
    na.setSource(query.valueString(13));
    na.setSourceURL(query.valueString(14));
    na.setSourceApplication(query.valueString(15));
    na.setContentClass(query.valueString(16));

    if (loadTags) {
        List<String> tagGuids = noteTagsTable.getNoteTags(n.getGuid());
        List<String> tagNames = new ArrayList<String>();
        TagTable tagTable = db.getTagTable();
        for (int i = 0; i < tagGuids.size(); i++) {
            String currentGuid = tagGuids.get(i);
            Tag tag = tagTable.getTag(currentGuid);
            if (tag.getName() != null)
                tagNames.add(tag.getName());
            else
                tagNames.add("");
        }

        n.setTagNames(tagNames);
        n.setTagGuids(tagGuids);
    }

    if (loadContent) {
        QTextCodec codec = QTextCodec.codecForLocale();
        codec = QTextCodec.codecForName("UTF-8");
        String unicode = codec.fromUnicode(query.valueString(17)).toString();

        // This is a hack.  Basically I need to convert HTML Entities to "normal" text, but if I
        // convert the &lt; character to < it will mess up the XML parsing.  So, to get around this
        // I am "bit stuffing" the &lt; to &&lt; so StringEscapeUtils doesn't unescape it.  After
        // I'm done I convert it back.
        StringBuffer buffer = new StringBuffer(unicode);
        if (Global.enableHTMLEntitiesFix && unicode.indexOf("&#") > 0) {
            unicode = query.valueString(17);
            //System.out.println(unicode);
            //unicode = unicode.replace("&lt;", "&_lt;");
            //unicode = codec.fromUnicode(StringEscapeUtils.unescapeHtml(unicode)).toString();
            //unicode = unicode.replace("&_lt;", "&lt;");
            //System.out.println("************************");
            int j = 1;
            for (int i = buffer.indexOf("&#"); i != -1
                    && buffer.indexOf("&#", i) > 0; i = buffer.indexOf("&#", i + 1)) {
                j = buffer.indexOf(";", i) + 1;
                if (i < j) {
                    String entity = buffer.substring(i, j).toString();
                    int len = entity.length() - 1;
                    String tempEntity = entity.substring(2, len);
                    try {
                        Integer.parseInt(tempEntity);
                        entity = codec.fromUnicode(StringEscapeUtils.unescapeHtml4(entity)).toString();
                        buffer.delete(i, j);
                        buffer.insert(i, entity);
                    } catch (Exception e) {
                    }

                }
            }
        }

        n.setContent(unicode);
        //         n.setContent(query.valueString(16).toString());

        String contentHash = query.valueString(18);
        if (contentHash != null)
            n.setContentHash(contentHash.getBytes());
        n.setContentLength(new Integer(query.valueString(19)));
    }
    if (loadResources)
        n.setResources(noteResourceTable.getNoteResources(n.getGuid(), loadBinary));
    if (loadRecognition) {
        if (n.getResources() == null) {
            List<Resource> resources = noteResourceTable.getNoteResourcesRecognition(n.getGuid());
            n.setResources(resources);
        } else {
            // We need to merge the recognition resources with the note resources retrieved earlier
            for (int i = 0; i < n.getResources().size(); i++) {
                Resource r = noteResourceTable.getNoteResourceRecognition(n.getResources().get(i).getGuid());
                n.getResources().get(i).setRecognition(r.getRecognition());
            }
        }
    }
    n.setContent(fixCarriageReturn(n.getContent()));
    return n;
}

From source file:net.sourceforge.processdash.ev.ui.EVReport.java

private void printTaskStyleLinks(EVTaskDataWriter taskDataWriter, String namespace) {
    if (exportingToExcel())
        return;//from  w  w  w.  j  a  va  2 s .  c  o  m

    StringBuffer href = new StringBuffer();
    String uri = (String) env.get(CMSSnippetEnvironment.CURRENT_FRAME_URI);
    if (uri == null) {
        href.append("ev.class");
    } else {
        href.append(uri);
        Matcher m = TASK_STYLE_PARAM_PATTERN.matcher(uri);
        if (m.find())
            HTMLUtils.removeParam(href, m.group());
    }
    HTMLUtils.appendQuery(href, settings.getQueryString(EVReportSettings.PURPOSE_TASK_STYLE));
    href.append(href.indexOf("?") == -1 ? '?' : '&');
    href.append(namespace).append(TASK_STYLE_PARAM).append('=');

    for (EVTaskDataWriter w : getTaskDataWriters()) {
        if (w == taskDataWriter)
            continue;

        out.print("<span " + HEADER_LINK_STYLE + ">" + "<span class='doNotPrint'>" + "<a id=\"" + namespace
                + "taskstyle" + w.getID() + "\" href=\"" + href + w.getID() + "#" + namespace + "tasks\">");
        out.print(HTMLUtils.escapeEntities(w.getDisplayName()));
        out.print("</a></span></span>");
    }
}