Add file to Java Client runtime

This commit is contained in:
Jianghao Lu 2015-04-08 15:02:32 -07:00
Родитель fb9b1327c8
Коммит 8ae8f2ab23
54 изменённых файлов: 4460 добавлений и 1 удалений

43
.gitignore поставляемый
Просмотреть файл

@ -96,10 +96,47 @@ ClientBin
# Build tasks
tools/*.dll
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# Azure Tooling #
node_modules
# Eclipse #
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# Other Tooling #
.classpath
.project
target
.idea
*.iml
# Sensitive files
*.keys
*.pfx
*.cer
*.pem
*.jks
# Backup & report files from converting a project to a new version of VS.
_UpgradeReport_Files/
@ -109,6 +146,10 @@ UpgradeLog*.XML
# NuGet
packages
# Mac development
# Mac OS #
.DS_Store
.DS_Store?
# Windows #
Thumbs.db

178
ClientRuntimes/Java/pom.xml Normal file
Просмотреть файл

@ -0,0 +1,178 @@
<!--
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.microsoft.rest</groupId>
<artifactId>autorest</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>Microsoft AutoRest Runtime for Java</name>
<description>This is the client runtime for AutoRest generated Java clients.</description>
<url>https://github.com/Azure/autorest</url>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<scm>
<url>scm:git:https://github.com/Azure/AutoRest</url>
<connection>scm:git:git://github.com/Azure/AutoRest.git</connection>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<legal><![CDATA[[INFO] Any downloads listed may be third party software. Microsoft grants you no rights for third party software.]]></legal>
<checkstyle.skip>true</checkstyle.skip>
</properties>
<developers>
<developer>
<id>microsoft</id>
<name>Microsoft</name>
</developer>
</developers>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-help-plugin</artifactId>
<version>2.1.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>evaluate</goal>
</goals>
<configuration>
<expression>legal</expression>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
<excludePackageNames>*.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage</excludePackageNames>
<bottom><![CDATA[<code>/**
<br/>* Copyright (c) Microsoft Corporation. All rights reserved.
<br/>* Licensed under the MIT License. See License.txt in the project root for license information.
<br/>*/</code>]]></bottom>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-help-plugin</artifactId>
<versionRange>[2.1.1,)</versionRange>
<goals>
<goal>evaluate</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<includes>
<include>**/Test*.java</include>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
<include>**/*TestCase.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

Просмотреть файл

@ -0,0 +1,21 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import com.microsoft.rest.core.pipeline.ServiceRequestFilter;
import com.microsoft.rest.core.pipeline.ServiceResponseFilter;
public interface FilterableService<T> {
FilterableService<T> withRequestFilterFirst(ServiceRequestFilter serviceRequestFilter);
FilterableService<T> withRequestFilterLast(ServiceRequestFilter serviceRequestFilter);
FilterableService<T> withResponseFilterFirst(ServiceResponseFilter serviceResponseFilter);
FilterableService<T> withResponseFilterLast(ServiceResponseFilter serviceResponseFilter);
}

Просмотреть файл

@ -0,0 +1,52 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
public class HttpOperationResponse {
private int httpStatusCode;
/**
* Gets the HTTP status code for the request.
*
* @return The HTTP status code.
*/
public int getStatusCode() {
return this.httpStatusCode;
}
/**
* Sets the HTTP status code for the request.
*
* @param httpStatusCode
* The HTTP status code.
*/
public void setStatusCode(int httpStatusCode) {
this.httpStatusCode = httpStatusCode;
}
private String requestId;
/**
* Gets the request identifier.
*
* @return The request identifier.
*/
public String getRequestId() {
return this.requestId;
}
/**
* Sets the request identifier.
*
* @param requestId
* The request identifier.
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
}

Просмотреть файл

@ -0,0 +1,84 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/*
* "not quite" ISO 8601 date time conversion routines
*/
public class ISO8601DateConverter {
// Note: because of the trailing "0000000", this is not quite ISO 8601
// compatible
private static final String DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String SHORT_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private static final String DATETIME_PATTERN_NO_S = "yyyy-MM-dd'T'HH:mm'Z'";
private static final String DATETIME_PATTERN_TO_DECIMAL = "yyyy-MM-dd'T'HH:mm:ss.";
public String format(Date date) {
DateFormat iso8601Format = new SimpleDateFormat(DATETIME_PATTERN,
Locale.US);
iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT"));
return iso8601Format.format(date);
}
public String shortFormat(Date date) {
DateFormat iso8601Format = new SimpleDateFormat(SHORT_DATETIME_PATTERN,
Locale.US);
iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT"));
return iso8601Format.format(date);
}
public Date parse(String date) throws ParseException {
if (date == null) {
return null;
}
int length = date.length();
if (length == 17) {
// [2012-01-04T23:21Z] length = 17
return parseDateFromString(date, DATETIME_PATTERN_NO_S);
} else if (length == 20) {
// [2012-01-04T23:21:59Z] length = 20
return parseDateFromString(date, SHORT_DATETIME_PATTERN);
} else if (length >= 22 && length <= 28) {
// [2012-01-04T23:21:59.1Z] length = 22
// [2012-01-04T23:21:59.1234567Z] length = 28
// Need to handle the milliseconds gently.
Date allExceptMilliseconds = parseDateFromString(date,
DATETIME_PATTERN_TO_DECIMAL);
long timeWithSecondGranularity = allExceptMilliseconds.getTime();
// Decimal point is at 19
String secondDecimalString = date.substring(19, date.indexOf('Z'));
Float secondDecimal = Float.parseFloat(secondDecimalString);
int milliseconds = Math.round(secondDecimal * 1000);
long timeInMS = timeWithSecondGranularity + milliseconds;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeInMS);
return calendar.getTime();
} else {
throw new IllegalArgumentException(String.format(
"Invalid Date String: %s", date));
}
}
private static Date parseDateFromString(final String value,
final String pattern) throws ParseException {
final DateFormat iso8601Format = new SimpleDateFormat(pattern,
Locale.US);
iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT"));
return iso8601Format.parse(value);
}
}

Просмотреть файл

@ -0,0 +1,163 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class LazyArrayList<E> extends ArrayList<E> implements LazyCollection {
private static final long serialVersionUID = 1L;
private boolean initialized;
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public void add(int index, E element) {
initialized = true;
super.add(index, element);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
initialized = true;
return super.addAll(index, c);
}
@Override
public E get(int index) {
initialized = true;
return super.get(index);
}
@Override
public int indexOf(Object o) {
initialized = true;
return super.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
initialized = true;
return super.lastIndexOf(o);
}
@Override
public ListIterator<E> listIterator() {
initialized = true;
return super.listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
initialized = true;
return super.listIterator(index);
}
@Override
public E remove(int index) {
initialized = true;
return super.remove(index);
}
@Override
public E set(int index, E element) {
initialized = true;
return super.set(index, element);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
initialized = true;
return super.subList(fromIndex, toIndex);
}
@Override
public boolean add(E e) {
initialized = true;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
initialized = true;
return super.addAll(c);
}
@Override
public void clear() {
initialized = true;
super.clear();
}
@Override
public boolean contains(Object o) {
initialized = true;
return super.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
initialized = true;
return super.containsAll(c);
}
@Override
public boolean isEmpty() {
initialized = true;
return super.isEmpty();
}
@Override
public boolean remove(Object o) {
initialized = true;
return super.remove(o);
}
@Override
public boolean removeAll(Collection<?> c) {
initialized = true;
return super.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
initialized = true;
return super.retainAll(c);
}
@Override
public int size() {
initialized = true;
return super.size();
}
@Override
public Object[] toArray() {
initialized = true;
return super.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
initialized = true;
return super.toArray(a);
}
@Override
public Iterator<E> iterator() {
initialized = true;
return super.iterator();
}
}

Просмотреть файл

@ -0,0 +1,12 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
public interface LazyCollection {
boolean isInitialized();
}

Просмотреть файл

@ -0,0 +1,96 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class LazyHashMap<K, V> extends HashMap<K, V> implements LazyCollection {
private static final long serialVersionUID = 1L;
private boolean initialized;
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public void clear() {
initialized = true;
super.clear();
}
@Override
public boolean containsKey(Object key) {
initialized = true;
return super.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
initialized = true;
return super.containsValue(value);
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
initialized = true;
return super.entrySet();
}
@Override
public V get(Object key) {
initialized = true;
return super.get(key);
}
@Override
public boolean isEmpty() {
initialized = true;
return super.isEmpty();
}
@Override
public Set<K> keySet() {
initialized = true;
return super.keySet();
}
@Override
public V put(K key, V value) {
initialized = true;
return super.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
initialized = true;
super.putAll(m);
}
@Override
public V remove(Object key) {
initialized = true;
return super.remove(key);
}
@Override
public int size() {
initialized = true;
return super.size();
}
@Override
public Collection<V> values() {
initialized = true;
return super.values();
}
}

Просмотреть файл

@ -0,0 +1,28 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/*
* JAXB adapter for RFC 1123 date element
*/
public class RFC1123DateAdapter extends XmlAdapter<String, Date> {
@Override
public Date unmarshal(String arg0) throws Exception {
return new RFC1123DateConverter().parse(arg0);
}
@Override
public String marshal(Date arg0) throws Exception {
return new RFC1123DateConverter().format(arg0);
}
}

Просмотреть файл

@ -0,0 +1,43 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/*
* RFC 1123 date to string conversion
*/
public class RFC1123DateConverter {
private static final String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
public String format(Date date) {
return getFormat().format(date);
}
public Date parse(String date) {
try {
return getFormat().parse(date);
} catch (ParseException e) {
String msg = String.format(
"The value \"%s\" is not a valid RFC 1123 date.", date);
throw new IllegalArgumentException(msg, e);
}
}
private DateFormat getFormat() {
DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN,
Locale.US);
rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT"));
return rfc1123Format;
}
}

Просмотреть файл

