コード例 #1
1
  private static void testSysOut(String fs, String exp, Object... args) {
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
      PrintStream saveOut = System.out;
      fos = new FileOutputStream("testSysOut");
      System.setOut(new PrintStream(fos));
      System.out.format(Locale.US, fs, args);
      fos.close();

      fis = new FileInputStream("testSysOut");
      byte[] ba = new byte[exp.length()];
      int len = fis.read(ba);
      String got = new String(ba);
      if (len != ba.length) fail(fs, exp, got);
      ck(fs, exp, got);

      System.setOut(saveOut);
    } catch (FileNotFoundException ex) {
      fail(fs, ex.getClass());
    } catch (IOException ex) {
      fail(fs, ex.getClass());
    } finally {
      try {
        if (fos != null) fos.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        fail(fs, ex.getClass());
      }
    }
  }
コード例 #2
0
  @Override
  public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b.booleanValue());

    if (executionCount > maxRetries) {
      // 尝试次数超过用户定义的测试,默认5次
      retry = false;
    } else if (exceptionBlacklist.contains(exception.getClass())) {
      // 线程被用户中断,则不继续尝试
      retry = false;
    } else if (exceptionWhitelist.contains(exception.getClass())) {
      retry = true;
    } else if (!sent) {
      retry = true;
    }

    if (retry) {
      HttpUriRequest currentReq =
          (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
      retry = currentReq != null && !"POST".equals(currentReq.getMethod());
    }

    if (retry) {
      // 休眠1秒钟后再继续尝试
      SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
    } else {
      exception.printStackTrace();
    }

    return retry;
  }
コード例 #3
0
  /**
   * Get the file that contains the original picture. This is used as a workaround for the following
   * JVM bug: once in the navigator, it can't transform picture read from a file whose name contains
   * non-ASCII characters, like French accents.
   *
   * @return The file that contains the original picture, as the source for picture transformation
   * @throws JUploadIOException
   */
  public File getWorkingSourceFile() throws JUploadIOException {

    if (this.workingCopyTempFile == null) {
      uploadPolicy.displayDebug(
          "[getWorkingSourceFile] Creating a copy of "
              + getFileName()
              + " as a source working target.",
          20);
      FileInputStream is = null;
      FileOutputStream os = null;
      try {
        createWorkingCopyTempFile();

        is = new FileInputStream(getFile());
        os = new FileOutputStream(this.workingCopyTempFile);
        byte b[] = new byte[1024];
        int l;
        while ((l = is.read(b)) > 0) {
          os.write(b, 0, l);
        }
      } catch (IOException e) {
        throw new JUploadIOException("ImageReaderWriterHelper.getWorkingSourceFile()", e);
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            uploadPolicy.displayWarn(
                e.getClass().getName()
                    + " while trying to close FileInputStream, in PictureUploadPolicy.copyOriginalToWorkingCopyTempFile.");
          } finally {
            is = null;
          }
        }
        if (os != null) {
          try {
            os.close();
          } catch (IOException e) {
            uploadPolicy.displayWarn(
                e.getClass().getName()
                    + " while trying to close FileOutputStream, in PictureUploadPolicy.copyOriginalToWorkingCopyTempFile.");
          } finally {
            os = null;
          }
        }
      }
    }
    return this.workingCopyTempFile;
  } // getWorkingSourceFile()
コード例 #4
0
  public String getVCardStringFromUri(Uri contactUri) {
    // TODO: use this and maybe remove pic? or resize pic? at least
    // refactor! :) only remove pic when writing to tag!
    String lookupKey = getContactLookupKey(contactUri);
    try {
      AssetFileDescriptor afd =
          context
              .getContentResolver()
              .openAssetFileDescriptor(
                  Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey), "r");
      FileInputStream input = afd.createInputStream();

      int ch;
      StringBuffer strContent = new StringBuffer("");
      while ((ch = input.read()) != -1) strContent.append((char) ch);

      input.close();

      // TODO: add things that are not added by Android:
      // TWITTER
      // FACEBOOK
      // SKYPE?
      // PHOTO from SKYPE/FACEBOOK

      return strContent.toString();
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
      System.err.println(
          "Could not read vcard file: [" + e.getClass().getSimpleName() + "]" + e.getMessage());
      e.printStackTrace();
    } finally {
    }
    return null;
  }
