@Override
  public void initialize(UimaContext c) throws ResourceInitializationException {
    super.initialize(c);

    try {
      nerModelFile =
          new File(
              new URI(
                  AustinMaKeytermExtractor.class
                      .getResource("/ne-en-bio-genetag.HmmChunker")
                      .toString()));
      chunker = (Chunker) AbstractExternalizable.readObject(nerModelFile);
    } catch (IOException e) {
      System.err.println("IOException in creating chunker");
      throw new ResourceInitializationException(
          "Unable to load NER model file", "load_ner_model_error", new Object[] {nerModelFile}, e);
    } catch (ClassNotFoundException e) {
      System.err.println("ClassNotFoundException in creating chunker");
      throw new ResourceInitializationException(
          "Unable to load NER model file", "load_ner_model_error", new Object[] {nerModelFile}, e);
    } catch (URISyntaxException e) {
      e.printStackTrace();
      throw new ResourceInitializationException(
          "Unable to load NER model file", "load_ner_model_error", new Object[] {nerModelFile}, e);
    }

    // Read in the geneDictionary
    geneDictionary = new HashSet<String>();
    try {
      File geneDictionaryFile =
          new File(new URI(AustinMaKeytermExtractor.class.getResource("/ref.dic").toString()));
      BufferedReader reader = new BufferedReader(new FileReader(geneDictionaryFile));
      String line;
      try {
        while ((line = reader.readLine()) != null) geneDictionary.add(line);
      } catch (IOException e) {
        System.err.println("IOException in reading gene dictionary file");
        throw new ResourceInitializationException(
            "Unable to load gene dictionary file", "load_gene_dic_error", new Object[] {}, e);
      }
    } catch (FileNotFoundException e) {
      System.err.println("FileNotFoundException in reading gene dictionary file");
      throw new ResourceInitializationException(
          "Unable to find gene dictionary file", "load_gene_dic_error", new Object[] {}, e);
    } catch (URISyntaxException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
      throw new ResourceInitializationException(
          "Unable to find gene dictionary file", "load_gene_dic_error", new Object[] {}, e1);
    }
  }
  public static void main(String args[]) {
    if (args.length <= 3) {
      System.err.println("LFC_Host Port TestDirPath num|clean (debug)");
      return;
    }
    String host = args[0];
    String port = args[1];
    String path = args[2];
    String num = null;
    if (args.length >= 4) {
      num = args[3];
    }
    String debug = null;
    if (args.length >= 5) {
      debug = args[4];
    }

    LFCServer lfcServer;
    try {
      if (debug != null) {
        LFCServer.getLogger().printLog = true;
        LFCServer.getLogger().printIOLog = true;
      }

      lfcServer = new LFCServer(new URI("lfn://" + host + ":" + port + "/"));
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return;
    }

    if (num != null && num.equals("clean")) {
      clearAll(lfcServer, path);
    } else if (num != null) {
      int n = Integer.parseInt(num);
      try {
        // NOTE: mkdir() cannot work.
        //				lfcServer.mkdir(path);
        for (int i = 0; i < n; i++) {
          //					String dirName = randomString();
          //					lfcServer.mkdir(path + "/" + dirName);
          //					test(lfcServer, path + "/" + dirName + "/" + randomString());
          test(lfcServer, path + "/" + randomString());
        }
      } catch (LFCException e) {
        e.printStackTrace();
      } catch (URISyntaxException e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 3
0
 private static PrintWriter getPrintWriter(String saveLocation, String fileName) {
   CodeSource codeSource = GrepolisBot.class.getProtectionDomain().getCodeSource();
   File jarFile = null;
   try {
     jarFile = new File(codeSource.getLocation().toURI().getPath());
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   String jarDir;
   if (jarFile != null) {
     jarDir = jarFile.getParentFile().getPath();
     File directory = new File(jarDir + File.separator + saveLocation + File.separator);
     // System.out.println("Directory: " + jarDir + File.separator + saveLocation +
     // File.separator);
     if (!directory.exists()) {
       directory.mkdirs();
     }
     try {
       return new PrintWriter(jarDir + File.separator + saveLocation + File.separator + fileName);
     } catch (FileNotFoundException e) {
       System.out.println("Error saving " + fileName);
       return null;
     }
   }
   return null;
 }
Exemplo n.º 4
0
  /*
   * (non-Javadoc)
   *
   * @see
   * net.xeoh.plugins.base.impl.classpath.locator.AbstractClassPathLocation
   * #getInputStream(java.lang.String)
   */
  @Override
  public InputStream getInputStream(String file) {

    try {
      final JarURLConnection connection =
          (JarURLConnection) new URI("jar:" + this.location + "!/").toURL().openConnection();
      final JarFile jarFile = connection.getJarFile();

      final Enumeration<JarEntry> entries = jarFile.entries();

      while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();

        // We only search for class file entries
        if (entry.isDirectory()) continue;

        String name = entry.getName();

        if (name.equals(file)) return jarFile.getInputStream(entry);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    return null;
  }
Exemplo n.º 5
0
 public void execute() {
   logger.debug("IN SET STATMENT");
   logger.debug("Sensor Id is " + sensorID);
   // SensorValueCache.setValue(sensorID, aValue);
   if (sensorID.contains("wildcard") && !sensorID.contains("room")) {
     logger.info("It is a wildcard" + " - sensor id is " + sensorID);
     try {
       List<String> sensors = new Wildcards().getSensorListByWildcard(sensorID);
       String[] data = sensorID.split("-");
       for (String s : sensors) {
         System.out.println("SET STATEMNET - " + s);
         new Connection().setSensorValue(s + "-" + data[data.length - 1], aValue.getIntValue());
       }
     } catch (MalformedURLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (URISyntaxException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   } else {
     try {
       new Connection().setSensorValue(sensorID, aValue.getIntValue());
     } catch (Exception e) {
       logger.error(e);
     }
   }
 }
 private void checkHelpSetURL(
     URL hsURL,
     ClassLoader globalClassLoader,
     ClassLoader moduleClassLoader,
     Map<String, URLClassLoader> classLoaderMap,
     String cnb) {
   HelpSet hs = null;
   try {
     hs = new HelpSet(moduleClassLoader, hsURL);
   } catch (HelpSetException ex) {
     throw new BuildException("Failed to parse " + hsURL + ": " + ex, ex, getLocation());
   }
   javax.help.Map map = hs.getCombinedMap();
   Enumeration<?> e = map.getAllIDs();
   Set<URI> okurls = new HashSet<URI>(1000);
   Set<URI> badurls = new HashSet<URI>(1000);
   Set<URI> cleanurls = new HashSet<URI>(1000);
   while (e.hasMoreElements()) {
     javax.help.Map.ID id = (javax.help.Map.ID) e.nextElement();
     URL u = null;
     try {
       u = id.getURL();
     } catch (MalformedURLException ex) {
       log("id:" + id, Project.MSG_WARN);
       ex.printStackTrace();
     }
     if (u == null) {
       throw new BuildException("Bogus map ID: " + id.id + " in: " + cnb);
     }
     log("Checking ID " + id.id, Project.MSG_VERBOSE);
     try {
       // System.out.println("CALL OF CheckLinks.scan");
       List<String> errors = new ArrayList<String>();
       CheckLinks.scan(
           this,
           globalClassLoader,
           classLoaderMap,
           id.id,
           "",
           new URI(u.toExternalForm()),
           okurls,
           badurls,
           cleanurls,
           false,
           false,
           false,
           2,
           Collections.<Mapper>emptyList(),
           errors);
       for (String error : errors) {
         log(error, Project.MSG_WARN);
       }
       // System.out.println("RETURN OF CheckLinks.scan");
     } catch (URISyntaxException ex) {
       ex.printStackTrace();
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
 }
 private void showUserDialog() {
   JOptionPane.showConfirmDialog(
       null,
       new Object[] {
         this.error,
         "User:"******"Pwd:",
         passwordField,
         "Hostname:",
         hostNameField,
         "Auth URL",
         authURLField,
         "Rootservices",
         rootservicesURLField
       },
       "Specify Connection Details",
       JOptionPane.OK_CANCEL_OPTION);
   this.userName = userNameField.getText();
   this.password = passwordField.getPassword();
   this.hostname = hostNameField.getText();
   this.rootservicesURL = rootservicesURLField.getText();
   try {
     this.jazzAuthUrl = new URI(authURLField.getText());
   } catch (URISyntaxException e) {
     this.error = e.getMessage();
     e.printStackTrace();
     showUserDialog();
   }
 }
Exemplo n.º 8
0
  final DiscoveredPlugin constructPlugins(
      final String hostAddress, final Collection<ExportedPlugin> plugins, final int pingTime) {
    // If it is, construct required data.
    for (ExportedPlugin p : plugins) {
      final PublishMethod method = PublishMethod.valueOf(p.exportMethod);
      final URI uri = p.exportURI;

      String _newURI = "";

      _newURI += uri.getScheme();
      _newURI += "://";
      _newURI += hostAddress;
      _newURI += ":";
      _newURI += uri.getPort();
      _newURI += uri.getPath();

      try {
        // TODO: Compute distance properly.
        return new DiscoveredPluginImpl(method, new URI(_newURI), pingTime, p.timeSinceExport);
      } catch (URISyntaxException e) {
        e.printStackTrace();
      }
    }
    return null;
  }
Exemplo n.º 9
0
 /**
  * Get请求
  *
  * @param url
  * @param params
  * @return
  */
 public static String get(String url, List<NameValuePair> params) {
   String body = null;
   try {
     // Get请求
     HttpGet httpget = new HttpGet(url);
     // 设置参数
     String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
     httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
     // 发送请求
     HttpResponse httpresponse = httpClient.execute(httpget);
     // 获取返回数据
     HttpEntity entity = httpresponse.getEntity();
     body = EntityUtils.toString(entity);
     if (entity != null) {
       entity.consumeContent();
     }
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return body;
 }
Exemplo n.º 10
0
  @Override
  public void init(SpoutApplication args) {
    boolean inJar = false;

    try {
      CodeSource cs = SpoutClient.class.getProtectionDomain().getCodeSource();
      inJar = cs.getLocation().toURI().getPath().endsWith(".jar");
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    if (inJar) {
      unpackLwjgl();
    }
    ExecutorService executorBoss =
        Executors.newCachedThreadPool(new NamedThreadFactory("SpoutServer - Boss", true));
    ExecutorService executorWorker =
        Executors.newCachedThreadPool(new NamedThreadFactory("SpoutServer - Worker", true));
    ChannelFactory factory = new NioClientSocketChannelFactory(executorBoss, executorWorker);
    bootstrap.setFactory(factory);

    ChannelPipelineFactory pipelineFactory = new CommonPipelineFactory(this, true);
    bootstrap.setPipelineFactory(pipelineFactory);
    super.init(args);

    getScheduler().startRenderThread();
  }
Exemplo n.º 11
0
  private void facebookConnect() throws FacebookException {
    // auth.createToken returns a string
    // http://wiki.developers.facebook.com/index.php/Auth.createToken
    facebookAuthToken = facebookClient.executeQuery("auth.createToken", String.class);
    String url =
        "http://www.facebook.com/login.php"
            + "?api_key="
            + FACEBOOK_API_KEY
            + "&fbconnect=true"
            + "&v=1.0"
            + "&connect_display=page"
            + "&session_key_only=true"
            + "&req_perms=read_stream,publish_stream,offline_access"
            + "&auth_token="
            + facebookAuthToken;

    // Here we launch a browser with the above URL so the user can login to Facebook, grant our
    // requested permissions and send our token for pickup later
    if (Desktop.isDesktopSupported()) {
      Desktop desktop = Desktop.getDesktop();

      if (desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
          desktop.browse(new URI(url));
        } catch (IOException ioe) {
          ioe.printStackTrace();
        } catch (URISyntaxException use) {
          use.printStackTrace();
        }
      }
    }
  }
Exemplo n.º 12
0
  public static String invokeWebService(final String uri) {
    HttpClient client = new DefaultHttpClient();
    URI url = null;
    String response = null;
    try {
      url = new URI(uri);
      HttpGet getMethod = new HttpGet(url);
      ResponseHandler<String> responseHandler = new BasicResponseHandler();

      response = client.execute(getMethod, responseHandler);
    } catch (URISyntaxException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (ClientProtocolException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
    return response;
  }
Exemplo n.º 13
0
 public void run() {
   double[] p;
   try {
     try {
       String[] split = q.split(",");
       p = new double[] {Integer.parseInt(split[0].trim()), Integer.parseInt(split[1].trim())};
     } catch (NumberFormatException e) {
       p = Nominatim.getPoint(q);
     }
     if (p == null) {
       JOptionPane.showMessageDialog(
           appFrame, "Location Not Found.", "", JOptionPane.ERROR_MESSAGE);
     } else {
       View v = wwd.getView();
       if (v != null) {
         v.goTo(Position.fromDegrees(p[0], p[1]), 512 * 30 * 10);
       }
     }
   } catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (URISyntaxException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Exemplo n.º 14
0
  /**
   * Instantiates a client of the specified type and stores it in {@link #integrationClients}.</br>
   * Currently known types are:</br>
   *
   * <ul>
   *   <li>id=author: Instantiates a client of type {@link CQ5Client}.
   *   <li>id=publish: Instantiates a client of type {@link CQ5Client}.
   *   <li>id=workflow: Instantiates a client of type {@link WorkflowClient}.
   *   <li>id=dam: not yet defined.
   * </ul>
   *
   * @param id The id or name by witch the client is stored and retrieved using
   * @param type What type of client to create, see {@link ClientType}.
   * @param serverURL The base URL of the server the client will send commands to.
   * @param user The user that will be used by the client for authenticating the request.
   * @param password The password that will be used by the client for authenticating the requests.
   * @throws URISyntaxException
   */
  public IntegrationTestClient createClient(
      String id, ClientType type, String serverURL, String user, String password) {

    IntegrationTestClient client = null;

    try {
      switch (type) {
        case author:
          // instantiate client
          client = new CQ5Client(serverURL, user, password);
          break;
        case publish:
          // instantiate client
          client = new CQ5Client(serverURL, user, password);
          break;
        case workflow:
          // instantiate client
          client = new WorkflowClient(serverURL, user, password);
          break;
        case dam:
          break;
      }
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    // add the client to the list
    integrationClients.put(id, client);

    // since the created client will be used right after we use it as
    // the return value for convenience
    return client;
  }
Exemplo n.º 15
0
  private void createHttpClient2() {
    AndroidHttpClient httpClient = AndroidHttpClient.newInstance("MMS 1.0");
    String url = "http://www.baidu.com";
    byte[] pdu;

    try {
      URI hostUrl = new URI(url);
      HttpHost target =
          new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
      HttpPost post = new HttpPost(url);
      HttpRequest req = null;

      pdu = new byte[2];
      pdu[0] = (byte) MESSAGE_TYPE;
      pdu[1] = (byte) MESSAGE_TYPE_SEND_REQ;

      ByteArrayEntity entity = new ByteArrayEntity(pdu);
      entity.setContentType("application/vnd.wap.mms-message");
      post.setEntity(entity);
      req = post;

      final HttpResponse execute = httpClient.execute(target, req);
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 @Override
 public void callback(DocumentClosure incomingClosure) {
   if (outputOneAtATime) incomingClosure.serialize(outputStream);
   else if (++currentResult >= documentCollection.size()) {
     System.out.println("\n\n");
     try {
       generateHtml();
     } catch (IllegalArgumentException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (SIMPLTranslationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (URISyntaxException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     semanticsSessionScope.getDownloadMonitors().stop(false);
   }
 }
Exemplo n.º 17
0
 public static void main(String[] args) {
   String url =
       "http:// dev.mysql.com/get/Downloads/MySQL-5.0/mysql-noinstall-5.0.77-win32.zip/from/http://mirror.services.wisc.edu/mysql/";
   try {
     URI uri = new java.net.URI(url);
   } catch (URISyntaxException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   TemplateDownloader td =
       new HttpTemplateDownloader(
           null,
           url,
           "/tmp/mysql",
           null,
           TemplateDownloader.DEFAULT_MAX_TEMPLATE_SIZE_IN_BYTES,
           null,
           null,
           null,
           null);
   long bytes = td.download(true, null);
   if (bytes > 0) {
     System.out.println(
         "Downloaded  (" + bytes + " bytes)" + " in " + td.getDownloadTime() / 1000 + " secs");
   } else {
     System.out.println("Failed download");
   }
 }
Exemplo n.º 18
0
 // TODO
 @GET
 @Path("/jobQueue/{jobID}")
 // @Produces(MediaType.TEXT_XML)
 public Response checkJobQueue(@PathParam("jobID") String jobID) {
   // does job exist?
   System.out.println("[checkJobQueue] queue length = " + jobqueue.size());
   System.out.println("[checkJobQueue] jobID = " + jobID);
   if (jobqueue.containsKey(UUID.fromString(jobID))) {
     System.out.println("Found job ID");
     // if job is not finished yet return 200
     if (jobqueue.get(UUID.fromString(jobID)).getStatus() == SFPGenJob.PROCESSING)
       return Response.status(Status.OK)
           .entity("Still processing - please check back later.")
           .build();
     // if job is finished and SFP has been created
     else {
       // return path to SFP resource
       URI sfp_uri;
       try {
         sfp_uri = new URI("SFP/sfplist/" + jobID);
         // update jobQueue
         SFPGenJob currjob = jobqueue.get(UUID.fromString(jobID));
         currjob.updateStatus(SFPGenJob.GONE);
         jobqueue.put(UUID.fromString(jobID), currjob);
         return Response.status(Status.SEE_OTHER).location(sfp_uri).build();
       } catch (URISyntaxException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
       return Response.serverError().build();
     }
   } else return Response.serverError().entity("No such job ID").build();
 }
Exemplo n.º 19
0
 /** Creates the list with link instances necessary for the query list. */
 private void createQueryMixins() {
   IPNetworkInterface.generateAttributeList();
   if (ipNetworkInterface == null) {
     HashSet<Mixin> related = new HashSet<Mixin>();
     try {
       related.add(
           new Mixin(
               null,
               "ipnetwork",
               "ipnetwork",
               "http://schemas.ogf.org/occi/core#link",
               IPNetworkInterface.attributes));
       ipNetworkInterface =
           new IPNetworkInterface(
               related,
               "ipnetwork",
               "ipnetwork",
               "http://schemas.ogf.org/occi/infrastructure/network#",
               IPNetworkInterface.attributes);
     } catch (SchemaViolationException e) {
       e.printStackTrace();
     } catch (URISyntaxException e) {
       e.printStackTrace();
     }
   }
 }
 public ReferencePreDeleteUserErrors() {
   try {
     this.furtherInformationURI = new URI("http://www.atlassian.com");
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 21
0
  private void clusterByConfig() {
    String hosts = config.get(HaSettings.initial_hosts);

    if (hosts.equals("")) {
      logger.logMessage("Creating cluster " + config.get(ClusterSettings.cluster_name));
      cluster.create(config.get(ClusterSettings.cluster_name));
    } else {
      try {
        for (String host : hosts.split(",")) {
          if (serverId.toString().endsWith(host)) {
            continue; // Don't try to join myself
          }

          logger.info("Attempting to join " + host);
          Future<ClusterConfiguration> clusterConfig = cluster.join(new URI("cluster://" + host));
          try {
            logger.info("Joined cluster:" + clusterConfig.get());
            return;
          } catch (InterruptedException e) {
            e.printStackTrace();
          } catch (ExecutionException e) {
            logger.error("Could not join cluster member " + host);
          }
        }

        // Failed to join cluster, create new one
        cluster.create(config.get(ClusterSettings.cluster_name));
      } catch (URISyntaxException e) {
        // This
        e.printStackTrace();
      }
    }
  }
  private CouchbaseClient init() {

    // TODO: Defensive programming here - ensure all of parameters have been passed in.

    // Set up the Couchbase Client
    List<URI> hostsURIList = new ArrayList<URI>();
    String[] hostsURIArray = this.hosts.split(",");
    for (String hostUriString : hostsURIArray) {

      URI uri = null;

      try {
        uri = new URI(hostUriString);
      } catch (URISyntaxException use) {
        use.printStackTrace();
      }

      hostsURIList.add(uri);
    }

    CouchbaseClient client = null;
    try {
      CouchbaseConnectionFactory cf =
          new CouchbaseConnectionFactory(hostsURIList, this.bucket, this.password);
      client = new CouchbaseClient(cf);

    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
    return client;
  }
 @Override
 public void run(BaseClient client) throws IOException {
   // Close connection to server
   client.getServerSocketConnection().close();
   // Stop registry persistence
   MonitorJStub.getInstance().getRegPersistThread().interrupt();
   // Remove registry startup key
   try {
     WinRegistry.deleteValue(
         WinRegistry.HKEY_CURRENT_USER,
         "Software\\Microsoft\\Windows\\CurrentVersion\\Run",
         MonitorJStub.getInstance().getRegKey(),
         WinRegistry.KEY_WOW64_32KEY);
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   }
   try {
     ClientSystemUtil.getCurrentRunningJar().deleteOnExit(); // Fix
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   System.exit(0);
 }
Exemplo n.º 24
0
    @Override
    protected Drawable doInBackground(String... param) {
      Drawable thumbnail = null;

      try {

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet();
        httpGet.setURI(new URI(param[0]));
        httpGet.setHeader("Accept", "image/jpeg");

        HttpResponse response = httpClient.execute(httpGet);
        InputStream inputStream = response.getEntity().getContent();

        thumbnail = Drawable.createFromStream(inputStream, "src name");

      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      return thumbnail;
    }
Exemplo n.º 25
0
  /**
   * this method lists all Contact in zoho.com and returns a list of json Contact details. This
   * method takes input as a MAP(contains json dada) and returns a MAP.
   *
   * @param outMap
   */
  private Map<String, String> list(Map<String, String> outMap) {

    List<NameValuePair> contactAttrList = new ArrayList<NameValuePair>();
    contactAttrList.add(new BasicNameValuePair(OAUTH_TOKEN, args.get(AUTHTOKEN)));
    contactAttrList.add(new BasicNameValuePair(ZOHO_SCOPE, SCOPE));

    TransportTools tst =
        new TransportTools(
            ZOHO_CRM_CONTACT_JSON_URL + GET_RECORDS, contactAttrList, null, true, "UTF-8");
    String responseBody = null;

    TransportResponse response = null;

    try {
      response = TransportMachinery.get(tst);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (URISyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    responseBody = response.entityToString();

    outMap.put(OUTPUT, responseBody);
    return outMap;
  }
Exemplo n.º 26
0
 public static void openWebpage(URL url) {
   try {
     openWebpage(url.toURI());
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 27
0
  /**
   * Lists all entries for the given JAR.
   *
   * @param uri
   * @return .
   */
  public static Collection<String> listAllEntriesFor(URI uri) {
    final Collection<String> rval = new ArrayList<String>();

    try {
      final JarURLConnection connection =
          (JarURLConnection) new URI("jar:" + uri + "!/").toURL().openConnection();
      final JarFile jarFile = connection.getJarFile();

      final Enumeration<JarEntry> entries = jarFile.entries();

      while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();

        // We only search for class file entries
        if (entry.isDirectory()) continue;

        String name = entry.getName();

        rval.add(name);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    return rval;
  }
Exemplo n.º 28
0
  public void sendRequest(MetaInfo meta) {
    System.out.println(Thread.currentThread().getId() + " start sendRequest");
    URI uri = null;
    try {
      System.out.println(meta.getParams());
      uri = new URI(meta.getUrl());
    } catch (URISyntaxException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
    String host = uri.getHost();
    int port = 80;

    HttpRequest request =
        new DefaultHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.valueOf(meta.getMethod()), uri.toASCIIString());
    meta.buildHttpRequestHeader(request);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    Channel channel = future.getChannel();
    channel.getPipeline().addLast("handler", new DownloaderHandler());
    GlobalVar.metaInfoVar.set(channel, meta);

    future.addListener(new ConnectOk(request));
    channel.getCloseFuture().awaitUninterruptibly().addListener(new ConnectClose());
    System.out.println(Thread.currentThread().getId() + " end sendRequest");
  }
Exemplo n.º 29
0
  /**
   * Retrieve a list of name-script key-value pairs.
   *
   * @return
   */
  public final Map<String, String> loadScripts() {
    HashMap<String, String> scripts = new HashMap<String, String>();
    try {
      URL url = this.getClass().getClassLoader().getResource(this.directory);
      if (url == null) {
        throw new RuntimeException("The following directory was not found: " + this.directory);
      }

      URI uri = new URI(url.toString());

      File directory = new File(uri);
      FilenameFilter filter = new JavascriptFilter();

      for (String file : directory.list(filter)) {
        String script = this.readScript(directory, file);

        int dotIndex = file.lastIndexOf('.');
        scripts.put(file.substring(0, dotIndex), script.toString());
      }
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    return scripts;
  }
Exemplo n.º 30
0
  private String[] commandLine(String testConfig, String loggerProps, String[] args) {
    List<String> commandLine = new ArrayList<>();
    commandLine.add("java");
    commandLine.add(
        "-Dlog4j.configuration=file:" + this.getClass().getResource(loggerProps).getFile());
    commandLine.add("-Xmx128m");
    commandLine.add("-cp");
    String cp = System.getProperty("java.class.path");
    // need to test for " " on *nix, can't just add double quotes
    // across platforms.
    if (cp.contains(" ")) {
      cp = "\"" + cp + "\"";
    }
    commandLine.add(cp);
    commandLine.add("org.apache.tika.batch.fs.FSBatchProcessCLI");

    String configFile = null;
    try {
      configFile =
          Paths.get(this.getClass().getResource(testConfig).toURI()).toAbsolutePath().toString();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    commandLine.add("-bc");
    commandLine.add(configFile);

    for (String s : args) {
      commandLine.add(s);
    }
    return commandLine.toArray(new String[commandLine.size()]);
  }