@ -0,0 +1,118 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import com.microsoft.rest.core.pipeline.HttpRequestInterceptorBackAdapter;
import com.microsoft.rest.core.pipeline.HttpRequestInterceptorFrontAdapter;
import com.microsoft.rest.core.pipeline.HttpResponseInterceptorBackAdapter;
import com.microsoft.rest.core.pipeline.HttpResponseInterceptorFrontAdapter;
import com.microsoft.rest.core.pipeline.ServiceRequestFilter;
import com.microsoft.rest.core.pipeline.ServiceResponseFilter;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public abstract class ServiceClient<TClient> implements
FilterableService<TClient>, Closeable {
private final ExecutorService executorService;
private CloseableHttpClient httpClient;
private HttpRequestInterceptorFrontAdapter httpRequestInterceptorFrontAdapter;
private HttpRequestInterceptorBackAdapter httpRequestInterceptorBackAdapter;
private HttpResponseInterceptorFrontAdapter httpResponseInterceptorFrontAdapter;
private HttpResponseInterceptorBackAdapter httpResponseInterceptorBackAdapter;
private final HttpClientBuilder httpClientBuilder;
public ServiceClient() {
this(HttpClientBuilder.create(), Executors.newCachedThreadPool());
}
public ServiceClient(HttpClientBuilder httpClientBuilder,
ExecutorService executorService) {
this.httpClientBuilder = httpClientBuilder;
this.executorService = executorService;
this.withRequestFilterFirst(new UserAgentFilter(this.getClass().getName()));
}
public ExecutorService getExecutorService() {
return this.executorService;
}
public CloseableHttpClient getHttpClient() {
if (this.httpClient == null) {
String proxyHost = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
if ((proxyHost != null) && (proxyPort != null)) {
HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
if (proxy != null) {
httpClientBuilder.setProxy(proxy);
}
}
this.httpClient = httpClientBuilder.build();
}
return this.httpClient;
}
@Override
public ServiceClient<TClient> withRequestFilterFirst(
ServiceRequestFilter serviceRequestFilter) {
if (httpRequestInterceptorFrontAdapter == null) {
httpRequestInterceptorFrontAdapter = new HttpRequestInterceptorFrontAdapter();
httpClientBuilder.addInterceptorFirst(httpRequestInterceptorFrontAdapter);
}
httpRequestInterceptorFrontAdapter.addFront(serviceRequestFilter);
return this;
}
@Override
public ServiceClient<TClient> withRequestFilterLast(
ServiceRequestFilter serviceRequestFilter) {
if (httpRequestInterceptorBackAdapter == null) {
httpRequestInterceptorBackAdapter = new HttpRequestInterceptorBackAdapter();
httpClientBuilder.addInterceptorLast(httpRequestInterceptorBackAdapter);
}
httpRequestInterceptorBackAdapter.addBack(serviceRequestFilter);
return this;
}
@Override
public ServiceClient<TClient> withResponseFilterFirst(
ServiceResponseFilter serviceResponseFilter) {
if (httpResponseInterceptorFrontAdapter == null) {
httpResponseInterceptorFrontAdapter = new HttpResponseInterceptorFrontAdapter();
httpClientBuilder.addInterceptorFirst(httpResponseInterceptorFrontAdapter);
}
httpResponseInterceptorFrontAdapter.addFront(serviceResponseFilter);
return this;
}
@Override
public ServiceClient<TClient> withResponseFilterLast(
ServiceResponseFilter serviceResponseFilter) {
if (httpResponseInterceptorBackAdapter == null) {
httpResponseInterceptorBackAdapter = new HttpResponseInterceptorBackAdapter();
httpClientBuilder.addInterceptorLast(httpResponseInterceptorBackAdapter);
}
httpResponseInterceptorBackAdapter.addBack(serviceResponseFilter);
return this;
}
@Override
public void close() throws IOException {
if (httpClient != null) {
httpClient.close();
}
}
}

Просмотреть файл

@ -0,0 +1,12 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
public interface ServiceOperations<TClient> {
TClient getClient();
}

Просмотреть файл

@ -0,0 +1,57 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import com.microsoft.rest.exception.ServiceException;
/**
* Exception indicating a service operation has timed out.
*/
public class ServiceTimeoutException extends ServiceException {
private static final long serialVersionUID = 6612846403178749361L;
/**
* Construct a ServiceTimeoutException instance with default parameters.
*/
public ServiceTimeoutException() {
}
/**
* Construct a ServiceTimeoutException instance with the specified message.
*
* @param message
* Exception message
*/
public ServiceTimeoutException(String message) {
super(message);
}
/**
* Construct a ServiceTimeoutException instance with specified message and
* cause
*
* @param message
* Exception message
* @param cause
* Exception that caused this exception to occur
*/
public ServiceTimeoutException(String message, Throwable cause) {
super(message, cause);
}
/**
* Construct a ServiceTimeoutException instance with the specified cause.
*
* @param cause
* Exception that caused this exception to occur
*/
public ServiceTimeoutException(Throwable cause) {
super(cause);
}
}

Просмотреть файл

@ -0,0 +1,30 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
public abstract class TimeSpan8601Converter {
public static String format(Duration duration) {
return duration.toString();
}
public static Duration parse(String duration) {
try {
DatatypeFactory factory = DatatypeFactory.newInstance();
return factory.newDuration(duration);
} catch (DatatypeConfigurationException e) {
String msg = String.format(
"The value \"%s\" is not a valid ISO8601 duration.",
duration);
throw new IllegalArgumentException(msg, e);
}
}
}

Просмотреть файл

