Java Code Examples for java.io.PrintWriter

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android-thaiime, under directory /latinime/src/com/sugree/inputmethod/latin/.

Source file: Utils.java

  33 
vote

private PrintWriter getPrintWriter(File dir,String filename,boolean renew) throws IOException {
  mFile=new File(dir,filename);
  if (mFile.exists()) {
    if (renew) {
      mFile.delete();
    }
  }
  return new PrintWriter(new FileOutputStream(mFile),true);
}
 

Example 2

From project azkaban, under directory /azkaban/src/java/azkaban/web/.

Source file: ApiServlet.java

  33 
vote

private void handleCall(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  if (!hasParam(req,"action")) {
    PrintWriter writer=resp.getWriter();
    writer.print("ApiServlet");
    return;
  }
  String action=getParam(req,"action");
  if (action.equals("run_job")) {
    handleRunJob(req,resp);
  }
}
 

Example 3

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: Utils.java

  32 
vote

public static void log(String message,Throwable throwable){
  if (throwable != null) {
    StringWriter sw;
    PrintWriter pw=new PrintWriter(sw=new StringWriter());
    throwable.printStackTrace(pw);
    message=message + '\n' + sw;
  }
  log(message,System.err);
}
 

Example 4

From project Aardvark, under directory /aardvark-core/src/test/java/gw/vark/.

Source file: AardvarkHelpModeTest.java

  32 
vote

@Test public void printHelp(){
  StringWriter writer=new StringWriter();
  PrintWriter out=new PrintWriter(writer);
  AardvarkHelpMode.printHelp(out);
  String eol=System.getProperty("line.separator");
  assertEquals("Usage:" + eol + "        vark [-f FILE] [options] [targets...]"+ eol+ ""+ eol+ "Options:"+ eol+ "        -f, -file FILE              load a file-based Gosu source"+ eol+ "            -url URL                load a url-based Gosu source"+ eol+ "            -classpath PATH         additional elements for the classpath, separated by commas"+ eol+ "        -p, -projecthelp            show project help (e.g. targets)"+ eol+ "            -logger LOGGERFQN       class name for a logger to use"+ eol+ "        -q, -quiet                  run with logging in quiet mode"+ eol+ "        -v, -verbose                run with logging in verbose mode"+ eol+ "        -d, -debug                  run with logging in debug mode"+ eol+ "        -g, -graphical              starts the graphical Aardvark editor"+ eol+ "            -verify                 verifies the Gosu source"+ eol+ "            -version                displays the version of Aardvark"+ eol+ "        -h, -help                   displays this command-line help"+ eol+ "",writer.toString());
}
 

Example 5

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/.

Source file: LazyList.java

  32 
vote

/** 
 * Dumps content of list to a stream. Use for debugging. 
 * @param out
 */
public void dump(OutputStream out){
  hydrate();
  PrintWriter p=new PrintWriter(out);
  for (  Model m : delegate) {
    p.write(m.toString() + "\n");
  }
  p.flush();
}
 

Example 6

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/Help/String/.

Source file: Str.java

  32 
vote

public static String getStackStr(final Exception err){
  if (err == null) {
    return "";
  }
  final Str stackoutstream=new Str();
  final PrintWriter stackstream=new PrintWriter(stackoutstream);
  err.printStackTrace(stackstream);
  stackstream.flush();
  stackstream.close();
  return stackoutstream.text;
}
 

Example 7

From project aerogear-controller, under directory /src/main/java/org/jboss/aerogear/controller/router/.

Source file: ErrorServlet.java

  32 
vote

/** 
 * Writes a general error page response to the client. 
 */
@Override protected void doGet(final HttpServletRequest req,final HttpServletResponse resp) throws ServletException, IOException {
  @SuppressWarnings("resource") final PrintWriter writer=resp.getWriter();
  final Throwable t=(Throwable)req.getAttribute(DefaultRouter.EXCEPTION_ATTRIBUTE_NAME);
  final String html=ErrorServlet.readTemplate(TEMPLATE,t);
  writer.write(html);
}
 

Example 8

From project agile, under directory /agile-apps/agile-app-search/src/main/java/org/headsupdev/agile/app/search/feed/.

Source file: SearchFeed.java

  32 
vote

@Override protected final void onRender(MarkupStream markupStream){
  PrintWriter writer=new PrintWriter(getResponse().getOutputStream());
  try {
    Document doc=new Document();
    Element root=new Element("searchResults");
    doc.setRootElement(root);
    populateFeed(root);
    XMLOutputter out=new XMLOutputter();
    out.output(doc,writer);
  }
 catch (  IOException e) {
    throw new RuntimeException("Error streaming feed.",e);
  }
}
 

Example 9

From project aim3-tu-berlin, under directory /seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/.

Source file: HadoopAndPactTestcase.java

  32 
vote

protected static void writeLines(File file,Iterable<String> lines) throws FileNotFoundException {
  PrintWriter writer=new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),Charset.forName("UTF-8")));
  try {
    for (    String line : lines) {
      writer.println(line);
    }
  }
  finally {
    writer.close();
  }
}
 

Example 10

From project airlift, under directory /bootstrap/src/main/java/io/airlift/bootstrap/.

Source file: Bootstrap.java

  32 
vote

private void logConfiguration(ConfigurationFactory configurationFactory,Map<String,String> unusedProperties){
  ColumnPrinter columnPrinter=makePrinterForConfiguration(configurationFactory);
  PrintWriter out=new PrintWriter(new LoggingWriter(log,Type.INFO));
  columnPrinter.print(out);
  out.flush();
  if (!unusedProperties.isEmpty()) {
    log.warn("UNUSED PROPERTIES");
    for (    Entry<String,String> unusedProperty : unusedProperties.entrySet()) {
      log.warn("%s=%s",unusedProperty.getKey(),unusedProperty.getValue());
    }
    log.warn("");
  }
}
 

Example 11

From project anadix, under directory /anadix-core/src/main/java/org/anadix/impl/.

Source file: DefaultReportFormatter.java

  32 
vote

/** 
 * {@inheritDoc} 
 */
public void formatAndStore(Report report,Writer w){
  if (report == null) {
    throw new NullPointerException("report cannot be null");
  }
  if (w == null) {
    throw new NullPointerException("w cannot be null");
  }
  PrintWriter pw=new PrintWriter(w);
  pw.println(format(report));
  pw.flush();
}
 

Example 12

From project androidannotations, under directory /AndroidAnnotations/androidannotations/src/main/java/com/googlecode/androidannotations/.

Source file: AndroidAnnotationProcessor.java

  32 
vote

private String stackTraceToString(Throwable e){
  StringWriter writer=new StringWriter();
  PrintWriter pw=new PrintWriter(writer);
  e.printStackTrace(pw);
  return writer.toString();
}
 

Example 13

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/utility/.

Source file: FileLogger.java

  32 
vote

static public synchronized void log(Exception e){
  if (sLogWriter != null) {
    log("Exception","Stack trace follows...");
    PrintWriter pw=new PrintWriter(sLogWriter);
    e.printStackTrace(pw);
    pw.flush();
  }
}
 

