Example usage for org.apache.commons.lang CharEncoding UTF_8

List of usage examples for org.apache.commons.lang CharEncoding UTF_8

Introduction

In this page you can find the example usage for org.apache.commons.lang CharEncoding UTF_8.

Prototype

String UTF_8

To view the source code for org.apache.commons.lang CharEncoding UTF_8.

Click Source Link

Document

Eight-bit Unicode Transformation Format.

Usage

From source file:net.jotel.ws.client.WebSocketClient.java

private String readFieldValue(InputStream is) throws IOException {
    // This reads a field value, terminated by a CRLF, skipping past a
    // single space after the colon if there is
    // one.//w  w  w .j  a v  a 2  s .co m

    // 4.1 33. Let /value/ be empty byte arrays
    ByteArrayOutputStream value = new ByteArrayOutputStream();

    // 4.1.35. Let /count/ equal 0.
    int count = 0;

    // NOTE: This is used in the next step to skip past a space character
    // after the colon, if necessary.

    // 4.1.36. Read a byte from the server and increment /count/ by 1.

    // If the connection closes before this byte is received, then fail the
    // WebSocket connection and abort these
    // steps.
    int b = -1;
    while ((b = is.read()) != -1) {
        count = +1;
        // Otherwise, handle the byte as described in the appropriate entry
        // below:

        if (b == 0x20 && count == 1) {
            // -> If the byte is 0x20 (ASCII space) and /count/ equals 1
            // Ignore the byte and redo this step for the next byte.
        } else if (b == 0x0D) {
            // -> If the byte is 0x0D (ASCII CR)
            // Move on to the next step.
            break;
        } else if (b == 0x0A) {
            // -> If the byte is 0x0A (ASCII LF)
            // Fail the WebSocket connection and abort these steps.
            throw new WebSocketException("Unexpected LF character in field value!");
        } else {
            // -> Otherwise
            // Append the byte to the /value/ byte array and redo this step
            // for the next byte.
            value.write(b);
        }
    }

    if (b == -1) {
        throw new WebSocketException("Unexpected end of stream!");
    }

    // 4.1.37. Read a byte from the server.
    // If the connection closes before this byte is received, or if the byte
    // is not a 0x0A byte (ASCII LF), then
    // fail the WebSocket connection and abort these steps.

    // NOTE: This skips past the LF byte of the CRLF after the field.
    skipByte(is, 0x0A);

    return new String(value.toByteArray(), CharEncoding.UTF_8);
}

From source file:net.jotel.ws.client.WebSocketClient.java

void onDataFrame(int opcode, byte[] data) throws IOException {
    switch (opcode) {
    case TEXT_OPCODE:
        triggerOnMessage(new String(data, CharEncoding.UTF_8));
        break;/*w w  w  .ja  v a2 s .  c o  m*/
    case BINARY_OPCODE:
        triggerOnMessage(data);
        break;
    case PING_OPCODE:
        trySend((byte) PONG_OPCODE, data);
        break;
    case CLOSE_OPCODE:
        Integer status = null;
        String message = null;

        if (data != null) {
            if (data.length >= 2) {
                status = (data[0] & 0xff) << 8 | (data[1] & 0xff);
            }
            if (data.length > 2) {
                message = new String(data, 2, data.length, Charset.forName(CharEncoding.UTF_8));
            }
        }

        log.debug("CLOSE_OPCODE {}:{}", status, message);

        triggerOnClose(status, message);
        break;
    default:
        // just ignore
        break;
    }
}

From source file:eionet.web.action.VocabularyFolderActionBean.java

/**
 * Imports CSV contents into vocabulary.
 *
 * @return resolution/*from   w  w  w  . jav  a 2  s  .  co m*/
 * @throws ServiceException
 *             when an error occurs
 */
