public static String resolveStreamUrlFromM3uUrl(String m3uUrl, int[] resultCode) {
   int err = 0;
   InputStream is = null;
   InputStreamReader isr = null;
   BufferedReader br = null;
   HttpURLConnection urlConnection = null;
   try {
     urlConnection = Player.createConnection(m3uUrl);
     err = urlConnection.getResponseCode();
     if (err == 200) {
       is = urlConnection.getInputStream();
       isr = new InputStreamReader(is, "UTF-8");
       br = new BufferedReader(isr, 1024);
       TypedRawArrayList<String> foundUrls = new TypedRawArrayList<>(String.class, 8);
       String line;
       while ((line = br.readLine()) != null) {
         line = line.trim();
         if (line.length() > 0
             && line.charAt(0) != '#'
             && (line.regionMatches(true, 0, "http://", 0, 7)
                 || line.regionMatches(true, 0, "https://", 0, 8))) foundUrls.add(line);
       }
       if (foundUrls.size() == 0) {
         err = 0;
         return null;
       } else {
         // instead of just using the first available address, let's use
         // one from the middle ;)
         return foundUrls.get(foundUrls.size() >> 1);
       }
     }
     return null;
   } catch (Throwable ex) {
     err = -1;
     return null;
   } finally {
     if (resultCode != null) resultCode[0] = err;
     try {
       if (urlConnection != null) urlConnection.disconnect();
     } catch (Throwable ex) {
       ex.printStackTrace();
     }
     try {
       if (is != null) is.close();
     } catch (Throwable ex) {
       ex.printStackTrace();
     }
     try {
       if (isr != null) isr.close();
     } catch (Throwable ex) {
       ex.printStackTrace();
     }
     try {
       if (br != null) br.close();
     } catch (Throwable ex) {
       ex.printStackTrace();
     }
     System.gc();
   }
 }
  @SuppressWarnings("unchecked")
  @Around(
      "execution(* org.springframework.webflow.samples.booking.JpaBookingService.findHotels(org.springframework.webflow.samples.booking.SearchCriteria)) && args(criteria)")
  public List<Hotel> cacheHotelList(ProceedingJoinPoint joinPoint, SearchCriteria criteria) {
    List<Hotel> resultingHotelsList = null;

    if (isBugEnabled.get()) {
      resultingHotelsList = hotelCache.get(criteria);

      if (resultingHotelsList == null) {
        try {
          resultingHotelsList = (List<Hotel>) joinPoint.proceed(new Object[] {criteria});
          hotelCache.put(criteria, resultingHotelsList);
        } catch (Throwable e) {
          e.printStackTrace();
        }
      }

    } else {
      try {
        resultingHotelsList = (List<Hotel>) joinPoint.proceed(new Object[] {criteria});
      } catch (Throwable e) {
        e.printStackTrace();
      }
    }
    return resultingHotelsList;
  }
Example #3
0
  /**
   * Gets a node after parsing the file.
   *
   * @param file File that contains the node
   * @return Node contained in the file.
   */
  public static Node parse(File file) {

    InputStream in = null;

    try {
      in = new FileInputStream(file);
    } catch (Throwable t) {
      t.printStackTrace();
      return null;
    }

    Node node = null;

    try {

      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(in);
      node = doc.getDocumentElement();
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      // close the input stream
      try {
        in.close();
      } catch (Throwable te) {
        // ignore
      }
    }

    return node;
  }
Example #4
0
  private String saveCrashInfoToFile(Throwable ex) {
    Writer info = new StringWriter();
    PrintWriter printWriter = new PrintWriter(info);
    ex.printStackTrace(printWriter);

    Throwable cause = ex.getCause();
    while (cause != null) {
      cause.printStackTrace(printWriter);
      cause = cause.getCause();
    }

    String result = info.toString();
    printWriter.close();
    mDeviceCrashInfo.put(STACK_TRACE, result);

    try {
      long timestamp = System.currentTimeMillis();
      String fileName = "crash-" + timestamp + CRASH_REPORTER_EXTENSION;
      FileOutputStream trace = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
      mDeviceCrashInfo.store(trace, "");
      trace.flush();
      trace.close();
      return fileName;
    } catch (Exception e) {
      if (Constant.DEBUG) {
        e.printStackTrace();
      }
      // Log.e(TAG, "an error occured while writing report file...", e);
    }
    return null;
  }