コード例 #5
0
  public static void write(HttpServletResponse response, byte[][] bytesArray) throws IOException {

    try {

      // LEP-3122

      if (!response.isCommitted()) {
        int contentLength = 0;

        for (byte[] bytes : bytesArray) {
          contentLength += bytes.length;
        }

        response.setContentLength(contentLength);

        response.flushBuffer();

        ServletOutputStream servletOutputStream = response.getOutputStream();

        for (byte[] bytes : bytesArray) {
          servletOutputStream.write(bytes);
        }
      }
    } catch (IOException ioe) {
      if (ioe instanceof SocketException
          || ioe.getClass().getName().equals(_CLIENT_ABORT_EXCEPTION)) {

        if (_log.isWarnEnabled()) {
          _log.warn(ioe);
        }
      } else {
        throw ioe;
      }
    }
  }
コード例 #6
0
  /**
   * Validate the instance
   *
   * <p>Unlike all other validators:
   *
   * <ul>
   *   <li>this is the only one which will, if required, go over the net to grab new schemas;
   *   <li>this is the only one which can spawn a {@link ValidationContext} with a different root
   *       schema (if the ref represents an absolute {@link URI});
   *   <li>this is the only validator implementation which can spawn errors (ie, {@link
   *       ValidationReport#isError()} returns {@code true}) and not only failures.
   * </ul>
   *
   * @return the report from the spawned validator
   */
  @Override
  public ValidationReport validate(final ValidationContext context, final JsonNode instance)
      throws JsonValidationFailureException {
    final ValidationReport report = context.createReport();

    final String ref = context.getSchema().get(keyword).getTextValue();

    final URI uri, baseURI;
    final JsonPointer pointer;

    try {
      uri = new URI(ref);
      baseURI = new URI(uri.getScheme(), uri.getSchemeSpecificPart(), null);
      pointer = new JsonPointer(uri.getRawFragment());
    } catch (URISyntaxException e) {
      throw new RuntimeException(
          "PROBLEM: invalid URI found (" + ref + "), syntax validation should have caught that", e);
    }

    final ValidationContext ctx;
    try {
      ctx = context.fromURI(baseURI);
    } catch (IOException e) {
      report.error(
          String.format(
              "cannot download schema at ref %s: %s: " + "%s",
              ref, e.getClass().getName(), e.getMessage()));
      return report;
    } catch (IllegalArgumentException e) {
      report.error(String.format("cannot use ref %s: %s", ref, e.getMessage()));
      return report;
    }

    return ctx.getValidator(pointer, instance).validate(ctx, instance);
  }
コード例 #7
0
  @Override
  public InputStream getHistoryGet(String parent, String basename, String rev) {
    InputStream ret = null;

    File directory = new File(directoryName);

    String filepath;
    try {
      filepath = (new File(parent, basename)).getCanonicalPath();
    } catch (IOException exp) {
      LOGGER.log(Level.SEVERE, "Failed to get canonical path: {0}", exp.getClass().toString());
      return null;
    }
    String filename = filepath.substring(directoryName.length() + 1);

    List<String> cmd = new ArrayList<>();
    ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
    cmd.add(RepoCommand);
    cmd.add("cat");
    cmd.add("-r");
    cmd.add(rev);
    cmd.add(escapeFileName(filename));

    Executor executor = new Executor(cmd, directory);
    if (executor.exec() == 0) {
      ret = executor.getOutputStream();
    }

    return ret;
  }
コード例 #8
0
  /**
   * Get an executor to be used for retrieving the history log for the named file.
   *
   * @param file The file to retrieve history for
   * @param sinceRevision the revision number immediately preceding the first revision we want, or
   *     {@code null} to fetch the entire history
   * @return An Executor ready to be started
   */
  Executor getHistoryLogExecutor(final File file, String sinceRevision) {
    String abs;
    try {
      abs = file.getCanonicalPath();
    } catch (IOException exp) {
      LOGGER.log(Level.SEVERE, "Failed to get canonical path: {0}", exp.getClass().toString());
      return null;
    }
    String filename = "";
    if (abs.length() > directoryName.length()) {
      filename = abs.substring(directoryName.length() + 1);
    }

    List<String> cmd = new ArrayList<>();
    ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
    cmd.add(RepoCommand);
    cmd.add("log");
    cmd.add("--non-interactive");
    cmd.addAll(getAuthCommandLineParams());
    cmd.add("--xml");
    cmd.add("-v");
    if (sinceRevision != null) {
      cmd.add("-r");
      // We would like to use sinceRevision+1 here, but if no new
      // revisions have been added after sinceRevision, it would fail
      // because there is no such revision as sinceRevision+1. Instead,
      // fetch the unneeded revision and remove it later.
      cmd.add("BASE:" + sinceRevision);
    }
    if (filename.length() > 0) {
      cmd.add(escapeFileName(filename));
    }

    return new Executor(cmd, new File(directoryName));
  }
