Java Code Examples for java.net.URISyntaxException

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 android_packages_apps_Exchange, under directory /src/com/android/exchange/utility/.

Source file: UriCodec.java

  34 
vote

/** 
 * Throws if  {@code s} contains characters that are not letters, digits orin  {@code legal}.
 */
public static void validateSimple(String s,String legal) throws URISyntaxException {
  for (int i=0; i < s.length(); i++) {
    char ch=s.charAt(i);
    if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')|| legal.indexOf(ch) > -1)) {
      throw new URISyntaxException(s,"Illegal character",i);
    }
  }
}
 

Example 2

From project any23, under directory /service/src/main/java/org/apache/any23/servlet/.

Source file: Servlet.java

  31 
vote

private DocumentSource createHTTPDocumentSource(WebResponder responder,String uri,boolean report) throws IOException {
  try {
    if (!isValidURI(uri)) {
      throw new URISyntaxException(uri,"@@@");
    }
    return createHTTPDocumentSource(responder.getRunner().getHTTPClient(),uri);
  }
 catch (  URISyntaxException ex) {
    responder.sendError(400,"Invalid input URI " + uri,report);
    return null;
  }
}
 

Example 3

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

Source file: URISupport.java

  30 
vote

public static Map<String,String> parseQuery(String uri) throws URISyntaxException {
  try {
    Map<String,String> rc=new HashMap<String,String>();
    if (uri != null) {
      String[] parameters=uri.split("&");
      for (int i=0; i < parameters.length; i++) {
        int p=parameters[i].indexOf("=");
        if (p >= 0) {
          String name=URLDecoder.decode(parameters[i].substring(0,p),"UTF-8");
          String value=URLDecoder.decode(parameters[i].substring(p + 1),"UTF-8");
          rc.put(name,value);
        }
 else {
          rc.put(parameters[i],null);
        }
      }
    }
    return rc;
  }
 catch (  UnsupportedEncodingException e) {
    throw (URISyntaxException)new URISyntaxException(e.toString(),"Invalid encoding").initCause(e);
  }
}
 

Example 4

From project ANNIS, under directory /annis-service/src/main/java/annis/.

Source file: AnnisRunner.java

  30 
vote

private QueryData extractSaltIds(String saltIds){
  QueryData queryData=new QueryData();
  SaltURIs uris=new SaltURIs();
  for (  String id : saltIds.split("\\s")) {
    java.net.URI uri;
    try {
      uri=new java.net.URI(id);
      if (!"salt".equals(uri.getScheme()) || uri.getFragment() == null) {
        throw new URISyntaxException("not a salt id",uri.toString());
      }
    }
 catch (    URISyntaxException ex) {
      log.error(null,ex);
      continue;
    }
    uris.add(uri);
  }
  Set<String> corpusNames=new TreeSet<String>();
  List<QueryNode> pseudoNodes=new ArrayList<QueryNode>(uris.size());
  for (  java.net.URI u : uris) {
    pseudoNodes.add(new QueryNode());
    corpusNames.add(CommonHelper.getCorpusPath(u).get(0));
  }
  List<Long> corpusIDs=annisDao.mapCorpusNamesToIds(new LinkedList<String>(corpusNames));
  queryData.setCorpusList(corpusIDs);
  queryData.addAlternative(pseudoNodes);
  log.debug(uris.toString());
  queryData.addExtension(uris);
  return queryData;
}
 

Example 5

From project Aardvark, under directory /aardvark/src/main/test/gw/vark/it/.

Source file: ITUtil.java

  29 
vote

private static void init(){
  File projectRoot;
  String globalVersion;
  File assemblyDir;
  try {
    URL location=ITUtil.class.getProtectionDomain().getCodeSource().getLocation();
    File pomRoot=findPomRoot(new File(location.toURI()));
    projectRoot=pomRoot.getParentFile();
    globalVersion=getLocalVersion(pomRoot);
    File targetDir=new File(pomRoot,"target");
    if (!targetDir.exists()) {
      throw new IllegalStateException("probably haven't run 'package' yet");
    }
    assemblyDir=new File(new File(targetDir,"aardvark-" + globalVersion + "-bin"),"aardvark-" + globalVersion);
  }
 catch (  URISyntaxException e) {
    throw new RuntimeException(e);
  }
  _projectRoot=projectRoot;
  _globalVersion=globalVersion;
  _assemblyDir=assemblyDir;
}
 

Example 6

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.

Source file: JsonConfigLoader.java

  29 
vote

/** 
 * Load the configuration from a URL.  This understands any URL that the JVM has a protocol handler for, and also "classpath:" URLs. 
 * @return the configuration or null
 * @param urlString the URL for the config file
 * @throws URISyntaxException 
 * @throws MalformedURLException 
 */
public C loadConfigurationFromUrl(String urlString) throws ConfigurationException {
  InputStream is=null;
  try {
    URI uri=new URI(urlString);
    if (uri.getScheme().equals("classpath")) {
      String path=uri.getSchemeSpecificPart();
      LOG.debug("Loading configuration from classpath resource '" + path + "'");
      is=JsonConfigLoader.class.getClassLoader().getResourceAsStream(path);
      if (is == null) {
        throw new IllegalArgumentException("Cannot locate resource '" + path + "' on the classpath");
      }
    }
 else {
      LOG.debug("Loading configuration from url '" + urlString + "'");
      is=uri.toURL().openStream();
    }
    return readConfiguration(is);
  }
 catch (  URISyntaxException ex) {
    throw new IllegalArgumentException("Invalid urlString '" + urlString + "'",ex);
  }
catch (  MalformedURLException ex) {
    throw new IllegalArgumentException("Invalid urlString '" + urlString + "'",ex);
  }
catch (  IOException ex) {
    throw new ConfigurationException("Cannot open URL input stream",ex);
  }
 finally {
    closeQuietly(is);
  }
}
 

