Example usage for java.nio CharBuffer toString

List of usage examples for java.nio CharBuffer toString

Introduction

In this page you can find the example usage for java.nio CharBuffer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representing the current remaining chars of this buffer.

Usage

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .touchosc file
 * //from w  ww  . ja  v a 2  s.com
 * @param zipTouchoscFilePath a .touchosc file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML2(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        URL url = TouchOSCUtils.class.getClassLoader().getResource(".");

        FileInputStream touchoscFile = new FileInputStream(url.getPath() + "../samples/" + zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            }
            FileOutputStream os = new FileOutputStream(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .jzml file
 * /*  ww  w .j a v  a 2  s  . c  o  m*/
 * @param zipTouchoscFilePath a .jzml file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    IPath path = new Path(zipTouchoscFilePath);

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            FileOutputStream os = new FileOutputStream(path.removeLastSegments(1) + "/_" + path.lastSegment());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<touchosc>", "");
            content = content.replace("</touchosc>", "");
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:sdf_manager.ExporterSiteHTML.java

/**
 *
 * @param fieldName//from   ww  w . j a va 2s  . c om
 * @return
 */
private String getString(String fieldName) {
    try {

        byte[] result = fieldName.getBytes();
        //String tmp = result != null ? new String(result) : null;
        if (result != null && result.length == 0) {
            //log("Empty string for: " + fieldName);
            return null;
        } //don't enter empty string in the database
        else {
            if (result != null) {
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.REPLACE);
                decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
                CharBuffer cbuf = decoder.decode(ByteBuffer.wrap(result));
                return cbuf.toString().trim();
            } else {
                return null;
            }
        }
    } catch (Exception e) {
        logToFile("Failed extracting field: " + fieldName
                + ". The field could have an erroneous name. Please verify.");
        //e.printStackTrace();
        ExporterSiteHTML.log.error("Failed extracting field: " + fieldName
                + ". The field could have an erroneous name. Please verify.");
        return null;
    }
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 *//*from   w w w.j  ava2 s . c om*/
protected HashMap selectCredentials(String uid) throws NamingException {
    HashMap credentialResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext();

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            for (int j = 0; j < credentialAttr.length; j++) {

                Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' of type '"
                            + credentialObject.getClass().getName() + ""
                            + (credentialObject.getClass().isArray()
                                    ? "[" + Array.getLength(credentialObject) + "]"
                                    : "")
                            + "'");

                // if the attribute value is an array, cast it to byte[] and then convert to
                // String using proper encoding
                if (credentialObject.getClass().isArray()) {

                    try {
                        // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                        // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                        byte[] credentialData = (byte[]) credentialObject;
                        ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                        in.put(credentialData);
                        in.flip();

                        Charset charset = Charset.forName("UTF-8");
                        CharsetDecoder decoder = charset.newDecoder();
                        CharBuffer charBuffer = decoder.decode(in);

                        credentialValue = charBuffer.toString();

                    } catch (CharacterCodingException e) {
                        if (logger.isDebugEnabled())
                            logger.debug("Can't convert credential value to String using UTF-8");
                    }

                } else if (credentialObject instanceof String) {
                    // The credential value must be a String ...
                    credentialValue = (String) credentialObject;

                }

                // Check what do we have ...
                if (credentialValue != null) {
                    // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                    credentialValue = getSchemeFreeValue(credentialValue);
                    credentialResultSet.put(credentialName, credentialValue);
                } else {
                    // We have a binary credential, leave it as it is ... probably binary value.
                    credentialResultSet.put(credentialName, credentialObject);
                }

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' with value '"
                            + (credentialValue != null ? credentialValue : credentialObject) + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return credentialResultSet;
}

From source file:uk.ac.cam.caret.sakai.rwiki.utils.NameHelper.java

private static String normalize(final String nameToNormalize, final boolean isPageName) {
    char[] chars = nameToNormalize.toCharArray();
    int charBufferLength = chars.length + 1 + (isPageName ? DEFAULT_PAGE.length() : 0);
    CharBuffer name = CharBuffer.allocate(charBufferLength);

    int wordStart = 0;

    boolean addSeparator = true;
    boolean addWhiteSpaceOrSeparator = true;
    int numberOfSeparators = 0;

    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];

        if (c == SPACE_SEPARATOR) {
            if (!addWhiteSpaceOrSeparator) {
                name.put(chars, wordStart, i - wordStart);
            }/*from w  w  w.jav a2s  . c o  m*/
            addSeparator = true;
            addWhiteSpaceOrSeparator = true;
        } else if (Character.isWhitespace(c)) {
            if (!addWhiteSpaceOrSeparator) {
                name.put(chars, wordStart, i - wordStart);

            }
            addWhiteSpaceOrSeparator = true;
        } else if (addSeparator) {
            name.put(SPACE_SEPARATOR);
            if (++numberOfSeparators > 2) {
                chars[i] = Character.toLowerCase(c);
            }
            wordStart = i;
            addSeparator = false;
            addWhiteSpaceOrSeparator = false;
        } else if (addWhiteSpaceOrSeparator) {
            addWhiteSpaceOrSeparator = false;
            wordStart = i;
            name.put(' ');
            if (numberOfSeparators > 2) {
                chars[i] = Character.toLowerCase(c);
            }
        } else {
            if (numberOfSeparators > 2) {
                chars[i] = Character.toLowerCase(c);
            }
        }

    }

    if (addSeparator && isPageName) {
        name.put(SPACE_SEPARATOR);
        name.put(DEFAULT_PAGE);
    } else if (!addWhiteSpaceOrSeparator) {
        name.put(chars, wordStart, chars.length - wordStart);
    }

    int position = name.position();
    name.position(0);
    name.limit(position);

    return name.toString();
}

