Beispiel #1
0
 public SVNErrorMessage readData(HTTPRequest request, OutputStream dst) throws IOException {
   InputStream stream = createInputStream(request.getResponseHeader(), getInputStream());
   byte[] buffer = getBuffer();
   boolean willCloseConnection = false;
   try {
     while (true) {
       int count = stream.read(buffer);
       if (count < 0) {
         break;
       }
       if (dst != null) {
         dst.write(buffer, 0, count);
       }
     }
   } catch (IOException e) {
     willCloseConnection = true;
     if (e instanceof IOExceptionWrapper) {
       IOExceptionWrapper wrappedException = (IOExceptionWrapper) e;
       return wrappedException.getOriginalException().getErrorMessage();
     }
     if (e.getCause() instanceof SVNException) {
       return ((SVNException) e.getCause()).getErrorMessage();
     }
     throw e;
   } finally {
     if (!willCloseConnection) {
       SVNFileUtil.closeFile(stream);
     }
     myRepository.getDebugLog().flushStream(stream);
   }
   return null;
 }
Beispiel #2
0
  @Test
  public void disconnectOldVersions1() throws Exception {
    // Set up the connection with an old version.
    final SettableFuture<Void> connectedFuture = SettableFuture.create();
    final SettableFuture<Void> disconnectedFuture = SettableFuture.create();
    peer.addEventListener(
        new AbstractPeerEventListener() {
          @Override
          public void onPeerConnected(Peer peer, int peerCount) {
            connectedFuture.set(null);
          }

          @Override
          public void onPeerDisconnected(Peer peer, int peerCount) {
            disconnectedFuture.set(null);
          }
        });
    connectWithVersion(500);
    // We must wait uninterruptibly here because connect[WithVersion] generates a peer that
    // interrupts the current
    // thread when it disconnects.
    Uninterruptibles.getUninterruptibly(connectedFuture);
    Uninterruptibles.getUninterruptibly(disconnectedFuture);
    try {
      peer.writeTarget.writeBytes(new byte[1]);
      fail();
    } catch (IOException e) {
      assertTrue(
          (e.getCause() != null && e.getCause() instanceof CancelledKeyException)
              || (e instanceof SocketException && e.getMessage().equals("Socket is closed")));
    }
  }
Beispiel #3
0
  @Override
  public void close() throws InterruptedException, BuildFileParseException {
    stdout.close();
    stderr.close();

    BuildFileParseException lastSeen = null;
    try {
      closer.close();
    } catch (IOException e) {
      if (e.getCause() instanceof BuildFileParseException) {
        lastSeen = (BuildFileParseException) e.getCause();
      }
      if (e.getCause() instanceof InterruptedException) {
        throw (InterruptedException) e.getCause();
      }
      Throwables.propagate(e);
    }

    LOG.debug(
        "Cleaning cache of build files with inputs under symlink %s", buildInputPathsUnderSymlink);
    Set<Path> buildInputPathsUnderSymlinkCopy = new HashSet<>(buildInputPathsUnderSymlink);
    buildInputPathsUnderSymlink.clear();
    for (Path buildFilePath : buildInputPathsUnderSymlinkCopy) {
      permState.invalidatePath(buildFilePath);
    }

    if (lastSeen != null) {
      throw lastSeen;
    }
  }
Beispiel #4
0
  @Test
  public void testTestCompression() {

    // This test will fail if you run the tests with LZO compression available.
    try {
      CompressionTest.testCompression(Compression.Algorithm.LZO);
      fail(); // always throws
    } catch (IOException e) {
      // there should be a 'cause'.
      assertNotNull(e.getCause());
    }

    // this is testing the caching of the test results.
    try {
      CompressionTest.testCompression(Compression.Algorithm.LZO);
      fail(); // always throws
    } catch (IOException e) {
      // there should be NO cause because it's a direct exception not wrapped
      assertNull(e.getCause());
    }

    assertFalse(CompressionTest.testCompression("LZO"));
    assertTrue(CompressionTest.testCompression("NONE"));
    assertTrue(CompressionTest.testCompression("GZ"));

    if (isCompressionAvailable("org.apache.hadoop.io.compress.SnappyCodec")) {
      assertTrue(CompressionTest.testCompression("SNAPPY"));
    } else {
      assertFalse(CompressionTest.testCompression("SNAPPY"));
    }
  }
