Java Code Examples for java.net.URL

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/options/.

Source file: OptionsPackage.java

  41 
vote

public boolean loadURL(String propertiesUrl){
  try {
    URL url=new URL(propertiesUrl);
    HttpURLConnection con=(HttpURLConnection)url.openConnection();
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    properties.load(in);
    return true;
  }
 catch (  Exception e) {
    Utils.log("Properties file not found",System.err);
    return false;
  }
}
 

Example 2

From project Aardvark, under directory /aardvark-core/src/main/java/gw/vark/.

Source file: Aardvark.java

  34 
vote

public static String getVersion(){
  URL versionResource=Aardvark.class.getResource("/gw/vark/version.txt");
  try {
    Reader reader=StreamUtil.getInputStreamReader(versionResource.openStream());
    String version=StreamUtil.getContent(reader).trim();
    return "Aardvark version " + version;
  }
 catch (  IOException e) {
    throw GosuExceptionUtil.forceThrow(e);
  }
}
 

Example 3

From project activejdbc, under directory /activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/.

Source file: ActiveJdbcInstrumentationPlugin.java

  32 
vote

private void instrument(String instrumentationDirectory) throws MalformedURLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  if (!new File(instrumentationDirectory).exists()) {
    getLog().info("Instrumentation: directory " + instrumentationDirectory + " does not exist, skipping");
    return;
  }
  ClassLoader realmLoader=getClass().getClassLoader();
  URL outDir=new File(instrumentationDirectory).toURL();
  Method addUrlMethod=realmLoader.getClass().getSuperclass().getDeclaredMethod("addURL",URL.class);
  addUrlMethod.setAccessible(true);
  addUrlMethod.invoke(realmLoader,outDir);
  Instrumentation instrumentation=new Instrumentation();
  instrumentation.setOutputDirectory(instrumentationDirectory);
  instrumentation.instrument();
}
 

Example 4

From project activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/command/.

Source file: ActiveMQBlobMessage.java

  32 
vote

public InputStream getInputStream() throws IOException, OpenwireException {
  URL value=getURL();
  if (value == null) {
    return null;
  }
  return value.openStream();
}
 

Example 5

From project addis, under directory /application/src/main/java/org/drugis/addis/.

Source file: AppInfo.java

  32 
vote

public String call(){
  URL updateWebService;
  try {
    updateWebService=new URL("http://drugis.org/service/currentVersion");
    URLConnection conn=updateWebService.openConnection();
    String line=new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
    return new StringTokenizer(line).nextToken();
  }
 catch (  Exception e) {
    System.err.println("Warning: Couldn't check for new versions. Connection issue?");
  }
  return null;
}
 

Example 6

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/.

Source file: Downloader.java

  32 
vote

private static boolean exists(final String URLName) throws IOException {
  HttpURLConnection con=null;
  try {
    HttpURLConnection.setFollowRedirects(false);
    con=(HttpURLConnection)new URL(URLName).openConnection();
    con.setRequestMethod("HEAD");
    return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
  }
  finally {
    if (con != null) {
      con.disconnect();
    }
  }
}
 

Example 7

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/http/.

Source file: KeywordUtils.java

  32 
vote

public static String getSearchEngineQueryString(HttpServletRequest request,String referrer){
  String queryString=null;
  String hostName=null;
  if (referrer != null) {
    URL refererURL;
    try {
      refererURL=new URL(referrer);
    }
 catch (    MalformedURLException e) {
      return null;
    }
    hostName=refererURL.getHost();
    queryString=refererURL.getQuery();
    if (Strings.isEmpty(queryString)) {
      return null;
    }
    Set<String> keys=seParams.keySet();
    for (    String se : keys) {
      if (hostName.toLowerCase().contains(se)) {
        queryString=getQueryStringParameter(queryString,seParams.get(se));
      }
    }
    return queryString;
  }
  return null;
}
 

Example 8

From project aether-core, under directory /aether-connector-asynchttpclient/src/test/java/org/eclipse/aether/connector/async/.

Source file: ProxyGetTest.java

  32 
vote

@Override public String url(){
  URL orig;
  try {
    orig=new URL(super.url());
    return new URL(orig.getProtocol(),"proxiedhost",orig.getPort(),"").toString();
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
    throw new IllegalStateException(e.getMessage(),e);
  }
}
 

Example 9

From project agile, under directory /agile-storage/src/main/java/org/headsupdev/agile/storage/.

Source file: HibernateUtil.java

  32 
vote

public URL getResource(String name){
  Enumeration<ClassLoader> loaderIter=loaders.elements();
  while (loaderIter.hasMoreElements()) {
    ClassLoader loader=loaderIter.nextElement();
    URL ret=loader.getResource(name);
    if (ret != null) {
      return ret;
    }
  }
  return super.getResource(name);
}
 

Example 10

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHTTPClient.java

  32 
vote

/** 
 * Set the username and password for authentication with the remote server.
 * @param username the username
 * @param password the password
 */