@ -0,0 +1,87 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import com.microsoft.rest.core.pipeline.ServiceRequestContext;
import com.microsoft.rest.core.pipeline.ServiceRequestFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* The Class UserAgentFilter.
*/
public class UserAgentFilter implements ServiceRequestFilter {
/** The azure SDK product token. */
private String productUserAgent;
/**
* Instantiates a new user agent filter.
*/
public UserAgentFilter(String productUserAgent) {
this.productUserAgent = productUserAgent;
}
@Override
public void filter(ServiceRequestContext request) {
String userAgent;
if (request.getHeader("User-Agent") != null) {
String currentUserAgent = request.getHeader("User-Agent");
userAgent = productUserAgent + " " + currentUserAgent;
request.removeHeader("User-Agent");
} else {
userAgent = productUserAgent;
}
request.setHeader("User-Agent", userAgent);
}
/**
* Creates the azure SDK product token.
*
* @return the string
*/
private String createAzureSDKProductToken() {
String version = getVersionFromResources();
String productToken;
if ((version != null) && (!version.isEmpty())) {
productToken = version;
} else {
productToken = "";
}
return productToken;
}
/**
* Gets the version of the SDK from resources.
*
* @return the version from resources
*/
private String getVersionFromResources() {
String version = null;
Properties properties = new Properties();
try {
InputStream inputStream = getClass()
.getClassLoader()
.getResourceAsStream(
"META-INF/maven/com.microsoft.azure/azure-core/pom.properties");
if (inputStream != null) {
properties.load(inputStream);
version = properties.getProperty("version");
inputStream.close();
}
} catch (IOException e) {
// Do nothing
}
return version;
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<html>
<head />
<body>This package contains the core classes across difference services.
</body>
</html>

Просмотреть файл

@ -0,0 +1,35 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.protocol.HttpContext;
import java.util.LinkedList;
public class HttpRequestInterceptorAdapter implements HttpRequestInterceptor {
private LinkedList<ServiceRequestFilter> filters;
public HttpRequestInterceptorAdapter() {
filters = new LinkedList<ServiceRequestFilter>();
}
public LinkedList<ServiceRequestFilter> getFilterList()
{
return filters;
}
@Override
public void process(HttpRequest request, HttpContext context) {
HttpServiceRequestContext serviceRequestContext = new HttpServiceRequestContext(request, context);
for (ServiceRequestFilter filter : filters) {
filter.filter(serviceRequestContext);
}
}
}

Просмотреть файл

@ -0,0 +1,14 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
public class HttpRequestInterceptorBackAdapter extends HttpRequestInterceptorAdapter {
public void addBack(ServiceRequestFilter filter) {
getFilterList().addLast(filter);
}
}

Просмотреть файл

@ -0,0 +1,14 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
public class HttpRequestInterceptorFrontAdapter extends HttpRequestInterceptorAdapter {
public void addFront(ServiceRequestFilter filter) {
getFilterList().addFirst(filter);
}
}

Просмотреть файл

@ -0,0 +1,35 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.protocol.HttpContext;
import java.util.LinkedList;
public class HttpResponseInterceptorAdapter implements HttpResponseInterceptor {
private LinkedList<ServiceResponseFilter> filters;
public HttpResponseInterceptorAdapter() {
filters = new LinkedList<ServiceResponseFilter>();
}
public LinkedList<ServiceResponseFilter> getFilterList()
{
return filters;
}
@Override
public void process(HttpResponse response, HttpContext context) {
HttpServiceResponseContext serviceResponseContext = new HttpServiceResponseContext(response, context);
for (ServiceResponseFilter filter : filters) {
filter.filter(null, serviceResponseContext);
}
}
}

Просмотреть файл

@ -0,0 +1,14 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
public class HttpResponseInterceptorBackAdapter extends HttpResponseInterceptorAdapter {
public void addBack(ServiceResponseFilter filter) {
getFilterList().addLast(filter);
}
}

Просмотреть файл

@ -0,0 +1,14 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
public class HttpResponseInterceptorFrontAdapter extends HttpResponseInterceptorAdapter {
public void addFront(ServiceResponseFilter filter) {
getFilterList().addFirst(filter);
}
}

Просмотреть файл

@ -0,0 +1,99 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
public class HttpServiceRequestContext implements ServiceRequestContext {
private final HttpRequest clientRequest;
private final HttpContext httpContext;
public HttpServiceRequestContext(HttpRequest clientRequest,
HttpContext httpContext) {
this.clientRequest = clientRequest;
this.httpContext = httpContext;
}
@Override
public Object getProperty(final String name) {
return httpContext.getAttribute(name);
}
@Override
public void setProperty(final String name, final Object value) {
httpContext.setAttribute(name, value);
}
@Override
public Map<String, String> getAllHeaders() {
Map<String, String> allHeaders = new HashMap<String, String>();
for (Header header : clientRequest.getAllHeaders()) {
allHeaders.put(header.getName(), header.getValue());
}
return allHeaders;
}
@Override
public URI getURI() {
try {
return new URI(clientRequest.getRequestLine().getUri());
} catch (URISyntaxException e) {
return null;
}
}
@Override
public void setURI(final URI uri) {
// Do nothing. not supported
}
@Override
public String getMethod() {
return clientRequest.getRequestLine().getMethod();
}
@Override
public void setMethod(String method) {
// Do nothing. not supported
}
@Override
public Object getEntity() {
// Do nothing. not supported
return null;
}
@Override
public void setEntity(final Object entity) {
// Do nothing. not supported
}
@Override
public String getHeader(final String name) {
final Header first = clientRequest.getFirstHeader(name);
return first != null ? first.getValue() : null;
}
@Override
public void setHeader(final String name, final String value) {
clientRequest.setHeader(name, value);
}
@Override
public void removeHeader(final String name) {
clientRequest.removeHeaders(name);
}
}

Просмотреть файл

@ -0,0 +1,88 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.protocol.HttpContext;
public class HttpServiceResponseContext implements ServiceResponseContext {
private HttpResponse clientResponse;
private HttpContext httpContext;
public HttpServiceResponseContext(HttpResponse clientResponse,
HttpContext httpContext) {
this.clientResponse = clientResponse;
this.httpContext = httpContext;
}
@Override
public Object getProperty(String name) {
return httpContext.getAttribute(name);
}
@Override
public void setProperty(String name, Object value) {
httpContext.setAttribute(name, value);
}
@Override
public int getStatus() {
return clientResponse.getStatusLine().getStatusCode();
}
@Override
public void setStatus(int status) {
clientResponse.setStatusCode(status);
}
@Override
public boolean hasEntity() {
return clientResponse.getEntity() != null;
}
@Override
public String getHeader(String name) {
Header first = clientResponse.getFirstHeader(name);
if (first != null) {
return first.getValue();
}
return null;
}
@Override
public void setHeader(String name, String value) {
clientResponse.setHeader(name, value);
}
@Override
public void removeHeader(String name) {
clientResponse.removeHeaders(name);
}
@Override
public InputStream getEntityInputStream() {
try {
return clientResponse.getEntity().getContent();
} catch (IOException e) {
return null;
} catch (IllegalStateException e) {
return null;
}
}
@Override
public void setEntityInputStream(InputStream entity) {
clientResponse.setEntity(new InputStreamEntity(entity));
}
}

Просмотреть файл

@ -0,0 +1,37 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
import java.net.URI;
import java.util.Map;
public interface ServiceRequestContext {
String getMethod();
void setMethod(String method);
URI getURI();
void setURI(URI uri);
String getHeader(String name);
void setHeader(String name, String value);
void removeHeader(String name);
Object getEntity();
void setEntity(Object entity);
Object getProperty(String name);
void setProperty(String name, Object value);
Map<String, String> getAllHeaders();
}

Просмотреть файл

@ -0,0 +1,12 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
public interface ServiceRequestFilter {
void filter(ServiceRequestContext request);
}

Просмотреть файл

@ -0,0 +1,32 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
import java.io.InputStream;
public interface ServiceResponseContext {
int getStatus();
void setStatus(int status);
String getHeader(String name);
void setHeader(String name, String value);
void removeHeader(String name);
boolean hasEntity();
InputStream getEntityInputStream();
void setEntityInputStream(InputStream entity);
Object getProperty(String name);
void setProperty(String name, Object value);
}

Просмотреть файл

@ -0,0 +1,12 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.pipeline;
public interface ServiceResponseFilter {
void filter(ServiceRequestContext request, ServiceResponseContext response);
}

Просмотреть файл

@ -0,0 +1,5 @@
<html>
<head />
<body>This package contains the core classes across difference services.
</body>
</html>

Просмотреть файл

@ -0,0 +1,226 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
public class BOMInputStream extends InputStream {
/**
* Constructs a new <code>BOMInputStream</code>.
*
* @param inputStream an <code>InputStream</code>.
*
*/
public BOMInputStream(final InputStream inputStream) throws NullPointerException,
IOException {
if (inputStream == null) {
throw new NullPointerException();
}
pushbackInputStream = new PushbackInputStream(inputStream, 4);
final byte [] bom = new byte[4];
final int read = pushbackInputStream.read(bom);
switch(read) {
case 4:
if ((bom[0] == (byte) 0xFF)
&& (bom[1] == (byte) 0xFE)
&& (bom[2] == (byte) 0x00)
&& (bom[3] == (byte) 0x00)) {
this.bom = BOM.UTF_32_LE;
break;
}
else
if ((bom[0] == (byte) 0x00)
&& (bom[1] == (byte) 0x00)
&& (bom[2] == (byte) 0xFE)
&& (bom[3] == (byte) 0xFF)) {
this.bom = BOM.UTF_32_BE;
break;
}
case 3:
if ((bom[0] == (byte) 0xEF)
&& (bom[1] == (byte) 0xBB)
&& (bom[2] == (byte) 0xBF)) {
this.bom = BOM.UTF_8;
break;
}
case 2:
if ((bom[0] == (byte) 0xFF)
&& (bom[1] == (byte) 0xFE)) {
this.bom = BOM.UTF_16_LE;
break;
}
else if ((bom[0] == (byte) 0xFE)
&& (bom[1] == (byte) 0xFF)) {
this.bom = BOM.UTF_16_BE;
break;
}
default:
this.bom = BOM.NONE;
break;
}
if (read > 0) {
// If bytes read were not from a BOM, unread them.
pushbackInputStream.unread(bom, 0, read);
}
if (this.bom != BOM.NONE) {
pushbackInputStream.skip(this.bom.bytes.length);
}
}
/**
* {@inheritDoc}
*/
public int read() throws IOException {
return pushbackInputStream.read();
}
/**
* {@inheritDoc}
*/
public int read(final byte [] b) throws IOException,
NullPointerException {
return pushbackInputStream.read(b, 0, b.length);
}
/**
* {@inheritDoc}
*/
public int read(final byte [] b,
final int off,
final int len) throws IOException,
NullPointerException {
return pushbackInputStream.read(b, off, len);
}
/**
* {@inheritDoc}
*/
public long skip(final long n) throws IOException {
return pushbackInputStream.skip(n);
}
/**
* {@inheritDoc}
*/
public int available() throws IOException {
return pushbackInputStream.available();
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
pushbackInputStream.close();
}
/**
* {@inheritDoc}
*/
public synchronized void mark(final int readlimit) {
pushbackInputStream.mark(readlimit);
}
/**
* {@inheritDoc}
*/
public synchronized void reset() throws IOException {
pushbackInputStream.reset();
}
/**
* {@inheritDoc}
*/
public boolean markSupported() {
return pushbackInputStream.markSupported();
}
private final PushbackInputStream pushbackInputStream;
private final BOM bom;
public static final class BOM {
/**
* NONE.
*/
public static final BOM NONE = new BOM(new byte[] {}, "NONE");
/**
* UTF-8 BOM (EF BB BF).
*/
public static final BOM UTF_8 = new BOM(new byte[] {(byte) 0xEF,
(byte) 0xBB,
(byte) 0xBF },
"UTF-8");
/**
* UTF-16, little-endian (FF FE).
*/
public static final BOM UTF_16_LE = new BOM(new byte[] {(byte) 0xFF,
(byte) 0xFE },
"UTF-16 little-endian");
/**
* UTF-16, big-endian (FE FF).
*/
public static final BOM UTF_16_BE = new BOM(new byte[] {(byte) 0xFE,
(byte) 0xFF },
"UTF-16 big-endian");
/**
* UTF-32, little-endian (FF FE 00 00).
*/
public static final BOM UTF_32_LE = new BOM(new byte[] {(byte) 0xFF,
(byte) 0xFE,
(byte) 0x00,
(byte) 0x00 },
"UTF-32 little-endian");
/**
* UTF-32, big-endian (00 00 FE FF).
*/
public static final BOM UTF_32_BE = new BOM(new byte[] {(byte) 0x00,
(byte) 0x00,
(byte) 0xFE,
(byte) 0xFF },
"UTF-32 big-endian");
/**
* Returns a <code>String</code> representation of this <code>BOM</code>
* value.
*/
public String toString() {
return description;
}
/**
* Returns the bytes corresponding to this <code>BOM</code> value.
*/
public byte[] getBytes() {
final byte[] result = new byte[bytes.length];
System.arraycopy(bytes, 0, result, 0, bytes.length);
return result;
}
private BOM(final byte [] bom, final String description) {
this.bytes = bom;
this.description = description;
}
private final byte [] bytes;
private final String description;
}
}

Просмотреть файл

@ -0,0 +1,314 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.utils;
/**
* RESERVED FOR INTERNAL USE. Provides Base64 encoding, decoding, and validation
* functionality.
*/
public final class Base64 {
/**
* The Base 64 Characters.
*/
private static final String BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* Decoded values, -1 is invalid character, -2 is = pad character.
*/
private static final byte [] DECODE_64 = {
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, // 0-15
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*
* 16-
* 31
*/
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /*
* 32-
* 47
*/
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, /*
* 48-
* 63
*/
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 64-79 */
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /*
* 80-
* 95
*/
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /*
* 96-
* 111
*/
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /*
* 112-
* 127
*/
};
/**
* Decodes a given Base64 string into its corresponding byte array.
*
* @param data
* the Base64 string, as a <code>String</code> object, to decode
*
* @return the corresponding decoded byte array
* @throws IllegalArgumentException
* If the string is not a valid base64 encoded string
*/
public static byte[] decode(final String data) {
int byteArrayLength = 3 * data.length() / 4;
if (data.endsWith("==")) {
byteArrayLength -= 2;
} else if (data.endsWith("=")) {
byteArrayLength -= 1;
}
final byte[] retArray = new byte[byteArrayLength];
int byteDex = 0;
int charDex = 0;
for (; charDex < data.length(); charDex += 4) {
// get 4 chars, convert to 3 bytes
final int char1 = DECODE_64[(byte) data.charAt(charDex)];
final int char2 = DECODE_64[(byte) data.charAt(charDex + 1)];
final int char3 = DECODE_64[(byte) data.charAt(charDex + 2)];
final int char4 = DECODE_64[(byte) data.charAt(charDex + 3)];
if (char1 < 0 || char2 < 0 || char3 == -1 || char4 == -1) {
// invalid character(-1), or bad padding (-2)
throw new IllegalArgumentException(
"The String is not a valid Base64-encoded string.");
}
int tVal = char1 << 18;
tVal += char2 << 12;
tVal += (char3 & 0xff) << 6;
tVal += char4 & 0xff;
if (char3 == -2) {
// two "==" pad chars, check bits 12-24
tVal &= 0x00FFF000;
retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
} else if (char4 == -2) {
// one pad char "=" , check bits 6-24.
tVal &= 0x00FFFFC0;
retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF);
} else {
// No pads take all 3 bytes, bits 0-24
retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF);
retArray[byteDex++] = (byte) (tVal & 0xFF);
}
}
return retArray;
}
/**
* Decodes a given Base64 string into its corresponding byte array.
*
* @param data
* the Base64 string, as a <code>String</code> object, to decode
*
* @return the corresponding decoded byte array
* @throws IllegalArgumentException
* If the string is not a valid base64 encoded string
*/
public static Byte[] decodeAsByteObjectArray(final String data) {
int byteArrayLength = 3 * data.length() / 4;
if (data.endsWith("==")) {
byteArrayLength -= 2;
} else if (data.endsWith("=")) {
byteArrayLength -= 1;
}
final Byte[] retArray = new Byte[byteArrayLength];
int byteDex = 0;
int charDex = 0;
for (; charDex < data.length(); charDex += 4) {
// get 4 chars, convert to 3 bytes
final int char1 = DECODE_64[(byte) data.charAt(charDex)];
final int char2 = DECODE_64[(byte) data.charAt(charDex + 1)];
final int char3 = DECODE_64[(byte) data.charAt(charDex + 2)];
final int char4 = DECODE_64[(byte) data.charAt(charDex + 3)];
if (char1 < 0 || char2 < 0 || char3 == -1 || char4 == -1) {
// invalid character(-1), or bad padding (-2)
throw new IllegalArgumentException(
"The String is not a valid Base64-encoded string.");
}
int tVal = char1 << 18;
tVal += char2 << 12;
tVal += (char3 & 0xff) << 6;
tVal += char4 & 0xff;
if (char3 == -2) {
// two "==" pad chars, check bits 12-24
tVal &= 0x00FFF000;
retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
} else if (char4 == -2) {
// one pad char "=" , check bits 6-24.
tVal &= 0x00FFFFC0;
retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF);
} else {
// No pads take all 3 bytes, bits 0-24
retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF);
retArray[byteDex++] = (byte) (tVal & 0xFF);
}
}
return retArray;
}
/**
* Encodes a byte array as a Base64 string.
*
* @param data
* the byte array to encode
* @return the Base64-encoded string, as a <code>String</code> object
*/
public static String encode(final byte[] data) {
final StringBuilder builder = new StringBuilder();
final int dataRemainder = data.length % 3;
int j = 0;
int n = 0;
for (; j < data.length; j += 3) {
if (j < data.length - dataRemainder) {
n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8)
+ (data[j + 2] & 0xFF);
} else {
if (dataRemainder == 1) {
n = (data[j] & 0xFF) << 16;
} else if (dataRemainder == 2) {
n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8);
}
}
// Left here for readability
// byte char1 = (byte) ((n >>> 18) & 0x3F);
// byte char2 = (byte) ((n >>> 12) & 0x3F);
// byte char3 = (byte) ((n >>> 6) & 0x3F);
// byte char4 = (byte) (n & 0x3F);
builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 18) & 0x3F)));
builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 12) & 0x3F)));
builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 6) & 0x3F)));
builder.append(BASE_64_CHARS.charAt((byte) (n & 0x3F)));
}
final int bLength = builder.length();
// append '=' to pad
if (data.length % 3 == 1) {
builder.replace(bLength - 2, bLength, "==");
} else if (data.length % 3 == 2) {
builder.replace(bLength - 1, bLength, "=");
}
return builder.toString();
}
/**
* Encodes a byte array as a Base64 string.
*
* @param data
* the byte array to encode
* @return the Base64-encoded string, as a <code>String</code> object
*/
public static String encode(final Byte[] data) {
final StringBuilder builder = new StringBuilder();
final int dataRemainder = data.length % 3;
int j = 0;
int n = 0;
for (; j < data.length; j += 3) {
if (j < data.length - dataRemainder) {
n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8)
+ (data[j + 2] & 0xFF);
} else {
if (dataRemainder == 1) {
n = (data[j] & 0xFF) << 16;
} else if (dataRemainder == 2) {
n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8);
}
}
// Left here for readability
// byte char1 = (byte) ((n >>> 18) & 0x3F);
// byte char2 = (byte) ((n >>> 12) & 0x3F);
// byte char3 = (byte) ((n >>> 6) & 0x3F);
// byte char4 = (byte) (n & 0x3F);
builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 18) & 0x3F)));
builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 12) & 0x3F)));
builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 6) & 0x3F)));
builder.append(BASE_64_CHARS.charAt((byte) (n & 0x3F)));
}
final int bLength = builder.length();
// append '=' to pad
if (data.length % 3 == 1) {
builder.replace(bLength - 2, bLength, "==");
} else if (data.length % 3 == 2) {
builder.replace(bLength - 1, bLength, "=");
}
return builder.toString();
}
/**
* Determines whether the given string contains only Base64 characters.
*
* @param data
* the string, as a <code>String</code> object, to validate
* @return <code>true</code> if <code>data</code> is a valid Base64 string,
* otherwise <code>false</code>
*/
public static boolean validateIsBase64String(final String data) {
if (data == null || data.length() % 4 != 0) {
return false;
}
for (int m = 0; m < data.length(); m++) {
final byte charByte = (byte) data.charAt(m);
// pad char detected
if (DECODE_64[charByte] == -2) {
if (m < data.length() - 2) {
return false;
} else if (m == data.length() - 2
&& DECODE_64[(byte) data.charAt(m + 1)] != -2) {
return false;
}
}
if (charByte < 0 || DECODE_64[charByte] == -1) {
return false;
}
}
return true;
}
/**
* Private Default Ctor.
*/
private Base64() {
// No op
}
}

