下面列出了java.net.URI#toASCIIString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void appendAtomSelfLink(final XMLStreamWriter writer, final EntityInfoAggregator eia)
throws EntityProviderException {
URI self = properties.getSelfLink();
String selfLink = "";
if (self == null) {
selfLink = createSelfLink(eia);
} else {
selfLink = self.toASCIIString();
}
try {
writer.writeStartElement(FormatXml.ATOM_LINK);
writer.writeAttribute(FormatXml.ATOM_HREF, selfLink);
writer.writeAttribute(FormatXml.ATOM_REL, Edm.LINK_REL_SELF);
writer.writeAttribute(FormatXml.ATOM_TITLE, eia.getEntitySetName());
writer.writeEndElement();
} catch (XMLStreamException e) {
throw new EntityProviderProducerException(EntityProviderException.COMMON, e);
}
}
/**
* The supported API was added to the Viewing Service to provide the following information:
* The allowed extensions
* The extensions to channel mapping
* The RegExp information
* @return
* @throws IOException
* @throws URISyntaxException
*/
public Result viewableSupported()
throws IOException,
URISyntaxException
{
String scope[] = {};
ResultAuthentication authResult = authenticate( scope );
if( authResult.isError() )
{
return authResult;
}
String frag = makeURN( API_VIEWING, PATT_VIEW_SUPPORTED, null );
URI uri = new URI( _protocol, null, lookupHostname(), _port, frag , null, null );
URL url = new URL( uri.toASCIIString() );
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod( "GET" );
authResult.setAuthHeader( connection );
connection.setRequestProperty( "Accept", "Application/json" );
return new Result( connection );
}
@PUT
@Path("/multiLevelNestedActivity")
@LRA(value = LRA.Type.MANDATORY, end = false)
public Response multiLevelNestedActivity(
@HeaderParam(LRA_HTTP_RECOVERY_HEADER) URI recoveryId,
@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI nestedLRAId,
@QueryParam("nestedCnt") @DefaultValue("1") Integer nestedCnt) {
assertHeaderPresent(nestedLRAId, LRA_HTTP_CONTEXT_HEADER);
assertHeaderPresent(recoveryId, LRA_HTTP_RECOVERY_HEADER);
storeActivity(nestedLRAId, recoveryId);
// invoke resources that enlist nested LRAs
String[] lras = new String[nestedCnt + 1];
lras[0] = nestedLRAId.toASCIIString();
IntStream.range(1, lras.length).forEach(i -> lras[i] = restPutInvocation(nestedLRAId,"nestedActivity", ""));
return Response.ok(String.join(",", lras)).build();
}
/**
* Constructor.
*
* @param uri the uri
*/
public Tag(URI uri) {
if (uri == null) {
throw new NullPointerException("URI for tag must be provided.");
}
this.value = uri.toASCIIString();
}
public Result viewableDeregister(
String viewableURN
)
throws IOException,
URISyntaxException
{
String scope[] = { SCOPE_DATA_READ, SCOPE_DATA_WRITE };
ResultAuthentication authResult = authenticate( scope );
if( authResult.isError() )
{
return authResult;
}
viewableURN = new String( Base64.encodeBase64( viewableURN.getBytes() ) );
String params[] = { viewableURN };
String frag = makeURN( API_VIEWING, PATT_VIEW_DEREGISTER, params );
URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null );
URL url = new URL( uri.toASCIIString() );
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod( "DELETE" );
authResult.setAuthHeader( connection );
// connection.setRequestProperty( "Accept", "Application/json" );
return new Result( connection );
}
public ResultViewerService viewableQuery(
String viewableURN
)
throws IOException,
URISyntaxException
{
String scope[] = { SCOPE_DATA_READ };
ResultAuthentication authResult = authenticate( scope );
if( authResult.isError() )
{
return new ResultViewerService( authResult );
}
viewableURN = new String( Base64.encodeBase64( viewableURN.getBytes() ) );
String params[] = { viewableURN };
String frag = makeURN( API_VIEWING, PATT_VIEW_QUERY, params );
URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null );
URL url = new URL( uri.toASCIIString() );
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod( "GET" );
authResult.setAuthHeader( connection );
connection.setRequestProperty( "Accept", "Application/json" );
return new ResultViewerService( connection );
}
@Override
protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String email = request.getParameter("email");
String browser = request.getParameter("browser");
String userAgent = request.getParameter("user_agent");
String trackingData = request.getParameter("tracking_data");
if (Strings.isNullOrEmpty(email)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid arguments");
return;
}
DBSignup signup = new DBSignup();
signup.setEmail(email);
signup.setBrowser(browser);
signup.setUserAgent(userAgent);
signup.setTrackingData(trackingData);
try (Manager mgr = ManagerFactory.getInstance().newManager()) {
// Note: multiple signup records from the same email address are permitted.
// They may be signing up with different browsers.
mgr.signupDao.create(signup);
mgr.commitTransaction();
}
String fragment = "";
if (browser.equals("chrome")) {
fragment = "#u=" + URLEncoder.encode(email, "UTF-8");
}
URI uri = new URI(WEB_SERVER_SCHEME, null, WEB_SERVER_HOST, WEB_SERVER_PORT, INSTALL_PATH, null, null);
String redirectLocation = uri.toASCIIString() + fragment;
response.sendRedirect(redirectLocation);
}
private String getProxyUrl(RMAppAttempt appAttempt) {
String url = null;
final String scheme = WebAppUtils.getHttpSchemePrefix(conf);
try {
String proxy = WebAppUtils.getProxyHostAndPort(conf);
URI proxyUri = ProxyUriUtils.getUriFromAMUrl(scheme, proxy);
URI result = ProxyUriUtils.getProxyUri(null, proxyUri, appAttempt
.getAppAttemptId().getApplicationId());
url = result.toASCIIString();
} catch (URISyntaxException ex) {
Assert.fail();
}
return url;
}
public void a(JsonWriter jsonwriter, URI uri)
{
String s;
if (uri == null)
{
s = null;
} else
{
s = uri.toASCIIString();
}
jsonwriter.value(s);
}
protected AtomicReference<URI> createURI(final Feed parent, String uri) throws URISyntaxException {
URI reqUri = new URI(uri);
if (reqUri.getHost() == null) {
for (Feed p = parent; p != null; p = p.parent) {
final URI parentURI = new URI(p.link.uri);
if (parentURI.isAbsolute()) {
reqUri = parentURI.resolve(reqUri);
uri = reqUri.toASCIIString();
break;
}
}
}
return new AtomicReference<URI>(reqUri);
}
/**
* Returns a {@code CouchURIHelper} for a given Cloudant or CouchDB instance.
*/
public CouchURIHelper(URI rootUri) {
this.rootUri = rootUri;
this.rootUriString = rootUri.toASCIIString();
}
/**
* Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
* due to limitation on request size).
*
* @return the list of headers that will be used in every example after
**/
private static List<Entry<String, String>> formget(
Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
// XXX /formget
// No use of HttpPostRequestEncoder since not a POST
Channel channel = bootstrap.connect(host, port).sync().channel();
// Prepare the HTTP request.
QueryStringEncoder encoder = new QueryStringEncoder(get);
// add Form attribute
encoder.addParam("getform", "GET");
encoder.addParam("info", "first value");
encoder.addParam("secondinfo", "secondvalue ���&");
// not the big one since it is not compatible with GET size
// encoder.addParam("thirdinfo", textArea);
encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
encoder.addParam("Send", "Send");
URI uriGet = new URI(encoder.toString());
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
HttpHeaders headers = request.headers();
headers.set(HttpHeaderNames.HOST, host);
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//connection will not close but needed
// headers.set("Connection","keep-alive");
// headers.set("Keep-Alive","300");
headers.set(
HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar"))
);
// send request
channel.writeAndFlush(request);
// Wait for the server to close the connection.
channel.closeFuture().sync();
// convert headers to list
return headers.entries();
}
@Override
public boolean canHandlePlugin(URI pluginURI) {
String uriStr = pluginURI.toASCIIString();
return uriStr.startsWith(modelRavenURI.toASCIIString())
&& uriStr.endsWith(className);
}
/**
* Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
* due to limitation on request size).
*
* @return the list of headers that will be used in every example after
**/
private static List<Entry<String, String>> formget(
Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
// XXX /formget
// No use of HttpPostRequestEncoder since not a POST
Channel channel = bootstrap.connect(host, port).sync().channel();
// Prepare the HTTP request.
QueryStringEncoder encoder = new QueryStringEncoder(get);
// add Form attribute
encoder.addParam("getform", "GET");
encoder.addParam("info", "first value");
encoder.addParam("secondinfo", "secondvalue ���&");
// not the big one since it is not compatible with GET size
// encoder.addParam("thirdinfo", textArea);
encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
encoder.addParam("Send", "Send");
URI uriGet = new URI(encoder.toString());
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
HttpHeaders headers = request.headers();
headers.set(HttpHeaderNames.HOST, host);
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//connection will not close but needed
// headers.set("Connection","keep-alive");
// headers.set("Keep-Alive","300");
headers.set(
HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar"))
);
// send request
channel.writeAndFlush(request);
// Wait for the server to close the connection.
channel.closeFuture().sync();
// convert headers to list
return headers.entries();
}
@Override
public boolean canHandlePlugin(URI activityURI) {
String activityUriStr = activityURI.toASCIIString();
return activityUriStr.startsWith(activityRavenURI.toASCIIString())
&& activityUriStr.endsWith(activityClassName);
}
public String readEntityReferenceID() {
URI id = getEntity() == null ? null : getEntity().getId();
return id == null ? null : id.toASCIIString();
}
private UriBuilder(URI uri) {
this.uri = new StringBuilder(uri.toASCIIString());
}
private void lookupOrDownload(
final URI sourceFileUri,
final File destinationFile
) throws DownloadException, IOException {
final String uriString = sourceFileUri.toASCIIString();
log.debug("Lookup: {}", uriString);
// Unique id to store the resource on local disk
final String resourceCacheId = getResourceCacheId(sourceFileUri);
// Get a handle to the resource
final Resource resource;
try {
resource = resourceLoader.getResource(uriString);
} catch (Throwable t) {
log.error(
"Failed to retrieve resource: {}, {} - {}",
uriString,
t.getClass().getSimpleName(),
t.getMessage()
);
throw t;
}
if (!resource.exists()) {
throw new DownloadException("Resource not found: " + uriString);
}
final long resourceLastModified = resource.lastModified();
//Handle to resourceCacheId/version
final File cacheResourceVersionDir = getCacheResourceVersionDir(
resourceCacheId,
resourceLastModified
);
//Create the resource version dir in cache if it does not exist
createDirectoryStructureIfNotExists(cacheResourceVersionDir);
try (
CloseableLock lock = fileLockFactory.getLock(
touchCacheResourceVersionLockFile(
resourceCacheId,
resourceLastModified
)
)
) {
//Critical section begin
lock.lock();
//Handle to the resource cached locally
final File cachedResourceVersionDataFile = getCacheResourceVersionDataFile(
resourceCacheId,
resourceLastModified
);
if (!cachedResourceVersionDataFile.exists()) {
log.debug(
"Cache miss: {} (id: {})",
uriString,
resourceCacheId
);
// Download the resource into the download file in cache
// resourceCacheId/version/data.tmp
final File cachedResourceVersionDownloadFile = getCacheResourceVersionDownloadFile(
resourceCacheId,
resourceLastModified
);
try (
InputStream in = resource.getInputStream();
OutputStream out = new FileOutputStream(cachedResourceVersionDownloadFile)
) {
FileCopyUtils.copy(in, out);
Files.move(cachedResourceVersionDownloadFile, cachedResourceVersionDataFile);
}
} else {
log.debug(
"Cache hit: {} (id: {})",
uriString,
resourceCacheId
);
}
//Copy from cache data file resourceCacheId/version/DATA_FILE_NAME to targetFile
Files.copy(cachedResourceVersionDataFile, destinationFile);
//Critical section end
} catch (LockException e) {
throw new DownloadException("Error downloading dependency", e);
}
//Clean up any older versions
cleanUpTaskExecutor.execute(
new CleanupOlderVersionsTask(resourceCacheId, resourceLastModified)
);
}
/**
* Use this API to create a bucket. Buckets are arbitrary spaces created and owned by services. Bucket
* keys are unique within the data center or region in which they were created. The service creating
* the bucket is the owner of the bucket, and the owning service will always have full access to a bucket.
* A bucket key cannot be changed once it is created.
* <p>
* Buckets must have a retention policy attached to them at create time. Policy options are:
* Transient,
* Temporary,
* Persistent
* @param bucketKey A unique name you assign to a bucket. It must be globally unique across
* all applications and regions, otherwise the call will fail. Possible
* values: -_.a-z0-9 (between 3-128 characters in length). Note that you cannot
* change a bucket key.
* @param policy
* @param region The region where the bucket resides Acceptable values: US, EMEA Default: US
* @return
* @throws IOException
* @throws URISyntaxException
*/
public ResultCreateBucket bucketCreate(
String bucketKey,
String policy,
String region
)
throws IOException,
URISyntaxException
{
String scope[] = { SCOPE_BUCKET_CREATE };
ResultAuthentication authResult = authenticate( scope );
if( authResult.isError() )
{
return new ResultCreateBucket( authResult );
}
JSONObject j_bucket = new JSONObject();
j_bucket.put( KEY_BUCKETKEY, bucketKey.toLowerCase() );
j_bucket.put( KEY_POLICY_KEY, policy );
String jStr = j_bucket.toString();
String frag = makeURN( API_OSS, PATT_BUCKET, null );
URI uri = new URI( _protocol, null, lookupHostname(), _port, frag , null, null );
URL url = new URL( uri.toASCIIString() );
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if( region != null && region.length() > 0 )
{
connection.setRequestProperty( "x-ads-region", region );
}
connection.setRequestMethod( "POST" );
authResult.setAuthHeader( connection );
connection.setRequestProperty( "Accept", "Application/json" );
connection.setRequestProperty( "Content-Length", "" + jStr.length() );
connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );
connection.setDoOutput( true );
OutputStream os = null;
try
{
os = connection.getOutputStream();
os.write(jStr.getBytes(Charset.forName("UTF-8")));
}
finally
{
if( os != null ) os.close();
}
ResultCreateBucket result = new ResultCreateBucket( connection );
return result;
}
/**
* Encodes the path so that it can be safely used in an URI.
* @param asciiOnly
* if true, return only ASCII characters (e.g. encode umlauts)
* @return encoded path as described in RFC 2396
*/
public static String encodeURIPath(String path, boolean asciiOnly) throws URISyntaxException {
URI relativeURI = new URI(null, null, path, null, null);
return asciiOnly ? relativeURI.toASCIIString() : relativeURI.getRawPath();
}