public Resolution uploadCsv() throws ServiceException {
    try {
        vocabularyFolder = vocabularyService.getVocabularyFolder(vocabularyFolder.getFolderName(),
                vocabularyFolder.getIdentifier(), vocabularyFolder.isWorkingCopy());
        validateView();
        if (!vocabularyFolder.isWorkingCopy()) {
            throw new ServiceException("Vocabulary should be in working copy status");
        }

        if (this.uploadedFileToImport == null) {
            throw new ServiceException("You should upload a file");
        }

        String fileName = this.uploadedFileToImport.getFileName();
        if (StringUtils.isEmpty(fileName)
                || !fileName.toLowerCase().endsWith(VocabularyFolderActionBean.CSV_FILE_EXTENSION)) {
            throw new ServiceException("File should be a CSV file");
        }

        // consume stupid bom first!! if it exists!
        InputStream is = this.uploadedFileToImport.getInputStream();
        byte[] firstBomBytes = new byte[VocabularyOutputHelper.BOM_BYTE_ARRAY_LENGTH];
        int readBytes = is.read(firstBomBytes);
        if (readBytes != VocabularyOutputHelper.BOM_BYTE_ARRAY_LENGTH) {
            is.close();
            throw new ServiceException("Input stream cannot be read");
        }

        if (!Arrays.equals(firstBomBytes, VocabularyOutputHelper.getBomByteArray())) {
            is.close();
            is = this.uploadedFileToImport.getInputStream();
        }

        Reader csvFileReader = new InputStreamReader(is, CharEncoding.UTF_8);
        List<String> systemMessages = this.vocabularyCsvImportService.importCsvIntoVocabulary(csvFileReader,
                vocabularyFolder, purgeVocabularyData, purgeBoundElements);
        for (String systemMessage : systemMessages) {
            addSystemMessage(systemMessage);
        }
        RedirectResolution resolution = new RedirectResolution(VocabularyFolderActionBean.class, "edit");
        resolution.addParameter("vocabularyFolder.folderName", vocabularyFolder.getFolderName());
        resolution.addParameter("vocabularyFolder.identifier", vocabularyFolder.getIdentifier());
        resolution.addParameter("vocabularyFolder.workingCopy", vocabularyFolder.isWorkingCopy());
        // navigate back to edit
        return resolution;
    } catch (ServiceException e) {
        LOGGER.error("Failed to import vocabulary CSV into db", e);
        e.setErrorParameter(ErrorActionBean.ERROR_TYPE_KEY, ErrorActionBean.ErrorType.INVALID_INPUT);
        throw e;
    } catch (Exception e) {
        LOGGER.error("Failed to import vocabulary CSV into db, unexpected exception: ", e);
        ErrorResolution error = new ErrorResolution(HttpURLConnection.HTTP_INTERNAL_ERROR);
        error.setErrorMessage(e.getMessage());
        return error;
    }
}

From source file:eionet.web.action.VocabularyFolderActionBean.java

/**
 * Imports RDF contents into vocabulary.
 *
 * @return resolution/*  w w  w  .j  a  v  a  2 s  . co  m*/
 * @throws ServiceException
 *             when an error occurs
 */
public Resolution uploadRdf() throws ServiceException {
    try {
        vocabularyFolder = vocabularyService.getVocabularyFolder(vocabularyFolder.getFolderName(),
                vocabularyFolder.getIdentifier(), vocabularyFolder.isWorkingCopy());
        validateView();
        if (!vocabularyFolder.isWorkingCopy()) {
            throw new ServiceException("Vocabulary should be in working copy status");
        }

        if (this.uploadedFileToImport == null) {
            throw new ServiceException("You should upload a file");
        }

        String fileName = this.uploadedFileToImport.getFileName();
        if (StringUtils.isEmpty(fileName)
                || !fileName.toLowerCase().endsWith(VocabularyFolderActionBean.RDF_FILE_EXTENSION)) {
            throw new ServiceException("File should be a RDF file");
        }

        LOGGER.debug("Starting RDF import operation");
        Reader rdfFileReader = new InputStreamReader(this.uploadedFileToImport.getInputStream(),
                CharEncoding.UTF_8);
        // TODO use enum instead for rdf purge option
        List<String> systemMessages = this.vocabularyRdfImportService.importRdfIntoVocabulary(rdfFileReader,
                vocabularyFolder, this.rdfPurgeOption == 3, this.rdfPurgeOption == 2);
        for (String systemMessage : systemMessages) {
            addSystemMessage(systemMessage);
            LOGGER.info(systemMessage);
        }
        LOGGER.debug("RDF import completed");

        RedirectResolution resolution = new RedirectResolution(VocabularyFolderActionBean.class, "edit");
        resolution.addParameter("vocabularyFolder.folderName", vocabularyFolder.getFolderName());
        resolution.addParameter("vocabularyFolder.identifier", vocabularyFolder.getIdentifier());
        resolution.addParameter("vocabularyFolder.workingCopy", vocabularyFolder.isWorkingCopy());
        // navigate back to edit
        return resolution;
    } catch (ServiceException e) {
        LOGGER.error("Failed to import vocabulary RDF into db", e);
        e.setErrorParameter(ErrorActionBean.ERROR_TYPE_KEY, ErrorActionBean.ErrorType.INVALID_INPUT);
        throw e;
    } catch (Exception e) {
        LOGGER.error("Failed to import vocabulary RDF into db, unexpected exception: ", e);
        ErrorResolution error = new ErrorResolution(HttpURLConnection.HTTP_INTERNAL_ERROR);
        error.setErrorMessage(e.getMessage());
        return error;
    }
}