Example 7

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

Source file: ModelInstrumentation.java

  29 
vote

private String getOutputDirectory(CtClass modelClass) throws NotFoundException, URISyntaxException {
  URL u=modelClass.getURL();
  String file=u.getFile();
  file=file.substring(0,file.length() - 6);
  String className=modelClass.getName();
  className=className.replace(".","/");
  return file.substring(0,file.indexOf(className));
}
 

Example 8

From project adbcj, under directory /api/src/main/java/org/adbcj/.

Source file: ConnectionManagerProvider.java

  29 
vote

public static ConnectionManager createConnectionManager(String url,String username,String password,Properties properties) throws DbException {
  if (url == null) {
    throw new IllegalArgumentException("Connection url can not be null");
  }
  try {
    URI uri=new URI(url);
    String adbcjProtocol=uri.getScheme();
    if (!ADBCJ_PROTOCOL.equals(adbcjProtocol)) {
      throw new DbException("Invalid connection URL: " + url);
    }
    URI driverUri=new URI(uri.getSchemeSpecificPart());
    String protocol=driverUri.getScheme();
    ServiceLoader<ConnectionManagerFactory> serviceLoader=ServiceLoader.load(ConnectionManagerFactory.class);
    for (    ConnectionManagerFactory factory : serviceLoader) {
      if (factory.canHandle(protocol)) {
        return factory.createConnectionManager(url,username,password,properties);
      }
    }
    throw new DbException("Could not find ConnectionManagerFactory for protocol '" + protocol + "'");
  }
 catch (  URISyntaxException e) {
    throw new DbException("Invalid connection URL: " + url);
  }
}
 

Example 9

From project aether-core, under directory /aether-util/src/main/java/org/eclipse/aether/util/repository/layout/.

Source file: MavenDefaultLayout.java

  29 
vote