public void setUsernameAndPassword(String username,String password){
  if (username != null && password != null) {
    logger.debug("Setting username '{}' and password for server at {}.",username,serverURL);
    try {
      URL server=new URL(serverURL);
      authScope=new AuthScope(server.getHost(),AuthScope.ANY_PORT);
      httpClient.getState().setCredentials(authScope,new UsernamePasswordCredentials(username,password));
      httpClient.getParams().setAuthenticationPreemptive(true);
    }
 catch (    MalformedURLException e) {
      logger.warn("Unable to set username and password for malformed URL " + serverURL,e);
    }
  }
 else {
    authScope=null;
    httpClient.getState().clearCredentials();
    httpClient.getParams().setAuthenticationPreemptive(false);
  }
}
 

Example 11

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/net/.

Source file: HttpClient.java

  32 
vote

/** 
 * Get a byte array version of the target URL.
 * @param url The URL to fetch.
 * @return The results of the URL, if possible, or null.
 * @throws IOException If the file could not be fetched.
 */
public static byte[] getBytes(final String url) throws IOException {
  try {
    final URL ur=new URL(url);
    URLConnection conn;
    conn=ur.openConnection();
    return StreamUtils.toByteArray(conn.getInputStream());
  }
 catch (  final MalformedURLException e) {
    return null;
  }
}
 

Example 12

From project AlarmApp-Android, under directory /src/org/alarmapp/web/http/.

Source file: HttpUtil.java

  32 
vote

public static String request(String url,HashMap<String,String> data,HashMap<String,String> headers) throws WebException {
  Ensure.notNull(url);
  try {
    URL uri=new URL(url);
    if (isNullOrEmpty(data))     return get(uri,headers);
 else     return post(uri,data,headers);
  }
 catch (  MalformedURLException e) {
    throw new WebException(URL_ERROR + url,e);
  }
}
 

Example 13

From project alfredo, under directory /alfredo/src/test/java/com/cloudera/alfredo/client/.

Source file: TestKerberosAuthenticator.java

  32 
vote

public void testNotAuthenticated() throws Exception {
  setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration());
  start();
  try {
    URL url=new URL(getBaseURL());
    HttpURLConnection conn=(HttpURLConnection)url.openConnection();
    conn.connect();
    assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,conn.getResponseCode());
    assertTrue(conn.getHeaderField(KerberosAuthenticator.WWW_AUTHENTICATE) != null);
  }
  finally {
    stop();
  }
}
 

Example 14

From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/object/reader/.

Source file: ExcelReader.java

  32 
vote

/** 
 * Instantiates a new excel reader.
 * @param fileName the file name
 * @param columnsHorizontal the columns horizontal
 * @param namedIndex the named index
 * @throws BiffException the biff exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public ExcelReader(String fileName,boolean columnsHorizontal,boolean namedIndex) throws BiffException, IOException {
  URL url=getClass().getClassLoader().getResource(fileName);
  if (url == null)   throw new RuntimeException("Unable get resource '" + fileName + "'");
  this.open(url.getPath());
  setColumnsHorizontal(columnsHorizontal);
  setNamedIndex(namedIndex);
}
 

Example 15

From project amber, under directory /oauth-2.0/integration-tests/src/test/java/org/apache/amber/oauth2/integration/.

Source file: Common.java

  32 
vote

public static HttpURLConnection doRequest(OAuthClientRequest req) throws IOException {
  URL url=new URL(req.getLocationUri());
  HttpURLConnection c=(HttpURLConnection)url.openConnection();
  c.setInstanceFollowRedirects(true);
  c.connect();
  c.getResponseCode();
  return c;
}
 

Example 16

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.

Source file: CacheInvalidator.java

  32 
vote

protected void flushUriIfSameHost(URL requestURL,URL targetURL){
  URL canonicalTarget=getAbsoluteURL(cacheKeyGenerator.canonicalizeUri(targetURL.toString()));
  if (canonicalTarget == null)   return;
  if (canonicalTarget.getAuthority().equalsIgnoreCase(requestURL.getAuthority())) {
    flushEntry(canonicalTarget.toString());
  }
}
 

Example 17

From project android-joedayz, under directory /Proyectos/FBConnectTest/src/com/facebook/android/.

Source file: Util.java

  32 
vote

/** 
 * Parse a URL query and fragment parameters into a key-value bundle.
 * @param url the URL to parse
 * @return a dictionary bundle of keys and values
 */
public static Bundle parseUrl(String url){
  url=url.replace("fbconnect","http");
  try {
    URL u=new URL(url);
    Bundle b=decodeUrl(u.getQuery());
    b.putAll(decodeUrl(u.getRef()));
    return b;
  }
 catch (  MalformedURLException e) {
    return new Bundle();
  }
}
 

Example 18

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/facebook/extpack/com/facebook/android/.

Source file: Util.java

  32 
vote

/** 
 * Parse a URL query and fragment parameters into a key-value bundle.
 * @param url the URL to parse
 * @return a dictionary bundle of keys and values
 */