From source file:com.meetup.memcached.MemcachedClient.java

private String sanitizeKey(String key) throws UnsupportedEncodingException {
    return (sanitizeKeys) ? URLEncoder.encode(key, CharEncoding.UTF_8) : key;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.loader.levelthree.LevelThreeLoader.java

/**
 * Loads BROAD SNP6, MSKCC and HUDSONALPHA center files.
 * /*from w  w w .ja  v  a2  s  . co m*/
 * @param fileName
 *            the file to load
 * @param extractNameIndex
 *            index of "EXTRACT_NAME" column in SDRF
 * @param sdrfNavigator
 *            a data structure containing SDRF
 * @param dataSetId
 *            id of the data set associated with the load
 * @param platform
 *            platform associated with the load
 * @param center
 *            center associated with the load
 * @throws LoaderException
 *             if CNA load resulted in an error
 */
public void loadCnaValues(File segmentFile, Integer extractNameIndex,
        TabDelimitedContentNavigator sdrfNavigator, Integer dataSetId, String platform, String center)
        throws LoaderException {

    logger.debug(String.format(fileToDbLoadInfoPlaceholder, segmentFile, "cna_value"));

    SegmentRecord segmentRecord = getSegmentRecordForCenter(center);
    String prevHybridizationRefName = "";
    Integer recordNumber = 0;

    List<CnaValue> cnaValues = new ArrayList<CnaValue>();
    Map<Integer, String> controlSampleRecords = new HashMap<Integer, String>();
    LineIterator segmentLineIterator = null;
    try {
        segmentLineIterator = FileUtils.lineIterator(segmentFile, CharEncoding.UTF_8);
        String segmentFileRecord = segmentLineIterator.nextLine();
        String[] recordValues = segmentFileRecord.split(SEGMENT_RECORD_DELIMITER);
        segmentRecord.setRecordValues(Arrays.asList(recordValues));
        segmentRecord.assertRecord(true);
        ++recordNumber;

        while (segmentLineIterator.hasNext()) {
            segmentFileRecord = segmentLineIterator.nextLine();
            recordValues = segmentFileRecord.split(SEGMENT_RECORD_DELIMITER);
            segmentRecord.setRecordValues(Arrays.asList(recordValues));
            segmentRecord.setRecordNumber(recordNumber);
            segmentRecord.assertRecord(false);

            CnaValue cnaValue = segmentRecord.getCnaValue();
            cnaValue.setDataSetId(dataSetId);

            resolveHybridizationRefId(cnaValue, prevHybridizationRefName, sdrfNavigator, extractNameIndex,
                    dataSetId);

            validate(cnaValue, recordNumber);

            if (cnaValue.getHybridizationRefId() != null) {
                cnaValues.add(cnaValue.copy());
            } else {
                controlSampleRecords.put(recordNumber, cnaValue.getHybridizationRefName());
            }

            if (cnaValues.size() == getBatchSize()) {
                if (logger.isDebugEnabled()) {
                    printCnaLoadBatchInfo(controlSampleRecords);
                }

                persistCnaValues(cnaValues);
                cnaValues.clear();
            }

            prevHybridizationRefName = cnaValue.getHybridizationRefName();
            ++recordNumber;
        }

        if (cnaValues.size() > 0) {
            if (logger.isDebugEnabled()) {
                printCnaLoadBatchInfo(controlSampleRecords);
            }

            persistCnaValues(cnaValues);
            cnaValues.clear();
        }
    } catch (IOException ioe) {
        throw new LoaderException(ioe.getMessage(), ioe);
    } finally {
        LineIterator.closeQuietly(segmentLineIterator);
    }
}

From source file:org.apache.sling.its.servlets.ItsServlet.java

@Override
protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (ResourceUtil.isNonExistingResource(request.getResource())) {
        LOG.error("No resource found for path: " + request.getResource().getPath());
        response.getWriter().write("500: No resource found for path: " + request.getResource().getPath());
        return;// w ww  .j ava  2  s. co  m
    }

    this.isHtml = request.getRequestPathInfo().getExtension().equals("html");

    try {
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements.
        final Document doc = docBuilder.newDocument();
        createDocument(request.getResource(), doc);

        // make sure the encoding is set before getWriter() is called.
        if (this.isHtml) {
            response.setCharacterEncoding(CharEncoding.UTF_8);
            response.setContentType(MimeTypeMapper.HTML_MIME_TYPE);
            response.getWriter().write("<!DOCTYPE html>");
        } else {
            response.setCharacterEncoding(CharEncoding.UTF_8);
            response.setContentType(MimeTypeMapper.XML_MIME_TYPE);
        }

        // write the content into xml file.
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final StreamResult result = new StreamResult(response.getWriter());

        // set the correct properties for the xml or html file.
        transformer.setOutputProperty(OutputKeys.METHOD, Namespaces.XML_NS_PREFIX);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // Output the xml or html file.
        transformer.transform(source, result);
    } catch (final ParserConfigurationException pce) {
        LOG.error("Failed to create DocumentBuilder. Stack Trace: ", pce);
    } catch (final TransformerException tfe) {
        LOG.error("Failed to transform the document. Stack Trace: ", tfe);
    }
}