Example 14

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: FileUtils.java

  32 
vote

/** 
 * Dumps the stack trace of the given exception into the specified file.
 * @param f file to generate dump.
 * @param t exception to be dumped.
 * @throws IOException
 */
public static void dumpContent(File f,Throwable t) throws IOException {
  final ByteArrayOutputStream baos=new ByteArrayOutputStream();
  final PrintWriter pw=new PrintWriter(baos);
  t.printStackTrace(pw);
  pw.close();
  dumpContent(f,baos.toString());
}
 

Example 15

From project apb, under directory /modules/apb-base/src/apb/utils/.

Source file: StringUtils.java

  32 
vote

public static String getStackTrace(Throwable t){
  StringWriter sw=new StringWriter();
  PrintWriter pw=new PrintWriter(sw,true);
  t.printStackTrace(pw);
  pw.flush();
  pw.close();
  return sw.toString();
}
 

Example 16

From project archive-commons, under directory /archive-commons/src/test/java/org/archive/util/binsearch/.

Source file: SortedTextFileTest.java

  32 
vote

private void createFile(File target,int max) throws FileNotFoundException {
  PrintWriter pw=new PrintWriter(target);
  for (int i=0; i < max; i++) {
    pw.println(formatS(i));
  }
  pw.flush();
  pw.close();
}
 

Example 17

From project ardverk-commons, under directory /src/main/java/org/ardverk/lang/.

Source file: ExceptionUtils.java

  32 
vote

public static String toString(Throwable t){
  if (t == null) {
    return null;
  }
  StringWriter out=new StringWriter();
  PrintWriter pw=new PrintWriter(out);
  t.printStackTrace(pw);
  pw.close();
  return out.toString();
}
 

Example 18

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/rest/.

Source file: AggregatorRenderer.java

  32 
vote

@Override public void writeTo(AggregatorImpl impl,Class<?> type,Type genericType,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,Object> httpHeaders,OutputStream entityStream) throws IOException, WebApplicationException {
  PrintWriter pw=new PrintWriter(entityStream);
  StringTemplate st=StringTemplates.getTemplate("htmlOpen");
  st.setAttribute("header","Aggregator Details");
  st.setAttribute("msg","");
  pw.println(st.toString());
  pw.println(StringTemplates.getTemplate("tableOpen"));
  StringTemplate th=StringTemplates.getTemplate("tableHeader");
  th.setAttribute("headers",Arrays.asList("Aggregator","InputEvent","OutputEvent","Esper Statement"));
  pw.println(th);
  impl.renderHtml(pw,0);
  pw.println(StringTemplates.getTemplate("tableClose"));
  pw.println(StringTemplates.getTemplate("htmlClose"));
}
 

Example 19

From project arquillian-extension-warp, under directory /ftest/src/main/java/org/jboss/arquillian/warp/ftest/.

Source file: TestingServlet.java

  32 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/html");
  PrintWriter out=resp.getWriter();
  out.write("hello there\n");
  for (  Entry<String,String[]> entry : req.getParameterMap().entrySet()) {
    out.write(entry.getKey() + " = ");
    for (    String value : entry.getValue()) {
      out.write(value);
      out.write(", ");
    }
    out.write("\n");
  }
  out.close();
}
 

Example 20

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/servlet/renderer/.

Source file: AtomRenderer.java

  32 
vote

@Override public void render(final HTTPRequestContext context){
  try {
    final HttpServletResponse response=context.getResponse();
    response.setContentType("application/atom+xml");
    response.setCharacterEncoding("UTF-8");
    final PrintWriter writer=response.getWriter();
    writer.write(content);
    writer.close();
  }
 catch (  final IOException e) {
    LOGGER.log(Level.SEVERE,"Render failed",e);
  }
}
 

Example 21

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: Main.java

  32 
vote

public void run() throws Exception {
  MavenRepository repo=createRepository();
  PrintWriter latestRedirect=createHtaccessWriter();
  JSONObject ucRoot=buildUpdateCenterJson(repo,latestRedirect);
  writeToFile(updateCenterPostCallJson(ucRoot),output);
  writeToFile(updateCenterPostMessageHtml(ucRoot),new File(output.getPath() + ".html"));
  JSONObject rhRoot=buildFullReleaseHistory(repo);
  String rh=prettyPrintJson(rhRoot);
  writeToFile(rh,releaseHistory);
  latestRedirect.close();
}
 

Example 22

From project BeeQueue, under directory /src/org/beequeue/util/.

Source file: Throwables.java

  32 
vote

public static String toString(Throwable t){
  StringWriter stringWriter=new StringWriter();
  PrintWriter printWriter=new PrintWriter(stringWriter);
  t.printStackTrace(printWriter);
  printWriter.close();
  return stringWriter.toString();
}
 

Example 23

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: ErrorDisplayer.java

  32 
vote

