@Override public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { if (this.isAccessAllowed(request, response, mappedValue) && this.isLoginRequest(request, response)) { if (((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")){ response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = response.getWriter(); out.println("{\"code\":200,\"info\":\"already logined\"}"); out.flush(); out.close(); }else { WebUtils.issueRedirect(request,response,this.getSuccessUrl()); } return false; } return super.onPreHandle(request, response, mappedValue); }
private synchronized String format(Level level, String msg, Throwable thrown) { date.setTime(System.currentTimeMillis()); String throwable = ""; if (thrown != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(); thrown.printStackTrace(pw); pw.close(); throwable = sw.toString(); } return String.format(formatString, date, getCallerInfo(), name, level.name(), msg, throwable); }
/** * Check to see if a class is well-formed. * * @param logger the logger to write to if a problem is found * @param logTag a tag to print to the log if a problem is found * @param classNode the class to check * @return true if the class is ok, false otherwise */ public static boolean isClassOk(final Logger logger, final String logTag, final ClassNode classNode) { final StringWriter sw = new StringWriter(); final ClassWriter verifyWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); classNode.accept(verifyWriter); final ClassReader ver = new ClassReader(verifyWriter.toByteArray()); try { DrillCheckClassAdapter.verify(ver, false, new PrintWriter(sw)); } catch(final Exception e) { logger.info("Caught exception verifying class:"); logClass(logger, logTag, classNode); throw e; } final String output = sw.toString(); if (!output.isEmpty()) { logger.info("Invalid class:\n" + output); return false; } return true; }
private static FileObject createFile ( final FileObject root, final String fqn, final String content) throws IOException { final FileObject file = FileUtil.createData( root, String.format("%s.java", fqn.replace('.', '/'))); //NOI18N final FileLock lck = file.lock(); try { final PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(lck))); try { out.print(content); } finally { out.close(); } } finally { lck.releaseLock(); } return file; }
public String helpScreen() { StringBuffer usage = new StringBuffer(); HelpFormatter formatter = new HelpFormatter(); if (cliOrder != null && cliOrder.size() > 0) { formatter.setOptionComparator(new OptionComparator()); } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); formatter.printHelp(pw, HCPMoverProperties.CLI_WIDTH.getAsInt(), getHelpUsageLine(), null /* header */, getOptions(), HelpFormatter.DEFAULT_LEFT_PAD /* leftPad */, HelpFormatter.DEFAULT_DESC_PAD /* descPad */, null /* footer */, false /* autoUsage */ ); usage.append(getHelpHeader()); usage.append(sw.toString()); usage.append(getHelpFooter()); return usage.toString(); }
/** * Saves the state of the logger to a file. * @throws IOException */ @Override public void saveLogFile() throws IOException { File logFile = new File(this.filename); if ( !(logFile.exists()) ) logFile.createNewFile(); FileWriter fileWriter = new FileWriter(this.filename); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.println("id,x,y,z"); for(int ctr = 0; ctr < this.ids.size(); ctr++) { printWriter.printf( "%d,%.4f,%.4f,%.4f%n", this.ids.get(ctr), this.x.get(ctr), this.y.get(ctr), this.z.get(ctr) ); } printWriter.close(); }
public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); Byte b = 1; int c; while ((c = System.in.read()) != -1) { char ch = (char) c; if (b == 1) { if (ch >= 'a' && ch <= 'z') ch = ((char) ((int) ch - 32)); if (ch >= 'A' && ch <= 'Z') b = 0; } else { if (ch >= 'A' && ch <= 'Z') ch = (char) ((int) ch + 32); } if (ch == '.' || ch == '!' || ch == '?') b = 1; out.print(ch); } out.flush(); }
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method=retriveMethod(req); if(method!=null){ invokeMethod(method, req, resp); }else{ VelocityContext context = new VelocityContext(); context.put("contextPath", req.getContextPath()); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("html/package-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
private FileObject createSource( @NonNull final FileObject root, @NonNull final String fqn, @NonNull final String content) throws IOException { final FileObject file = FileUtil.createData(root, fqn.replace('.', '/')+"."+JavaDataLoader.JAVA_EXTENSION); //NOI18N final FileLock lck = file.lock(); try { final PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(lck),"UTF-8")); //NOI18N try { out.print(content); } finally { out.close(); } } finally { lck.releaseLock(); } return file; }
synchronized public void dumpSessions(PrintWriter pwriter) { pwriter.print("Session Sets ("); pwriter.print(sessionSets.size()); pwriter.println("):"); ArrayList<Long> keys = new ArrayList<Long>(sessionSets.keySet()); Collections.sort(keys); for (long time : keys) { pwriter.print(sessionSets.get(time).sessions.size()); pwriter.print(" expire at "); pwriter.print(new Date(time)); pwriter.println(":"); for (SessionImpl s : sessionSets.get(time).sessions) { pwriter.print("\t0x"); pwriter.println(Long.toHexString(s.sessionId)); } } }
public RedisProcess runAndCheck() throws IOException, InterruptedException, FailedToStartRedisException { List<String> args = new ArrayList(options.values()); if (sentinelFile != null && sentinelFile.length() > 0) { String confFile = defaultDir + File.separator + sentinelFile; try (PrintWriter printer = new PrintWriter(new FileWriter(confFile))) { args.stream().forEach((arg) -> { if (arg.contains("--")) { printer.println(arg.replace("--", "\n\r")); } }); } args = args.subList(0, 1); args.add(confFile); args.add("--sentinel"); } RedisProcess rp = runWithOptions(this, args.toArray(new String[0])); if (!isCluster() && rp.redisProcess.waitFor(1000, TimeUnit.MILLISECONDS)) { throw new FailedToStartRedisException(); } Runtime.getRuntime().addShutdownHook(new Thread(() -> { rp.stop(); })); return rp; }
public static void addFavorite(String ip, int port) throws IOException { try { String path = Runner.class.getProtectionDomain().getCodeSource().getLocation().getPath(); PrintWriter pw = new PrintWriter(new FileWriter(path + "favorites.ini", true)); if (!favorites.contains(ip + " " + port)) { System.out.println("You haven't visited this server before. Would you like to save it for quick access later? (Y/N)"); String ch = lc.nextLine(); if (ch.contains("y") || ch.contains("Y")) { favorites.add(ip + " " + port); pw.println(ip + " " + port); pw.close(); System.out.println("Server saved.");} } } catch (Exception e) { System.err.println("addFavorite encountered an exception: " + e); e.printStackTrace(); } }
@BeforeClass public static void generateTestDataAndQueries() throws Exception { // Table consists of two columns "emp_id", "emp_name" and "dept_id" empTableLocation = testTempFolder.newFolder().getAbsolutePath(); // Write 100 records for each new file final int empNumRecsPerFile = 100; for(int fileIndex=0; fileIndex<NUM_EMPLOYEES/empNumRecsPerFile; fileIndex++) { File file = new File(empTableLocation + File.separator + fileIndex + ".json"); PrintWriter printWriter = new PrintWriter(file); for (int recordIndex = fileIndex*empNumRecsPerFile; recordIndex < (fileIndex+1)*empNumRecsPerFile; recordIndex++) { String record = String.format("{ \"emp_id\" : %d, \"emp_name\" : \"Employee %d\", \"dept_id\" : %d }", recordIndex, recordIndex, recordIndex % NUM_DEPTS); printWriter.println(record); } printWriter.close(); } // Initialize test queries groupByQuery = String.format("SELECT dept_id, count(*) as numEmployees FROM dfs.`%s` GROUP BY dept_id", empTableLocation); }
/** * 通用电脑模式,更改底部的二维码,提交保存 */ @RequestMapping(value = "popupQrImageUpdateSubmit") public void popupQrImageUpdateSubmit(Model model,HttpServletRequest request,HttpServletResponse response, @RequestParam("qrImageFile") MultipartFile multipartFile) throws IOException{ JSONObject json = new JSONObject(); Site site = getSite(); if(!(multipartFile.getContentType().equals("image/pjpeg") || multipartFile.getContentType().equals("image/jpeg") || multipartFile.getContentType().equals("image/png") || multipartFile.getContentType().equals("image/gif"))){ json.put("result", "0"); json.put("info", "请传入jpg、png、gif格式的二维码图"); }else{ //格式转换 BufferedImage bufferedImage = ImageUtil.inputStreamToBufferedImage(multipartFile.getInputStream()); BufferedImage tag = ImageUtil.formatConversion(bufferedImage); BufferedImage tag1 = ImageUtil.proportionZoom(tag, 400); //上传 AttachmentFile.put("site/"+site.getId()+"/images/qr.jpg", ImageUtil.bufferedImageToInputStream(tag1, "jpg")); AliyunLog.addActionLog(getSiteId(), "通用电脑模式,更改底部的二维码,提交保存"); json.put("result", "1"); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.append(json.toString()); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } }
private static GoogleCredentials createApplicationDefaultCredential() throws IOException { final MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); // Set the GOOGLE_APPLICATION_CREDENTIALS environment variable for application-default // credentials. This requires us to write the credentials to the location specified by the // environment variable. File credentialsFile = File.createTempFile("google-test-credentials", "json"); PrintWriter writer = new PrintWriter(Files.newBufferedWriter(credentialsFile.toPath(), UTF_8)); writer.print(ServiceAccount.EDITOR.asString()); writer.close(); Map<String, String> environmentVariables = ImmutableMap.<String, String>builder() .put("GOOGLE_APPLICATION_CREDENTIALS", credentialsFile.getAbsolutePath()) .build(); TestUtils.setEnvironmentVariables(environmentVariables); credentialsFile.deleteOnExit(); return GoogleCredentials.getApplicationDefault(new HttpTransportFactory() { @Override public HttpTransport create() { return transport; } }); }
protected void setUp() throws Exception { clearWorkDir(); File workDir = getWorkDir(); File cacheFolder = new File (workDir, "cache"); //NOI18N cacheFolder.mkdirs(); IndexUtil.setCacheFolder(cacheFolder); FileObject wd = FileUtil.toFileObject(this.getWorkDir()); assertNotNull(wd); this.src = wd.createFolder("src"); this.data = src.createData("Test","java"); FileLock lock = data.lock(); try { PrintWriter out = new PrintWriter ( new OutputStreamWriter (data.getOutputStream(lock))); try { out.println ("public class Test {}"); } finally { out.close (); } } finally { lock.releaseLock(); } ClassPathProviderImpl.getDefault().setClassPaths(createBootPath(),ClassPathSupport.createClassPath(new URL[0]),ClassPathSupport.createClassPath(new FileObject[]{this.src})); }
public static void main(String argv[]) throws Exception { AutoRunFromConsole.runYourselfInConsole(true); String clientSentence; ServerSocket welcomeSocket = new ServerSocket(4405); System.out.println("Logger started!"); PrintWriter outPrinter = new PrintWriter("tcp_log.txt"); while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while (true) { try { clientSentence = inFromClient.readLine(); if (clientSentence == null) break; System.out.println(clientSentence); outPrinter.println(clientSentence); outPrinter.flush(); } catch (Exception e) { break; } } System.out.println("Connection closed."); } }
@Override public void execute() throws BuildException { checkParameters(); try { final BufferedReader in = new BufferedReader(new FileReader(template)); //todo: encoding try { final PrintWriter out = new PrintWriter (new FileWriter(destFile)); //todo: encoding try { copy (in,out); } finally { out.close(); } } finally { in.close(); } } catch (IOException ioe) { throw new BuildException(ioe, getLocation()); } }
@Override public void printStackTrace(PrintWriter w) { // Print the stack trace for this exception. super.printStackTrace(w); Throwable parent = this; Throwable child; // Print the stack trace for each nested exception. while( (child = parent.getCause()) != null ) { w.print("Caused by: "); child.printStackTrace(w); if( child instanceof ApplicationException ) { break; } parent = child; } }
private void displayResults( PrintWriter writer, String failureNodeName, Enumeration resultsEnumeration ) { for (Enumeration e = resultsEnumeration; e.hasMoreElements();) { TestFailure failure = (TestFailure) e.nextElement(); writer.println( " <testcase name=" + asAttribute( failure.failedTest().toString() ) + ">" ); writer.print( " <" + failureNodeName + " type=" + asAttribute( failure.thrownException().getClass().getName() ) + " message=" + asAttribute( failure.exceptionMessage() ) ); if (!displayException( failure )) { writer.println( "/>" ); } else { writer.println( ">" ); writer.print( sgmlEscape( BaseTestRunner.getFilteredTrace( failure.thrownException() ) ) ); writer.println( " </" + failureNodeName + ">" ); } writer.println( " </testcase>" ); } }
/** * 返回报错信息。需要先保存到本地,再发送到后台;或者直接发送到后台? */ public static String getCrashText(Context context, Throwable ex) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.CHINA); //获取报错的堆栈信息 Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } //获取app的版本号 PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo; int versionCode = 0; try { packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); versionCode = packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } printWriter.close(); String result = writer.toString(); String time = formatter.format(new Date()); StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append("\nModel:" + android.os.Build.MODEL);//手机型号 stringBuffer.append("\nBrand:" + android.os.Build.BRAND);//手机厂商 stringBuffer.append("\nSdkVersion:" + android.os.Build.VERSION.RELEASE);//系统版本号 stringBuffer.append("\nappVersion" + versionCode);//软件版本号 stringBuffer.append("\nerrorStr:" + result);//报错信息 stringBuffer.append("\ntime:" + time);//时间 return stringBuffer.toString(); }
public void processException(HttpServletRequest request, HttpServletResponse response, Exception e) throws ServletException { boolean hide_error = EnginePropertiesManager.getProperty( PropertyName.HIDING_ERROR_INFORMATION ).equals( "true" ); boolean bThrowHTTP500 = Boolean.parseBoolean(EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.THROW_HTTP_500)); Engine.logEngine.error("Unexpected exception", e); if (bThrowHTTP500) { if(hide_error) throw new ServletException(); else throw new ServletException(e); } else { try { if (hide_error) response.addHeader("Convertigo-Exception", ""); else response.addHeader("Convertigo-Exception", e.getClass().getName()); response.setContentType(MimeType.Plain.value()); PrintWriter out = response.getWriter(); if (hide_error) out.println("Convertigo error:"); else out.println("Convertigo error: " + e.getMessage()); } catch (IOException e1) { Engine.logEngine.error("Unexpected exception", e1); if (hide_error) throw new ServletException(); else throw new ServletException(e); } } }
protected void sendOutboundScriptSuffix(PrintWriter out, String batchId) throws IOException { synchronized (out) { out.println(EnginePrivate.remoteEndIFrameResponse(batchId, true)); out.println("</script></body></html>"); } }
/** * Print the matrix to the output stream. Line the elements up in * columns with a Fortran-like 'Fw.d' style format. * * @param output Output stream. * @param w Column width. * @param d Number of digits after the decimal. */ public void print(PrintWriter output, int w, int d) { DecimalFormat format = new DecimalFormat(); format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(d); format.setMinimumFractionDigits(d); format.setGroupingUsed(false); print(output, format, w + 2); }
@Test public void test12() { StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); pw.println("insert into"); pw.println(" employee(id,name,sharding_id) values(4, 'myhome', 10011)"); pw.flush(); String oriSql = sw.toString(); String tableName = StringUtil.getTableName(oriSql); Assert.assertEquals("employee", tableName); }
/** * Initializes this server, setting the accepted connection protocol. * * @param protocol typically either SC_PROTOCOL_HTTP or SC_PROTOCOL_HSQL */ protected void init(int protocol) { // PRE: This method is only called from the constructor serverState = ServerConstants.SERVER_STATE_SHUTDOWN; serverConnSet = new HashSet(); serverId = toString(); serverId = serverId.substring(serverId.lastIndexOf('.') + 1); serverProtocol = protocol; serverProperties = ServerConfiguration.newDefaultProperties(protocol); logWriter = new PrintWriter(System.out); errWriter = new PrintWriter(System.err); JavaSystem.setLogToSystem(isTrace()); }
void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { writer.print(prefix); writer.print("Local Activity "); writer.print(Integer.toHexString(System.identityHashCode(this))); writer.println(" State:"); String innerPrefix = prefix + " "; writer.print(innerPrefix); writer.print("mResumed="); writer.print(mResumed); writer.print(" mStopped="); writer.print(mStopped); writer.print(" mFinished="); writer.println(mFinished); writer.print(innerPrefix); writer.print("mChangingConfigurations="); writer.println(mChangingConfigurations); writer.print(innerPrefix); writer.print("mCurrentConfig="); writer.println(mCurrentConfig); mFragments.dumpLoaders(innerPrefix, fd, writer, args); mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args); if (mVoiceInteractor != null) { mVoiceInteractor.dump(innerPrefix, fd, writer, args); } if (getWindow() != null && getWindow().peekDecorView() != null && getWindow().peekDecorView().getViewRootImpl() != null) { getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args); } mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix); }
/** * Returned socket may be sslsocket if TLSEnabled. * * @param socket * @param TLSEnabled * @param host * @param charset * @return * @throws IOException */ public static Socket getHelloFromServer(Socket socket, boolean TLSEnabled, String host, Charset charset) throws SSLPeerUnverifiedException, IOException, SocketTimeoutException{ PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset)); String line = in.readLine(); if (line == null || (!line.startsWith("200") && !line.startsWith("201") )){ Log.get().log(Level.WARNING, "Bad Hello from host {0} : {1}", new Object[]{host, line}); throw new IOException(); } if (TLSEnabled){ SSLSocket sslsocket = TLS.createSSLClientSocket(socket); out.print("STARTTLS"+NNTPConnection.NEWLINE); out.flush(); line = in.readLine(); if (line == null || !line.startsWith("382")) { //"382 Continue with TLS negotiation" Log.get().log(Level.WARNING, "From host {0} STARTTLS response: {1}", new Object[]{host, line}); throw new IOException(); } SSLSession session = sslsocket.getSession(); //handshake //throw exception: X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0]; //I am not sure how to check that it is right cert. TrustManager must do it. //ready for encrypted communication //new encrypted streams //this.out = new PrintWriter(new OutputStreamWriter(sslsocket.getOutputStream(), this.charset)); //this.in = new BufferedReader(new InputStreamReader(sslsocket.getInputStream(), this.charset)); return sslsocket; }else return socket; }
/** * Write a String into a PrintWriter, and encode special characters using * XML-specific encoding. * <p> * In particular, it changes LESS THAN, GREATER THAN, AMPERSAND, SINGLE * QUOTE, and DOUBLE QUOTE into "&lt;" "&gt;" "&amp;" * "&apos;" and "&quot;" and turns any characters outside of the * 32..126 range into the "&#xHHHH;" encoding (where HHHH is the 4 digit * lowercase hexadecimal representation of the character value). * * @param out - the PrintWriter to write into * @param str - the String to write out */ public static void encodeXML(PrintWriter out, String str) { int n = str.length(); for (int i = 0; i < n; i++) { char c = str.charAt(i); if (c == '<') { out.write("<"); continue; } if (c == '>') { out.write(">"); continue; } if (c == '&') { out.write("&"); continue; } if (c == '\'') { out.write("'"); continue; } if (c == '\"') { out.write("""); continue; } if (c >= 32 && c <= 126) { out.write(c); continue; } out.write("&#x"); String v = Integer.toString(c, 16); for (int j = v.length(); j < 4; j++) out.write('0'); out.write(v); out.write(';'); } }
private void generateInitDefaultLibrariesIngoreOrder(PrintWriter buff, Set<String> urls, String baseName) { buff.println("set = new TreeSet<String>();"); for (String url : urls) { buff.println("set.add(\"" + url + "\");"); } buff.println("librariesUrls.put(\"" + baseName + "\", set);"); }
/** * Stop the web application at the specified context path. * * @param writer Writer to render to * @param path Context path of the application to be stopped */ protected void stop(final PrintWriter writer, String path) { if (debug >= 1) { log("stop: Stopping web application at '" + path + '\''); } if (path == null || !path.startsWith("/") && path.length() == 0) { writer.println(sm.getString("managerServlet.invalidPath", path)); return; } final String displayPath = path; if (path.equals("/")) { path = ""; } try { final Context context = deployer.findDeployedApp(path); if (context == null) { writer.println(sm.getString("managerServlet.noContext", displayPath)); return; } // It isn't possible for the manager to stop itself if (context.getPath().equals(this.context.getPath())) { writer.println(sm.getString("managerServlet.noSelf")); return; } deployer.stop(path); writer.println(sm.getString("managerServlet.stopped", displayPath)); } catch (Throwable t) { log("ManagerServlet.stop[" + displayPath + ']', t); writer.println(sm.getString("managerServlet.exception", t.toString())); } }
/** * Write to the output the text and return a null view. * * @param response http response * @param text output text * @param status status code * @return a null view */ public static ModelAndView writeText(final HttpServletResponse response, final String text, final int status) { PrintWriter printWriter; try { printWriter = response.getWriter(); response.setStatus(status); printWriter.print(text); } catch (final IOException e) { LOGGER.error("Failed to write to response", e); } return null; }
void print(PrintWriter writer, String indent, boolean printChildren) { writer.printf("%s%s %s [%s] version %d%n", indent, type, name, fullPath(), getVersion()); if (printChildren) { for (Node child : children) { child.print(writer, indent + " ", true); } } }
private static void storeResult (File file, Set<String>data) throws IOException { PrintWriter out = new PrintWriter (new OutputStreamWriter (new FileOutputStream (file))); try { for (String s : data) { out.println(s); } } finally { out.close (); } }
public static void e(Exception ex) { if (!debug) { return; } StringWriter writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); ex.printStackTrace(pw); String string = writer.toString(); Log.e(DEFAULT_TAG, string); }
public void writeProjectFile(String projectFileName, String projectName, Vector<BuildConfig> allConfigs) throws IOException { System.out.println(); System.out.println(" Writing .vcproj file: " + projectFileName); // If we got this far without an error, we're safe to actually // write the .vcproj file printWriter = new PrintWriter(new FileWriter(projectFileName)); printWriter .println("<?xml version=\"1.0\" encoding=\"windows-1251\"?>"); startTag("VisualStudioProject", new String[] { "ProjectType", "Visual C++", "Version", projectVersion(), "Name", projectName, "ProjectGUID", "{8822CB5C-1C41-41C2-8493-9F6E1994338B}", "SccProjectName", "", "SccLocalPath", "" }); startTag("Platforms"); tag("Platform", new String[] { "Name", (String) BuildConfig.getField(null, "PlatformName") }); endTag(); startTag("Configurations"); for (BuildConfig cfg : allConfigs) { writeConfiguration(cfg); } endTag(); tag("References"); writeFiles(allConfigs); tag("Globals"); endTag(); printWriter.close(); System.out.println(" Done."); }
@Override public String toString() { try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintWriter out = new PrintWriter(buf); Method print = m_item.getClass().getMethod("print", PrintWriter.class); print.setAccessible(true); print.invoke(m_item, out); out.close(); return buf.toString().replace("\n", ""); } catch (Exception ex) { throw new Error(ex); } }
static void initialize(final Severity severity, final PrintStream out, final PrintStream err) { LOG_LEVEL = severity; final Charset cs; final String fileEncoding = System.getProperty("file.encoding"); if (fileEncoding == null || fileEncoding.trim().isEmpty()) { cs = StandardCharsets.UTF_8; } else { cs = Charset.forName(fileEncoding); } LoggerImpl.OUT = new PrintWriter(new OutputStreamWriter(out, cs)); LoggerImpl.ERR = new PrintWriter(new OutputStreamWriter(err, cs)); }
public void getAttribute(PrintWriter writer, String onameStr, String att, String key) { try { ObjectName oname = new ObjectName(onameStr); Object value = mBeanServer.getAttribute(oname, att); if(null != key && value instanceof CompositeData) value = ((CompositeData)value).get(key); String valueStr; if (value != null) { valueStr = value.toString(); } else { valueStr = "<null>"; } writer.print("OK - Attribute get '"); writer.print(onameStr); writer.print("' - "); writer.print(att); if(null != key) { writer.print(" - key '"); writer.print(key); writer.print("'"); } writer.print(" = "); writer.println(MBeanDumper.escape(valueStr)); } catch (Exception ex) { writer.println("Error - " + ex.toString()); ex.printStackTrace(writer); } }
public static void writeAll(final PrintWriter pw) { root.traverse(new Visitor() { public void visit(Node node) { node.write(pw); } }); pw.flush(); }