List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:com.commonsware.android.tte.DocumentStorageService.java
private void save(Uri document, String text, boolean isClosing) { boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme()); try {//from w ww . j ava 2 s . co m OutputStream os = getContentResolver().openOutputStream(document, "w"); OutputStreamWriter osw = new OutputStreamWriter(os); try { osw.write(text); osw.flush(); if (isClosing && isContent) { int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION; getContentResolver().releasePersistableUriPermission(document, perms); } EventBus.getDefault().post(new DocumentSavedEvent(document)); } finally { osw.close(); } } catch (Exception e) { Log.e(getClass().getSimpleName(), "Exception saving " + document.toString(), e); EventBus.getDefault().post(new DocumentSaveErrorEvent(document, e)); } }
From source file:net.yacy.http.servlets.SolrSelectServlet.java
@Override public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { HttpServletRequest hrequest = (HttpServletRequest) request; HttpServletResponse hresponse = (HttpServletResponse) response; SolrQueryRequest req = null;//from w w w . ja v a 2 s . c om final Method reqMethod = Method.getMethod(hrequest.getMethod()); Writer out = null; try { // prepare request to solr MultiMapSolrParams mmsp = SolrRequestParsers.parseQueryString(hrequest.getQueryString()); Switchboard sb = Switchboard.getSwitchboard(); // TODO: isUserInRole needs a login to jetty container (not done automatically on admin from localhost) boolean authenticated = hrequest.isUserInRole(UserDB.AccessRight.ADMIN_RIGHT.toString()); // count remote searches if this was part of a p2p search if (mmsp.getMap().containsKey("partitions")) { final int partitions = mmsp.getInt("partitions", 30); sb.searchQueriesGlobal += 1.0f / partitions; // increase query counter } // get the ranking profile id int profileNr = mmsp.getInt("profileNr", 0); // rename post fields according to result style String querystring = ""; if (!mmsp.getMap().containsKey(CommonParams.Q) && mmsp.getMap().containsKey(CommonParams.QUERY)) { querystring = mmsp.get(CommonParams.QUERY, ""); mmsp.getMap().remove(CommonParams.QUERY); QueryModifier modifier = new QueryModifier(0); querystring = modifier.parse(querystring); modifier.apply(mmsp); QueryGoal qg = new QueryGoal(querystring); StringBuilder solrQ = qg.collectionTextQuery(); mmsp.getMap().put(CommonParams.Q, new String[] { solrQ.toString() }); // sru patch // experimental p2p enrichment if flag to do so is set /* final String p2pQuery = querystring; new Thread() { @Override public void run() { FederateSearchManager.getManager().query(p2pQuery); } }.start(); */ } String q = mmsp.get(CommonParams.Q, ""); if (querystring.length() == 0) querystring = q; if (!mmsp.getMap().containsKey(CommonParams.START)) { int startRecord = mmsp.getFieldInt("startRecord", null, 0); mmsp.getMap().remove("startRecord"); mmsp.getMap().put(CommonParams.START, new String[] { Integer.toString(startRecord) }); // sru patch } if (!mmsp.getMap().containsKey(CommonParams.ROWS)) { int maximumRecords = mmsp.getFieldInt("maximumRecords", null, 10); mmsp.getMap().remove("maximumRecords"); mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer.toString(maximumRecords) }); // sru patch } mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer .toString(Math.min(mmsp.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100)) }); // set ranking according to profile number if ranking attributes are not given in the request Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr); if (!mmsp.getMap().containsKey(CommonParams.SORT) && !mmsp.getMap().containsKey(DisMaxParams.BQ) && !mmsp.getMap().containsKey(DisMaxParams.BF) && !mmsp.getMap().containsKey("boost")) { if (!mmsp.getMap().containsKey("defType")) mmsp.getMap().put("defType", new String[] { "edismax" }); String fq = ranking.getFilterQuery(); String bq = ranking.getBoostQuery(); String bf = ranking.getBoostFunction(); if (fq.length() > 0) mmsp.getMap().put(CommonParams.FQ, new String[] { fq }); if (bq.length() > 0) mmsp.getMap().put(DisMaxParams.BQ, StringUtils.split(bq, "\t\n\r\f")); // bq split into multiple query params, allowing space in single query if (bf.length() > 0) mmsp.getMap().put("boost", new String[] { bf }); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29 } // get a response writer for the result String wt = mmsp.get(CommonParams.WT, "xml"); // maybe use /solr/select?q=*:*&start=0&rows=10&wt=exml QueryResponseWriter responseWriter = RESPONSE_WRITER.get(wt); if (responseWriter == null) throw new ServletException("no response writer"); if (responseWriter instanceof OpensearchResponseWriter) { // set the title every time, it is possible that it has changed final String promoteSearchPageGreeting = (sb .getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false)) ? sb.getConfig("network.unit.description", "") : sb.getConfig(SwitchboardConstants.GREETING, ""); ((OpensearchResponseWriter) responseWriter).setTitle(promoteSearchPageGreeting); } // if this is a call to YaCys special search formats, enhance the query with field assignments if ((responseWriter instanceof YJsonResponseWriter || responseWriter instanceof OpensearchResponseWriter) && "true".equals(mmsp.get("hl", "true"))) { // add options for snippet generation if (!mmsp.getMap().containsKey("hl.q")) mmsp.getMap().put("hl.q", new String[] { q }); if (!mmsp.getMap().containsKey("hl.fl")) mmsp.getMap().put("hl.fl", new String[] { CollectionSchema.description_txt.getSolrFieldName() + "," + CollectionSchema.h4_txt.getSolrFieldName() + "," + CollectionSchema.h3_txt.getSolrFieldName() + "," + CollectionSchema.h2_txt.getSolrFieldName() + "," + CollectionSchema.h1_txt.getSolrFieldName() + "," + CollectionSchema.text_t.getSolrFieldName() }); if (!mmsp.getMap().containsKey("hl.alternateField")) mmsp.getMap().put("hl.alternateField", new String[] { CollectionSchema.description_txt.getSolrFieldName() }); if (!mmsp.getMap().containsKey("hl.simple.pre")) mmsp.getMap().put("hl.simple.pre", new String[] { "<b>" }); if (!mmsp.getMap().containsKey("hl.simple.post")) mmsp.getMap().put("hl.simple.post", new String[] { "</b>" }); if (!mmsp.getMap().containsKey("hl.fragsize")) mmsp.getMap().put("hl.fragsize", new String[] { Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH) }); if (!mmsp.getMap().containsKey("fl")) mmsp.getMap().put("fl", new String[] { CollectionSchema.sku.getSolrFieldName() + "," + CollectionSchema.title + "," + CollectionSchema.description_txt.getSolrFieldName() + "," + CollectionSchema.id.getSolrFieldName() + "," + CollectionSchema.url_paths_sxt.getSolrFieldName() + "," + CollectionSchema.last_modified.getSolrFieldName() + "," + CollectionSchema.size_i.getSolrFieldName() + "," + CollectionSchema.url_protocol_s.getSolrFieldName() + "," + CollectionSchema.url_file_ext_s.getSolrFieldName() }); } // get the embedded connector String requestURI = hrequest.getRequestURI(); boolean defaultConnector = (requestURI.startsWith("/solr/" + WebgraphSchema.CORE_NAME)) ? false : requestURI.startsWith("/solr/" + CollectionSchema.CORE_NAME) || mmsp.get("core", CollectionSchema.CORE_NAME).equals(CollectionSchema.CORE_NAME); mmsp.getMap().remove("core"); SolrConnector connector = defaultConnector ? sb.index.fulltext().getDefaultEmbeddedConnector() : sb.index.fulltext().getEmbeddedConnector(WebgraphSchema.CORE_NAME); if (connector == null) { connector = defaultConnector ? sb.index.fulltext().getDefaultConnector() : sb.index.fulltext().getConnectorForRead(WebgraphSchema.CORE_NAME); } if (connector == null) throw new ServletException("no core"); // add default queryfield parameter according to local ranking config (or defaultfield) if (ranking != null) { // ranking normally never null final String qf = ranking.getQueryFields(); if (qf.length() > 4) { // make sure qf has content (else use df) addParam(DisMaxParams.QF, qf, mmsp.getMap()); // add QF that we set to be best suited for our index // TODO: if every peer applies a decent QF itself, this can be reverted to getMap().put() } else { mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() }); } } else { mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() }); } // do the solr request, generate facets if we use a special YaCy format final SolrQueryResponse rsp; if (connector instanceof EmbeddedSolrConnector) { req = ((EmbeddedSolrConnector) connector).request(mmsp); rsp = ((EmbeddedSolrConnector) connector).query(req); // prepare response hresponse.setHeader("Cache-Control", "no-cache, no-store"); HttpCacheHeaderUtil.checkHttpCachingVeto(rsp, hresponse, reqMethod); // check error if (rsp.getException() != null) { AccessTracker.addToDump(querystring, "0", new Date()); sendError(hresponse, rsp.getException()); return; } NamedList<?> values = rsp.getValues(); DocList r = ((ResultContext) values.get("response")).docs; int numFound = r.matches(); AccessTracker.addToDump(querystring, Integer.toString(numFound), new Date()); // write response header final String contentType = responseWriter.getContentType(req, rsp); if (null != contentType) response.setContentType(contentType); if (Method.HEAD == reqMethod) { return; } // write response body if (responseWriter instanceof BinaryResponseWriter) { ((BinaryResponseWriter) responseWriter).write(response.getOutputStream(), req, rsp); } else { out = new FastWriter( new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)); responseWriter.write(out, req, rsp); out.flush(); } } else { // write a 'faked' response using a call to the backend SolrDocumentList sdl = connector.getDocumentListByQuery(mmsp.getMap().get(CommonParams.Q)[0], mmsp.getMap().get(CommonParams.SORT) == null ? null : mmsp.getMap().get(CommonParams.SORT)[0], Integer.parseInt(mmsp.getMap().get(CommonParams.START)[0]), Integer.parseInt(mmsp.getMap().get(CommonParams.ROWS)[0]), mmsp.getMap().get(CommonParams.FL)); OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream()); EnhancedXMLResponseWriter.write(osw, req, sdl); osw.close(); } } catch (final Throwable ex) { sendError(hresponse, ex); } finally { if (req != null) { req.close(); } SolrRequestInfo.clearRequestInfo(); if (out != null) try { out.close(); } catch (final IOException e1) { } } }
From source file:de.liedtke.data.url.BasicDAOUrl.java
protected JSONObject requestUrl(final String daoName, final String methodName, final String jsonValue) throws JSONException { String jsonString = null;//from w w w. j a va 2 s .com try { // Construct data final StringBuilder params = new StringBuilder(); params.append(URLEncoder.encode("daoName", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(daoName, Constants.UTF8)); params.append("&"); params.append(URLEncoder.encode("methodName", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(methodName, Constants.UTF8)); if (jsonValue != null) { params.append("&"); params.append(URLEncoder.encode("jsonValue", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(jsonValue, Constants.UTF8)); } params.append("&"); params.append(URLEncoder.encode("kind", Constants.UTF8)); params.append("="); params.append(URLEncoder.encode(ResultKind.JSON.toString(), Constants.UTF8)); // Send data URL url = new URL(address); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(params.toString()); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuilder sBuilder = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sBuilder.append(line); } jsonString = sBuilder.toString(); wr.close(); rd.close(); } catch (UnsupportedEncodingException e) { logger.warning("UnsupportedEncodingException occured: " + e.getMessage()); } catch (IOException e) { logger.warning("IOException occured: " + e.getMessage()); } JSONObject json = null; if (jsonString == null) { json = null; } else { json = new JSONObject(jsonString); } return json; }
From source file:org.onebusaway.nyc.vehicle_tracking.webapp.controllers.VehicleLocationSimulationController.java
/**** * Private Methods/*from w w w .j a va 2 s . com*/ ****/ private void writeRecordsToOutput(HttpServletResponse response, List<NycTestLocationRecord> records) throws IOException { CsvEntityWriterFactory factory = new CsvEntityWriterFactory(); OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream()); EntityHandler handler = factory.createWriter(NycTestLocationRecord.class, writer); if (records == null) records = Collections.emptyList(); for (NycTestLocationRecord record : records) handler.handleEntity(record); writer.close(); }
From source file:it.infn.ct.jsaga.adaptor.tosca.job.ToscaJobControlAdaptor.java
private String submitTosca() throws IOException, ParseException, BadResource, NoSuccessException { StringBuilder orchestrator_result = new StringBuilder(""); StringBuilder postData = new StringBuilder(); postData.append("{ \"template\": \""); String tosca_template_content = ""; try {// w w w .j a v a 2s.co m tosca_template_content = new String(Files.readAllBytes(Paths.get(tosca_template))).replace("\n", "\\n"); postData.append(tosca_template_content); } catch (IOException ex) { log.error("Template '" + tosca_template + "'is not readable"); throw new BadResource("Template '" + tosca_template + "'is not readable; template:" + LS + "'" + tosca_template_content + "'"); } postData.append("\" }"); log.debug("JSON Data sent to the orchestrator: \n" + postData); HttpURLConnection conn; try { conn = (HttpURLConnection) endpoint.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("charset", "utf-8"); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postData.toString()); wr.flush(); wr.close(); log.debug("Orchestrator status code: " + conn.getResponseCode()); log.debug("Orchestrator status message: " + conn.getResponseMessage()); if (conn.getResponseCode() == 201) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); orchestrator_result = new StringBuilder(); String ln; while ((ln = br.readLine()) != null) { orchestrator_result.append(ln); } log.debug("Orchestrator result: " + orchestrator_result); String orchestratorDoc = orchestrator_result.toString(); tosca_UUID = getDocumentValue(orchestratorDoc, "uuid"); log.debug("Created resource has UUID: '" + tosca_UUID + "'"); return orchestratorDoc; } } catch (IOException ex) { log.error("Connection error with the service at " + endpoint.toString()); log.error(ex); throw new NoSuccessException("Connection error with the service at " + endpoint.toString()); } catch (ParseException ex) { log.error("Orchestrator response not parsable"); throw new NoSuccessException( "Orchestrator response not parsable:" + LS + "'" + orchestrator_result.toString() + "'"); } return tosca_UUID; }
From source file:org.guanxi.sp.engine.service.shibboleth.AuthConsumerServiceThread.java
/** * This opens the connection to the guard, sends the SOAP request, and reads the response. * /*from w w w . ja va 2 s.co m*/ * @param acsURL The URL of the Guard Attribute Consumer Service * @param entityID The entity ID of the Guard * @param keystoreFile The location of the keystore to use to identify the engine to the guard * @param keystorePassword The password for the keystore * @param truststoreFile The location of the truststore to use to verify the guard * @param truststorePassword The password for the truststore * @param soapRequest The request that will be sent to the Guard * @param guardSession The Guard's session ID * @return A string containing the response from the guard * @throws GuanxiException If there is a problem creating the EntityConnection or setting the attributes on it * @throws IOException If there is a problem using the EntityConnection to read or write data */ private String processGuardConnection(String acsURL, String entityID, String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword, EnvelopeDocument soapRequest, String guardSession) throws GuanxiException, IOException { ResponseDocument responseDoc = unmarshallSAML(soapRequest); Bag bag = getBag(responseDoc, guardSession); // Initialise the connection to the Guard's attribute consumer service EntityConnection connection = new EntityConnection(acsURL, entityID, keystoreFile, keystorePassword, truststoreFile, truststorePassword, EntityConnection.PROBING_OFF); connection.setDoOutput(true); connection.connect(); // Send the data to the Guard in an explicit POST variable String json = URLEncoder.encode(Guanxi.REQUEST_PARAMETER_SAML_ATTRIBUTES, "UTF-8") + "=" + URLEncoder.encode(bag.toJSON(), "UTF-8"); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(json); wr.flush(); wr.close(); // ...and read the response from the Guard return new String(Utils.read(connection.getInputStream())); }
From source file:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java
/** * The method is synchronized since the caching seems to have issues upon mult-threaded caching * @param overwrite if true, it would overwrite the values on cache *///from w w w. j a v a 2 s . c om public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception { String viewsConnected = Arrays.toString(viewsToAdd); String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", ""); ConcurrentMap<String, byte[]> concurrentMap = (db != null) ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen() : null; String key = DigestUtils.sha1Hex(str + views); if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) { byte[] taByte = concurrentMap.get(key); return SerializationHelper.deserializeTextAnnotationFromBytes(taByte); } else { URL obj = new URL(url + ":" + port + "/annotate"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); con.setDoOutput(true); con.setUseCaches(false); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views); wr.flush(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); BufferedReader in = new BufferedReader(reader); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); reader.close(); wr.close(); con.disconnect(); TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString()); if (concurrentMap != null) { concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta)); this.db.commit(); } return ta; } }
From source file:ncbi2rkb.SparqlProxy.java
public boolean storeData(StringBuilder query) { boolean ret = true; query = SparqlProxy.makeQuery(query); HttpURLConnection connection = null; try {/* w ww .j a v a2 s. c o m*/ String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8"); URL url = new URL(this.urlServer + "update"); //Create connection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String rep = ""; while ((line = reader.readLine()) != null) { rep += line; } writer.close(); reader.close(); } catch (Exception e) { System.err.println("ERROR UPDATE : " + e); SparqlProxy.saveQueryOnFile("Query.sparql", query.toString()); ret = false; } finally { if (connection != null) { connection.disconnect(); } } return ret; }
From source file:com.otisbean.keyring.Ring.java
/** * Initialize the cipher object and create the key object. * /* w w w . ja va 2 s . c om*/ * @param password * @return A checkData string, which can be compared against the existing * one to determine if the password is valid. * @throws GeneralSecurityException */ private String initCipher(char[] password) throws GeneralSecurityException { log("initCipher()"); String base64Key = null; try { // Convert a char array into a UTF-8 byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter out = new OutputStreamWriter(baos, "UTF-8"); try { out.write(password); out.close(); } catch (IOException e) { // the only reason this would throw is an encoding problem. throw new RuntimeException(e.getLocalizedMessage()); } byte[] passwordBytes = baos.toByteArray(); /* The following code looks like a lot of monkey-motion, but it yields * results compatible with the on-phone Keyring Javascript and Mojo code. * * In newPassword() in ring.js, we have this (around line 165): * this._key = b64_sha256(this._salt + newPassword); */ byte[] saltBytes = salt.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(saltBytes, 0, saltBytes.length); md.update(passwordBytes, 0, passwordBytes.length); byte[] keyHash = md.digest(); String paddedBase64Key = Base64.encodeBytes(keyHash); /* The Javascript SHA-256 library used in Keyring doesn't pad base64 output, * so we need to trim off any trailing "=" signs. */ base64Key = paddedBase64Key.replace("=", ""); byte[] keyBytes = base64Key.getBytes("UTF-8"); /* Keyring passes data to Mojo.Model.encrypt(key, data), which eventually * make a JNI call to OpenSSL's blowfish api. The following is the * equivalent in straight up JCE. */ key = new SecretKeySpec(keyBytes, "Blowfish"); iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); } catch (UnsupportedEncodingException e) { // This is a bit dodgy, but handling a UEE elsewhere is foolish throw new GeneralSecurityException(e.getLocalizedMessage()); } return "{" + base64Key + "}"; }
From source file:com.roche.iceboar.demo.JnlpServlet.java
/** * This method handle all HTTP requests for *.jnlp files (defined in web.xml). Method check, is name correct * (allowed), read file from disk, replace #{codebase} (it's necessary to be generated based on where application * is deployed), #{host} () and write to the response. * <p>// ww w . ja v a 2 s. c o m * You can use this class in your code for downloading JNLP files. * Return a content of requested jnlp file in response. * * @throws IOException when can't close some stream */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String contextPath = request.getContextPath(); String requestURI = request.getRequestURI(); String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String codebase = host + contextPath; String filename = StringUtils.removeStart(requestURI, contextPath); response.setContentType("application/x-java-jnlp-file"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "-1"); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream()); InputStream in = JnlpServlet.class.getResourceAsStream(filename); if (in == null) { error(response, "Can't open: " + filename); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { line = line.replace("#{codebase}", codebase); line = line.replace("#{host}", host); out.write(line); out.write("\n"); line = reader.readLine(); } out.flush(); out.close(); reader.close(); }