private static String StackStraceTostring(Exception e){
  try {
    final Writer result=new StringWriter();
    final PrintWriter printWriter=new PrintWriter(result);
    e.printStackTrace(printWriter);
    return result.toString();
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return "";
}
 

Example 24

From project BetterShop_1, under directory /src/me/jascotty2/lib/util/.

Source file: Str.java

  32 
vote

public static String getStackStr(Exception err){
  if (err == null) {
    return "";
  }
  Str stackoutstream=new Str();
  PrintWriter stackstream=new PrintWriter(stackoutstream);
  err.printStackTrace(stackstream);
  stackstream.flush();
  stackstream.close();
  return stackoutstream.text.toString();
}
 

Example 25

From project big-data-plugin, under directory /shims/common/src-mapred/org/pentaho/hadoop/mapreduce/.

Source file: MRUtil.java

  32 
vote

public static String getStackTrace(Throwable t){
  StringWriter stringWritter=new StringWriter();
  PrintWriter printWritter=new PrintWriter(stringWritter,true);
  t.printStackTrace(printWritter);
  printWritter.flush();
  stringWritter.flush();
  return stringWritter.toString();
}
 

Example 26

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/spok/utils/.

Source file: SpectrumUtils.java

  32 
vote

public static Element readJCampDict() throws ValidityException, ParsingException, IOException {
  Builder builder=new Builder();
  URL varPluginUrl=Platform.getBundle("net.bioclipse.cml").getEntry("/dict10/simple/");
  String varInstallPath=null;
  try {
    varInstallPath=Platform.asLocalURL(varPluginUrl).getFile();
  }
 catch (  IOException e) {
    StringWriter strWr=new StringWriter();
    PrintWriter prWr=new PrintWriter(strWr);
  }
  Document jcampDict=builder.build(varInstallPath + "jcampDXDict.xml");
  return jcampDict.getRootElement();
}
 

Example 27

From project Blitz, under directory /src/com/laxser/blitz/web/instruction/.

Source file: TextInstruction.java

  32 
vote

private void sendResponse(HttpServletResponse response,String text) throws IOException {
  if (StringUtils.isNotEmpty(text)) {
    PrintWriter out=response.getWriter();
    if (logger.isDebugEnabled()) {
      logger.debug("write text to response:" + text);
    }
    out.print(text);
  }
}
 

Example 28

From project bndtools, under directory /bndtools.core/src/bndtools/.

Source file: Logger.java

  32 
vote

private String getStackTrace(Throwable t){
  if (t == null) {
    return "No exception trace is available";
  }
  final Writer sw=new StringWriter();
  final PrintWriter pw=new PrintWriter(sw);
  t.printStackTrace(pw);
  return sw.toString();
}
 

Example 29

From project boilerpipe, under directory /boilerpipe-core/src/demo/com/gbayer/boilerpipe/demo/.

Source file: ExtractHTMLWithImagesDemo.java

  32 
vote

public static void main(String[] args) throws Exception {
  URL url=new URL("file:///Users/gbayer/Desktop/techcrunch_story.html");
  final BoilerpipeExtractor extractor=CommonExtractors.ARTICLE_EXTRACTOR;
  final boolean includeImages=true;
  final boolean bodyOnly=true;
  final HTMLHighlighter hh=HTMLHighlighter.newExtractingInstance(includeImages,bodyOnly);
  PrintWriter out=new PrintWriter("/tmp/highlighted.html","UTF-8");
  out.println("<base href=\"" + url + "\" >");
  out.println("<meta http-equiv=\"Content-Type\" content=\"text-html; charset=utf-8\" />");
  String extractedHtml=hh.process(url,extractor);
  out.println(extractedHtml);
  out.close();
  System.out.println("Now open file:///tmp/highlighted.html in your web browser");
}
 

Example 30

From project boilerpipe_1, under directory /boilerpipe-core/src/demo/de/l3s/boilerpipe/demo/.

Source file: HTMLHighlightDemo.java

  32 
vote

public static void main(String[] args) throws Exception {
  URL url=new URL("http://research.microsoft.com/en-us/um/people/ryenw/hcir2010/challenge.html");
  final BoilerpipeExtractor extractor=CommonExtractors.ARTICLE_EXTRACTOR;
  final HTMLHighlighter hh=HTMLHighlighter.newHighlightingInstance();
  PrintWriter out=new PrintWriter("/tmp/highlighted.html","UTF-8");
  out.println("<base href=\"" + url + "\" >");
  out.println("<meta http-equiv=\"Content-Type\" content=\"text-html; charset=utf-8\" />");
  out.println(hh.process(url,extractor));
  out.close();
  System.out.println("Now open file:///tmp/highlighted.html in your web browser");
}
 

Example 31

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: PoolUtil.java

  32 
vote

/** 
 * For backwards compatibility with JDK1.5 (SQLException doesn't accept the original exception).
 * @param t exception
 * @return printStackTrace converted to a string
 */
public static String stringifyException(Throwable t){
  StringWriter sw=new StringWriter();
  PrintWriter pw=new PrintWriter(sw);
  t.printStackTrace(pw);
  String result="";
  result="------\r\n" + sw.toString() + "------\r\n";
  return result;
}
 

Example 32

From project book, under directory /src/main/java/com/tamingtext/classifier/bayes/.

Source file: ExtractTrainingData.java

  32 
vote

/** 
 * Obtain a writer for the training data assigned to the the specified category. <p> Maintains an internal hash of writers used for a category which must be closed by  {@link #closeWriters()}. <p>
 * @param outputDir
 * @param category
 * @return
 * @throws IOException
 */
protected static PrintWriter getWriterForCategory(File outputDir,String category) throws IOException {
  PrintWriter out=trainingWriters.get(category);
  if (out == null) {
    out=new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(outputDir,category))));
    trainingWriters.put(category,out);
  }
  return out;
}
 

Example 33

From project BPMN2-Editor-for-Eclipse, under directory /org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/wizards/.

Source file: FileService.java

  32 
vote

private static String getExceptionAsString(Throwable t){
  final StringWriter stringWriter=new StringWriter();
  final PrintWriter printWriter=new PrintWriter(stringWriter);
  t.printStackTrace(printWriter);
  final String result=stringWriter.toString();
  try {
    stringWriter.close();
  }
 catch (  final IOException e) {
  }
  printWriter.close();
  return result;
}
 

Example 34

From project bundlemaker, under directory /main/org.bundlemaker.core/src/org/bundlemaker/core/util/.

Source file: ListUtils.java

  32 
vote

/** 
 * <p> </p>
 * @param list
 * @param file
 */