Beispiel #5
0
 private APIResponse post_single(String urlString, String postBodyString) {
   if (!NetworkUtils.isOnline(context)) {
     return new APIResponse(context);
   }
   try {
     URL url = new URL(urlString);
     if (AppConstants.VERBOSE_LOG) {
       Log.d(this.getClass().getName(), "API POST " + url);
       Log.d(this.getClass().getName(), "post body: " + postBodyString);
     }
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     connection.setDoOutput(true);
     connection.setRequestMethod("POST");
     connection.setFixedLengthStreamingMode(postBodyString.getBytes().length);
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     SharedPreferences preferences = context.getSharedPreferences(PrefConstants.PREFERENCES, 0);
     String cookie = preferences.getString(PrefConstants.PREF_COOKIE, null);
     if (cookie != null) {
       connection.setRequestProperty("Cookie", cookie);
     }
     PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
     printWriter.print(postBodyString);
     printWriter.close();
     return new APIResponse(context, url, connection);
   } catch (IOException e) {
     Log.e(
         this.getClass().getName(),
         "Error opening POST connection to " + urlString + ": " + e.getCause(),
         e.getCause());
     return new APIResponse(context);
   }
 }
  public static ImmutableSet<ProvisioningProfileMetadata> findProfilesInPath(Path searchPath)
      throws InterruptedException {
    final ImmutableSet.Builder<ProvisioningProfileMetadata> profilesBuilder =
        ImmutableSet.builder();
    try {
      Files.walkFileTree(
          searchPath.toAbsolutePath(),
          new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
              if (file.toString().endsWith(".mobileprovision")) {
                try {
                  ProvisioningProfileMetadata profile =
                      ProvisioningProfileMetadata.fromProvisioningProfilePath(file);
                  profilesBuilder.add(profile);
                } catch (IOException | IllegalArgumentException e) {
                  LOG.error(e, "Ignoring invalid or malformed .mobileprovision file");
                } catch (InterruptedException e) {
                  throw new IOException(e);
                }
              }

              return FileVisitResult.CONTINUE;
            }
          });
    } catch (IOException e) {
      if (e.getCause() instanceof InterruptedException) {
        throw ((InterruptedException) e.getCause());
      }
      LOG.error(e, "Error while searching for mobileprovision files");
    }

    return profilesBuilder.build();
  }
  protected DocumentModel doCreateLeafNode(DocumentModel parent, SourceNode node)
      throws IOException {
    if (!shouldImportDocument(node)) {
      return null;
    }
    Stopwatch stopwatch = SimonManager.getStopwatch("org.nuxeo.ecm.platform.importer.create_leaf");
    Split split = stopwatch.start();
    DocumentModel leaf = null;
    try {
      leaf = getFactory().createLeafNode(session, parent, node);
    } catch (IOException e) {
      String errMsg =
          "Unable to create leaf document for "
              + node.getSourcePath()
              + ":"
              + e
              + (e.getCause() != null ? e.getCause() : "");
      fslog(errMsg, true);
      log.error(errMsg);
      // Process leaf node creation error and check if the global
      // import task should continue
      boolean shouldImportTaskContinue =
          getFactory().processLeafNodeCreationError(session, parent, node);
      if (!shouldImportTaskContinue) {
        throw new NuxeoException(e);
      }
    } finally {
      split.stop();
    }
    BlobHolder bh = node.getBlobHolder();
    if (leaf != null && bh != null) {
      Blob blob = bh.getBlob();
      if (blob != null) {
        long fileSize = blob.getLength();
        String fileName = blob.getFilename();
        if (fileSize > 0) {
          long kbSize = fileSize / 1024;
          String parentPath = (parent == null) ? "null" : parent.getPathAsString();
          fslog(
              "Created doc "
                  + leaf.getName()
                  + " at "
                  + parentPath
                  + " with file "
                  + fileName
                  + " of size "
                  + kbSize
                  + "KB",
              true);
        }
        uploadedKO += fileSize;
      }

      // save session if needed
      commit();
    }
    return leaf;
  }