public static Bundle parseUrl(String url){
  url=url.replace("fbconnect","http");
  try {
    URL u=new URL(url);
    Bundle b=decodeUrl(u.getQuery());
    b.putAll(decodeUrl(u.getRef()));
    return b;
  }
 catch (  MalformedURLException e) {
    return new Bundle();
  }
}
 

Example 19

From project android-tether, under directory /facebook/src/com/facebook/android/.

Source file: Util.java

  32 
vote

/** 
 * Parse a URL query and fragment parameters into a key-value bundle.
 * @param url the URL to parse
 * @return a dictionary bundle of keys and values
 */
public static Bundle parseUrl(String url){
  url=url.replace("fbconnect","http");
  try {
    URL u=new URL(url);
    Bundle b=decodeUrl(u.getQuery());
    b.putAll(decodeUrl(u.getRef()));
    return b;
  }
 catch (  MalformedURLException e) {
    return new Bundle();
  }
}
 

Example 20

From project androidquery, under directory /auth/com/androidquery/auth/.

Source file: FacebookHandle.java

  32 
vote

private static Bundle parseUrl(String url){
  try {
    URL u=new URL(url);
    Bundle b=decodeUrl(u.getQuery());
    b.putAll(decodeUrl(u.getRef()));
    return b;
  }
 catch (  MalformedURLException e) {
    return new Bundle();
  }
}
 

Example 21

From project android_7, under directory /src/org/immopoly/android/api/.

Source file: IS24ApiService.java

  32 
vote

/** 
 * Gets result page number 'page' from IS24 for the given lat,lon,r
 * @param lat
 * @param lon
 * @param r
 * @param page
 * @return
 * @throws MalformedURLException
 * @throws JSONException
 */
private JSONObject loadPage(double lat,double lon,float r,int page) throws MalformedURLException, JSONException {
  URL url=new URL(OAuthData.SERVER + OAuthData.SEARCH_PREFIX + "search/radius.json?realEstateType=apartmentrent&pagenumber="+ page+ "&geocoordinates="+ lat+ ";"+ lon+ ";"+ r);
  JSONObject obj=WebHelper.getHttpData(url,true,this);
  if (obj == null) {
    throw new JSONException("Got (JSONObject) null for search result. Lat: " + lat + "Lon: "+ lon+ " R: "+ r+ " pageNr: "+ page);
  }
  return obj;
}
 

Example 22

From project android_external_guava, under directory /src/com/google/common/base/.

Source file: FinalizableReferenceQueue.java

  32 
vote

/** 
 * Gets URL for base of path containing Finalizer.class.
 */
URL getBaseUrl() throws IOException {
  String finalizerPath=FINALIZER_CLASS_NAME.replace('.','/') + ".class";
  URL finalizerUrl=getClass().getClassLoader().getResource(finalizerPath);
  if (finalizerUrl == null) {
    throw new FileNotFoundException(finalizerPath);
  }
  String urlString=finalizerUrl.toString();
  if (!urlString.endsWith(finalizerPath)) {
    throw new IOException("Unsupported path style: " + urlString);
  }
  urlString=urlString.substring(0,urlString.length() - finalizerPath.length());
  return new URL(finalizerUrl,urlString);
}
 

Example 23

From project android_external_oauth, under directory /core/src/main/java/net/oauth/.

Source file: ConsumerProperties.java

  32 
vote

public static URL getResource(String name,ClassLoader loader) throws IOException {
  URL resource=loader.getResource(name);
  if (resource == null) {
    throw new IOException("resource not found: " + name);
  }
  return resource;
}
 

Example 24

From project android_external_tagsoup, under directory /src/org/ccil/cowan/tagsoup/.

Source file: Parser.java

  32 
vote

private InputStream getInputStream(String publicid,String systemid) throws IOException, SAXException {
  URL basis=new URL("file","",System.getProperty("user.dir") + "/.");
  URL url=new URL(basis,systemid);
  URLConnection c=url.openConnection();
  return c.getInputStream();
}
 

Example 25

From project ant4eclipse, under directory /org.ant4eclipse.ant.pydt.test/src-framework/org/ant4eclipse/ant/pydt/test/.

Source file: AbstractWorkspaceBasedTest.java

  32 
vote

/** 
 * Returns the location of a specific resource. This function causes an exception in case the resource could not be located.
 * @param path The path of the resource (must be root based). Neither <code>null</code> nor empty.
 * @return The URL pointing to that resource. Not <code>null</code>.
 */
protected URL getResource(String path){
  Assert.assertNotNull(path);
  URL result=getClass().getResource(path);
  if (result == null) {
    Assert.fail(String.format("The resource '%s' is not located on the classpath !",path));
  }
  return result;
}
 

Example 26

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Commands/.

Source file: cmdRebuild.java

  31 
vote