コード例 #9
0
 /**
  * Parse a text file to create the name/value pairs.
  *
  * @param input Object containing input file
  */
 public void processInput(java.io.LineNumberReader input) {
   String lineContents = null;
   try {
     while (true) {
       String working = null;
       String name = null;
       String value = null;
       lineContents = input.readLine();
       if (lineContents == null) {
         break;
       }
       /* Process line */
       working = lineContents.trim();
       int pos = working.indexOf(":");
       if (pos <= 0) {
         continue;
       }
       if (pos == working.length() - 1) {
         continue;
       }
       name = working.substring(0, pos).trim();
       if (!caseSensitive) {
         name = name.toLowerCase();
       }
       value = working.substring(pos + 1).trim();
       internalList.add(new namePair(name, value));
     }
   } catch (java.io.IOException e) {
     System.out.println(
         "Error in processing input: " + e.getClass().getName() + " : " + e.getMessage());
     e.printStackTrace();
   }
 }
コード例 #10
0
ファイル: ExportLogicTest.java プロジェクト: bsvdev/bsv
  /** Set up a clean database before we do the testing on it. */
  @Before
  public void setup() {
    // create workding dir
    (new File(this.path)).mkdirs();

    // make sure the old file is deleted
    new File(this.dbFile).delete();
    arff.delete();
    csv.delete();

    try {
      this.database = new Database(this.dbFile);
      this.selCon = new SelectionController();
      this.subCon = new SubspaceController(database);
      this.grCon = new GroupController(database, subCon);
      this.daHub = new DataHub(database, grCon, subCon);
      arff.createNewFile();
      csv.createNewFile();
    } catch (IllegalArgumentException e) {
      Assert.fail("Database setup failed; path is invalid: " + e.getMessage());
    } catch (InvalidDriverException e) {
      Assert.fail("Database setup failed; SQL driver is invalid: " + e.getMessage());
    } catch (DatabaseAccessException e) {
      Assert.fail("Database setup failed; connection could not be created: " + e.getMessage());
    } catch (IncompatibleVersionException e) {
      Assert.fail("Database setup failed; connection could not be created: " + e.getMessage());
    } catch (IOException e) {
      Assert.fail(e.getClass().toString());
    }
  }
コード例 #11
0
 @Override
 protected void onPostExecute(String result) {
   super.onPostExecute(result);
   Log.d("XMLResult", result);
   try {
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
     InputStream xmlData = new ByteArrayInputStream(result.getBytes());
     Document xmlDoc = dBuilder.parse(xmlData);
     ;
     int redLevel = Integer.parseInt(xmlDoc.getElementsByTagName("r").item(0).getTextContent());
     int greenLevel = Integer.parseInt(xmlDoc.getElementsByTagName("g").item(0).getTextContent());
     int blueLevel = Integer.parseInt(xmlDoc.getElementsByTagName("b").item(0).getTextContent());
     int transition =
         Integer.parseInt(xmlDoc.getElementsByTagName("lastTransition").item(0).getTextContent());
     Integer time =
         Integer.parseInt(xmlDoc.getElementsByTagName("lastTime").item(0).getTextContent());
     uiMan.setRGB(redLevel, greenLevel, blueLevel);
     uiMan.setTime(time);
     uiMan.setTransition(transition);
   } catch (ParserConfigurationException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   } catch (SAXException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   } catch (IOException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   }
 }