public static void outputListToFile(List<String> list,File file){
  try {
    PrintWriter printWriter=new PrintWriter(new FileWriter(file));
    for (    Object o : list) {
      printWriter.println(o);
    }
    printWriter.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 35

From project byteman, under directory /agent/src/main/java/org/jboss/byteman/agent/.

Source file: RuleScript.java

  32 
vote

public String toString(){
  StringWriter stringWriter=new StringWriter();
  PrintWriter writer=new PrintWriter(stringWriter);
  writeTo(writer);
  writer.flush();
  return stringWriter.toString();
}
 

Example 36

From project Cafe, under directory /testrunner/src/com/baidu/cafe/local/.

Source file: Log.java

  32 
vote

/** 
 * Handy function to get a loggable stack trace from a Throwable
 * @param tr An exception to log
 */
public static String getStackTraceString(Throwable tr){
  if (tr == null) {
    return "";
  }
  StringWriter sw=new StringWriter();
  PrintWriter pw=new PrintWriter(sw);
  tr.printStackTrace(pw);
  return sw.toString();
}
 

Example 37

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/servlet/.

Source file: AdServlet.java

  31 
vote

private void execute(final AsyncContext ctx,final AdContext adcontext){
  ctx.start(new Runnable(){
    public void run(){
      ServletResponse response=ctx.getResponse();
      PrintWriter out=null;
      try {
        out=response.getWriter();
        Map<String,Object> context=new HashMap<String,Object>();
        String adselect_url=RuntimeContext.getProperties().getProperty(AdServerConstants.CONFIG.PROPERTIES.ADSERVER_SELECT_URL,"");
        String adserver_url=RuntimeContext.getProperties().getProperty(AdServerConstants.CONFIG.PROPERTIES.ADSERVER_URL,"");
        context.put("adselect_url",adselect_url);
        context.put("adserver_url",adserver_url);
        context.put("adrequest_id",adcontext.getRequestid());
        context.put("enviroment",RuntimeContext.getEnviroment().toLowerCase());
        String content=RuntimeContext.getTemplateManager().processTemplate("ads",context);
        out.println(content);
      }
 catch (      Exception e) {
        log("Problem processing task",e);
        e.printStackTrace();
      }
 finally {
        if (out != null) {
          out.close();
        }
        ctx.complete();
      }
    }
  }
);
}
 

Example 38

From project AirReceiver, under directory /src/main/java/org/phlo/AirReceiver/.

Source file: LogFormatter.java

  31 
vote

@Override public String format(final LogRecord record){
  final StringBuilder s=new StringBuilder();
  s.append(DateFormater.format(new Date(record.getMillis())));
  s.append(" ");
  s.append(record.getLevel() != null ? record.getLevel().getName() : "?");
  s.append(" ");
  s.append(record.getLoggerName() != null ? record.getLoggerName() : "");
  s.append(" ");
  s.append(record.getMessage() != null ? record.getMessage() : "");
  if (record.getThrown() != null) {
    String stackTrace;
{
      final Throwable throwable=record.getThrown();
      final StringWriter stringWriter=new StringWriter();
      final PrintWriter stringPrintWriter=new PrintWriter(stringWriter);
      throwable.printStackTrace(stringPrintWriter);
      stringPrintWriter.flush();
      stackTrace=stringWriter.toString();
    }
    s.append(String.format("%n"));
    s.append(stackTrace);
  }
  s.append(String.format("%n"));
  return s.toString();
}
 

Example 39

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/controller/.

Source file: ReloadController.java

  31 
vote

/** 
 * Handle request.
 * @param request the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
@RequestMapping(method=RequestMethod.GET) @SuppressWarnings("unchecked") public ModelAndView handleRequest(final HttpServletRequest request,final HttpServletResponse response) throws Exception {
  if (this.log.isDebugEnabled()) {
    this.log.debug("Entering 'execute' method");
  }
  StartupListener.setupContext(request.getSession().getServletContext());
  final String referer=request.getHeader("Referer");
  if (referer != null) {
    this.log.info("reload complete, reloading user back to: " + referer);
    List<String> messages=(List)request.getSession().getAttribute(BaseFormController.MESSAGES_KEY);
    if (messages == null) {
      messages=new ArrayList();
    }
    messages.add("Reloading options completed successfully.");
    request.getSession().setAttribute(BaseFormController.MESSAGES_KEY,messages);
    response.sendRedirect(response.encodeRedirectURL(referer));
    return null;
  }
 else {
    response.setContentType("text/html");
    final PrintWriter out=response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Context Reloaded</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("<script type=\"text/javascript\">");
    out.println("alert('Context Reload Succeeded! Click OK to continue.');");
    out.println("history.back();");
    out.println("</script>");
    out.println("</body>");
    out.println("</html>");
  }
  return null;
}
 

Example 40

From project amber, under directory /oauth-2.0/integration-tests/src/test/java/org/apache/amber/oauth2/integration/.

Source file: ResourceTest.java

  31 
vote

@Test public void testResourceAccessBodyValidToken() throws Exception {
  URL url=new URL(Common.RESOURCE_SERVER + Common.PROTECTED_RESOURCE_BODY);
  URLConnection c=url.openConnection();
  if (c instanceof HttpURLConnection) {
    HttpURLConnection httpURLConnection=(HttpURLConnection)c;
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setAllowUserInteraction(false);
    httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    httpURLConnection.setRequestProperty("Content-Length",Integer.toString(Common.BODY_OAUTH2.length()));
    OutputStream ost=httpURLConnection.getOutputStream();
    PrintWriter pw=new PrintWriter(ost);
    pw.print(Common.BODY_OAUTH2);
    pw.flush();
    pw.close();
    testValidTokenResponse(httpURLConnection);
  }
}
 

Example 41

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: CreateTracking.java

  31 
vote

@Override public String toString(){
  if (this.createStr == null) {
    StringWriter sw=new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    this.createStr=sw.toString();
  }
  return this.createStr;
}
 

Example 42

From project android-client, under directory /xwiki-android-test-core/src/org/xwiki/android/rest/ral/test/.

Source file: TestDocumentRaoCreate.java

  31 
vote

@Override public void setUp() throws Exception {
  super.setUp();
  username=TestConstants.USERNAME;
  password=TestConstants.PASSWORD;
  serverUrl=TestConstants.SERVER_URL;
  wikiName=TestConstants.WIKI_NAME;
  spaceName=TestConstants.SPACE_NAME;
  pageName=TestConstants.CREATE_PAGE_NAME + "-" + count;
  attachmentName=TestConstants.ATTACHMENT_NAME;
  objClsName1=TestConstants.OBJECT_CLASS_NAME_1;
  objClsName2=TestConstants.OBJECT_CLASS_NAME_2;
  rm=new XmlRESTFulManager(serverUrl,username,password);
  api=rm.getRestConnector();
  rao=rm.newDocumentRao();
  doc=new Document(wikiName,spaceName,pageName);
  doc.setTitle(pageName);
  api.deletePage(wikiName,spaceName,pageName);
  if (count == 9) {
    Application sys=XWikiApplicationContext.getInstance();
    FileOutputStream fos=sys.openFileOutput(attachmentName,Context.MODE_WORLD_READABLE);
    PrintWriter writer=new PrintWriter(fos);
    writer.println("this is a text attachment.");
    writer.flush();
    writer.close();
    FileInputStream fis=sys.openFileInput(attachmentName);
    byte[] buff=new byte[30];
    int i=0;
    while (i != -1) {
      i=fis.read(buff);
    }
    Log.d(TAG,new String(buff));
    af1=sys.getFileStreamPath(attachmentName);
  }
  Log.d(TAG,"setup test method:" + count);
}
 

Example 43

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/src/au/com/bytecode/opencsv/.

Source file: CSVWriter.java

  31 
vote

/** 
 * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
 * @param writer the writer to an underlying CSV source.
 * @param separator the delimiter to use for separating entries
 * @param quotechar the character to use for quoted elements
 * @param escapechar the character to use for escaping quotechars or escapechars
 * @param lineEnd the line feed terminator to use
 */
public CSVWriter(Writer writer,char separator,char quotechar,char escapechar,String lineEnd){
  this.rawWriter=writer;
  this.pw=new PrintWriter(writer);
  this.separator=separator;
  this.quotechar=quotechar;
  this.escapechar=escapechar;
  this.lineEnd=lineEnd;
}
 

Example 44

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/latin/.

Source file: Utils.java

  31 
vote

private PrintWriter getPrintWriter(File dir,String filename,boolean renew) throws IOException {
  mFile=new File(dir,filename);
  if (mFile.exists()) {
    if (renew) {
      mFile.delete();
    }
  }
  return new PrintWriter(new FileOutputStream(mFile),true);
}
 

Example 45

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: CustomExceptionHandler.java

  31 
vote

@Override public void uncaughtException(Thread t,Throwable e){
  Log.i(AnkiDroidApp.TAG,"uncaughtException");
  collectInformation();
  Date currentDate=new Date();
  SimpleDateFormat df1=new SimpleDateFormat("EEE MMM dd HH:mm:ss ",Locale.US);
  SimpleDateFormat df2=new SimpleDateFormat(" yyyy",Locale.US);
  TimeZone tz=TimeZone.getDefault();
  StringBuilder reportInformation=new StringBuilder(10000);
  reportInformation.append(String.format("Report Generated: %s%s%s\nBegin Collected Information\n\n",df1.format(currentDate),tz.getID(),df2.format(currentDate)));
  for (  String key : mInformation.keySet()) {
    String value=mInformation.get(key);
    reportInformation.append(String.format("%s = %s\n",key,value));
  }
  reportInformation.append(String.format("End Collected Information\n\nBegin Stacktrace\n\n"));
  final Writer result=new StringWriter();
  final PrintWriter printWriter=new PrintWriter(result);
  e.printStackTrace(printWriter);
  reportInformation.append(String.format("%s\n",result.toString()));
  reportInformation.append(String.format("End Stacktrace\n\nBegin Inner exceptions\n\n"));
  Throwable cause=e.getCause();
  while (cause != null) {
    cause.printStackTrace(printWriter);
    reportInformation.append(String.format("%s\n",result.toString()));
    cause=cause.getCause();
  }
  reportInformation.append(String.format("End Inner exceptions"));
  printWriter.close();
  Log.i(AnkiDroidApp.TAG,"report infomation string created");
  saveReportToFile(reportInformation.toString());
  mPreviousHandler.uncaughtException(t,e);
}
 

Example 46

From project ant4eclipse, under directory /org.ant4eclipse.ant.core/src/org/ant4eclipse/ant/core/.

Source file: AbstractAnt4EclipseTask.java

  31 
vote

/** 
 * Delegates to the <code>doExecute()</code> method where the actual task logic should be implemented.
 */
@Override public final void execute() throws BuildException {
  try {
    AbstractAnt4EclipseDataType.validateAll();
    preconditions();
    doExecute();
  }
 catch (  Exception ex) {
    StringWriter sw=new StringWriter();
    ex.printStackTrace(new PrintWriter(sw));
    A4ELogging.error("Execute of %s failed: %s%n%s",getClass().getName(),ex,sw);
    throw new BuildException(ex.toString(),ex);
  }
}
 

Example 47

From project arquillian-core, under directory /protocols/servlet/src/main/java/org/jboss/arquillian/protocol/servlet/runner/.

Source file: ServletTestRunner.java

  31 
vote

public void executeTest(HttpServletResponse response,String outputMode,String className,String methodName) throws ClassNotFoundException, IOException {
  Class<?> testClass=SecurityActions.getThreadContextClassLoader().loadClass(className);
  TestRunner runner=TestRunners.getTestRunner();
  TestResult testResult=runner.execute(testClass,methodName);
  if (OUTPUT_MODE_SERIALIZED.equalsIgnoreCase(outputMode)) {
    writeObject(testResult,response);
  }
 else {
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    PrintWriter writer=response.getWriter();
    writer.write("<html>\n");
    writer.write("<head><title>TCK Report</title></head>\n");
    writer.write("<body>\n");
    writer.write("<h2>Configuration</h2>\n");
    writer.write("<table>\n");
    writer.write("<tr>\n");
    writer.write("<td><b>Method</b></td><td><b>Status</b></td>\n");
    writer.write("</tr>\n");
    writer.write("</table>\n");
    writer.write("<h2>Tests</h2>\n");
    writer.write("<table>\n");
    writer.write("<tr>\n");
    writer.write("<td><b>Method</b></td><td><b>Status</b></td>\n");
    writer.write("</tr>\n");
    writer.write("</table>\n");
    writer.write("</body>\n");
  }
}
 

Example 48

From project arquillian-extension-android, under directory /android-impl/src/main/java/org/jboss/arquillian/android/impl/.

Source file: EmulatorShutdown.java

  31 
vote

/** 
 * Sends a user command to the running emulator via its telnet interface.
 * @param port The emulator's telnet port.
 * @param command The command to execute on the emulator's telnet interface.
 * @return Whether sending the command succeeded.
 */
private Callable<Boolean> sendEmulatorCommand(final int port,final String command){
  return new Callable<Boolean>(){
    public Boolean call() throws IOException {
      Socket socket=null;
      BufferedReader in=null;
      PrintWriter out=null;
      try {
        socket=new Socket("127.0.0.1",port);
        out=new PrintWriter(socket.getOutputStream(),true);
        in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        if (in.readLine() == null) {
          return false;
        }
        out.write(command);
        out.write("\r\n");
      }
  finally {
        try {
          out.close();
          in.close();
          socket.close();
        }
 catch (        Exception e) {
        }
      }
      return true;
    }
  }
;
}
 

Example 49

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/result/statistics/.

Source file: OverallStatistics.java

  31 
vote

@Override public void setProperties(Properties properties){
  Writer writer=(Writer)properties.getProperty("overall-statistics-output");
  if (writer == null) {
    writer=new OutputStreamWriter(System.out);
  }
  this.printerWriter=new PrintWriter(writer);
}
 

Example 50

From project asadmin, under directory /war-example/src/main/java/org/n0pe/mojo/examples/war/.

Source file: DumbServlet.java

  31 
vote

@Override protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out=response.getWriter();
  try {
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet DumbServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet DumbServlet at " + request.getContextPath() + "</h1>");
    out.println("<p>Random Integer: " + new Random().nextInt() + "</p>");
    out.println("</body>");
    out.println("</html>");
  }
  finally {
    out.close();
  }
}
 

Example 51

From project atlas, under directory /src/main/java/com/ning/atlas/logging/.

Source file: ColorizedAppender.java

  31 
vote

public ColorizedAppender(){
  Console console=System.console();
  if (console == null) {
    error=warn=info=debug=NO_OP;
    this.writer=new PrintWriter(System.out);
  }
 else {
    error=new ColorWrapper("31");
    warn=new ColorWrapper("33");
    info=new ColorWrapper("32");
    debug=new ColorWrapper("34");
    this.writer=console.writer();
  }
}
 

Example 52

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/trace/.

Source file: TraceClientServlet.java

  31 
vote

@Override public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out=response.getWriter();
  String servers=request.getParameter("servers");
  if (servers != null) {
    String splitToken=System.getProperty("line.separator");
    lastInput=servers;
    if (splitToken == null) {
      splitToken="\n";
    }
    String[] parts=servers.split(splitToken);
    List<URL> urls=new LinkedList<URL>();
    for (    String p : parts) {
      String[] portHost=p.split(":");
      if (portHost.length != 2) {
        continue;
      }
      try {
        URL url=new URL("http://" + p);
        urls.add(url);
      }
 catch (      MalformedURLException e) {
        continue;
      }
    }
    List<Span> spans=collectAllSpans(urls);
    List<Span> merged=SpanAggregator.getFullSpans(spans).completeSpans;
    this.activeSpans.addAll(merged);
    List<Trace> traces=SpanAggregator.getTraces(merged).traces;
    List<TraceCollection> collections=SpanAggregator.getTraceCollections(traces);
    for (    TraceCollection col : collections) {
      this.activeCollections.put(col.getExecutionPathHash(),col);
    }
    response.sendRedirect("/overview/");
  }
 else {
    out.println("No text entered.");
  }
}
 