Beispiel #8
0
 public Document parse(
     final MultiProtocolURI location,
     final String mimeType,
     final String charset,
     final IInStream source)
     throws Parser.Failure, InterruptedException {
   final Document doc =
       new Document(
           location,
           mimeType,
           charset,
           this,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           0.0f,
           0.0f,
           (Object) null,
           null,
           null,
           null,
           false);
   Handler archive;
   super.log.logFine("opening 7zip archive...");
   try {
     archive = new Handler(source);
   } catch (final IOException e) {
     throw new Parser.Failure("error opening 7zip archive: " + e.getMessage(), location);
   }
   final SZParserExtractCallback aec =
       new SZParserExtractCallback(super.log, archive, doc, location.getFile());
   super.log.logFine("processing archive contents...");
   try {
     archive.Extract(null, -1, 0, aec);
     return doc;
   } catch (final IOException e) {
     if (e.getCause() instanceof InterruptedException) throw (InterruptedException) e.getCause();
     if (e.getCause() instanceof Parser.Failure) throw (Parser.Failure) e.getCause();
     throw new Parser.Failure(
         "error processing 7zip archive at internal file "
             + aec.getCurrentFilePath()
             + ": "
             + e.getMessage(),
         location);
   } finally {
     try {
       archive.close();
     } catch (final IOException e) {
     }
   }
 }
  private List<KeyStore> initSingle(final InputStream store, final PasswordCallback pssCallBack)
      throws AOKeyStoreManagerException, IOException {
    if (store == null) {
      throw new AOKeyStoreManagerException(
          "Es necesario proporcionar el fichero X.509 o PKCS#7"); //$NON-NLS-1$
    }

    final Provider pkcs7Provider;
    try {
      pkcs7Provider =
          (Provider)
              Class.forName("es.gob.afirma.keystores.single.SingleCertKeyStoreProvider")
                  .newInstance(); //$NON-NLS-1$
    } catch (final Exception e) {
      throw new MissingLibraryException(
          "No se ha podido instanciar el proveedor SingleCertKeyStoreProvider: " + e,
          e); //$NON-NLS-1$
    }
    Security.addProvider(pkcs7Provider);

    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName(), pkcs7Provider);
    } catch (final Exception e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#7 / X.509", e); // $NON-NLS-1$
    }

    try {
      this.ks.load(store, pssCallBack != null ? pssCallBack.getPassword() : null);
    } catch (final IOException e) {
      if (e.getCause() instanceof UnrecoverableKeyException
          || e.getCause() instanceof BadPaddingException) {
        throw new IOException("Contrasena invalida: " + e, e); // $NON-NLS-1$
      }
      throw new AOKeyStoreManagerException(
          "No se ha podido abrir el almacen PKCS#7 / X.509 solicitado", e); // $NON-NLS-1$
    } catch (final CertificateException e) {
      throw new AOKeyStoreManagerException(
          "No se han podido cargar los certificados del almacen PKCS#7 / X.509 solicitado",
          e); //$NON-NLS-1$
    } catch (final NoSuchAlgorithmException e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido verificar la integridad del almacen PKCS#7 / X.509 solicitado",
          e); //$NON-NLS-1$
    }
    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    try {
      store.close();
    } catch (final Exception e) {
      // Ignoramos errores en el cierre
    }
    return ret;
  }