コード例 #12
0
ファイル: SSLImpl.java プロジェクト: rhomobile/rhodes
  private static Certificate loadCertificate(File f) {
    X509Certificate cert = null;

    Logger.I(TAG, "Loading SSL certificate from PEM file: " + f.getAbsolutePath());

    try {

      byte[] fileBuf = fileToBytes(f);
      byte[] certBytes =
          parseDERFromPEM(fileBuf, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
      cert = generateCertificateFromDER(certBytes);

      Logger.I(TAG, "SSL certificate loaded successfully");

    } catch (IOException e) {
      Logger.E(
          TAG,
          "Reading certificate file failed: "
              + e.getClass().getSimpleName()
              + ": "
              + e.getMessage());
    } catch (CertificateException e) {
      Logger.E(
          TAG,
          "Certificate generation failed: " + e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    return cert;
  }
コード例 #13
0
  /**
   * Log IOExceptions.
   *
   * @param e The exception.
   * @return A description of the exception.
   */
  protected final String logIOException(IOException e) {

    final Class<? extends IOException> c = e.getClass();
    final String message = e.getMessage();
    final String description;

    if (e instanceof NoActivityTimeOutException) {
      description = "Listen time out";
    } else if (e instanceof ConnectException) {
      description = message;
    } else if (e instanceof UnknownHostException) {
      description = "Failed to connect to unknown host '" + message + "'";

    } else if (IOException.class.equals(c) && "Stream closed".equals(message)
        || e instanceof SocketException) {
      // Ignore common exceptions that are due to connections being
      // closed.
      return "";
    } else {
      e.printStackTrace(getLogger().getErrorLogWriter());
      return message;
    }

    getLogger().error(description);
    return description;
  }
コード例 #14
0
  public void processRender(UIStandaloneApplication uicomponent, WebuiRequestContext context)
      throws Exception {

    PortalRequestContext prc = (PortalRequestContext) context;
    OutputStream responseOutputStream = prc.getResponse().getOutputStream();

    PortalPrinter parentWriter = new PortalPrinter(responseOutputStream, true, 5000);
    PortalPrinter childWriter = new PortalPrinter(responseOutputStream, true, 25000, true);

    context.setWriter(childWriter);
    processRender(
        uicomponent,
        context,
        "system:/groovy/portal/webui/workspace/UIStandaloneApplicationChildren.gtmpl");

    context.setWriter(parentWriter);
    processRender(
        uicomponent,
        context,
        "system:/groovy/portal/webui/workspace/UIStandaloneApplication.gtmpl");

    try {
      // flush the parent writer to the output stream so that we are really to accept the child
      // content
      parentWriter.flushOutputStream();
      // now that the parent has been flushed, we can flush the contents of the child to the output
      childWriter.flushOutputStream();
    } catch (IOException ioe) {
      // We want to ignore the ClientAbortException since this is caused by the users
      // browser closing the connection and is not something we should be logging.
      if (!ioe.getClass().toString().contains("ClientAbortException")) {
        throw ioe;
      }
    }
  }
コード例 #15
0
  public void load() {
    JFileChooser jfilechooser = new JFileChooser();
    int returnOption = jfilechooser.showOpenDialog(jFrameMain);

    if (returnOption == JFileChooser.APPROVE_OPTION) {
      try {
        Equation equation = controllerIO.load(jfilechooser.getSelectedFile());
        controllerEquation.setEquation(equation);
        controllerEquation.solveEquation();
        changeView(PANEL.RESULT);
      } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(
            jFrameMain,
            "Didn't found \"Equation.class\".",
            e.getClass().getSimpleName(),
            JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
      } catch (IOException e) {
        JOptionPane.showMessageDialog(
            jFrameMain,
            "Error while loading file : " + jfilechooser.getSelectedFile().getAbsolutePath(),
            e.getClass().getSimpleName(),
            JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
      }
    }
  }
コード例 #16
0
  private void logIOException(NHttpServerConnection conn, IOException e) {
    // this check feels like crazy! But weird things happened, when load testing.
    if (e == null) {
      return;
    }
    if (e instanceof ConnectionClosedException
        || (e.getMessage() != null
            && (e.getMessage().toLowerCase().contains("connection reset by peer")
                || e.getMessage().toLowerCase().contains("forcibly closed")))) {
      if (log.isDebugEnabled()) {
        log.debug(
            conn
                + ": I/O error (Probably the keepalive connection "
                + "was closed):"
                + e.getMessage());
      }
    } else if (e.getMessage() != null) {
      String msg = e.getMessage().toLowerCase();
      if (msg.indexOf("broken") != -1) {
        log.warn(
            "I/O error (Probably the connection "
                + "was closed by the remote party):"
                + e.getMessage());
      } else {
        log.error("I/O error: " + e.getMessage(), e);
      }

      metrics.incrementFaultsReceiving();
    } else {
      log.error("Unexpected I/O error: " + e.getClass().getName(), e);

      metrics.incrementFaultsReceiving();
    }
  }
コード例 #17
0
 @Override
 public void draw(final GL2 gl, final RobotState rs, final Camera camera) {
   if (rs.getLastMessage() != null && rs.getLastMessage() instanceof BHumanMessage) {
     final BHumanMessage msg = (BHumanMessage) rs.getLastMessage();
     final Whistle whistle = msg.queue.getMessage(Whistle.class);
     if (whistle != null
         && whistle.confidenceOfLastWhistleDetection > 50
         && whistle.lastTimeWhistleDetected >= msg.queue.getTimestamp() - 200) {
       gl.glPushMatrix();
       gl.glTranslatef(msg.pose[0] / 1000.f, msg.pose[1] / 1000.f, 1);
       camera.turnTowardsCamera(gl);
       try {
         final File f = new File("plugins/05/resources/whistle.png").getAbsoluteFile();
         Image.drawImage(gl, TextureLoader.getInstance().loadTexture(gl, f), 0, 0, 0.2f);
       } catch (IOException ex) {
         JOptionPane.showMessageDialog(
             null,
             "Error loading texture: " + ex.getMessage(),
             ex.getClass().getSimpleName(),
             JOptionPane.ERROR_MESSAGE);
       }
       gl.glPopMatrix();
     }
   }
 }
コード例 #18
0
ファイル: UtilTest.java プロジェクト: Bhupendra2020/jenkins
 @Test
 public void deleteFile() throws Exception {
   Assume.assumeTrue(Functions.isWindows());
   Class<?> c;
   try {
     c = Class.forName("java.nio.file.FileSystemException");
   } catch (ClassNotFoundException x) {
     throw new AssumptionViolatedException("prior to JDK 7", x);
   }
   File d = Util.createTempDir();
   try {
     File f = new File(d, "f");
     OutputStream os = new FileOutputStream(f);
     try {
       Util.deleteFile(f);
       fail("should not have been deletable");
     } catch (IOException x) {
       assertEquals(c, x.getClass());
     } finally {
       os.close();
     }
   } finally {
     Util.deleteRecursive(d);
   }
 }
コード例 #19
0
ファイル: SGCConf.java プロジェクト: crisrc012/SGC
 private void btnGuardarActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnGuardarActionPerformed
   try (OutputStream output = new FileOutputStream("db.properties")) {
     prop.setProperty("Servidor", txtServidor.getText());
     prop.setProperty("Puerto", txtPuerto.getValue().toString());
     prop.setProperty("BD", txtBasedeDatos.getText());
     prop.setProperty("Usuario", txtUsuario.getText());
     String contrasena = "";
     for (char a : txtContrasena.getPassword()) {
       contrasena += a;
     }
     prop.setProperty("Clave", contrasena);
     prop.store(output, null);
     JOptionPane.showMessageDialog(
         this,
         "Configuración actualizada correctamente",
         "Correcto",
         JOptionPane.INFORMATION_MESSAGE);
     new Iniciar_Sesion().setVisible(true);
     dispose();
   } catch (FileNotFoundException e) {
     error();
     e.printStackTrace();
     System.err.println(e.getClass().getName() + ": " + e.getMessage());
     System.exit(0);
   } catch (IOException e) {
     error();
     e.printStackTrace();
     System.err.println(e.getClass().getName() + ": " + e.getMessage());
     System.exit(0);
   }
 } // GEN-LAST:event_btnGuardarActionPerformed
コード例 #20
0
ファイル: ScriptRunnable.java プロジェクト: greyp9/arwo
 @Override
 public final void run() {
   final Locus locus = context.getLocus();
   final Bundle bundle = context.getBundle();
   final Alerts alerts = context.getAlerts();
   final File file = context.getFile();
   final String href = context.getHref();
   try {
     logger.entering(getClass().getName(), Runnable.class.getName());
     script.start();
     runInner();
   } catch (IOException e) {
     alerts.add(new Alert(Alert.Severity.ERR, e.getMessage(), e.getClass().getSimpleName()));
   } finally {
     script.finish();
   }
   try {
     new ScriptWriter(script, locus).writeTo(file);
     new AlertWriter(bundle, alerts).write("command.finished", "results.view", href);
   } catch (IOException e) {
     alerts.add(new Alert(Alert.Severity.ERR, e.getMessage()));
   } finally {
     logger.exiting(getClass().getName(), Runnable.class.getName());
   }
 }
コード例 #21
0
ファイル: SearchFiles.java プロジェクト: rachely3n/info4300
  /** This function is only for test search. */
  public static List<String> searchQuery(
      String indexDir, String queryString, int numResults, CharArraySet stopwords) {
    String field = "contents";
    List<String> hitPaths = new ArrayList<String>();

    try {
      IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexDir)));
      IndexSearcher searcher = new IndexSearcher(reader);

      Analyzer analyzer = new MyAnalyzer(Version.LUCENE_44, stopwords);

      QueryParser parser = new QueryParser(Version.LUCENE_44, field, analyzer);
      Query query;
      query = parser.parse(QueryParser.escape(queryString));

      TopDocs results = searcher.search(query, null, numResults);
      for (ScoreDoc hit : results.scoreDocs) {
        String path = searcher.doc(hit.doc).get("path");
        hitPaths.add(path.substring(0, path.length() - 4)); // chop off the file extension (".txt")
      }
    } catch (IOException e) {
      System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
    } catch (ParseException e) {
      System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
    }

    return hitPaths;
  }