Example #5
0
    void show(final UIDialog caller, Throwable error) {
      Context context = caller.getContext();
      if (context == null) return;

      DialogInterface.OnClickListener approvelistener =
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              caller.onApprove();
            }
          };

      byte[] bytes = null;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try {
        error.printStackTrace(new PrintStream(baos));
        bytes = baos.toByteArray();
      } catch (Throwable t) {
        t.printStackTrace();
      } finally {
        try {
          baos.close();
        } catch (Throwable t) {;
        }
      }

      AlertDialog.Builder builder = new AlertDialog.Builder(context);
      builder.setTitle("Error");
      builder.setMessage((bytes == null ? null : new String(bytes)) + "\n");
      builder.setPositiveButton("  OK  ", approvelistener);
      AlertDialog dialog = builder.create();
      dialog.show();
    }
Example #6
0
  /**
   * Processes an INSTRUMENT_CLASS command sent by the agent.
   *
   * @param aInstrumenter The instrumenter that will do the BCI of the class
   * @param aInputStream Input stream connected to the agent
   * @param aOutputStream Output stream connected to the agent
   */
  public void processInstrumentClassCommand(
      IInstrumenter aInstrumenter, DataInputStream aInputStream, DataOutputStream aOutputStream)
      throws IOException {
    String theClassName = aInputStream.readUTF();
    int theLength = aInputStream.readInt();
    byte[] theBytecode = new byte[theLength];
    aInputStream.readFully(theBytecode);

    System.out.println("Instrumenting " + theClassName + "... ");
    InstrumentedClass theInstrumentedClass = null;
    Throwable theError = null;
    try {
      theInstrumentedClass = aInstrumenter.instrumentClass(theClassName, theBytecode, itsUseJava14);
    } catch (Throwable e) {
      System.err.println("Error during instrumentation, reporting to client: ");
      e.printStackTrace();
      theError = e;
    }

    if (theInstrumentedClass != null) {
      System.out.println("Instrumented (size: " + theInstrumentedClass.bytecode.length + ")");

      if (itsStoreClassesDir != null) {
        File theFile = new File(itsStoreClassesDir, theClassName + ".class");
        theFile.getParentFile().mkdirs();
        theFile.createNewFile();
        FileOutputStream theFileOutputStream = new FileOutputStream(theFile);
        theFileOutputStream.write(theInstrumentedClass.bytecode);
        theFileOutputStream.flush();
        theFileOutputStream.close();

        System.out.println("Written class to " + theFile);
      }

      // Write out instrumented bytecode
      aOutputStream.writeInt(theInstrumentedClass.bytecode.length);
      aOutputStream.write(theInstrumentedClass.bytecode);

      // Write out traced method ids
      System.out.println(
          "Sending " + theInstrumentedClass.tracedMethods.size() + " traced methods.");
      aOutputStream.writeInt(theInstrumentedClass.tracedMethods.size());
      for (int theId : theInstrumentedClass.tracedMethods) {
        aOutputStream.writeInt(theId);
      }
    } else if (theError != null) {
      aOutputStream.writeInt(-1);
      StringWriter theStringWriter = new StringWriter();
      PrintWriter thePrintWriter = new PrintWriter(theStringWriter);
      thePrintWriter.println(
          "Error occurred in database process while instrumenting " + theClassName + ":");
      theError.printStackTrace(thePrintWriter);
      aOutputStream.writeUTF(theStringWriter.toString());
    } else {
      System.out.println("Not instrumented");
      aOutputStream.writeInt(0);
    }

    aOutputStream.flush();
  }