Beispiel #10
0
  /**
   * This method actually launches 'gdb --vesion' to determine the version of the GDB that is being
   * used. This method should ideally be called only once and the resulting version string stored
   * for future uses.
   */
  public static String getGDBVersion(final ILaunchConfiguration configuration)
      throws CoreException {
    Process process = null;
    String cmd = getGDBPath(configuration).toOSString() + " --version"; // $NON-NLS-1$
    try {
      process = ProcessFactory.getFactory().exec(cmd, getLaunchEnvironment(configuration));
    } catch (IOException e) {
      throw new DebugException(
          new Status(
              IStatus.ERROR,
              GdbPlugin.PLUGIN_ID,
              DebugException.REQUEST_FAILED,
              "Error while launching command: " + cmd,
              e.getCause())); // $NON-NLS-1$
    }

    InputStream stream = null;
    StringBuilder cmdOutput = new StringBuilder(200);
    try {
      stream = process.getInputStream();
      Reader r = new InputStreamReader(stream);
      BufferedReader reader = new BufferedReader(r);

      String line;
      while ((line = reader.readLine()) != null) {
        cmdOutput.append(line);
      }
    } catch (IOException e) {
      throw new DebugException(
          new Status(
              IStatus.ERROR,
              GdbPlugin.PLUGIN_ID,
              DebugException.REQUEST_FAILED,
              "Error reading GDB STDOUT after sending: " + cmd,
              e.getCause())); // $NON-NLS-1$
    } finally {
      // Cleanup to avoid leaking pipes
      // Close the stream we used, and then destroy the process
      // Bug 345164
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e) {
        }
      }
      process.destroy();
    }

    return getGDBVersionFromText(cmdOutput.toString());
  }
Beispiel #11
0
  public void processArgs(String[] args) {
    UOption.parseArgs(args, options);
    if (options[HELP1].doesOccur || options[HELP2].doesOccur) {
      System.out.println(HELP_TEXT1);
      return;
    }

    String sourceDir = options[SOURCEDIR].value; // Utility.COMMON_DIRECTORY + "transforms/";
    String targetDir = options[DESTDIR].value; // Utility.GEN_DIRECTORY + "main/";
    String match = options[MATCH].value;
    skipComments = options[SKIP_COMMENTS].doesOccur;
    writeIndex = options[WRITE_INDEX].doesOccur;
    verbose = options[VERBOSE].doesOccur;

    try {
      if (writeIndex) {
        throw new InternalError("writeIndex not implemented.");
      } else {
        ElapsedTimer et = new ElapsedTimer();
        writeTransforms(sourceDir, match, targetDir + File.separator);
        System.out.println("ConvertTransforms: wrote " + fileCount + " files in " + et);
      }
    } catch (IOException ex) {
      RuntimeException e = new RuntimeException();
      e.initCause(ex.getCause());
      throw e;
    } finally {
      System.out.println("DONE");
    }
  }
  /**
   * Constructor. Initializes the ComboPooledDataSource based on the config.properties.
   *
   * @throws PropertyVetoException
   */
  public DatabaseMultiTenantConnectionProvider() throws PropertyVetoException {
    logger.info("Initializing Connection Pool!");

    if (tenants == null) tenants = new ArrayList<String>();
    tenants.add(CurrentTenantResolver.DEFAULT_TENANT_ID);
    Resource resource = new ClassPathResource("/application.properties");
    try {
      props = PropertiesLoaderUtils.loadProperties(resource);
      String t = ConfigurationHelper.getString("tenants", props);

      if (t != null) {
        for (String tenant : t.split(",")) {
          tenants.add(tenant);
        }
      }

    } catch (IOException e) {
      logger.error(e.getCause() + ":" + e.getMessage());
    }

    for (String tenant : tenants) {
      connProviderMap.put(tenant, initPoolConnection(tenant));
    }

    logger.info("Connection Pool initialised!");
  }