From source file:org.bml.util.io.net.NetworkUtils.java

/**
 * <p>/*from   w  w w . j a v  a2 s. c  o  m*/
 * Attempt to resolve this computers host name. In its current state this 
 * method only calls 'hostname'.
 * </p>
 * <p>
 * <b>WARNING:</b>This method uses Runtime and a Process. It also waits for
 * the process to complete before returning.
 * </p>
 * <p>
 * Order of host name source.
 * <ol>
 * <li><code>Runtime.getRuntime().exec("hostname")</code>(Linux)</li>
 * <li><code>Runtime.getRuntime().exec("gethostname")</code>(Unix)</li>
 * <li><code>InetAddress.getLocalHost().getHostName()</code>(Other)</li>
 * </ol>
 * </p>
 *
 * @return The host name of the server that this code runs on.
 *
 * @throws java.io.IOException If there is a problem with {@link Process} IO
 * @throws java.lang.InterruptedException if this thread is interrupted while
 * it is waiting for a process to complete.
 * 
 * @todo Implement multiple hostname attempts and try to guess the rite one for the OS.
 */
public static String getThisHostName() throws IOException, InterruptedException {
    String hostname = null;
    Process process;
    StringWriter writer = new StringWriter();
    InputStream processInputStream;
    Runtime runtime = Runtime.getRuntime();
    try {
        //Attempt hostname call
        process = Runtime.getRuntime().exec("hostname");
        process.waitFor();
        processInputStream = process.getInputStream();
        IOUtils.copy(processInputStream, writer, CharEncoding.UTF_8);
        hostname = writer.toString();
        process.exitValue();
    } catch (IOException ioe) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("IPException caught while attempting to resolve hostname.", ioe);
        }
        throw ioe;
    }
    return hostname;
}

From source file:org.bml.util.RequestDataContainer.java

/**
 * Accepts a URI and parses out the parameters if there are any.
 * @param theUri A vaild URI/*from  w ww.j  a v a 2  s .c o  m*/
 * @return a map of key - distinct values representing the parameters in the URI if any 
 *
 * @pre theUri!=null
 */
public static Map<String, Set<String>> parseURIParams(final URI theUri) {
    if (CHECKED) {
        Preconditions.checkNotNull(theUri, "Can not parse parameters from a null URI");
    }
    List<NameValuePair> paramList = URLEncodedUtils.parse(theUri, CharEncoding.UTF_8);
    Map<String, Set<String>> paramMap = new HashMap<String, Set<String>>();
    Set<String> tmpValues = null;
    for (NameValuePair pair : paramList) {
        tmpValues = paramMap.get(pair.getName());
        if (tmpValues == null) {
            tmpValues = new HashSet<String>();
            paramMap.put(pair.getName(), tmpValues);
        }
        tmpValues.add(pair.getValue());
    }
    return paramMap;
}

From source file:org.carewebframework.security.spring.AbstractSecurityService.java

/**
 * Replaces the inline parameter with the specified value.
 * //from   w w  w  .ja va 2  s.co m
 * @param text Text containing parameter placeholder.
 * @param param Parameter name.
 * @param value Value to replace (will be url-encoded).
 * @return Updated text.
 */
private String replaceParam(String text, String param, String value) {
    if (text.contains(param)) {
        try {
            value = value == null ? "" : URLEncoder.encode(value, CharEncoding.UTF_8);
            text = text.replace(param, value);
        } catch (UnsupportedEncodingException e) {
            log.error("Error encoding parameter value.", e);
        }
    }
    return text;
}