List of usage examples for java.nio CharBuffer toString
public String toString()
From source file:fr.cls.atoll.motu.processor.wps.StringList.java
public static CharBuffer byteConvert(byte[] value, String charset) { ByteBuffer bb = ByteBuffer.wrap(value); CharBuffer charBuffer = null; try {// ww w.j a va 2s .c o m Charset csets = Charset.forName(charset); charBuffer = csets.decode(bb); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } String str = charBuffer.toString(); System.out.println("XXXXXXXX"); System.out.println(str); return charBuffer; }
From source file:org.josso.gateway.identity.service.store.db.IdentityDAO.java
/** * Builds an array of credentials based on a ResultSet * Column names are used to build a credential. *//*from w ww .ja v a 2 s.c o m*/ protected Credential[] fetchCredentials(ResultSet rs) throws SQLException, IOException, SSOAuthenticationException { List creds = new ArrayList(); while (rs.next()) { ResultSetMetaData md = rs.getMetaData(); // Each column is a credential, the column name is used as credential name ... for (int i = 1; i <= md.getColumnCount(); i++) { String cName = md.getColumnLabel(i); Object credentialObject = rs.getObject(i); String credentialValue = null; // 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; } Credential c = null; if (credentialValue != null) { c = _cp.newCredential(cName, credentialValue); } else { c = _cp.newCredential(cName, credentialObject); } if (c != null) { creds.add(c); } } } return (Credential[]) creds.toArray(new Credential[creds.size()]); }
From source file:com.adaptris.core.AdaptrisMessageCase.java
@Test public void testWriter_ChangeCharEncoding() throws Exception { StringBuilder sb = new StringBuilder(PAYLOAD2); Charset iso8859 = Charset.forName("ISO-8859-1"); ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[] { (byte) 0xFC // a u with an umlaut in ISO-8859-1 });/*w w w. ja v a 2 s. com*/ CharBuffer d1 = iso8859.decode(inputBuffer); sb.append(d1.toString()); String payload = sb.toString(); AdaptrisMessage msg1 = createMessage("ISO-8859-1"); PrintWriter out = new PrintWriter(msg1.getWriter("UTF-8")); out.print(payload); out.close(); assertEquals("UTF-8", msg1.getCharEncoding()); assertFalse(Arrays.equals(payload.getBytes("ISO-8859-1"), msg1.getPayload())); }
From source file:org.rapla.rest.gwtjsonrpc.server.JsonServlet.java
private String readBody(final ActiveCall call) throws IOException { if (!isBodyJson(call)) { throw new JsonParseException("Invalid Request Content-Type"); }/*from w ww . ja v a 2s .c o m*/ if (!isBodyUTF8(call)) { throw new JsonParseException("Invalid Request Character-Encoding"); } final int len = call.httpRequest.getContentLength(); if (len < 0) { throw new JsonParseException("Invalid Request Content-Length"); } if (len == 0) { throw new JsonParseException("Invalid Request POST Body Required"); } if (len > maxRequestSize()) { throw new JsonParseException("Invalid Request POST Body Too Large"); } final InputStream in = call.httpRequest.getInputStream(); if (in == null) { throw new JsonParseException("Invalid Request POST Body Required"); } try { final byte[] body = new byte[len]; int off = 0; while (off < len) { final int n = in.read(body, off, len - off); if (n <= 0) { throw new JsonParseException("Invalid Request Incomplete Body"); } off += n; } final CharsetDecoder d = Charset.forName(JsonConstants.JSON_ENC).newDecoder(); d.onMalformedInput(CodingErrorAction.REPORT); d.onUnmappableCharacter(CodingErrorAction.REPORT); try { ByteBuffer wrap = ByteBuffer.wrap(body); CharBuffer decode = d.decode(wrap); return decode.toString(); } catch (CharacterCodingException e) { throw new JsonParseException("Invalid Request Not UTF-8", e); } } finally { in.close(); } }
From source file:org.geppetto.frontend.controllers.WebsocketConnection.java
/** * Receives message(s) from client.//from w w w . j a v a2 s. c o m * * @throws IOException */ @Override protected void onTextMessage(CharBuffer message) throws IOException { String msg = message.toString(); Map<String, String> parameters; long experimentId = -1; long projectId = -1; String instancePath = null; // de-serialize JSON GeppettoTransportMessage gmsg = new Gson().fromJson(msg, GeppettoTransportMessage.class); String requestID = gmsg.requestID; // switch on message type // NOTE: each message handler knows how to interpret the GeppettoMessage data field switch (InboundMessages.valueOf(gmsg.type.toUpperCase())) { case GEPPETTO_VERSION: { connectionHandler.getVersionNumber(requestID); break; } case NEW_EXPERIMENT: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); projectId = Long.parseLong(parameters.get("projectId")); connectionHandler.newExperiment(requestID, projectId); break; } case CLONE_EXPERIMENT: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); projectId = Long.parseLong(parameters.get("projectId")); experimentId = Long.parseLong(parameters.get("experimentId")); connectionHandler.cloneExperiment(requestID, projectId, experimentId); break; } case LOAD_PROJECT_FROM_URL: { connectionHandler.loadProjectFromURL(requestID, gmsg.data); messageSender.reset(); break; } case LOAD_PROJECT_FROM_ID: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); if (parameters.containsKey("experimentId")) { experimentId = Long.parseLong(parameters.get("experimentId")); } projectId = Long.parseLong(parameters.get("projectId")); connectionHandler.loadProjectFromId(requestID, projectId, experimentId); messageSender.reset(); break; } case LOAD_PROJECT_FROM_CONTENT: { connectionHandler.loadProjectFromContent(requestID, gmsg.data); messageSender.reset(); break; } case PERSIST_PROJECT: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); projectId = Long.parseLong(parameters.get("projectId")); connectionHandler.persistProject(requestID, projectId); break; } case SAVE_PROJECT_PROPERTIES: { ReceivedObject receivedObject = new Gson().fromJson(gmsg.data, ReceivedObject.class); connectionHandler.saveProjectProperties(requestID, receivedObject.projectId, receivedObject.properties); break; } case SAVE_EXPERIMENT_PROPERTIES: { ReceivedObject receivedObject = new Gson().fromJson(gmsg.data, ReceivedObject.class); connectionHandler.saveExperimentProperties(requestID, receivedObject.projectId, receivedObject.experimentId, receivedObject.properties); break; } case LOAD_EXPERIMENT: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); connectionHandler.loadExperiment(requestID, experimentId, projectId); break; } case GET_SCRIPT: { String urlString = gmsg.data; URL url = null; try { url = URLReader.getURL(urlString); connectionHandler.sendScriptData(requestID, url, this); } catch (MalformedURLException e) { sendMessage(requestID, OutboundMessages.ERROR_READING_SCRIPT, ""); } break; } case GET_DATA_SOURCE_RESULTS: { URL url = null; String dataSourceName; try { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); url = URLReader.getURL(parameters.get("url")); dataSourceName = parameters.get("data_source_name"); connectionHandler.sendDataSourceResults(requestID, dataSourceName, url, this); } catch (MalformedURLException e) { sendMessage(requestID, OutboundMessages.ERROR_READING_SCRIPT, ""); } break; } case PLAY_EXPERIMENT: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); connectionHandler.playExperiment(requestID, experimentId, projectId); break; } case DELETE_EXPERIMENT: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); connectionHandler.deleteExperiment(requestID, experimentId, projectId); break; } case RUN_EXPERIMENT: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); connectionHandler.runExperiment(requestID, experimentId, projectId); break; } case SET_WATCHED_VARIABLES: { ReceivedObject receivedObject = new Gson().fromJson(gmsg.data, ReceivedObject.class); try { connectionHandler.setWatchedVariables(requestID, receivedObject.variables, receivedObject.experimentId, receivedObject.projectId, receivedObject.watch); } catch (GeppettoExecutionException e) { sendMessage(requestID, OutboundMessages.ERROR_SETTING_WATCHED_VARIABLES, ""); } catch (GeppettoInitializationException e) { sendMessage(requestID, OutboundMessages.ERROR_SETTING_WATCHED_VARIABLES, ""); } break; } case GET_SUPPORTED_OUTPUTS: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); instancePath = parameters.get("instancePath"); connectionHandler.getSupportedOuputs(requestID, instancePath, experimentId, projectId); break; } case DOWNLOAD_MODEL: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); instancePath = parameters.get("instancePath"); String format = parameters.get("format"); connectionHandler.downloadModel(requestID, instancePath, format, experimentId, projectId); break; } case SET_PARAMETERS: { ReceivedObject receivedObject = new Gson().fromJson(gmsg.data, ReceivedObject.class); connectionHandler.setParameters(requestID, receivedObject.modelParameters, receivedObject.projectId, receivedObject.experimentId); break; } case LINK_DROPBOX: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); String key = parameters.get("key"); connectionHandler.linkDropBox(requestID, key); break; } case UNLINK_DROPBOX: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); String key = parameters.get("key"); connectionHandler.unLinkDropBox(requestID, key); break; } case UPLOAD_MODEL: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); String format = parameters.get("format"); String aspectPath = parameters.get("aspectPath"); connectionHandler.uploadModel(aspectPath, projectId, experimentId, format); break; } case UPLOAD_RESULTS: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); String format = parameters.get("format"); String aspectPath = parameters.get("aspectPath"); connectionHandler.uploadResults(aspectPath, projectId, experimentId, format); break; } case DOWNLOAD_RESULTS: { parameters = new Gson().fromJson(gmsg.data, new TypeToken<HashMap<String, String>>() { }.getType()); experimentId = Long.parseLong(parameters.get("experimentId")); projectId = Long.parseLong(parameters.get("projectId")); String format = parameters.get("format"); String aspectPath = parameters.get("aspectPath"); connectionHandler.downloadResults(requestID, aspectPath, projectId, experimentId, format); break; } case EXPERIMENT_STATUS: { connectionHandler.checkExperimentStatus(requestID, gmsg.data); break; } case FETCH_VARIABLE: { GeppettoModelAPIParameters receivedObject = new Gson().fromJson(gmsg.data, GeppettoModelAPIParameters.class); connectionHandler.fetchVariable(requestID, receivedObject.projectId, receivedObject.dataSourceId, receivedObject.variableId); break; } case RESOLVE_IMPORT_TYPE: { GeppettoModelAPIParameters receivedObject = new Gson().fromJson(gmsg.data, GeppettoModelAPIParameters.class); connectionHandler.resolveImportType(requestID, receivedObject.projectId, receivedObject.paths); break; } case RUN_QUERY: { GeppettoModelAPIParameters receivedObject = new Gson().fromJson(gmsg.data, GeppettoModelAPIParameters.class); connectionHandler.runQuery(requestID, receivedObject.projectId, receivedObject.runnableQueries); break; } case RUN_QUERY_COUNT: { GeppettoModelAPIParameters receivedObject = new Gson().fromJson(gmsg.data, GeppettoModelAPIParameters.class); connectionHandler.runQueryCount(requestID, receivedObject.projectId, receivedObject.runnableQueries); break; } default: { // NOTE: no other messages expected for now } } }
From source file:morphy.service.SocketConnectionService.java
protected synchronized String readMessage(SocketChannel channel) { try {/*from w ww. ja v a 2 s. c o m*/ ByteBuffer buffer = ByteBuffer.allocate(maxCommunicationSizeBytes); int charsRead = -1; try { charsRead = channel.read(buffer); } catch (IOException cce) { if (channel.isOpen()) { channel.close(); if (LOG.isInfoEnabled()) { LOG.info("Closed channel " + channel); } } } if (charsRead == -1) { return null; } else if (charsRead > 0) { buffer.flip(); Charset charset = Charset.forName(Morphy.getInstance().getMorphyPreferences() .getString(PreferenceKeys.SocketConnectionServiceCharEncoding)); SocketChannelUserSession socketChannelUserSession = socketToSession.get(channel.socket()); byte[] bytes = buffer.array(); buffer.position(0); System.out.println("IN: " + new String(bytes).trim()); if (looksLikeTimesealInit(bytes)) { if (socketChannelUserSession.usingTimeseal == false) { // First time? socketChannelUserSession.usingTimeseal = true; return MSG_TIMESEAL_OK; } } if (socketChannelUserSession.usingTimeseal) { /* * Clients may pass multiple Timeseal-encoded messages at once. * We need to parse each separated message to Timeseal decoder as necessary. */ byte[] bytesToDecode = Arrays.copyOfRange(bytes, 0, charsRead - 1 /* \n or 10 */); byte[][] splitBytes = TimesealCoder.splitBytes(bytesToDecode, (byte) 10); buffer = ByteBuffer.allocate(bytesToDecode.length); buffer.position(0); for (int i = 0; i < splitBytes.length; i++) { byte[] splitBytesToDecode = splitBytes[i]; TimesealParseResult parseResult = timesealCoder.decode(splitBytesToDecode); if (parseResult != null) { System.out.println(parseResult.getTimestamp()); parseResult.setMessage(parseResult.getMessage() + "\n"); System.out.println(parseResult.getMessage()); buffer.put(parseResult.getMessage().getBytes(charset)); } } //buffer.position(0); buffer.flip(); } CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(buffer); String message = charBuffer.toString(); return message; //System.out.println(message); //return ""; } else { return ""; } } catch (Throwable t) { if (LOG.isErrorEnabled()) LOG.error("Error reading SocketChannel " + channel.socket().getLocalAddress(), t); return null; } }
From source file:net.sf.extjwnl.princeton.file.PrincetonRandomAccessDictionaryFile.java
public String readLineWord() throws IOException { if (isOpen()) { synchronized (file) { //in data files offset needs no decoding, it is numeric if (null == encoding || DictionaryFileType.DATA == getFileType()) { StringBuilder input = new StringBuilder(); int c; while (((c = raFile.read()) != -1) && c != '\n' && c != '\r' && c != ' ') { input.append((char) c); }/*w w w . jav a 2 s . c o m*/ return input.toString(); } else { int idx = 1; int c; while (((c = raFile.read()) != -1) && c != '\n' && c != '\r' && c != ' ') { lineArr[idx - 1] = (byte) c; idx++; if (LINE_MAX == idx) { byte[] t = new byte[LINE_MAX * 2]; System.arraycopy(lineArr, 0, t, 0, LINE_MAX); lineArr = t; LINE_MAX = 2 * LINE_MAX; } } if (1 < idx) { ByteBuffer bb = ByteBuffer.wrap(lineArr, 0, idx - 1); CharBuffer cb = decoder.decode(bb); return cb.toString(); } else { return ""; } } } } else { throw new JWNLRuntimeException("PRINCETON_EXCEPTION_001"); } }
From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java
public String loadTouchOscXML(String zipTouchoscFilePath) { List<String> touchoscFilePathList = new ArrayList<String>(); IPath path = new Path(zipTouchoscFilePath); String xml = ""; try {// w w w.j a va 2 s . c om 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()); } BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8"))); CharBuffer charBuffer = CharBuffer.allocate(65535); while (reader.read(charBuffer) != -1) charBuffer.flip(); xml = charBuffer.toString(); } fileIS.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } return xml; }
From source file:net.sf.extjwnl.princeton.file.PrincetonRandomAccessDictionaryFile.java
public String readLine() throws IOException { if (isOpen()) { synchronized (file) { if (null == encoding) { return raFile.readLine(); } else { int c = -1; boolean eol = false; int idx = 1; while (!eol) { switch (c = read()) { case -1: case '\n': eol = true;/* w ww.j a v a2s. c o m*/ break; case '\r': eol = true; long cur = getFilePointer(); if ((read()) != '\n') { seek(cur); } break; default: { lineArr[idx - 1] = (byte) c; idx++; if (LINE_MAX == idx) { byte[] t = new byte[LINE_MAX * 2]; System.arraycopy(lineArr, 0, t, 0, LINE_MAX); lineArr = t; LINE_MAX = 2 * LINE_MAX; } break; } } } if ((c == -1) && (1 == idx)) { return null; } if (1 < idx) { ByteBuffer bb = ByteBuffer.wrap(lineArr, 0, idx - 1); try { CharBuffer cb = decoder.decode(bb); return cb.toString(); } catch (MalformedInputException e) { return " "; } } else { return null; } } } } else { throw new JWNLRuntimeException("PRINCETON_EXCEPTION_001"); } }
From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java
public void dumpTouchOsc(TOP top, String destDirname, String destFilename) { reverseZOrders(top);//w w w .ja v a 2s .c o m // // Get tests for TouchOSC legacy compliances : need precise version info // //applyBase64Transformation(top); // 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); String dirname; if (destDirname == null) { dirname = Platform.getInstanceLocation().getURL().getPath() + "/" + UUID.randomUUID().toString(); if (Platform.inDebugMode()) { System.out.println("creating " + dirname + " directory"); } new File(dirname).mkdir(); } else { dirname = destDirname; } // // Get the URI of the model file. // URI touchoscURI = URI.createFileURI(dirname + "/" + "index.xml"); // // Demand load the resource for this file. // Resource resource = resourceSet.createResource(touchoscURI); resource.getContents().add(top); try { Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); resource.save(options); } catch (IOException e) { e.printStackTrace(); } String TOUCHOSC_HEADER = "<touchosc:TOP xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:touchosc=\"http:///net.sf.smbt.touchosc/src/net/sf/smbt/touchosc/model/touchosc.xsd\">"; String TOUCHOSC_FOOTER = "</touchosc:TOP>"; String path = touchoscURI.path().toString(); String outputZipFile = dirname + "/" + destFilename + ".touchosc"; try { FileInputStream touchoscFile = new FileInputStream(path); BufferedReader reader = new BufferedReader( new InputStreamReader(touchoscFile, Charset.forName("ASCII"))); CharBuffer charBuffer = CharBuffer.allocate(65535); while (reader.read(charBuffer) != -1) charBuffer.flip(); String content = charBuffer.toString(); content = content.replace(TOUCHOSC_HEADER, "<touchosc>"); content = content.replace(TOUCHOSC_FOOTER, "</touchosc>"); content = content.replace("<layout>", "<layout version=\"10\" mode=\"" + top.getLayout().getMode() + "\" orientation=\"" + top.getLayout().getOrientation() + "\">"); 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="); content = content.replace("xypad", "xy"); touchoscFile.close(); FileOutputStream os = new FileOutputStream(path); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8"))); writer.write(content); writer.flush(); os.flush(); os.close(); FileOutputStream fos = new FileOutputStream(outputZipFile); ZipOutputStream fileOS = new ZipOutputStream(fos); ZipEntry ze = new ZipEntry("index.xml"); fileOS.putNextEntry(ze); fileOS.write(content.getBytes(Charset.forName("UTF-8"))); fileOS.flush(); fileOS.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { File f = new File(path); if (f.exists() && f.canWrite()) { if (!f.delete()) { throw new IllegalArgumentException(path + " deletion failed"); } } } }