private boolean downloadSkin(String playerName){
  int len1=0;
  InputStream is=null;
  OutputStream os=null;
  try {
    URL url=new URL("http://s3.amazonaws.com/MinecraftSkins/" + playerName + ".png");
    is=url.openStream();
    os=new FileOutputStream(new File(Core.getInstance().getDataFolder(),"/skins/" + playerName + ".png"));
    byte[] buff=new byte[4096];
    while (-1 != (len1=is.read(buff))) {
      os.write(buff,0,len1);
    }
    os.flush();
  }
 catch (  Exception ex) {
    return false;
  }
 finally {
    if (os != null)     try {
      os.close();
    }
 catch (    IOException ex) {
    }
    if (is != null)     try {
      is.close();
    }
 catch (    IOException ex) {
    }
  }
  return true;
}
 

Example 27

From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial.extension.ui/src/org/eclipse/acceleo/tutorial/extension/ui/common/.

Source file: GenerateAll.java

  31 
vote

/** 
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * @param bundleID is the plug-in ID
 * @param relativePath is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings("unchecked") private URI getTemplateURI(String bundleID,IPath relativePath) throws IOException {
  Bundle bundle=Platform.getBundle(bundleID);
  if (bundle == null) {
    return URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(),false);
  }
  URL url=bundle.getEntry(relativePath.toString());
  if (url == null && relativePath.segmentCount() > 1) {
    Enumeration<URL> entries=bundle.findEntries("/","*.emtl",true);
    if (entries != null) {
      String[] segmentsRelativePath=relativePath.segments();
      while (url == null && entries.hasMoreElements()) {
        URL entry=entries.nextElement();
        IPath path=new Path(entry.getPath());
        if (path.segmentCount() > relativePath.segmentCount()) {
          path=path.removeFirstSegments(path.segmentCount() - relativePath.segmentCount());
        }
        String[] segmentsPath=path.segments();
        boolean equals=segmentsPath.length == segmentsRelativePath.length;
        for (int i=0; equals && i < segmentsPath.length; i++) {
          equals=segmentsPath[i].equals(segmentsRelativePath[i]);
        }
        if (equals) {
          url=bundle.getEntry(entry.getPath());
        }
      }
    }
  }
  URI result;
  if (url != null) {
    result=URI.createPlatformPluginURI(new Path(bundleID).append(new Path(url.getPath())).toString(),false);
  }
 else {
    result=URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(),false);
  }
  return result;
}
 

Example 28

From project accesointeligente, under directory /src/org/accesointeligente/server/solr/.

Source file: SolrClient.java

  31 
vote

static public String execQuery(String query){
  HttpClient client=new DefaultHttpClient();
  HtmlCleaner cleaner=new HtmlCleaner();
  HttpGet get;
  HttpResponse response;
  TagNode document;
  String jsonResponse=null;
  String httpQuery="";
  URL url=null;
  URI uri=null;
  try {
    httpQuery=ApplicationProperties.getProperty("solr.server.address") + ApplicationProperties.getProperty("solr.core.path") + ApplicationProperties.getProperty("solr.query.path");
    httpQuery+=query;
    url=new URL(httpQuery);
    uri=new URI(url.getProtocol(),url.getUserInfo(),url.getHost(),url.getPort(),url.getPath(),url.getQuery(),url.getRef());
    url=uri.toURL();
    httpQuery=url.toString();
    get=new HttpGet(httpQuery);
    response=client.execute(get);
    document=cleaner.clean(new InputStreamReader(response.getEntity().getContent()));
    jsonResponse=document.getText().toString();
  }
 catch (  Exception ex) {
    logger.error(httpQuery);
    logger.error(ex.getMessage(),ex);
  }
  return jsonResponse;
}
 

Example 29

From project airlift, under directory /configuration/src/test/java/io/airlift/configuration/testing/.

Source file: TestConfigAssertions.java

  31 
vote

@Test public void testRecordedDefaultsFailInvokedDeprecatedSetter() throws MalformedURLException {
  boolean pass=true;
  try {
    ConfigAssertions.assertRecordedDefaults(ConfigAssertions.recordDefaults(PersonConfig.class).setName("Dain").setEmail("dain@proofpoint.com").setPhone(null).setHomePageUrl(new URL("http://iq80.com")));
  }
 catch (  AssertionError e) {
    pass=false;
    Assertions.assertContains(e.getMessage(),"HomePageUrl");
  }
  if (pass) {
    Assert.fail("Expected AssertionError");
  }
}
 

Example 30

From project akubra, under directory /akubra-www/src/main/java/org/akubraproject/www/.

Source file: WWWConnection.java

  31 
vote

/** 
 * Gets a WWWBlob instance for an id. Instances are cached so that instance equality is guaranteed for the same connection.
 * @param blobId the blob identifier
 * @param create whether to create new blob instances
 * @return the WWWBlob instance
 * @throws IOException if the connection is closed or on a failure to create a WWWBlob instance
 * @throws IllegalArgumentException if the blobId is null or not an absolute URL
 */