Beispiel #13
0
 private byte[] serialize() {
   byte[] result = null;
   ByteArrayOutputStream bos = new ByteArrayOutputStream(150000);
   try {
     //			GZIPOutputStream zos = new GZIPOutputStream(bos);
     ZipOutputStream zos = new ZipOutputStream(bos);
     // zos.setLevel(4);
     zos.putNextEntry(new ZipEntry("Object"));
     ObjectOutputStream oos = new ObjectOutputStream(zos);
     //			oos.writeInt(1);
     oos.writeObject(this);
     oos.flush();
     oos.reset();
     zos.closeEntry();
     zos.flush();
     result = bos.toByteArray();
     bos.reset();
     bos.close();
     zos.close();
     oos.close();
   } catch (IOException e) {
     log.severe("Failed to serialize MemoStorable: " + e.getMessage());
     log.severe(e.getCause().getMessage());
   }
   return result;
 }
 private void cleanup() {
   if (writer != null) {
     try {
       writer.close();
     } catch (IOException ex) {
       System.err.println(ex.getCause());
     }
   }
   if (logWriter != null) {
     try {
       logWriter.close();
     } catch (IOException ex) {
       System.err.println(ex.getCause());
     }
   }
 }
Beispiel #15
0
  @Override
  public void performOperation() throws OperationFailedException {
    if (verbose) {
      System.out.println("TestOperator is performing operation");
    }

    inputFile = inputBuffers.get(0).getFile();

    try {
      BufferedReader reader = new BufferedReader(new FileReader(inputFile));
      FileBuffer output = outputBuffers.get(0);

      String line = reader.readLine();

      BufferedWriter writer = new BufferedWriter(new FileWriter(output.getFile()));
      writer.write("Top of the new output buffer!\n");

      int count = 0;
      while (line != null) {
        System.out.println("Read this line from input file : " + line);
        writer.write(count + "\t " + line + "\n");
        count++;
        line = reader.readLine();
      }

      reader.close();
      writer.close();
    } catch (FileNotFoundException e) {
      throw new OperationFailedException(e.getCause() + "\t" + e.getMessage(), this);
    } catch (IOException e) {
      throw new OperationFailedException(e.getCause() + "\t" + e.getMessage(), this);
    }
  }
Beispiel #16
0
 /**
  * 写入文件
  *
  * @param filePathAndName 带有完整绝对路径的文件名
  * @param encoding 文本文件打开的编码方式
  * @param text writer text
  * @return true/false
  */
 public static boolean writeFile(String filePathAndName, String encoding, String text)
     throws RuntimeException {
   boolean a = false;
   encoding = encoding.trim();
   OutputStreamWriter writer = null;
   try {
     if (encoding.equals("")) {
       writer = new OutputStreamWriter(new FileOutputStream(filePathAndName));
     } else {
       writer = new OutputStreamWriter(new FileOutputStream(filePathAndName), encoding);
     }
     writer.write(text);
     writer.close();
     a = true;
   } catch (Exception e) {
     throw new RuntimeException(e.getMessage(), e.getCause());
   } finally {
     if (writer != null) {
       try {
         writer.close();
       } catch (IOException e) {
         throw new RuntimeException(e.getMessage(), e.getCause());
       }
     }
   }
   return a;
 }
  private FileWriter handleLoadCastor(FileWriter writer, RulesPostImportContainer rpic) {

    try {
      // Create Mapping
      Mapping mapping = new Mapping();
      mapping.loadMapping(SpringServletAccess.getPropertiesDir(context) + "mappingMarshaller.xml");
      // Create XMLContext
      XMLContext xmlContext = new XMLContext();
      xmlContext.addMapping(mapping);

      Marshaller marshaller = xmlContext.createMarshaller();
      marshaller.setWriter(writer);
      marshaller.marshal(rpic);
      return writer;

    } catch (FileNotFoundException ex) {
      throw new OpenClinicaSystemException(ex.getMessage(), ex.getCause());
    } catch (IOException ex) {
      throw new OpenClinicaSystemException(ex.getMessage(), ex.getCause());
    } catch (MarshalException e) {
      throw new OpenClinicaSystemException(e.getMessage(), e.getCause());
    } catch (ValidationException e) {
      throw new OpenClinicaSystemException(e.getMessage(), e.getCause());
    } catch (MappingException e) {
      throw new OpenClinicaSystemException(e.getMessage(), e.getCause());
    } catch (Exception e) {
      throw new OpenClinicaSystemException(e.getMessage(), e.getCause());
    }
  }
    @Override
    public void run() {
      Log.i(TAG, "BEGIN mConnectedThread");
      byte[] buffer = new byte[1024];
      int bytes;

      // Keep listening to the InputStream while connected
      while (true) {
        try {
          // Read from the InputStream
          bytes = mmInStream.read(buffer);

          // Send the obtained bytes to the UI Activity
          mHandler
              .obtainMessage(BlueMSP430Service.MESSAGE_READ, btDeviceID, bytes, buffer.clone())
              .sendToTarget();
        } catch (IOException e) {
          if (e.getCause() != null) {
            Log.e(TAG, "disconnected", e);
            // connectionLost();
          }
          Log.e(TAG, "disconnected");
          setState(STATE_NONE);
          connectionLost();
          break;
        }
      }
    }
 /**
  * Get the cause of an I/O exception if caused by a possible disk error
  *
  * @param ioe an I/O exception
  * @return cause if the I/O exception is caused by a possible disk error; null otherwise.
  */
 static IOException getCauseIfDiskError(IOException ioe) {
   if (ioe.getMessage() != null && ioe.getMessage().startsWith(DISK_ERROR)) {
     return (IOException) ioe.getCause();
   } else {
     return null;
   }
 }