Example 53

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.

Source file: IndexProcessor.java

  31 
vote

@Override public void render(final HTTPRequestContext context){
  final HttpServletResponse response=context.getResponse();
  response.setContentType("text/html");
  response.setCharacterEncoding("UTF-8");
  try {
    final Template template=ConsoleRenderer.TEMPLATE_CFG.getTemplate("kill-browser.ftl");
    final PrintWriter writer=response.getWriter();
    final StringWriter stringWriter=new StringWriter();
    template.setOutputEncoding("UTF-8");
    template.process(getDataModel(),stringWriter);
    final String pageContent=stringWriter.toString();
    context.getRequest().setAttribute(PageCaches.CACHED_CONTENT,pageContent);
    writer.write(pageContent);
    writer.flush();
    writer.close();
  }
 catch (  final Exception e) {
    try {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
 catch (    final IOException ex) {
      LOGGER.log(Level.SEVERE,"Can not sned error 500!",ex);
    }
  }
}
 

Example 54

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/internal/.

Source file: Activator.java

  31 
vote

/** 
 * Logs an  {@link Exception} to the eclipse workbench.
 * @param e the  {@link Exception} to log
 */
public static void logException(Exception e){
  if (getInstance() == null) {
    final Writer result=new StringWriter();
    e.printStackTrace(new PrintWriter(result));
    System.err.println(result.toString());
  }
 else {
    getInstance().getLog().log(new Status(IStatus.ERROR,Activator.PLUGIN_ID,-1,e.getMessage(),e));
  }
}
 

Example 55

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/util/.

Source file: ErrorReporter.java

  31 
vote

public synchronized void uncaughtException(final Thread t,final Throwable e){
  report.append("=== collected at exception time ===\n\n");
  report.append("Total Internal memory: " + getTotalInternalMemorySize() + "\n");
  report.append("Available Internal memory: " + getAvailableInternalMemorySize() + "\n");
  report.append("\n");
  final Writer result=new StringWriter();
  final PrintWriter printWriter=new PrintWriter(result);
  e.printStackTrace(printWriter);
  final String stacktrace=result.toString();
  report.append(stacktrace + "\n");
  Throwable cause=e.getCause();
  while (cause != null) {
    cause.printStackTrace(printWriter);
    report.append("Cause:\n");
    report.append(result.toString() + "\n");
    cause=cause.getCause();
  }
  printWriter.close();
  report.append("\nContents of FilesDir " + filesDir + ":\n");
  appendReport(report,filesDir,0);
  report.append("\nContents of CacheDir " + cacheDir + ":\n");
  appendReport(report,cacheDir,0);
  saveAsFile(report.toString());
  previousHandler.uncaughtException(t,e);
}
 

Example 56

From project blacktie, under directory /stompconnect-1.0/src/main/java/org/codehaus/stomp/jms/.

Source file: ProtocolConverter.java

  31 
vote

protected void onStompReceive(StompFrame command) throws IllegalStateException, SystemException, JMSException, NamingException, IOException {
  checkConnected();
  Map<String,Object> headers=command.getHeaders();
  String destinationName=(String)headers.remove(Stomp.Headers.Send.DESTINATION);
  String xid=(String)headers.get("messagexid");
  Message msg;
  StompSession session;
  if (xid != null) {
    log.trace("Transaction was propagated: " + xid);
    TransactionImple tx=controlToTx(xid);
    tm.resume(tx);
    log.trace("Resumed transaction: " + tx);
    session=getXASession(tx);
    msg=session.receiveFromJms(destinationName,headers);
    tm.suspend();
    log.trace("Suspended transaction: " + tx);
  }
 else {
    log.trace("WAS NULL XID");
    session=noneXaSession;
    msg=session.receiveFromJms(destinationName,headers);
    log.trace("Received from JMS");
  }
  StompFrame sf;
  if (msg == null) {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    PrintWriter stream=new PrintWriter(new OutputStreamWriter(baos,"UTF-8"));
    stream.print("No messages available");
    stream.close();
    Map<String,Object> eheaders=new HashMap<String,Object>();
    eheaders.put(Stomp.Headers.Error.MESSAGE,"timeout");
    sf=new StompFrame(Stomp.Responses.ERROR,eheaders,baos.toByteArray());
  }
 else {
    sf=session.convertMessage(msg);
  }
  if (headers.containsKey(Stomp.Headers.RECEIPT_REQUESTED))   sf.getHeaders().put(Stomp.Headers.Response.RECEIPT_ID,headers.get(Stomp.Headers.RECEIPT_REQUESTED));
  sendToStomp(sf);
}
 

Example 57

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: Logger.java

  31 
vote

/** 
 * Write the exception stacktrace to the error log file 
 * @param e The exception to log
 */
public static void logError(Exception e,String msg){
  DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date date=new Date();
  String now=dateFormat.format(date);
  StringWriter sw=new StringWriter();
  PrintWriter pw=new PrintWriter(sw);
  e.printStackTrace(pw);
  String error="An Exception Occured @ " + now + "\n"+ "In Phone "+ Build.MODEL+ " ("+ Build.VERSION.SDK_INT+ ") \n"+ msg+ "\n"+ sw.toString();
  try {
    Log.e("BC Logger",error);
    BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(StorageUtils.getErrorLog()),"utf8"),8192);
    out.write(error);
    out.close();
  }
 catch (  Exception e1) {
  }
}
 