WWWBlob getWWWBlob(URI blobId,boolean create) throws IOException {
  if (blobs == null)   throw new IllegalStateException("Connection closed.");
  if (blobId == null)   throw new UnsupportedOperationException("Must supply a valid URL as the blob-id. " + "This store has no id generation capability.");
  WWWBlob blob=blobs.get(blobId);
  if ((blob == null) && create) {
    try {
      URL url=new URL(null,blobId.toString(),handlers.get(blobId.getScheme()));
      blob=new WWWBlob(url,this,streamManager);
    }
 catch (    MalformedURLException e) {
      throw new UnsupportedIdException(blobId," must be a valid URL",e);
    }
    blobs.put(blobId,blob);
  }
  return blob;
}
 

Example 31

From project ambrose, under directory /common/src/main/java/com/twitter/ambrose/server/.

Source file: ScriptStatusServer.java

  31 
vote

/** 
 * Run the server in the current thread.
 */
@Override public void run(){
  server=new Server(port);
  URL resourcesUrl=this.getClass().getClassLoader().getResource(ROOT_PATH);
  HandlerList handler=new HandlerList();
  handler.setHandlers(new Handler[]{new APIHandler(statsReadService),new WebAppContext(resourcesUrl.toExternalForm(),SLASH)});
  server.setHandler(handler);
  server.setStopAtShutdown(false);
  try {
    server.start();
    server.join();
  }
 catch (  Exception e) {
    LOG.error("Error launching ScriptStatusServer on port " + port,e);
  }
}
 

Example 32

From project and-bible, under directory /AndBible/src/net/bible/service/common/.

Source file: CommonUtils.java

  31 
vote