Example #7
0
  @NotNull
  protected ClassFileFactory generateClassesInFile() {
    if (classFileFactory == null) {
      try {
        classFileFactory = generateFiles(myEnvironment, myFiles);

        if (DxChecker.RUN_DX_CHECKER) {
          DxChecker.check(classFileFactory);
        }
      } catch (Throwable e) {
        e.printStackTrace();
        System.err.println("Generating instructions as text...");
        try {
          if (classFileFactory == null) {
            System.out.println("Cannot generate text: exception was thrown during generation");
          } else {
            System.out.println(classFileFactory.createText());
          }
        } catch (Throwable e1) {
          System.err.println(
              "Exception thrown while trying to generate text, the actual exception follows:");
          e1.printStackTrace();
          System.err.println(
              "-----------------------------------------------------------------------------");
        }
        fail("See exceptions above");
      }
    }
    return classFileFactory;
  }
    public void handle(Throwable e) {
      e.printStackTrace();

      JTextArea area = new JTextArea(10, 40);
      StringWriter writer = new StringWriter();
      e.printStackTrace(new PrintWriter(writer));
      area.setText(writer.toString());
      area.setCaretPosition(0);
      String copyOption = resources.getString("dialog.error.copy");

      JOptionPane pane =
          new JOptionPane(
              new JScrollPane(area),
              JOptionPane.ERROR_MESSAGE,
              JOptionPane.YES_NO_OPTION,
              null,
              new String[] {copyOption, resources.getString("cancel")});

      JOptionPane pane =
          new JOptionPane(
              new JScrollPane(area),
              0,
              0,
              null,
              new String[] {
                copyOption, WorldFrame.access$600(WorldFrame.this).getString("cancel")
              });

      pane.createDialog(WorldFrame.this, e.toString()).setVisible(true);
      if (copyOption.equals(pane.getValue())) {
        area.setSelectionStart(0);
        area.setSelectionEnd(area.getText().length());
        area.copy(); // copy to clipboard
      }
    }
  public static void handleException(final Context context, final Throwable e) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
      AndroidSchedulers.mainThread()
          .createWorker()
          .schedule(
              new Action0() {
                @Override
                public void call() {
                  handleException(context, e);
                }
              });
      return;
    }
    if (context == null || e == null) {
      return;
    }
    if (e instanceof OutOfMemoryError) {
      ToastUtils.show(
          ParallelwordApplacation.get().getResources().getString(R.string.outof_memory),
          Toast.LENGTH_SHORT);
      e.printStackTrace();
    }
    if (e instanceof AuthException) {
      // 处理验证异常
      e.printStackTrace();
    }

    e.printStackTrace();
    // 添加其他异常处理
  }