コード例 #22
0
  protected static ClientConfigSpec getClientConfig() {
    ClientConfigSpec clientConfig = null;

    String configFile = System.getProperty("configFile");

    Preconditions.checkArgument(
        configFile != null, "Please specify -DconfigFile as a startup parameter");

    LOG.debug("Using config file {}", configFile);

    try (FileInputStream jsonData = new FileInputStream(configFile)) {
      LOG.debug("Trying to load the configFile as json...");
      clientConfig = TDSClientConfig.read(jsonData);
    } catch (Exception e) {
      LOG.debug("Trying to load the configFile as nbt printed text...");
      try (FileInputStream inputStream = new FileInputStream(configFile)) {
        FullNbtModelConsumerImpl consumer = new FullNbtModelConsumerImpl();
        PrintedFileVisitor.getInstance().visit(consumer, inputStream);
        clientConfig = consumer.getCentralUnit();
      } catch (IOException e1) {
        LOG.error(
            "Exception ({}) caught in getClientConfig: {}",
            e1.getClass().getName(),
            e1.getMessage(),
            e1);
      }
    }

    Preconditions.checkState(
        clientConfig != null,
        "Could not determine the configuration. Make sure the clientConfig parameter refers to a valid json config file or a valid teletask nbt printed text file.");

    return clientConfig;
  }