Example 58

From project brut.apktool, under directory /apktool-lib/src/main/java/brut/androlib/res/.

Source file: ResSmaliUpdater.java

  31 
vote

public void updateResIDs(ResTable resTable,File smaliDir) throws AndrolibException {
  try {
    Directory dir=new FileDirectory(smaliDir);
    for (    String fileName : dir.getFiles(true)) {
      Iterator<String> it=IOUtils.readLines(dir.getFileInput(fileName)).iterator();
      PrintWriter out=new PrintWriter(dir.getFileOutput(fileName));
      while (it.hasNext()) {
        String line=it.next();
        out.println(line);
        Matcher m1=RES_NAME_PATTERN.matcher(line);
        if (!m1.matches()) {
          continue;
        }
        Matcher m2=RES_ID_PATTERN.matcher(it.next());
        if (!m2.matches()) {
          throw new AndrolibException();
        }
        int resID=resTable.getPackage(m1.group(1)).getType(m1.group(2)).getResSpec(m1.group(3)).getId().id;
        if (m2.group(1) != null) {
          out.println(String.format(RES_ID_FORMAT_FIELD,m2.group(1),resID));
        }
 else {
          out.println(String.format(RES_ID_FORMAT_CONST,m2.group(2),resID));
        }
      }
      out.close();
    }
  }
 catch (  IOException ex) {
    throw new AndrolibException("Could not tag res IDs for: " + smaliDir.getAbsolutePath(),ex);
  }
catch (  DirectoryException ex) {
    throw new AndrolibException("Could not tag res IDs for: " + smaliDir.getAbsolutePath(),ex);
  }
}
 

Example 59

From project C-Cat, under directory /core/src/main/java/gov/llnl/ontology/mains/.

Source file: ParseUkWac.java

  31 
vote

public static void main(String[] args) throws Exception {
  PrintWriter writer=new PrintWriter(args[0]);
  Parser parser;
  if (args[1].equals("s"))   parser=new MaltSvmParser();
 else   parser=new MaltLinearParser();
  StringBuilder sentence=new StringBuilder();
  for (int i=2; i < args.length; ++i) {
    for (    String line : FileUtils.iterateFileLines(args[i])) {
      if (line.startsWith("<text") || line.startsWith("<s") || line.startsWith("</text")|| line.length() == 0)       writer.println(line);
 else       if (line.startsWith("</s")) {
        writer.println(parser.parseText("",sentence.toString()));
        sentence=new StringBuilder();
      }
 else       sentence.append(line.split("\\s+")[0]).append(" ");
    }
  }
  writer.close();
}
 