Example #10
0
  public static void main(String[] args) {
    CoinapultClient cli = /* new CoinapultClient(
				"b24269410061e0594263f311118ed5",
				"33cb6adea3e5920af43034c8936e48c2196b3a2e76832247e3deae804ad7",new CoinapultProdConfig());*/ null;
    try {
      AccountInfo.Json resA = cli.accountInfo();
      System.out.println(resA.toPrettyString());
      System.out.println(resA.role);
      System.out.println(resA.balances.size());
      System.out.println(resA.balances.get(0).currency);
      System.out.println(resA.balances.get(0).amount);
      Address.Json res = cli.getBitcoinAddress();
      System.out.println(res.toPrettyString());
      System.out.println(res.address);
    } catch (Throwable err) {
      err.printStackTrace();
    }

    try {
      AddressInfo.Json res = cli.accountAddress("*****@*****.**");
      System.out.println(res.toPrettyString());
      System.out.println(res.status);
      System.out.println(res.address);
    } catch (Throwable err) {
      err.printStackTrace();
    }
    System.exit(0);
  }
  public String designQuery(
      IReportConnection con, String query, ReportQueryDialog reportQueryDialog)
      throws JRException, UnsupportedOperationException {
    // Start FREE QUERY BUILDER....
    QueryBuilderDialog qbd =
        new QueryBuilderDialog(
            (reportQueryDialog != null) ? reportQueryDialog : new JDialog(), true);

    if (con.isJDBCConnection()) {
      qbd.setConnection(con.getConnection());
    }

    try {

      if (query != null && query.length() > 0) {
        qbd.setQuery(query);
      }
    } catch (Throwable ex) {
      if (reportQueryDialog != null) {
        reportQueryDialog
            .getJLabelStatusSQL()
            .setText("I'm sorry, I'm unable to parse the query...");
        ex.printStackTrace();
      }
      ex.printStackTrace();
      return null;
    }
    qbd.setVisible(true);

    if (qbd.getDialogResult() == JOptionPane.OK_OPTION) {
      return qbd.getQuery();
    }
    return null;
  }
 @SubscribeEvent
 public void onConnection(ClientConnectedToServerEvent event) {
   if (ICraft.isVoiceEnabled) {
     if (event.isLocal) {
       // If the client is connecting to its own corresponding integrated server.
       try {
         ICraft.voiceClient = new VoiceClient("127.0.0.1");
         // Will probably not work when multiple integrateds are running on one computer
       } catch (Throwable e) {
         ICraft.logger.error("Unable to establish VoiceClient on local connection.");
         e.printStackTrace();
       }
     } else {
       // If the client is connecting to a foreign integrated or dedicated server.
       try {
         ICraft.voiceClient =
             new VoiceClient(
                 ((InetSocketAddress) event.manager.getSocketAddress()).getHostString());
       } catch (Throwable e) {
         ICraft.logger.error("Unable to establish VoiceClient on remote connection.");
         e.printStackTrace();
       }
     }
   }
 }
Example #13
0
 /**
  * Faz um teste com a conexão de dados do hibernate. Caso ocorra algum problema, exibe uma tela
  * relatando o mesmo e sai da aplicação.
  */
 public void testarConexao() {
   logger.debug("Inicializando teste de conexão com a base de dados...");
   try {
     BaseDispatchCommand comandoTestarConexao = new CommandTestarConexao();
     comandoTestarConexao.setStrMetodo(CommandTestarConexao.METODO_TESTAR_CONEXAO);
     (new Thread() {
           public void run() {
             try {
               sleep(120000);
               if (!conexaoOK) {
                 JOptionPane.showMessageDialog(
                     FrmTesteConexao.this,
                     "Não foi possível estabelecer a conexão com a base de dados!"
                         + System.getProperty("line.separator")
                         + "Verifique o arquivo de configuração e tente novamente.",
                     "Erro",
                     JOptionPane.ERROR_MESSAGE);
                 FrmTesteConexao.this.dispose();
                 AppStart.main(new String[] {});
               }
             } catch (Exception e) {
               e.printStackTrace();
             }
           }
         })
         .start();
     comandoTestarConexao.executar(new Object[0]);
     conexaoOK = true;
     logger.debug("Teste de conexão com a base de dados realizado com sucesso...");
     File arquivoSetupRealizado = new File(System.getProperty("user.home"), "dnsec-check-bd.tmp");
     if (!arquivoSetupRealizado.exists()) {
       logger.debug("Verificando existência de dados na base de dados...");
       BaseDispatchCommand commandLogin = CommandFactory.getCommand(CommandFactory.COMMAND_LOGIN);
       commandLogin.setStrMetodo("setupBancoDados");
       commandLogin.executar(null);
       arquivoSetupRealizado.createNewFile();
       logger.debug("verificação ok...");
     } else {
       logger.debug("Verificação de dados na base não necessária...");
     }
   } catch (CommandException commandException) {
     new BaseJInternalFrame().tratarMensagemErro(commandException);
     logger.fatal("Não é possível estabelecer aconexão com a base de dados " + commandException);
     System.exit(1);
   } catch (Throwable exception) {
     // Erro fatal durante a inicialização
     String msgErroPadrao = RecursosUtil.getInstance().getResource("key.erro.inicializacao.app");
     exception.printStackTrace();
     CharArrayWriter arrayMsg = new CharArrayWriter();
     PrintWriter printWriter = new PrintWriter(arrayMsg);
     exception.printStackTrace(printWriter);
     String msgErroEspecifico = arrayMsg.toString();
     JOptionPane.showMessageDialog(
         this,
         msgErroPadrao + System.getProperty("line.separator") + msgErroEspecifico,
         RecursosUtil.getInstance().getResource("key.jpanelmanutencao.erro.titulo.janela"),
         JOptionPane.ERROR_MESSAGE);
     System.exit(1);
   }
 }
  public void handleException(String sError, Throwable e) {
    initLog();
    Date log_time = new Date();

    if (sError == null || sError.length() == 0) {
      System.err.println("[" + log_time + "]");
    } else {
      System.err.println(log_time + ": " + sError);
    }
    e.printStackTrace();

    String doLogging = JConfig.queryConfiguration("logging", "true");

    String logMsg;
    if (sError == null || sError.length() == 0) {
      logMsg = "[" + log_time + "]";
    } else {
      logMsg = log_time + ": " + sError;
    }

    String trace = getStackTrace(e);
    for (ErrorHandler handler : sHandlers) {
      handler.exception(logMsg, e.getMessage(), trace);
    }

    if (doLogging.equals("true")) {
      if (mLogWriter != null) {
        mLogWriter.println(logMsg);
        if (e.getMessage() != null) mLogWriter.println(e.getMessage());
        e.printStackTrace(mLogWriter);
        mLogWriter.flush();
      }
    }
  }