コード例 #23
0
  /**
   * Does a HTTP/HTTPS HEADER request (currently used to check ex.fm links)
   *
   * @param urlString the complete url string to do the request with
   * @return a String containing the response of this request
   */
  public static boolean httpHeaderRequest(String urlString) {
    URLConnection urlConnection;
    HttpURLConnection connection = null;
    try {
      URL url = new URL(urlString);
      urlConnection = url.openConnection();
      if (urlConnection instanceof HttpURLConnection) {
        connection = (HttpURLConnection) urlConnection;
      } else {
        throw new MalformedURLException("Connection could not be cast to HttpUrlConnection");
      }

      connection.setConnectTimeout(15000);
      connection.setReadTimeout(15000);
      connection.setRequestMethod("HEAD");
      connection.setInstanceFollowRedirects(false);
      connection.setRequestProperty("Accept-Encoding", "");
      int responseCode = connection.getResponseCode();
      connection.disconnect();
      return responseCode == HttpURLConnection.HTTP_OK;
    } catch (IOException e) {
      Log.e(TAG, "httpHeaderRequest: " + e.getClass() + ": " + e.getLocalizedMessage());
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
    return false;
  }
コード例 #24
0
ファイル: JSONObject.java プロジェクト: jhorstmann/jjson
 public String toString(boolean pretty) {
   try {
     return JSONUtils.format(this, pretty);
   } catch (IOException ex) {
     throw new RuntimeException(
         ex.getClass().getSimpleName() + " in " + getClass().getSimpleName() + ".toString()", ex);
   }
 }
コード例 #25
0
ファイル: PublicKeyEntry.java プロジェクト: volth/mina-sshd
 /**
  * @param key The {@link PublicKey}
  * @return The {@code OpenSSH} encoded data
  * @throws IllegalArgumentException If failed to encode
  * @see #appendPublicKeyEntry(Appendable, PublicKey)
  */
 public static String toString(PublicKey key) throws IllegalArgumentException {
   try {
     return appendPublicKeyEntry(new StringBuilder(Byte.MAX_VALUE), key).toString();
   } catch (IOException e) {
     throw new IllegalArgumentException(
         "Failed (" + e.getClass().getSimpleName() + ") to encode: " + e.getMessage(), e);
   }
 }
コード例 #26
0
 /**
  * This implementation delegates to getResultInternal, passing in the LobHandler of this type.
  *
  * @see #getResultInternal
  */
 public final Object getResult(ResultSet rs, int columnIndex) throws SQLException {
   try {
     return getResultInternal(rs, columnIndex, this.lobHandler);
   } catch (IOException ex) {
     throw new SQLException(
         "I/O errors during LOB access: " + ex.getClass().getName() + ": " + ex.getMessage());
   }
 }
コード例 #27
0
 public Classifier(Message message) throws MessagingException {
   subject = message.getSubject();
   try {
     text = getRawText(message.getContent());
   } catch (IOException e) {
     throw (new MessagingException(
         "Unable to extract message body. [" + e.getClass().getName() + "] " + e.getMessage()));
   }
 }
コード例 #28
0
  /**
   * Loads configuration.
   *
   * @return configuration
   */
  public static ExperienceConfiguration load() {

    // Create config:
    if (!WriterReader.checkExists(Directory.EXPERIENCE_CONFIG)) {

      try {
        WriterReader.unpackConfig(Directory.EXPERIENCE_CONFIG);
      } catch (IOException e) {
        SagaLogger.severe(
            ExperienceConfiguration.class,
            "failed to create default configuration: " + e.getClass().getSimpleName());
      }
    }

    // Read config:
    ExperienceConfiguration config;
    try {

      config = WriterReader.readConfig(Directory.EXPERIENCE_CONFIG, ExperienceConfiguration.class);

    } catch (IOException e) {

      SagaLogger.severe(
          ExperienceConfiguration.class,
          "failed to read configuration: " + e.getClass().getSimpleName());
      config = new ExperienceConfiguration();

    } catch (JsonParseException e) {

      SagaLogger.severe(
          ExperienceConfiguration.class,
          "failed to parse configuration: " + e.getClass().getSimpleName());
      SagaLogger.info("message: " + e.getMessage());
      config = new ExperienceConfiguration();
    }

    // Set instance:
    instance = config;

    config.complete();

    return config;
  }
コード例 #29
0
  @Test
  public void testErrorHandling() throws Exception {
    final TexQueryGenerator t = new TexQueryGenerator();
    t.setLaTeXMLURL("http://example.com");
    assertEquals("http://example.com", t.getLaTeXMLURL());
    try {
      t.request("E=mc^2");
    } catch (final IOException expected) {
      assertEquals(
          "com.fasterxml.jackson.core.JsonParseException", expected.getClass().getCanonicalName());
    }

    t.setLaTeXMLURL("xxy://invalid");

    try {
      t.request("E=mc^2");
    } catch (final IOException expected) {
      assertEquals(
          "org.apache.http.client.ClientProtocolException", expected.getClass().getCanonicalName());
    }
  }
コード例 #30
0
 /** {@inheritDoc} */
 @Override
 public boolean remove(Object o) {
   try {
     return this.removeUnsynchronized(o);
   } catch (InterruptedException e) {
     throw new RuntimeException(e.getClass().getSimpleName() + " caught", e);
   } catch (KeeperException e) {
     throw new RuntimeException(e.getClass().getSimpleName() + " caught", e);
   } catch (IOException e) {
     throw new RuntimeException(e.getClass().getSimpleName() + " caught", e);
   }
 }