Просмотреть файл

@ -0,0 +1,68 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.utils;
import org.apache.commons.lang.StringUtils;
import java.util.List;
public class CollectionStringBuilder {
private static final String DEFAULT_SEPARATOR = ",";
private final StringBuilder sb;
private static String separator;
public CollectionStringBuilder() {
sb = new StringBuilder();
separator = DEFAULT_SEPARATOR;
}
public CollectionStringBuilder(String separator) {
sb = new StringBuilder();
CollectionStringBuilder.separator = separator;
}
public void add(String representation) {
if (sb.length() > 0) {
sb.append(separator);
}
sb.append(representation);
}
public void addValue(boolean value, String representation) {
if (value) {
add(representation);
}
}
public static String join(List<String> values) {
return StringUtils.join(values, separator);
}
public static String join(List<String> values, String separator) {
return StringUtils.join(values, separator);
}
public static String join(String... values) {
CollectionStringBuilder sb = new CollectionStringBuilder();
for (String value : values) {
sb.add(value);
}
return sb.toString();
}
@Override
public String toString() {
if (sb.length() == 0) {
return null;
}
return sb.toString();
}
}

Просмотреть файл

@ -0,0 +1,687 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.utils;
/**
* Defines constants for use with blob operations, HTTP headers, and query
* strings.
*/
public final class Constants {
/**
* Defines constants for use Analytics requests.
*/
public static class AnalyticsConstants {
/**
* The XML element for the Analytics RetentionPolicy Days.
*/
public static final String DAYS_ELEMENT = "Days";
/**
* The XML element for the Default Service Version.
*/
public static final String DEFAULT_SERVICE_VERSION = "DefaultServiceVersion";
/**
* The XML element for the Analytics Logging Delete type.
*/
public static final String DELETE_ELEMENT = "Delete";
/**
* The XML element for the Analytics RetentionPolicy Enabled.
*/
public static final String ENABLED_ELEMENT = "Enabled";
/**
* The XML element for the Analytics Metrics IncludeAPIs.
*/
public static final String INCLUDE_APIS_ELEMENT = "IncludeAPIs";
/**
* The XML element for the Analytics Logging
*/
public static final String LOGGING_ELEMENT = "Logging";
/**
* The XML element for the Analytics Metrics
*/
public static final String METRICS_ELEMENT = "Metrics";
/**
* The XML element for the Analytics Logging Read type.
*/
public static final String READ_ELEMENT = "Read";
/**
* The XML element for the Analytics RetentionPolicy.
*/
public static final String RETENTION_POLICY_ELEMENT = "RetentionPolicy";
/**
* The XML element for the StorageServiceProperties
*/
public static final String STORAGE_SERVICE_PROPERTIES_ELEMENT = "StorageServiceProperties";
/**
* The XML element for the Analytics Version
*/
public static final String VERSION_ELEMENT = "Version";
/**
* The XML element for the Analytics Logging Write type.
*/
public static final String WRITE_ELEMENT = "Write";
}
/**
* Defines constants for use with HTTP headers.
*/
public static class HeaderConstants {
/**
* The Accept header.
*/
public static final String ACCEPT = "Accept";
/**
* The Accept header.
*/
public static final String ACCEPT_CHARSET = "Accept-Charset";
/**
* The Authorization header.
*/
public static final String AUTHORIZATION = "Authorization";
/**
* The CacheControl header.
*/
public static final String CACHE_CONTROL = "Cache-Control";
/**
* The header that specifies blob caching control.
*/
public static final String CACHE_CONTROL_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "blob-cache-control";
/**
* The Comp value.
*/
public static final String COMP = "comp";
/**
* The ContentEncoding header.
*/
public static final String CONTENT_ENCODING = "Content-Encoding";
/**
* The ContentLangauge header.
*/
public static final String CONTENT_LANGUAGE = "Content-Language";
/**
* The ContentLength header.
*/
public static final String CONTENT_LENGTH = "Content-Length";
/**
* The ContentMD5 header.
*/
public static final String CONTENT_MD5 = "Content-MD5";
/**
* The ContentRange header.
*/
public static final String CONTENT_RANGE = "Cache-Range";
/**
* The ContentType header.
*/
public static final String CONTENT_TYPE = "Content-Type";
/**
* The header for copy source.
*/
public static final String COPY_SOURCE_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "copy-source";
/**
* The header that specifies the date.
*/
public static final String DATE = PREFIX_FOR_STORAGE_HEADER + "date";
/**
* The header to delete snapshots.
*/
public static final String DELETE_SNAPSHOT_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "delete-snapshots";
/**
* The ETag header.
*/
public static final String ETAG = "ETag";
/**
* Buffer width used to copy data to output streams.
*/
public static final int HTTP_UNUSED_306 = 306;
/**
* The IfMatch header.
*/
public static final String IF_MATCH = "If-Match";
/**
* The IfModifiedSince header.
*/
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
/**
* The IfNoneMatch header.
*/
public static final String IF_NONE_MATCH = "If-None-Match";
/**
* The IfUnmodifiedSince header.
*/
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
/**
* The header that specifies lease ID.
*/
public static final String LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "lease-id";
/**
* The header that specifies lease status.
*/
public static final String LEASE_STATUS = PREFIX_FOR_STORAGE_HEADER
+ "lease-status";
/**
* The header that specifies lease state.
*/
public static final String LEASE_STATE = PREFIX_FOR_STORAGE_HEADER
+ "lease-state";
/**
* The header that specifies lease duration.
*/
public static final String LEASE_DURATION = PREFIX_FOR_STORAGE_HEADER
+ "lease-duration";
/**
* The header that specifies copy status.
*/
public static final String COPY_STATUS = PREFIX_FOR_STORAGE_HEADER
+ "copy-status";
/**
* The header that specifies copy progress.
*/
public static final String COPY_PROGRESS = PREFIX_FOR_STORAGE_HEADER
+ "copy-progress";
/**
* The header that specifies copy status description.
*/
public static final String COPY_STATUS_DESCRIPTION = PREFIX_FOR_STORAGE_HEADER
+ "copy-status-description";
/**
* The header that specifies copy id.
*/
public static final String COPY_ID = PREFIX_FOR_STORAGE_HEADER
+ "copy-id";
/**
* The header that specifies copy source.
*/
public static final String COPY_SOURCE = PREFIX_FOR_STORAGE_HEADER
+ "copy-source";
/**
* The header that specifies copy completion time.
*/
public static final String COPY_COMPLETION_TIME = PREFIX_FOR_STORAGE_HEADER
+ "copy-completion-time";
/**
* The header prefix for metadata.
*/
public static final String PREFIX_FOR_STORAGE_METADATA = "x-ms-meta-";
/**
* The header prefix for properties.
*/
public static final String PREFIX_FOR_STORAGE_PROPERTIES = "x-ms-prop-";
/**
* The Range header.
*/
public static final String RANGE = "Range";
/**
* The header that specifies if the request will populate the ContentMD5
* header for range gets.
*/
public static final String RANGE_GET_CONTENT_MD5 = PREFIX_FOR_STORAGE_HEADER
+ "range-get-content-md5";
/**
* The format string for specifying ranges.
*/
public static final String RANGE_HEADER_FORMAT = "bytes=%d-%d";
/**
* The header that indicates the request ID.
*/
public static final String REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "request-id";
/**
* The header that indicates the client request ID.
*/
public static final String CLIENT_REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "client-request-id";
/**
* The header for the If-Match condition.
*/
public static final String SOURCE_IF_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "source-if-match";
/**
* The header for the If-Modified-Since condition.
*/
public static final String SOURCE_IF_MODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "source-if-modified-since";
/**
* The header for the If-None-Match condition.
*/
public static final String SOURCE_IF_NONE_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "source-if-none-match";
/**
* The header for the If-Unmodified-Since condition.
*/
public static final String SOURCE_IF_UNMODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "source-if-unmodified-since";
/**
* The header for the source lease id.
*/
public static final String SOURCE_LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "source-lease-id";
/**
* The header for data ranges.
*/
public static final String STORAGE_RANGE_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "range";
/**
* The header for storage version.
*/
public static final String STORAGE_VERSION_HEADER = PREFIX_FOR_STORAGE_HEADER
+ "version";
/**
* The current storage version header value.
*/
public static final String TARGET_STORAGE_VERSION = "2012-02-12";
/**
* The UserAgent header.
*/
public static final String USER_AGENT = "User-Agent";
/**
* Specifies the value to use for UserAgent header.
*/
public static final String USER_AGENT_PREFIX = "WA-Storage";
/**
* Specifies the value to use for UserAgent header.
*/
public static final String USER_AGENT_VERSION = "Client v0.1.3.2";
}
/**
* Defines constants for use with query strings.
*/
public static class QueryConstants {
/**
* The query component for the SAS signature.
*/
public static final String SIGNATURE = "sig";
/**
* The query component for the signed SAS expiry time.
*/
public static final String SIGNED_EXPIRY = "se";
/**
* The query component for the signed SAS identifier.
*/
public static final String SIGNED_IDENTIFIER = "si";
/**
* The query component for the signed SAS permissions.
*/
public static final String SIGNED_PERMISSIONS = "sp";
/**
* The query component for the signed SAS resource.
*/
public static final String SIGNED_RESOURCE = "sr";
/**
* The query component for the signed SAS start time.
*/
public static final String SIGNED_START = "st";
/**
* The query component for the SAS start partition key.
*/
public static final String START_PARTITION_KEY = "spk";
/**
* The query component for the SAS start row key.
*/
public static final String START_ROW_KEY = "srk";
/**
* The query component for the SAS end partition key.
*/
public static final String END_PARTITION_KEY = "epk";
/**
* The query component for the SAS end row key.
*/
public static final String END_ROW_KEY = "erk";
/**
* The query component for the SAS table name.
*/
public static final String SAS_TABLE_NAME = "tn";
/**
* The query component for the signing SAS key.
*/
public static final String SIGNED_KEY = "sk";
/**
* The query component for the signed SAS version.
*/
public static final String SIGNED_VERSION = "sv";
/**
* The query component for snapshot time.
*/
public static final String SNAPSHOT = "snapshot";
}
/**
* The master Windows Azure Storage header prefix.
*/
public static final String PREFIX_FOR_STORAGE_HEADER = "x-ms-";
/**
* Constant representing a kilobyte (Non-SI version).
*/
public static final int KB = 1024;
/**
* Constant representing a megabyte (Non-SI version).
*/
public static final int MB = 1024 * KB;
/**
* Constant representing a gigabyte (Non-SI version).
*/
public static final int GB = 1024 * MB;
/**
* Buffer width used to copy data to output streams.
*/
public static final int BUFFER_COPY_LENGTH = 8 * KB;
/**
* Default client side timeout, in milliseconds, for all service clients.
*/
public static final int DEFAULT_TIMEOUT_IN_MS = 90 * 1000;
/**
* XML element for delimiters.
*/
public static final String DELIMITER_ELEMENT = "Delimiter";
/**
* An empty <code>String</code> to use for comparison.
*/
public static final String EMPTY_STRING = "";
/**
* XML element for page range end elements.
*/
public static final String END_ELEMENT = "End";
/**
* XML element for error codes.
*/
public static final String ERROR_CODE = "Code";
/**
* XML element for exception details.
*/
public static final String ERROR_EXCEPTION = "ExceptionDetails";
/**
* XML element for exception messages.
*/
public static final String ERROR_EXCEPTION_MESSAGE = "ExceptionMessage";
/**
* XML element for stack traces.
*/
public static final String ERROR_EXCEPTION_STACK_TRACE = "StackTrace";
/**
* XML element for error messages.
*/
public static final String ERROR_MESSAGE = "Message";
/**
* XML root element for errors.
*/
public static final String ERROR_ROOT_ELEMENT = "Error";
/**
* XML element for the ETag.
*/
public static final String ETAG_ELEMENT = "Etag";
/**
* Constant for False.
*/
public static final String FALSE = "false";
/**
* Specifies HTTP.
*/
public static final String HTTP = "http";
/**
* Specifies HTTPS.
*/
public static final String HTTPS = "https";
/**
* XML attribute for IDs.
*/
public static final String ID = "Id";
/**
* XML element for an invalid metadata name.
*/
public static final String INVALID_METADATA_NAME = "x-ms-invalid-name";
/**
* XML element for the last modified date.
*/
public static final String LAST_MODIFIED_ELEMENT = "Last-Modified";
/**
* XML element for the lease status.
*/
public static final String LEASE_STATUS_ELEMENT = "LeaseStatus";
/**
* XML element for the lease state.
*/
public static final String LEASE_STATE_ELEMENT = "LeaseState";
/**
* XML element for the lease duration.
*/
public static final String LEASE_DURATION_ELEMENT = "LeaseDuration";
/**
* XML element for the copy id.
*/
public static final String COPY_ID_ELEMENT = "CopyId";
/**
* XML element for the copy status.
*/
public static final String COPY_STATUS_ELEMENT = "CopyStatus";
/**
* XML element for the copy source .
*/
public static final String COPY_SOURCE_ELEMENT = "CopySource";
/**
* XML element for the copy progress.
*/
public static final String COPY_PROGRESS_ELEMENT = "CopyProgress";
/**
* XML element for the copy completion time.
*/
public static final String COPY_COMPLETION_TIME_ELEMENT = "CopyCompletionTime";
/**
* XML element for the copy status description.
*/
public static final String COPY_STATUS_DESCRIPTION_ELEMENT = "CopyStatusDescription";
/**
* Constant signaling the resource is locked.
*/
public static final String LOCKED_VALUE = "Locked";
/**
* XML element for a marker.
*/
public static final String MARKER_ELEMENT = "Marker";
/**
* XML element for maximum results.
*/
public static final String MAX_RESULTS_ELEMENT = "MaxResults";
/**
* Number of default concurrent requests for parallel operation.
*/
public static final int MAXIMUM_SEGMENTED_RESULTS = 5000;
/**
* The maximum size, in bytes, of a given stream mark operation.
*/
// Note if BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES is updated
// then this needs to be as well.
public static final int MAX_MARK_LENGTH = 64 * MB;
/**
* XML element for the metadata.
*/
public static final String METADATA_ELEMENT = "Metadata";
/**
* XML element for names.
*/
public static final String NAME_ELEMENT = "Name";
/**
* XML element for the next marker.
*/
public static final String NEXT_MARKER_ELEMENT = "NextMarker";
/**
* XML element for a prefix.
*/
public static final String PREFIX_ELEMENT = "Prefix";
/**
* Constant for True.
*/
public static final String TRUE = "true";
/**
* Constant signaling the resource is unlocked.
*/
public static final String UNLOCKED_VALUE = "Unlocked";
/**
* XML element for the URL.
*/
public static final String URL_ELEMENT = "Url";
/**
* XML element for a signed identifier.
*/
public static final String SIGNED_IDENTIFIER_ELEMENT = "SignedIdentifier";
/**
* XML element for signed identifiers.
*/
public static final String SIGNED_IDENTIFIERS_ELEMENT = "SignedIdentifiers";
/**
* XML element for an access policy.
*/
public static final String ACCESS_POLICY = "AccessPolicy";
/**
* Maximum number of shared access policy identifiers supported by server.
*/
public static final int MAX_SHARED_ACCESS_POLICY_IDENTIFIERS = 5;
/**
* XML element for the start time of an access policy.
*/
public static final String START = "Start";
/**
* XML element for the end time of an access policy.
*/
public static final String EXPIRY = "Expiry";
/**
* XML element for the permission of an access policy.
*/
public static final String PERMISSION = "Permission";
/**
* Private Default Ctor
*/
private Constants() {
// No op
}
}