From source file:ti.modules.titanium.network.TiHTTPClient.java

private String decodeResponseData(String charsetName) {
    Charset charset;//from w w w  .  j  a  v  a 2 s  .c  om
    try {
        charset = Charset.forName(charsetName);

    } catch (IllegalArgumentException e) {
        Log.e(TAG, "Could not find charset: " + e.getMessage());
        return null;
    }

    CharsetDecoder decoder = charset.newDecoder();
    ByteBuffer in = ByteBuffer.wrap(responseData.getBytes());

    try {
        CharBuffer decodedText = decoder.decode(in);
        return decodedText.toString();

    } catch (CharacterCodingException e) {
        return null;

    } catch (OutOfMemoryError e) {
        Log.e(TAG, "Not enough memory to decode response data.");
        return null;
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static Object isCodepage(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    boolean bRC = false;
    if (ArgList.length == 2) {
        try {/*from   w ww.ja  va 2s . co m*/
            if (isNull(ArgList, new int[] { 0, 1 }))
                return null;
            else if (isUndefined(ArgList, new int[] { 0, 1 }))
                return undefinedValue;
            String strValueToCheck = (String) ArgList[0];
            String strCodePage = (String) ArgList[1];
            byte bytearray[] = strValueToCheck.getBytes();
            CharsetDecoder d = Charset.forName(strCodePage).newDecoder();
            CharBuffer r = d.decode(ByteBuffer.wrap(bytearray));
            r.toString();
            bRC = true;
        } catch (Exception e) {
            bRC = false;
        }
    } else {
        throw new RuntimeException("The function call isCodepage requires 2 arguments.");
    }
    return Boolean.valueOf(bRC);
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object isCodepage(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    boolean bRC = false;
    if (ArgList.length == 2) {
        try {//from ww  w  .j  a  va2s .  co m
            if (isNull(ArgList, new int[] { 0, 1 }))
                return null;
            else if (isUndefined(ArgList, new int[] { 0, 1 }))
                return Context.getUndefinedValue();
            String strValueToCheck = Context.toString(ArgList[0]);
            String strCodePage = Context.toString(ArgList[1]);
            byte bytearray[] = strValueToCheck.getBytes();
            CharsetDecoder d = Charset.forName(strCodePage).newDecoder();
            CharBuffer r = d.decode(ByteBuffer.wrap(bytearray));
            r.toString();
            bRC = true;
        } catch (Exception e) {
            bRC = false;
        }
    } else {
        throw Context.reportRuntimeError("The function call isCodepage requires 2 arguments.");
    }
    return Boolean.valueOf(bRC);
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static Object isCodepage(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    boolean bRC = false;
    if (ArgList.length == 2) {
        try {//w w w . ja va 2s .  co  m
            if (isNull(ArgList, new int[] { 0, 1 })) {
                return null;
            } else if (isUndefined(ArgList, new int[] { 0, 1 })) {
                return undefinedValue;
            }
            String strValueToCheck = (String) ArgList[0];
            String strCodePage = (String) ArgList[1];
            byte[] bytearray = strValueToCheck.getBytes();
            CharsetDecoder d = Charset.forName(strCodePage).newDecoder();
            CharBuffer r = d.decode(ByteBuffer.wrap(bytearray));
            r.toString();
            bRC = true;
        } catch (Exception e) {
            bRC = false;
        }
    } else {
        throw new RuntimeException("The function call isCodepage requires 2 arguments.");
    }
    return Boolean.valueOf(bRC);
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id (or lookup value) for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 * @throws IOException //ww w  .  j a  v  a 2  s .co m
 */
protected HashMap selectCredentials(String uid, CredentialProvider cp) throws NamingException, IOException {
    HashMap credentialResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String schemeName = null;
    if (cp instanceof AuthenticationScheme) {
        schemeName = ((AuthenticationScheme) cp).getName();
    }

    String principalLookupAttrName = this.getPrincipalLookupAttributeID();
    if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("")
            || !"strong-authentication".equals(schemeName)) {
        principalLookupAttrName = this.getPrincipalUidAttributeID();
    }

    String usersCtxDN = this.getUsersCtxDN();

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalLookupAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            String userDN = sr.getNameInNamespace();
            if (logger.isDebugEnabled())
                logger.debug("Processing results for entry '" + userDN + "'");

            for (int j = 0; j < credentialAttr.length; j++) {
                if (attrs.get(credentialAttr[j]) == null)
                    continue;

                //Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                Attribute attr = attrs.get(credentialAttr[j]);
                NamingEnumeration attrEnum = attr.getAll();
                while (attrEnum.hasMore()) {
                    Object credentialObject = attrEnum.next();
                    if (credentialObject == null)
                        continue;

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' of type '"
                                + credentialObject.getClass().getName() + ""
                                + (credentialObject.getClass().isArray()
                                        ? "[" + Array.getLength(credentialObject) + "]"
                                        : "")
                                + "'");

                    // if the attribute value is an array, cast it to byte[] and then convert to
                    // String using proper encoding
                    if (credentialObject.getClass().isArray()) {

                        try {
                            // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                            // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                            byte[] credentialData = (byte[]) credentialObject;
                            ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                            in.put(credentialData);
                            in.flip();

                            Charset charset = Charset.forName("UTF-8");
                            CharsetDecoder decoder = charset.newDecoder();
                            CharBuffer charBuffer = decoder.decode(in);

                            credentialValue = charBuffer.toString();

                        } catch (CharacterCodingException e) {
                            if (logger.isDebugEnabled())
                                logger.debug("Can't convert credential value to String using UTF-8");
                        }

                    } else if (credentialObject instanceof String) {
                        // The credential value must be a String ...
                        credentialValue = (String) credentialObject;

                    }

                    // Check what do we have ...
                    List credentials = (List) credentialResultSet.get(credentialName);
                    if (credentials == null) {
                        credentials = new ArrayList();
                    }
                    if (credentialValue != null) {
                        // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                        credentialValue = getSchemeFreeValue(credentialValue);
                        credentials.add(credentialValue);
                    } else {
                        // We have a binary credential, leave it as it is ... probably binary value.
                        credentials.add(credentialObject);
                    }
                    credentialResultSet.put(credentialName, credentials);

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' with value '"
                                + (credentialValue != null ? credentialValue : credentialObject) + "'");
                }
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return credentialResultSet;
}