Ejemplo n.º 1
0
  public CommandResult exec(String[] pCmd, File dir, Writer pOut, Writer pErr)
      throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder();
    Map<String, String> env = builder.environment();

    int out = 0;
    String pCmdString = ArrayUtils.toString(pCmd);
    logExec(pCmdString, env);

    StopWatch clock = new StopWatch();
    clock.start();
    try {
      process = Runtime.getRuntime().exec(pCmd, null, dir);
      out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
      this.cleanUpProcess();
      clock.stop();
      if (_log.isInfoEnabled()) _log.info("'" + pCmd + "' completed in " + clock.getTime() + " ms");
    }
    if (sig_interrupt.getValue() == true) {
      out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
  }
Ejemplo n.º 2
0
  protected List getList(String requestURL, HttpMethod method, Class clazz) {
    try {
      ClientHttpResponse response =
          requestFactory.createRequest(new URI(requestURL), method).execute();
      Writer writer = new StringWriter();
      char[] buffer = new char[1024];
      Reader reader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
      int n;
      while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
      }
      Log.d(TAG, writer.toString());
      JsonParser parser = new JsonParser();

      List result = new ArrayList();
      String jsonString = writer.toString();
      if (jsonString.equals("{}")) return result;

      JsonArray array = parser.parse(jsonString).getAsJsonArray();

      if (array != null) {
        for (int i = 0; i < array.size(); i++) {
          result.add(getObjectFromJsonString(array.get(i).toString(), clazz));
        }
      }

      return result;

    } catch (Exception e) {
      Log.d(TAG, "Error running getList", e);
      return null;
    }
  }
