List of usage examples for com.google.common.io CharStreams toString
public static String toString(Readable r) throws IOException
From source file:com.google.cloud.testing.BaseEmulatorHelper.java
protected final String sendPostRequest(String request) throws IOException { URL url = new URL("http", DEFAULT_HOST, this.port, request); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true);//from w w w . j av a2 s . co m OutputStream out = con.getOutputStream(); out.write("".getBytes()); out.flush(); InputStream in = con.getInputStream(); String response = CharStreams.toString(new InputStreamReader(con.getInputStream())); in.close(); return response; }
From source file:com.cisco.oss.foundation.directory.utils.HttpUtils.java
/** * Invoke REST Service using DELETE method. * * @param urlStr//from w ww .java2s. c om * the REST URL String. * @return * the HttpResponse. * @throws IOException */ public static HttpResponse deleteJson(String urlStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Accept", "application/json"); urlConnection.setRequestMethod("DELETE"); BufferedReader in = null; try { int errorCode = urlConnection.getResponseCode(); if ((errorCode <= 202) && (errorCode >= 200)) { in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); } else { InputStream error = urlConnection.getErrorStream(); if (error != null) { in = new BufferedReader(new InputStreamReader(error)); } } String json = null; if (in != null) { json = CharStreams.toString(in); } return new HttpResponse(errorCode, json); } finally { if (in != null) { in.close(); } } }
From source file:org.opensextant.solrtexttagger.TaggerRequestHandler.java
@Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { setTopInitArgsAsInvariants(req);/*from ww w . j a v a 2s . c o m*/ //--Read params final String indexedField = req.getParams().get("field"); if (indexedField == null) throw new RuntimeException("required param 'field'"); final TagClusterReducer tagClusterReducer = chooseTagClusterReducer(req.getParams().get(OVERLAPS)); final int rows = req.getParams().getInt(CommonParams.ROWS, 10000); final int tagsLimit = req.getParams().getInt(TAGS_LIMIT, 1000); final boolean addMatchText = req.getParams().getBool(MATCH_TEXT, false); final SchemaField idSchemaField = req.getSchema().getUniqueKeyField(); if (idSchemaField == null) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "The tagger requires a" + "uniqueKey in the schema.");//TODO this could be relaxes } final boolean skipAltTokens = req.getParams().getBool(SKIP_ALT_TOKENS, false); final boolean ignoreStopWords = req.getParams().getBool(IGNORE_STOPWORDS, fieldHasIndexedStopFilter(indexedField, req)); final boolean htmlOffsetAdjust = req.getParams().getBool(HTML_OFFSET_ADJUST, false); final boolean xmlOffsetAdjust = req.getParams().getBool(XML_OFFSET_ADJUST, false); final String nonTaggableTags = req.getParams().get(NON_TAGGABLE_TAGS); final String textToTag = req.getParams().get(TEXT_TO_TAG); //--Get posted data Reader inputReader = null; Iterable<ContentStream> streams = req.getContentStreams(); if (streams != null) { Iterator<ContentStream> iter = streams.iterator(); if (iter.hasNext()) { inputReader = iter.next().getReader(); } if (iter.hasNext()) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, getClass().getSimpleName() + " does not support multiple ContentStreams"); } } if (inputReader == null) { if (textToTag != null) { inputReader = new StringReader(textToTag); } else { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, getClass().getSimpleName() + " requires text to be POSTed to it"); } } final String inputString;//only populated if needed if (addMatchText || xmlOffsetAdjust || htmlOffsetAdjust) { //Read the input fully into a String buffer that we'll need later, // then replace the input with a reader wrapping the buffer. inputString = CharStreams.toString(inputReader); inputReader.close(); inputReader = new StringReader(inputString); } else { inputString = null;//not used } final OffsetCorrector offsetCorrector = initOffsetCorrector(htmlOffsetAdjust, xmlOffsetAdjust, inputString, nonTaggableTags); final SolrIndexSearcher searcher = req.getSearcher(); final FixedBitSet matchDocIdsBS = new FixedBitSet(searcher.maxDoc()); final List tags = new ArrayList(2000); try { Analyzer analyzer = req.getSchema().getField(indexedField).getType().getQueryAnalyzer(); try (TokenStream tokenStream = analyzer.tokenStream("", inputReader)) { Terms terms = searcher.getSlowAtomicReader().terms(indexedField); if (terms == null) throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "field " + indexedField + " has no indexed data"); Tagger tagger = new Tagger(terms, computeDocCorpus(req), tokenStream, tagClusterReducer, skipAltTokens, ignoreStopWords) { @SuppressWarnings("unchecked") @Override protected void tagCallback(int startOffset, int endOffset, Object docIdsKey) { if (tags.size() >= tagsLimit) return; if (offsetCorrector != null) { int[] offsetPair = offsetCorrector.correctPair(startOffset, endOffset); if (offsetPair == null) { log.debug("Discarded offsets [{}, {}] because couldn't balance XML.", startOffset, endOffset); return; } startOffset = offsetPair[0]; endOffset = offsetPair[1]; } NamedList tag = new NamedList(); tag.add("startOffset", startOffset); tag.add("endOffset", endOffset); if (addMatchText) tag.add("matchText", inputString.substring(startOffset, endOffset)); //below caches, and also flags matchDocIdsBS tag.add("ids", lookupSchemaDocIds(docIdsKey)); tags.add(tag); } Map<Object, List> docIdsListCache = new HashMap<>(2000); ValueSourceAccessor uniqueKeyCache = new ValueSourceAccessor(searcher, idSchemaField.getType().getValueSource(idSchemaField, null)); @SuppressWarnings("unchecked") private List lookupSchemaDocIds(Object docIdsKey) { List schemaDocIds = docIdsListCache.get(docIdsKey); if (schemaDocIds != null) return schemaDocIds; IntsRef docIds = lookupDocIds(docIdsKey); //translate lucene docIds to schema ids schemaDocIds = new ArrayList(docIds.length); for (int i = docIds.offset; i < docIds.offset + docIds.length; i++) { int docId = docIds.ints[i]; matchDocIdsBS.set(docId);//also, flip docid in bitset schemaDocIds.add(uniqueKeyCache.objectVal(docId));//translates here } assert !schemaDocIds.isEmpty(); docIdsListCache.put(docIds, schemaDocIds); return schemaDocIds; } }; tagger.enableDocIdsCache(2000);//TODO configurable tagger.process(); } } finally { inputReader.close(); } rsp.add("tagsCount", tags.size()); rsp.add("tags", tags); rsp.setReturnFields(new SolrReturnFields(req)); //Solr's standard name for matching docs in response rsp.add("response", getDocList(rows, matchDocIdsBS)); }
From source file:com.stackframe.sarariman.RootServlet.java
@Override protected void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.err.println("in RootServlet::doPropfind pathInfo=" + request.getPathInfo() + " requestURI=" + request.getRequestURI());/*from ww w . j ava 2 s . c o m*/ String requestDocument = CharStreams.toString(new InputStreamReader(request.getInputStream(), "UTF-8")); System.err.println("in RootServlet::doPropfind headers='" + headers(request) + "'"); String depth = request.getHeader("depth"); System.err.println("in RootServlet::doPropfind depth='" + depth + "'"); System.err.println("in RootServlet::doPropfind requestDocument='" + requestDocument + "'"); Document d; if (depth.equals("0")) { d = makePROPFINDResponseDepth0(request.getContextPath()); } else { d = makePROPFINDResponseDepth1(request.getContextPath()); } System.err.println("going to send response:"); System.err.println(serialize(d)); PrintWriter writer = response.getWriter(); serialize(d, writer); writer.close(); response.setStatus(207); }
From source file:com.microsoft.graph.snippets.snippet.DrivesSnippets.java
static DrivesSnippets[] getDrivesSnippets() { return new DrivesSnippets[] { // Marker element new DrivesSnippets(null) { @Override/*from ww w . j a v a 2 s.c o m*/ public void request(ICallback callback) { //No implementation } }, //Snippets /* Get the user's drive * GET https://graph.microsoft.com/{version}/me/drive * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/drive_get */ new DrivesSnippets<JsonObject>(get_me_drive) { @Override public void request(final ICallback<JsonObject> callback) { mGraphServiceClient.getMe().getDrive().buildRequest().get(new ICallback<Drive>() { @Override public void success(Drive drive) { callback.success(drive.getRawObject()); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } }, /* * Get files in the root folder * GET https://graph.microsoft.com/{version}/me/drive/root/children * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/item_list_children */ new DrivesSnippets<JsonObject>(get_me_files) { @Override public void request(final ICallback<JsonObject> callback) { //Get files in root folder mGraphServiceClient.getMe().getDrive().getRoot().getChildren().buildRequest() .get(new ICallback<IDriveItemCollectionPage>() { @Override public void success(IDriveItemCollectionPage iDriveItemCollectionPage) { callback.success(iDriveItemCollectionPage.getRawObject()); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } }, /* * Create a file * PUT https://graph.microsoft.com/{version}/me/drive/root/children/{filename}/content * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/item_post_children */ new DrivesSnippets<JsonObject>(create_me_file) { @Override public void request(final ICallback<JsonObject> callback) { // create a new file try { String guid = UUID.randomUUID().toString(); byte[] byteArray = guid.getBytes("UTF-8"); mGraphServiceClient.getMe().getDrive().getRoot().getChildren(guid).getContent() .buildRequest().put(byteArray, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { callback.success(driveItem.getRawObject()); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } } }, /* * Download the content of a file * GET https://graph.microsoft.com/{version}/me/drive/items/{filename}/content * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/item_downloadcontent */ new DrivesSnippets<JsonObject>(download_me_file) { @Override public void request(final ICallback<JsonObject> callback) { //create a new file to download String guid = UUID.randomUUID().toString(); byte[] byteArray = null; try { byteArray = guid.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } mGraphServiceClient.getMe().getDrive().getRoot().getChildren(guid).getContent() .buildRequest().put(byteArray, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { // Get the guid that the service assigned to my file String guid = driveItem.id; mGraphServiceClient.getMe().getDrive().getItems().byId(guid).getContent() .buildRequest().get(new ICallback<InputStream>() { @Override public void success(InputStream inputStream) { final InputStreamReader inr = new InputStreamReader( inputStream); String text; try { text = CharStreams.toString(inr); JsonObject result = new JsonObject(); result.addProperty("value", text); callback.success(result); } catch (IOException ex) { ex.printStackTrace(); } } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } }, /* * Update the content of a file * PUT https://graph.microsoft.com/{version}/me/drive/items/{filename}/content * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/item_update */ new DrivesSnippets<JsonObject>(update_me_file) { @Override public void request(final ICallback<JsonObject> callback) { //create a new file to update String guid = UUID.randomUUID().toString(); byte[] byteArray = null; try { byteArray = guid.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } mGraphServiceClient.getMe().getDrive().getRoot().getChildren(guid).getContent() .buildRequest().put(byteArray, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { // This is the new content that we use to update the file byte[] byteArray = null; try { byteArray = "A plain text file".getBytes("UTF-8"); mGraphServiceClient.getMe().getDrive().getItems().byId(driveItem.id) .getContent().buildRequest() .put(byteArray, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { callback.success(driveItem.getRawObject()); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } catch (IOException ex) { ex.printStackTrace(); } } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } }, /* * Delete the content of a file * DELETE https://graph.microsoft.com/{version}/me/drive/items/{fileId}/ * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/item_delete */ new DrivesSnippets<JsonObject>(delete_me_file) { @Override public void request(final ICallback<JsonObject> callback) { //create a new file to delete String guid = UUID.randomUUID().toString(); byte[] byteArray = null; try { byteArray = guid.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } mGraphServiceClient.getMe().getDrive().getRoot().getChildren(guid).getContent() .buildRequest().put(byteArray, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { mGraphServiceClient.getMe().getDrive().getItems().byId(driveItem.id) .buildRequest().delete(new ICallback<Void>() { @Override public void success(Void aVoid) { callback.success(null); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } }, /* * Renames a file * PATCH https://graph.microsoft.com/{version}/me/drive/items/{fileId}/ * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/item_update */ new DrivesSnippets<JsonObject>(rename_me_file) { @Override public void request(final ICallback<JsonObject> callback) { //create a new file to rename String guid = UUID.randomUUID().toString(); byte[] byteArray = null; try { byteArray = guid.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } mGraphServiceClient.getMe().getDrive().getRoot().getChildren(guid).getContent() .buildRequest().put(byteArray, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { DriveItem renamedDriveItem = new DriveItem(); renamedDriveItem.name = "Updated name"; mGraphServiceClient.getMe().getDrive().getItems().byId(driveItem.id) .buildRequest().patch(renamedDriveItem, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { callback.success(driveItem.getRawObject()); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } }, /* * Creates a folder * POST https://graph.microsoft.com/me/drive/root/children * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/item_post_children */ new DrivesSnippets<JsonObject>(create_me_folder) { @Override public void request(final ICallback<JsonObject> callback) { String guid = UUID.randomUUID().toString(); DriveItem driveItem = new DriveItem(); driveItem.name = guid; driveItem.folder = new Folder(); mGraphServiceClient.getMe().getDrive().getRoot().getChildren().buildRequest() .post(driveItem, new ICallback<DriveItem>() { @Override public void success(DriveItem driveItem) { callback.success(driveItem.getRawObject()); } @Override public void failure(ClientException ex) { callback.failure(ex); } }); } } }; }
From source file:com.google.appinventor.server.project.youngandroid.YoungAndroidWebStartSupport.java
/** * {@inheritDoc}/* ww w.ja v a2 s.com*/ * * Handle Post requests from codeblocks. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp, String userId, long projectId, String fileName) { try { String encoding = req.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), encoding)); String content; try { content = CharStreams.toString(reader); } finally { reader.close(); } if (fileName.startsWith(YaHttpServerConstants.CODEBLOCKS_SAVE_PORT)) { // Special case for saving the codeblocks port. projectId is ignored. int port = Integer.parseInt(content); byte[] data = JsonpConnectionUtil.saveJsonpConnectionInfo(getStorageIo(), userId, YaHttpServerConstants.CODEBLOCKS_INFO_FILE_PREFIX, port); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain; charset=utf-8"); OutputStream out = resp.getOutputStream(); out.write(data); out.close(); } else { // Codeblocks is posting a project source file. if (!content.endsWith("\n")) { content = content + "\n"; } List<String> sourceFiles = getStorageIo().getProjectSourceFiles(userId, projectId); if (!sourceFiles.contains(fileName)) { getStorageIo().addSourceFilesToProject(userId, projectId, false, fileName); } getStorageIo().uploadFile(projectId, fileName, userId, content, StorageUtil.DEFAULT_CHARSET); // TODO(sharon): technically this should probably return HttpServletResponse.SC_CREATED (201) // I'm not sure whether it really matters. resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(CONTENT_TYPE); } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, req, null, e); } }
From source file:org.apache.pulsar.client.impl.auth.AuthenticationAthenz.java
private PrivateKey loadPrivateKey(String privateKeyURL) { PrivateKey privateKey = null; try {/* w ww .j a v a2 s. c om*/ URLConnection urlConnection = new URL(privateKeyURL).openConnection(); String protocol = urlConnection.getURL().getProtocol(); if ("data".equals(protocol) && !APPLICATION_X_PEM_FILE.equals(urlConnection.getContentType())) { throw new IllegalArgumentException( "Unsupported media type or encoding format: " + urlConnection.getContentType()); } String keyData = CharStreams.toString(new InputStreamReader((InputStream) urlConnection.getContent())); privateKey = Crypto.loadPrivateKey(keyData); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid privateKey format", e); } catch (CryptoException | InstantiationException | IllegalAccessException | IOException e) { privateKey = null; } return privateKey; }
From source file:ch.pec0ra.mobilityratecalculator.DistanceCalculator.java
private String downloadUrl(String myurl) throws IOException { InputStream is = null;/*from w w w . j a v a2 s. c o m*/ try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); conn.getResponseCode(); is = conn.getInputStream(); String responseAsString = CharStreams.toString(new InputStreamReader(is)); return responseAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } }
From source file:org.anhonesteffort.flock.registration.RegistrationApi.java
public Double getCostPerYearUsd() throws IOException, RegistrationApiException { HttpGet httpGet = new HttpGet(OwsRegistration.HREF_PRICING); DefaultHttpClient httpClient = getClient(context); HttpResponse response = httpClient.execute(httpGet); InputStreamReader reader = new InputStreamReader(response.getEntity().getContent()); throwExceptionIfNotOK(response);//w ww. jav a 2s .co m return Double.valueOf(CharStreams.toString(reader)); }
From source file:org.eclipse.che.multiuser.keycloak.server.KeycloakServiceClient.java
private String doRequest(String url, String method, List<Pair<String, ?>> parameters) throws IOException, ServerException, ForbiddenException, NotFoundException, UnauthorizedException, BadRequestException { final String authToken = EnvironmentContext.getCurrent().getSubject().getToken(); final boolean hasQueryParams = parameters != null && !parameters.isEmpty(); if (hasQueryParams) { final UriBuilder ub = UriBuilder.fromUri(url); for (Pair<String, ?> parameter : parameters) { ub.queryParam(parameter.first, parameter.second); }//from w w w .j a v a 2 s .c o m url = ub.build().toString(); } final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(60000); conn.setReadTimeout(60000); try { conn.setRequestMethod(method); // drop a hint for server side that we want to receive application/json conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); if (authToken != null) { conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "bearer " + authToken); } final int responseCode = conn.getResponseCode(); if ((responseCode / 100) != 2) { InputStream in = conn.getErrorStream(); if (in == null) { in = conn.getInputStream(); } final String str; try (Reader reader = new InputStreamReader(in)) { str = CharStreams.toString(reader); } final String contentType = conn.getContentType(); if (contentType != null && (contentType.startsWith(MediaType.APPLICATION_JSON) || contentType.startsWith("application/vnd.api+json"))) { final KeycloakErrorResponse serviceError = DtoFactory.getInstance().createDtoFromJson(str, KeycloakErrorResponse.class); if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) { throw new ForbiddenException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) { throw new NotFoundException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) { throw new UnauthorizedException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) { throw new ServerException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) { throw new BadRequestException(serviceError.getErrorMessage()); } throw new ServerException(serviceError.getErrorMessage()); } // Can't parse content as json or content has format other we expect for error. throw new IOException(String.format("Failed access: %s, method: %s, response code: %d, message: %s", UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str)); } try (Reader reader = new InputStreamReader(conn.getInputStream())) { return CharStreams.toString(reader); } } finally { conn.disconnect(); } }