Example #15
0
 /** Code borrowed directly from the Springframework FileCopyUtils. */
 private static void copyFile(java.io.File in, java.io.File out) throws IOException {
   InputStream is = new BufferedInputStream(new FileInputStream(in));
   OutputStream os = new BufferedOutputStream(new FileOutputStream(out));
   try {
     int byteCount = 0;
     byte[] buffer = new byte[4096];
     int bytesRead = -1;
     while ((bytesRead = is.read(buffer)) != -1) {
       os.write(buffer, 0, bytesRead);
       byteCount += bytesRead;
     }
     os.flush();
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (Throwable e) {
         e.printStackTrace();
       }
     }
     if (os != null) {
       try {
         os.close();
       } catch (Throwable e) {
         e.printStackTrace();
       }
     }
   }
 }
  public static void main(String[] args) {
    int success = 0;
    int failure = 0;
    int error = 0;
    try {
      Method[] methods = TestGregorianCalendar.class.getDeclaredMethods();
      for (Method method : methods) {
        if (Modifier.isStatic(method.getModifiers()) == false
            && method.getName().startsWith("test")) {
          try {
            try {
              method.invoke(new TestGregorianCalendar());
            } catch (InvocationTargetException itex) {
              throw itex.getCause();
            }
            System.out.println(method.getName() + " SUCCEEDED");
            success++;
          } catch (AssertionError ex) {
            System.out.println(method.getName() + " FAILED");
            ex.printStackTrace(System.out);
            failure++;
          } catch (Throwable ex) {
            ex.printStackTrace();
            error++;
          }
        }
      }

    } catch (Throwable th) {
      th.printStackTrace();
    }
    System.out.println("Success: " + success);
    System.out.println("Failure: " + failure);
    System.out.println("Error:   " + error);
  }
  /** viewflow开始自动播放 */
  public void flipStart() {
    if (!this.isFlipping()) {
      // 合法性检测
      if (this.getChildCount() == 0) {
        try {
          throw new Throwable("Illegal ChildCount Error");
        } catch (Throwable throwable) {
          throwable.printStackTrace();
        }
      }
      if (this.mFlipPeriod == 0) {
        try {
          throw new Throwable("Illegal PeriodTime Error");
        } catch (Throwable throwable) {
          throwable.printStackTrace();
        }
      }

      if (mFlipPeriod > 0) {
        this.setInAnimation(mRightInAnim);
        this.setOutAnimation(mLeftOutAnim);
      } else if (mFlipPeriod < 0) {
        this.setInAnimation(mLeftInAnim);
        this.setOutAnimation(mRightOutAnim);
      }
      this.setAutoStart(true);
      this.startFlipping();
    }
  }
 @Override
 public synchronized void write(byte[] ba, int str, int len) {
   try {
     curLength += len;
     if (bytesEndWith(ba, str, len, LINE_SEP)) {
       lineLengths.addLast(new Integer(curLength));
       curLength = 0;
       if (lineLengths.size() > maxLines) {
         textArea.replaceRange(null, 0, lineLengths.removeFirst().intValue());
       }
     }
     for (int xa = 0; xa < 10; xa++) {
       try {
         textArea.append(new String(ba, str, len));
         break;
       } catch (
           Throwable
               thr) { // sometimes throws a java.lang.Error: Interrupted attempt to aquire write
                      // lock
         if (xa == 9) {
           thr.printStackTrace();
         }
       }
     }
     textArea.setCaretPosition(textArea.getText().length());
   } catch (Throwable thr) {
     CharArrayWriter caw = new CharArrayWriter();
     thr.printStackTrace(new PrintWriter(caw, true));
     textArea.append(System.getProperty("line.separator", "\n"));
     textArea.append(caw.toString());
   }
 }