Просмотреть файл

@ -0,0 +1,33 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.utils;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public final class StreamUtils {
private StreamUtils() {
}
public static String toString(final InputStream inputStream)
throws IOException {
final BufferedInputStream bufferedStream = new BufferedInputStream(
inputStream);
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int result = bufferedStream.read();
while (result >= 0) {
final byte data = (byte) result;
byteStream.write(data);
result = bufferedStream.read();
}
return byteStream.toString();
}
}

Просмотреть файл

@ -0,0 +1,771 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
* RESERVED FOR INTERNAL USE. A class which provides utility methods.
*/
public final class Utility {
/**
* Stores a reference to the GMT time zone.
*/
public static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");
/**
* Stores a reference to the UTC time zone.
*/
public static final TimeZone UTC_ZONE = TimeZone.getTimeZone("UTC");
/**
* Stores a reference to the US locale.
*/
public static final Locale LOCALE_US = Locale.US;
/**
* Stores a reference to the RFC1123 date/time pattern.
*/
private static final String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
/**
* Stores a reference to the ISO8061 date/time pattern.
*/
public static final String ISO8061_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'";
/**
* Stores a reference to the ISO8061 date/time pattern.
*/
public static final String ISO8061_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
/**
* Stores a reference to the ISO8061_LONG date/time pattern.
*/
public static final String ISO8061_LONG_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'";
/**
* Asserts that a value is not <code>null</code>.
*
* @param param
* A <code>String</code> that represents the name of the
* parameter, which becomes the exception message text if the
* <code>value</code> parameter is <code>null</code>.
* @param value
* An <code>Object</code> object that represents the value of the
* specified parameter. This is the value being asserted as not
* <code>null</code>.
*/
public static void assertNotNull(final String param, final Object value) {
if (value == null) {
throw new IllegalArgumentException(param);
}
}
/**
* Asserts that the specified string is not <code>null</code> or empty.
*
* @param param
* A <code>String</code> that represents the name of the
* parameter, which becomes the exception message text if the
* <code>value</code> parameter is <code>null</code> or an empty
* string.
* @param value
* A <code>String</code> that represents the value of the
* specified parameter. This is the value being asserted as not
* <code>null</code> and not an empty string.
*/
public static void assertNotNullOrEmpty(final String param,
final String value) {
assertNotNull(param, value);
if (Utility.isNullOrEmpty(value)) {
throw new IllegalArgumentException(
"The argument must not be an empty string or null:"
.concat(param));
}
}
/**
* Asserts that the specified integer is in the valid range.
*
* @param param
* A <code>String</code> that represents the name of the
* parameter, which becomes the exception message text if the
* <code>value</code> parameter is out of bounds.
* @param value
* The value of the specified parameter.
* @param min
* The minimum value for the specified parameter.
* @param max
* The maximum value for the specified parameter.
*/
public static void assertInBounds(final String param, final int value,
final int min, final int max) {
if (value < min || value > max) {
throw new IllegalArgumentException(
String.format(
"The value of the parameter %s should be between %s and %s.",
param, min, max));
}
}
/**
* Creates an XML stream reader from the specified input stream.
*
* @param streamRef
* An <code>InputStream</code> object that represents the input
* stream to use as the source.
*
* @return A <code>java.xml.stream.XMLStreamReader</code> object that
* represents the XML stream reader created from the specified input
* stream.
*
* @throws XMLStreamException
* If the XML stream reader could not be created.
*/
public static XMLStreamReader createXMLStreamReaderFromStream(
final InputStream streamRef) throws XMLStreamException {
// TODO optimization keep this static
XMLInputFactory xmlif = null;
xmlif = XMLInputFactory.newInstance();
xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,
Boolean.TRUE);
xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,
Boolean.FALSE);
// set the IS_COALESCING property to true , if application desires to
// get whole text data as one event.
xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
return xmlif.createXMLStreamReader(streamRef);
}
/**
* Creates an XML stream reader from the specified input stream.
*
* @param reader
* An <code>InputStreamReader</code> object that represents the
* input reader to use as the source.
*
* @return A <code>java.xml.stream.XMLStreamReader</code> object that
* represents the XML stream reader created from the specified input
* stream.
*
* @throws XMLStreamException
* If the XML stream reader could not be created.
*/
public static XMLStreamReader createXMLStreamReaderFromReader(
final Reader reader) throws XMLStreamException {
// TODO optimization keep this static
XMLInputFactory xmlif = null;
xmlif = XMLInputFactory.newInstance();
xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,
Boolean.TRUE);
xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,
Boolean.FALSE);
// set the IS_COALESCING property to true , if application desires to
// get whole text data as one event.
xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
return xmlif.createXMLStreamReader(reader);
}
/**
* Returns a value that indicates whether a specified URI is a path-style
* URI.
*
* @param baseURI
* A <code>java.net.URI</code> value that represents the URI
* being checked.
* @param knownAccountName
* A <code>String</code> that represents the known account name
* to examine with <code>baseURI</code>, or <code>null</code> to
* examine <code>baseURI</code> on its own for being a path-style
* URI.
*
* @return <code>true</code> if the specified URI is path-style; otherwise,
* <code>false</code>.
*/
public static boolean determinePathStyleFromUri(final URI baseURI,
final String knownAccountName) {
String path = baseURI.getPath();
if (knownAccountName == null) {
if (Utility.isNullOrEmpty(path) || path.equals("/")) {
return false;
}
return true;
}
if (!Utility.isNullOrEmpty(path) && path.startsWith("/")) {
path = path.substring(1);
}
if (Utility.isNullOrEmpty(path)
|| baseURI.getHost().startsWith(knownAccountName)) {
return false;
} else if (!Utility.isNullOrEmpty(path)
&& path.startsWith(knownAccountName)) {
return true;
}
return false;
}
/**
* Returns a byte array that represents the data of a <code>long</code>
* value.
*
* @param value
* The value from which the byte array will be returned.
*
* @return A byte array that represents the data of the specified
* <code>long</code> value.
*/
public static byte[] getBytesFromLong(final long value) {
final byte[] tempArray = new byte[8];
for (int m = 0; m < 8; m++) {
tempArray[7 - m] = (byte) ((value >> (8 * m)) & 0xFF);
}
return tempArray;
}
/**
* Returns the current GMT date/time using the RFC1123 pattern.
*
* @return A <code>String</code> that represents the current GMT date/time
* using the RFC1123 pattern.
*/
public static String getGMTTime() {
final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN,
LOCALE_US);
rfc1123Format.setTimeZone(GMT_ZONE);
return rfc1123Format.format(new Date());
}
public static String getTimeByZoneAndFormat(Date date, TimeZone zone,
String format) {
final DateFormat formatter = new SimpleDateFormat(format, LOCALE_US);
formatter.setTimeZone(zone);
return formatter.format(date);
}
/**
* Returns the GTM date/time for the specified value using the RFC1123
* pattern.
*
* @param inDate
* A <code>Date</code> object that represents the date to convert
* to GMT date/time in the RFC1123 pattern.
*
* @return A <code>String</code> that represents the GMT date/time for the
* specified value using the RFC1123 pattern.
*/
public static String getGMTTime(final Date inDate) {
final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN,
LOCALE_US);
rfc1123Format.setTimeZone(GMT_ZONE);
return rfc1123Format.format(inDate);
}
/**
* Returns the standard header value from the specified connection request,
* or an empty string if no header value has been specified for the request.
*
* @param conn
* An <code>HttpURLConnection</code> object that represents the
* request.
* @param headerName
* A <code>String</code> that represents the name of the header
* being requested.
*
* @return A <code>String</code> that represents the header value, or
* <code>null</code> if there is no corresponding header value for
* <code>headerName</code>.
*/
public static String getStandardHeaderValue(final HttpURLConnection conn,
final String headerName) {
final String headerValue = conn.getRequestProperty(headerName);
// Coalesce null value
return headerValue == null ? Constants.EMPTY_STRING : headerValue;
}
/**
* Returns the current UTC date/time using the RFC1123 pattern.
*
* @return A <code>String</code> that represents the current UTC date/time
* using the RFC1123 pattern.
*/
protected static String getUTCTime() {
final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN,
LOCALE_US);
rfc1123Format.setTimeZone(UTC_ZONE);
return rfc1123Format.format(new Date());
}
/**
* Returns the UTC date/time for the specified value using the RFC1123
* pattern.
*
* @param inDate
* A <code>Date</code> object that represents the date to convert
* to UTC date/time in the RFC1123 pattern.
*
* @return A <code>String</code> that represents the UTC date/time for the
* specified value using the RFC1123 pattern.
*/
protected static String getUTCTime(final Date inDate) {
final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN,
LOCALE_US);
rfc1123Format.setTimeZone(UTC_ZONE);
return rfc1123Format.format(inDate);
}
/**
* Returns the UTC date/time for the specified value using the ISO8061
* pattern.
*
* @param value
* A <code>Date</code> object that represents the date to convert
* to UTC date/time in the ISO8061 pattern. If this value is
* <code>null</code>, this method returns an empty string.
*
* @return A <code>String</code> that represents the UTC date/time for the
* specified value using the ISO8061 pattern, or an empty string if
* <code>value</code> is <code>null</code>.
*/
public static String getUTCTimeOrEmpty(final Date value) {
if (value == null) {
return Constants.EMPTY_STRING;
}
final DateFormat iso8061Format = new SimpleDateFormat(ISO8061_PATTERN,
LOCALE_US);
iso8061Format.setTimeZone(UTC_ZONE);
return iso8061Format.format(value);
}
/**
* Creates an instance of the <code>IOException</code> class using the
* specified exception.
*
* @param ex
* An <code>Exception</code> object that represents the exception
* used to create the IO exception.
*
* @return A <code>java.io.IOException</code> object that represents the
* created IO exception.
*/
public static IOException initIOException(final Exception ex) {
final IOException retEx = new IOException();
retEx.initCause(ex);
return retEx;
}
/**
* Returns a value that indicates whether the specified string is
* <code>null</code> or empty.
*
* @param value
* A <code>String</code> being examined for <code>null</code> or
* empty.
*
* @return <code>true</code> if the specified value is <code>null</code> or
* empty; otherwise, <code>false</code>
*/
public static boolean isNullOrEmpty(final String value) {
return value == null || value.length() == 0;
}
/**
* Parses a connection string and returns its values as a hash map of
* key/value pairs.
*
* @param parseString
* A <code>String</code> that represents the connection string to
* parse.
*
* @return A <code>java.util.HashMap</code> object that represents the hash
* map of the key / value pairs parsed from the connection string.
*/
public static HashMap<String, String> parseAccountString(
final String parseString) {
// 1. split name value pairs by splitting on the ';' character
final String[] valuePairs = parseString.split(";");
final HashMap<String, String> retVals = new HashMap<String, String>();
// 2. for each field value pair parse into appropriate map entries
for (int m = 0; m < valuePairs.length; m++) {
final int equalDex = valuePairs[m].indexOf("=");
if (equalDex < 1) {
throw new IllegalArgumentException("Invalid Connection String");
}
final String key = valuePairs[m].substring(0, equalDex);
final String value = valuePairs[m].substring(equalDex + 1);
// 2.1 add to map
retVals.put(key, value);
}
return retVals;
}
/**
* Returns a GMT date in the specified format
*
* @param value
* the string to parse
* @return the GMT date, as a <code>Date</code>
* @throws ParseException
* If the specified string is invalid
*/
public static Date parseDateFromString(final String value,
final String pattern, final TimeZone timeZone)
throws ParseException {
final DateFormat rfc1123Format = new SimpleDateFormat(pattern,
Utility.LOCALE_US);
rfc1123Format.setTimeZone(timeZone);
return rfc1123Format.parse(value);
}
/**
* Returns a date in the ISO8061 long pattern for the specified string.
*
* @param value
* A <code>String</code> that represents the string to parse.
*
* @return A <code>Date</code> object that represents the date in the
* ISO8061 long pattern.
*
* @throws ParseException
* If the specified string is invalid.
*/
public static Date parseISO8061LongDateFromString(final String value)
throws ParseException {
return parseDateFromString(value, ISO8061_LONG_PATTERN,
Utility.UTC_ZONE);
}
/**
* Returns a GMT date in the RFC1123 pattern for the specified string.
*
* @param value
* A <code>String</code> that represents the string to parse.
*
* @return A <code>Date</code> object that represents the GMT date in the
* RFC1123 pattern.
*
* @throws ParseException
* If the specified string is invalid.
*/
public static Date parseRFC1123DateFromStringInGMT(final String value)
throws ParseException {
return parseDateFromString(value, RFC1123_PATTERN, Utility.GMT_ZONE);
}
/**
* Reads character data for the specified XML element from an XML stream
* reader. This method will read start events, characters, and end events
* from a stream.
*
* @param xmlr
* An <code>XMLStreamReader</code> object that represents the
* source XML stream reader.
*
* @param elementName
* A <code>String</code> that represents XML element name.
*
* @return A <code>String</code> that represents the character data for the
* specified element.
*
* @throws XMLStreamException
* If an XML stream failure occurs.
*/
public static String readElementFromXMLReader(final XMLStreamReader xmlr,
final String elementName) throws XMLStreamException {
return readElementFromXMLReader(xmlr, elementName, true);
}
/**
* Reads character data for the specified XML element from an XML stream
* reader. This method will read start events, characters, and end events
* from a stream.
*
* @param xmlr
* An <code>XMLStreamReader</code> object that represents the
* source XML stream reader.
*
* @param elementName
* A <code>String</code> that represents XML element name.
* @param returnNullOnEmpty
* If true, returns null when a empty string is read, otherwise
* EmptyString ("") is returned.
*
* @return A <code>String</code> that represents the character data for the
* specified element.
*
* @throws XMLStreamException
* If an XML stream failure occurs.
*/
public static String readElementFromXMLReader(final XMLStreamReader xmlr,
final String elementName, boolean returnNullOnEmpty)
throws XMLStreamException {
xmlr.require(XMLStreamConstants.START_ELEMENT, null, elementName);
int eventType = xmlr.next();
final StringBuilder retVal = new StringBuilder();
if (eventType == XMLStreamConstants.CHARACTERS) {
// This do while is in case the XMLStreamReader does not have
// the IS_COALESCING property set
// to true which may result in text being read in multiple events
// If we ensure all xmlreaders have this property we can optimize
// the StringBuilder and while loop
// away
do {
retVal.append(xmlr.getText());
eventType = xmlr.next();
} while (eventType == XMLStreamConstants.CHARACTERS);
}
xmlr.require(XMLStreamConstants.END_ELEMENT, null, elementName);
if (retVal.length() == 0) {
return returnNullOnEmpty ? null : Constants.EMPTY_STRING;
} else {
return retVal.toString();
}
}
/**
* Determines the relative difference between the two specified URIs.
*
* @param baseURI
* A <code>java.net.URI</code> object that represents the base
* URI for which <code>toUri</code> will be made relative.
* @param toUri
* A <code>java.net.URI</code> object that represents the URI to
* make relative to <code>baseURI</code>.
*
* @return A <code>String</code> that either represents the relative URI of
* <code>toUri</code> to <code>baseURI</code>, or the URI of
* <code>toUri</code> itself, depending on whether the hostname and
* scheme are identical for <code>toUri</code> and
* <code>baseURI</code>. If the hostname and scheme of
* <code>baseURI</code> and <code>toUri</code> are identical, this
* method returns a relative URI such that if appended to
* <code>baseURI</code>, it will yield <code>toUri</code>. If the
* hostname or scheme of <code>baseURI</code> and <code>toUri</code>
* are not identical, this method returns the full URI specified by
* <code>toUri</code>.
*
* @throws URISyntaxException
* If <code>baseURI</code> or <code>toUri</code> is invalid.
*/
public static String safeRelativize(final URI baseURI, final URI toUri)
throws URISyntaxException {
// For compatibility followed
// http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx
// if host and scheme are not identical return from uri
if (!baseURI.getHost().equals(toUri.getHost())
|| !baseURI.getScheme().equals(toUri.getScheme())) {
return toUri.toString();
}
final String basePath = baseURI.getPath();
String toPath = toUri.getPath();
int truncatePtr = 1;
// Seek to first Difference
// int maxLength = Math.min(basePath.length(), toPath.length());
int m = 0;
int ellipsesCount = 0;
for (; m < basePath.length(); m++) {
if (m >= toPath.length()) {
if (basePath.charAt(m) == '/') {
ellipsesCount++;
}
} else {
if (basePath.charAt(m) != toPath.charAt(m)) {
break;
} else if (basePath.charAt(m) == '/') {
truncatePtr = m + 1;
}
}
}
if (m == toPath.length()) {
// No path difference, return query + fragment
return new URI(null, null, null, toUri.getQuery(),
toUri.getFragment()).toString();
} else {
toPath = toPath.substring(truncatePtr);
final StringBuilder sb = new StringBuilder();
while (ellipsesCount > 0) {
sb.append("../");
ellipsesCount--;
}
if (!Utility.isNullOrEmpty(toPath)) {
sb.append(toPath);
}
if (!Utility.isNullOrEmpty(toUri.getQuery())) {
sb.append("?");
sb.append(toUri.getQuery());
}
if (!Utility.isNullOrEmpty(toUri.getFragment())) {
sb.append("#");
sb.append(toUri.getRawFragment());
}
return sb.toString();
}
}
/**
* Trims the specified character from the end of a string.
*
* @param value
* A <code>String</code> that represents the string to trim.
* @param trimChar
* The character to trim from the end of the string.
*
* @return The string with the specified character trimmed from the end.
*/
protected static String trimEnd(final String value, final char trimChar) {
int stopDex = value.length() - 1;
while (stopDex > 0 && value.charAt(stopDex) == trimChar) {
stopDex--;
}
return stopDex == value.length() - 1 ? value : value.substring(stopDex);
}
/**
* Trims whitespace from the beginning of a string.
*
* @param value
* A <code>String</code> that represents the string to trim.
*
* @return The string with whitespace trimmed from the beginning.
*/
public static String trimStart(final String value) {
int spaceDex = 0;
while (spaceDex < value.length() && value.charAt(spaceDex) == ' ') {
spaceDex++;
}
return value.substring(spaceDex);
}
/**
* Private Default Ctor.
*/
private Utility() {
// No op
}
public static void checkNullaryCtor(Class<?> clazzType) {
Constructor<?> ctor = null;
try {
ctor = clazzType.getDeclaredConstructor((Class<?>[]) null);
} catch (Exception e) {
throw new IllegalArgumentException(
"Class type must have contain a nullary constructor.");
}
if (ctor == null) {
throw new IllegalArgumentException(
"Class type must have contain a nullary constructor.");
}
}
public static Date parseDate(String dateString) {
try {
if (dateString.length() == 28) {
// "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"->
// [2012-01-04T23:21:59.1234567Z] length = 28
return Utility.parseDateFromString(dateString,
Utility.ISO8061_LONG_PATTERN, Utility.UTC_ZONE);
} else if (dateString.length() == 20) {
// "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length =
// 20
return Utility.parseDateFromString(dateString,
Utility.ISO8061_PATTERN, Utility.UTC_ZONE);
} else if (dateString.length() == 17) {
// "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17
return Utility.parseDateFromString(dateString,
Utility.ISO8061_PATTERN_NO_SECONDS, Utility.UTC_ZONE);
} else if (dateString.length() == 27) {
// "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"->
// [2012-01-04T23:21:59.123456Z] length = 27
return Utility.parseDateFromString(dateString,
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", Utility.UTC_ZONE);
} else if (dateString.length() == 26) {
// "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"->
// [2012-01-04T23:21:59.12345Z] length = 26
return Utility.parseDateFromString(dateString,
"yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'", Utility.UTC_ZONE);
} else if (dateString.length() == 25) {
// "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z]
// length = 25
return Utility.parseDateFromString(dateString,
"yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'", Utility.UTC_ZONE);
} else if (dateString.length() == 24) {
// "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z]
// length = 24
return Utility.parseDateFromString(dateString,
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Utility.UTC_ZONE);
} else if (dateString.length() == 23) {
// "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z]
// length = 23
return Utility.parseDateFromString(dateString,
"yyyy-MM-dd'T'HH:mm:ss.SS'Z'", Utility.UTC_ZONE);
} else if (dateString.length() == 22) {
// "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z]
// length = 22
return Utility.parseDateFromString(dateString,
"yyyy-MM-dd'T'HH:mm:ss.S'Z'", Utility.UTC_ZONE);
} else {
throw new IllegalArgumentException(String.format(
"Invalid Date String: %s", dateString));
}
} catch (final ParseException e) {
throw new IllegalArgumentException(String.format(
"Invalid Date String: %s", dateString), e);
}
}
}