Beispiel #20
0
  @Override
  public void saveAllTasks(Collection<Task> tasks) {

    try {
      doc = new Document(new Element("tasks"), new DocType("tasks", "XmlDTD.dtd"));

      Iterator it = tasks.iterator();
      while (it.hasNext()) {
        Task task = (Task) it.next();
        doc.getRootElement()
            .addContent(
                new Element("task")
                    .setAttribute("id", task.getId())
                    .addContent(new Element("name").addContent(task.getName()))
                    .addContent(new Element("description").addContent(task.getDescription()))
                    .addContent(new Element("date").addContent(sdf.format(task.getDate()))));
      }

      XMLOutputter outPutter =
          new XMLOutputter(Format.getRawFormat().setIndent(" ").setLineSeparator("\n"));

      outPutter.output(doc, new FileWriter(config.getFileName()));

    } catch (IOException ex) {
      log.error(null, ex);
      throw new WritingFileException("Didn't write xml", ex.getCause());
    }
  }
Beispiel #21
0
 @Override
 public Ref getRef(final String needle) throws IOException {
   final RefList<Ref> packed = getPackedRefs();
   Ref ref = null;
   for (String prefix : SEARCH_PATH) {
     try {
       ref = readRef(prefix + needle, packed);
       if (ref != null) {
         ref = resolve(ref, 0, null, null, packed);
       }
       if (ref != null) {
         break;
       }
     } catch (IOException e) {
       if (!(!needle.contains("/")
           && "".equals(prefix)
           && e //$NON-NLS-1$ //$NON-NLS-2$
                   .getCause()
               instanceof InvalidObjectIdException)) {
         throw e;
       }
     }
   }
   fireRefsChanged();
   return ref;
 }