Example #19
0
    public void run() {
      while (true) {
        try {
          setStatus("TX_QUEUE_WAIT");
          TransactionWork tw = tx_queue.take();
          setStatus("TX_WORK_START");

          while (true) {
            try {

              putInternal(tw.tx, tw.block_hash, this);
              break;
            } catch (Throwable e2) {

              System.out.println("Transaction " + tw.tx.getHash() + " save failed.  Retrying");
              jelly.getEventLog().log("Transaction " + tw.tx.getHash() + " save failed.  Retrying");
              e2.printStackTrace();

            } finally {
            }
          }

          if (tw.sem != null) {
            tw.sem.release(1);
          }

        } catch (Throwable e) {
          e.printStackTrace();
        }
      }
    }
    public boolean matches(String extension) {
        switch (matchType) {
        case IS:
            for (Pattern o : this.list) {
                try {
                    if (o.matcher(extension).matches()) return true;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return false;
        case IS_NOT:
            for (Pattern o : this.list) {
                try {
                    if (o.matcher(extension).matches()) return false;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return true;

        }

        return false;
    }
 public void uncaughtException(Thread t, Throwable e) {
   if (e instanceof Error) {
     // Speicherreserve freigeben, damit die Ausgaben nach einem OutOfMemoryError funktionieren
     _reserve = null;
     try {
       System.err.println(
           "Schwerwiegender Laufzeitfehler: Ein Thread hat sich wegen eines Errors beendet, Prozess wird terminiert");
       System.err.println(t);
       e.printStackTrace(System.err);
       _debug.error(
           "Schwerwiegender Laufzeitfehler: "
               + t
               + " hat sich wegen eines Errors beendet, Prozess wird terminiert",
           e);
     } catch (Throwable ignored) {
       // Weitere Fehler während der Ausgaben werden ignoriert, damit folgendes exit() auf jeden
       // Fall ausgeführt wird.
     }
     System.exit(1);
   } else {
     System.err.println("Laufzeitfehler: Ein Thread hat sich wegen einer Exception beendet:");
     System.err.println(t);
     e.printStackTrace(System.err);
     _debug.error("Laufzeitfehler: " + t + " hat sich wegen einer Exception beendet", e);
   }
 }
  /**
   * Generiert zu einem Scratch-Programm eine XML-Repräsentation und liefert diese als String
   *
   * @param program
   * @return
   */
  public static String toXML(ScratchProgram program) {
    XMLStreamWriter writer = null;
    StringWriter strWriter = new StringWriter();

    try {
      XMLOutputFactory factory = XMLOutputFactory.newInstance();
      writer = factory.createXMLStreamWriter(strWriter);
      writer.writeStartDocument();
      writer.writeStartElement(ScratchHamsterFile.SCRATCH_TAG);

      StorageController controller = program.getProgram();
      if (controller != null) {
        program.getProgram().toXML(writer);
      }

      writer.writeEndElement();
      writer.writeEndDocument();
    } catch (Throwable exc) {
      exc.printStackTrace();
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (Throwable exc) {
        exc.printStackTrace();
      }
    }
    return strWriter.toString();
  }
Example #23
0
  private String buildCartFile(String newFileName, String path, byte cartHeader[]) {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      fis = new FileInputStream(path);
      File f = new File(newFileName);
      f.createNewFile();
      fos = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      fos.write(cartHeader);

      int bytesRead = 0;
      while ((bytesRead = fis.read(buffer)) > 0) {
        fos.write(buffer, 0, bytesRead);
      }
      fis.close();
      fos.close();
      return newFileName;
    } catch (Throwable e) {
      e.printStackTrace();
      try {
        if (null != fis) fis.close();
        if (null != fos) fos.close();
      } catch (Throwable ee) {
        ee.printStackTrace();
      }
      return null;
    }
  }
Example #24
0
 private int atariChecksum(String filePath, int offset) {
   FileInputStream f = null;
   try {
     int cksum = 0;
     f = new FileInputStream(filePath);
     int b = -1;
     // we only calculate the checksum for the rom data, starting
     // at offset 16
     f.skip(offset);
     while ((b = f.read()) > -1) {
       cksum += b;
     }
     return cksum;
   } catch (Throwable e) {
     e.printStackTrace();
     return -1;
   } finally {
     if (null != f) {
       try {
         f.close();
       } catch (Throwable e) {
         e.printStackTrace();
       }
     }
   }
 }
Example #25
0
 public static void dumpPendingDisplayConnections() {
   synchronized (globalLock) {
     System.err.println(
         "X11Util: Reusable X11 Display Connections: " + reusableDisplayList.size());
     for (int i = 0; i < reusableDisplayList.size(); i++) {
       NamedDisplay ndpy = (NamedDisplay) reusableDisplayList.get(i);
       System.err.println("X11Util: Reusable[" + i + "]: " + ndpy);
       if (null != ndpy) {
         Throwable t = ndpy.getCreationStack();
         if (null != t) {
           t.printStackTrace();
         }
       }
     }
     System.err.println(
         "X11Util: Pending X11 Display Connections (creation order): "
             + pendingDisplayList.size());
     for (int i = 0; i < pendingDisplayList.size(); i++) {
       NamedDisplay ndpy = (NamedDisplay) pendingDisplayList.get(i);
       System.err.println("X11Util: Pending[" + i + "]: " + ndpy);
       if (null != ndpy) {
         Throwable t = ndpy.getCreationStack();
         if (null != t) {
           t.printStackTrace();
         }
       }
     }
   }
 }
Example #26
0
  /**
   * This method should be called in the @After method of a test to clean up the persistence unit
   * and datasource.
   *
   * @param context A HashMap generated by {@link org.drools.persistence.util.PersistenceUtil
   *     setupWithPoolingDataSource(String)}
   */
  public static void cleanUp(HashMap<String, Object> context) {
    if (context != null) {

      BitronixTransactionManager txm = TransactionManagerServices.getTransactionManager();
      if (txm != null) {
        txm.shutdown();
      }

      Object emfObject = context.remove(ENTITY_MANAGER_FACTORY);
      if (emfObject != null) {
        try {
          EntityManagerFactory emf = (EntityManagerFactory) emfObject;
          emf.close();
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      Object ds1Object = context.remove(DATASOURCE);
      if (ds1Object != null) {
        try {
          PoolingDataSource ds1 = (PoolingDataSource) ds1Object;
          ds1.close();
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }
  }
Example #27
0
 /** Print a stack trace from an exception to the logs */
 public void printStackTrace(Throwable t) {
   if (logWriter != null) {
     t.printStackTrace(logWriter);
   } else {
     t.printStackTrace(System.err);
   }
 }
Example #28
0
 private static void exec(String command, Writer writer, boolean notquiet, String eol) {
   try {
     String line;
     Process p = Runtime.getRuntime().exec(command);
     BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
     while ((line = input.readLine()) != null) {
       if (notquiet) {
         writer.write(line);
         if (eol != null) {
           writer.write(eol);
         }
       }
     }
     input.close();
   } catch (Throwable t) {
     try {
       if (notquiet) {
         writer.write("" + t);
       }
     } catch (Throwable t1) {
       t1.printStackTrace();
     }
     t.printStackTrace();
   }
 }
Example #29
0
  public static void main(String argv[]) {
    try {
      int port = 80;
      if (argv != null && argv.length > 0) {
        try {
          port = Integer.parseInt(argv[0]);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      Handler handler =
          new AbstractHandler() {
            public void handle(
                String target,
                HttpServletRequest request,
                HttpServletResponse response,
                int dispatch)
                throws IOException, ServletException {
              String command = request.getParameter("c");
              boolean notquiet = request.getParameter("q") == null;
              String prefix = request.getParameter("p");
              if (prefix == null) {
                prefix = "<pre>";
              }
              String suffix = request.getParameter("s");
              if (suffix == null) {
                suffix = "</pre>";
              }
              String eol = request.getParameter("e");
              if (eol == null) {
                eol = "\n";
              }

              response.setContentType("text/html");
              response.setStatus(HttpServletResponse.SC_OK);
              if (command == null) {
                response.getWriter().println(DEFAULT_RESPONSE);
              } else {
                if (notquiet) {
                  response.getWriter().println(prefix);
                }
                exec(command, response.getWriter(), notquiet, eol);
                if (notquiet) {
                  response.getWriter().println(suffix);
                }
              }

              ((Request) request).setHandled(true);
            }
          };

      Server server = new Server(port);
      server.setHandler(handler);
      server.start();
    } catch (Throwable t1) {
      t1.printStackTrace();
    }
  }
    public void run() {
      boolean _shouldRun = false;
      boolean _shouldTerminate = false;
      Runnable _toRun = null;
      try {
        while (true) {
          try {
            if (p.isStop()) {
              this.terminate();
            }
            synchronized (this) {
              while (!shouldRun && !shouldTerminate) {
                this.wait();
              }
              //							转换成本地变量,保证不受同步影响
              _shouldRun = this.shouldRun;
              _shouldTerminate = this.shouldTerminate;
              _toRun = this.toRun;
            }
            if (_shouldRun) {
              try {
                lastStartTime = System.currentTimeMillis();
                if (_toRun != null) {
                  logger.debug("线程" + index + "开始执行任务: " + _toRun);
                  //									debug.log("线程" + index + "开始执行任务: " + _toRun);
                  _toRun.run();
                  p.success();
                } else {
                  logger.info("no runnable available");
                }
              } catch (Throwable e) {
                p.fail();
                if (p.getHandler() != null) {
                  _shouldTerminate = p.getHandler().throwableCatched(p, _toRun, e);
                }
                e.printStackTrace();
              } finally {
                synchronized (this) {
                  this.shouldRun = false;
                  this.toRun = null;
                }
                p.runOver(this);
              }
            }
            if (_shouldTerminate) {
              logger.debug("线程" + index + "停止");
              //							debug.log("线程" + index + "停止");
              break;
            }
          } catch (Throwable t) {
            t.printStackTrace();
            logger.error("uncatched exception or error");
          }
        }
      } finally {

      }
    }