public static boolean isHttpUrlAvailable(String urlString){
  HttpURLConnection connection=null;
  try {
    URL url=new URL(urlString);
    Log.d(TAG,"Opening test connection");
    connection=(HttpURLConnection)url.openConnection();
    connection.setConnectTimeout(3000);
    Log.d(TAG,"Connecting to test internet connection");
    connection.connect();
    boolean success=(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    Log.d(TAG,"Url test result for:" + urlString + " is "+ success);
    return success;
  }
 catch (  IOException e) {
    Log.i(TAG,"No internet connection");
    return false;
  }
 finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}
 

Example 33

From project andlytics, under directory /src/com/github/andlyticsproject/.

Source file: DeveloperConsole.java

  31 
vote

private String grapAppStatistics(String startApp,long lenght) throws DeveloperConsoleException, NetworkException {
  String developerPostData=Preferences.getRequestFullAssetInfo(context);
  if (developerPostData == null) {
    developerPostData=GET_FULL_ASSET_INFO_FOR_USER_REQUEST;
  }
  String lengthString="" + lenght;
  String xsrfToken=((AndlyticsApp)context.getApplicationContext()).getXsrfToken();
  developerPostData=developerPostData.replace(PARAM_APPNAME,startApp != null ? startApp : "");
  developerPostData=developerPostData.replace(PARAM_LENGTH,lengthString);
  developerPostData=developerPostData.replace(PARAM_XSRFTOKEN,xsrfToken != null ? xsrfToken : "");
  String result=null;
  try {
    URL aURL=new java.net.URL(URL_DEVELOPER_EDIT_APP + "?dev_acc=" + devacc);
    result=getGwtRpcResponse(developerPostData,aURL);
  }
 catch (  ConnectException ex) {
    throw new NetworkException(ex);
  }
catch (  Exception f) {
    throw new DeveloperConsoleException(result,f);
  }
  return result;
}
 

Example 34

From project android-aac-enc, under directory /src/com/coremedia/iso/.

Source file: PropertyBoxParserImpl.java

  31 
vote

public PropertyBoxParserImpl(String... customProperties){
  Context context=AACToM4A.getContext();
  InputStream raw=null, is=null;
  mapping=new Properties();
  try {
    raw=context.getResources().openRawResource(R.raw.isoparser);
    is=new BufferedInputStream(raw);
    mapping.load(is);
    Enumeration<URL> enumeration=Thread.currentThread().getContextClassLoader().getResources("isoparser-custom.properties");
    while (enumeration.hasMoreElements()) {
      URL url=enumeration.nextElement();
      InputStream customIS=new BufferedInputStream(url.openStream());
      try {
        mapping.load(customIS);
      }
  finally {
        customIS.close();
      }
    }
    for (    String customProperty : customProperties) {
      mapping.load(new BufferedInputStream(getClass().getResourceAsStream(customProperty)));
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
 finally {
    try {
      if (raw != null)       raw.close();
      if (is != null)       is.close();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
  }
}
 

Example 35

From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/rest/transformation/.

Source file: DocumentBuilder_XML.java

  31 
vote

@Override public DocumentBuilder withAttachment(Attachment attachment){
  org.xwiki.android.xmodel.entity.Attachment a=new org.xwiki.android.xmodel.entity.Attachment();
  a.setId(attachment.id);
  a.setName(attachment.name);
  a.setSize(attachment.size);
  a.setVersion(attachment.version);
  a.setPageId(attachment.pageId);
  a.setPageVersion(attachment.version);
  a.setMimeType(attachment.mimeType);
  a.setAuthor(attachment.author);
  a.setDate(XUtils.toDate(attachment.date));
  URL absUrl=null;
  URL relUrl=null;
  try {
    absUrl=new URL(attachment.xwikiAbsoluteUrl);
    relUrl=new URL(attachment.xwikiRelativeUrl);
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
  a.setXwikiAbsoluteUrl(absUrl);
  a.setXwikiRelativeUrl(relUrl);
  a.setEdited(false);
  a.setNew(false);
  d.setAttachment(a);
  return this;
}
 

Example 36

From project android-context, under directory /src/edu/fsu/cs/contextprovider/monitor/.

Source file: WeatherMonitor.java

  31 
vote

@Override public void run(){
  weatherZip=LocationMonitor.getZip();
  URL url;
  try {
    String tmpStr=null;
    String cityParamString=weatherZip;
    Log.d(TAG,"cityParamString: " + cityParamString);
    String queryString="http://www.google.com/ig/api?weather=" + cityParamString;
    url=new URL(queryString.replace(" ","%20"));
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    gwh=new GoogleWeatherHandler();
    xr.setContentHandler(gwh);
    xr.parse(new InputSource(url.openStream()));
    ws=gwh.getWeatherSet();
    if (ws == null)     return;
    WeatherCurrentCondition wcc=ws.getWeatherCurrentCondition();
    if (wcc != null) {
      weatherTemp=null;
      Integer weatherTempInt=wcc.getTempFahrenheit();
      if (weatherTempInt != null) {
        weatherTemp=weatherTempInt;
      }
      weatherCond=wcc.getCondition();
      weatherHumid=wcc.getHumidity();
      weatherWindCond=wcc.getWindCondition();
      weatherHazard=calcHazard();
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"WeatherQueryError",e);
  }
}
 

Example 37

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: DownloadableLessonList.java

  31 
vote

public void run(){
  try {
    URL url=new URL("http://secretsockssoftware.com/androidflashcards/lessons/lesson_list.xml");
    URLConnection conn=url.openConnection();
    XMLReader xr=XMLReaderFactory.createXMLReader();
    LessonXMLParser lxp=new LessonXMLParser();
    xr.setContentHandler(lxp);
    xr.setErrorHandler(lxp);
    xr.parse(new InputSource(conn.getInputStream()));
    handler.sendMessage(handler.obtainMessage(0,lxp.getLessons()));
  }
 catch (  Exception e) {
    e.printStackTrace();
    handler.sendMessage(handler.obtainMessage(1,e.getMessage()));
  }
}
 

Example 38

From project android-mapviewballoons, under directory /android-mapviewballoons-example/src/mapviewballoons/example/custom/.

Source file: CustomBalloonOverlayView.java

  31 
vote

@Override protected Bitmap doInBackground(String... arg0){
  Bitmap b=null;
  try {
    b=BitmapFactory.decodeStream((InputStream)new URL(arg0[0]).getContent());
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return b;
}
 

Example 39

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.

Source file: OcrInitAsyncTask.java

  31 
vote

/** 
 * Download a file from the site specified by DOWNLOAD_BASE, and gunzip to the given destination.
 * @param sourceFilenameBase Name of file to download, minus the required ".gz" extension
 * @param destinationFile Name of file to save the unzipped data to, including path
 * @return True if download and unzip are successful
 * @throws IOException
 */
private boolean downloadFile(String sourceFilenameBase,File destinationFile) throws IOException {
  try {
    return downloadGzippedFileHttp(new URL(CaptureActivity.DOWNLOAD_BASE + sourceFilenameBase + ".gz"),destinationFile);
  }
 catch (  MalformedURLException e) {
    throw new IllegalArgumentException("Bad URL string.");
  }
}
 

Example 40

From project android-rackspacecloud, under directory /extensions/gae/src/main/java/org/jclouds/gae/.

Source file: GaeHttpCommandExecutorService.java

  31 
vote

@VisibleForTesting protected HTTPRequest convert(HttpRequest request) throws IOException {
  URL url=request.getEndpoint().toURL();
  FetchOptions options=disallowTruncate();
  options.doNotFollowRedirects();
  HTTPRequest gaeRequest=new HTTPRequest(url,HTTPMethod.valueOf(request.getMethod().toString()),options);
  for (  String header : request.getHeaders().keySet()) {
    for (    String value : request.getHeaders().get(header)) {
      gaeRequest.addHeader(new HTTPHeader(header,value));
    }
  }
  gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT,USER_AGENT));
  if (request.getPayload() != null) {
    changeRequestContentToBytes(request);
    gaeRequest.setPayload(((ByteArrayPayload)request.getPayload()).getRawContent());
  }
 else {
    gaeRequest.addHeader(new HTTPHeader(HttpHeaders.CONTENT_LENGTH,"0"));
  }
  return gaeRequest;
}
 

Example 41

From project android-xbmcremote, under directory /src/org/xbmc/android/remote/presentation/controller/.

Source file: MediaIntentController.java

  31 
vote

private static boolean isValidURL(String path){
  if (path == null || path.equals(""))   return false;
  try {
    new URL(path);
  }
 catch (  MalformedURLException e) {
    return false;
  }
  return true;
}
 

Example 42

From project AndroidExamples, under directory /RSSExample/src/com/robertszkutak/androidexamples/rss/.

Source file: RSSExampleActivity.java

  31 
vote

@Override protected RSSFeed doInBackground(String... RSSuri){
  try {
    URL url=new URL(RSSuri[0]);
    SAXParserFactory factory=SAXParserFactory.newInstance();
    SAXParser parser=factory.newSAXParser();
    XMLReader xmlreader=parser.getXMLReader();
    RSSHandler theRssHandler=new RSSHandler();
    xmlreader.setContentHandler(theRssHandler);
    InputSource is=new InputSource(url.openStream());
    xmlreader.parse(is);
    return theRssHandler.getFeed();
  }
 catch (  Exception ee) {
    return null;
  }
}
 

Example 43

From project androidpn, under directory /androidpn-server-bin-tomcat/src/org/dom4j/io/.

Source file: XMPPPacketReader.java

  31 
vote

/** 
 * <p>Reads a Document from the given URL or filename.</p> <p/> <p/> If the systemID contains a <code>':'</code> character then it is assumed to be a URL otherwise its assumed to be a file name. If you want finer grained control over this mechansim then please explicitly pass in either a  {@link URL} or a {@link File} instanceinstead of a  {@link String} to denote the source of the document.</p>
 * @param systemID is a URL for a document or a file name.
 * @return the newly created Document instance
 * @throws DocumentException              if an error occurs during parsing.
 * @throws java.net.MalformedURLException if a URL could not be made for the given File
 */
public Document read(String systemID) throws DocumentException, IOException, XmlPullParserException {
  if (systemID.indexOf(':') >= 0) {
    return read(new URL(systemID));
  }
 else {
    return read(new File(systemID));
  }
}
 

Example 44

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/examples/.

Source file: MockResultSet.java

  31 
vote

public URL getURL(int columnIndex) throws SQLException {
  try {
    return new URL("http://www.google.com/");
  }
 catch (  MalformedURLException ex) {
    throw new SQLException();
  }
}
 

Example 45

From project android_8, under directory /src/com/google/gson/.

Source file: DefaultTypeAdapters.java

  31 
vote

@Override public URL deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context) throws JsonParseException {
  try {
    return new URL(json.getAsString());
  }
 catch (  MalformedURLException e) {
    throw new JsonSyntaxException(e);
  }
}
 

Example 46

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.

Source file: DownloadCache.java

  31 
vote

public File run(JobContext jc){
  jc.setMode(ThreadPool.MODE_NETWORK);
  File tempFile=null;
  try {
    URL url=new URL(mUrl);
    tempFile=File.createTempFile("cache",".tmp",mRoot);
    jc.setMode(ThreadPool.MODE_NETWORK);
    boolean downloaded=DownloadUtils.requestDownload(jc,url,tempFile);
    jc.setMode(ThreadPool.MODE_NONE);
    if (downloaded)     return tempFile;
  }
 catch (  Exception e) {
    Log.e(TAG,String.format("fail to download %s",mUrl),e);
  }
 finally {
    jc.setMode(ThreadPool.MODE_NONE);
  }
  if (tempFile != null)   tempFile.delete();
  return null;
}
 

Example 47

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: UriTexture.java

  31 
vote

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,ClientConnectionManager connectionManager){
  InputStream contentInput=null;
  if (connectionManager == null) {
    try {
      URL url=new URI(uri).toURL();
      URLConnection conn=url.openConnection();
      conn.connect();
      contentInput=conn.getInputStream();
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + uri);
      e.printStackTrace();
      return null;
    }
  }
 else {
    final DefaultHttpClient mHttpClient=new DefaultHttpClient(connectionManager,HTTP_PARAMS);
    HttpUriRequest request=new HttpGet(uri);
    HttpResponse httpResponse=null;
    try {
      httpResponse=mHttpClient.execute(request);
      HttpEntity entity=httpResponse.getEntity();
      if (entity != null) {
        contentInput=entity.getContent();
      }
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + request.getURI());
      return null;
    }
  }
  if (contentInput != null) {
    return new BufferedInputStream(contentInput,4096);
  }
 else {
    return null;
  }
}
 