Просмотреть файл

@ -0,0 +1,84 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core.utils;
import java.util.ArrayList;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public abstract class XmlUtility {
public static Element getElementByTagNameNS(Node element, String namespace,
String name) {
NodeList elements = element.getChildNodes();
CharSequence colon = ":";
if (elements != null) {
for (int i = 0; i < elements.getLength(); i++) {
if (elements.item(i).getNodeType() == Node.ELEMENT_NODE
&& (elements.item(i).getAttributes().getNamedItemNS("http://www.w3.org/2001/XMLSchema-instance", "nil") == null
|| !"true".equals(elements.item(i).getAttributes().getNamedItemNS("http://www.w3.org/2001/XMLSchema-instance", "nil")))) {
Element currentElement = (Element) elements.item(i);
String nodeName = currentElement.getNodeName();
String nodeNameOnly = nodeName;
if (nodeName.contains(colon)) {
String[] nodeNameSplit = nodeName.split(":");
nodeNameOnly = nodeNameSplit[1];
}
if ((currentElement.getNamespaceURI() == null
|| currentElement.getNamespaceURI().equals(namespace))
&& nodeNameOnly.equals(name)) {
return currentElement;
}
}
}
}
return null;
}
public static ArrayList<Element> getElementsByTagNameNS(Node element,
String namespace, String name) {
ArrayList<Element> childElements = new ArrayList<Element>();
NodeList elements = element.getChildNodes();
if (elements != null) {
for (int i = 0; i < elements.getLength(); i++) {
if (elements.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) elements.item(i);
if ((currentElement.getNamespaceURI() == null
|| currentElement.getNamespaceURI().equals(namespace))
&& currentElement.getNodeName().equals(name)) {
childElements.add(currentElement);
}
}
}
}
return childElements;
}
public static Element getElementByTagName(Node element, String name) {
NodeList elements = element.getChildNodes();
if (elements != null) {
for (int i = 0; i < elements.getLength(); i++) {
if (elements.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) elements.item(i);
if (currentElement.getNodeName().equals(name)) {
return currentElement;
}
}
}
}
return null;
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<html>
<head />
<body>This package contains the core classes across difference services.
</body>
</html>