Example 60

From project Calendar-Application, under directory /au/com/bytecode/opencsv/.

Source file: CSVWriter.java

  31 
vote

/** 
 * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
 * @param writer the writer to an underlying CSV source.
 * @param separator the delimiter to use for separating entries
 * @param quotechar the character to use for quoted elements
 * @param escapechar the character to use for escaping quotechars or escapechars
 * @param lineEnd the line feed terminator to use
 */
public CSVWriter(Writer writer,char separator,char quotechar,char escapechar,String lineEnd){
  this.rawWriter=writer;
  this.pw=new PrintWriter(writer);
  this.separator=separator;
  this.quotechar=quotechar;
  this.escapechar=escapechar;
  this.lineEnd=lineEnd;
}
 

Example 61

From project candlepin, under directory /src/main/java/org/candlepin/servlet/filter/logging/.

Source file: LoggingResponseWrapper.java

  31 
vote

public PrintWriter getWriter() throws java.io.IOException {
  if (writer == null) {
    writer=new PrintWriter(getOutputStream());
  }
  return writer;
}
 

Example 62

From project capedwarf-blue, under directory /channel/src/main/java/org/jboss/capedwarf/channel/transport/.

Source file: LongIFrameChannelTransport.java

  31 
vote

public void serveMessages() throws IOException {
  log.info("Channel queue opened.");
  getResponse().setContentType("text/html");
  getResponse().setHeader("Transfer-Encoding","chunked");
  PrintWriter writer=getResponse().getWriter();
  writeMessage(writer,getChannelToken(),"open","");
  long startTime=System.currentTimeMillis();
  while (true) {
    long timeActive=System.currentTimeMillis() - startTime;
    long timeLeft=MAX_CONNECTION_DURATION - timeActive;
    if (timeLeft < 0) {
      break;
    }
    try {
      log.info("Waiting for message (for " + timeLeft + "ms)");
      List<String> messages=getQueue().getPendingMessages(timeLeft);
      for (      String message : messages) {
        log.info("Received message " + message);
        writeMessage(writer,getChannelToken(),"message",message);
      }
    }
 catch (    InterruptedException e) {
    }
  }
  writeMessage(writer,getChannelToken(),"close","");
}
 

Example 63

From project ambrose, under directory /common/src/main/java/com/twitter/ambrose/service/impl/.

Source file: InMemoryStatsService.java

  30 
vote

public InMemoryStatsService(){
  String dumpDagFileName=System.getProperty(DUMP_DAG_FILE_PARAM);
  String dumpEventsFileName=System.getProperty(DUMP_EVENTS_FILE_PARAM);
  if (dumpDagFileName != null) {
    try {
      dagWriter=new PrintWriter(dumpDagFileName);
    }
 catch (    FileNotFoundException e) {
      LOG.error("Could not create dag PrintWriter at " + dumpDagFileName,e);
    }
  }
  if (dumpEventsFileName != null) {
    try {
      eventsWriter=new PrintWriter(dumpEventsFileName);
    }
 catch (    FileNotFoundException e) {
      LOG.error("Could not create events PrintWriter at " + dumpEventsFileName,e);
    }
  }
}
 

Example 64

From project asterisk-java, under directory /src/main/java/org/asteriskjava/tools/.

Source file: HtmlEventTracer.java

  30 
vote