Example 48

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/.

Source file: EditTagActivity.java

  31 
vote

/** 
 * Populates the editor from extras in a given  {@link Intent}
 * @param intent the {@link Intent} to parse.
 * @return whether or not the {@link Intent} could be handled.
 */
private boolean buildFromSendIntent(final Intent intent){
  String type=intent.getType();
  if ("text/plain".equals(type)) {
    String text=getIntent().getStringExtra(Intent.EXTRA_TEXT);
    try {
      URL parsed=new URL(text);
      mRecord=new UriRecordEditInfo(text);
      refresh();
      return true;
    }
 catch (    MalformedURLException ex) {
      mRecord=new TextRecordEditInfo(text);
      refresh();
      return true;
    }
  }
 else   if ("text/x-vcard".equals(type)) {
    Uri stream=(Uri)getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
    if (stream != null) {
      RecordEditInfo editInfo=VCardRecord.editInfoForUri(stream);
      if (editInfo != null) {
        mRecord=editInfo;
        refresh();
        return true;
      }
    }
  }
  return false;
}
 

Example 49

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  31 
vote

/** 
 * Configures the POST Reporter. The given configuration <b>must</b> contain the  {@link PostReporter#ANDROLOG_REPORTER_POST_URL} property and it mustbe a valid  {@link URL}.
 * @see de.akquinet.android.androlog.reporter.Reporter#configure(java.util.Properties)
 */
