下面列出了org.apache.http.entity.mime.MIME#org.apache.http.util.Args 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
Args.notNull(cookie, HttpHeader.COOKIE);
if (TextUtils.isBlank(value)) {
throw new MalformedCookieException("Blank or null value for domain attribute");
}
// Ignore domain attributes ending with '.' per RFC 6265, 4.1.2.3
if (value.endsWith(".")) {
return;
}
String domain = value;
domain = domain.toLowerCase(Locale.ROOT);
final int dotIndex = domain.indexOf('.');
if (browserVersion_.hasFeature(HTTP_COOKIE_REMOVE_DOT_FROM_ROOT_DOMAINS)
&& dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
domain = domain.toLowerCase(Locale.ROOT);
domain = domain.substring(1);
}
if (dotIndex > 0) {
domain = '.' + domain;
}
cookie.setDomain(domain);
}
private static void testArtifact(OArtifact expected, OArtifact actual) {
Args.notNull(expected, "expected");
Args.notNull(actual, "actual");
assertEquals("test artifact load", expected.isLoad(), actual.isLoad());
assertEquals("test artifact trusted", expected.isTrusted(), actual.isTrusted());
assertEquals("test artifact groupId", expected.getArtifactReference().getGroupId(),
actual.getArtifactReference().getGroupId());
assertEquals("test artifact artifactId", expected.getArtifactReference().getArtifactId(),
actual.getArtifactReference().getArtifactId());
assertEquals("test artifact version", expected.getArtifactReference().getVersion(),
actual.getArtifactReference().getVersion());
assertEquals("test artifact jar files", expected.getArtifactReference().getFile().getAbsoluteFile(),
actual.getArtifactReference().getFile().getAbsoluteFile());
assertEquals("test artifact descriptions", expected.getArtifactReference().getDescription(),
actual.getArtifactReference().getDescription());
}
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context)
throws ProtocolException {
Args.notNull(request, "HTTP request");
Args.notNull(response, "HTTP response");
final int statusCode = response.getStatusLine().getStatusCode();
final String method = request.getRequestLine().getMethod();
final Header locationHeader = response.getFirstHeader("location");
switch (statusCode) {
case HttpStatus.SC_MOVED_TEMPORARILY:
return isRedirectable(method) && locationHeader != null;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
case 308: // Ensure that HTTP 308 is redirected as well
return isRedirectable(method);
case HttpStatus.SC_SEE_OTHER:
return true;
default:
return false;
} // end of switch
}
/**
* Writes bytes from the {@code InputStream} this entity was constructed
* with to an {@code OutputStream}. The content length
* determines how many bytes are written. If the length is unknown ({@code -1}), the
* stream will be completely consumed (to the end of the stream).
*/
@Override
public void writeTo(final OutputStream outstream ) throws IOException {
Args.notNull( outstream, "Output stream" );
try (InputStream instream = this.content) {
final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE];
int l;
if (this.length < 0) {
// consume until EOF
while ((l = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, l);
}
} else {
// consume no more than length
long remaining = this.length;
while (remaining > 0) {
l = instream.read(buffer, 0, (int) Math.min(OUTPUT_BUFFER_SIZE, remaining));
if (l == -1) {
break;
}
outstream.write(buffer, 0, l);
remaining -= l;
}
}
}
}
@Override
public IONotificationTransport create(ODocument document) {
Args.notNull(document, "document");
IONotificationTransport transport = null;
switch (document.getSchemaClass().getName()) {
case IOMailNotificationTransport.CLASS_NAME:
transport = DAO.create(IOMailNotificationTransport.class);
break;
case IOSmsNotificationTransport.CLASS_NAME:
transport = DAO.create(IOSmsNotificationTransport.class);
break;
}
if (transport != null) {
transport.fromStream(document);
}
return transport;
}
/**
* Delete list of {@link OArtifact} from metadata.xml
* @param oArtifacts list of {@link OArtifact} for delete from metadata.xml
* @throws IllegalArgumentException if oArtifacts is null
*/
@SuppressWarnings("unchecked")
void delete(List<OArtifact> oArtifacts) {
Args.notNull(oArtifacts, "oArtifacts");
Document document = readDocumentFromFile(pathToMetadata);
if (document == null) documentCannotReadException(pathToMetadata);
NodeList nodeList = executeExpression(ALL_MODULES_EXP, document);
if (nodeList != null) {
Element root = document.getDocumentElement();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0);
OArtifact metadata = containsInModulesConfigsList(dependencyElement, oArtifacts);
if (metadata != null) {
root.removeChild(element);
}
}
}
saveDocument(document, pathToMetadata);
}
}
/**
* Search pom.xml if jar file
* @param path {@link Path} of jar file
* @return {@link Path} of pom.xml or Optional.absent() if pom.xml is not present
* @throws IllegalArgumentException if path is null
*/
public Path getPomFromJar(Path path) {
Args.notNull(path, "path");
Path result = null;
try {
JarFile jarFile = new JarFile(path.toFile());
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
if (jarEntry.getName().endsWith("pom.xml")) {
result = unarchivePomFile(jarFile, jarEntry);
break;
}
}
jarFile.close();
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.error("Cannot open file to read. File: " + path.toAbsolutePath(), e);
}
}
return result;
}
/**
* Read maven group, artifact, version in xml node <parent></parent>
* @param pomXml pom.xml for read
* @return {@link Artifact} with parent's group, artifact, version
*/
Artifact readParentGAVInPomXml(Path pomXml) {
Args.notNull(pomXml, "pomXml");
Document doc = readDocumentFromFile(pomXml);
String expression = String.format("/%s/%s", PROJECT, PARENT);
NodeList nodeList = executeExpression(expression, doc);
if (nodeList != null && nodeList.getLength() > 0) {
Element element = (Element) nodeList.item(0);
String groupId = element.getElementsByTagName(GROUP).item(0).getTextContent();
String artifactId = element.getElementsByTagName(ARTIFACT).item(0).getTextContent();
String version = element.getElementsByTagName(VERSION).item(0).getTextContent();
if (groupId != null && artifactId != null && version != null)
return (Artifact) new DefaultArtifact(getGAV(groupId, artifactId, version));
}
return null;
}
/**
* Save {@link Document} document in file system with {@link Path} xml
* @param document - {@link Document} for save
* @param xml - {@link Path} for saving document
* @throws IllegalArgumentException if document or xml is null
*/
protected final void saveDocument(Document document, Path xml) {
Args.notNull(document, "document");
Args.notNull(xml, "xml");
TransformerFactory factory = TransformerFactory.newInstance();
try {
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(xml.toFile());
transformer.transform(source, result);
} catch (TransformerException e) {
LOG.error("Cannot save document!", e);
}
}
/**
* Delete artifact jar file
* @param oArtifact {@link OArtifact} artifact which jar file will be delete
* @throws IllegalArgumentException if oArtifact is null
*/
public static boolean deleteOArtifactFile(OArtifact oArtifact) {
Args.notNull(oArtifact, "oArtifact");
boolean deleted = false;
try {
File file = oArtifact.getArtifactReference().getFile();
if (file != null && file.exists()) {
File artifactMavenDir = getOArtifactMavenDir(oArtifact);
if (artifactMavenDir != null) {
FileUtils.deleteDirectory(artifactMavenDir);
deleted = true;
LOG.info("Delete directory in maven repository: {}", artifactMavenDir);
} else {
Files.delete(file.toPath());
deleted = true;
LOG.info("Delete jar file: {}", file);
}
}
} catch (IOException e) {
LOG.error("Can't delete jar file of Orienteer module: {}", oArtifact, e);
}
return deleted;
}
/**
* Replace artifactForReplace in metadata.xml by newArtifact
* @param artifactForReplace - artifact for replace
* @param newArtifact - new artifact
* @throws IllegalArgumentException if artifactForReplace or newArtifact is null
*/
@SuppressWarnings("unchecked")
void update(OArtifact artifactForReplace, OArtifact newArtifact) {
Args.notNull(artifactForReplace, "artifactForUpdate");
Args.notNull(newArtifact, "newArtifact");
Document document = readDocumentFromFile(pathToMetadata);
if (document == null) documentCannotReadException(pathToMetadata);
NodeList nodeList = executeExpression(ALL_MODULES_EXP, document);
if (nodeList != null) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0);
OArtifact module = containsInModulesConfigsList(dependencyElement, Lists.newArrayList(artifactForReplace));
if (module != null) {
changeArtifactElement(element, newArtifact);
break;
}
}
}
saveDocument(document, pathToMetadata);
}
}
/**
* Delete oArtifact from metadata.xml
* @param oArtifact {@link OArtifact} for delete from metadata.xml
* @throws IllegalArgumentException if oArtifact is null
*/
@SuppressWarnings("unchecked")
void delete(OArtifact oArtifact) {
Args.notNull(oArtifact, "oArtifact");
Document document = readDocumentFromFile(pathToMetadata);
if (document == null) documentCannotReadException(pathToMetadata);
NodeList nodeList = executeExpression(ALL_MODULES_EXP, document);
if (nodeList != null) {
Element root = document.getDocumentElement();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0);
if (isNecessaryElement(dependencyElement, oArtifact)) {
root.removeChild(element);
break;
}
}
}
saveDocument(document, pathToMetadata);
}
}
private String executeGet(String url, String hostName, Integer port, String schemeName, Map<String, String> paramMap) {
Args.notNull(url, "url");
url = buildGetParam(url, paramMap);
Request request = Request.Get(url);
request = buildProxy(request, hostName, port, schemeName);
try {
return request.execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e.toString());
}
return null;
}
private String buildGetParam(String url, Map<String, String> paramMap) {
Args.notNull(url, "url");
if(!paramMap.isEmpty()) {
List<NameValuePair> paramList = Lists.newArrayListWithCapacity(paramMap.size());
for (String key : paramMap.keySet()) {
paramList.add(new BasicNameValuePair(key, paramMap.get(key)));
}
//拼接参数
url += "?" + URLEncodedUtils.format(paramList, Consts.UTF_8);
}
return url;
}
private String executePost(String url, String hostName, Integer port, String schemeName, List<NameValuePair> nameValuePairs, List<File> files) {
Args.notNull(url, "url");
HttpEntity entity = buildPostParam(nameValuePairs, files);
Request request = Request.Post(url).body(entity);
request = buildProxy(request, hostName, port, schemeName);
try {
return request.execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e.toString());
}
return null;
}
@Substitute
@Override
public void put(final HttpHost host, final AuthScheme authScheme) {
Args.notNull(host, "HTTP host");
if (authScheme == null) {
return;
}
this.map.put(getKey(host), authScheme);
}
/**
* Check that content length less then Integer.MAX_VALUE.
* Try to get content length from entity
* If length less then zero return 4096
*
* @param entity HttpEntity for get capacity.
* @return Capacity.
*/
private int getCapacity(final HttpEntity entity) {
Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory");
int capacity = (int) entity.getContentLength();
if (capacity < 0) {
capacity = 4096;
}
return capacity;
}
@Override
public void put(final HttpHost host, final AuthScheme authScheme) {
Args.notNull(host, "HTTP host");
if (authScheme == null) {
return;
}
this.map.put(getKey(host), authScheme);
}
private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp,
char[] kp, PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException,
KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
Args.notNull(file, "Keystore file"); //$NON-NLS-1$
final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
final FileInputStream instream = new FileInputStream(file);
try {
identityStore.load(instream, ksp);
} finally {
instream.close();
}
return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
}
private static final byte[] toByteArray(final HttpEntity entity,
int maxContent, MutableBoolean trimmed) throws IOException {
if (entity == null)
return new byte[] {};
final InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory");
int reportedLength = (int) entity.getContentLength();
// set default size for buffer: 100 KB
int bufferInitSize = 102400;
if (reportedLength != -1) {
bufferInitSize = reportedLength;
}
// avoid init of too large a buffer when we will trim anyway
if (maxContent != -1 && bufferInitSize > maxContent) {
bufferInitSize = maxContent;
}
final ByteArrayBuffer buffer = new ByteArrayBuffer(bufferInitSize);
final byte[] tmp = new byte[4096];
int lengthRead;
while ((lengthRead = instream.read(tmp)) != -1) {
// check whether we need to trim
if (maxContent != -1 && buffer.length() + lengthRead > maxContent) {
buffer.append(tmp, 0, maxContent - buffer.length());
trimmed.setValue(true);
break;
}
buffer.append(tmp, 0, lengthRead);
}
return buffer.toByteArray();
}
public ByteBufHttpEntity(ByteBuf byteBuf, long length, ContentType contentType) {
this.content = Args.notNull(byteBuf, "Source input stream");
this.length = length;
if (contentType != null) {
setContentType(contentType.toString());
}
}
/**
* User principal with user name as well as one or more roles that he/she belong to
* @param username string with user name for user
* @param token compact string representation of JWT token
* @param claims list of verified JWT claims as a map
*/
public JWTPrincipal(final String username, String token, Map<String,Object> claims) {
super();
Args.notNull(username, "User name");
Args.notNull(token, "JWT token");
Args.notNull(claims, "JWT claims");
this.token = token;
this.claims = claims;
this.username = username;
}
@Override
public HttpRoute determineRoute(final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException {
Args.notNull(request, "Request");
if (host == null) {
throw new ProtocolException("Target host is not specified");
}
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final RequestConfig config = clientContext.getRequestConfig();
int remotePort;
if (host.getPort() <= 0) {
try {
remotePort = schemePortResolver.resolve(host);
} catch (final UnsupportedSchemeException e) {
throw new HttpException(e.getMessage());
}
} else
remotePort = host.getPort();
final Tuple<Inet4Address, Inet6Address> remoteAddresses = IpAddressTools.getRandomAddressesFromHost(host);
final Tuple<InetAddress, InetAddress> addresses = determineAddressPair(remoteAddresses);
final HttpHost target = new HttpHost(addresses.r, host.getHostName(), remotePort, host.getSchemeName());
final HttpHost proxy = config.getProxy();
final boolean secure = target.getSchemeName().equalsIgnoreCase("https");
clientContext.setAttribute(CHOSEN_IP_ATTRIBUTE, addresses.l);
log.debug("Setting route context attribute to {}", addresses.l);
if (proxy == null) {
return new HttpRoute(target, addresses.l, secure);
} else {
return new HttpRoute(target, addresses.l, proxy, secure);
}
}
/**
* Delete oArtifact from metadata.xml
* @param oArtifact {@link OArtifact} for delete
* @throws IllegalArgumentException if oArtifact is null
*/
public void deleteOArtifactFromMetadata(OArtifact oArtifact) {
Args.notNull(oArtifact, "oArtifact");
if (!metadataExists()) return;
OMetadataUpdater updater = new OMetadataUpdater(metadataPath);
updater.delete(oArtifact);
}
/**
* Update metadata.xml.
* oArtifacts will be write to metadata.xml or will be update its flag load or trusted.
* @param oArtifacts list of {@link OArtifact} for update
* @param updateJar true - jar will be update
* false - jar will not be update
* @throws IllegalArgumentException if oArtifacts is null
*/
@SuppressWarnings("unchecked")
void update(List<OArtifact> oArtifacts, boolean updateJar) {
Args.notNull(oArtifacts, "oArtifacts");
Document document = readDocumentFromFile(pathToMetadata);
if (document == null) documentCannotReadException(pathToMetadata);
NodeList nodeList = executeExpression(ALL_MODULES_EXP, document);
List<OArtifact> updatedModules = Lists.newArrayList();
if (nodeList != null) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Element.ELEMENT_NODE) {
Element element = (Element) node;
Element dependencyElement = (Element) element.getElementsByTagName(MetadataTag.DEPENDENCY.get()).item(0);
OArtifact oArtifact = containsInModulesConfigsList(dependencyElement, oArtifacts);
if (oArtifact != null) {
if (updateJar) {
changeoArtifactsLoadAndJar(element, oArtifact);
} else changeArtifactElement(element, oArtifact);
updatedModules.add(oArtifact);
}
}
}
}
if (updatedModules.size() != oArtifacts.size()) {
addArtifacts(difference(updatedModules, oArtifacts), document);
}
saveDocument(document, pathToMetadata);
}
/**
* Delete oArtifacts from metadata.xml
* @param oArtifacts list of {@link OArtifact} for delete from metadata.xml
* @throws IllegalArgumentException if oArtifacts is null.
*/
public void deleteOArtifactsFromMetadata(List<OArtifact> oArtifacts) {
Args.notNull(oArtifacts, "oArtifacts");
if (!metadataExists()) return;
OMetadataUpdater updater = new OMetadataUpdater(metadataPath);
updater.delete(oArtifacts);
}
/**
* @param instream input stream
* @param length of the input stream, {@code -1} if unknown
* @param contentType for specifying the {@code Content-Type} header, may be {@code null}
* @throws IllegalArgumentException if {@code instream} is {@code null}
*/
public InputStreamEntity( final InputStream instream, final long length, final ContentType contentType ) {
super();
this.content = Args.notNull( instream, "Source input stream" );
this.length = length;
if( contentType != null ) {
setContentType( contentType.toString() );
}
}
/**
* Update metadata.xml.
* Search artifactForUpdate in metadata.xml and replace by newArtifact.
* @param artifactForUpdate {@link OArtifact} for replace.
* @param newArtifact new {@link OArtifact}.
* @throws IllegalArgumentException if artifactForUpdate or newArtifact is null.
*/
public void updateOArtifactMetadata(OArtifact artifactForUpdate, OArtifact newArtifact) {
Args.notNull(artifactForUpdate, "artifactForUpdate");
Args.notNull(newArtifact, "newArtifactConfig");
if (!metadataExists()) {
return;
}
OMetadataUpdater updater = new OMetadataUpdater(metadataPath);
updater.update(artifactForUpdate, newArtifact);
}
private static SSLContextBuilder loadTrustMaterial(SSLContextBuilder builder, final File file,
final char[] tsp, final TrustStrategy trustStrategy)
throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
Args.notNull(file, "Truststore file"); //$NON-NLS-1$
final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
final FileInputStream instream = new FileInputStream(file);
try {
trustStore.load(instream, tsp);
} finally {
instream.close();
}
return builder.loadTrustMaterial(trustStore, trustStrategy);
}
public GeneratorMode(String name, Class<? extends IGeneratorStrategy> strategyClass) {
Args.notEmpty(name, "name");
Args.notNull(strategyClass, "strategyClass");
this.name = name;
this.strategyClass = strategyClass;
}