Просмотреть файл

@ -0,0 +1,48 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.credentials;
/**
* The Class CertificateCloudCredentials.
*/
public class BasicAuthenticationCredentials extends ServiceClientCredentials {
private String userName;
private String password;
/**
* Instantiates a new basic authentication credential.
*/
public BasicAuthenticationCredentials() {
}
/**
* Instantiates a new basic authentication credential.
*
* @param userName the uri
* @param password the subscription id
*/
public BasicAuthenticationCredentials(String userName, String password) {
this.userName = userName;
this.password = password;
}
/**
* Get the username of the credential.
*/
public String getUserName() {
return userName;
}
/**
* Get the password of the credential.
*/
public String getPassword() {
return password;
}
}

Просмотреть файл

@ -0,0 +1,39 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.credentials;
import com.microsoft.rest.core.pipeline.ServiceRequestContext;
import com.microsoft.rest.core.pipeline.ServiceRequestFilter;
import com.microsoft.rest.core.utils.Base64;
import java.util.concurrent.ExecutorService;
public class BasicAuthenticationCredentialsFilter implements ServiceRequestFilter {
private BasicAuthenticationCredentials credentials;
public BasicAuthenticationCredentialsFilter(BasicAuthenticationCredentials credentials) {
this.credentials = credentials;
}
@Override
public void filter(ServiceRequestContext request) {
ExecutorService service = null;
try {
String auth = credentials.getUserName() + ":" + credentials.getPassword();
auth = new String(Base64.encode(auth.getBytes("UTF8")));
request.setHeader("Authorization", "Basic " + auth);
} catch (Exception e) {
// silently fail
} finally {
if (service != null) {
service.shutdown();
}
}
}
}

Просмотреть файл

@ -0,0 +1,19 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.credentials;
import com.microsoft.rest.core.ServiceClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.util.Map;
/**
* ServiceClientCredentials is the abstraction for credentials used by ServiceClients accessing REST services.
*/
public abstract class ServiceClientCredentials {
}

Просмотреть файл

@ -0,0 +1,60 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.credentials;
import java.util.ArrayList;
import java.util.Map;
/**
* The Class CertificateCloudCredentials.
*/
public class TokenCredentials extends ServiceClientCredentials {
/** The scheme. */
private String scheme;
/** The token */
private String token;
/**
* Instantiates a new certificate cloud credentials.
*/
public TokenCredentials() {
}
/**
* Instantiates a new certificate cloud credentials.
*
* @param scheme the scheme in the authorization header
* @param token the access token
*/
public TokenCredentials(String scheme, String token) {
if (scheme == null)
{
scheme = "Bearer";
}
this.scheme = scheme;
this.token = token;
}
/**
* Get the authentication token.
*
* @return the ADAL authentication token
*/
public String getToken() {
return token;
}
/**
* Get the authentication scheme.
*
*/
public String getScheme() {
return scheme;
}
}

Просмотреть файл