@Override public void configure(Properties configuration){
  String u=configuration.getProperty(ANDROLOG_REPORTER_POST_URL);
  if (u == null) {
    Log.e(this,"The Property " + ANDROLOG_REPORTER_POST_URL + " is mandatory");
    return;
  }
  try {
    url=new URL(u);
  }
 catch (  MalformedURLException e) {
    Log.e(this,"The Property " + ANDROLOG_REPORTER_POST_URL + " is not a valid url",e);
  }
}
 

Example 50

From project anadix, under directory /anadix-tests/src/test/java/org/anadix/factories/.

Source file: URLSourceTest.java

  30 
vote

@BeforeMethod(alwaysRun=true) public void prepareFile() throws Exception {
  try {
    f=File.createTempFile("SourceFactoryTestFile",".html");
  }
 catch (  IOException ex) {
    f=new File("SourceFactoryTestFile.htlm");
  }
  f.deleteOnExit();
  PrintWriter pw=new PrintWriter(f);
  pw.print(sourceText);
  pw.flush();
  pw.close();
  try {
    url=new URL("file://" + f.getAbsolutePath());
  }
 catch (  IOException ex) {
    throw new Exception("Unable to instantiate URL: ",ex);
  }
}
 

Example 51

From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.

Source file: TileDownloadMapGenerator.java

  30 
vote

@Override final boolean executeJob(MapGeneratorJob mapGeneratorJob){
  try {
    getTilePath(mapGeneratorJob.tile,this.stringBuilder);
    InputStream inputStream=new URL(this.stringBuilder.toString()).openStream();
    this.decodedBitmap=BitmapFactory.decodeStream(inputStream);
    inputStream.close();
    if (this.decodedBitmap == null) {
      return false;
    }
    this.decodedBitmap.getPixels(this.pixelColors,0,Tile.TILE_SIZE,0,0,Tile.TILE_SIZE,Tile.TILE_SIZE);
    this.decodedBitmap.recycle();
    if (this.tileBitmap != null) {
      this.tileBitmap.setPixels(this.pixelColors,0,Tile.TILE_SIZE,0,0,Tile.TILE_SIZE,Tile.TILE_SIZE);
    }
    return true;
  }
 catch (  UnknownHostException e) {
    Logger.debug(e.getMessage());
    return false;
  }
catch (  IOException e) {
    Logger.exception(e);
    return false;
  }
}
 

Example 52

From project aerogear-controller, under directory /src/test/java/org/jboss/aerogear/controller/.

Source file: TypeNameExtractorTest.java

  29 
vote

@Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercased() throws NoSuchMethodException {
  Assert.assertEquals("urlClassLoader",extractor.nameFor(URLClassLoader.class));
  Assert.assertEquals("bigDecimal",extractor.nameFor(BigDecimal.class));
  Assert.assertEquals("string",extractor.nameFor(String.class));
  Assert.assertEquals("aClass",extractor.nameFor(AClass.class));
  Assert.assertEquals("url",extractor.nameFor(URL.class));
}
 

Example 53

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: UriFactoryImpl.java

  29 
vote

/** 
 * This method creates the  {@link URI} from the given argument.TODO! Need to check for path information in the URI in particular use of ../ to try to game the urls on amplafi servers.
 * @param uriStr {@link Object} from which {@link URI} has to be created. Allowed to be relative URI.
 * @param forceEncoding true if URI has to be encoded
 * @return {@link URI}
 */
public static URI createUri(Object uriStr,boolean forceEncoding){
  URI uri=null;
  if (uriStr == null || uriStr instanceof URI) {
    uri=(URI)uriStr;
  }
 else   if (uriStr instanceof URL) {
    try {
      uri=((URL)uriStr).toURI();
    }
 catch (    URISyntaxException e) {
    }
  }
 else {
    String uriString=uriStr.toString().trim();
    if (forceEncoding) {
      uriString=percentEncoding(uriString);
    }
    if (isNotBlank(uriString)) {
      try {
        uri=new URI(uriString);
      }
 catch (      URISyntaxException e) {
      }
    }
  }
  return uri;
}