List of usage examples for java.nio CharBuffer wrap
public static CharBuffer wrap(CharSequence chseq)
From source file:org.omnaest.utils.structure.container.ByteArrayContainer.java
/** * Copies the content from a {@link Readable} using the given encoding * //from w w w . j a va 2 s . co m * @param readable * @param encoding * @return this */ public ByteArrayContainer copyFrom(Readable readable, String encoding) { // this.isContentInvalid = false; if (readable != null) { // encoding = StringUtils.defaultString(encoding, ENCODING_UTF8); // try { // final StringBuffer stringBuffer = new StringBuffer(); final CharBuffer charBuffer = CharBuffer.wrap(new char[1000]); for (int read = 0; read >= 0;) { // charBuffer.clear(); read = readable.read(charBuffer); charBuffer.flip(); if (read > 0) { stringBuffer.append(charBuffer, 0, read); } } this.copyFrom(stringBuffer, encoding); } catch (IOException e) { // this.isContentInvalid = true; // this.handleException(e); } } // return this; }
From source file:de.undercouch.bson4jackson.BsonGenerator.java
@Override public void writeRaw(char[] text, int offset, int len) throws IOException, JsonGenerationException { _writeArrayFieldNameIfNeeded();//from w w w . ja va 2 s. co m _verifyValueWrite("write raw string"); _buffer.putByte(_typeMarker, BsonConstants.TYPE_BINARY); _buffer.putInt(text.length * 2); _buffer.putByte(BsonConstants.SUBTYPE_BINARY); _buffer.putString(CharBuffer.wrap(text)); flushBuffer(); }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>//from w ww . j ava2 s . c o m * * @param publicKey * @return true : ?false: */ private synchronized boolean deleteKey(String publicKey) { m_log.debug("delete key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped deleting publicKey"); return true; } Charset charset = Charset.forName("UTF-8"); CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder(); //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean delete = false; try { //RandomAccessFile? randomAccessFile = new RandomAccessFile(fi, "rw"); //FileChannel? channel = randomAccessFile.getChannel(); // for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) { if (null != (lock = channel.tryLock())) { break; } m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT) + " : " + fileName + "]"); Thread.sleep(FILELOCK_WAIT); } if (null == lock) { m_log.warn("file locking timeout."); return false; } // (?) synchronized (authKeyLock) { //?? ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); //?? channel.read(buffer); // ???????????0? buffer.flip(); //?? String contents = decoder.decode(buffer).toString(); // ? m_log.debug("contents " + contents.length() + " : " + contents); //?? List<String> keyCheck = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(contents, "\n"); while (tokenizer.hasMoreTokens()) { keyCheck.add(tokenizer.nextToken()); } //?????? int s = keyCheck.lastIndexOf(publicKey); if (s != -1) { // ? m_log.debug("remobe key : " + keyCheck.get(s)); keyCheck.remove(s); } //????? encoder.reset(); buffer.clear(); int i; if (keyCheck.size() > 0) { for (i = 0; i < keyCheck.size() - 1; i++) { encoder.encode(CharBuffer.wrap(keyCheck.get(i) + "\n"), buffer, false); } encoder.encode(CharBuffer.wrap(keyCheck.get(i)), buffer, true); } //??? buffer.flip(); channel.truncate(0); channel.position(0); channel.write(buffer); } delete = true; } catch (IOException e) { m_log.error(e.getMessage(), e); } catch (RuntimeException e) { m_log.error(e.getMessage(), e); } catch (InterruptedException e) { m_log.error(e.getMessage(), e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } //? if (lock != null) { lock.release(); } } catch (Exception e) { } } return delete; }
From source file:org.geppetto.frontend.SimulationListener.java
/** * Sends a message to a specific user. The id of the * WebSocket connection is used to contact the desired user. * /*from w w w.j ava2s . c om*/ * @param id - ID of WebSocket connection that will be sent a message * @param msg - The message the user will be receiving */ public void sendMessage(GeppettoVisitorWebSocket visitor, String msg) { try { long startTime = System.currentTimeMillis(); CharBuffer buffer = CharBuffer.wrap(msg); visitor.getWsOutbound().writeTextMessage(buffer); String debug = ((long) System.currentTimeMillis() - startTime) + "ms were spent sending a message of " + msg.length() / 1024 + "KB to the client"; logger.info(debug); } catch (IOException ignore) { logger.error("Unable to communicate with client " + ignore.getMessage()); } }
From source file:org.apache.ctakes.ytex.uima.annotators.NegexAnnotator.java
/** * check the negation status of the specfied term in the specified sentence * //from w w w . j av a 2s . c o m * @param aJCas * for adding annotations * @param s * the sentence in which we will look * @param ne * the named entity whose negation status will be checked. * @param checkPoss * should possibility be checked? * @param negPoss * should possiblities be negated? */ private void checkNegation(JCas aJCas, Sentence s, Annotation ne) { if (storeAsInterval && ne instanceof IdentifiedAnnotation) { // default is affirmed, which is coded as confidence = 1 ((IdentifiedAnnotation) ne).setConfidence(1); } // need to add . on either side due to the way the regexs are built String sentence = "." + s.getCoveredText() + "."; // allocate array of tokens // this maps each character of the sentence to a token NegexToken[] tokens = new NegexToken[sentence.length()]; // char buffer for modify the sentence // we want to 'black out' trigger words already found and the phrase we // were looking for CharBuffer buf = CharBuffer.wrap(sentence.toCharArray()); // calculate location of the ne relative to the sentence int neRelStart = ne.getBegin() - s.getBegin() + 1; int neRelEnd = ne.getEnd() - s.getBegin() + 1; // black out the ne in the sentence buffer for (int i = neRelStart; i < neRelEnd; i++) { // black out the named entity from the char buffer buf.put(i, '_'); } // look for negex rules in the sentence for (NegexRule rule : this.listNegexRules) { Matcher m = rule.getPattern().matcher(buf); while (m.find() == true) { // see if the range has not already been marked boolean bUnoccupied = true; for (int i = m.start(); i < m.end() && bUnoccupied; i++) bUnoccupied = tokens[i] == null; if (bUnoccupied) { // mark the range in the sentence with this token // black it out so other rules do not match NegexToken t = new NegexToken(m.start(), m.end(), rule); for (int i = m.start(); i < m.end() && bUnoccupied; i++) { // black out this range from the char buffer buf.put(i, '_'); // add the token to the array tokens[i] = t; } } } } // prenegation // look for a PREN rule before the ne, without any intervening stop tags NegexToken t = this.findTokenByTag("[PREN]", new String[] { "[CONJ]", "[PSEU]", "[POST]", "[PREP]", "[POSP]" }, true, neRelStart, neRelEnd, tokens); if (t != null) { // hit - negate the ne annotateNegation(aJCas, s, ne, t, true, false); } else { // look for POST rule after the ne, without any intervening stop // tags t = this.findTokenByTag("[POST]", new String[] { "[CONJ]", "[PSEU]", "[PREN]", "[PREP]", "[POSP]" }, false, neRelStart, neRelEnd, tokens); if (t != null) { annotateNegation(aJCas, s, ne, t, true, false); } else if (this.checkPossibilities || this.negatePossibilities) { // check possibles t = this.findTokenByTag("[PREP]", new String[] { "[CONJ]", "[PSEU]", "[PREN]", "[POST]", "[POSP]" }, true, neRelStart, neRelEnd, tokens); if (t != null) { annotateNegation(aJCas, s, ne, t, false, true); } else { t = this.findTokenByTag("[POSP]", new String[] { "[CONJ]", "[PSEU]", "[PREN]", "[POST]", "[PREP]" }, false, neRelStart, neRelEnd, tokens); if (t != null) annotateNegation(aJCas, s, ne, t, true, true); } } } }
From source file:com.all.networking.AbstractNetworkingService.java
private boolean write(IoSession session, NetworkingMessage networkingMessage) throws InterruptedException { String json = JsonConverter.toJson(networkingMessage); String encodedMessage = null; try {/*w w w . j a v a2 s.com*/ ByteBuffer byteBuffer = UTF_ENCODER.encode(CharBuffer.wrap(json)); encodedMessage = new String(Base64.encode(byteBuffer.array())); } catch (CharacterCodingException e) { LOG.warn("Could not encode message with UTF-8."); encodedMessage = new String(Base64.encode(json.getBytes())); } WriteFuture future = session.write(encodedMessage); future.await(); if (!future.isWritten()) { LOG.error("Could not send message through the network.", future.getException()); } return future.isWritten(); }
From source file:nl.tue.ddss.ifcrdf.model.IfcStepSerializer.java
private void writePrimitive(Resource val) throws IOException, SerializerException { if (isLogical(val)) { if (val.hasProperty(HASLOGICAL, EXPRESS_TRUE)) { print(BOOLEAN_TRUE);//from w w w .j av a 2s.c om } else if (val.hasProperty(HASLOGICAL, EXPRESS_FALSE)) { print(BOOLEAN_FALSE); } else if (val.hasProperty(HASLOGICAL, EXPRESS_UNDEFINED)) { print(BOOLEAN_UNDEFINED); } } else if (isReal(val) || isNumber(val)) { Double valDouble = val.getProperty(HASDOUBLE).getObject().asLiteral().getDouble(); if ((valDouble).isInfinite() || ((valDouble).isNaN())) { LOGGER.info("Serializing infinite or NaN double as 0.0"); print("0.0"); } else { String string = valDouble.toString(); if (string.endsWith(DOT_0)) { print(string.substring(0, string.length() - 1)); } else { print(string); } } } else if (isInteger(val)) { Integer valInteger = val.getProperty(HASINTEGER).getObject().asLiteral().getInt(); String string = valInteger.toString(); if (string.endsWith(DOT_0)) { print(string.substring(0, string.length() - 2)); } else { print(string); } } else if (isBoolean(val)) { if (val.hasLiteral(HASBOOLEAN, true)) { print(BOOLEAN_TRUE); } else if (val.hasLiteral(HASBOOLEAN, false)) { print(BOOLEAN_FALSE); } } else if (isString(val)) { print(SINGLE_QUOTE); String stringVal = val.getProperty(HASSTRING).getObject().asLiteral().getString(); for (int i = 0; i < stringVal.length(); i++) { char c = stringVal.charAt(i); if (c == '\'') { print("\'\'"); } else if (c == '\\') { print("\\\\"); } else if (c >= 32 && c <= 126) { // ISO 8859-1 print("" + c); } else if (c < 255) { // ISO 10646 and ISO 8859-1 are the same < 255 , using // ISO_8859_1 print("\\X\\" + new String(Hex.encodeHex( Charsets.ISO_8859_1.encode(CharBuffer.wrap(new char[] { (char) c })).array())) .toUpperCase()); } else { if (useIso8859_1) { // ISO 8859-1 with -128 offset ByteBuffer encode = Charsets.ISO_8859_1.encode(new String(new char[] { (char) (c - 128) })); print("\\S\\" + (char) encode.get()); } else { // The following code has not been tested (2012-04-25) // Use UCS-2 or UCS-4 // TODO when multiple sequential characters should be // encoded in UCS-2 or UCS-4, we don't really need to // add all those \X0\ \X2\ and \X4\ chars if (Character.isLowSurrogate(c)) { throw new SerializerException("Unexpected low surrogate range char"); } else if (Character.isHighSurrogate(c)) { // We need UCS-4, this is probably never happening if (i + 1 < stringVal.length()) { char low = stringVal.charAt(i + 1); if (!Character.isLowSurrogate(low)) { throw new SerializerException( "High surrogate char should be followed by char in low surrogate range"); } try { print("\\X4\\" + new String(Hex.encodeHex(Charset.forName("UTF-32") .encode(new String(new char[] { c, low })).array())).toUpperCase() + "\\X0\\"); } catch (UnsupportedCharsetException e) { throw new SerializerException(e); } i++; } else { throw new SerializerException( "High surrogate char should be followed by char in low surrogate range, but end of string reached"); } } else { // UCS-2 will do print("\\X2\\" + new String(Hex .encodeHex(Charsets.UTF_16BE.encode(CharBuffer.wrap(new char[] { c })).array())) .toUpperCase() + "\\X0\\"); } } } } print(SINGLE_QUOTE); } else if (isEnumeration(val)) { String enumVal = val.getLocalName(); print("." + enumVal + "."); } else { print(val == null ? "$" : val.toString()); } }
From source file:com.mcxiaoke.next.http.util.URLUtils.java
/** * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true. * * @param content the portion to decode * @param charset the charset to use * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is. * @return encoded string//w ww.j a v a2 s . co m */ private static String urlDecode(final String content, final Charset charset, final boolean plusAsBlank) { if (content == null) { return null; } final ByteBuffer bb = ByteBuffer.allocate(content.length()); final CharBuffer cb = CharBuffer.wrap(content); while (cb.hasRemaining()) { final char c = cb.get(); if (c == '%' && cb.remaining() >= 2) { final char uc = cb.get(); final char lc = cb.get(); final int u = Character.digit(uc, 16); final int l = Character.digit(lc, 16); if (u != -1 && l != -1) { bb.put((byte) ((u << 4) + l)); } else { bb.put((byte) '%'); bb.put((byte) uc); bb.put((byte) lc); } } else if (plusAsBlank && c == '+') { bb.put((byte) ' '); } else { bb.put((byte) c); } } bb.flip(); return charset.decode(bb).toString(); }
From source file:org.tolven.security.password.PasswordHolder.java
public boolean isPasswordStoreUpToDate() { Passwords initialPasswords = loadPasswords(); HashMap<String, PasswordInfo> passwordMapCopy = new HashMap<String, PasswordInfo>(getPasswordMap()); passwordMapCopy.remove(getAdminGroupId()); if (passwordMapCopy.size() != initialPasswords.getPasswordInfo().size()) { return false; }// w ww . j av a 2s. c om char[] password = null; PasswordInfo passwordInfo = null; for (PasswordDetail passwordDetail : initialPasswords.getPasswordInfo()) { passwordInfo = passwordMapCopy.get(passwordDetail.getRefId()); if (passwordInfo == null) { return false; } password = getPassword(passwordInfo.getRefId()); CharBuffer passwordBuff = CharBuffer.wrap(password); if (!passwordBuff.toString().equals(passwordDetail.getPassword())) return false; } return true; }
From source file:com.albert.util.StringUtilCommon.java
public static boolean isISO88593(String v) { if (v == null || v.length() == 0) { return true; }//from w w w. j a va2 s. c o m CharsetEncoder d = Charset.forName("ISO-8859-3").newEncoder(); d.onMalformedInput(CodingErrorAction.REPORT); d.onUnmappableCharacter(CodingErrorAction.REPORT); try { ByteBuffer bb = d.encode(CharBuffer.wrap(v.toCharArray())); bb.toString(); } catch (CharacterCodingException e) { return false; } return true; }