Beispiel #22
0
 /**
  * Convert a file to the EPackage containing a metamodel.
  *
  * @param iFile The file that is to be converted to the Epackage.
  * @return The EPackage containing the metamodel loaded from the file.
  * @throws CodeGenerationException
  */
 protected EPackage fileToEPack(IFile iFile) throws CodeGenerationException {
   ResourceSet resSet = new ResourceSetImpl();
   resSet.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap());
   URI fileURI =
       URI.createPlatformResourceURI(
           "/" + iFile.getProject().getName() + "/" + iFile.getProjectRelativePath().toString(),
           true);
   Resource resource = resSet.createResource(fileURI);
   Map<Object, Object> options = new HashMap<Object, Object>();
   options.put(XMLResource.OPTION_ENCODING, "UTF-8");
   try {
     resource.load(options);
   } catch (IOException e) {
     throw new CodeGenerationException(
         "Error while loading resource of File: " + iFile.getName(), e.getCause());
   }
   EList<EObject> sd = resource.getContents();
   for (EObject object : sd) {
     if (object instanceof EPackage) {
       EPackage ePack = (EPackage) object;
       pi.setNsURI(ePack.getNsURI());
       return ePack;
     }
   }
   return null;
 }
  public boolean xpathEvent(EmbeddedBrowser browser, StateVertex vertex, String path, EventType t) {
    log.debug("xpathEvent(EmbeddedBrowser browser, StateVertex vertex, String path, EventType t)");
    log.debug("path: " + path);
    Document doc = null;
    try {
      doc = vertex.getDocument();
    } catch (IOException e) {
      log.debug("exception");
      log.debug(e.getMessage());
      log.debug(e.getCause().toString());
      return false;
    }
    assert (doc != null);
    if (xpathQuery(doc, path)) {
      Identification id = new Identification();
      id.setHow(How.xpath);
      id.setValue(path);
      Eventable ev = new Eventable();
      ev.setEventType(t);
      ev.setIdentification(id);

      return fireEvent(ev, browser);
    }
    return false;
  }
Beispiel #24
0
 /**
  * @param base64
  * @return
  */
 public static byte[] decode(String base64) {
   BASE64Decoder decoder = new BASE64Decoder();
   try {
     return decoder.decodeBuffer(base64);
   } catch (IOException io) {
     throw new RuntimeException(io.getMessage(), io.getCause());
   }
 }
Beispiel #25
0
  /**
   * Open connection with device. Connection is opened automatically when object is created but can
   * be closed by user
   *
   * @throws CardReaderException
   * @see pl.edu.pw.mini.x1.janiszewskit.SwipeCardReader.Reader.Device#close()
   */
  public void open() throws CardReaderException {

    try {
      device = manager.openById(vendor, id, null);
    } catch (IOException e) {
      throw new CardReaderException("Cannot open device", e.getCause());
    }
  }
 /** Execute this Controller. */
 public void run() {
   try {
     start();
   } catch (IOException e) {
     notifyException(e);
     throw new RuntimeException(e.getCause());
   }
 }
 /**
  * Decode a string using Base64 encoding.
  *
  * @param str
  * @return String
  */
 public static String decodeString(String str) {
   sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
   try {
     return new String(dec.decodeBuffer(str));
   } catch (IOException io) {
     throw new RuntimeException(io.getMessage(), io.getCause());
   }
 }
Beispiel #28
0
  /**
   * Close connection with device. Before next read attempt connection should be resotred using
   * <code>open</code>
   *
   * @throws CardReaderException
   * @see pl.edu.pw.mini.x1.janiszewskit.SwipeCardReader.Reader.Device#open()
   */
  public void close() throws CardReaderException {

    try {
      device.close();
    } catch (IOException e) {
      throw new CardReaderException("Cannot close device", e.getCause());
    }
  }
Beispiel #29
0
 public String getBetterExceptionMessage(IOException x, String root) {
   if (x instanceof SardineException) {
     // hide this from callers because its getMessage() is borked
     SardineException sx = (SardineException) x;
     if (sx.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN) {
       return "authentication failed on repository " + root;
     }
     return sx.getMessage() + ": " + sx.getResponsePhrase() + " " + sx.getStatusCode();
   }
   if (x instanceof ClientProtocolException) {
     // in case of protocol exception (invalid response) we get this sort of
     // chain set up with a null message, so unwrap it for better messages
     if (x.getCause() != null && x.getCause() instanceof ProtocolException)
       return x.getCause().getMessage();
   }
   return null;
 }
 private boolean isRecoverable(IOException e) {
   // If the problem was a CertificateException from the X509TrustManager,
   // do not retry, we didn't have an abrupt server initiated exception.
   boolean sslFailure =
       e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
   boolean protocolFailure = e instanceof ProtocolException;
   return !sslFailure && !protocolFailure;
 }