List of usage examples for java.io StringWriter write
public void write(String str)
From source file:org.sakaiproject.jsf.renderer.InputRichTextRenderer.java
protected void writeFilesArray(ResponseWriter writer, String arrayVar, Object attchedFiles, MessageFormat format, boolean includeLabel) throws IOException { StringWriter buffer = new StringWriter(); char startChar = '['; char endChar = ']'; if (format == LIST_ITEM_FORMAT_HTML) { startChar = '{'; endChar = '}'; }/*from ww w .j a v a 2s . com*/ buffer.write(" var " + arrayVar + " = " + startChar + "\n"); if (includeLabel) { buffer.write("\"select a file url to insert\" : \"\""); } if (attchedFiles instanceof Map) { buffer.write(outputFiles((Map) attchedFiles, format, !includeLabel)); } else { buffer.write(outputFiles((List) attchedFiles, format, !includeLabel)); } buffer.write(endChar + ";\n"); String result = buffer.toString(); writer.write(result); }
From source file:fr.univlr.cri.planning.factory.HugICalendarFactory.java
/** * Lecture d'un fichier icalendar via l'API de la librairie ical4j. Les * occupations contenues dans la fenetre d'interrogation [dateDebut, dateFin] * sont retournees.//from w ww.jav a 2 s.c o m * * @param pathICalendar * : le chemin du fichier ICS * @param dateDebut * : date de debut de la periode d'interrogation * @param dateFin * : date de fin de la periode d'interrogation * @return * @throws CalendarNotFoundException */ private CalendarObject newCalendarObjectFromICalendarFileICal4J(String pathICalendar, NSTimestamp dateDebut, NSTimestamp dateFin) throws CalendarNotFoundException { CalendarObject oCal = null; InputStream in = null; try { // fin = new FileInputStream(pathICalendar); URL url = new URL(pathICalendar); URLConnection con = url.openConnection(); con.connect(); in = con.getInputStream(); } catch (FileNotFoundException e) { throw new CalendarNotFoundException("Calendar " + pathICalendar + " non trouv ou acc?s refus."); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * CalendarBuilder calendarBuilder = new CalendarBuilder(); * * try { long l1 = System.currentTimeMillis(); Calendar calendar = * calendarBuilder.build(in); oCal = new CalendarObject(pathICalendar); l1 = * System.currentTimeMillis() - l1; CktlLog.log(">> parsing : " + l1 + * " ms ("+pathICalendar+")"); * * // on passe au evenements for (Iterator i = * calendar.getComponents().iterator(); i.hasNext();) { Component component * = (Component) i.next(); if (component.getName().equals(Component.VEVENT)) * { VEvent vEvent = (VEvent) component; oCal.addSPVEvent(new * SPVEvent(vEvent)); } } * * * * } catch (IOException e) { throw new * CalendarNotFoundException("Calendar "+ pathICalendar * +" erreur de lecture " + e.getMessage()); } catch (ParserException e) { * throw new CalendarNotFoundException("Calendar "+ pathICalendar * +" erreur de lecture " + e.getMessage()); } */ String string = null; try { long l1 = System.currentTimeMillis(); URL url = new URL(pathICalendar); URLConnection con = url.openConnection(); con.connect(); BufferedInputStream bin = new BufferedInputStream(con.getInputStream()); StringWriter out = new StringWriter(); int b; while ((b = bin.read()) != -1) out.write(b); out.flush(); out.close(); bin.close(); string = out.toString(); l1 = System.currentTimeMillis() - l1; System.out.println("converting calendar url to string : " + l1 + " ms (" + pathICalendar + ")"); } catch (IOException ie) { ie.printStackTrace(); } long l1 = System.currentTimeMillis(); StringReader sin = new StringReader(string); CalendarBuilder builder = new CalendarBuilder(); Calendar calendar = null; try { calendar = builder.build(sin); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } l1 = System.currentTimeMillis() - l1; System.out.println("parse calendar string : " + l1 + " ms (" + pathICalendar + ")"); oCal = new CalendarObject(pathICalendar); // on passe au evenements for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) { Component component = (Component) i.next(); if (component.getName().equals(Component.VEVENT)) { VEvent vEvent = (VEvent) component; oCal.addSPVEvent(new SPVEvent(vEvent)); } } // on met en cache notre affaire if (oCal != null) { putCalendarInCache(pathICalendar, oCal); } return oCal; }
From source file:org.occiware.clouddesigner.occi.hypervisor.connector.libvirt.util.DomainMarshaller.java
public String asString(final String uuid) { try {/*from w w w . j av a2 s .c o m*/ final String filename = (("/" + uuid) + ".xml"); final StringWriter logwriter = new StringWriter(); final File tmpDir = this.createTempDir(this.xmlDirectory); String _plus = (tmpDir + "/"); String _plus_1 = (_plus + filename); InputStream response = new FileInputStream(_plus_1); try { final LineIterator itr = IOUtils.lineIterator(response, "UTF-8"); while (itr.hasNext()) { { String line = itr.next(); boolean _hasNext = itr.hasNext(); if (_hasNext) { logwriter.write((line + "\n")); } else { logwriter.write((line + "")); } } } response.close(); return logwriter.toString(); } catch (final Throwable _t) { if (_t instanceof IOException) { final IOException e = (IOException) _t; throw new RuntimeException(e); } else { throw Exceptions.sneakyThrow(_t); } } finally { IOUtils.closeQuietly(response); } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
From source file:org.botlibre.util.Utils.java
/** * Reduce the sentence to a simple form. *///from ww w . j a v a2 s . c om public static String reduce(String sentence) { if (sentence.length() == 0) { return sentence; } int terminate = sentence.length(); while ((terminate > 0) && TextStream.TERMINATORS.indexOf(sentence.charAt(terminate - 1)) != -1) { terminate--; } StringWriter writer = new StringWriter(); TextStream stream = new TextStream(sentence); boolean first = true; boolean ignore = false; String previous = null; while (stream.getPosition() < terminate) { String word = stream.nextWord(); if (word == null) { break; } word = word.toLowerCase(); if (word.equals("'") && "what".equals(previous)) { if ("s".equals(stream.peekWord())) { writer.write(" is"); stream.nextWord(); continue; } } if (!first && !ignore) { writer.write(" "); } else { first = false; } if (word.equals("whats")) { writer.write("what is"); } else if (!TextStream.IGNORABLE.contains(word)) { writer.write(word); ignore = false; } else { ignore = true; } previous = word; } return writer.toString(); }
From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java
protected String readCode(DesignMetadata md) throws FileNotFoundException, IOException, WGDesignSyncException, InstantiationException, IllegalAccessException { // No, filecontainers have no code, but thanks for asking.... if (getType() == WGDocument.TYPE_FILECONTAINER) { return null; }/* w w w .ja va2s .co m*/ FileObject codeFile = getCodeFile(); if (!codeFile.exists()) { throw new WGDesignSyncException("Code of file '" + getCodeFile().getName().getPath() + "' could not be read because the file does not exist."); } LineNumberReader reader = new LineNumberReader(createReader(codeFile)); StringWriter writer = new StringWriter(); int headerLines = 0; try { String line; boolean lookForHeaders = true; boolean firstLine = true; while ((line = reader.readLine()) != null) { if (lookForHeaders == true && line.startsWith("##")) { processDesignHeader(line, md.getInfo()); headerLines++; } else { lookForHeaders = false; if (!firstLine) { writer.write("\n"); } else { firstLine = false; } writer.write(line); } } } finally { reader.close(); codeFile.getContent().close(); } writer.close(); md.setHeaderLines(headerLines); String code = writer.toString(); return code; }
From source file:org.yamj.api.common.http.AbstractPoolingHttpClient.java
protected DigestedResponse readContent(final HttpResponse response, final Charset charset) throws IOException { StringWriter content = new StringWriter(SW_BUFFER_10K); InputStream is = response.getEntity().getContent(); InputStreamReader isr = null; BufferedReader br = null;/*from w ww . j a v a2 s. c o m*/ final DigestedResponse digestedResponse = new DigestedResponse(); digestedResponse.setStatusCode(response.getStatusLine().getStatusCode()); try { if (charset == null) { isr = new InputStreamReader(is, Charset.defaultCharset()); } else { isr = new InputStreamReader(is, charset); } br = new BufferedReader(isr); String line = br.readLine(); while (line != null) { content.write(line); line = br.readLine(); } content.flush(); digestedResponse.setContent(content.toString()); return digestedResponse; } finally { if (br != null) { try { br.close(); } catch (IOException ex) { LOG.trace("Failed to close BufferedReader", ex); } } if (isr != null) { try { isr.close(); } catch (IOException ex) { LOG.trace("Failed to close InputStreamReader", ex); } } try { content.close(); } catch (IOException ex) { LOG.trace("Failed to close StringWriter", ex); } try { is.close(); } catch (IOException ex) { LOG.trace("Failed to close InputStream", ex); } } }
From source file:com.espertech.esper.epl.db.DatabasePollingViewableFactory.java
/** * Lexes the sample SQL and inserts a "where 1=0" where-clause. * @param querySQL to inspect using lexer * @return sample SQL with where-clause inserted * @throws ExprValidationException to indicate a lexer problem *//*from www . j a v a 2s . c o m*/ protected static String lexSampleSQL(String querySQL) throws ExprValidationException { querySQL = querySQL.replaceAll("\\s\\s+|\\n|\\r", " "); StringReader reader = new StringReader(querySQL); CharStream input; try { input = new NoCaseSensitiveStream(reader); } catch (IOException ex) { throw new ExprValidationException("IOException lexing query SQL '" + querySQL + '\'', ex); } int whereIndex = -1; int groupbyIndex = -1; int havingIndex = -1; int orderByIndex = -1; List<Integer> unionIndexes = new ArrayList<Integer>(); EsperEPL2GrammarLexer lex = new EsperEPL2GrammarLexer(input); CommonTokenStream tokens = new CommonTokenStream(lex); List tokenList = tokens.getTokens(); for (int i = 0; i < tokenList.size(); i++) { Token token = (Token) tokenList.get(i); if ((token == null) || token.getText() == null) { break; } String text = token.getText().toLowerCase().trim(); if (text.equals("where")) { whereIndex = token.getCharPositionInLine() + 1; } if (text.equals("group")) { groupbyIndex = token.getCharPositionInLine() + 1; } if (text.equals("having")) { havingIndex = token.getCharPositionInLine() + 1; } if (text.equals("order")) { orderByIndex = token.getCharPositionInLine() + 1; } if (text.equals("union")) { unionIndexes.add(token.getCharPositionInLine() + 1); } } // If we have a union, break string into subselects and process each if (unionIndexes.size() != 0) { StringWriter changedSQL = new StringWriter(); int lastIndex = 0; for (int i = 0; i < unionIndexes.size(); i++) { int index = unionIndexes.get(i); String fragment; if (i > 0) { fragment = querySQL.substring(lastIndex + 5, index - 1); } else { fragment = querySQL.substring(lastIndex, index - 1); } String lexedFragment = lexSampleSQL(fragment); if (i > 0) { changedSQL.append("union "); } changedSQL.append(lexedFragment); lastIndex = index - 1; } // last part after last union String fragment = querySQL.substring(lastIndex + 5, querySQL.length()); String lexedFragment = lexSampleSQL(fragment); changedSQL.append("union "); changedSQL.append(lexedFragment); return changedSQL.toString(); } // Found a where clause, simplest cases if (whereIndex != -1) { StringWriter changedSQL = new StringWriter(); String prefix = querySQL.substring(0, whereIndex + 5); String suffix = querySQL.substring(whereIndex + 5, querySQL.length()); changedSQL.write(prefix); changedSQL.write("1=0 and "); changedSQL.write(suffix); return changedSQL.toString(); } // No where clause, find group-by int insertIndex; if (groupbyIndex != -1) { insertIndex = groupbyIndex; } else if (havingIndex != -1) { insertIndex = havingIndex; } else if (orderByIndex != -1) { insertIndex = orderByIndex; } else { StringWriter changedSQL = new StringWriter(); changedSQL.write(querySQL); changedSQL.write(" where 1=0 "); return changedSQL.toString(); } try { StringWriter changedSQL = new StringWriter(); String prefix = querySQL.substring(0, insertIndex - 1); changedSQL.write(prefix); changedSQL.write("where 1=0 "); String suffix = querySQL.substring(insertIndex - 1, querySQL.length()); changedSQL.write(suffix); return changedSQL.toString(); } catch (Exception ex) { String text = "Error constructing sample SQL to retrieve metadata for JDBC-drivers that don't support metadata, consider using the " + SAMPLE_WHERECLAUSE_PLACEHOLDER + " placeholder or providing a sample SQL"; log.error(text, ex); throw new ExprValidationException(text, ex); } }
From source file:com.google.acre.script.AcreFetch.java
@SuppressWarnings("boxing") public void fetch(boolean system, String response_encoding, boolean log_to_user, boolean no_redirect) { if (request_url.length() > 2047) { throw new AcreURLFetchException("fetching URL failed - url is too long"); }// ww w .j a v a 2s . c om DefaultHttpClient client = new DefaultHttpClient(_connectionManager, null); HttpParams params = client.getParams(); // pass the deadline down to the invoked service. // this will be ignored unless we are fetching from another // acre server. // note that we may send a deadline that is already passed: // it's not our job to throw here since we don't know how // the target service will interpret the quota header. // NOTE: this is done *after* the user sets the headers to overwrite // whatever settings they might have tried to change for this value // (which could be a security hazard) long sub_deadline = (HostEnv.LIMIT_EXECUTION_TIME) ? _deadline - HostEnv.SUBREQUEST_DEADLINE_ADVANCE : System.currentTimeMillis() + HostEnv.ACRE_URLFETCH_TIMEOUT; int reentries = _reentries + 1; request_headers.put(HostEnv.ACRE_QUOTAS_HEADER, "td=" + sub_deadline + ",r=" + reentries); // if this is not an internal call, we need to invoke the call thru a proxy if (!_internal) { // XXX No sense wasting the resources to gzip inside the network. // XXX seems that twitter gets upset when we do this /* if (!request_headers.containsKey("accept-encoding")) { request_headers.put("accept-encoding", "gzip"); } */ String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue(); int proxy_port = -1; if (!(proxy_host.length() == 0)) { proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger(); HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http"); params.setParameter(AllClientPNames.DEFAULT_PROXY, proxy); } } params.setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); // in msec long timeout = _deadline - System.currentTimeMillis(); if (timeout < 0) timeout = 0; params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, (int) timeout); params.setParameter(AllClientPNames.SO_TIMEOUT, (int) timeout); // we're not streaming the request so this should be a win. params.setParameter(AllClientPNames.TCP_NODELAY, true); // reuse an existing socket if it is in TIME_WAIT state. params.setParameter(AllClientPNames.SO_REUSEADDR, true); // set the encoding of our POST payloads to UTF-8 params.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, "UTF-8"); BasicCookieStore cstore = new BasicCookieStore(); for (AcreCookie cookie : request_cookies.values()) { cstore.addCookie(cookie.toClientCookie()); } client.setCookieStore(cstore); HttpRequestBase method; HashMap<String, String> logmsg = new HashMap<String, String>(); logmsg.put("Method", request_method); logmsg.put("URL", request_url); params.setParameter(AllClientPNames.HANDLE_REDIRECTS, !no_redirect); logmsg.put("Redirect", Boolean.toString(!no_redirect)); try { if (request_method.equals("GET")) { method = new HttpGet(request_url); } else if (request_method.equals("POST")) { method = new HttpPost(request_url); } else if (request_method.equals("HEAD")) { method = new HttpHead(request_url); } else if (request_method.equals("PUT")) { method = new HttpPut(request_url); } else if (request_method.equals("DELETE")) { method = new HttpDelete(request_url); } else if (request_method.equals("PROPFIND")) { method = new HttpPropFind(request_url); } else { throw new AcreURLFetchException("Failed: unsupported (so far) method " + request_method); } method.getParams().setBooleanParameter(AllClientPNames.USE_EXPECT_CONTINUE, false); } catch (java.lang.IllegalArgumentException e) { throw new AcreURLFetchException("Unable to fetch URL; this is most likely an issue with URL encoding."); } catch (java.lang.IllegalStateException e) { throw new AcreURLFetchException("Unable to fetch URL; possibly an illegal protocol?"); } StringBuilder request_header_log = new StringBuilder(); for (Map.Entry<String, String> header : request_headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); // XXX should suppress cookie headers? // content-type and length? if ("content-type".equalsIgnoreCase(key)) { Matcher m = contentTypeCharsetPattern.matcher(value); if (m.find()) { content_type = m.group(1); content_type_charset = m.group(2); } else { content_type_charset = "utf-8"; } method.addHeader(key, value); } else if ("content-length".equalsIgnoreCase(key)) { // ignore user-supplied content-length, which is // probably wrong due to chars vs bytes and is // redundant anyway ArrayList<String> msg = new ArrayList<String>(); msg.add("User-supplied content-length header is ignored"); _acre_response.log("warn", msg); } else if ("user-agent".equalsIgnoreCase(key)) { params.setParameter(AllClientPNames.USER_AGENT, value); } else { method.addHeader(key, value); } if (!("x-acre-auth".equalsIgnoreCase(key))) { request_header_log.append(key + ": " + value + "\r\n"); } } logmsg.put("Headers", request_header_log.toString()); // XXX need more detailed error checking if (method instanceof HttpEntityEnclosingRequestBase && request_body != null) { HttpEntityEnclosingRequestBase em = (HttpEntityEnclosingRequestBase) method; try { if (request_body instanceof String) { StringEntity ent = new StringEntity((String) request_body, content_type_charset); em.setEntity(ent); } else if (request_body instanceof JSBinary) { ByteArrayEntity ent = new ByteArrayEntity(((JSBinary) request_body).get_data()); em.setEntity(ent); } } catch (UnsupportedEncodingException e) { throw new AcreURLFetchException( "Failed to fetch URL. " + " - Unsupported charset: " + content_type_charset); } } if (!system && log_to_user) { ArrayList<Object> msg = new ArrayList<Object>(); msg.add("urlfetch request"); msg.add(logmsg); _acre_response.log("debug", msg); } _logger.info("urlfetch.request", logmsg); long startTime = System.currentTimeMillis(); try { // this sends the http request and waits HttpResponse hres = client.execute(method); status = hres.getStatusLine().getStatusCode(); HashMap<String, String> res_logmsg = new HashMap<String, String>(); res_logmsg.put("URL", request_url); res_logmsg.put("Status", ((Integer) status).toString()); Header content_type_header = null; // translate response headers StringBuilder response_header_log = new StringBuilder(); Header[] rawheaders = hres.getAllHeaders(); for (Header rawheader : rawheaders) { String headername = rawheader.getName().toLowerCase(); if (headername.equalsIgnoreCase("content-type")) { content_type_header = rawheader; // XXX should strip everything after ; content_type = rawheader.getValue(); // XXX don't set content_type_parameters, deprecated? } else if (headername.equalsIgnoreCase("x-metaweb-cost")) { _costCollector.merge(rawheader.getValue()); } else if (headername.equalsIgnoreCase("x-metaweb-tid")) { res_logmsg.put("ITID", rawheader.getValue()); } headers.put(headername, rawheader.getValue()); response_header_log.append(headername + ": " + rawheader.getValue() + "\r\n"); } res_logmsg.put("Headers", response_header_log.toString()); if (!system && log_to_user) { ArrayList<Object> msg = new ArrayList<Object>(); msg.add("urlfetch response"); msg.add(res_logmsg); _acre_response.log("debug", msg); } _logger.info("urlfetch.response", res_logmsg); // read cookies for (Cookie c : cstore.getCookies()) { cookies.put(c.getName(), new AcreCookie(c)); } // get body encoding String charset = null; if (content_type_header != null) { HeaderElement values[] = content_type_header.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset == null) charset = response_encoding; // read body HttpEntity ent = hres.getEntity(); if (ent != null) { InputStream res_stream = ent.getContent(); Header cenc = ent.getContentEncoding(); if (cenc != null && res_stream != null) { HeaderElement[] codecs = cenc.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { res_stream = new GZIPInputStream(res_stream); } } } long firstByteTime = 0; long endTime = 0; if (content_type != null && (content_type.startsWith("image/") || content_type.startsWith("application/octet-stream") || content_type.startsWith("multipart/form-data"))) { // HttpClient's InputStream doesn't support mark/reset, so // wrap it with one that does. BufferedInputStream bufis = new BufferedInputStream(res_stream); bufis.mark(2); bufis.read(); firstByteTime = System.currentTimeMillis(); bufis.reset(); byte[] data = IOUtils.toByteArray(bufis); endTime = System.currentTimeMillis(); body = new JSBinary(); ((JSBinary) body).set_data(data); try { if (res_stream != null) { res_stream.close(); } } catch (IOException e) { // ignore } } else if (res_stream == null || charset == null) { firstByteTime = endTime = System.currentTimeMillis(); body = ""; } else { StringWriter writer = new StringWriter(); Reader reader = new InputStreamReader(res_stream, charset); int i = reader.read(); firstByteTime = System.currentTimeMillis(); writer.write(i); IOUtils.copy(reader, writer); endTime = System.currentTimeMillis(); body = writer.toString(); try { reader.close(); writer.close(); } catch (IOException e) { // ignore } } long waitingTime = firstByteTime - startTime; long readingTime = endTime - firstByteTime; _logger.debug("urlfetch.timings", "waiting time: " + waitingTime + "ms"); _logger.debug("urlfetch.timings", "reading time: " + readingTime + "ms"); Statistics.instance().collectUrlfetchTime(startTime, firstByteTime, endTime); _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waitingTime) .collect((system) ? "asub" : "auub", waitingTime); } } catch (IllegalArgumentException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; throw new AcreURLFetchException("failed to fetch URL. " + " - Request Error: " + cause.getMessage()); } catch (IOException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage()); } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage()); } finally { method.abort(); } }
From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java
@Override public DaemonTaskResult executeTask(Log log, DaemonTask task) { try {// w ww.j ava 2s . c om // Get the server version if (rpcVersion <= -1) { // Get server session statistics JSONObject response = makeRequest(log, buildRequestObject("session-get", new JSONObject())); rpcVersion = response.getJSONObject("arguments").getInt("rpc-version"); } JSONObject request = new JSONObject(); switch (task.getMethod()) { case Retrieve: // Request all torrents from server JSONArray fields = new JSONArray(); final String[] fieldsArray = new String[] { RPC_ID, RPC_NAME, RPC_ERROR, RPC_ERRORSTRING, RPC_STATUS, RPC_DOWNLOADDIR, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_PEERSGETTING, RPC_PEERSSENDING, RPC_PEERSCONNECTED, RPC_ETA, RPC_DOWNLOADSIZE1, RPC_DOWNLOADSIZE2, RPC_UPLOADEDEVER, RPC_TOTALSIZE, RPC_DATEADDED, RPC_DATEDONE, RPC_AVAILABLE, RPC_COMMENT }; for (String field : fieldsArray) { fields.put(field); } request.put("fields", fields); JSONObject result = makeRequest(log, buildRequestObject("torrent-get", request)); return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result.getJSONObject("arguments")), null); case GetStats: // Request the current server statistics JSONObject stats = makeRequest(log, buildRequestObject("session-get", new JSONObject())) .getJSONObject("arguments"); return new GetStatsTaskSuccessResult((GetStatsTask) task, stats.getBoolean("alt-speed-enabled"), rpcVersion >= 12 ? stats.getLong("download-dir-free-space") : -1); case GetTorrentDetails: // Request fine details of a specific torrent JSONArray dfields = new JSONArray(); dfields.put("trackers"); dfields.put("trackerStats"); JSONObject buildDGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false); buildDGet.put("fields", dfields); JSONObject getDResult = makeRequest(log, buildRequestObject("torrent-get", buildDGet)); return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(getDResult.getJSONObject("arguments"))); case GetFileList: // Request all details for a specific torrent JSONArray ffields = new JSONArray(); ffields.put("files"); ffields.put("fileStats"); JSONObject buildGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false); buildGet.put("fields", ffields); JSONObject getResult = makeRequest(log, buildRequestObject("torrent-get", buildGet)); return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFileList(getResult.getJSONObject("arguments"), task.getTargetTorrent())); case AddByFile: // Add a torrent to the server by sending the contents of a local .torrent file String file = ((AddByFileTask) task).getFile(); // Encode the .torrent file's data InputStream in = new Base64.InputStream(new FileInputStream(new File(URI.create(file))), Base64.ENCODE); StringWriter writer = new StringWriter(); int c; while ((c = in.read()) != -1) { writer.write(c); } in.close(); // Request to add a torrent by Base64-encoded meta data request.put("metainfo", writer.toString()); makeRequest(log, buildRequestObject("torrent-add", request)); return new DaemonTaskSuccessResult(task); case AddByUrl: // Request to add a torrent by URL String url = ((AddByUrlTask) task).getUrl(); request.put("filename", url); makeRequest(log, buildRequestObject("torrent-add", request)); return new DaemonTaskSuccessResult(task); case AddByMagnetUrl: // Request to add a magnet link by URL String magnet = ((AddByMagnetUrlTask) task).getUrl(); request.put("filename", magnet); makeRequest(log, buildRequestObject("torrent-add", request)); return new DaemonTaskSuccessResult(task); case Remove: // Remove a torrent RemoveTask removeTask = (RemoveTask) task; makeRequest(log, buildRequestObject("torrent-remove", buildTorrentRequestObject(removeTask.getTargetTorrent().getUniqueID(), "delete-local-data", removeTask.includingData()))); return new DaemonTaskSuccessResult(task); case Pause: // Pause a torrent PauseTask pauseTask = (PauseTask) task; makeRequest(log, buildRequestObject("torrent-stop", buildTorrentRequestObject(pauseTask.getTargetTorrent().getUniqueID(), null, false))); return new DaemonTaskSuccessResult(task); case PauseAll: // Resume all torrents makeRequest(log, buildRequestObject("torrent-stop", buildTorrentRequestObject(FOR_ALL, null, false))); return new DaemonTaskSuccessResult(task); case Resume: // Resume a torrent ResumeTask resumeTask = (ResumeTask) task; makeRequest(log, buildRequestObject("torrent-start", buildTorrentRequestObject(resumeTask.getTargetTorrent().getUniqueID(), null, false))); return new DaemonTaskSuccessResult(task); case ResumeAll: // Resume all torrents makeRequest(log, buildRequestObject("torrent-start", buildTorrentRequestObject(FOR_ALL, null, false))); return new DaemonTaskSuccessResult(task); case SetDownloadLocation: // Change the download location SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task; // Build request JSONObject sdlrequest = new JSONObject(); JSONArray sdlids = new JSONArray(); sdlids.put(Long.parseLong(task.getTargetTorrent().getUniqueID())); sdlrequest.put("ids", sdlids); sdlrequest.put("location", sdlTask.getNewLocation()); sdlrequest.put("move", true); makeRequest(log, buildRequestObject("torrent-set-location", sdlrequest)); return new DaemonTaskSuccessResult(task); case SetFilePriorities: // Set priorities of the files of some torrent SetFilePriorityTask prioTask = (SetFilePriorityTask) task; // Build request JSONObject prequest = new JSONObject(); JSONArray ids = new JSONArray(); ids.put(Long.parseLong(task.getTargetTorrent().getUniqueID())); prequest.put("ids", ids); JSONArray fileids = new JSONArray(); for (TorrentFile forfile : prioTask.getForFiles()) { fileids.put(Integer.parseInt(forfile.getKey())); // The keys are the indices of the files, so always numeric } switch (prioTask.getNewPriority()) { case Off: prequest.put("files-unwanted", fileids); break; case Low: prequest.put("files-wanted", fileids); prequest.put("priority-low", fileids); break; case Normal: prequest.put("files-wanted", fileids); prequest.put("priority-normal", fileids); break; case High: prequest.put("files-wanted", fileids); prequest.put("priority-high", fileids); break; } makeRequest(log, buildRequestObject("torrent-set", prequest)); return new DaemonTaskSuccessResult(task); case SetTransferRates: // Request to set the maximum transfer rates SetTransferRatesTask ratesTask = (SetTransferRatesTask) task; if (ratesTask.getUploadRate() == null) { request.put("speed-limit-up-enabled", false); } else { request.put("speed-limit-up-enabled", true); request.put("speed-limit-up", ratesTask.getUploadRate().intValue()); } if (ratesTask.getDownloadRate() == null) { request.put("speed-limit-down-enabled", false); } else { request.put("speed-limit-down-enabled", true); request.put("speed-limit-down", ratesTask.getDownloadRate().intValue()); } makeRequest(log, buildRequestObject("session-set", request)); return new DaemonTaskSuccessResult(task); case SetAlternativeMode: // Request to set the alternative speed mode (Tutle Mode) SetAlternativeModeTask altModeTask = (SetAlternativeModeTask) task; request.put("alt-speed-enabled", altModeTask.isAlternativeModeEnabled()); makeRequest(log, buildRequestObject("session-set", request)); return new DaemonTaskSuccessResult(task); case ForceRecheck: // Verify torrent data integrity ForceRecheckTask verifyTask = (ForceRecheckTask) task; makeRequest(log, buildRequestObject("torrent-verify", buildTorrentRequestObject(verifyTask.getTargetTorrent().getUniqueID(), null, false))); return new DaemonTaskSuccessResult(task); default: return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType())); } } catch (JSONException e) { return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString())); } catch (DaemonException e) { return new DaemonTaskFailureResult(task, e); } catch (FileNotFoundException e) { return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString())); } catch (IOException e) { return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString())); } }
From source file:com.nhncorp.lucy.security.xss.XssFilter.java
private void serialize(Writer writer, Element element, StringWriter neloLogWriter) throws IOException { boolean hasAttrXss = false; checkRuleRemove(element);/* w w w. j a v a 2 s .c o m*/ if (element.isRemoved()) { /* if (this.isNeloLogEnabled) { neloLogWriter.write(this.neloElementRemoveMSG); neloLogWriter.write(element.getName() + "\n"); }*/ if (!this.withoutComment) { writer.write(REMOVE_TAG_INFO_START); writer.write(element.getName()); writer.write(REMOVE_TAG_INFO_END); } if (!element.isEmpty()) { this.serialize(writer, element.getContents(), neloLogWriter); } } else { //TODO // v1.3.3 & v1.5.1 BEFORE if (!element.isDisabled()) { if ((!element.isDisabled() || this.blockingPrefixEnabled)) { checkRule(element); } if (element.isDisabled()) { /*if (this.isNeloLogEnabled) { neloLogWriter.write(this.neloElementMSG); neloLogWriter.write(element.getName() + "\n"); }*/ if (this.blockingPrefixEnabled) { //BlockingPrefix ? , <, > ? Escape ? Element ?? ?? . element.setName(this.blockingPrefix + element.getName()); element.setEnabled(true); // close ? escape ?. isBlockingPrefixEnabled ?? ? . //writer.write('<'); //writer.write(element.getName()); } else { //BlockingPrefix ? , <, > ? Escape . if (!this.withoutComment) { writer.write(BAD_TAG_INFO); } writer.write("<"); writer.write(element.getName()); } } if (!element.isDisabled() && !this.withoutComment && element.existDisabledAttribute()) { writer.write(BAD_ATT_INFO_START); } Collection<Attribute> atts = element.getAttributes(); StringWriter attrSw = new StringWriter(); StringWriter attrXssSw = new StringWriter(); if (atts != null && !atts.isEmpty()) { for (Attribute att : atts) { if (!element.isDisabled() && att.isDisabled()) { hasAttrXss = true; if (!this.withoutComment) { attrXssSw.write(' '); att.serialize(attrXssSw); } } else { attrSw.write(' '); att.serialize(attrSw); } } } if (hasAttrXss) { String attrXssString = attrXssSw.toString(); /*if (this.isNeloLogEnabled) { neloLogWriter.write(this.neloAttrMSG); neloLogWriter.write(element.getName()); neloLogWriter.write(attrXssString + "\n"); }*/ if (!this.withoutComment) { writer.write(attrXssString); writer.write(BAD_ATT_INFO_END); } } if (!element.isDisabled()) { writer.write('<'); writer.write(element.getName()); } writer.write(attrSw.toString()); if (element.isStartClosed()) { writer.write(element.isDisabled() ? " />" : " />"); } else { writer.write(element.isDisabled() ? ">" : ">"); } if (!element.isEmpty()) { this.serialize(writer, element.getContents(), neloLogWriter); } if (element.isClosed()) { if (element.isDisabled() && !this.blockingPrefixEnabled) { writer.write("</"); writer.write(element.getName()); writer.write(">"); } else { writer.write("</"); writer.write(element.getName()); writer.write('>'); } } } }