private URI toUri(String path){
  try {
    return new URI(null,null,path,null);
  }
 catch (  URISyntaxException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 10

From project agit, under directory /agit/src/main/java/com/madgag/agit/.

Source file: CloneLauncherActivity.java

  29 
vote

public void onClick(View v){
  URIish uri;
  try {
    uri=getCloneUri();
  }
 catch (  URISyntaxException e) {
    Toast.makeText(v.getContext(),"bad dog",10).show();
    return;
  }
  File checkoutLocation=getTargetFolder();
  boolean bare=bareRepoCheckbox.isChecked();
  try {
    launchClone(uri,checkoutLocation,bare);
  }
 catch (  Exception e) {
    Toast.makeText(v.getContext(),"ARRG: " + e,10).show();
    e.printStackTrace();
  }
}
 

Example 11

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.

Source file: HttpBuilder.java

  29 
vote

private <T>HttpResult<T> doGet(Type target){
  try {
    URI path=createPath(address,query());
    HttpGet get=new HttpGet(path);
    return doRequest(get,target);
  }
 catch (  URISyntaxException e) {
    Log.e(Constants.TAG,"Couldn't create path",e);
    return error();
  }
}
 

Example 12

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

Source file: TestConfigAssertions.java

  29 
vote

@LegacyConfig(value="home-page-url",replacedBy="home-page") public PersonConfig setHomePageUrl(URL homePage){
  try {
    this.homePage=homePage.toURI();
    return this;
  }
 catch (  URISyntaxException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 13

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

Source file: FSBlob.java

  29 
vote

static URI validateId(URI blobId) throws UnsupportedIdException {
  if (blobId == null)   throw new NullPointerException("Id cannot be null");
  if (!blobId.getScheme().equalsIgnoreCase(scheme))   throw new UnsupportedIdException(blobId,"Id must be in " + scheme + " scheme");
  String path=blobId.getRawSchemeSpecificPart();
  if (path.startsWith("/"))   throw new UnsupportedIdException(blobId,"Id must specify a relative path");
  try {
    URI tmp=new URI(scheme + ":/" + path);
    String nPath=tmp.normalize().getRawSchemeSpecificPart().substring(1);
    if (nPath.equals("..") || nPath.startsWith("../"))     throw new UnsupportedIdException(blobId,"Id cannot be outside top-level directory");
    if (nPath.endsWith("/"))     throw new UnsupportedIdException(blobId,"Id cannot specify a directory");
    return new URI(scheme + ":" + nPath);
  }
 catch (  URISyntaxException wontHappen) {
    throw new Error(wontHappen);
  }
}
 

Example 14

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

Source file: AuthzEndpoint.java

  29 
vote

@GET public Response authorize(@Context HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
  OAuthAuthzRequest oauthRequest=null;
  OAuthIssuerImpl oauthIssuerImpl=new OAuthIssuerImpl(new MD5Generator());
  try {
    oauthRequest=new OAuthAuthzRequest(request);
    String responseType=oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
    OAuthASResponse.OAuthAuthorizationResponseBuilder builder=OAuthASResponse.authorizationResponse(request,HttpServletResponse.SC_FOUND);
    if (responseType.equals(ResponseType.CODE.toString())) {
      builder.setCode(oauthIssuerImpl.authorizationCode());
    }
    if (responseType.equals(ResponseType.TOKEN.toString())) {
      builder.setAccessToken(oauthIssuerImpl.accessToken());
      builder.setExpiresIn(3600l);
    }
    String redirectURI=oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
    final OAuthResponse response=builder.location(redirectURI).buildQueryMessage();
    URI url=new URI(response.getLocationUri());
    return Response.status(response.getResponseStatus()).location(url).build();
  }
 catch (  OAuthProblemException e) {
    final Response.ResponseBuilder responseBuilder=Response.status(HttpServletResponse.SC_FOUND);
    String redirectUri=e.getRedirectUri();
    if (OAuthUtils.isEmpty(redirectUri)) {
      throw new WebApplicationException(responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build());
    }
    final OAuthResponse response=OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
    final URI location=new URI(response.getLocationUri());
    return responseBuilder.location(location).build();
  }
}
 

Example 15

From project ambrose, under directory /common/src/main/java/azkaban/common/utils/.

Source file: Props.java

  29 
vote

public URI getUri(String name){
  if (containsKey(name)) {
    try {
      return new URI(get(name));
    }
 catch (    URISyntaxException e) {
      throw new IllegalArgumentException(e.getMessage());
    }
  }
 else {
    throw new UndefinedPropertyException("Missing required property '" + name + "'");
  }
}
 

Example 16

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

Source file: URIUtils.java

  29 
vote

/** 
 * Constructs a  {@link URI} using all the parameters. This should beused instead of {@link URI#URI(String,String,String,int,String,String,String)}or any of the other URI multi-argument URI constructors.
 * @param scheme Scheme name
 * @param host Host name
 * @param port Port number
 * @param path Path
 * @param query Query
 * @param fragment Fragment
 * @throws URISyntaxException If both a scheme and a path are given but the path is relative, if the URI string constructed from the given components violates RFC&nbsp;2396, or if the authority component of the string is present but cannot be parsed as a server-based authority
 */
public static URI createURI(final String scheme,final String host,int port,final String path,final String query,final String fragment) throws URISyntaxException {
  StringBuilder buffer=new StringBuilder();
  if (host != null) {
    if (scheme != null) {
      buffer.append(scheme);
      buffer.append("://");
    }
    buffer.append(host);
    if (port > 0) {
      buffer.append(':');
      buffer.append(port);
    }
  }
  if (path == null || !path.startsWith("/")) {
    buffer.append('/');
  }
  if (path != null) {
    buffer.append(path);
  }
  if (query != null) {
    buffer.append('?');
    buffer.append(query);
  }
  if (fragment != null) {
    buffer.append('#');
    buffer.append(fragment);
  }
  return new URI(buffer.toString());
}
 

Example 17

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

Source file: UriFactoryImpl.java

  29 
vote

/** 
 * suitable for namespacing
 * @return the uri with relative schema ( ex. //facebook.com/path/to/stuff?query )
 */
public static URI createNamespaceUri(Object uriStr){
  URI temp=createUriWithOptions(uriStr,true,true);
  try {
    URI namesUri=new URI(null,temp.getUserInfo(),temp.getHost(),-1,temp.getPath(),temp.getQuery(),temp.getFragment());
    return namesUri;
  }
 catch (  URISyntaxException e) {
    return null;
  }
}
 

Example 18

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

Source file: FontControl.java

  29 
vote

public void downloadFont(String font) throws InstallException {
  log.debug("Download font " + font);
  URI source=null;
  try {
    source=new URI(FONT_DOWNLOAD_URL + font);
  }
 catch (  URISyntaxException use) {
    log.error("Invalid URI",use);
    throw new InstallException("Error downloading font");
  }
  File target=new File(SharedConstants.FONT_DIR,font);
  GenericFileDownloader downloader=new GenericFileDownloader();
  downloader.downloadFileInBackground(source,target,"font");
}
 

Example 19

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

Source file: HttpConnector.java

  29 
vote

public int headRequest(String Uri) throws RestConnectionException {
  initialize();
  HttpHead request=new HttpHead();
  try {
    requestUri=new URI(Uri);
  }
 catch (  URISyntaxException e) {
    e.printStackTrace();
  }
  setCredentials();
  request.setURI(requestUri);
  Log.d("HEAD Request URL",Uri);
  try {
    response=client.execute(request);
    Log.d("Response status",response.getStatusLine().toString());
    return response.getStatusLine().getStatusCode();
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
    throw new RestConnectionException(e);
  }
  return -1;
}
 

Example 20

From project android-rackspacecloud, under directory /src/com/rackspace/cloud/files/api/client/.

Source file: ContainerManager.java

  29 
vote

private String getSafeURL(String badURL,String name){
  URI uri=null;
  try {
    uri=new URI("https",badURL.substring(8),"/" + name.toString() + "/","");
  }
 catch (  URISyntaxException e1) {
    e1.printStackTrace();
  }
  String url=null;
  try {
    url=uri.toURL().toString();
  }
 catch (  MalformedURLException e1) {
    e1.printStackTrace();
  }
  return url.substring(0,url.length() - 1);
}
 

Example 21

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/preference/activity/.

Source file: SynchronizationSettingsActivity.java

  29 
vote

private boolean verifyUrl(int color){
  try {
    new URI(mUrlTextbox.getText().toString());
    mUrlTextbox.setTextColor(color);
    return true;
  }
 catch (  URISyntaxException e) {
    mUrlTextbox.setTextColor(Color.RED);
    return false;
  }
}
 

Example 22

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/signature/.

Source file: SignatureBaseString.java

  29 
vote

public String normalizeRequestUrl() throws URISyntaxException {
  URI uri=new URI(request.getRequestUrl());
  String scheme=uri.getScheme().toLowerCase();
  String authority=uri.getAuthority().toLowerCase();
  boolean dropPort=(scheme.equals("http") && uri.getPort() == 80) || (scheme.equals("https") && uri.getPort() == 443);
  if (dropPort) {
    int index=authority.lastIndexOf(":");
    if (index >= 0) {
      authority=authority.substring(0,index);
    }
  }
  String path=uri.getRawPath();
  if (path == null || path.length() <= 0) {
    path="/";
  }
  return scheme + "://" + authority+ path;
}
 

Example 23

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

Source file: NowPlayingPollerThread.java

  29 
vote

private byte[] download(String pathToDownload) throws IOException, URISyntaxException {
  Connection connection;
  final Host host=HostFactory.host;
  if (host != null) {
    connection=Connection.getInstance(host.addr,host.port);
    connection.setAuth(host.user,host.pass);
  }
 else {
    connection=Connection.getInstance(null,0);
  }
  return connection.download(pathToDownload);
}
 

Example 24

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: Client.java

  29 
vote

public synchronized Object connect(ID remote,Object data,int timeout) throws ECFException {
  Log.d(TAG,"connect(" + remote + ","+ data+ ","+ timeout+ ")");
  if (socket != null)   throw new ECFException(Messages.Client_Already_Connected);
  URI anURI=null;
  try {
    anURI=new URI(remote.getName());
  }
 catch (  final URISyntaxException e) {
    throw new ECFException(Messages.Client_Invalid_URI + remote,e);
  }
  SocketFactory fact=SocketFactory.getSocketFactory();
  if (fact == null)   fact=SocketFactory.getDefaultSocketFactory();
  ConnectResultMessage res=null;
  try {
    keepAlive=timeout;
    final Socket s=fact.createSocket(anURI.getHost(),anURI.getPort(),keepAlive);
    setSocketOptions(s);
    setSocket(s);
    outputStream=new ObjectOutputStream(s.getOutputStream());
    outputStream.flush();
    inputStream=new ObjectInputStream(s.getInputStream());
    debug("connect;" + anURI);
    send(new ConnectRequestMessage(anURI,(Serializable)data));
    res=(ConnectResultMessage)readObject();
  }
 catch (  final Exception e) {
    throw new ECFException("Exception during connection to " + remote.getName(),e);
  }
  debug("connect;rcv:" + res);
  setupThreads();
  final Object ret=res.getData();
  debug("connect;returning:" + ret);
  return ret;
}
 

Example 25

From project android_5, under directory /src/aarddict/.

Source file: LookupWord.java

  29 
vote

public static LookupWord splitWord(String word){
  if (word == null || word.equals("") || word.equals("#")) {
    return new LookupWord();
  }
  try {
    return splitWordAsURI(word);
  }
 catch (  URISyntaxException e) {
    Log.d(TAG,"Word is not proper URI: " + word);
    return splitWordSimple(word);
  }
}
 

Example 26

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

Source file: DefaultTypeAdapters.java

  29 
vote

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

Example 27

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

Source file: OAuthClient.java

  29 
vote

/** 
 * Get a fresh request token from the service provider.
 * @param accessor should contain a consumer that contains a non-null consumerKey and consumerSecret. Also, accessor.consumer.serviceProvider.requestTokenURL should be the URL (determined by the service provider) for getting a request token.
 * @param httpMethod typically OAuthMessage.POST or OAuthMessage.GET, or null to use the default method.
 * @param parameters additional parameters for this request, or null to indicate that there are no additional parameters.
 * @throws OAuthProblemException the HTTP response status code was not 200 (OK)
 */
public void getRequestToken(OAuthAccessor accessor,String httpMethod,Collection<? extends Map.Entry> parameters) throws IOException, OAuthException, URISyntaxException {
  accessor.accessToken=null;
  accessor.tokenSecret=null;
{
    Object accessorSecret=accessor.getProperty(OAuthConsumer.ACCESSOR_SECRET);
    if (accessorSecret != null) {
      List<Map.Entry> p=(parameters == null) ? new ArrayList<Map.Entry>(1) : new ArrayList<Map.Entry>(parameters);
      p.add(new OAuth.Parameter("oauth_accessor_secret",accessorSecret.toString()));
      parameters=p;
    }
  }
  OAuthMessage response=invoke(accessor,httpMethod,accessor.consumer.serviceProvider.requestTokenURL,parameters);
  accessor.requestToken=response.getParameter(OAuth.OAUTH_TOKEN);
  accessor.tokenSecret=response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
  response.requireParameters(OAuth.OAUTH_TOKEN,OAuth.OAUTH_TOKEN_SECRET);
}
 

Example 28

From project android_packages_apps_cmparts, under directory /src/com/cyanogenmod/cmparts/utils/.

Source file: ShortcutPickHelper.java

  29 
vote

public String getFriendlyNameForUri(String uri){
  if (uri == null) {
    return null;
  }
  try {
    Intent intent=Intent.parseUri(uri,0);
    if (Intent.ACTION_MAIN.equals(intent.getAction())) {
      return getFriendlyActivityName(intent,false);
    }
    return getFriendlyShortcutName(intent);
  }
 catch (  URISyntaxException e) {
  }
  return uri;
}
 

Example 29

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

Source file: UriTexture.java

  29 
vote

public static String writeHttpDataInDirectory(Context context,String uri,String path){
  long crc64=Utils.Crc64Long(uri);
  if (!isCached(crc64,1024)) {
    Bitmap bitmap;
    try {
      bitmap=UriTexture.createFromUri(context,uri,1024,1024,crc64,null);
    }
 catch (    OutOfMemoryError e) {
      return null;
    }
catch (    IOException e) {
      return null;
    }
catch (    URISyntaxException e) {
      return null;
    }
    bitmap.recycle();
  }
  String fileString=createFilePathFromCrc64(crc64,1024);
  try {
    File file=new File(fileString);
    if (file.exists()) {
      String newPath=path + (path.endsWith("/") ? "" : "/") + crc64+ ".jpg";
      File newFile=new File(newPath);
      Utils.Copy(file,newFile);
      return newPath;
    }
    return null;
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 30

From project android_packages_apps_TouchWiz30Launcher, under directory /src/com/sec/android/app/twlauncher/.

Source file: LauncherProvider.java

  29 
vote

private boolean addShortcut(SQLiteDatabase sqlitedatabase,ContentValues contentvalues,TypedArray typedarray){
  label0: {
    Resources resources=mContext.getResources();
    int i=typedarray.getResourceId(7,0);
    int j=typedarray.getResourceId(8,0);
    String s=null;
    boolean flag;
    Intent intent;
    try {
      s=typedarray.getString(9);
      intent=Intent.parseUri(s,0);
    }
 catch (    URISyntaxException urisyntaxexception) {
      Log.w("Launcher.LauncherProvider",(new StringBuilder()).append("Shortcut has malformed uri: ").append(s).toString());
      urisyntaxexception.printStackTrace();
      flag=false;
      if (false)       ;
 else       break label0;
    }
    if (i == 0 || j == 0) {
      Log.w("Launcher.LauncherProvider","Shortcut is missing title or icon resource ID");
      flag=false;
    }
 else {
      intent.setFlags(0x10000000);
      contentvalues.put("intent",intent.toUri(0));
      contentvalues.put("title",resources.getString(j));
      contentvalues.put("itemType",Integer.valueOf(1));
      contentvalues.put("spanX",Integer.valueOf(1));
      contentvalues.put("spanY",Integer.valueOf(1));
      contentvalues.put("iconType",Integer.valueOf(0));
      contentvalues.put("iconPackage",mContext.getPackageName());
      contentvalues.put("iconResource",mContext.getResources().getResourceName(i));
      sqlitedatabase.insert("favorites",null,contentvalues);
      flag=true;
    }
  }
  return flag;
}
 

Example 31

From project anode, under directory /app/src/org/meshpoint/anode/util/.

Source file: ArgProcessor.java

  29 
vote

/** 
 * Process the text string
 * @return the processed string, with downloaded resource names substituted
 */
public String processString(){
  if (extras != null) {
    try {
      Set<String> keys=extras.keySet();
      for (      String key : keys) {
        if (key.startsWith(GET_PREFIX)) {
          String rawUri=extras.getString(key);
          String rawKey=key.substring(GET_PREFIX.length());
          URI uri=new URI(rawUri);
          String filename=ModuleUtils.getResourceUriHash(rawUri);
          uriMap.put(rawKey,uri);
          filenameMap.put(rawKey,filename);
        }
      }
    }
 catch (    URISyntaxException e) {
      Log.v(TAG,"process exception: aborting; exception: " + e);
      return null;
    }
    for (    String key : uriMap.keySet()) {
      try {
        ModuleUtils.getResource(uriMap.get(key),filenameMap.get(key));
      }
 catch (      IOException e) {
        Log.v(TAG,"process exception: aborting; exception: " + e + "; resource = "+ uriMap.get(key).toString());
        return null;
      }
    }
    for (    String key : filenameMap.keySet()) {
      text=text.replace("%" + key,Constants.RESOURCE_DIR + '/' + filenameMap.get(key));
    }
  }
  return text;
}
 

Example 32

From project ant4eclipse, under directory /org.ant4eclipse.lib.platform/src/org/ant4eclipse/lib/platform/internal/model/resource/workspaceregistry/.

Source file: LocationFileParser.java

  29 
vote

/** 
 * Reads the given location file and returns the location that is stored inside the location as a File. <p> The file returned by this method may not exist, no check is performed here, thus you have to check for the existence of the file (and propably for the correct type too). </p> <p> You might want to use  {@link #getProjectDirectory(File)} to receive a pointer to a valid, existing Eclipse projectfile </p>
 * @param locationfile The file which contains the desired data.
 * @return The location stored in the .location file (typically the root-folder of an external project) or null if nolocation could be read from the .location file
 * @throws IOException
 */
static final File readLocation(File locationfile) throws IOException {
  Assure.isFile("locationfile",locationfile);
  ChunkyFile cf=new ChunkyFile(locationfile);
  if (cf.getChunkCount() == 1) {
    byte[] data=cf.getChunk(0);
    DataInputStream datain=new DataInputStream(new ByteArrayInputStream(data));
    String location=datain.readUTF();
    File file=null;
    if (location.length() > 0) {
      if (location.startsWith(URI_PREFIX)) {
        URI uri=URI.create(location.substring(URI_PREFIX.length()));
        if (!uri.getScheme().startsWith("file")) {
          A4ELogging.debug("LocationFileParser.readLocation(): the stored location uri '%s' is not a file-uri",uri);
        }
 else {
          file=new File(uri);
        }
      }
 else {
        try {
          file=new File(new URI(location));
        }
 catch (        URISyntaxException ex) {
          A4ELogging.debug("LocationFileParser.readLocation(): the location '%s' will be interpreted as a path",location);
          file=new File(location);
        }
catch (        IllegalArgumentException ex) {
          A4ELogging.debug("LocationFileParser.readLocation(): the location '%s' will be interpreted as a path",location);
          file=new File(location);
        }
      }
      return file;
    }
  }
 else {
    A4ELogging.warn("the file '%s' contains %d chunks instead of a single one",locationfile,Integer.valueOf(cf.getChunkCount()));
  }
  return null;
}
 

Example 33

From project apb, under directory /modules/apb-base/src/apb/utils/.

Source file: SchemaUtils.java

  29 
vote

private static void processLocation(URL doc,Queue<File> pending,String location){
  try {
    URI locUri=new URI(location);
    if (locUri.isAbsolute()) {
      return;
    }
    locUri=doc.toURI().resolve(locUri);
    pending.add(new File(locUri));
  }
 catch (  URISyntaxException e) {
    logException(e);
  }
}
 

Example 34

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/server/.

Source file: AndroidNativeDriver.java

  29 
vote

/** 
 * Takes a string that looks like a URL and performs an operation based on the contents of the URL. Currently only starting activities is supported. <p> Supported URL type follows: <ul> <li> {@code and-activity://<Activity class name>}<br> start specified activity </ul>
 */
@Override public void get(String url){
  URI dest;
  try {
    dest=new URI(url);
  }
 catch (  URISyntaxException exception) {
    throw new IllegalArgumentException(exception);
  }
  if (!"and-activity".equals(dest.getScheme())) {
    throw new WebDriverException("Unrecognized scheme in URI: " + dest.toString());
  }
 else   if (!Strings.isNullOrEmpty(dest.getPath())) {
    throw new WebDriverException("Unrecognized path in URI: " + dest.toString());
  }
  Class<?> clazz;
  try {
    clazz=Class.forName(dest.getAuthority());
  }
 catch (  ClassNotFoundException exception) {
    throw new WebDriverException("The specified Activity class does not exist: " + dest.getAuthority(),exception);
  }
  for (  NameValuePair nvp : URLEncodedUtils.parse(dest,"utf8")) {
    if ("id".equals(nvp.getName())) {
      throw new WebDriverException("Moving to the specified activity is not supported.");
    }
  }
  startActivity(clazz);
}
 

Example 35

From project Archimedes, under directory /br.org.archimedes.core/src/br/org/archimedes/rcp/.

Source file: AbstractFileLocatorActivator.java

  29 
vote

/** 
 * @param path The path to the file relative to this plugin's root
 * @param bundle The bundle containing information as to where is this plugin
 * @return A File pointing to the system file or null if the activator is not set or could notfind the file (this is not a regular RCP run... happens for non-plugins tests)
 * @throws IOException Thrown if there is an error while reading the file
 */
public static File resolveFile(String path,Bundle bundle) throws IOException {
  File file=null;
  if (bundle != null) {
    URL url=FileLocator.find(bundle,new Path(path),Collections.emptyMap());
    if (url != null) {
      URL fileUrl=FileLocator.toFileURL(url);
      try {
        file=new File(fileUrl.toURI());
      }
 catch (      URISyntaxException e) {
        e.printStackTrace();
      }
    }
  }
  return file;
}
 

Example 36

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/extract/.

Source file: RealCDXExtractorOutput.java

  29 
vote

private String resolve(String context,String spec){
  try {
    URL cUrl=new URL(context);
    URL resolved=new URL(cUrl,spec);
    return resolved.toURI().toASCIIString();
  }
 catch (  URISyntaxException e) {
  }
catch (  MalformedURLException e) {
  }
catch (  NullPointerException e) {
  }
  return spec;
}
 

Example 37

From project arquillian-container-openshift, under directory /openshift-express/src/main/java/org/jboss/arquillian/container/openshift/express/.

Source file: OpenShiftExpressConfiguration.java

  29 
vote

/** 
 * @return the rootContextUrl
 */
public String getRootContextUrl(){
  try {
    return constructRootContext().toURI().toString();
  }
 catch (  MalformedURLException e) {
    throw new IllegalArgumentException("Application name, namespace and Libra Domain does not represent a valid URL",e);
  }
catch (  URISyntaxException e) {
    throw new RuntimeException("Application name, namespace and Libra Domain does not represent a valid URL",e);
  }
}
 

Example 38

From project arquillian-container-tomcat, under directory /tomcat-common/src/main/java/org/jboss/arquillian/container/tomcat/.

Source file: CommonTomcatConfiguration.java

  29 
vote

@Override public void validate() throws ConfigurationException {
  Validate.notNullOrEmpty(bindAddress,"Bind address must not be null or empty");
  Validate.isInRange(jmxPort,0,MAX_PORT,"JMX port must be in interval ]" + MIN_PORT + ","+ MAX_PORT+ "[, but was "+ jmxPort);
  try {
    this.setJmxUri(createJmxUri());
    this.setManagerUrl(createManagerUrl());
  }
 catch (  URISyntaxException ex) {
    throw new ConfigurationException("JMX URI is not valid, please provide ",ex);
  }
catch (  MalformedURLException e) {
    throw new ConfigurationException("JMX URI is not valid",e);
  }
}
 

Example 39

From project arquillian-core, under directory /container/test-impl-base/src/main/java/org/jboss/arquillian/container/test/impl/enricher/resource/.

Source file: URIResourceProvider.java

  29 
vote

@Override public Object lookup(ArquillianResource resource,Annotation... qualifiers){
  Object object=super.lookup(resource,qualifiers);
  if (object == null) {
    return object;
  }
  try {
    return ((URL)object).toURI();
  }
 catch (  URISyntaxException e) {
    throw new RuntimeException("Could not convert URL to URI: " + object,e);
  }
}
 

Example 40

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/data/provider/.

Source file: ResourceProvider.java

  29 
vote

private boolean existsInGivenLocation(String location){
  try {
    final URL url=load(location);
    if (url == null) {
      return false;
    }
  }
 catch (  URISyntaxException e) {
    throw new InvalidResourceLocation("Unable to open resource file in " + location,e);
  }
  return true;
}
 

Example 41

From project arquillian-extension-seam2, under directory /src/main/java/org/jboss/arquillian/seam2/configuration/.

Source file: ConfigurationTypeConverter.java

  29 
vote

/** 
 * A helper converting method. Converts string to a class of given type
 * @param value String value to be converted
 * @param to Type of desired value
 * @param < T > Type of returned value
 * @return Value converted to a appropriate type
 */
public <T>T convert(String value,Class<T> to){
  if (String.class.equals(to)) {
    return to.cast(value);
  }
 else   if (Integer.class.equals(to)) {
    return to.cast(Integer.valueOf(value));
  }
 else   if (Double.class.equals(to)) {
    return to.cast(Double.valueOf(value));
  }
 else   if (Long.class.equals(to)) {
    return to.cast(Long.valueOf(value));
  }
 else   if (Boolean.class.equals(to)) {
    return to.cast(Boolean.valueOf(value));
  }
 else   if (URL.class.equals(to)) {
    try {
      return to.cast(new URI(value).toURL());
    }
 catch (    MalformedURLException e) {
      throw new IllegalArgumentException("Unable to convert value " + value + " to URL",e);
    }
catch (    URISyntaxException e) {
      throw new IllegalArgumentException("Unable to convert value " + value + " to URL",e);
    }
  }
 else   if (URI.class.equals(to)) {
    try {
      return to.cast(new URI(value));
    }
 catch (    URISyntaxException e) {
      throw new IllegalArgumentException("Unable to convert value " + value + " to URL",e);
    }
  }
  throw new IllegalArgumentException("Unable to convert value " + value + "to a class: "+ to.getName());
}
 

Example 42

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-drone/src/main/java/org/jboss/arquillian/ajocado/drone/configuration/.

Source file: ArquillianGrapheneConfiguration.java

  29 
vote

private void initContextRoot(){
  try {
    this.contextRoot=new URI("http://localhost:8080").toURL();
  }
 catch (  MalformedURLException e) {
    throw new IllegalStateException("Unable to set default value for contextRoot",e);
  }
catch (  URISyntaxException e) {
    throw new IllegalStateException("Unable to set default value for contextRoot",e);
  }
}
 

Example 43

From project arquillian_deprecated, under directory /extensions/drone/src/main/java/org/jboss/arquillian/drone/configuration/.

Source file: ArquillianAjocadoConfiguration.java

  29 
vote

private void initContextRoot(){
  try {
    this.contextRoot=new URI("http://localhost:8080").toURL();
  }
 catch (  MalformedURLException e) {
    throw new IllegalStateException("Unable to set default value for contextRoot",e);
  }
catch (  URISyntaxException e) {
    throw new IllegalStateException("Unable to set default value for contextRoot",e);
  }
}
 

Example 44

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/gradle/.

Source file: GradleInitScriptWriter.java

  29 
vote

/** 
 * Generate the init script from the Artifactory URL.
 * @return The generated script.
 */
public String generateInitScript() throws URISyntaxException, IOException, InterruptedException {
  StringBuilder initScript=new StringBuilder();
  InputStream templateStream=getClass().getResourceAsStream("/initscripttemplate.gradle");
  String templateAsString=IOUtils.toString(templateStream,Charsets.UTF_8.name());
  File localGradleExtractorJar=Which.jarFile(getClass().getResource("/initscripttemplate.gradle"));
  FilePath dependencyDir=PluginDependencyHelper.getActualDependencyDirectory(build,localGradleExtractorJar);
  String absoluteDependencyDirPath=dependencyDir.getRemote();
  absoluteDependencyDirPath=absoluteDependencyDirPath.replace("\\","/");
  String str=templateAsString.replace("${pluginLibDir}",absoluteDependencyDirPath);
  initScript.append(str);
  return initScript.toString();
}
 

Example 45

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/servlet/.

Source file: ScriptRunnerSessionServlet.java

  29 
vote

private boolean loginIfNot(HttpServletRequest request,HttpServletResponse response) throws ServletException {
  if (userManager.getRemoteUsername(request) == null) {
    try {
      URI currentUri=new URI(request.getRequestURI());
      URI loginUri=loginUriProvider.getLoginUri(currentUri);
      response.sendRedirect(loginUri.toASCIIString());
    }
 catch (    URISyntaxException e) {
      throw new ServletException(e);
    }
catch (    IOException e) {
      throw new ServletException(e);
    }
    return true;
  }
  return false;
}
 

Example 46

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-sync/src/main/java/fm/audiobox/sync/stream/.

Source file: SocketClient.java

  29 
vote

/** 
 * Connects to Socket server and returns  {@code true} it everithing went ok
 * @return boolean
 */
public void connect() throws ServiceException {
  log.info("Trying to connect to server");
  if (this.isConnected()) {
    this.disconnect();
    this.wasConnected=false;
  }
  if (this.audiobox.getUser() != null) {
    String urlStr=this.getServerUrl();
    URL url=null;
    try {
      url=new URL(urlStr);
      log.info("Server will be " + url.toURI().toString());
    }
 catch (    MalformedURLException e) {
      log.error("Invalid url found");
      throw new ServiceException("No valid URL for server found");
    }
catch (    URISyntaxException e) {
      log.error("Invalid url found");
      throw new ServiceException("No valid URL for server found");
    }
    this.socket=new SocketIO(url);
    this.socket.addHeader(IConnector.X_AUTH_TOKEN_HEADER,this.audiobox.getUser().getAuthToken());
    this.socket.connect(this);
  }
 else {
    this.wasConnected=true;
  }
}
 

Example 47

From project avro, under directory /lang/java/compiler/src/test/java/org/apache/avro/compiler/.

Source file: TestSpecificCompiler.java

  29 
vote

@Test public void testCanReadTemplateFilesOnTheFilesystem() throws IOException, URISyntaxException {
  String schemaSrcPath="src/test/resources/simple_record.avsc";
  String velocityTemplateDir="src/main/velocity/org/apache/avro/compiler/specific/templates/java/classic/";
  File src=new File(schemaSrcPath);
  Schema.Parser parser=new Schema.Parser();
  Schema schema=parser.parse(src);
  SpecificCompiler compiler=new SpecificCompiler(schema);
  compiler.setTemplateDir(velocityTemplateDir);
  compiler.setStringType(StringType.CharSequence);
  File outputDir=AvroTestUtil.tempDirectory(getClass(),"specific-output");
  compiler.compileToDestination(src,outputDir);
  assertTrue(new File(outputDir,"SimpleRecord.java").exists());
}
 

Example 48

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/.

Source file: AWSClientFactory.java

  29 
vote

private static ClientConfiguration createClientConfiguration(String secureEndpoint){
  ClientConfiguration config=new ClientConfiguration();
  AwsClientUtils clientUtils=new AwsClientUtils();
  config.setUserAgent(clientUtils.formUserAgentString("AWS-Toolkit-For-Eclipse",AwsToolkitCore.getDefault()));
  AwsToolkitCore plugin=AwsToolkitCore.getDefault();
  if (plugin != null) {
    IProxyService proxyService=AwsToolkitCore.getDefault().getProxyService();
    if (proxyService.isProxiesEnabled()) {
      try {
        IProxyData[] proxyData;
        proxyData=proxyService.select(new URI(secureEndpoint));
        if (proxyData.length > 0) {
          config.setProxyHost(proxyData[0].getHost());
          config.setProxyPort(proxyData[0].getPort());
          if (proxyData[0].isRequiresAuthentication()) {
            config.setProxyUsername(proxyData[0].getUserId());
            config.setProxyPassword(proxyData[0].getPassword());
          }
        }
      }
 catch (      URISyntaxException e) {
        plugin.getLog().log(new Status(Status.ERROR,AwsToolkitCore.PLUGIN_ID,e.getMessage(),e));
      }
    }
  }
  return config;
}
 

Example 49

From project azkaban, under directory /azkaban-common/src/java/azkaban/common/utils/.

Source file: Props.java

  29 
vote

public URI getUri(String name){
  if (containsKey(name)) {
    try {
      return new URI(get(name));
    }
 catch (    URISyntaxException e) {
      throw new IllegalArgumentException(e.getMessage());
    }
  }
 else {
    throw new UndefinedPropertyException("Missing required property '" + name + "'");
  }
}
 

Example 50

From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.

Source file: FederatedLoginManager.java

  29 
vote

protected void setAudienceUris(SamlTokenValidator validator) throws FederationException {
  String[] audienceUris=FederatedConfiguration.getInstance().getAudienceUris();
  for (  String audienceUriStr : audienceUris) {
    try {
      validator.getAudienceUris().add(new URI(audienceUriStr));
    }
 catch (    URISyntaxException e) {
      throw new FederationException("Federated Login Configuration failure: Invalid Audience URI",e);
    }
  }
}
 

Example 51

From project azure4j-blog-samples, under directory /Log4J/CustomLog4JAppender/src/com/persistent/azure/logger/.

Source file: AzureTableStorageAppender.java

  29 
vote

/** 
 * The method adds the log message to the Windows Azure Table storage depending upon the layout.
 * @param event 
 */
@Override protected synchronized void append(LoggingEvent event){
  String messageLevel=event.getLevel().toString();
  if (this.layout == null) {
    errorHandler.error("layout not specified",null,ErrorCode.MISSING_LAYOUT);
    return;
  }
  String message=this.layout.format(event);
  try {
    CloudTableClient cloudTableClient=TableClient.getTableClient(storageEndpoint,accountName,accountKey,tableName);
    makeEntryIntoAzureTableStorage(cloudTableClient,messageLevel,message);
  }
 catch (  InvalidKeyException e) {
    e.printStackTrace();
  }
catch (  StorageException e) {
    e.printStackTrace();
  }
catch (  URISyntaxException e) {
    e.printStackTrace();
  }
}
 

Example 52

From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/support/.

Source file: OAuthSupport.java

  29 
vote

/** 
 * Sign a property Map with OAuth.
 * @param url		the url where the request is to be made
 * @param props		the map of properties to sign
 * @param method	the HTTP request method, eg POST
 * @param key		the oauth_consumer_key
 * @param secret	the shared secret
 * @return
 */
public static Map<String,String> signProperties(String url,Map<String,String> props,String method,String key,String secret){
  if (key == null || secret == null) {
    log.error("Error in signProperties - key and secret must be specified");
    return null;
  }
  OAuthMessage oam=new OAuthMessage(method,url,props.entrySet());
  OAuthConsumer cons=new OAuthConsumer("about:blank",key,secret,null);
  OAuthAccessor acc=new OAuthAccessor(cons);
  try {
    oam.addRequiredParameters(acc);
    log.info("Base Message String\n" + OAuthSignatureMethod.getBaseString(oam) + "\n");
    List<Map.Entry<String,String>> params=oam.getParameters();
    Map<String,String> headers=new HashMap<String,String>();
    for (    Map.Entry<String,String> p : params) {
      String param=URLEncoder.encode(p.getKey(),CHARSET);
      String value=p.getValue();
      String encodedValue=value != null ? URLEncoder.encode(value,CHARSET) : "";
      headers.put(param,encodedValue);
    }
    return headers;
  }
 catch (  OAuthException e) {
    log.error(e.getClass() + ":" + e.getMessage());
    return null;
  }
catch (  IOException e) {
    log.error(e.getClass() + ":" + e.getMessage());
    return null;
  }
catch (  URISyntaxException e) {
    log.error(e.getClass() + ":" + e.getMessage());
    return null;
  }
}