Java Code Examples for java.net.URISyntaxException

The following are top voted examples for showing how to use java.net.URISyntaxException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: AIDR   File: RedisTweetInjector.java View source code 7 votes vote down vote up
public RedisTweetInjector() {
	config = new InjectorConfig();
	try {
		this.host = new URI(config.host);
	} catch (URISyntaxException e) {
		System.err.println("Unable to create host URI for: " + config.host.toString());
		e.printStackTrace();
	}
	this.port = config.port;
	jedisConn = setupJedisConn(this.host.toString(), this.port);
}
 
Example 2
Project: EiraIRC   File: Utils.java View source code 7 votes vote down vote up
public static void openWebpage(URL url) {
    try {
        openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}
 
Example 3
Project: btpka3.github.com   File: Client.java View source code 6 votes vote down vote up
public void add() throws IOException {

        AddRequest addReq = new AddRequest();
        addReq.setX(1);
        addReq.setY(2);
//        AddResponse addResp = (AddResponse) getWebServiceTemplate()
//                .marshalSendAndReceive(addReq);
//        AddResponse addResp = (AddResponse) getWebServiceTemplate()
//                .marshalSendAndReceive(addReq,
//                        new SoapActionCallback(NAMESPACE_URI + "add"));
        AddResponse addResp = null;
        try {
            addResp = (AddResponse) getWebServiceTemplate()
                    .marshalSendAndReceive(addReq,
                            new ActionCallback(NAMESPACE_URI + "add"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        logger.debug("RESPONSE = " + addResp.getOut());
    }
 
Example 4
Project: R5A   File: Receiver.java View source code 6 votes vote down vote up
/**
 * Creates a Socket Pipe Advertisement with the pre-defined pipe ID
 * 
 * @return a socket PipeAdvertisement
 */
public static PipeAdvertisement getSocketAdvertisement() {
	PipeID socketID = null;

	try {
		socketID = (PipeID) IDFactory.fromURI(new URI(SOCKETIDSTR));
	} catch (URISyntaxException use) {
		use.printStackTrace();
	}
	PipeAdvertisement advertisement = (PipeAdvertisement) AdvertisementFactory
			.newAdvertisement(PipeAdvertisement.getAdvertisementType());

	advertisement.setPipeID(socketID);
	// set to type to propagate
	advertisement.setType(PipeService.PropagateType);
	advertisement.setName("Socket Logoot");
	return advertisement;
}
 
Example 5
Project: azure-bing-search-java   File: AbstractAzureSearchTest.java View source code 6 votes vote down vote up
/**
  *
  * @param aq
  */
 public void logURL(@SuppressWarnings("rawtypes") AbstractAzureSearchQuery aq) {
     String full_path = aq.getQueryPath();
     String full_query = aq.getUrlQuery();

     try {
         URI uri = new URI(AbstractAzureSearchQuery.AZURESEARCH_SCHEME, AbstractAzureSearchQuery.AZURESEARCH_AUTHORITY, full_path,
                 full_query, null);
// Bing and java URI disagree about how to represent + in query
         // parameters. This is what we have to do instead...

         uri = new URI(uri.getScheme() + "://" + uri.getAuthority()
                 + uri.getPath() + "?"
                 + uri.getRawQuery().replace("+", "%2b"));
         System.out.println(uri.toString());
     } catch (URISyntaxException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }

 }
 
Example 6
Project: magnificent-mileage   File: AuthFilter.java View source code 6 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest containerRequest) 
        throws WebApplicationException {

    // rewrite URIs to remove 
    // calling these methods clears the cached method, path etc.
    try {
        containerRequest.setUris(containerRequest.getBaseUri(), 
                new URI(containerRequest.getRequestUri().toString().replace("/ws/", "/")));
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    // Automatically allow certain requests.
    String method = containerRequest.getMethod();
    //String path = containerRequest.getPath(true);
    if (method.equals("GET")) // && path.endsWith("metadata")) // skip auth for now
        return containerRequest;
    
    // Get the authentication passed in HTTP headers parameters
    String auth = containerRequest.getHeaderValue("authorization");
    if (auth == null)
        throw unauthorized;
    if (auth.startsWith("Basic ") || auth.startsWith("Basic ")) {
        auth = auth.replaceFirst("[Bb]asic ", "");
        String userColonPass = Base64.base64Decode(auth);
        if (!userColonPass.equals("admin:admin"))
            throw unauthorized;
    } else {
        // fail on unrecognized auth type
        throw unauthorized;
    }
    return containerRequest;
}
 
Example 7
Project: jPastebin   File: PastebinLink.java View source code 6 votes vote down vote up
/**
 * Creates a new <code>PastebinLink</code> object, representing an existing
 * paste
 * 
 * @param paste
 *            paste details
 * @param url
 *            link to paste
 * @param pasteDate
 *            date the paste has been pasted
 */
public PastebinLink(PastebinPaste paste, URL url, Date pasteDate) {
	this.paste = paste;
	this.link = url;
	this.pasteDate = pasteDate;
	try {
		this.key = url.toURI().getPath().substring(1);
	} catch (URISyntaxException e) {
		e.printStackTrace();
	}
}
 
Example 8
Project: dummydroid   File: BrowseUtil.java View source code 6 votes vote down vote up
public void hyperlinkUpdate(HyperlinkEvent e) {
	if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
		if (e.getURL()==null) {
			// Custom protocols (e.g. market://)
			return;
		}
		if ("file".equals(e.getURL().getProtocol())) {
			try {
				BrowseUtil.openFile(new File(e.getURL().toURI()));
			}
			catch (Exception exp) {
				exp.printStackTrace();
			}
		}
		if ("http".equals(e.getURL().getProtocol())) {
			BrowseUtil.openUrl(e.getURL().toString());
		}
		if ("https".equals(e.getURL().getProtocol())) {
			BrowseUtil.openUrl(e.getURL().toString());
		}
		if ("mailto".equals(e.getURL().getProtocol())) {
			try {
				BrowseUtil.openMail(e.getURL().toURI());
			}
			catch (URISyntaxException e1) {
				e1.printStackTrace();
			}
		}
	}
}
 
Example 9
Project: registry-core   File: Login.java View source code 6 votes vote down vote up
public static Response redirectTo(String path) {
    URI uri;
    try {
        uri = new URI(path);
        return Response.seeOther(uri).build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 10
Project: erlide   File: ReportFinder.java View source code 6 votes vote down vote up
public static IFile findReportFile(final File parent) {
    String location = getFileContent(parent, "last_test.html");
    if (location != null) {
        final Pattern pattern = Pattern
                .compile("<a href=\"([^\"]+)\">.*</a>");
        final Matcher matcher = pattern.matcher(location);
        if (matcher.find()) {
            location = matcher.group(1);
        } else {
            location = getFileContent(parent, "last_name");
        }
    } else {
        location = getFileContent(parent, "last_name");
    }
    if (!location.startsWith("/")) {
        location = parent.getAbsolutePath() + "/" + location;
    }
    final IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot();
    try {
        return wroot.findFilesForLocationURI(new URI("file://" + location))[0];
    } catch (final URISyntaxException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 11
Project: JustJson   File: SchemaV4.java View source code 6 votes vote down vote up
@Override
public Schema getEmptySchema(String path) {
    SchemaV4 res=  new SchemaV4().setSchemaFetcher(schemaFetcher);
    URI newScr = null;
    if(this.origSrc!=null && path!=null) {
        try {
            if(origSrc.getFragment() == null) {

                newScr = new URI(getOrigSrc().getScheme(), origSrc.getAuthority(),origSrc.getPath(), origSrc.getQuery(), path);

            } else {
                newScr = new URI(getOrigSrc().getScheme(),origSrc.getAuthority(),origSrc.getPath(), origSrc.getQuery(), origSrc.getFragment() + "/" + path);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    res.setOrigSrc(newScr);
    return res;
}
 
Example 12
Project: Desktop   File: LinkController.java View source code 6 votes vote down vote up
public URI createRelativeURI(final File map, final File input, final int linkType) {
	if (linkType == LINK_ABSOLUTE || input == null) {
		return null;
	}
	try {
		URI mapUri = null;
		if (map != null) {
			mapUri = map.getAbsoluteFile().toURI();
		}
		
		final URI fileUri = input.getAbsoluteFile().toURI();
		boolean isUNCinput = fileUri.getPath().startsWith("//");
		boolean isUNCmap = mapUri.getPath().startsWith("//");
		if((isUNCinput != isUNCmap)) {
			return fileUri;
		}
		final String filePathAsString = fileUri.getRawPath();
		final String mapPathAsString = mapUri.getRawPath();
		int differencePos;
		final int lastIndexOfSeparatorInMapPath = mapPathAsString.lastIndexOf("/");
		final int lastIndexOfSeparatorInFilePath = filePathAsString.lastIndexOf("/");
		int lastCommonSeparatorPos = -1;
		for (differencePos = 0; differencePos <= lastIndexOfSeparatorInMapPath
				&& differencePos <= lastIndexOfSeparatorInFilePath
				&& filePathAsString.charAt(differencePos) == mapPathAsString.charAt(differencePos); differencePos++) {
			if (filePathAsString.charAt(differencePos) == '/') {
				lastCommonSeparatorPos = differencePos;
			}
		}
		if (lastCommonSeparatorPos < 0) {
			return fileUri;
		}
		final StringBuilder relativePath = new StringBuilder();
		for (int i = lastCommonSeparatorPos + 1; i <= lastIndexOfSeparatorInMapPath; i++) {
			if (mapPathAsString.charAt(i) == '/') {
				relativePath.append("../");
			}
		}
		relativePath.append(filePathAsString.substring(lastCommonSeparatorPos + 1));

		return new URI(relativePath.toString());
	}
	catch (final URISyntaxException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 13
Project: phonegap-geolocation   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 14
Project: java-csp   File: DOMRetrievalMethod.java View source code 6 votes vote down vote up
/**
 * Creates a <code>DOMRetrievalMethod</code> containing the specified 
 * URIReference and List of Transforms.
 *
 * @param uri the URI
 * @param type the type
 * @param transforms a list of [email protected] Transform}s. The list is defensively
 *    copied to prevent subsequent modification. May be <code>null</code>
 *    or empty.
 * @throws IllegalArgumentException if the format of <code>uri</code> is 
 *    invalid, as specified by Reference's URI attribute in the W3C
 *    specification for XML-Signature Syntax and Processing
 * @throws NullPointerException if <code>uriReference</code>
 *    is <code>null</code> 
 * @throws ClassCastException if <code>transforms</code> contains any
 *    entries that are not of type [email protected] Transform}
 */
public DOMRetrievalMethod(String uri, String type,
                          List<? extends Transform> transforms)
{
    if (uri == null) {
        throw new NullPointerException("uri cannot be null");
    }
    if (transforms == null || transforms.isEmpty()) {
        this.transforms = Collections.emptyList();
    } else {
        this.transforms = Collections.unmodifiableList(
            new ArrayList<Transform>(transforms));
        for (int i = 0, size = this.transforms.size(); i < size; i++) {
            if (!(this.transforms.get(i) instanceof Transform)) {
                throw new ClassCastException
                    ("transforms["+i+"] is not a valid type");
            }
        }
    }
    this.uri = uri;
    if (!uri.equals("")) {
        try {
            new URI(uri);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    this.type = type;
}
 
Example 15
Project: angularjs-navigation-master-detail   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 16
Project: phonegap-plugin-wizPurchase   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 * creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 * immediately prior to this request/response pair, such as a same-host
 * redirect. This engine assumes ownership of the connection and must
 * release it when it is unneeded.
 */
public HttpEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 17
Project: xface-android   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 18
Project: pg-twit   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 * creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 * immediately prior to this request/response pair, such as a same-host
 * redirect. This engine assumes ownership of the connection and must
 * release it when it is unneeded.
 */
public HttpEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 19
Project: Developing-with-Cordova   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 * creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 * immediately prior to this request/response pair, such as a same-host
 * redirect. This engine assumes ownership of the connection and must
 * release it when it is unneeded.
 */
public HttpEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 20
Project: fourinone   File: FttpException.java View source code 6 votes vote down vote up
static URI getURI(String fttpPath, String filename)throws FttpException{
	URI fl = null;
	try{
		fl = new URI(fttpPath);
		if(!fl.getScheme().toLowerCase().equals("fttp"))
			throw new FttpException("Illegal protocol character in "+fttpPath);

		if(filename!=null)
			fl = getFttpURI(fl, fl.getPath(), filename);
			
	}catch(URISyntaxException uie){
		throw new FttpException(uie.getMessage());
	}
	return fl;
}
 
Example 21
Project: jaamsim   File: Input.java View source code 6 votes vote down vote up
/**
 * Converts a file path entry in a configuration file to a URI.
 * @param kw - keyword input containing the file path data
 * @return the URI corresponding to the file path data.
 * @throws InputErrorException
 */
public static URI parseURI(KeywordIndex kw)
throws InputErrorException {
	Input.assertCount(kw, 1);

	String arg = kw.getArg(0);

	// Convert the file path to a URI
	URI uri = null;
	try {
		if (kw.context != null)
			uri = InputAgent.getFileURI(kw.context.context, arg, kw.context.jail);
		else
			uri = InputAgent.getFileURI(null, arg, null);
	}
	catch (URISyntaxException ex) {
		throw new InputErrorException("File Entity parse error: %s", ex.getMessage());
	}

	if (uri == null)
		throw new InputErrorException("Unable to parse the file path:\n%s", arg);

	if (!uri.isOpaque() && uri.getPath() == null)
		 throw new InputErrorException("Unable to parse the file path:\n%s", arg);

	return uri;
}
 
Example 22
Project: classapp   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 * creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 * immediately prior to this request/response pair, such as a same-host
 * redirect. This engine assumes ownership of the connection and must
 * release it when it is unneeded.
 */
public HttpEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 23
Project: aws-sdk-android   File: RegionUtils.java View source code 6 votes vote down vote up
/**
 * Get the URI object for the given endpoint. URI class cannot correctly
 * parse the endpoint if it doesn't include protocol. This method will add
 * the protocol if this happens.
 */
private static URI getUriByEndpoint(String endpoint) {
    URI targetEndpointUri = null;
    try {
        targetEndpointUri = new URI(endpoint);
        if (targetEndpointUri.getHost() == null) {
            targetEndpointUri = new URI("http://" + endpoint);
        }
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unable to parse service endpoint: " + e.getMessage());
    }
    return targetEndpointUri;
}
 
Example 24
Project: Desktop   File: MModeWorkspaceUrlManager.java View source code 6 votes vote down vote up
public URI getAbsoluteUri(final MapModel map, final URI uri) throws MalformedURLException {
   	if(uri == null) {
		return null;
	}
   	URL url = null;
   	try {
   		url = getAbsoluteUrl(map, uri);
   		if(url == null) {
   			return null;
   		}
		return url.toURI();
	} catch (URISyntaxException e) {
		try {
			return new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
		}
		catch (Exception ex) {
			throw new MalformedURLException(e.getMessage());
		}			
	}
}
 
Example 25
Project: nuCommander   File: InternalBrowse.java View source code 6 votes vote down vote up
/**
 * Opens the specified URL in the system's default browser.
 * @param  url         URL to browse.
 * @throws IOException if an error occured.
 */
@Override
public void execute(URL url) throws IOException {
    // If java.awt.Desktop browsing is available, use it.
    if(isAvailable()) {
        try {getDesktop().browse(url.toURI());}
        catch(URISyntaxException e) {throw new IOException(e.getMessage());}
    }

    throw new UnsupportedOperationException();
}
 
Example 26
Project: code   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 27
Project: rfDynHUD   File: ClassSearcher.java View source code 6 votes vote down vote up
/**
 * Reads all classnames from given packages into a List, that match certrain
 * criteria.
 * 
 * @param classLoader
 * @param packagePrefixesDot dot separated package prefix names (like "org.jagatoo.test")
 * @param packagePrefixesSlash slash separated package prefix names (like "org/jagatoo/test")
 * @param crit the Criterium to check for each class
 * @param classes
 * @param jarMap
 * 
 * @throws IOException
 */
private static void findClassesFromURLClassLoader( URLClassLoader classLoader, String[] packagePrefixesDot, String[] packagePrefixesSlash, ClassSearchCriterium crit, Set<Class<?>> classes, Map<Class<?>, JarFile> jarMap ) throws IOException
{
    for ( URL url : classLoader.getURLs() )
    {
        try
        {
            URI uri = url.toURI();
            
            if ( uri.toString().endsWith( "/" ) )
                findClassNamesFromFolder( classLoader, new File( uri ), packagePrefixesDot, crit, classes );
            else
                findClassNamesFromJar( classLoader, new File( uri ), packagePrefixesSlash, crit, classes, jarMap );
        }
        catch ( URISyntaxException e )
        {
            throw new MalformedURLException( e.getMessage() );
        }
    }
}
 
Example 28
Project: hd-easy-app   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 29
Project: hadoop_ekg   File: FsUrlConnection.java View source code 6 votes vote down vote up
@Override
public void connect() throws IOException {
  try {
    FileSystem fs = FileSystem.get(url.toURI(), conf);
    is = fs.open(new Path(url.getPath()));
  } catch (URISyntaxException e) {
    throw new IOException(e.toString());
  }
}
 
Example 30
Project: HDP-2.2-Patched   File: CopyCommands.java View source code 6 votes vote down vote up
@Override
protected List<PathData> expandArgument(String arg) throws IOException {
  List<PathData> items = new LinkedList<PathData>();
  if (arg.equals("-")) {
    readStdin = true;
  } else {
    try {
      items.add(new PathData(new URI(arg), getConf()));
    } catch (URISyntaxException e) {
      if (Path.WINDOWS) {
        // Unlike URI, PathData knows how to parse Windows drive-letter paths.
        items.add(new PathData(arg, getConf()));
      } else {
        throw new IOException("Unexpected URISyntaxException: " + e.toString());
      }
    }
  }
  return items;
}
 
Example 31
Project: bigpetstore   File: FsUrlConnection.java View source code 6 votes vote down vote up
@Override
public void connect() throws IOException {
  try {
    FileSystem fs = FileSystem.get(url.toURI(), conf);
    is = fs.open(new Path(url.getPath()));
  } catch (URISyntaxException e) {
    throw new IOException(e.toString());
  }
}
 
Example 32
Project: yarn-comment   File: FsUrlConnection.java View source code 6 votes vote down vote up
@Override
public void connect() throws IOException {
  try {
    FileSystem fs = FileSystem.get(url.toURI(), conf);
    is = fs.open(new Path(url.getPath()));
  } catch (URISyntaxException e) {
    throw new IOException(e.toString());
  }
}
 
Example 33
Project: hadoop-src-research   File: FsUrlConnection.java View source code 6 votes vote down vote up
@Override
public void connect() throws IOException {
  try {
    FileSystem fs = FileSystem.get(url.toURI(), conf);
    is = fs.open(new Path(url.getPath()));
  } catch (URISyntaxException e) {
    throw new IOException(e.toString());
  }
}
 
Example 34
Project: jdbc4sparql   File: J4SUrl.java View source code 6 votes vote down vote up
private void parseJ4SEndpoint(final String urlStr, final int pos) {
	try {
		this.endpoint = new URI(urlStr.substring(pos));
	} catch (final URISyntaxException e) {
		throw new IllegalArgumentException(
				"Not a valid J4S JDBC URL -- endpoint is not a valid URI : "
						+ e.toString());
	}
}
 
Example 35
Project: eclipse.platform.resources   File: WrapperFileSystem.java View source code 6 votes vote down vote up
public static URI getWrappedURI(URI baseURI) {
	try {
		return new URI(SCHEME_WRAPPED, null, baseURI.getPath(), baseURI.toString(), null);
	} catch (URISyntaxException e) {
		throw new IllegalArgumentException(e.toString());
	}
}
 
Example 36
Project: hadoop-on-lustre2   File: CopyCommands.java View source code 6 votes vote down vote up
@Override
protected List<PathData> expandArgument(String arg) throws IOException {
  List<PathData> items = new LinkedList<PathData>();
  if (arg.equals("-")) {
    readStdin = true;
  } else {
    try {
      items.add(new PathData(new URI(arg), getConf()));
    } catch (URISyntaxException e) {
      if (Path.WINDOWS) {
        // Unlike URI, PathData knows how to parse Windows drive-letter paths.
        items.add(new PathData(arg, getConf()));
      } else {
        throw new IOException("Unexpected URISyntaxException: " + e.toString());
      }
    }
  }
  return items;
}
 
Example 37
Project: HadoopEKG   File: FsUrlConnection.java View source code 6 votes vote down vote up
@Override
public void connect() throws IOException {
  try {
    FileSystem fs = FileSystem.get(url.toURI(), conf);
    is = fs.open(new Path(url.getPath()));
  } catch (URISyntaxException e) {
    throw new IOException(e.toString());
  }
}
 
Example 38
Project: hadoop-20-warehouse   File: FsUrlConnection.java View source code 6 votes vote down vote up
@Override
public void connect() throws IOException {
  try {
    FileSystem fs = FileSystem.get(url.toURI(), conf);
    is = fs.open(new Path(url.getPath()));
  } catch (URISyntaxException e) {
    throw new IOException(e.toString());
  }
}
 
Example 39
Project: irma_web_service   File: IRMAProtocolApplication.java View source code 6 votes vote down vote up
/**
 * Starting point for the IRMA REST interface for smartcard protocols. Contains
 * the URL router.
 * 
 * @author Maarten Everts
 */
@Override
public synchronized Restlet createInboundRoot() {
	Router router = new Router(getContext());

	URI CORE_LOCATION;
	try {
		CORE_LOCATION = IRMAProtocolApplication.class.getClassLoader()
				.getResource("/resources/irma_configuration/").toURI();
	} catch (URISyntaxException e) {
		e.printStackTrace();
		throw new RuntimeException(e.toString());
	}
	CredentialInformation.setCoreLocation(CORE_LOCATION);
	DescriptionStore.setCoreLocation(CORE_LOCATION);

	router.attach("/verification/SpuitenEnSlikken", SpuitenEnSlikkenVerificationResource.class);
	router.attach("/verification/SpuitenEnSlikken/{id}/{step}", SpuitenEnSlikkenVerificationResource.class);

	router.attach("/verification/NYTimes", NYTimesVerificationResource.class);
	router.attach("/verification/NYTimes/{id}/{step}", NYTimesVerificationResource.class);

	router.attach("/verification/IRMATube/{age}", IRMATubeVerificationResource.class);
	router.attach("/verification/IRMATube/{age}/{id}/{step}", IRMATubeVerificationResource.class);

	router.attach("/verification/SurfnetVoucher", SurfnetVoucherVerificationResource.class);
	router.attach("/verification/SurfnetVoucher/{id}/{step}", SurfnetVoucherVerificationResource.class);

	router.attach("/verification/IRMAWiki", IRMAWikiVerificationResource.class);
	router.attach("/verification/IRMAWiki/{id}/{step}", IRMAWikiVerificationResource.class);
	router.attach("/verification/IRMAWikiRegistration", IRMAWikiRegistrationVerificationResource.class);
	router.attach("/verification/IRMAWikiRegistration/{id}/{step}", IRMAWikiRegistrationVerificationResource.class);
	router.attach("/issue/IRMAWikiRegistration/{id}", IRMAWikiRegistrationIssueResource.class);
	router.attach("/issue/IRMAWikiRegistration/{id}/{cred}/{step}", IRMAWikiRegistrationIssueResource.class);

	router.attach("/verification/StudentCard", StudentCardVerificationResource.class);
	router.attach("/verification/StudentCard/{id}/{step}", StudentCardVerificationResource.class);
	router.attach("/issue/StudentCard/{id}", StudentCardIssueResource.class);
	router.attach("/issue/StudentCard/{id}/{cred}/{step}", StudentCardIssueResource.class);

	router.attach("/verification/IRMATubeRegistration", IRMATubeRegistrationVerificationResource.class);
	router.attach("/verification/IRMATubeRegistration/{id}/{step}", IRMATubeRegistrationVerificationResource.class);
	router.attach("/issue/IRMATubeRegistration/{id}", IRMATubeRegistrationIssueResource.class);
	router.attach("/issue/IRMATubeRegistration/{id}/{cred}/{step}", IRMATubeRegistrationIssueResource.class);

	return router;
}
 
Example 40
Project: Info_Moist_2_Splicer_Streaming   File: FsUrlConnection.java View source code 6 votes vote down vote up
@Override
public void connect() throws IOException {
  try {
    FileSystem fs = FileSystem.get(url.toURI(), conf);
    is = fs.open(new Path(url.getPath()));
  } catch (URISyntaxException e) {
    throw new IOException(e.toString());
  }
}
 
Example 41
Project: Piggydb   File: FileSystemUtils.java View source code 6 votes vote down vote up
public static File urlToFile(URL url) {
	if (url == null) {
		return null;
	}
	File file = null;
	try {
		file = new File(new URI(url.toExternalForm()));
	}
	catch (URISyntaxException e) {
		throw new IllegalArgumentException(e.toString());
	}
	return file;
}
 
Example 42
Project: JESL   File: JKCloudEventSinkFactory.java View source code 6 votes vote down vote up
@Override
  public void setConfiguration(Map<String, Object> settings) throws ConfigException {
super.setConfiguration(settings);
url = config.get("Url") != null? config.get("Url").toString(): url;
token = config.get("Token") != null? config.get("Token").toString(): token;
fileName = config.get("Filename") != null? config.get("Filename").toString(): fileName;
if (fileName != null) {
	eventSinkFactory = new FileEventSinkFactory(fileName);
	eventSinkFactory.setTTL(getTTL());
}
try {
	URI uri = new URI(url);
	url = uri.toString();
}
catch (URISyntaxException e1) {
	ConfigException ce = new ConfigException(e1.toString(), settings);
	ce.initCause(e1);
	throw ce;
}
  }
 
Example 43
Project: GWSHolmesWatson   File: HttpEngine.java View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
        HttpConnection connection, RetryableOutputStream requestBodyOut) throws IOException {
    this.policy = policy;
    this.method = method;
    this.connection = connection;
    this.requestBodyOut = requestBodyOut;

    try {
        uri = URLs.toURILenient(policy.getURL());
    } catch (URISyntaxException e) {
        throw new IOException(e.toString());
    }

    this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 44
Project: nio-fs-provider   File: SFTPFileSystemProvider.java View source code 6 votes vote down vote up
@Override
public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
  try {
    return getSFTPHost(uri, true);
  } catch(URISyntaxException e) {
    throw new FileSystemException(e.toString());
  }
}
 
Example 45
Project: Grendel-Scan   File: TransactionSummary.java View source code 6 votes vote down vote up
public TransactionSummary(final StandardHttpTransaction transaction)
{
    updateSummary(transaction);
    transactionID = transaction.getId();
    // method = stringCache.addValue(transaction.getRequestWrapper().getMethod());
    // host = stringCache.addValue(transaction.getRequestWrapper().getHost());
    // source = stringCache.addValue(transaction.getSource().getText());
    // reason = stringCache.addValue(transaction.getRequestOptions().reason);

    method = transaction.getRequestWrapper().getMethod();
    host = transaction.getRequestWrapper().getHost();
    source = transaction.getSource().getText();
    reason = transaction.getRequestOptions().reason;
    try
    {
        // path = stringCache.addValue(transaction.getRequestWrapper().getPath() + URIStringUtils.getFilename(transaction.getRequestWrapper().getURI()));
        // query = stringCache.addValue(URIStringUtils.getQuery(transaction.getRequestWrapper().getURI()));

        path = transaction.getRequestWrapper().getPath() + URIStringUtils.getFilename(transaction.getRequestWrapper().getURI());
        query = URIStringUtils.getQuery(transaction.getRequestWrapper().getURI());
    }
    catch (URISyntaxException e)
    {
        IllegalStateException ise = new IllegalStateException("Really, really weird problem with uri parsing: " + e.toString(), e);
        LOGGER.error(ise.toString(), ise);
        throw ise;
    }
}
 
Example 46
Project: ManagedRuntimeInitiative   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String u, String h, int n,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, u, h, n, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 47
Project: ManagedRuntimeInitiative   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String a,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, a, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 48
Project: openjdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String u, String h, int n,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, u, h, n, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 49
Project: openjdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String a,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, a, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 50
Project: ical-combinator   File: UriListHttpMessageConverter.java View source code 6 votes vote down vote up
@Override
protected List<URI> readInternal(Class<? extends List<URI>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    InputStream in = inputMessage.getBody();
    try {
        String text = IOUtils.toString(in, "UTF-8");
        List<URI> result = parseURIs(text);
        logger.info("Produced a list of " + result.size() + " items: " + result);
        return result;
    } catch (URISyntaxException e) {
        throw new HttpMessageNotReadableException("Illegal URI in list of URIs: " + e.getInput());
    } finally {
        IOUtils.closeQuietly(in);
    }
}
 
Example 51
Project: openjdk8-jdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String u, String h, int n,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, u, h, n, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 52
Project: openjdk8-jdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String a,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, a, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 53
Project: jdk7-jdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String u, String h, int n,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, u, h, n, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 54
Project: jdk7-jdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String a,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, a, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 55
Project: jdk7u-jdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String u, String h, int n,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, u, h, n, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 56
Project: jdk7u-jdk   File: Test.java View source code 6 votes vote down vote up
private Test(String s, String a,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, a, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 57
Project: HDP-2.2-Patched   File: PathData.java View source code 6 votes vote down vote up
private static URI removeAuthority(URI uri) {
  try {
    uri = new URI(
        uri.getScheme(), "",
        uri.getPath(), uri.getQuery(), uri.getFragment()
    );
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getLocalizedMessage());
  }
  return uri;
}
 
Example 58
Project: teiid-designer   File: BasicWsdlGenerator.java View source code 6 votes vote down vote up
protected IStatus doCheckValidUri( final String location ) {
    try {
        new java.net.URI(location);
    } catch (URISyntaxException err) {
        final IStatus problem = new Status(IStatus.ERROR, WebServicePlugin.PLUGIN_ID, INVALID_URL, err.getLocalizedMessage(),
                                           null);
        return problem;
    }
    return null;
}
 
Example 59
Project: yarn-comment   File: PathData.java View source code 6 votes vote down vote up
private static URI removeAuthority(URI uri) {
  try {
    uri = new URI(
        uri.getScheme(), "",
        uri.getPath(), uri.getQuery(), uri.getFragment()
    );
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getLocalizedMessage());
  }
  return uri;
}
 
Example 60
Project: hadoop-on-lustre2   File: PathData.java View source code 6 votes vote down vote up
private static URI removeAuthority(URI uri) {
  try {
    uri = new URI(
        uri.getScheme(), "",
        uri.getPath(), uri.getQuery(), uri.getFragment()
    );
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getLocalizedMessage());
  }
  return uri;
}
 
Example 61
Project: Locast-Core-Android   File: NetworkClient.java View source code 6 votes vote down vote up
private void setBaseUrl(String baseUrlString) throws MalformedURLException {
    final URL baseUrl = new URL(baseUrlString);
    try {
        mBaseUrl = baseUrl.toURI();

        mAuthScope = new AuthScope(mBaseUrl.getHost(), mBaseUrl.getPort());

    } catch (final URISyntaxException e) {
        final MalformedURLException me = new MalformedURLException(e.getLocalizedMessage());
        me.initCause(e);
        throw me;
    }
}
 
Example 62
Project: carbon-business-process   File: AttachmentMgtDAOTransformerFactoryImpl.java View source code 6 votes vote down vote up
@Override
public Attachment convertAttachment(AttachmentDAO attachment) throws AttachmentMgtException {
    Attachment attachmentDTO = null;
    try {
        attachmentDTO = new AttachmentImpl(attachment);
    } catch (URISyntaxException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new AttachmentMgtException("Object conversion failed due to reason : " + e.getLocalizedMessage(), e);
    }

    return attachmentDTO;
}
 
Example 63
Project: acs-android-sdk   File: ACSClient.java View source code 6 votes vote down vote up
/**
   * Show dialog for authentication
   * @param context
   * @param action
   * @param parameters
   * @param listener
   * @throws ACSClientError 
   */
  private void dialog(Context context, String action, Bundle parameters, final DialogListener listener, boolean useSecure) throws ACSClientError {

  	StringBuffer endpoint = null;
if (useSecure) {
	endpoint = new StringBuffer(CCConstants.HTTPS_HEAD);
} else {
	endpoint = new StringBuffer(CCConstants.HTTP_HEAD);
}

if(this.authHost == null || this.authHost.length() == 0) {
	listener.onACSClientError(new ACSClientError("Authorization Server isn't set."));
	return;
}
  	endpoint.append(this.authHost);
  	parameters.putString("oauth_consumer_key", this.oauthKey);
      parameters.putString("client_id", this.oauthKey);
      parameters.putString("redirect_uri", REDIRECT_URI);

      if(ACTION_LOGIN.equals(action)) {
   	endpoint.append("/oauth/authorize");
       parameters.putString("response_type", "token");
} else if(ACTION_SIGNUP.equals(action)) {
	endpoint.append("/users/sign_up");
} else {
	throw new ACSClientError("Action not supported: " + action);
}

      if (isSessionValid()) {
          parameters.putString(ACCESS_TOKEN, getAccessToken());
      }
      endpoint.append("?");
      endpoint.append(Util.encodeUrl(parameters));
      
try {
	URI reqUri = new URL(endpoint.toString()).toURI();
} catch (MalformedURLException e1) {
	throw new ACSClientError("Incorrect Auth Host: " + e1.getLocalizedMessage());
} catch (URISyntaxException e2) {
	throw new ACSClientError("Incorrect Auth Host: " + e2.getLocalizedMessage());
}
      
      if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
          Util.showAlert(context, "Error", "Application requires permission to access the Internet");
      } else {
          new ACSClientDialog(context, endpoint.toString(), listener, this.dlgCustomizer).show();
      }
  }
 
Example 64
Project: codehaus-mojo   File: MojoURIResolver.java View source code 6 votes vote down vote up
private InputStream getResourceAsStream( String fullUri )
    throws IOException
{
    try
    {
        URI uri = new URI( fullUri );

        String groupId = uri.getAuthority();
        String path = uri.getPath().substring( 1 );
        String artifactId = path.substring( 0, path.indexOf( "/" ) );
        String resource = path.substring( path.indexOf( "/" ) );

        for ( Iterator i = this.artifacts.iterator(); i.hasNext(); )
        {
            Artifact a = (Artifact) i.next();
            if ( ( a.getGroupId().equals( groupId ) ) && ( a.getArtifactId().equals( artifactId ) ) )
            {
                ZipFile jar = new ZipFile( a.getFile() );
                for ( Enumeration e = jar.entries(); e.hasMoreElements(); )
                {
                    ZipEntry je = (ZipEntry) e.nextElement();
                    String name = je.getName();
                    if ( !name.startsWith( "/" ) )
                    {
                        name = "/" + name;
                    }
                    if ( name.equals( resource ) )
                    {
                        return jar.getInputStream( je );
                    }
                }
            }
        }

        return MojoURIResolver.class.getResourceAsStream( fullUri.substring( 10 ) );
    }
    catch ( URISyntaxException use )
    {
        throw new IOException( use.getLocalizedMessage() );
    }
}
 
Example 65
Project: hadoop   File: PathData.java View source code 6 votes vote down vote up
private static URI removeAuthority(URI uri) {
  try {
    uri = new URI(
        uri.getScheme(), "",
        uri.getPath(), uri.getQuery(), uri.getFragment()
    );
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getLocalizedMessage());
  }
  return uri;
}
 
Example 66
Project: hadoop-release-2.6.0   File: PathData.java View source code 6 votes vote down vote up
private static URI removeAuthority(URI uri) {
  try {
    uri = new URI(
        uri.getScheme(), "",
        uri.getPath(), uri.getQuery(), uri.getFragment()
    );
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getLocalizedMessage());
  }
  return uri;
}
 
Example 67
Project: rhq   File: ApplicationServerComponent.java View source code 6 votes vote down vote up
private static void validateNamingURL(String namingURL) {
    URI namingURI;
    try {
        namingURI = new URI(namingURL);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Naming URL '" + namingURL + "' is not valid: " + e.getLocalizedMessage());
    }
    if (!namingURI.isAbsolute())
        throw new RuntimeException("Naming URL '" + namingURL + "' is not absolute.");
    if (!namingURI.getScheme().equals("jnp"))
        throw new RuntimeException("Naming URL '" + namingURL
            + "' has an invalid protocol - the only valid protocol is 'jnp'.");
}
 
Example 68
Project: hops   File: PathData.java View source code 6 votes vote down vote up
private static URI removeAuthority(URI uri) {
  try {
    uri = new URI(
        uri.getScheme(), "",
        uri.getPath(), uri.getQuery(), uri.getFragment()
    );
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getLocalizedMessage());
  }
  return uri;
}
 
Example 69
Project: gatein-wsrp   File: RegistrationPropertyDescription.java View source code 6 votes vote down vote up
public URI getSchemaLocationAsURI()
{
   try
   {
      return new URI(schemaLocation);
   }
   catch (URISyntaxException e)
   {
      // shouldn't happen
      throw new IllegalArgumentException("Invalid URI: " + schemaLocation + ". Cause: " + e.getLocalizedMessage());
   }
}
 
Example 70
Project: camel-extra   File: StubFileSmbApiFactory.java View source code 6 votes vote down vote up
public SmbFile createSmbFile(String urlString, NtlmPasswordAuthentication authentication) throws MalformedURLException, SmbException {
    try {
        URI uri = new URI(urlString);
        return smbFiles.get(uri.getPath());
    } catch (URISyntaxException e) {
        throw new MalformedURLException(e.getLocalizedMessage());
    }
}
 
Example 71
Project: Locast-Android   File: NetworkClient.java View source code 6 votes vote down vote up
private void setBaseUrl(String baseUrlString) throws MalformedURLException {
	final URL baseUrl = new URL(baseUrlString);
	try {
		mBaseUrl = baseUrl.toURI();

		mAuthScope = new AuthScope(mBaseUrl.getHost(), mBaseUrl.getPort());

	} catch (final URISyntaxException e) {
		final MalformedURLException me = new MalformedURLException(e.getLocalizedMessage());
		me.initCause(e);
		throw me;
	}
}
 
Example 72
Project: hadaps   File: PathData.java View source code 6 votes vote down vote up
private static URI removeAuthority(URI uri) {
  try {
    uri = new URI(
        uri.getScheme(), "",
        uri.getPath(), uri.getQuery(), uri.getFragment()
    );
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getLocalizedMessage());
  }
  return uri;
}
 
Example 73
Project: classpath   File: AnyURIType.java View source code 6 votes vote down vote up
public void checkValid(String value, ValidationContext context)
  throws DatatypeException
{
  super.checkValid(value, context);
  try
    {
      new URI(value);
    }
  catch (URISyntaxException e)
    {
      DatatypeException e2 = new DatatypeException(e.getIndex(),
                                                   e.getReason());
      e2.initCause(e);
      throw e2;
    }
}
 
Example 74
Project: ManagedRuntimeInitiative   File: Test.java View source code 6 votes vote down vote up
static void show(String prefix, URISyntaxException x) {
    out.println(uquote(x.getInput()));
    if (x.getIndex() >= 0) {
        for (int i = 0; i < x.getIndex(); i++) {
            if (x.getInput().charAt(i) >= '\u0080')
                out.print("      ");        // Skip over \u1234
            else
                out.print(" ");
        }
        out.println("^");
    }
    out.println(prefix + ": " + x.getReason());
}
 
Example 75
Project: openjdk   File: Test.java View source code 6 votes vote down vote up
static void show(String prefix, URISyntaxException x) {
    out.println(uquote(x.getInput()));
    if (x.getIndex() >= 0) {
        for (int i = 0; i < x.getIndex(); i++) {
            if (x.getInput().charAt(i) >= '\u0080')
                out.print("      ");        // Skip over \u1234
            else
                out.print(" ");
        }
        out.println("^");
    }
    out.println(prefix + ": " + x.getReason());
}
 
Example 76
Project: JamVM-PH   File: AnyURIType.java View source code 6 votes vote down vote up
public void checkValid(String value, ValidationContext context)
  throws DatatypeException
{
  super.checkValid(value, context);
  try
    {
      new URI(value);
    }
  catch (URISyntaxException e)
    {
      DatatypeException e2 = new DatatypeException(e.getIndex(),
                                                   e.getReason());
      e2.initCause(e);
      throw e2;
    }
}
 
Example 77
Project: openjdk8-jdk   File: Test.java View source code 6 votes vote down vote up
static void show(String prefix, URISyntaxException x) {
    out.println(uquote(x.getInput()));
    if (x.getIndex() >= 0) {
        for (int i = 0; i < x.getIndex(); i++) {
            if (x.getInput().charAt(i) >= '\u0080')
                out.print("      ");        // Skip over \u1234
            else
                out.print(" ");
        }
        out.println("^");
    }
    out.println(prefix + ": " + x.getReason());
}
 
Example 78
Project: jdk7-jdk   File: Test.java View source code 6 votes vote down vote up
static void show(String prefix, URISyntaxException x) {
    out.println(uquote(x.getInput()));
    if (x.getIndex() >= 0) {
        for (int i = 0; i < x.getIndex(); i++) {
            if (x.getInput().charAt(i) >= '\u0080')
                out.print("      ");        // Skip over \u1234
            else
                out.print(" ");
        }
        out.println("^");
    }
    out.println(prefix + ": " + x.getReason());
}
 
Example 79
Project: jdk7u-jdk   File: Test.java View source code 6 votes vote down vote up
static void show(String prefix, URISyntaxException x) {
    out.println(uquote(x.getInput()));
    if (x.getIndex() >= 0) {
        for (int i = 0; i < x.getIndex(); i++) {
            if (x.getInput().charAt(i) >= '\u0080')
                out.print("      ");        // Skip over \u1234
            else
                out.print(" ");
        }
        out.println("^");
    }
    out.println(prefix + ": " + x.getReason());
}
 
Example 80
Project: openstack4j   File: HttpCommand.java View source code 6 votes vote down vote up
private void initialize() {
    URI url = null;
    try
    {
        url = populateQueryParams(request);
    }
    catch (URISyntaxException e) {
        throw new ConnectionException(e.getMessage(),e.getIndex(), e);
    }
    client = HttpClientFactory.INSTANCE.getClient(request.getConfig());
    
    switch (request.getMethod()) {
    case POST:
        clientReq = new HttpPost(url);
        break;
    case PUT:
        clientReq = new HttpPut(url);
        break;
    case DELETE:
        clientReq = new HttpDelete(url);
        break;
    case HEAD:
        clientReq = new HttpHead(url);
        break;
    case GET:
    default:
        clientReq = new HttpGet(url);
        break;
    }
    clientReq.setHeader("Accept", MediaType.JSON_UTF_8.toString());
    populateHeaders(request);
}
 
Example 81
Project: phoneme-components-cdc   File: URITest.java View source code 6 votes vote down vote up
static void show(String prefix, URISyntaxException x) {
out.println(uquote(x.getInput()));
if (x.getIndex() >= 0) {
    for (int i = 0; i < x.getIndex(); i++) {
	if (x.getInput().charAt(i) >= '\u0080')
	    out.print("      ");	// Skip over \u1234
	else
	    out.print(" ");
    }
    out.println("^");
}
out.println(prefix + ": " + x.getReason());
   }
 
Example 82
Project: josm-plugins   File: OpenLinkAction.java View source code 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    try {
        Main.info("Opening "+url);
        OpenBrowser.displayUrl(url.toURI());
    } catch (URISyntaxException e1) {
        try {
            Main.error(e1.getLocalizedMessage());
            int index = e1.getIndex();
            if (index > -1) {
                String s = url.toString().substring(index, index+1);
                s = url.toString().replace(s, URLEncoder.encode(s, OdConstants.UTF8));
                URI uri = new URI(s);
                Main.info("Opening "+uri);
                OpenBrowser.displayUrl(uri);
            }
        } catch (Exception e2) {
            Main.error(e2);
        }
    }
}
 
Example 83
Project: openaz   File: OpenAzPolicyReader.java View source code 5 votes vote down vote up
/**
   * An Obligation contains a collection of AttributeAssignments
   * that may be returned in a Xacml Response.
   * <p>
   * An Obligation has the following parameters to its constructor:
   * <pre>
   * Obligation(
   * 		URI id, 
   * 		int fulfillOn, 
   * 		List assignments)
   * 
   *  Constructor that takes all the data associated with an obligation.
   * </pre>
   */
  public OpenAzXacmlObject processObligation(
  			OpenAzLineContext curLineCtx)
  		throws OpenAzParseException {
  	
OpenAzXacmlObject resultObject = null;
LineType currentLineType = curLineCtx.getLineType();
int myLineNumber = curLineCtx.getLineNumber();
String msg = curLineCtx.getMessage();

// create a list in prep for obligation attributes
List<AttributeMatchExpression> obligationAmeList = 
	new ArrayList<AttributeMatchExpression>();

// intent here is to loop thru all the Obligation attributes
// (OA), which has the effect of processing one Obligation;
// We want to readAzLine until we hit a terminator ( i.e. a
// terminating LineType, meaning no more OA records expected
// for the current Obligation.
OpenAzXacmlObject azObject = null;
curLineCtx.setLookingForLineType(LineType.OA); //extensionLineType
boolean moreObligationAttributes = true;
while (moreObligationAttributes){
	log.trace(
	"\nTRACE: *****************************************");
	log.trace(
		"TRACE: " + curLineCtx.getStateDescriptor() + 
		" processObligation:OB CALLING into readAzLine() using" +
		"\n\t\t\tparentLineNumber = " + myLineNumber);
	azObject = readAzLine(curLineCtx);
	log.trace(
		"TRACE: " + curLineCtx.getStateDescriptor() + 
		" SL2-OBS:OB: RETURNed to processObligation:OB " +
		"SL2-OBS:OB loop from readAzLine(" +
		"\n\t\t\tparentLineNumber(myLineNumber) = " + 
				 myLineNumber +
		"\n\t\t\tparentLineType(currentLineType) = " +
				currentLineType +
		"\n\t\t\tlookingForType = " + null +
		"\n\t\t\treadAhead flag = " + azObject.getReadAhead());
	
	LineType recordLineType = azObject.getLineType();
	// set this to enable continuation (extensionLineType)
	curLineCtx.setLookingForLineType(recordLineType);
	switch (recordLineType) {
	case OA:
		log.trace("TRACE: OBS:OB:OA switch level 3");
		// Try to save the attribute just returned
		try {
			// object for obl attr to be stored
			AttributeMatchExpression ame =  
				(AttributeMatchExpression) azObject.getObject();
			obligationAmeList.add(ame);
		} catch (ClassCastException cce) {
			// if the OA msg is bad end things here
			cce.printStackTrace(new PrintWriter(swStatic));
			String msgClassCast = "ClassCastException: " + 
				cce.getMessage() + 
				" looking for AttributeMatchExpression, " + 
				"got something else." + swStatic;
			throw new OpenAzParseException(
					msgClassCast, curLineCtx.getLineNumber());
		}		
		break;
	default:
		// Any non-OA LineType is effectively a terminator;
		// just break the loop, let ancestors determine
		// legitimacy of the terminator LineType
		log.trace(
			"TRACE: " + curLineCtx.getStateDescriptor() +
			" OBS:OB:default  switch level 3: " + 
				" next line is LineType: " + azObject.getLineType() + 
				"  terminate the OA loop");
		moreObligationAttributes = false; // terminate the loop
		break;
	} // end switch (recordLineType)					
} // end while (moreObligationAttributes)

// get the Obligation metadata from the current OB line
// Allocate variables to collect Obligation token data:
String obligationId = null;
   String obligationFulfillOnStr = null;

   // Go thru tokens to get metadata values for the Obligation
      String thisObject = "Obligation";
  	Map<String,String> map = curLineCtx.getTokens();
  	log.trace(
  		"TRACE: Building a " + thisObject + 
  		" using these tokens: " + map);
  	Set<String> keys = map.keySet();
  	for (String s : keys) {
  		String sValue = map.get(s);
  		log.trace("TRACE: loop for " + thisObject + 
  				":\n\t\t  key: " + s +
  				",\n\t\t  sValue: " + sValue);
  		if (sValue.equals("!")) {
  			log.trace(
  				"TRACE:\t sValue is a null, skip to next key");
  			continue;
  		}
  		int size = keys.size();
  		for (int i=0; i<size; i++) {
  			log.trace(
  				"TRACE:   Inner loop: (" + i +
  				") match key then value: key = " + s);
  			switch (i) {
  			case 0:
  				if (s.equals(OPENAZ_OBLIGATION_ID)) {
  					i = size; // force break on loop condition
  	    			log.trace(
       				"TRACE:   Inner loop: key matched:" + 
       				OPENAZ_OBLIGATION_ID +
       				" now test value: sValue = " + sValue);
  	    			// append line num to ruleId, may remove/option later	    	    		
  	    			obligationId = sValue + "-Line-" +
							new Integer(myLineNumber).toString();;
   				log.trace(
    					"TRACE:\t created obligationId: key: " + s +
    					",  with sValue: " + sValue + 
    					"\n\t\t\tresults in obligationId\n\t\t\t\t" + 
    					obligationId);
  				}
  				break;
  			case 1:
  				if (s.equals(OPENAZ_OBLIGATION_FULFILL_ON)) {
  					i = size; // force break on loop condition
  	    			log.trace(
       				"TRACE:   Inner loop: key matched:" + 
       				OPENAZ_OBLIGATION_FULFILL_ON +
       				" now test value: sValue = " + sValue);
  	    			obligationFulfillOnStr = sValue;
   				log.trace(
   					"TRACE:\t created obligation fulfillOn key: " + s +
   					",  with sValue: " + sValue + 
   					"\n\t\t\tresults in obligationFulfillOnStr" + 
   					"\n\t\t\t\t" + obligationFulfillOnStr +
  						" which will be converted " + 
  						"to lower case for processing");
   				// force it lower case, so users don't need to worry
   				obligationFulfillOnStr = 
   						obligationFulfillOnStr.toLowerCase();
  				}
  				break;
  			} // end switch (i)
  		} // end for (i<size)
  	} // end for (more keys)

// set default data
  	if (obligationId == null)
  	{
  		obligationId = "defaultObligationID-LineNumber-" +
		new Integer(myLineNumber).toString();
  		log.trace(
  			"TRACE: no ObligationId provided, so setting default to: " +
  			obligationId);
  	}
  	if (obligationFulfillOnStr == null) {
  		obligationFulfillOnStr = OPENAZ_RULE_EFFECT_DENY;
  		log.trace(
      			"TRACE: no FulfillOn provided, so setting default to: " +
      			obligationFulfillOnStr);
  	}
int obligationFulfillOn = Result.DECISION_DENY; // default
if (obligationFulfillOnStr.length() > 0) {
	if (obligationFulfillOnStr.equals(OPENAZ_RULE_EFFECT_DENY)) {
		obligationFulfillOn = Result.DECISION_DENY;
		log.trace("TRACE(" + curLineCtx.getLineNumber() + 
			") setting Obligation FulfillOn = Deny");
	} else if (obligationFulfillOnStr.equals(OPENAZ_RULE_EFFECT_PERMIT)) {
		obligationFulfillOn = Result.DECISION_PERMIT;
		log.trace("TRACE(" + curLineCtx.getLineNumber() + 
			") setting Obligation FulfillOn = Permit");
	}
}
   
// process Obligation attributes collected above in obligationAmeList
// move the AMEs to an array and process
   int ameSize = obligationAmeList.size();
   AttributeMatchExpression[] obligationAme = 
   	new AttributeMatchExpression[ameSize];
   Iterator<AttributeMatchExpression> itAme = 
   	obligationAmeList.iterator();
   for (int i=0; i<ameSize; i++){
   	obligationAme[i] = itAme.next();
   	log.trace(
   		"TRACE: retrieving obligation attr: " +
   			obligationAme[i].attributeId);
   }
   List obligationAttributeList = new ArrayList();
   try {
       obligationAttributeList = 
       	xpb.createObligationAttributeList(obligationAme);
	log.trace("TRACE:  " + 
		"\n\tLine# " + curLineCtx.getLineNumber() +
		": Creating Obligation to include in resultObject - " +
		"available tokens: \n\t\t" + curLineCtx.getTokens());
    Obligation obligation = new Obligation(
    		new URI(obligationId),
    		obligationFulfillOn,
    		obligationAttributeList);

    // what we are trying to do here is
    // return the obl plus reread the OB
    resultObject = new OpenAzXacmlObject(
			currentLineType,
			obligation,
			true,
			azObject.getReadAheadObject());
   } catch (URISyntaxException uri) {
   	String msgURI = uri.getMessage();
	throw new OpenAzParseException(
			msgURI, myLineNumber);		        	
   }
   return resultObject;
  }