@ -0,0 +1,36 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.credentials;
import com.microsoft.rest.core.pipeline.ServiceRequestContext;
import com.microsoft.rest.core.pipeline.ServiceRequestFilter;
import java.util.concurrent.ExecutorService;
public class TokenCredentialsFilter implements ServiceRequestFilter {
private TokenCredentials credentials;
public TokenCredentialsFilter(TokenCredentials credentials) {
this.credentials = credentials;
}
@Override
public void filter(ServiceRequestContext request) {
ExecutorService service = null;
try {
request.setHeader("Authorization", credentials.getScheme() + " " + credentials.getToken());
} catch (Exception e) {
// silently fail
} finally {
if (service != null) {
service.shutdown();
}
}
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<html>
<head />
<body>This package contains the core classes across difference services.
</body>
</html>

Просмотреть файл

@ -0,0 +1,64 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.exception;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import java.io.IOException;
/**
* The Service Exception indicates an error while executing a service operation.
*/
public class ServiceException extends Exception {
/**
* Information about the associated HTTP request.
*/
public HttpRequest request;
/**
* Information about the associated HTTP response.
*/
public HttpResponse response;
public ServiceException() {
super();
}
public ServiceException(final String message) {
super(message);
}
public ServiceException(final String message, final Throwable cause) {
super(message, cause);
}
public ServiceException(final Throwable cause) {
super(cause);
}
@Override
public String getMessage() {
final StringBuffer buffer = new StringBuffer(50);
buffer.append(super.getMessage());
if (this.response != null) {
String responseBody = "\nResponse Body: ";
try {
responseBody += IOUtils.toString(response.getEntity().getContent());
} catch (IOException e) {
// silent
}
buffer.append(responseBody);
}
return buffer.toString();
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<html>
<head />
<body>This package contains the core classes across difference services.
</body>
</html>

Просмотреть файл

@ -0,0 +1,5 @@
<html>
<head />
<body>This package contains the core classes across difference services.
</body>
</html>

Просмотреть файл

@ -0,0 +1,37 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.tracing;
import com.microsoft.rest.core.pipeline.ServiceRequestContext;
import com.microsoft.rest.core.pipeline.ServiceRequestFilter;
import com.microsoft.rest.core.pipeline.ServiceResponseContext;
import com.microsoft.rest.core.pipeline.ServiceResponseFilter;
public class ClientRequestTrackingHandler implements ServiceRequestFilter,
ServiceResponseFilter {
private final String trackingId;
public String getTrackingId() {
return trackingId;
}
public ClientRequestTrackingHandler(String trackingId) {
this.trackingId = trackingId;
}
@Override
public void filter(ServiceRequestContext request) {
request.setHeader("client-tracking-id", trackingId);
}
@Override
public void filter(ServiceRequestContext request,
ServiceResponseContext response) {
response.setHeader("client-tracking-id", trackingId);
}
}

Просмотреть файл

@ -0,0 +1,186 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.tracing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
/**
* Provides tracing utilities that insight into all aspects of client operations
* via implementations of the ICloudTracingInterceptor interface. All tracing is
* global.
*/
public abstract class CloudTracing {
private CloudTracing() {
}
/**
* The collection of tracing interceptors to notify.
*/
private static List<CloudTracingInterceptor> interceptors;
/**
* Gets the collection of tracing interceptors to notify.
*
* @return the collection of tracing interceptors.
*/
public static List<CloudTracingInterceptor> getInterceptors() {
return interceptors;
}
/**
* Gets a value indicating whether tracing is enabled. Tracing can be
* disabled for performance.
*/
private static boolean isEnabled;
/**
* Gets the value indicating whether tracing is enabled.
*
* @return Boolean value indicating if tracing is enabled.
*/
public static boolean getIsEnabled() {
return isEnabled;
}
/**
* Sets the value indicating whether tracing is enabled.
*
* @param enabled
* Boolean value indicating if tracing is enabled.
*/
public static void setIsEnabled(final boolean enabled) {
isEnabled = enabled;
}
static {
isEnabled = true;
interceptors = Collections
.synchronizedList(new ArrayList<CloudTracingInterceptor>());
}
/**
* Add a tracing interceptor to be notified of changes.
*
* @param cloudTracingInterceptor
* The tracing interceptor.
*/
public static void addTracingInterceptor(
final CloudTracingInterceptor cloudTracingInterceptor) {
if (cloudTracingInterceptor == null) {
throw new NullPointerException();
}
interceptors.add(cloudTracingInterceptor);
}
/**
* Remove a tracing interceptor from change notifications.
*
* @param cloudTracingInterceptor
* The tracing interceptor.
* @return True if the tracing interceptor was found and removed; false
* otherwise.
*/
public static boolean removeTracingInterceptor(
CloudTracingInterceptor cloudTracingInterceptor) {
if (cloudTracingInterceptor == null) {
throw new NullPointerException();
}
return interceptors.remove(cloudTracingInterceptor);
}
private static long nextInvocationId = 0;
public static long getNextInvocationId() {
return ++nextInvocationId;
}
public static void information(String message, Object... parameters) {
if (isEnabled) {
information(String.format(message, parameters));
}
}
public static void configuration(String source, String name, String value) {
if (isEnabled) {
synchronized (interceptors) {
for (CloudTracingInterceptor writer : interceptors) {
writer.configuration(source, name, value);
}
}
}
}
public static void information(String message) {
if (isEnabled) {
synchronized (interceptors) {
for (CloudTracingInterceptor writer : interceptors) {
writer.information(message);
}
}
}
}
public static void enter(String invocationId, Object instance,
String method, HashMap<String, Object> parameters) {
if (isEnabled) {
synchronized (interceptors) {
for (CloudTracingInterceptor writer : interceptors) {
writer.enter(invocationId, instance, method, parameters);
}
}
}
}
public static void sendRequest(String invocationId, HttpRequest request) {
if (isEnabled) {
synchronized (interceptors) {
for (CloudTracingInterceptor writer : interceptors) {
writer.sendRequest(invocationId, request);
}
}
}
}
public static void receiveResponse(String invocationId,
HttpResponse response) {
if (isEnabled) {
synchronized (interceptors) {
for (CloudTracingInterceptor writer : interceptors) {
writer.receiveResponse(invocationId, response);
}
}
}
}
public static void error(String invocationId, Exception ex) {
if (isEnabled) {
synchronized (interceptors) {
for (CloudTracingInterceptor writer : interceptors) {
writer.error(invocationId, ex);
}
}
}
}
public static void exit(String invocationId, Object result) {
if (isEnabled) {
synchronized (interceptors) {
for (CloudTracingInterceptor writer : interceptors) {
writer.exit(invocationId, result);
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,94 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.tracing;
import java.util.HashMap;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
/**
* The CloudTracingInterceptor provides useful information about cloud
* operations. Interception is global and a tracing interceptor can be added via
* CloudContext.Configuration.Tracing.AddTracingInterceptor.
*/
public interface CloudTracingInterceptor {
/**
* Trace information.
*
* @param message
* The information to trace.
*/
void information(String message);
/**
* Probe configuration for the value of a setting.
*
* @param source
* The configuration source.
* @param name
* The name of the setting.
* @param value
* The value of the setting in the source.
*/
void configuration(String source, String name, String value);
/**
* Enter a method.
*
* @param invocationId
* Method invocation identifier.
* @param instance
* The instance with the method.
* @param method
* Name of the method.
* @param parameters
* Method parameters.
*/
void enter(String invocationId, Object instance, String method,
HashMap<String, Object> parameters);
/**
* Send an HTTP request.
*
* @param invocationId
* Method invocation identifier.
* @param request
* The request about to be sent.
*/
void sendRequest(String invocationId, HttpRequest request);
/**
* Receive an HTTP response.
*
* @param invocationId
* Method invocation identifier.
* @param response
* The response instance.
*/
void receiveResponse(String invocationId, HttpResponse response);
/**
* Raise an error.
*
* @param invocationId
* Method invocation identifier.
* @param exception
* The error.
*/
void error(String invocationId, Exception exception);
/**
* Exit a method. Note: Exit will not be called in the event of an error.
*
* @param invocationId
* Method invocation identifier.
* @param returnValue
* Method return value.
*/
void exit(String invocationId, Object returnValue);
}

Просмотреть файл

@ -0,0 +1,5 @@
<html>
<head />
<body>This package contains the core classes across difference services.
</body>
</html>

Просмотреть файл

@ -0,0 +1,116 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import static org.junit.Assert.*;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Test;
public class ISO8601DateConverterTests {
@Test
public void shortFormatWorks() throws Exception {
// Arrange
ISO8601DateConverter converter = new ISO8601DateConverter();
String value = "2012-01-12T00:35:58Z";
// Act
Date result = converter.parse(value);
String value2 = converter.format(result);
// Assert
assertNotNull(result);
Calendar calendar = Calendar.getInstance();
calendar.setTime(result);
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
assertEquals("Year", 2012, calendar.get(Calendar.YEAR));
assertEquals("Month", 1, calendar.get(Calendar.MONTH) + 1);
assertEquals("Day", 12, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals("Hour", 0, calendar.get(Calendar.HOUR));
assertEquals("Minute", 35, calendar.get(Calendar.MINUTE));
assertEquals("Second", 58, calendar.get(Calendar.SECOND));
assertEquals("Millisecond", 0, calendar.get(Calendar.MILLISECOND));
assertEquals("2012-01-12T00:35:58.000Z", value2);
}
@Test
public void longFormatWorks() throws Exception {
// Arrange
ISO8601DateConverter converter = new ISO8601DateConverter();
String value = "2012-01-12T00:35:58.1234567Z";
// Act
Date result = converter.parse(value);
String value2 = converter.format(result);
// Assert
assertNotNull(result);
Calendar calendar = Calendar.getInstance();
calendar.setTime(result);
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
assertEquals("Year", 2012, calendar.get(Calendar.YEAR));
assertEquals("Month", 1, calendar.get(Calendar.MONTH) + 1);
assertEquals("Day", 12, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals("Hour", 0, calendar.get(Calendar.HOUR));
assertEquals("Minute", 35, calendar.get(Calendar.MINUTE));
assertEquals("Second", 58, calendar.get(Calendar.SECOND));
assertEquals("Millisecond", 123, calendar.get(Calendar.MILLISECOND));
assertEquals("2012-01-12T00:35:58.123Z", value2);
}
@Test
public void mixedFormatWorks() throws Exception {
// Arrange
ISO8601DateConverter converter = new ISO8601DateConverter();
String value = "2012-01-12T00:35:58.12Z";
// Act
Date result = converter.parse(value);
String value2 = converter.format(result);
// Assert
assertNotNull(result);
Calendar calendar = Calendar.getInstance();
calendar.setTime(result);
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
assertEquals("Year", 2012, calendar.get(Calendar.YEAR));
assertEquals("Month", 1, calendar.get(Calendar.MONTH) + 1);
assertEquals("Day", 12, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals("Hour", 0, calendar.get(Calendar.HOUR));
assertEquals("Minute", 35, calendar.get(Calendar.MINUTE));
assertEquals("Second", 58, calendar.get(Calendar.SECOND));
assertEquals("Millisecond", 120, calendar.get(Calendar.MILLISECOND));
assertEquals("2012-01-12T00:35:58.120Z", value2);
}
@Test
public void shortFormatRoundTrips() throws Exception {
// Arrange
ISO8601DateConverter converter = new ISO8601DateConverter();
String value = "2012-01-12T00:35:58Z";
// Act
Date result = converter.parse(value);
String value2 = converter.shortFormat(result);
String value3 = converter.format(result);
// Assert
assertNotNull(result);
assertEquals(value, value2);
assertEquals("2012-01-12T00:35:58.000Z", value3);
}
}

Просмотреть файл

@ -0,0 +1,39 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class LazyArrayListTests {
@Test
public void lazyByDefaultTests() throws Exception {
// Arrange
LazyArrayList<String> lazyArrayList = new LazyArrayList<String>();
// Act
boolean initialized = lazyArrayList.isInitialized();
// Assert
assertEquals(false, initialized);
}
@Test
public void lazyAddTests() throws Exception {
// Arrange
LazyArrayList<String> lazyArrayList = new LazyArrayList<String>();
// Act
lazyArrayList.add("item");
boolean initialized = lazyArrayList.isInitialized();
// Assert
assertEquals(true, initialized);
}
}

Просмотреть файл

@ -0,0 +1,39 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class LazyHashMapTests {
@Test
public void lazyByDefaultTests() throws Exception {
// Arrange
LazyHashMap<String, String> lazyHashMap = new LazyHashMap<String, String>();
// Act
boolean initialized = lazyHashMap.isInitialized();
// Assert
assertEquals(false, initialized);
}
@Test
public void lazyAddTests() throws Exception {
// Arrange
LazyHashMap<String, String> lazyHashMap = new LazyHashMap<String, String>();
// Act
lazyHashMap.put("Key", "Value");
boolean initialized = lazyHashMap.isInitialized();
// Assert
assertEquals(true, initialized);
}
}

Просмотреть файл

@ -0,0 +1,36 @@
/**
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
*/
package com.microsoft.rest.core;
import static org.junit.Assert.*;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import org.junit.Test;
public class TimeSpan8601ConverterTests {
@Test
public void formatShouldWork() throws Exception {
DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
Duration duration = dataTypeFactory.newDurationDayTime(true, 0, 3, 10,
2);
String durationString = TimeSpan8601Converter.format(duration);
assertEquals("P0DT3H10M2S", durationString);
}
@Test
public void parseShouldWork() throws Exception {
Duration duration = TimeSpan8601Converter.parse("P0DT3H10M2S");
assertEquals(0, duration.getDays());
assertEquals(3, duration.getHours());
assertEquals(10, duration.getMinutes());
assertEquals(2, duration.getSeconds());
}
}