Ejemplo n.º 3
0
  public CommandResult exec(
      String[] pCmd, Map<String, String> pEnv, boolean useSysEnv, Writer pOut, Writer pErr)
      throws IOException, InterruptedException {

    int out = 0;
    String pCmdString = ArrayUtils.toString(pCmd);
    ProcessBuilder builder = new ProcessBuilder();
    builder.command(pCmd);

    Map<String, String> env = builder.environment();
    if (!useSysEnv) env.clear();
    for (String name : pEnv.keySet()) {
      env.put(name, pEnv.get(name));
    }

    logExec(pCmdString, env);

    StopWatch clock = new StopWatch();
    clock.start();
    try {
      process = builder.start();
      out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
      this.cleanUpProcess();
      clock.stop();
      if (_log.isInfoEnabled())
        _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms");
    }

    if (sig_interrupt.getValue() == true) {
      out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
  }
Ejemplo n.º 4
0
 public static void Main() {
   try {
     URL streams = new URL(sc2);
     URL bwstreams = new URL(bw);
     HttpURLConnection getstreams = (HttpURLConnection) streams.openConnection();
     HttpURLConnection getbwstreams = (HttpURLConnection) bwstreams.openConnection();
     InputStream in = new BufferedInputStream(getstreams.getInputStream());
     InputStream in2 = new BufferedInputStream(getbwstreams.getInputStream());
     Writer sw = new StringWriter();
     Writer sw2 = new StringWriter();
     char[] b = new char[1024];
     char[] c = new char[1024];
     Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
     Reader reader2 = new BufferedReader(new InputStreamReader(in2, "UTF-8"));
     int n, n2;
     while ((n = reader.read(b)) != -1) {
       sw.write(b, 0, n);
     }
     while ((n2 = reader2.read(c)) != -1) {
       sw2.write(c, 0, n2);
     }
     ss = sw.toString();
     ss2 = sw2.toString();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 5
0
 public static String getStackTrace(Throwable aThrowable) {
   final Writer result = new StringWriter();
   final PrintWriter printWriter = new PrintWriter(result);
   aThrowable.printStackTrace(printWriter);
   System.out.println("error: " + result.toString());
   return result.toString();
 }
Ejemplo n.º 6
0
  public void uncaughtException(Thread t, Throwable e) {
    // Cancel the notifications
    NotificationManager mNotificationMgr =
        (NotificationManager) CurContext.getSystemService(Context.NOTIFICATION_SERVICE);
    // Cancel the notifications
    if (mNotificationMgr != null) {
      mNotificationMgr.cancel(4);
      mNotificationMgr.cancel(3);
      mNotificationMgr.cancel(2);
    }
    Log.d(LOG, "unCaughtException");
    String Report = "";
    Date CurDate = new Date();
    Report += "Error Report collected on : " + CurDate.toString();
    Report += "\n";
    Report += "\n";
    Report += "Informations :";
    Report += "\n";
    Report += "==============";
    Report += "\n";
    Report += "\n";
    Report += CreateInformationString();

    Report += "\n\n";
    Report += "K-Phone Configuration: \n";
    Report += "==============\n\n";
    Report += CreatePreferencesString();
    Report += "======= \n";
    Report += "\n\n";
    Report += "Stack : \n";
    Report += "======= \n";
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    e.printStackTrace(printWriter);
    String stacktrace = result.toString();
    Report += stacktrace;

    Report += "\n";
    Report += "Cause : \n";
    Report += "======= \n";

    // If the exception was thrown in a background thread inside
    // AsyncTask, then the actual exception can be found with getCause
    Throwable cause = e.getCause();
    while (cause != null) {
      cause.printStackTrace(printWriter);
      Report += result.toString();
      cause = cause.getCause();
    }
    printWriter.close();
    Report += "****  End of current Report ***";
    SaveAsFile(Report);
    // SendErrorMail( Report );
    CheckErrorAndSendMail(CurContext);

    PreviousHandler.uncaughtException(t, e);
  }
Ejemplo n.º 7
0
  public ResultSet drillthrough(
      String queryName, List<Integer> cellPosition, Integer maxrows, String returns) {
    OlapStatement stmt = null;
    try {
      IQuery query = getIQuery(queryName);
      CellSet cs = query.getCellset();
      SaikuCube cube = getQuery(queryName).getCube();
      final OlapConnection con = olapDiscoverService.getNativeConnection(cube.getConnectionName());
      stmt = con.createStatement();

      String select = null;
      StringBuffer buf = new StringBuffer();
      buf.append("SELECT (");
      for (int i = 0; i < cellPosition.size(); i++) {
        List<Member> members =
            cs.getAxes().get(i).getPositions().get(cellPosition.get(i)).getMembers();
        for (int k = 0; k < members.size(); k++) {
          Member m = members.get(k);
          if (k > 0 || i > 0) {
            buf.append(", ");
          }
          buf.append(m.getUniqueName());
        }
      }
      buf.append(") ON COLUMNS \r\n");
      buf.append("FROM " + cube.getCubeName() + "\r\n");

      SelectNode sn = (new DefaultMdxParserImpl().parseSelect(getMDXQuery(queryName)));
      final Writer writer = new StringWriter();
      sn.getFilterAxis().unparse(new ParseTreeWriter(new PrintWriter(writer)));
      if (StringUtils.isNotBlank(writer.toString())) {
        buf.append("WHERE " + writer.toString());
      }
      select = buf.toString();
      if (maxrows > 0) {
        select = "DRILLTHROUGH MAXROWS " + maxrows + " " + select + "\r\n";
      } else {
        select = "DRILLTHROUGH " + select + "\r\n";
      }
      if (StringUtils.isNotBlank(returns)) {
        select += "\r\n RETURN " + returns;
      }

      log.debug("Drill Through for query (" + queryName + ") : \r\n" + select);
      ResultSet rs = stmt.executeQuery(select);
      return rs;
    } catch (Exception e) {
      throw new SaikuServiceException("Error DRILLTHROUGH: " + queryName, e);
    } finally {
      try {
        if (stmt != null) stmt.close();
      } catch (Exception e) {
      }
    }
  }
Ejemplo n.º 8
0
  /**
   * Compare contents of two resources (files) by performing some sort of processing on input
   * resource.
   *
   * @param inputResourceUri uri of the resource to process.
   * @param expectedContentResourceUri uri of the resource to compare with processed content.
   * @param processor a closure used to process somehow the input content.
   */
  public static void compare(
      final Reader resultReader, final Reader expectedReader, final ResourcePostProcessor processor)
      throws IOException {
    final Writer resultWriter = new StringWriter();
    processor.process(resultReader, resultWriter);
    final Writer expectedWriter = new StringWriter();

    IOUtils.copy(expectedReader, expectedWriter);
    compare(expectedWriter.toString(), resultWriter.toString());
    expectedReader.close();
    expectedWriter.close();
  }
 public String createTable() {
   Element root = new Element("table");
   root.setAttribute("border", "0");
   Document doc = new Document(root);
   Element thead = new Element("thead");
   Element th = new Element("th");
   th.addContent("A header");
   th.setAttribute("class", "aka_header_border");
   thead.addContent(th);
   Element th2 = new Element("th");
   th2.addContent("Another header");
   th2.setAttribute("class", "aka_header_border");
   thead.addContent(th2);
   root.addContent(thead);
   Element tr1 = new Element("tr");
   Element td1 = new Element("td");
   td1.setAttribute("valign", "top");
   td1.setAttribute("class", "cellBorders");
   td1.setText("cell contents");
   tr1.addContent(td1);
   root.addContent(tr1);
   XMLOutputter outp = new XMLOutputter();
   Format format = Format.getPrettyFormat();
   format.setOmitDeclaration(true);
   outp.setFormat(format);
   Writer writer = new StringWriter();
   try {
     outp.output(doc, writer);
   } catch (IOException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
   return writer.toString();
 }
  /** Handle the httpResponse and return the SOAP XML String. */
  protected String handleResponse(final HttpResponse response, final HttpContext context)
      throws IOException {
    final HttpEntity entity = response.getEntity();
    if (null == entity.getContentType()
        || !entity.getContentType().getValue().startsWith("application/soap+xml")) {
      throw new WinRMRuntimeIOException(
          "Error when sending request to "
              + getTargetURL()
              + "; Unexpected content-type: "
              + entity.getContentType());
    }

    final InputStream is = entity.getContent();
    final Writer writer = new StringWriter();
    final Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    try {
      int n;
      final char[] buffer = new char[1024];
      while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
      }
    } finally {
      Closeables.closeQuietly(reader);
      Closeables.closeQuietly(is);
      EntityUtils.consume(response.getEntity());
    }

    return writer.toString();
  }
Ejemplo n.º 11
0
  /**
   * @param configuration
   * @throws FileNotFoundException
   */
  public void generate(final Configuration configuration) {

    IOUtil ioUtil = new IOUtil();

    for (ConfigOutput configOutput : configuration.getOutputs()) {

      Writer writer = null;
      try {
        writer = this.generate(configOutput, configuration);
      } catch (Exception e) {
        e.printStackTrace();
        continue;
      }

      // TODO tratar o getFilenamePattern quando é "pattern"
      File outputFile =
          new File(configuration.getOutputBaseDir() + configOutput.getFilenamePattern());
      // grava no file system
      try {
        ioUtil.writeTo(outputFile, new StringReader(writer.toString()), "UTF-8");
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 12
0
 public String retriveInfo(String id) {
   Log.i(TAG, "retriveInfo()");
   URL url;
   HttpURLConnection urlConnection = null;
   Writer writer = null;
   String result = null;
   try {
     url = new URL("http://www.dndzgz.com/point?service=wifi&id=" + id);
     Log.i(TAG, url.toString());
     urlConnection = (HttpURLConnection) url.openConnection();
     InputStream in = urlConnection.getInputStream();
     if (in != null) {
       writer = new StringWriter();
       char[] buffer = new char[1024];
       try {
         Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
         int n;
         while ((n = reader.read(buffer)) != -1) {
           writer.write(buffer, 0, n);
         }
       } finally {
         in.close();
       }
     }
     result = writer.toString();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     urlConnection.disconnect();
   }
   Log.i(TAG, "Info Obtenida (¡¡Gracias DndZgz!!)");
   return result;
 }
Ejemplo n.º 13
0
 private String getErrorInfo(Throwable arg1) {
   Writer writer = new StringWriter();
   PrintWriter pw = new PrintWriter(writer);
   arg1.printStackTrace(pw);
   pw.close();
   return writer.toString();
 }
  /**
   * @see org.opencms.frontend.layoutpage.I_CmsMacroWrapper#getResult(java.lang.String,
   *     java.lang.String[])
   */
  public String getResult(String macroName, String[] args) {

    Writer out = new StringWriter();
    boolean error = false;
    try {
      // get the macro object to process
      Macro macro = (Macro) m_template.getMacros().get(macroName);
      if (macro != null) {
        // found macro, put it context
        putContextVariable(MACRO_NAME, macro);
        // process the template
        m_template.process(getContext(), out);
      } else {
        // did not find macro
        error = true;
      }
    } catch (Exception e) {
      if (LOG.isErrorEnabled()) {
        LOG.error(e.getLocalizedMessage(), e);
      }
      error = true;
    } finally {
      try {
        out.close();
      } catch (Exception e) {
        // ignore exception when closing writer
      }
    }
    if (error) {
      return "";
    }
    return out.toString();
  }
Ejemplo n.º 15
0
  public Task ProcessImage(byte[] in, ProcessingSettings settings) throws Exception {
    BufferedReader reader = null;
    try {
      URL url = new URL(ServerUrl + "/processImage?" + settings.AsUrlParams());
      // byte[] fileContents = in;//readDataFromFile( filePath );
      byte[] fileContents =
          readDataFromFile(Environment.getExternalStorageDirectory() + "/pirates.jpg");

      HttpURLConnection connection = openPostConnection(url);
      Log.e("wtffff", "it made it after openPost");
      connection.setRequestProperty("Content-Length", Integer.toString(fileContents.length));
      connection.getOutputStream().write(fileContents);
      Log.e("WTF", "it made it after getOutputStream");

      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } catch (Exception e) {
      final Writer result = new StringWriter();
      final PrintWriter printWriter = new PrintWriter(result);
      e.printStackTrace(printWriter);
      Log.e("MOTHER F****R", result.toString());
      // displayMessage( "Error: " + e.getClass() + ", " + e.getStackTrace().toString() + ", " +
      // e.getMessage() );
    }
    return new Task(reader);
  }
Ejemplo n.º 16
0
  @Override
  public void uncaughtException(Thread thread, Throwable ex) {

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);

    // Inject some info about android version and the device, since google can't provide them in the
    // developer console
    StackTraceElement[] trace = ex.getStackTrace();
    StackTraceElement[] trace2 = new StackTraceElement[trace.length + 3];
    System.arraycopy(trace, 0, trace2, 0, trace.length);
    trace2[trace.length + 0] =
        new StackTraceElement("Android", "MODEL", android.os.Build.MODEL, -1);
    trace2[trace.length + 1] =
        new StackTraceElement("Android", "VERSION", android.os.Build.VERSION.RELEASE, -1);
    trace2[trace.length + 2] =
        new StackTraceElement("Android", "FINGERPRINT", android.os.Build.FINGERPRINT, -1);
    ex.setStackTrace(trace2);

    ex.printStackTrace(printWriter);
    String stacktrace = result.toString();
    printWriter.close();
    Log.e(TAG, stacktrace);

    // Save the log on SD card if available
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      String sdcardPath = Environment.getExternalStorageDirectory().getPath();
      writeLog(stacktrace, sdcardPath + "/vlc_crash");
      writeLogcat(sdcardPath + "/vlc_logcat");
    }

    defaultUEH.uncaughtException(thread, ex);
  }
  private String readContent(InputStream content) throws IOException {
    if (content == null) return "";

    Reader reader = null;
    Writer writer = new StringWriter();
    String result;

    char[] buffer = new char[1024];
    try {
      reader = new BufferedReader(new InputStreamReader(content, ENCODING));
      int n;
      while ((n = reader.read(buffer)) > 0) {
        writer.write(buffer, 0, n);
      }
      result = writer.toString();
    } finally {
      content.close();
      if (reader != null) {
        reader.close();
      }
      if (writer != null) {
        writer.close();
      }
    }
    return result;
  }
  @Override
  public Object convertToInternal(Object payload, MessageHeaders headers) {
    Assert.notNull(this.marshaller, "Property 'marshaller' is required");
    try {
      if (byte[].class.equals(getSerializedPayloadClass())) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result result = new StreamResult(out);

        this.marshaller.marshal(payload, result);

        payload = out.toByteArray();
      } else {
        Writer writer = new StringWriter();
        Result result = new StreamResult(writer);

        this.marshaller.marshal(payload, result);

        payload = writer.toString();
      }
    } catch (MarshallingFailureException ex) {
      throw new MessageConversionException("Could not marshal XML: " + ex.getMessage(), ex);
    } catch (IOException ex) {
      throw new MessageConversionException("Could not marshal XML: " + ex.getMessage(), ex);
    }
    return payload;
  }
Ejemplo n.º 19
0
  public static String marshal(
      Object msg, String msgQName, String msgLocalName, String[] userPackages) throws Exception {

    TreeSet<String> contextPackages = new TreeSet<String>();
    for (int i = 0; i < userPackages.length; i++) {
      String userPackage = userPackages[i];
      contextPackages.add(userPackage);
    }

    JAXBContext jaxbContext =
        JAXBUtils.getJAXBContext(
            contextPackages,
            constructionType,
            contextPackages.toString(),
            XmlUtils.class.getClassLoader(),
            new HashMap<String, Object>());
    Marshaller marshaller = JAXBUtils.getJAXBMarshaller(jaxbContext);

    JAXBElement jaxbRequest =
        new JAXBElement(new QName(msgQName, msgLocalName), msg.getClass(), msg);
    Writer writer = new StringWriter();

    // Support XMLDsig
    XMLEventWriter xmlWriter = staxOF.createXMLEventWriter(writer);
    marshaller.marshal(jaxbRequest, xmlWriter);
    xmlWriter.flush();
    JAXBUtils.releaseJAXBMarshaller(jaxbContext, marshaller);

    return writer.toString();
  }
Ejemplo n.º 20
0
 public String outputHtmlText() {
   if (!legalChecker.empty()) {
     throw new RuntimeException("Stack not empty.");
   }
   if (writer instanceof StringWriter) return writer.toString();
   throw new RuntimeException("Not a string writer. Cannot use this method.");
 }
  /**
   * @param unusedLocale the wanted locale (actually unused).
   * @throws MavenReportException if any
   */
  protected void executeReport(Locale unusedLocale) throws MavenReportException {

    File config = buildConfigurationFile();

    Commandline cli = new Commandline();
    cli.setWorkingDirectory(getBasedir().getAbsolutePath());
    cli.setExecutable(getExecutablePath());
    cli.createArgument().setValue(config.getAbsolutePath());

    Writer stringWriter = new StringWriter();
    StreamConsumer out = new WriterStreamConsumer(stringWriter);
    StreamConsumer err = new WriterStreamConsumer(stringWriter);

    try {
      int returnCode = CommandLineUtils.executeCommandLine(cli, out, err);

      if (!isQuiet()) {
        // Get all output from doxygen and put it to the log out of Maven.
        String[] lines = stringWriter.toString().split("\n");
        for (int i = 0; i < lines.length; i++) {
          lines[i] = lines[i].replaceAll("\n|\r", "");
          getLog().info("doxygen: " + lines[i]);
        }
      }

      if (returnCode != 0) {
        throw new MavenReportException("Failed to generate Doxygen documentation.");
      }

    } catch (CommandLineException ex) {
      throw new MavenReportException("Error while executing Doxygen.", ex);
    }
  }
Ejemplo n.º 22
0
  private static String convertStreamToString(InputStream is) throws IOException {
    /*
     * To convert the InputStream to String we use the Reader.read(char[]
     * buffer) method. We iterate until the Reader return -1 which means
     * there's no more data to read. We use the StringWriter class to
     * produce the string.
     */
    if (is != null) {
      Writer writer = new StringWriter();

      char[] buffer = new char[1024];
      try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }
      } finally {
        is.close();
      }
      return writer.toString();
    } else {
      return "";
    }
  }
Ejemplo n.º 23
0
	public static String XMLContent(List<Book> books, Writer writer)
	{
		XmlSerializer serializer = Xml.newSerializer();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "books");
			for (Book book : books) {
				serializer.startTag("", "book");
				serializer.attribute("", "id", String.valueOf(book.getId()));
				serializer.startTag("", "name");
				serializer.text(book.getName());
				serializer.endTag("", "name");
				serializer.startTag("", "price");
				serializer.text(String.valueOf(book.getPrice()));
				serializer.endTag("", "price");
				serializer.endTag("", "book");
			}
			serializer.endTag("", "books");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
Ejemplo n.º 24
0
  @Override
  public void uncaughtException(Thread thread, Throwable ex) {
    try {
      final Writer result = new StringWriter();
      final PrintWriter printWriter = new PrintWriter(result);
      ex.printStackTrace(printWriter);
      String errorReport =
          String.format(
              "[%s]\nAndroidVersion=%s\nIMEI=%s\nID=%s\n%s",
              new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
              VERSION.RELEASE,
              getIMEI(),
              Preference.getUsername(mAppContext),
              result.toString());

      Log.e(LOGTAG, errorReport);

      File logFile = new File(mAppContext.getFilesDir(), LOG_FILE);
      FileWriter fw = new FileWriter(logFile, true);

      fw.write(errorReport);

      fw.flush();
      fw.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      android.os.Process.killProcess(android.os.Process.myPid());
    }
  }
Ejemplo n.º 25
0
  /**
   * Creates the REST API documentation in HTML form, using the controllers' data and the velocity
   * template.
   *
   * @param controllers .
   * @return string that contains the documentation in HTML form.
   * @throws Exception .
   */
  public String generateHtmlDocumentation(final List<DocController> controllers) throws Exception {

    logger.log(
        Level.INFO,
        "Generate velocity using template: "
            + velocityTemplatePath
            + (isUserDefineTemplatePath
                ? File.separator + velocityTemplateFileName + " (got template path from user)"
                : "(default template path)"));

    Properties p = new Properties();
    p.setProperty("directive.set.null.allowed", "true");
    if (isUserDefineTemplatePath) {
      p.setProperty("file.resource.loader.path", velocityTemplatePath);
    } else {
      p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
      p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    }

    Velocity.init(p);

    VelocityContext ctx = new VelocityContext();

    ctx.put("controllers", controllers);
    ctx.put("version", version);
    ctx.put("docCssPath", docCssPath);

    Writer writer = new StringWriter();

    Template template = Velocity.getTemplate(velocityTemplateFileName);
    template.merge(ctx, writer);

    return writer.toString();
  }
Ejemplo n.º 26
0
  public static void saveException(
      Throwable exception, Thread thread, CrashManagerListener listener) {
    final Date now = new Date();
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    BufferedWriter writer = null;
    exception.printStackTrace(printWriter);

    try {
      // Create filename from a random uuid
      String filename = UUID.randomUUID().toString();
      String path = Constants.FILES_PATH + "/" + filename + ".stacktrace";
      Log.d(Constants.TAG, "Writing unhandled exception to: " + path);

      // Write the stacktrace to disk
      writer = new BufferedWriter(new FileWriter(path));

      // HockeyApp expects the package name in the first line!
      writer.write("Package: " + Constants.APP_PACKAGE + "\n");
      writer.write("Version Code: " + Constants.APP_VERSION + "\n");
      writer.write("Version Name: " + Constants.APP_VERSION_NAME + "\n");

      if ((listener == null) || (listener.includeDeviceData())) {
        writer.write("Android: " + Constants.ANDROID_VERSION + "\n");
        writer.write("Manufacturer: " + Constants.PHONE_MANUFACTURER + "\n");
        writer.write("Model: " + Constants.PHONE_MODEL + "\n");
      }

      if (thread != null && ((listener == null) || (listener.includeThreadDetails()))) {
        writer.write("Thread: " + thread.getName() + "-" + thread.getId() + "\n");
      }

      if (Constants.CRASH_IDENTIFIER != null
          && (listener == null || listener.includeDeviceIdentifier())) {
        writer.write("CrashReporter Key: " + Constants.CRASH_IDENTIFIER + "\n");
      }

      writer.write("Date: " + now + "\n");
      writer.write("\n");
      writer.write(result.toString());
      writer.flush();

      if (listener != null) {
        writeValueToFile(limitedString(listener.getUserID()), filename + ".user");
        writeValueToFile(limitedString(listener.getContact()), filename + ".contact");
        writeValueToFile(listener.getDescription(), filename + ".description");
      }
    } catch (Exception another) {
      Log.e(Constants.TAG, "Error saving exception stacktrace!\n", another);
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (IOException e) {
        Log.e(Constants.TAG, "Error saving exception stacktrace!\n", e);
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 27
0
 public static String formatDoc(Document document) {
   try {
     OutputFormat format = new OutputFormat(document);
     format.setLineWidth(65);
     format.setIndenting(true);
     format.setIndent(2);
     Writer out = new StringWriter();
     XMLSerializer serializer = new XMLSerializer(out, format);
     serializer.serialize(document);
     System.out.println(out.toString());
     return out.toString();
   } catch (IOException e) {
     log.error("XmlWorks::formatDoc()", e);
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 28
0
  public static LayoutContent displayHome(spark.Request request, Configuration cfg) {
    String html = "";
    Map<String, String> root = Tools.listLayoutMap();
    root.replace("msg", DBH.getMsg(request.session().id()));
    Template temp;
    try {
      temp = cfg.getTemplate("user-home.htm");
      Writer out = new StringWriter();
      temp.process(root, out);
      html = out.toString();
    } catch (IOException | TemplateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      html = e.getMessage();
    }
    HashMap<String, String> options = new HashMap<String, String>();
    options.put("addBtn", Tools.getAddBtn("/tramites/agregar", "Iniciar Trámite"));
    options.put(
        "toolBar",
        Tools.getToolbarItem("/tramites/agregar", "Iniciar Trámite", "", "btn red darken-3")
            + Tools.getToolbarItem("/tramites", "Trámites", "", "btn green darken-3"));

    LayoutContent lc = new LayoutContent(html, options);
    return lc;
  }
Ejemplo n.º 29
0
  public static JSONObject getJsonFromInputStream(final InputStream inputStream, String type) {

    if (inputStream != null) {
      Writer writer = new StringWriter();
      int buffer_size = 1024;
      char[] buffer = new char[buffer_size];

      try {
        Reader reader =
            new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), buffer_size);
        int n;

        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }

        inputStream.close();
        reader.close();
        writer.close();

        return new JSONObject(writer.toString()).getJSONObject(type);

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return null;
  }
Ejemplo n.º 30
0
  @Override
  public void execute(Context context, Writer writer, Object[] values) throws Exception {
    Object assign = values[1];
    if (assign != null) {
      writer = new StringWriter();
    }

    // 加载子模板, 设置子模板的父容器
    Template template = context.getTemplate();
    String name = template.getPath((String) values[0], true);

    template = template.getEngine().getTemplate(name);
    Context childContext = new Context(context);

    int len = values.length;
    for (int i = 2; i < len; i += 2) {
      childContext.set((String) values[i], values[i + 1]);
    }

    template.merge(childContext, writer);

    if (assign != null) {
      context.set((String) assign, writer.toString());
    }
  }