public HtmlEventTracer(){
  uniqueIds=new ArrayList<String>();
  events=new ArrayList<ManagerEvent>();
  colors=new HashMap<Class<? extends ManagerEvent>,String>();
  colors.put(NewChannelEvent.class,"#7cd300");
  colors.put(NewStateEvent.class,"#a4b6c8");
  colors.put(NewExtenEvent.class,"#efefef");
  colors.put(RenameEvent.class,"#ddeeff");
  colors.put(DialEvent.class,"#feec30");
  colors.put(BridgeEvent.class,"#fff8ae");
  colors.put(HangupEvent.class,"#ff6c17");
  try {
    writer=new PrintWriter(filename);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 65

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/util/.

Source file: CheckClassAdapter.java

  30 
vote

/** 
 * Checks a given class. <p> Usage: CheckClassAdapter &lt;fully qualified class name or class file name&gt;
 * @param args the command line arguments.
 * @throws Exception if the class cannot be found, or if an IO exceptionoccurs.
 */
public static void main(final String[] args) throws Exception {
  if (args.length != 1) {
    System.err.println("Verifies the given class.");
    System.err.println("Usage: CheckClassAdapter " + "<fully qualified class name or class file name>");
    return;
  }
  ClassReader cr;
  if (args[0].endsWith(".class")) {
    cr=new ClassReader(new FileInputStream(args[0]));
  }
 else {
    cr=new ClassReader(args[0]);
  }
  verify(cr,false,new PrintWriter(System.err));
}
 

Example 66

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/deterministic/.

Source file: GENMDeterministicGenerator.java

  30 
vote

/** 
 * Constructor for the GENMDeterministicGenerator. Allows for setting the molecular formula for which the isomers are to be generated as well as for setting an output path for a file with generated structures.
 * @param mf	 molecular formula string
 * @param path Path to the file used for writing structures. Leave blank if current directory should be used.If set to null then no structure file is written.
 */
public GENMDeterministicGenerator(String mf,String path) throws Exception {
  logger=LoggingToolFactory.createLoggingTool(GENMDeterministicGenerator.class);
  builder=NoNotificationChemObjectBuilder.getInstance();
  numberOfSetFragment=0;
  numberOfStructures=0;
  logger.debug(mf);
  IMolecularFormula formula=MolecularFormulaManipulator.getMolecularFormula(mf,this.builder);
  molecularFormula=new int[12];
  numberOfBasicUnit=new int[23];
  numberOfBasicFragment=new int[34];
  basicFragment=new ArrayList();
  structures=new ArrayList();
  listeners=new ArrayList();
  if (path != null)   structureout=new PrintWriter(new FileWriter(path + "structuredata.txt"),true);
 else   structureout=null;
  initializeParameters();
  analyseMolecularFormula(formula);
}
 

Example 67

From project Birthdays, under directory /src/com/rexmenpara/birthdays/util/.

Source file: ErrorReportHandler.java

  30 
vote

private String generateDebugReport(Throwable e){
  String report="";
  report+="-------------------------------\n\n";
  report+="--------- Device ---------\n\n";
  report+="Brand: " + Build.BRAND + "\n";
  report+="Device: " + Build.DEVICE + "\n";
  report+="Model: " + Build.MODEL + "\n";
  report+="Id: " + Build.ID + "\n";
  report+="Product: " + Build.PRODUCT + "\n";
  report+="-------------------------------\n\n";
  report+="--------- Firmware ---------\n\n";
  report+="SDK: " + Build.VERSION.SDK + "\n";
  report+="Release: " + Build.VERSION.RELEASE + "\n";
  report+="Incremental: " + Build.VERSION.INCREMENTAL + "\n";
  report+="-------------------------------\n\n";
  report+="--------- Exception ---------\n\n";
  report+="Message: " + e.getMessage() + "\n";
  StringWriter sw=new StringWriter();
  e.printStackTrace(new PrintWriter(sw));
  String stacktrace=sw.toString();
  report+="StackTrace: " + stacktrace + "\n";
  report+="-------------------------------\n\n";
  report+="--------- Cause ---------\n\n";
  Throwable cause=e.getCause();
  if (cause != null) {
    sw=new StringWriter();
    cause.printStackTrace(new PrintWriter(sw));
    stacktrace=sw.toString();
    report+="Message: " + cause.getMessage() + "\n";
    report+="StackTrace: " + cause.getStackTrace() + "\n";
    report+="-------------------------------\n\n";
  }
  return report;
}
 

Example 68

From project aether-core, under directory /aether-impl/src/test/java/org/eclipse/aether/internal/impl/.

Source file: DependencyGraphDumper.java

  29 
vote

public static void dump(PrintWriter writer,DependencyNode node){
  Context context=new Context();
  dump(context,node,0,true);
  LinkedList<Indent> indents=new LinkedList<Indent>();
  for (  Line line : context.lines) {
    if (line.depth > indents.size()) {
      if (!indents.isEmpty()) {
        if (indents.getLast() == Indent.CHILD) {
          indents.removeLast();
          indents.addLast(Indent.CHILDREN);
        }
 else         if (indents.getLast() == Indent.LAST_CHILD) {
          indents.removeLast();
          indents.addLast(Indent.NO_CHILDREN);
        }
      }
      indents.addLast(line.last ? Indent.LAST_CHILD : Indent.CHILD);
    }
 else     if (line.depth < indents.size()) {
      while (line.depth <= indents.size()) {
        indents.removeLast();
      }
      indents.addLast(line.last ? Indent.LAST_CHILD : Indent.CHILD);
    }
 else     if (line.last && !indents.isEmpty()) {
      indents.removeLast();
      indents.addLast(Indent.LAST_CHILD);
    }
    for (    Indent indent : indents) {
      writer.print(indent);
    }
    line.print(writer);
  }
  writer.flush();
}
 

Example 69

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/log/.

Source file: Report.java

  29 
vote

/** 
 * Prints a string to the writers.
 * @param string The string to print to the writers.
 */
public void print(final String string){
  this.log.info(string);
  for (  final PrintWriter out : this.writers) {
    out.print(string);
  }
}
 

Example 70

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/config/.

Source file: ConfigurationException.java

  29 
vote

/** 
 * Prints this <code>Throwable</code> and its backtrace to the specified print writer.
 * @param s  <code>PrintWriter</code> to use for output
 * @since JDK1.1
 */
public void printStackTrace(PrintWriter s){
  super.printStackTrace(s);
  if (throwable != null) {
    s.println("with nested exception " + throwable);
    throwable.printStackTrace(s);
  }
}
 

Example 71

From project android_packages_apps_Nfc, under directory /src/com/android/nfc/.

Source file: NfcDispatcher.java

  29 
vote

void dump(FileDescriptor fd,PrintWriter pw,String[] args){
synchronized (this) {
    pw.println("mOverrideIntent=" + mOverrideIntent);
    pw.println("mOverrideFilters=" + mOverrideFilters);
    pw.println("mOverrideTechLists=" + mOverrideTechLists);
  }
}
 

Example 72

From project ANNIS, under directory /annis-service/src/main/java/annis/ql/parser/.

Source file: AnnisParser.java

  29 
vote

public static String dumpTree(Start start){
  try {
    StringWriter result=new StringWriter();
    start.apply(new TreeDumper(new PrintWriter(result)));
    return result.toString();
  }
 catch (  RuntimeException e) {
    String errorMessage="could not serialize syntax tree";
    log.warn(errorMessage,e);
    return errorMessage;
  }
}
 

Example 73

From project Application-Builder, under directory /src/main/java/org/silverpeas/applicationbuilder/.

Source file: AppBuilderException.java

  29 
vote

public void printStackTrace(PrintWriter s){
  if (nestedException != null) {
    s.println(getMessage());
    nestedException.printStackTrace(s);
  }
 else {
    super.printStackTrace(s);
  }
}
 

Example 74

From project astyanax, under directory /src/main/java/com/netflix/astyanax/util/.

Source file: JsonRowsWriter.java

  29 
vote

public JsonRowsWriter(PrintWriter out,SerializerPackage serializers) throws ConnectionException {
  this.out=out;
  this.serializers=serializers;
  fieldNames.put(Field.NAMES,"names");
  fieldNames.put(Field.ROWS,"rows");
  fieldNames.put(Field.COUNT,"count");
  fieldNames.put(Field.ROW_KEY,"_key");
  fieldNames.put(Field.COLUMN,"column");
  fieldNames.put(Field.TIMESTAMP,"timestamp");
  fieldNames.put(Field.VALUE,"value");
  fieldNames.put(Field.TTL,"ttl");
}
 

Example 75

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/rest/service/.

Source file: ScriptRunner.java

  29 
vote

private ConsoleOutputBean eval(ScriptEngine engine,String evalScript,Map<String,?> bindings,final ConsoleOutputBean consoleOutputBean) throws ScriptException {
  updateBindings(engine,ScriptContext.ENGINE_SCOPE,new HashMap<String,Object>(){
{
      put("out",new PrintWriter(consoleOutputBean.getOut(),true));
      put("err",new PrintWriter(consoleOutputBean.getErr(),true));
    }
  }
);
  if (bindings != null && !bindings.isEmpty()) {
    updateBindings(engine,ScriptContext.ENGINE_SCOPE,bindings);
  }
  engine.getContext().setWriter(consoleOutputBean.getOut());
  engine.getContext().setErrorWriter(consoleOutputBean.getErr());
  engine.getContext().setReader(new NullReader(0));
  consoleOutputBean.setEvalResult(engine.eval(evalScript,engine.getContext()));
  return consoleOutputBean;
}
 

Example 76

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionSCM.java

  29 
vote

/** 
 * Submits the authentication info. This code is fairly ugly because of the way SVNKit handles credentials.
 */
public void postCredential(String url,final UserProvidedCredential upc,PrintWriter logWriter) throws SVNException, IOException {
  SVNRepository repository=null;
  try {
    repository=SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
    repository.setTunnelProvider(SVNWCUtil.createDefaultOptions(true));
    AuthenticationManagerImpl authManager=upc.new AuthenticationManagerImpl(logWriter){
      @Override protected void onSuccess(      String realm,      Credential cred){
        LOGGER.info("Persisted " + cred + " for "+ realm);
        credentials.put(realm,cred);
        save();
        if (upc.inContextOf != null)         new PerJobCredentialStore(upc.inContextOf).acknowledgeAuthentication(realm,cred);
      }
    }
;
    authManager.setAuthenticationForced(true);
    repository.setAuthenticationManager(authManager);
    repository.testConnection();
    authManager.checkIfProtocolCompleted();
  }
  finally {
    if (repository != null)     repository.closeSession();
  }
}
 

Example 77

From project BoneJ, under directory /src/org/doube/jama/.

Source file: Matrix.java

  29 
vote

/** 
 * 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);
}