index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator/util/Constants.java | /**
*
* 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.airavata.orchestrator.util;
public class Constants {
public static final String ORCHESTRATOT_SERVER_PORT = "orchestrator.server.port";
public static final String ORCHESTRATOT_SERVER_HOST = "orchestrator.server.host";
public static final String ORCHESTRATOT_SERVER_MIN_THREADS = "orchestrator.server.min.threads";
}
| 1,200 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator/server/OrchestratorServerHandler.java | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.airavata.orchestrator.server;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.logging.MDCConstants;
import org.apache.airavata.common.logging.MDCUtil;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.common.utils.ZkConstants;
import org.apache.airavata.messaging.core.*;
import org.apache.airavata.metascheduler.core.api.ProcessScheduler;
import org.apache.airavata.metascheduler.process.scheduling.api.ProcessSchedulerImpl;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription;
import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile;
import org.apache.airavata.model.application.io.DataType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.commons.ErrorModel;
import org.apache.airavata.model.data.replica.DataProductModel;
import org.apache.airavata.model.data.replica.DataReplicaLocationModel;
import org.apache.airavata.model.data.replica.ReplicaLocationCategory;
import org.apache.airavata.model.error.LaunchValidationException;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.ExperimentType;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.messaging.event.*;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.status.*;
import org.apache.airavata.model.task.TaskTypes;
import org.apache.airavata.model.util.ExperimentModelUtil;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
import org.apache.airavata.orchestrator.core.schedule.HostScheduler;
import org.apache.airavata.orchestrator.core.utils.OrchestratorConstants;
import org.apache.airavata.orchestrator.cpi.OrchestratorService;
import org.apache.airavata.orchestrator.cpi.impl.SimpleOrchestratorImpl;
import org.apache.airavata.orchestrator.util.OrchestratorServerThreadPoolExecutor;
import org.apache.airavata.orchestrator.util.OrchestratorUtils;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.apache.airavata.registry.api.client.RegistryServiceClientFactory;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.commons.lang.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.text.MessageFormat;
import java.util.*;
public class OrchestratorServerHandler implements OrchestratorService.Iface {
private static Logger log = LoggerFactory.getLogger(OrchestratorServerHandler.class);
private SimpleOrchestratorImpl orchestrator = null;
private String airavataUserName;
private String gatewayName;
private Publisher publisher;
private final Subscriber statusSubscribe;
private final Subscriber experimentSubscriber;
private CuratorFramework curatorClient;
/**
* Query orchestrator server to fetch the CPI version
*/
@Override
public String getAPIVersion() throws TException {
return null;
}
public OrchestratorServerHandler() throws OrchestratorException, TException {
// orchestrator init
try {
// first constructing the monitorManager and orchestrator, then fill
// the required properties
setAiravataUserName(ServerSettings.getDefaultUser());
orchestrator = new SimpleOrchestratorImpl();
publisher = MessagingFactory.getPublisher(Type.STATUS);
orchestrator.initialize();
orchestrator.getOrchestratorContext().setPublisher(this.publisher);
statusSubscribe = getStatusSubscriber();
experimentSubscriber = getExperimentSubscriber();
startCurator();
} catch (OrchestratorException | AiravataException e) {
log.error(e.getMessage(), e);
throw new OrchestratorException("Error while initializing orchestrator service", e);
}
}
private Subscriber getStatusSubscriber() throws AiravataException {
List<String> routingKeys = new ArrayList<>();
// routingKeys.add("*"); // listen for gateway level messages
// routingKeys.add("*.*"); // listen for gateway/experiment level messages
routingKeys.add("*.*.*"); // listen for gateway/experiment/process level messages
return MessagingFactory.getSubscriber(new ProcessStatusHandler(), routingKeys, Type.STATUS);
}
private Subscriber getExperimentSubscriber() throws AiravataException {
List<String> routingKeys = new ArrayList<>();
routingKeys.add(ServerSettings.getRabbitmqExperimentLaunchQueueName());
return MessagingFactory.getSubscriber(new ExperimentHandler(), routingKeys, Type.EXPERIMENT_LAUNCH);
}
/**
* * After creating the experiment Data user have the * experimentID as the
* handler to the experiment, during the launchProcess * We just have to
* give the experimentID * * @param experimentID * @return sucess/failure *
* *
*
* @param experimentId
*/
public boolean launchExperiment(String experimentId, String gatewayId) throws TException {
ExperimentModel experiment = null;
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
// TODO deprecate this approach as we are replacing gfac
String experimentNodePath = getExperimentNodePath(experimentId);
ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), experimentNodePath);
String experimentCancelNode = ZKPaths.makePath(experimentNodePath, ZkConstants.ZOOKEEPER_CANCEL_LISTENER_NODE);
ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), experimentCancelNode);
experiment = registryClient.getExperiment(experimentId);
if (experiment == null) {
throw new Exception("Error retrieving the Experiment by the given experimentID: " + experimentId);
}
UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData();
String token = null;
final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId();
if (groupResourceProfileId == null) {
throw new Exception("Experiment not configured with a Group Resource Profile: " + experimentId);
}
if ( userConfigurationData.getComputationalResourceScheduling() != null &&
userConfigurationData.getComputationalResourceScheduling().isSet(ComputationalResourceSchedulingModel._Fields.RESOURCE_HOST_ID)) {
GroupComputeResourcePreference groupComputeResourcePreference = registryClient.getGroupComputeResourcePreference(
userConfigurationData.getComputationalResourceScheduling().getResourceHostId(),
groupResourceProfileId);
if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) {
token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken();
}
}
if (token == null || token.isEmpty()) {
// try with group resource profile level token
GroupResourceProfile groupResourceProfile = registryClient.getGroupResourceProfile(groupResourceProfileId);
token = groupResourceProfile.getDefaultCredentialStoreToken();
}
// still the token is empty, then we fail the experiment
if (token == null || token.isEmpty()) {
throw new Exception("You have not configured credential store token at group resource profile or compute resource preference." +
" Please provide the correct token at group resource profile or compute resource preference.");
}
ExperimentType executionType = experiment.getExperimentType();
if (executionType == ExperimentType.SINGLE_APPLICATION) {
//its an single application execution experiment
List<ProcessModel> processes = orchestrator.createProcesses(experimentId, gatewayId);
for (ProcessModel processModel : processes) {
//FIXME Resolving replica if available. This is a very crude way of resolving input replicas. A full featured
//FIXME replica resolving logic should come here
processModel.getProcessInputs().stream().forEach(pi -> {
if (pi.getType().equals(DataType.URI) && pi.getValue() != null && pi.getValue().startsWith("airavata-dp://")) {
try {
DataProductModel dataProductModel = registryClient.getDataProduct(pi.getValue());
Optional<DataReplicaLocationModel> rpLocation = dataProductModel.getReplicaLocations()
.stream().filter(rpModel -> rpModel.getReplicaLocationCategory().
equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)).findFirst();
if (rpLocation.isPresent()) {
pi.setValue(rpLocation.get().getFilePath());
pi.setStorageResourceId(rpLocation.get().getStorageResourceId());
} else {
log.error("Could not find a replica for the URI " + pi.getValue());
}
} catch (RegistryServiceException e) {
throw new RuntimeException("Error while launching experiment", e);
} catch (TException e) {
throw new RuntimeException("Error while launching experiment", e);
}
} else if (pi.getType().equals(DataType.URI_COLLECTION) && pi.getValue() != null && pi.getValue().contains("airavata-dp://")) {
try {
String[] uriList = pi.getValue().split(",");
final ArrayList<String> filePathList = new ArrayList<>();
for (String uri : uriList) {
if (uri.startsWith("airavata-dp://")) {
DataProductModel dataProductModel = registryClient.getDataProduct(uri);
Optional<DataReplicaLocationModel> rpLocation = dataProductModel.getReplicaLocations()
.stream().filter(rpModel -> rpModel.getReplicaLocationCategory().
equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)).findFirst();
if (rpLocation.isPresent()) {
filePathList.add(rpLocation.get().getFilePath());
} else {
log.error("Could not find a replica for the URI " + pi.getValue());
}
} else {
// uri is in file path format
filePathList.add(uri);
}
}
pi.setValue(StringUtils.join(filePathList, ','));
} catch (RegistryServiceException e) {
throw new RuntimeException("Error while launching experiment", e);
} catch (TException e) {
throw new RuntimeException("Error while launching experiment", e);
}
}
});
if (!experiment.getUserConfigurationData().isAiravataAutoSchedule()) {
String taskDag = orchestrator.createAndSaveTasks(gatewayId, processModel);
processModel.setTaskDag(taskDag);
}
registryClient.updateProcess(processModel, processModel.getProcessId());
}
if (!experiment.getUserConfigurationData().isAiravataAutoSchedule() && !validateProcess(experimentId, processes)) {
throw new Exception("Validating process fails for given experiment Id : " + experimentId);
}
ProcessScheduler scheduler = new ProcessSchedulerImpl();
if (!experiment.getUserConfigurationData().isAiravataAutoSchedule() || scheduler.canLaunch(experimentId)) {
createAndValidateTasks(experiment,registryClient, false);
runExperimentLauncher(experimentId, gatewayId, token);
} else {
log.debug(experimentId, "Queuing single application experiment {}.", experimentId);
ExperimentStatus status = new ExperimentStatus(ExperimentState.SCHEDULED);
status.setReason("Compute resources are not ready");
status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId);
log.info("expId: {}, Scheduled experiment ", experimentId);
}
} else if (executionType == ExperimentType.WORKFLOW) {
//its a workflow execution experiment
log.debug(experimentId, "Launching workflow experiment {}.", experimentId);
launchWorkflowExperiment(experimentId, token, gatewayId);
} else {
log.error(experimentId, "Couldn't identify experiment type, experiment {} is neither single application nor workflow.", experimentId);
throw new TException("Experiment '" + experimentId + "' launch failed. Unable to figureout execution type for application " + experiment.getExecutionId());
}
} catch (LaunchValidationException launchValidationException) {
ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED);
status.setReason("Validation failed: " + launchValidationException.getErrorMessage());
status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId);
throw new TException("Experiment '" + experimentId + "' launch failed. Experiment failed to validate: " + launchValidationException.getErrorMessage(), launchValidationException);
} catch (Exception e) {
ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED);
status.setReason("Unexpected error occurred: " + e.getMessage());
status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId);
throw new TException("Experiment '" + experimentId + "' launch failed.", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
return true;
}
/**
* This method will validate the experiment before launching, if is failed
* we do not run the launch in airavata thrift service (only if validation
* is enabled
*
* @param experimentId
* @return
* @throws TException
*/
public boolean validateExperiment(String experimentId) throws TException, LaunchValidationException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
ExperimentModel experimentModel = registryClient.getExperiment(experimentId);
return orchestrator.validateExperiment(experimentModel).isValidationState();
} catch (OrchestratorException e) {
log.error(experimentId, "Error while validating experiment", e);
throw new TException(e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
@Override
public boolean validateProcess(String experimentId, List<ProcessModel> processes) throws LaunchValidationException, TException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
ExperimentModel experimentModel = registryClient.getExperiment(experimentId);
for (ProcessModel processModel : processes) {
boolean state = orchestrator.validateProcess(experimentModel, processModel).isSetValidationState();
if (!state) {
return false;
}
}
return true;
} catch (LaunchValidationException lve) {
// If a process failed to validate, also add an error message at the experiment level
ErrorModel details = new ErrorModel();
details.setActualErrorMessage(lve.getErrorMessage());
details.setCreationTime(Calendar.getInstance().getTimeInMillis());
registryClient.addErrors(OrchestratorConstants.EXPERIMENT_ERROR, details, experimentId);
throw lve;
} catch (OrchestratorException e) {
log.error(experimentId, "Error while validating process", e);
throw new TException(e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
/**
* This can be used to cancel a running experiment and store the status to
* terminated in registry
*
* @param experimentId
* @return
* @throws TException
*/
public boolean terminateExperiment(String experimentId, String gatewayId) throws TException {
final RegistryService.Client registryClient = getRegistryServiceClient();
log.info(experimentId, "Experiment: {} is cancelling !!!!!", experimentId);
try {
return validateStatesAndCancel(registryClient, experimentId, gatewayId);
} catch (Exception e) {
log.error("expId : " + experimentId + " :- Error while cancelling experiment", e);
return false;
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public void fetchIntermediateOutputs(String experimentId, String gatewayId, List<String> outputNames) throws TException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
submitIntermediateOutputsProcess(registryClient, experimentId, gatewayId, outputNames);
} catch (Exception e) {
log.error("expId : " + experimentId + " :- Error while fetching intermediate", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
private void submitIntermediateOutputsProcess(Client registryClient, String experimentId,
String gatewayId, List<String> outputNames) throws Exception {
ExperimentModel experimentModel = registryClient.getExperiment(experimentId);
ProcessModel processModel = ExperimentModelUtil.cloneProcessFromExperiment(experimentModel);
processModel.setExperimentDataDir(processModel.getExperimentDataDir() + "/intermediates");
List<OutputDataObjectType> applicationOutputs = registryClient.getApplicationOutputs(
experimentModel.getExecutionId()); // This is to get a clean output object set
List<OutputDataObjectType> requestedOutputs = new ArrayList<>();
for (OutputDataObjectType output : applicationOutputs) {
if (outputNames.contains(output.getName())) {
requestedOutputs.add(output);
}
}
processModel.setProcessOutputs(requestedOutputs);
String processId = registryClient.addProcess(processModel, experimentId);
processModel.setProcessId(processId);
try {
// Find the process that is responsible for main experiment workflow by
// looking for the process that has the JOB_SUBMISSION task
Optional<ProcessModel> jobSubmissionProcess = experimentModel.getProcesses().stream()
.filter(p -> p.getTasks().stream().anyMatch(t -> t.getTaskType() == TaskTypes.JOB_SUBMISSION))
.findFirst();
if (!jobSubmissionProcess.isPresent()) {
throw new Exception(MessageFormat.format(
"Could not find job submission process for experiment {0}, unable to fetch intermediate outputs {1}",
experimentId, outputNames));
}
String taskDag = orchestrator.createAndSaveIntermediateOutputFetchingTasks(gatewayId, processModel,
jobSubmissionProcess.get());
processModel.setTaskDag(taskDag);
registryClient.updateProcess(processModel, processModel.getProcessId());
// Figure out the credential token
UserConfigurationDataModel userConfigurationData = experimentModel.getUserConfigurationData();
String token = null;
final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId();
if (groupResourceProfileId == null) {
throw new Exception("Experiment not configured with a Group Resource Profile: " + experimentId);
}
GroupComputeResourcePreference groupComputeResourcePreference = registryClient.getGroupComputeResourcePreference(
userConfigurationData.getComputationalResourceScheduling().getResourceHostId(),
groupResourceProfileId);
if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) {
token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken();
}
if (token == null || token.isEmpty()) {
// try with group resource profile level token
GroupResourceProfile groupResourceProfile = registryClient.getGroupResourceProfile(groupResourceProfileId);
token = groupResourceProfile.getDefaultCredentialStoreToken();
}
// still the token is empty, then we fail the experiment
if (token == null || token.isEmpty()) {
throw new Exception("You have not configured credential store token at group resource profile or compute resource preference." +
" Please provide the correct token at group resource profile or compute resource preference.");
}
orchestrator.launchProcess(processModel, token);
} catch (Exception e) {
log.error("Failed to launch process for intermediate output fetching", e);
// Update Process status to FAILED
ProcessStatus status = new ProcessStatus(ProcessState.FAILED);
status.setReason("Intermediate output fetching process failed to launch: " + e.getMessage());
status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
registryClient.addProcessStatus(status, processId);
throw e;
}
}
private String getAiravataUserName() {
return airavataUserName;
}
private String getGatewayName() {
return gatewayName;
}
public void setAiravataUserName(String airavataUserName) {
this.airavataUserName = airavataUserName;
}
public void setGatewayName(String gatewayName) {
this.gatewayName = gatewayName;
}
@Override
public boolean launchProcess(String processId, String airavataCredStoreToken, String gatewayId) throws TException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
ProcessStatus processStatus = registryClient.getProcessStatus(processId);
switch (processStatus.getState()) {
case CREATED:
case VALIDATED:
case DEQUEUING:
ProcessModel processModel = registryClient.getProcess(processId);
String applicationId = processModel.getApplicationInterfaceId();
if (applicationId == null) {
log.error(processId, "Application interface id shouldn't be null.");
throw new OrchestratorException("Error executing the job, application interface id shouldn't be null.");
}
// set application deployment id to process model
ApplicationDeploymentDescription applicationDeploymentDescription = getAppDeployment(registryClient, processModel, applicationId);
if (applicationDeploymentDescription == null) {
log.error("Could not find an application deployment for " + processModel.getComputeResourceId() + " and application " + applicationId);
throw new OrchestratorException("Could not find an application deployment for " + processModel.getComputeResourceId() + " and application " + applicationId);
}
processModel.setApplicationDeploymentId(applicationDeploymentDescription.getAppDeploymentId());
// set compute resource id to process model, default we set the same in the user preferred compute host id
processModel.setComputeResourceId(processModel.getProcessResourceSchedule().getResourceHostId());
registryClient.updateProcess(processModel, processModel.getProcessId());
return orchestrator.launchProcess(processModel, airavataCredStoreToken);
default:
log.warn("Process " + processId + " is already launched. So it can not be relaunched");
return false;
}
} catch (Exception e) {
log.error(processId, "Error while launching process ", e);
throw new TException(e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
private ApplicationDeploymentDescription getAppDeployment(RegistryService.Client registryClient, ProcessModel processModel, String applicationId)
throws OrchestratorException,
ClassNotFoundException, ApplicationSettingsException,
InstantiationException, IllegalAccessException, TException {
String selectedModuleId = getModuleId(registryClient, applicationId);
return getAppDeploymentForModule(registryClient, processModel, selectedModuleId);
}
private ApplicationDeploymentDescription getAppDeploymentForModule(RegistryService.Client registryClient, ProcessModel processModel, String selectedModuleId)
throws ClassNotFoundException,
ApplicationSettingsException, InstantiationException,
IllegalAccessException, TException {
List<ApplicationDeploymentDescription> applicationDeployements = registryClient.getApplicationDeployments(selectedModuleId);
Map<ComputeResourceDescription, ApplicationDeploymentDescription> deploymentMap = new HashMap<ComputeResourceDescription, ApplicationDeploymentDescription>();
for (ApplicationDeploymentDescription deploymentDescription : applicationDeployements) {
if (processModel.getComputeResourceId().equals(deploymentDescription.getComputeHostId())) {
deploymentMap.put(registryClient.getComputeResource(deploymentDescription.getComputeHostId()), deploymentDescription);
}
}
List<ComputeResourceDescription> computeHostList = Arrays.asList(deploymentMap.keySet().toArray(new ComputeResourceDescription[]{}));
Class<? extends HostScheduler> aClass = Class.forName(
ServerSettings.getHostScheduler()).asSubclass(
HostScheduler.class);
HostScheduler hostScheduler = aClass.newInstance();
ComputeResourceDescription ComputeResourceDescription = hostScheduler.schedule(computeHostList);
return deploymentMap.get(ComputeResourceDescription);
}
private String getModuleId(RegistryService.Client registryClient, String applicationId)
throws OrchestratorException, TException {
ApplicationInterfaceDescription applicationInterface = registryClient.getApplicationInterface(applicationId);
List<String> applicationModules = applicationInterface.getApplicationModules();
if (applicationModules.size() == 0) {
throw new OrchestratorException(
"No modules defined for application "
+ applicationId);
}
// AiravataAPI airavataAPI = getAiravataAPI();
String selectedModuleId = applicationModules.get(0);
return selectedModuleId;
}
private boolean validateStatesAndCancel(RegistryService.Client registryClient, String experimentId, String gatewayId) throws Exception {
ExperimentStatus experimentStatus = registryClient.getExperimentStatus(experimentId);
switch (experimentStatus.getState()) {
case COMPLETED:
case CANCELED:
case FAILED:
case CANCELING:
log.warn("Can't terminate already {} experiment", experimentStatus.getState().name());
return false;
case CREATED:
log.warn("Experiment termination is only allowed for launched experiments.");
return false;
default:
ExperimentModel experimentModel = registryClient.getExperiment(experimentId);
final UserConfigurationDataModel userConfigurationData = experimentModel.getUserConfigurationData();
final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId();
GroupComputeResourcePreference groupComputeResourcePreference = registryClient.getGroupComputeResourcePreference(
userConfigurationData.getComputationalResourceScheduling().getResourceHostId(),
groupResourceProfileId);
String token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken();
if (token == null || token.isEmpty()) {
// try with group resource profile level token
GroupResourceProfile groupResourceProfile = registryClient.getGroupResourceProfile(groupResourceProfileId);
token = groupResourceProfile.getDefaultCredentialStoreToken();
}
// still the token is empty, then we fail the experiment
if (token == null || token.isEmpty()) {
log.error("You have not configured credential store token at group resource profile or compute resource preference." +
" Please provide the correct token at group resource profile or compute resource preference.");
return false;
}
orchestrator.cancelExperiment(experimentModel, token);
// TODO deprecate this approach as we are replacing gfac
String expCancelNodePath = ZKPaths.makePath(ZKPaths.makePath(ZkConstants.ZOOKEEPER_EXPERIMENT_NODE,
experimentId), ZkConstants.ZOOKEEPER_CANCEL_LISTENER_NODE);
Stat stat = curatorClient.checkExists().forPath(expCancelNodePath);
if (stat != null) {
curatorClient.setData().withVersion(-1).forPath(expCancelNodePath, ZkConstants.ZOOKEEPER_CANCEL_REQEUST
.getBytes());
ExperimentStatus status = new ExperimentStatus(ExperimentState.CANCELING);
status.setReason("Experiment cancel request processed");
status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId);
log.info("expId : " + experimentId + " :- Experiment status updated to " + status.getState());
}
return true;
}
}
private void launchWorkflowExperiment(String experimentId, String airavataCredStoreToken, String gatewayId) throws TException {
// FIXME
// try {
// WorkflowEnactmentService.getInstance().
// submitWorkflow(experimentId, airavataCredStoreToken, getGatewayName(), getRabbitMQProcessPublisher());
// } catch (Exception e) {
// log.error("Error while launching workflow", e);
// }
}
private class SingleAppExperimentRunner implements Runnable {
String experimentId;
String airavataCredStoreToken;
String gatewayId;
public SingleAppExperimentRunner(String experimentId, String airavataCredStoreToken, String gatewayId) {
this.experimentId = experimentId;
this.airavataCredStoreToken = airavataCredStoreToken;
this.gatewayId = gatewayId;
}
@Override
public void run() {
try {
launchSingleAppExperiment();
} catch (TException e) {
log.error("Unable to launch experiment..", e);
throw new RuntimeException("Error while launching experiment", e);
} catch (AiravataException e) {
log.error("Unable to publish experiment status..", e);
}
}
private boolean launchSingleAppExperiment() throws TException, AiravataException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
List<String> processIds = registryClient.getProcessIds(experimentId);
for (String processId : processIds) {
launchProcess(processId, airavataCredStoreToken, gatewayId);
}
// ExperimentStatus status = new ExperimentStatus(ExperimentState.LAUNCHED);
// status.setReason("submitted all processes");
// status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
// OrchestratorUtils.updageAndPublishExperimentStatus(experimentId, status);
// log.info("expId: {}, Launched experiment ", experimentId);
} catch (Exception e) {
ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED);
status.setReason("Error while updating task status");
OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId);
log.error("expId: " + experimentId + ", Error while updating task status, hence updated experiment status to " +
ExperimentState.FAILED, e);
ExperimentStatusChangeEvent event = new ExperimentStatusChangeEvent(ExperimentState.FAILED,
experimentId,
gatewayId);
String messageId = AiravataUtils.getId("EXPERIMENT");
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
publisher.publish(messageContext);
throw new TException(e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
return true;
}
}
private class ProcessStatusHandler implements MessageHandler {
/**
* This method only handle MessageType.PROCESS type messages.
*
* @param message
*/
@Override
public void onMessage(MessageContext message) {
if (message.getType().equals(MessageType.PROCESS)) {
try {
ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent();
TBase event = message.getEvent();
byte[] bytes = ThriftUtils.serializeThriftObject(event);
ThriftUtils.createThriftFromBytes(bytes, processStatusChangeEvent);
ExperimentStatus status = new ExperimentStatus();
ProcessIdentifier processIdentity = processStatusChangeEvent.getProcessIdentity();
log.info("expId: {}, processId: {} :- Process status changed event received for status {}",
processIdentity.getExperimentId(), processIdentity.getProcessId(),
processStatusChangeEvent.getState().name());
try {
ProcessModel process = OrchestratorUtils.getProcess(processIdentity.getProcessId());
boolean isIntermediateOutputFetchingProcess = process.getTasks().stream().anyMatch(t -> t.getTaskType() == TaskTypes.OUTPUT_FETCHING);
if (isIntermediateOutputFetchingProcess) {
log.info("Not updating experiment status because process is an intermediate output fetching one");
return;
}
} catch (ApplicationSettingsException e) {
throw new RuntimeException("Error getting process " + processIdentity.getProcessId(), e);
}
switch (processStatusChangeEvent.getState()) {
// case CREATED:
// case VALIDATED:
case STARTED:
try {
ExperimentStatus stat = OrchestratorUtils.getExperimentStatus(processIdentity
.getExperimentId());
if (stat.getState() == ExperimentState.CANCELING) {
status.setState(ExperimentState.CANCELING);
status.setReason("Process started but experiment cancelling is triggered");
} else {
status.setState(ExperimentState.EXECUTING);
status.setReason("process started");
}
} catch (ApplicationSettingsException e) {
throw new RuntimeException("Error ", e);
}
break;
// case PRE_PROCESSING:
// break;
// case CONFIGURING_WORKSPACE:
// case INPUT_DATA_STAGING:
// case EXECUTING:
// case MONITORING:
// case OUTPUT_DATA_STAGING:
// case POST_PROCESSING:
// case CANCELLING:
// break;
case COMPLETED:
try {
ExperimentStatus stat = OrchestratorUtils.getExperimentStatus(processIdentity
.getExperimentId());
if (stat.getState() == ExperimentState.CANCELING) {
status.setState(ExperimentState.CANCELED);
status.setReason("Process competed but experiment cancelling is triggered");
} else {
status.setState(ExperimentState.COMPLETED);
status.setReason("process completed");
}
} catch (ApplicationSettingsException e) {
throw new RuntimeException("Error ", e);
}
break;
case FAILED:
try {
ExperimentStatus stat = OrchestratorUtils.getExperimentStatus(processIdentity
.getExperimentId());
if (stat.getState() == ExperimentState.CANCELING) {
status.setState(ExperimentState.CANCELED);
status.setReason("Process failed but experiment cancelling is triggered");
} else {
status.setState(ExperimentState.FAILED);
status.setReason("process failed");
}
} catch (ApplicationSettingsException e) {
throw new RuntimeException("Unable to create registry client...", e);
}
break;
case CANCELED:
// TODO if experiment have more than one process associated with it, then this should be changed.
status.setState(ExperimentState.CANCELED);
status.setReason("process cancelled");
break;
case QUEUED:
status.setState(ExperimentState.SCHEDULED);
status.setReason("Process started but compute resource not avaialable");
break;
case REQUEUED:
status.setState(ExperimentState.SCHEDULED);
status.setReason("Job submission failed, requeued to resubmit");
List<QueueStatusModel> queueStatusModels = new ArrayList<>();
final RegistryService.Client registryClient = getRegistryServiceClient();
ExperimentModel experimentModel = registryClient.getExperiment(processIdentity.getExperimentId());
UserConfigurationDataModel userConfigurationDataModel = experimentModel.getUserConfigurationData();
if(userConfigurationDataModel != null) {
ComputationalResourceSchedulingModel computationalResourceSchedulingModel =
userConfigurationDataModel.getComputationalResourceScheduling();
if(computationalResourceSchedulingModel != null) {
String queueName = computationalResourceSchedulingModel.getQueueName();
String resourceId = computationalResourceSchedulingModel.getResourceHostId();
ComputeResourceDescription comResourceDes = registryClient.getComputeResource(resourceId);
QueueStatusModel queueStatusModel = new QueueStatusModel();
queueStatusModel.setHostName(comResourceDes.getHostName());
queueStatusModel.setQueueName(queueName);
queueStatusModel.setQueueUp(false);
queueStatusModel.setRunningJobs(0);
queueStatusModel.setQueuedJobs(0);
queueStatusModel.setTime(System.currentTimeMillis());
queueStatusModels.add(queueStatusModel);
registryClient.registerQueueStatuses(queueStatusModels);
}
}
break;
case DEQUEUING:
try {
ExperimentStatus stat = OrchestratorUtils.getExperimentStatus(processIdentity
.getExperimentId());
if (stat.getState() == ExperimentState.CANCELING) {
status.setState(ExperimentState.CANCELING);
status.setReason("Process started but experiment cancelling is triggered");
} else {
launchQueuedExperiment(processIdentity.getExperimentId());
}
} catch (Exception e) {
throw new RuntimeException("Error ", e);
}
break;
default:
// ignore other status changes, thoes will not affect for experiment status changes
return;
}
if (status.getState() != null) {
status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
OrchestratorUtils.updateAndPublishExperimentStatus(processIdentity.getExperimentId(), status, publisher, processIdentity.getGatewayId());
log.info("expId : " + processIdentity.getExperimentId() + " :- Experiment status updated to " +
status.getState());
}
} catch (TException e) {
log.error("Message Id : " + message.getMessageId() + ", Message type : " + message.getType() +
"Error" + " while prcessing process status change event");
throw new RuntimeException("Error while updating experiment status", e);
}
} else {
System.out.println("Message Recieved with message id " + message.getMessageId() + " and with message " +
"type " + message.getType().name());
}
}
}
private class ExperimentHandler implements MessageHandler {
@Override
public void onMessage(MessageContext messageContext) {
MDC.put(MDCConstants.GATEWAY_ID, messageContext.getGatewayId());
switch (messageContext.getType()) {
case EXPERIMENT:
launchExperiment(messageContext);
break;
case EXPERIMENT_CANCEL:
cancelExperiment(messageContext);
break;
case INTERMEDIATE_OUTPUTS:
handleIntermediateOutputsEvent(messageContext);
break;
default:
experimentSubscriber.sendAck(messageContext.getDeliveryTag());
log.error("Orchestrator got un-support message type : " + messageContext.getType());
break;
}
MDC.clear();
}
private void cancelExperiment(MessageContext messageContext) {
try {
byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent());
ExperimentSubmitEvent expEvent = new ExperimentSubmitEvent();
ThriftUtils.createThriftFromBytes(bytes, expEvent);
log.info("Cancelling experiment with experimentId: {} gateway Id: {}", expEvent.getExperimentId(), expEvent.getGatewayId());
terminateExperiment(expEvent.getExperimentId(), expEvent.getGatewayId());
} catch (TException e) {
log.error("Error while cancelling experiment", e);
throw new RuntimeException("Error while cancelling experiment", e);
} finally {
experimentSubscriber.sendAck(messageContext.getDeliveryTag());
}
}
private void handleIntermediateOutputsEvent(MessageContext messageContext) {
try {
byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent());
ExperimentIntermediateOutputsEvent event = new ExperimentIntermediateOutputsEvent();
ThriftUtils.createThriftFromBytes(bytes, event);
log.info("INTERMEDIATE_OUTPUTS event for experimentId: {} gateway Id: {} outputs: {}", event.getExperimentId(), event.getGatewayId(), event.getOutputNames());
fetchIntermediateOutputs(event.getExperimentId(), event.getGatewayId(), event.getOutputNames());
} catch (TException e) {
log.error("Error while fetching intermediate outputs", e);
throw new RuntimeException("Error while fetching intermediate outputs", e);
} finally {
experimentSubscriber.sendAck(messageContext.getDeliveryTag());
}
}
}
private void launchExperiment(MessageContext messageContext) {
ExperimentSubmitEvent expEvent = new ExperimentSubmitEvent();
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent());
ThriftUtils.createThriftFromBytes(bytes, expEvent);
MDC.put(MDCConstants.EXPERIMENT_ID, expEvent.getExperimentId());
log.info("Launching experiment with experimentId: {} gateway Id: {}", expEvent.getExperimentId(), expEvent.getGatewayId());
if (messageContext.isRedeliver()) {
ExperimentModel experimentModel = registryClient.
getExperiment(expEvent.getExperimentId());
MDC.put(MDCConstants.EXPERIMENT_NAME, experimentModel.getExperimentName());
if (experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED) {
launchExperiment(expEvent.getExperimentId(), expEvent.getGatewayId());
}
} else {
launchExperiment(expEvent.getExperimentId(), expEvent.getGatewayId());
}
} catch (TException e) {
String logMessage = expEvent.getExperimentId() != null && expEvent.getGatewayId() != null ?
String.format("Experiment launch failed due to Thrift conversion error, experimentId: %s, gatewayId: %s",
expEvent.getExperimentId(), expEvent.getGatewayId()) : "Experiment launch failed due to Thrift conversion error";
log.error(logMessage, e);
} catch (Exception e) {
log.error("An unknown issue while launching experiment " + Optional.ofNullable(expEvent.getExperimentId()).orElse("missing experiment") +
" on gateway " + Optional.ofNullable(expEvent.getGatewayId()).orElse("missing gateway"), e);
} finally {
experimentSubscriber.sendAck(messageContext.getDeliveryTag());
MDC.clear();
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
private RegistryService.Client getRegistryServiceClient() {
try {
final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
final String serverHost = ServerSettings.getRegistryServerHost();
return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort);
} catch (RegistryServiceException | ApplicationSettingsException e) {
throw new RuntimeException("Unable to create registry client...", e);
}
}
private void startCurator() throws ApplicationSettingsException {
String connectionSting = ServerSettings.getZookeeperConnection();
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
curatorClient = CuratorFrameworkFactory.newClient(connectionSting, retryPolicy);
curatorClient.start();
}
public String getExperimentNodePath(String experimentId) {
return ZKPaths.makePath(ZkConstants.ZOOKEEPER_EXPERIMENT_NODE, experimentId);
}
private void runExperimentLauncher(String experimentId, String gatewayId, String token) throws TException {
ExperimentStatus status = new ExperimentStatus(ExperimentState.LAUNCHED);
status.setReason("submitted all processes");
status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId);
log.info("expId: {}, Launched experiment ", experimentId);
OrchestratorServerThreadPoolExecutor.getCachedThreadPool().execute(MDCUtil.wrapWithMDC(new SingleAppExperimentRunner(experimentId, token, gatewayId)));
}
private void launchQueuedExperiment(String experimentId) throws TException, Exception {
ExperimentModel experiment = null;
final RegistryService.Client registryClient = getRegistryServiceClient();
// TODO deprecate this approach as we are replacing gfac
experiment = registryClient.getExperiment(experimentId);
if (experiment == null) {
throw new Exception("Error retrieving the Experiment by the given experimentID: " + experimentId);
}
UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData();
String token = null;
final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId();
if (groupResourceProfileId == null) {
throw new Exception("Experiment not configured with a Group Resource Profile: " + experimentId);
}
GroupComputeResourcePreference groupComputeResourcePreference = registryClient.getGroupComputeResourcePreference(
userConfigurationData.getComputationalResourceScheduling().getResourceHostId(),
groupResourceProfileId);
if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) {
token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken();
}
if (token == null || token.isEmpty()) {
// try with group resource profile level token
GroupResourceProfile groupResourceProfile = registryClient.getGroupResourceProfile(groupResourceProfileId);
token = groupResourceProfile.getDefaultCredentialStoreToken();
}
// still the token is empty, then we fail the experiment
if (token == null || token.isEmpty()) {
throw new Exception("You have not configured credential store token at group resource profile or compute resource preference." +
" Please provide the correct token at group resource profile or compute resource preference.");
}
createAndValidateTasks(experiment,registryClient, true);
runExperimentLauncher(experimentId, experiment.getGatewayId(), token);
}
private void createAndValidateTasks(ExperimentModel experiment, RegistryService.Client registryClient, boolean recreateTaskDag) throws Exception {
if (experiment.getUserConfigurationData().isAiravataAutoSchedule()){
List<ProcessModel> processModels = registryClient.getProcessList(experiment.getExperimentId());
for (ProcessModel processModel : processModels) {
if (processModel.getTaskDag() == null || recreateTaskDag) {
registryClient.deleteTasks(processModel.getProcessId());
String taskDag = orchestrator.createAndSaveTasks(experiment.getGatewayId(), processModel);
processModel.setTaskDag(taskDag);
registryClient.updateProcess(processModel, processModel.getProcessId());
}
}
if (!validateProcess(experiment.getExperimentId(), processModels)) {
throw new Exception("Validating process fails for given experiment Id : " + experiment.getExperimentId());
}
}
}
}
| 1,201 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator/server/OrchestratorServer.java | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.airavata.orchestrator.server;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.IServer;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.compute.resource.monitoring.ComputationalResourceMonitoringService;
import org.apache.airavata.metascheduler.metadata.analyzer.DataInterpreterService;
import org.apache.airavata.metascheduler.process.scheduling.engine.rescheduler.ProcessReschedulingService;
import org.apache.airavata.orchestrator.cpi.OrchestratorService;
import org.apache.airavata.orchestrator.util.Constants;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
public class OrchestratorServer implements IServer {
private final static Logger logger = LoggerFactory.getLogger(OrchestratorServer.class);
private static final String SERVER_NAME = "Orchestrator Server";
private static final String SERVER_VERSION = "1.0";
private ServerStatus status;
private TServer server;
private static ComputationalResourceMonitoringService monitoringService;
private static ProcessReschedulingService metaschedulerService;
private static DataInterpreterService dataInterpreterService;
// private ClusterStatusMonitorJobScheduler clusterStatusMonitorJobScheduler;
public OrchestratorServer() {
setStatus(ServerStatus.STOPPED);
}
public void StartOrchestratorServer(OrchestratorService.Processor<OrchestratorServerHandler> orchestratorServerHandlerProcessor)
throws Exception {
final int serverPort = Integer.parseInt(ServerSettings.getSetting(Constants.ORCHESTRATOT_SERVER_PORT, "8940"));
try {
final String serverHost = ServerSettings.getSetting(Constants.ORCHESTRATOT_SERVER_HOST, null);
TServerTransport serverTransport;
if (serverHost == null) {
serverTransport = new TServerSocket(serverPort);
} else {
InetSocketAddress inetSocketAddress = new InetSocketAddress(serverHost, serverPort);
serverTransport = new TServerSocket(inetSocketAddress);
}
//server = new TSimpleServer(
// new TServer.Args(serverTransport).processor(orchestratorServerHandlerProcessor));
TThreadPoolServer.Args options = new TThreadPoolServer.Args(serverTransport);
options.minWorkerThreads = Integer.parseInt(ServerSettings.getSetting(Constants.ORCHESTRATOT_SERVER_MIN_THREADS, "30"));
server = new TThreadPoolServer(options.processor(orchestratorServerHandlerProcessor));
new Thread() {
public void run() {
server.serve();
setStatus(ServerStatus.STARTING);
logger.info("Starting Orchestrator Server ... ");
}
}.start();
new Thread() {
public void run() {
while (!server.isServing()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
if (server.isServing()) {
setStatus(ServerStatus.STARTED);
logger.info("Started Orchestrator Server on Port " + serverPort + " ...");
}
}
}.start();
} catch (TTransportException e) {
logger.error(e.getMessage());
setStatus(ServerStatus.FAILED);
logger.error("Failed to start Orchestrator server on port " + serverPort + " ...");
}
}
public void startClusterStatusMonitoring() throws SchedulerException, ApplicationSettingsException {
// clusterStatusMonitorJobScheduler = new ClusterStatusMonitorJobScheduler();
// clusterStatusMonitorJobScheduler.scheduleClusterStatusMonitoring();
try {
if (monitoringService == null) {
monitoringService = new ComputationalResourceMonitoringService();
monitoringService.setServerStatus(ServerStatus.STARTING);
}
if (monitoringService != null && !monitoringService.getStatus().equals(ServerStatus.STARTED)) {
monitoringService.start();
monitoringService.setServerStatus(ServerStatus.STARTED);
logger.info("Airavata compute resource monitoring service started ....");
}
} catch (Exception ex) {
logger.error("Airavata compute resource monitoring service failed ....",ex);
}
}
public void startMetaschedulerJobScanning() throws SchedulerException, ApplicationSettingsException {
try {
if (metaschedulerService == null) {
metaschedulerService = new ProcessReschedulingService();
metaschedulerService.setServerStatus(ServerStatus.STARTING);
}
if (metaschedulerService != null && !metaschedulerService.getStatus().equals(ServerStatus.STARTED)) {
metaschedulerService.start();
metaschedulerService.setServerStatus(ServerStatus.STARTED);
logger.info("Airavata metascheduler job scanning service started ....");
}
} catch (Exception ex) {
logger.error("Airavata metascheduler job scanning service failed ....",ex);
}
}
public void startMetadataDataAnalyzer() throws SchedulerException, ApplicationSettingsException {
try {
if (dataInterpreterService == null) {
dataInterpreterService = new DataInterpreterService();
dataInterpreterService.setServerStatus(ServerStatus.STARTING);
}
if (dataInterpreterService != null && !dataInterpreterService.getStatus().equals(ServerStatus.STARTED)) {
dataInterpreterService.start();
dataInterpreterService.setServerStatus(ServerStatus.STARTED);
logger.info("Airavata data interpreter job scanning service started ....");
}
} catch (Exception ex) {
logger.error("Airavata data interpreter job scanning service failed ....",ex);
}
}
public static void main(String[] args) {
try {
new OrchestratorServer().start();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void start() throws Exception {
if (ServerSettings.enableClusterStatusMonitoring()) {
//starting cluster status monitoring
startClusterStatusMonitoring();
}
if (ServerSettings.enableMetaschedulerJobScanning()) {
//starting cluster status monitoring
startMetaschedulerJobScanning();
}
if (ServerSettings.enableDataAnalyzerJobScanning()) {
//starting metadata analyzer
startMetadataDataAnalyzer();
}
setStatus(ServerStatus.STARTING);
OrchestratorService.Processor<OrchestratorServerHandler> orchestratorService =
new OrchestratorService.Processor<OrchestratorServerHandler>(new OrchestratorServerHandler());
StartOrchestratorServer(orchestratorService);
}
@Override
public void stop() throws Exception {
if (server != null && server.isServing()) {
setStatus(ServerStatus.STOPING);
server.stop();
}
if (monitoringService != null) {
monitoringService.stop();
monitoringService.setServerStatus(ServerStatus.STOPPED);
}
}
@Override
public void restart() throws Exception {
stop();
start();
}
@Override
public void configure() throws Exception {
// TODO Auto-generated method stub
}
@Override
public ServerStatus getStatus() throws Exception {
return status;
}
private void setStatus(ServerStatus stat) {
status = stat;
status.updateTime();
}
@Override
public String getName() {
return SERVER_NAME;
}
@Override
public String getVersion() {
return SERVER_VERSION;
}
}
| 1,202 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator/cpi/orchestrator_cpiConstants.java | /**
* 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.
*/
/**
* Autogenerated by Thrift Compiler (0.18.1)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.airavata.orchestrator.cpi;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public class orchestrator_cpiConstants {
public static final java.lang.String ORCHESTRATOR_CPI_VERSION = "0.18.0";
}
| 1,203 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator/cpi/OrchestratorService.java | /**
* 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.
*/
/**
* Autogenerated by Thrift Compiler (0.18.1)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.airavata.orchestrator.cpi;
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.18.1)")
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public class OrchestratorService {
public interface Iface extends org.apache.airavata.base.api.BaseAPI.Iface {
/**
* * After creating the experiment Data user have the
* * experimentID as the handler to the experiment, during the launchExperiment
* * We just have to give the experimentID
* *
* * @param experimentID
* * @return sucess/failure
* *
* *
*
* @param experimentId
* @param gatewayId
*/
public boolean launchExperiment(java.lang.String experimentId, java.lang.String gatewayId) throws org.apache.thrift.TException;
/**
* * In order to run single applications users should create an associating
* * process and hand it over for execution
* * along with a credential store token for sshKeyAuthentication
* *
* * @param processId
* * @param airavataCredStoreToken
* * @return sucess/failure
* *
* *
*
* @param processId
* @param airavataCredStoreToken
* @param gatewayId
*/
public boolean launchProcess(java.lang.String processId, java.lang.String airavataCredStoreToken, java.lang.String gatewayId) throws org.apache.thrift.TException;
/**
* *
* * Validate funcations which can verify if the experiment is ready to be launced.
* *
* * @param experimentID
* * @return sucess/failure
* *
* *
*
* @param experimentId
*/
public boolean validateExperiment(java.lang.String experimentId) throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException;
public boolean validateProcess(java.lang.String experimentId, java.util.List<org.apache.airavata.model.process.ProcessModel> processes) throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException;
/**
* *
* * Terminate the running experiment.
* *
* * @param experimentID
* * @return sucess/failure
* *
* *
*
* @param experimentId
* @param gatewayId
*/
public boolean terminateExperiment(java.lang.String experimentId, java.lang.String gatewayId) throws org.apache.thrift.TException;
}
public interface AsyncIface extends org.apache.airavata.base.api.BaseAPI.AsyncIface {
public void launchExperiment(java.lang.String experimentId, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException;
public void launchProcess(java.lang.String processId, java.lang.String airavataCredStoreToken, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException;
public void validateExperiment(java.lang.String experimentId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException;
public void validateProcess(java.lang.String experimentId, java.util.List<org.apache.airavata.model.process.ProcessModel> processes, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException;
public void terminateExperiment(java.lang.String experimentId, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.airavata.base.api.BaseAPI.Client implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {}
@Override
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
@Override
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot)
{
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
@Override
public boolean launchExperiment(java.lang.String experimentId, java.lang.String gatewayId) throws org.apache.thrift.TException
{
send_launchExperiment(experimentId, gatewayId);
return recv_launchExperiment();
}
public void send_launchExperiment(java.lang.String experimentId, java.lang.String gatewayId) throws org.apache.thrift.TException
{
launchExperiment_args args = new launchExperiment_args();
args.setExperimentId(experimentId);
args.setGatewayId(gatewayId);
sendBase("launchExperiment", args);
}
public boolean recv_launchExperiment() throws org.apache.thrift.TException
{
launchExperiment_result result = new launchExperiment_result();
receiveBase(result, "launchExperiment");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "launchExperiment failed: unknown result");
}
@Override
public boolean launchProcess(java.lang.String processId, java.lang.String airavataCredStoreToken, java.lang.String gatewayId) throws org.apache.thrift.TException
{
send_launchProcess(processId, airavataCredStoreToken, gatewayId);
return recv_launchProcess();
}
public void send_launchProcess(java.lang.String processId, java.lang.String airavataCredStoreToken, java.lang.String gatewayId) throws org.apache.thrift.TException
{
launchProcess_args args = new launchProcess_args();
args.setProcessId(processId);
args.setAiravataCredStoreToken(airavataCredStoreToken);
args.setGatewayId(gatewayId);
sendBase("launchProcess", args);
}
public boolean recv_launchProcess() throws org.apache.thrift.TException
{
launchProcess_result result = new launchProcess_result();
receiveBase(result, "launchProcess");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "launchProcess failed: unknown result");
}
@Override
public boolean validateExperiment(java.lang.String experimentId) throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException
{
send_validateExperiment(experimentId);
return recv_validateExperiment();
}
public void send_validateExperiment(java.lang.String experimentId) throws org.apache.thrift.TException
{
validateExperiment_args args = new validateExperiment_args();
args.setExperimentId(experimentId);
sendBase("validateExperiment", args);
}
public boolean recv_validateExperiment() throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException
{
validateExperiment_result result = new validateExperiment_result();
receiveBase(result, "validateExperiment");
if (result.isSetSuccess()) {
return result.success;
}
if (result.lve != null) {
throw result.lve;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "validateExperiment failed: unknown result");
}
@Override
public boolean validateProcess(java.lang.String experimentId, java.util.List<org.apache.airavata.model.process.ProcessModel> processes) throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException
{
send_validateProcess(experimentId, processes);
return recv_validateProcess();
}
public void send_validateProcess(java.lang.String experimentId, java.util.List<org.apache.airavata.model.process.ProcessModel> processes) throws org.apache.thrift.TException
{
validateProcess_args args = new validateProcess_args();
args.setExperimentId(experimentId);
args.setProcesses(processes);
sendBase("validateProcess", args);
}
public boolean recv_validateProcess() throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException
{
validateProcess_result result = new validateProcess_result();
receiveBase(result, "validateProcess");
if (result.isSetSuccess()) {
return result.success;
}
if (result.lve != null) {
throw result.lve;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "validateProcess failed: unknown result");
}
@Override
public boolean terminateExperiment(java.lang.String experimentId, java.lang.String gatewayId) throws org.apache.thrift.TException
{
send_terminateExperiment(experimentId, gatewayId);
return recv_terminateExperiment();
}
public void send_terminateExperiment(java.lang.String experimentId, java.lang.String gatewayId) throws org.apache.thrift.TException
{
terminateExperiment_args args = new terminateExperiment_args();
args.setExperimentId(experimentId);
args.setGatewayId(gatewayId);
sendBase("terminateExperiment", args);
}
public boolean recv_terminateExperiment() throws org.apache.thrift.TException
{
terminateExperiment_result result = new terminateExperiment_result();
receiveBase(result, "terminateExperiment");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "terminateExperiment failed: unknown result");
}
}
public static class AsyncClient extends org.apache.airavata.base.api.BaseAPI.AsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
@Override
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
@Override
public void launchExperiment(java.lang.String experimentId, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
checkReady();
launchExperiment_call method_call = new launchExperiment_call(experimentId, gatewayId, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class launchExperiment_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.Boolean> {
private java.lang.String experimentId;
private java.lang.String gatewayId;
public launchExperiment_call(java.lang.String experimentId, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.experimentId = experimentId;
this.gatewayId = gatewayId;
}
@Override
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("launchExperiment", org.apache.thrift.protocol.TMessageType.CALL, 0));
launchExperiment_args args = new launchExperiment_args();
args.setExperimentId(experimentId);
args.setGatewayId(gatewayId);
args.write(prot);
prot.writeMessageEnd();
}
@Override
public java.lang.Boolean getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_launchExperiment();
}
}
@Override
public void launchProcess(java.lang.String processId, java.lang.String airavataCredStoreToken, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
checkReady();
launchProcess_call method_call = new launchProcess_call(processId, airavataCredStoreToken, gatewayId, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class launchProcess_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.Boolean> {
private java.lang.String processId;
private java.lang.String airavataCredStoreToken;
private java.lang.String gatewayId;
public launchProcess_call(java.lang.String processId, java.lang.String airavataCredStoreToken, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.processId = processId;
this.airavataCredStoreToken = airavataCredStoreToken;
this.gatewayId = gatewayId;
}
@Override
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("launchProcess", org.apache.thrift.protocol.TMessageType.CALL, 0));
launchProcess_args args = new launchProcess_args();
args.setProcessId(processId);
args.setAiravataCredStoreToken(airavataCredStoreToken);
args.setGatewayId(gatewayId);
args.write(prot);
prot.writeMessageEnd();
}
@Override
public java.lang.Boolean getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_launchProcess();
}
}
@Override
public void validateExperiment(java.lang.String experimentId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
checkReady();
validateExperiment_call method_call = new validateExperiment_call(experimentId, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class validateExperiment_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.Boolean> {
private java.lang.String experimentId;
public validateExperiment_call(java.lang.String experimentId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.experimentId = experimentId;
}
@Override
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("validateExperiment", org.apache.thrift.protocol.TMessageType.CALL, 0));
validateExperiment_args args = new validateExperiment_args();
args.setExperimentId(experimentId);
args.write(prot);
prot.writeMessageEnd();
}
@Override
public java.lang.Boolean getResult() throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_validateExperiment();
}
}
@Override
public void validateProcess(java.lang.String experimentId, java.util.List<org.apache.airavata.model.process.ProcessModel> processes, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
checkReady();
validateProcess_call method_call = new validateProcess_call(experimentId, processes, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class validateProcess_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.Boolean> {
private java.lang.String experimentId;
private java.util.List<org.apache.airavata.model.process.ProcessModel> processes;
public validateProcess_call(java.lang.String experimentId, java.util.List<org.apache.airavata.model.process.ProcessModel> processes, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.experimentId = experimentId;
this.processes = processes;
}
@Override
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("validateProcess", org.apache.thrift.protocol.TMessageType.CALL, 0));
validateProcess_args args = new validateProcess_args();
args.setExperimentId(experimentId);
args.setProcesses(processes);
args.write(prot);
prot.writeMessageEnd();
}
@Override
public java.lang.Boolean getResult() throws org.apache.airavata.model.error.LaunchValidationException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_validateProcess();
}
}
@Override
public void terminateExperiment(java.lang.String experimentId, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
checkReady();
terminateExperiment_call method_call = new terminateExperiment_call(experimentId, gatewayId, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class terminateExperiment_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.Boolean> {
private java.lang.String experimentId;
private java.lang.String gatewayId;
public terminateExperiment_call(java.lang.String experimentId, java.lang.String gatewayId, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.experimentId = experimentId;
this.gatewayId = gatewayId;
}
@Override
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("terminateExperiment", org.apache.thrift.protocol.TMessageType.CALL, 0));
terminateExperiment_args args = new terminateExperiment_args();
args.setExperimentId(experimentId);
args.setGatewayId(gatewayId);
args.write(prot);
prot.writeMessageEnd();
}
@Override
public java.lang.Boolean getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_terminateExperiment();
}
}
}
public static class Processor<I extends Iface> extends org.apache.airavata.base.api.BaseAPI.Processor<I> implements org.apache.thrift.TProcessor {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface, java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("launchExperiment", new launchExperiment());
processMap.put("launchProcess", new launchProcess());
processMap.put("validateExperiment", new validateExperiment());
processMap.put("validateProcess", new validateProcess());
processMap.put("terminateExperiment", new terminateExperiment());
return processMap;
}
public static class launchExperiment<I extends Iface> extends org.apache.thrift.ProcessFunction<I, launchExperiment_args> {
public launchExperiment() {
super("launchExperiment");
}
@Override
public launchExperiment_args getEmptyArgsInstance() {
return new launchExperiment_args();
}
@Override
protected boolean isOneway() {
return false;
}
@Override
protected boolean rethrowUnhandledExceptions() {
return false;
}
@Override
public launchExperiment_result getResult(I iface, launchExperiment_args args) throws org.apache.thrift.TException {
launchExperiment_result result = new launchExperiment_result();
result.success = iface.launchExperiment(args.experimentId, args.gatewayId);
result.setSuccessIsSet(true);
return result;
}
}
public static class launchProcess<I extends Iface> extends org.apache.thrift.ProcessFunction<I, launchProcess_args> {
public launchProcess() {
super("launchProcess");
}
@Override
public launchProcess_args getEmptyArgsInstance() {
return new launchProcess_args();
}
@Override
protected boolean isOneway() {
return false;
}
@Override
protected boolean rethrowUnhandledExceptions() {
return false;
}
@Override
public launchProcess_result getResult(I iface, launchProcess_args args) throws org.apache.thrift.TException {
launchProcess_result result = new launchProcess_result();
result.success = iface.launchProcess(args.processId, args.airavataCredStoreToken, args.gatewayId);
result.setSuccessIsSet(true);
return result;
}
}
public static class validateExperiment<I extends Iface> extends org.apache.thrift.ProcessFunction<I, validateExperiment_args> {
public validateExperiment() {
super("validateExperiment");
}
@Override
public validateExperiment_args getEmptyArgsInstance() {
return new validateExperiment_args();
}
@Override
protected boolean isOneway() {
return false;
}
@Override
protected boolean rethrowUnhandledExceptions() {
return false;
}
@Override
public validateExperiment_result getResult(I iface, validateExperiment_args args) throws org.apache.thrift.TException {
validateExperiment_result result = new validateExperiment_result();
try {
result.success = iface.validateExperiment(args.experimentId);
result.setSuccessIsSet(true);
} catch (org.apache.airavata.model.error.LaunchValidationException lve) {
result.lve = lve;
}
return result;
}
}
public static class validateProcess<I extends Iface> extends org.apache.thrift.ProcessFunction<I, validateProcess_args> {
public validateProcess() {
super("validateProcess");
}
@Override
public validateProcess_args getEmptyArgsInstance() {
return new validateProcess_args();
}
@Override
protected boolean isOneway() {
return false;
}
@Override
protected boolean rethrowUnhandledExceptions() {
return false;
}
@Override
public validateProcess_result getResult(I iface, validateProcess_args args) throws org.apache.thrift.TException {
validateProcess_result result = new validateProcess_result();
try {
result.success = iface.validateProcess(args.experimentId, args.processes);
result.setSuccessIsSet(true);
} catch (org.apache.airavata.model.error.LaunchValidationException lve) {
result.lve = lve;
}
return result;
}
}
public static class terminateExperiment<I extends Iface> extends org.apache.thrift.ProcessFunction<I, terminateExperiment_args> {
public terminateExperiment() {
super("terminateExperiment");
}
@Override
public terminateExperiment_args getEmptyArgsInstance() {
return new terminateExperiment_args();
}
@Override
protected boolean isOneway() {
return false;
}
@Override
protected boolean rethrowUnhandledExceptions() {
return false;
}
@Override
public terminateExperiment_result getResult(I iface, terminateExperiment_args args) throws org.apache.thrift.TException {
terminateExperiment_result result = new terminateExperiment_result();
result.success = iface.terminateExperiment(args.experimentId, args.gatewayId);
result.setSuccessIsSet(true);
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.airavata.base.api.BaseAPI.AsyncProcessor<I> {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface, java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("launchExperiment", new launchExperiment());
processMap.put("launchProcess", new launchProcess());
processMap.put("validateExperiment", new validateExperiment());
processMap.put("validateProcess", new validateProcess());
processMap.put("terminateExperiment", new terminateExperiment());
return processMap;
}
public static class launchExperiment<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, launchExperiment_args, java.lang.Boolean> {
public launchExperiment() {
super("launchExperiment");
}
@Override
public launchExperiment_args getEmptyArgsInstance() {
return new launchExperiment_args();
}
@Override
public org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean>() {
@Override
public void onComplete(java.lang.Boolean o) {
launchExperiment_result result = new launchExperiment_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
@Override
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
launchExperiment_result result = new launchExperiment_result();
if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
@Override
protected boolean isOneway() {
return false;
}
@Override
public void start(I iface, launchExperiment_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
iface.launchExperiment(args.experimentId, args.gatewayId,resultHandler);
}
}
public static class launchProcess<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, launchProcess_args, java.lang.Boolean> {
public launchProcess() {
super("launchProcess");
}
@Override
public launchProcess_args getEmptyArgsInstance() {
return new launchProcess_args();
}
@Override
public org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean>() {
@Override
public void onComplete(java.lang.Boolean o) {
launchProcess_result result = new launchProcess_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
@Override
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
launchProcess_result result = new launchProcess_result();
if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
@Override
protected boolean isOneway() {
return false;
}
@Override
public void start(I iface, launchProcess_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
iface.launchProcess(args.processId, args.airavataCredStoreToken, args.gatewayId,resultHandler);
}
}
public static class validateExperiment<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, validateExperiment_args, java.lang.Boolean> {
public validateExperiment() {
super("validateExperiment");
}
@Override
public validateExperiment_args getEmptyArgsInstance() {
return new validateExperiment_args();
}
@Override
public org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean>() {
@Override
public void onComplete(java.lang.Boolean o) {
validateExperiment_result result = new validateExperiment_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
@Override
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
validateExperiment_result result = new validateExperiment_result();
if (e instanceof org.apache.airavata.model.error.LaunchValidationException) {
result.lve = (org.apache.airavata.model.error.LaunchValidationException) e;
result.setLveIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
@Override
protected boolean isOneway() {
return false;
}
@Override
public void start(I iface, validateExperiment_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
iface.validateExperiment(args.experimentId,resultHandler);
}
}
public static class validateProcess<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, validateProcess_args, java.lang.Boolean> {
public validateProcess() {
super("validateProcess");
}
@Override
public validateProcess_args getEmptyArgsInstance() {
return new validateProcess_args();
}
@Override
public org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean>() {
@Override
public void onComplete(java.lang.Boolean o) {
validateProcess_result result = new validateProcess_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
@Override
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
validateProcess_result result = new validateProcess_result();
if (e instanceof org.apache.airavata.model.error.LaunchValidationException) {
result.lve = (org.apache.airavata.model.error.LaunchValidationException) e;
result.setLveIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
@Override
protected boolean isOneway() {
return false;
}
@Override
public void start(I iface, validateProcess_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
iface.validateProcess(args.experimentId, args.processes,resultHandler);
}
}
public static class terminateExperiment<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, terminateExperiment_args, java.lang.Boolean> {
public terminateExperiment() {
super("terminateExperiment");
}
@Override
public terminateExperiment_args getEmptyArgsInstance() {
return new terminateExperiment_args();
}
@Override
public org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean>() {
@Override
public void onComplete(java.lang.Boolean o) {
terminateExperiment_result result = new terminateExperiment_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
@Override
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
terminateExperiment_result result = new terminateExperiment_result();
if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
@Override
protected boolean isOneway() {
return false;
}
@Override
public void start(I iface, terminateExperiment_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
iface.terminateExperiment(args.experimentId, args.gatewayId,resultHandler);
}
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class launchExperiment_args implements org.apache.thrift.TBase<launchExperiment_args, launchExperiment_args._Fields>, java.io.Serializable, Cloneable, Comparable<launchExperiment_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("launchExperiment_args");
private static final org.apache.thrift.protocol.TField EXPERIMENT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("experimentId", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField GATEWAY_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("gatewayId", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new launchExperiment_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new launchExperiment_argsTupleSchemeFactory();
public @org.apache.thrift.annotation.Nullable java.lang.String experimentId; // required
public @org.apache.thrift.annotation.Nullable java.lang.String gatewayId; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
EXPERIMENT_ID((short)1, "experimentId"),
GATEWAY_ID((short)2, "gatewayId");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // EXPERIMENT_ID
return EXPERIMENT_ID;
case 2: // GATEWAY_ID
return GATEWAY_ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.EXPERIMENT_ID, new org.apache.thrift.meta_data.FieldMetaData("experimentId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.GATEWAY_ID, new org.apache.thrift.meta_data.FieldMetaData("gatewayId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(launchExperiment_args.class, metaDataMap);
}
public launchExperiment_args() {
}
public launchExperiment_args(
java.lang.String experimentId,
java.lang.String gatewayId)
{
this();
this.experimentId = experimentId;
this.gatewayId = gatewayId;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public launchExperiment_args(launchExperiment_args other) {
if (other.isSetExperimentId()) {
this.experimentId = other.experimentId;
}
if (other.isSetGatewayId()) {
this.gatewayId = other.gatewayId;
}
}
@Override
public launchExperiment_args deepCopy() {
return new launchExperiment_args(this);
}
@Override
public void clear() {
this.experimentId = null;
this.gatewayId = null;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getExperimentId() {
return this.experimentId;
}
public launchExperiment_args setExperimentId(@org.apache.thrift.annotation.Nullable java.lang.String experimentId) {
this.experimentId = experimentId;
return this;
}
public void unsetExperimentId() {
this.experimentId = null;
}
/** Returns true if field experimentId is set (has been assigned a value) and false otherwise */
public boolean isSetExperimentId() {
return this.experimentId != null;
}
public void setExperimentIdIsSet(boolean value) {
if (!value) {
this.experimentId = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getGatewayId() {
return this.gatewayId;
}
public launchExperiment_args setGatewayId(@org.apache.thrift.annotation.Nullable java.lang.String gatewayId) {
this.gatewayId = gatewayId;
return this;
}
public void unsetGatewayId() {
this.gatewayId = null;
}
/** Returns true if field gatewayId is set (has been assigned a value) and false otherwise */
public boolean isSetGatewayId() {
return this.gatewayId != null;
}
public void setGatewayIdIsSet(boolean value) {
if (!value) {
this.gatewayId = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case EXPERIMENT_ID:
if (value == null) {
unsetExperimentId();
} else {
setExperimentId((java.lang.String)value);
}
break;
case GATEWAY_ID:
if (value == null) {
unsetGatewayId();
} else {
setGatewayId((java.lang.String)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case EXPERIMENT_ID:
return getExperimentId();
case GATEWAY_ID:
return getGatewayId();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case EXPERIMENT_ID:
return isSetExperimentId();
case GATEWAY_ID:
return isSetGatewayId();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof launchExperiment_args)
return this.equals((launchExperiment_args)that);
return false;
}
public boolean equals(launchExperiment_args that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_experimentId = true && this.isSetExperimentId();
boolean that_present_experimentId = true && that.isSetExperimentId();
if (this_present_experimentId || that_present_experimentId) {
if (!(this_present_experimentId && that_present_experimentId))
return false;
if (!this.experimentId.equals(that.experimentId))
return false;
}
boolean this_present_gatewayId = true && this.isSetGatewayId();
boolean that_present_gatewayId = true && that.isSetGatewayId();
if (this_present_gatewayId || that_present_gatewayId) {
if (!(this_present_gatewayId && that_present_gatewayId))
return false;
if (!this.gatewayId.equals(that.gatewayId))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetExperimentId()) ? 131071 : 524287);
if (isSetExperimentId())
hashCode = hashCode * 8191 + experimentId.hashCode();
hashCode = hashCode * 8191 + ((isSetGatewayId()) ? 131071 : 524287);
if (isSetGatewayId())
hashCode = hashCode * 8191 + gatewayId.hashCode();
return hashCode;
}
@Override
public int compareTo(launchExperiment_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetExperimentId(), other.isSetExperimentId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetExperimentId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.experimentId, other.experimentId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetGatewayId(), other.isSetGatewayId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetGatewayId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.gatewayId, other.gatewayId);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("launchExperiment_args(");
boolean first = true;
sb.append("experimentId:");
if (this.experimentId == null) {
sb.append("null");
} else {
sb.append(this.experimentId);
}
first = false;
if (!first) sb.append(", ");
sb.append("gatewayId:");
if (this.gatewayId == null) {
sb.append("null");
} else {
sb.append(this.gatewayId);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (experimentId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'experimentId' was not present! Struct: " + toString());
}
if (gatewayId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'gatewayId' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class launchExperiment_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchExperiment_argsStandardScheme getScheme() {
return new launchExperiment_argsStandardScheme();
}
}
private static class launchExperiment_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme<launchExperiment_args> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, launchExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // EXPERIMENT_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // GATEWAY_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.gatewayId = iprot.readString();
struct.setGatewayIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, launchExperiment_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.experimentId != null) {
oprot.writeFieldBegin(EXPERIMENT_ID_FIELD_DESC);
oprot.writeString(struct.experimentId);
oprot.writeFieldEnd();
}
if (struct.gatewayId != null) {
oprot.writeFieldBegin(GATEWAY_ID_FIELD_DESC);
oprot.writeString(struct.gatewayId);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class launchExperiment_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchExperiment_argsTupleScheme getScheme() {
return new launchExperiment_argsTupleScheme();
}
}
private static class launchExperiment_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<launchExperiment_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, launchExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
oprot.writeString(struct.experimentId);
oprot.writeString(struct.gatewayId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, launchExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
struct.gatewayId = iprot.readString();
struct.setGatewayIdIsSet(true);
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class launchExperiment_result implements org.apache.thrift.TBase<launchExperiment_result, launchExperiment_result._Fields>, java.io.Serializable, Cloneable, Comparable<launchExperiment_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("launchExperiment_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new launchExperiment_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new launchExperiment_resultTupleSchemeFactory();
public boolean success; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(launchExperiment_result.class, metaDataMap);
}
public launchExperiment_result() {
}
public launchExperiment_result(
boolean success)
{
this();
this.success = success;
setSuccessIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public launchExperiment_result(launchExperiment_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
}
@Override
public launchExperiment_result deepCopy() {
return new launchExperiment_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = false;
}
public boolean isSuccess() {
return this.success;
}
public launchExperiment_result setSuccess(boolean success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((java.lang.Boolean)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return isSuccess();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof launchExperiment_result)
return this.equals((launchExperiment_result)that);
return false;
}
public boolean equals(launchExperiment_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((success) ? 131071 : 524287);
return hashCode;
}
@Override
public int compareTo(launchExperiment_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetSuccess(), other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("launchExperiment_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class launchExperiment_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchExperiment_resultStandardScheme getScheme() {
return new launchExperiment_resultStandardScheme();
}
}
private static class launchExperiment_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme<launchExperiment_result> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, launchExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, launchExperiment_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeBool(struct.success);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class launchExperiment_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchExperiment_resultTupleScheme getScheme() {
return new launchExperiment_resultTupleScheme();
}
}
private static class launchExperiment_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<launchExperiment_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, launchExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
oprot.writeBool(struct.success);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, launchExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class launchProcess_args implements org.apache.thrift.TBase<launchProcess_args, launchProcess_args._Fields>, java.io.Serializable, Cloneable, Comparable<launchProcess_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("launchProcess_args");
private static final org.apache.thrift.protocol.TField PROCESS_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("processId", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField AIRAVATA_CRED_STORE_TOKEN_FIELD_DESC = new org.apache.thrift.protocol.TField("airavataCredStoreToken", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField GATEWAY_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("gatewayId", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new launchProcess_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new launchProcess_argsTupleSchemeFactory();
public @org.apache.thrift.annotation.Nullable java.lang.String processId; // required
public @org.apache.thrift.annotation.Nullable java.lang.String airavataCredStoreToken; // required
public @org.apache.thrift.annotation.Nullable java.lang.String gatewayId; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
PROCESS_ID((short)1, "processId"),
AIRAVATA_CRED_STORE_TOKEN((short)2, "airavataCredStoreToken"),
GATEWAY_ID((short)3, "gatewayId");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // PROCESS_ID
return PROCESS_ID;
case 2: // AIRAVATA_CRED_STORE_TOKEN
return AIRAVATA_CRED_STORE_TOKEN;
case 3: // GATEWAY_ID
return GATEWAY_ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.PROCESS_ID, new org.apache.thrift.meta_data.FieldMetaData("processId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.AIRAVATA_CRED_STORE_TOKEN, new org.apache.thrift.meta_data.FieldMetaData("airavataCredStoreToken", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.GATEWAY_ID, new org.apache.thrift.meta_data.FieldMetaData("gatewayId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(launchProcess_args.class, metaDataMap);
}
public launchProcess_args() {
}
public launchProcess_args(
java.lang.String processId,
java.lang.String airavataCredStoreToken,
java.lang.String gatewayId)
{
this();
this.processId = processId;
this.airavataCredStoreToken = airavataCredStoreToken;
this.gatewayId = gatewayId;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public launchProcess_args(launchProcess_args other) {
if (other.isSetProcessId()) {
this.processId = other.processId;
}
if (other.isSetAiravataCredStoreToken()) {
this.airavataCredStoreToken = other.airavataCredStoreToken;
}
if (other.isSetGatewayId()) {
this.gatewayId = other.gatewayId;
}
}
@Override
public launchProcess_args deepCopy() {
return new launchProcess_args(this);
}
@Override
public void clear() {
this.processId = null;
this.airavataCredStoreToken = null;
this.gatewayId = null;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getProcessId() {
return this.processId;
}
public launchProcess_args setProcessId(@org.apache.thrift.annotation.Nullable java.lang.String processId) {
this.processId = processId;
return this;
}
public void unsetProcessId() {
this.processId = null;
}
/** Returns true if field processId is set (has been assigned a value) and false otherwise */
public boolean isSetProcessId() {
return this.processId != null;
}
public void setProcessIdIsSet(boolean value) {
if (!value) {
this.processId = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getAiravataCredStoreToken() {
return this.airavataCredStoreToken;
}
public launchProcess_args setAiravataCredStoreToken(@org.apache.thrift.annotation.Nullable java.lang.String airavataCredStoreToken) {
this.airavataCredStoreToken = airavataCredStoreToken;
return this;
}
public void unsetAiravataCredStoreToken() {
this.airavataCredStoreToken = null;
}
/** Returns true if field airavataCredStoreToken is set (has been assigned a value) and false otherwise */
public boolean isSetAiravataCredStoreToken() {
return this.airavataCredStoreToken != null;
}
public void setAiravataCredStoreTokenIsSet(boolean value) {
if (!value) {
this.airavataCredStoreToken = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getGatewayId() {
return this.gatewayId;
}
public launchProcess_args setGatewayId(@org.apache.thrift.annotation.Nullable java.lang.String gatewayId) {
this.gatewayId = gatewayId;
return this;
}
public void unsetGatewayId() {
this.gatewayId = null;
}
/** Returns true if field gatewayId is set (has been assigned a value) and false otherwise */
public boolean isSetGatewayId() {
return this.gatewayId != null;
}
public void setGatewayIdIsSet(boolean value) {
if (!value) {
this.gatewayId = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case PROCESS_ID:
if (value == null) {
unsetProcessId();
} else {
setProcessId((java.lang.String)value);
}
break;
case AIRAVATA_CRED_STORE_TOKEN:
if (value == null) {
unsetAiravataCredStoreToken();
} else {
setAiravataCredStoreToken((java.lang.String)value);
}
break;
case GATEWAY_ID:
if (value == null) {
unsetGatewayId();
} else {
setGatewayId((java.lang.String)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case PROCESS_ID:
return getProcessId();
case AIRAVATA_CRED_STORE_TOKEN:
return getAiravataCredStoreToken();
case GATEWAY_ID:
return getGatewayId();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case PROCESS_ID:
return isSetProcessId();
case AIRAVATA_CRED_STORE_TOKEN:
return isSetAiravataCredStoreToken();
case GATEWAY_ID:
return isSetGatewayId();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof launchProcess_args)
return this.equals((launchProcess_args)that);
return false;
}
public boolean equals(launchProcess_args that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_processId = true && this.isSetProcessId();
boolean that_present_processId = true && that.isSetProcessId();
if (this_present_processId || that_present_processId) {
if (!(this_present_processId && that_present_processId))
return false;
if (!this.processId.equals(that.processId))
return false;
}
boolean this_present_airavataCredStoreToken = true && this.isSetAiravataCredStoreToken();
boolean that_present_airavataCredStoreToken = true && that.isSetAiravataCredStoreToken();
if (this_present_airavataCredStoreToken || that_present_airavataCredStoreToken) {
if (!(this_present_airavataCredStoreToken && that_present_airavataCredStoreToken))
return false;
if (!this.airavataCredStoreToken.equals(that.airavataCredStoreToken))
return false;
}
boolean this_present_gatewayId = true && this.isSetGatewayId();
boolean that_present_gatewayId = true && that.isSetGatewayId();
if (this_present_gatewayId || that_present_gatewayId) {
if (!(this_present_gatewayId && that_present_gatewayId))
return false;
if (!this.gatewayId.equals(that.gatewayId))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetProcessId()) ? 131071 : 524287);
if (isSetProcessId())
hashCode = hashCode * 8191 + processId.hashCode();
hashCode = hashCode * 8191 + ((isSetAiravataCredStoreToken()) ? 131071 : 524287);
if (isSetAiravataCredStoreToken())
hashCode = hashCode * 8191 + airavataCredStoreToken.hashCode();
hashCode = hashCode * 8191 + ((isSetGatewayId()) ? 131071 : 524287);
if (isSetGatewayId())
hashCode = hashCode * 8191 + gatewayId.hashCode();
return hashCode;
}
@Override
public int compareTo(launchProcess_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetProcessId(), other.isSetProcessId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetProcessId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.processId, other.processId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetAiravataCredStoreToken(), other.isSetAiravataCredStoreToken());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAiravataCredStoreToken()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.airavataCredStoreToken, other.airavataCredStoreToken);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetGatewayId(), other.isSetGatewayId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetGatewayId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.gatewayId, other.gatewayId);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("launchProcess_args(");
boolean first = true;
sb.append("processId:");
if (this.processId == null) {
sb.append("null");
} else {
sb.append(this.processId);
}
first = false;
if (!first) sb.append(", ");
sb.append("airavataCredStoreToken:");
if (this.airavataCredStoreToken == null) {
sb.append("null");
} else {
sb.append(this.airavataCredStoreToken);
}
first = false;
if (!first) sb.append(", ");
sb.append("gatewayId:");
if (this.gatewayId == null) {
sb.append("null");
} else {
sb.append(this.gatewayId);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (processId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'processId' was not present! Struct: " + toString());
}
if (airavataCredStoreToken == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'airavataCredStoreToken' was not present! Struct: " + toString());
}
if (gatewayId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'gatewayId' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class launchProcess_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchProcess_argsStandardScheme getScheme() {
return new launchProcess_argsStandardScheme();
}
}
private static class launchProcess_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme<launchProcess_args> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, launchProcess_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // PROCESS_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.processId = iprot.readString();
struct.setProcessIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // AIRAVATA_CRED_STORE_TOKEN
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.airavataCredStoreToken = iprot.readString();
struct.setAiravataCredStoreTokenIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // GATEWAY_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.gatewayId = iprot.readString();
struct.setGatewayIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, launchProcess_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.processId != null) {
oprot.writeFieldBegin(PROCESS_ID_FIELD_DESC);
oprot.writeString(struct.processId);
oprot.writeFieldEnd();
}
if (struct.airavataCredStoreToken != null) {
oprot.writeFieldBegin(AIRAVATA_CRED_STORE_TOKEN_FIELD_DESC);
oprot.writeString(struct.airavataCredStoreToken);
oprot.writeFieldEnd();
}
if (struct.gatewayId != null) {
oprot.writeFieldBegin(GATEWAY_ID_FIELD_DESC);
oprot.writeString(struct.gatewayId);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class launchProcess_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchProcess_argsTupleScheme getScheme() {
return new launchProcess_argsTupleScheme();
}
}
private static class launchProcess_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<launchProcess_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, launchProcess_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
oprot.writeString(struct.processId);
oprot.writeString(struct.airavataCredStoreToken);
oprot.writeString(struct.gatewayId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, launchProcess_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
struct.processId = iprot.readString();
struct.setProcessIdIsSet(true);
struct.airavataCredStoreToken = iprot.readString();
struct.setAiravataCredStoreTokenIsSet(true);
struct.gatewayId = iprot.readString();
struct.setGatewayIdIsSet(true);
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class launchProcess_result implements org.apache.thrift.TBase<launchProcess_result, launchProcess_result._Fields>, java.io.Serializable, Cloneable, Comparable<launchProcess_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("launchProcess_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new launchProcess_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new launchProcess_resultTupleSchemeFactory();
public boolean success; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(launchProcess_result.class, metaDataMap);
}
public launchProcess_result() {
}
public launchProcess_result(
boolean success)
{
this();
this.success = success;
setSuccessIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public launchProcess_result(launchProcess_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
}
@Override
public launchProcess_result deepCopy() {
return new launchProcess_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = false;
}
public boolean isSuccess() {
return this.success;
}
public launchProcess_result setSuccess(boolean success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((java.lang.Boolean)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return isSuccess();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof launchProcess_result)
return this.equals((launchProcess_result)that);
return false;
}
public boolean equals(launchProcess_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((success) ? 131071 : 524287);
return hashCode;
}
@Override
public int compareTo(launchProcess_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetSuccess(), other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("launchProcess_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class launchProcess_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchProcess_resultStandardScheme getScheme() {
return new launchProcess_resultStandardScheme();
}
}
private static class launchProcess_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme<launchProcess_result> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, launchProcess_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, launchProcess_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeBool(struct.success);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class launchProcess_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public launchProcess_resultTupleScheme getScheme() {
return new launchProcess_resultTupleScheme();
}
}
private static class launchProcess_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<launchProcess_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, launchProcess_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
oprot.writeBool(struct.success);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, launchProcess_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class validateExperiment_args implements org.apache.thrift.TBase<validateExperiment_args, validateExperiment_args._Fields>, java.io.Serializable, Cloneable, Comparable<validateExperiment_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("validateExperiment_args");
private static final org.apache.thrift.protocol.TField EXPERIMENT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("experimentId", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new validateExperiment_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new validateExperiment_argsTupleSchemeFactory();
public @org.apache.thrift.annotation.Nullable java.lang.String experimentId; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
EXPERIMENT_ID((short)1, "experimentId");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // EXPERIMENT_ID
return EXPERIMENT_ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.EXPERIMENT_ID, new org.apache.thrift.meta_data.FieldMetaData("experimentId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(validateExperiment_args.class, metaDataMap);
}
public validateExperiment_args() {
}
public validateExperiment_args(
java.lang.String experimentId)
{
this();
this.experimentId = experimentId;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public validateExperiment_args(validateExperiment_args other) {
if (other.isSetExperimentId()) {
this.experimentId = other.experimentId;
}
}
@Override
public validateExperiment_args deepCopy() {
return new validateExperiment_args(this);
}
@Override
public void clear() {
this.experimentId = null;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getExperimentId() {
return this.experimentId;
}
public validateExperiment_args setExperimentId(@org.apache.thrift.annotation.Nullable java.lang.String experimentId) {
this.experimentId = experimentId;
return this;
}
public void unsetExperimentId() {
this.experimentId = null;
}
/** Returns true if field experimentId is set (has been assigned a value) and false otherwise */
public boolean isSetExperimentId() {
return this.experimentId != null;
}
public void setExperimentIdIsSet(boolean value) {
if (!value) {
this.experimentId = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case EXPERIMENT_ID:
if (value == null) {
unsetExperimentId();
} else {
setExperimentId((java.lang.String)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case EXPERIMENT_ID:
return getExperimentId();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case EXPERIMENT_ID:
return isSetExperimentId();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof validateExperiment_args)
return this.equals((validateExperiment_args)that);
return false;
}
public boolean equals(validateExperiment_args that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_experimentId = true && this.isSetExperimentId();
boolean that_present_experimentId = true && that.isSetExperimentId();
if (this_present_experimentId || that_present_experimentId) {
if (!(this_present_experimentId && that_present_experimentId))
return false;
if (!this.experimentId.equals(that.experimentId))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetExperimentId()) ? 131071 : 524287);
if (isSetExperimentId())
hashCode = hashCode * 8191 + experimentId.hashCode();
return hashCode;
}
@Override
public int compareTo(validateExperiment_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetExperimentId(), other.isSetExperimentId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetExperimentId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.experimentId, other.experimentId);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("validateExperiment_args(");
boolean first = true;
sb.append("experimentId:");
if (this.experimentId == null) {
sb.append("null");
} else {
sb.append(this.experimentId);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (experimentId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'experimentId' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class validateExperiment_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateExperiment_argsStandardScheme getScheme() {
return new validateExperiment_argsStandardScheme();
}
}
private static class validateExperiment_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme<validateExperiment_args> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, validateExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // EXPERIMENT_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, validateExperiment_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.experimentId != null) {
oprot.writeFieldBegin(EXPERIMENT_ID_FIELD_DESC);
oprot.writeString(struct.experimentId);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class validateExperiment_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateExperiment_argsTupleScheme getScheme() {
return new validateExperiment_argsTupleScheme();
}
}
private static class validateExperiment_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<validateExperiment_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, validateExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
oprot.writeString(struct.experimentId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, validateExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class validateExperiment_result implements org.apache.thrift.TBase<validateExperiment_result, validateExperiment_result._Fields>, java.io.Serializable, Cloneable, Comparable<validateExperiment_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("validateExperiment_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
private static final org.apache.thrift.protocol.TField LVE_FIELD_DESC = new org.apache.thrift.protocol.TField("lve", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new validateExperiment_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new validateExperiment_resultTupleSchemeFactory();
public boolean success; // required
public @org.apache.thrift.annotation.Nullable org.apache.airavata.model.error.LaunchValidationException lve; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success"),
LVE((short)1, "lve");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
case 1: // LVE
return LVE;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
tmpMap.put(_Fields.LVE, new org.apache.thrift.meta_data.FieldMetaData("lve", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, org.apache.airavata.model.error.LaunchValidationException.class)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(validateExperiment_result.class, metaDataMap);
}
public validateExperiment_result() {
}
public validateExperiment_result(
boolean success,
org.apache.airavata.model.error.LaunchValidationException lve)
{
this();
this.success = success;
setSuccessIsSet(true);
this.lve = lve;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public validateExperiment_result(validateExperiment_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
if (other.isSetLve()) {
this.lve = new org.apache.airavata.model.error.LaunchValidationException(other.lve);
}
}
@Override
public validateExperiment_result deepCopy() {
return new validateExperiment_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = false;
this.lve = null;
}
public boolean isSuccess() {
return this.success;
}
public validateExperiment_result setSuccess(boolean success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
@org.apache.thrift.annotation.Nullable
public org.apache.airavata.model.error.LaunchValidationException getLve() {
return this.lve;
}
public validateExperiment_result setLve(@org.apache.thrift.annotation.Nullable org.apache.airavata.model.error.LaunchValidationException lve) {
this.lve = lve;
return this;
}
public void unsetLve() {
this.lve = null;
}
/** Returns true if field lve is set (has been assigned a value) and false otherwise */
public boolean isSetLve() {
return this.lve != null;
}
public void setLveIsSet(boolean value) {
if (!value) {
this.lve = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((java.lang.Boolean)value);
}
break;
case LVE:
if (value == null) {
unsetLve();
} else {
setLve((org.apache.airavata.model.error.LaunchValidationException)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return isSuccess();
case LVE:
return getLve();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
case LVE:
return isSetLve();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof validateExperiment_result)
return this.equals((validateExperiment_result)that);
return false;
}
public boolean equals(validateExperiment_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
boolean this_present_lve = true && this.isSetLve();
boolean that_present_lve = true && that.isSetLve();
if (this_present_lve || that_present_lve) {
if (!(this_present_lve && that_present_lve))
return false;
if (!this.lve.equals(that.lve))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((success) ? 131071 : 524287);
hashCode = hashCode * 8191 + ((isSetLve()) ? 131071 : 524287);
if (isSetLve())
hashCode = hashCode * 8191 + lve.hashCode();
return hashCode;
}
@Override
public int compareTo(validateExperiment_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetSuccess(), other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetLve(), other.isSetLve());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetLve()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.lve, other.lve);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("validateExperiment_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
if (!first) sb.append(", ");
sb.append("lve:");
if (this.lve == null) {
sb.append("null");
} else {
sb.append(this.lve);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class validateExperiment_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateExperiment_resultStandardScheme getScheme() {
return new validateExperiment_resultStandardScheme();
}
}
private static class validateExperiment_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme<validateExperiment_result> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, validateExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 1: // LVE
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.lve = new org.apache.airavata.model.error.LaunchValidationException();
struct.lve.read(iprot);
struct.setLveIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, validateExperiment_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeBool(struct.success);
oprot.writeFieldEnd();
}
if (struct.lve != null) {
oprot.writeFieldBegin(LVE_FIELD_DESC);
struct.lve.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class validateExperiment_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateExperiment_resultTupleScheme getScheme() {
return new validateExperiment_resultTupleScheme();
}
}
private static class validateExperiment_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<validateExperiment_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, validateExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
if (struct.isSetLve()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetSuccess()) {
oprot.writeBool(struct.success);
}
if (struct.isSetLve()) {
struct.lve.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, validateExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
}
if (incoming.get(1)) {
struct.lve = new org.apache.airavata.model.error.LaunchValidationException();
struct.lve.read(iprot);
struct.setLveIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class validateProcess_args implements org.apache.thrift.TBase<validateProcess_args, validateProcess_args._Fields>, java.io.Serializable, Cloneable, Comparable<validateProcess_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("validateProcess_args");
private static final org.apache.thrift.protocol.TField EXPERIMENT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("experimentId", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField PROCESSES_FIELD_DESC = new org.apache.thrift.protocol.TField("processes", org.apache.thrift.protocol.TType.LIST, (short)2);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new validateProcess_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new validateProcess_argsTupleSchemeFactory();
public @org.apache.thrift.annotation.Nullable java.lang.String experimentId; // required
public @org.apache.thrift.annotation.Nullable java.util.List<org.apache.airavata.model.process.ProcessModel> processes; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
EXPERIMENT_ID((short)1, "experimentId"),
PROCESSES((short)2, "processes");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // EXPERIMENT_ID
return EXPERIMENT_ID;
case 2: // PROCESSES
return PROCESSES;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.EXPERIMENT_ID, new org.apache.thrift.meta_data.FieldMetaData("experimentId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.PROCESSES, new org.apache.thrift.meta_data.FieldMetaData("processes", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, org.apache.airavata.model.process.ProcessModel.class))));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(validateProcess_args.class, metaDataMap);
}
public validateProcess_args() {
}
public validateProcess_args(
java.lang.String experimentId,
java.util.List<org.apache.airavata.model.process.ProcessModel> processes)
{
this();
this.experimentId = experimentId;
this.processes = processes;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public validateProcess_args(validateProcess_args other) {
if (other.isSetExperimentId()) {
this.experimentId = other.experimentId;
}
if (other.isSetProcesses()) {
java.util.List<org.apache.airavata.model.process.ProcessModel> __this__processes = new java.util.ArrayList<org.apache.airavata.model.process.ProcessModel>(other.processes.size());
for (org.apache.airavata.model.process.ProcessModel other_element : other.processes) {
__this__processes.add(new org.apache.airavata.model.process.ProcessModel(other_element));
}
this.processes = __this__processes;
}
}
@Override
public validateProcess_args deepCopy() {
return new validateProcess_args(this);
}
@Override
public void clear() {
this.experimentId = null;
this.processes = null;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getExperimentId() {
return this.experimentId;
}
public validateProcess_args setExperimentId(@org.apache.thrift.annotation.Nullable java.lang.String experimentId) {
this.experimentId = experimentId;
return this;
}
public void unsetExperimentId() {
this.experimentId = null;
}
/** Returns true if field experimentId is set (has been assigned a value) and false otherwise */
public boolean isSetExperimentId() {
return this.experimentId != null;
}
public void setExperimentIdIsSet(boolean value) {
if (!value) {
this.experimentId = null;
}
}
public int getProcessesSize() {
return (this.processes == null) ? 0 : this.processes.size();
}
@org.apache.thrift.annotation.Nullable
public java.util.Iterator<org.apache.airavata.model.process.ProcessModel> getProcessesIterator() {
return (this.processes == null) ? null : this.processes.iterator();
}
public void addToProcesses(org.apache.airavata.model.process.ProcessModel elem) {
if (this.processes == null) {
this.processes = new java.util.ArrayList<org.apache.airavata.model.process.ProcessModel>();
}
this.processes.add(elem);
}
@org.apache.thrift.annotation.Nullable
public java.util.List<org.apache.airavata.model.process.ProcessModel> getProcesses() {
return this.processes;
}
public validateProcess_args setProcesses(@org.apache.thrift.annotation.Nullable java.util.List<org.apache.airavata.model.process.ProcessModel> processes) {
this.processes = processes;
return this;
}
public void unsetProcesses() {
this.processes = null;
}
/** Returns true if field processes is set (has been assigned a value) and false otherwise */
public boolean isSetProcesses() {
return this.processes != null;
}
public void setProcessesIsSet(boolean value) {
if (!value) {
this.processes = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case EXPERIMENT_ID:
if (value == null) {
unsetExperimentId();
} else {
setExperimentId((java.lang.String)value);
}
break;
case PROCESSES:
if (value == null) {
unsetProcesses();
} else {
setProcesses((java.util.List<org.apache.airavata.model.process.ProcessModel>)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case EXPERIMENT_ID:
return getExperimentId();
case PROCESSES:
return getProcesses();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case EXPERIMENT_ID:
return isSetExperimentId();
case PROCESSES:
return isSetProcesses();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof validateProcess_args)
return this.equals((validateProcess_args)that);
return false;
}
public boolean equals(validateProcess_args that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_experimentId = true && this.isSetExperimentId();
boolean that_present_experimentId = true && that.isSetExperimentId();
if (this_present_experimentId || that_present_experimentId) {
if (!(this_present_experimentId && that_present_experimentId))
return false;
if (!this.experimentId.equals(that.experimentId))
return false;
}
boolean this_present_processes = true && this.isSetProcesses();
boolean that_present_processes = true && that.isSetProcesses();
if (this_present_processes || that_present_processes) {
if (!(this_present_processes && that_present_processes))
return false;
if (!this.processes.equals(that.processes))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetExperimentId()) ? 131071 : 524287);
if (isSetExperimentId())
hashCode = hashCode * 8191 + experimentId.hashCode();
hashCode = hashCode * 8191 + ((isSetProcesses()) ? 131071 : 524287);
if (isSetProcesses())
hashCode = hashCode * 8191 + processes.hashCode();
return hashCode;
}
@Override
public int compareTo(validateProcess_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetExperimentId(), other.isSetExperimentId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetExperimentId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.experimentId, other.experimentId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetProcesses(), other.isSetProcesses());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetProcesses()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.processes, other.processes);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("validateProcess_args(");
boolean first = true;
sb.append("experimentId:");
if (this.experimentId == null) {
sb.append("null");
} else {
sb.append(this.experimentId);
}
first = false;
if (!first) sb.append(", ");
sb.append("processes:");
if (this.processes == null) {
sb.append("null");
} else {
sb.append(this.processes);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (experimentId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'experimentId' was not present! Struct: " + toString());
}
if (processes == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'processes' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class validateProcess_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateProcess_argsStandardScheme getScheme() {
return new validateProcess_argsStandardScheme();
}
}
private static class validateProcess_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme<validateProcess_args> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, validateProcess_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // EXPERIMENT_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // PROCESSES
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();
struct.processes = new java.util.ArrayList<org.apache.airavata.model.process.ProcessModel>(_list0.size);
@org.apache.thrift.annotation.Nullable org.apache.airavata.model.process.ProcessModel _elem1;
for (int _i2 = 0; _i2 < _list0.size; ++_i2)
{
_elem1 = new org.apache.airavata.model.process.ProcessModel();
_elem1.read(iprot);
struct.processes.add(_elem1);
}
iprot.readListEnd();
}
struct.setProcessesIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, validateProcess_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.experimentId != null) {
oprot.writeFieldBegin(EXPERIMENT_ID_FIELD_DESC);
oprot.writeString(struct.experimentId);
oprot.writeFieldEnd();
}
if (struct.processes != null) {
oprot.writeFieldBegin(PROCESSES_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.processes.size()));
for (org.apache.airavata.model.process.ProcessModel _iter3 : struct.processes)
{
_iter3.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class validateProcess_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateProcess_argsTupleScheme getScheme() {
return new validateProcess_argsTupleScheme();
}
}
private static class validateProcess_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<validateProcess_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, validateProcess_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
oprot.writeString(struct.experimentId);
{
oprot.writeI32(struct.processes.size());
for (org.apache.airavata.model.process.ProcessModel _iter4 : struct.processes)
{
_iter4.write(oprot);
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, validateProcess_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
{
org.apache.thrift.protocol.TList _list5 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRUCT);
struct.processes = new java.util.ArrayList<org.apache.airavata.model.process.ProcessModel>(_list5.size);
@org.apache.thrift.annotation.Nullable org.apache.airavata.model.process.ProcessModel _elem6;
for (int _i7 = 0; _i7 < _list5.size; ++_i7)
{
_elem6 = new org.apache.airavata.model.process.ProcessModel();
_elem6.read(iprot);
struct.processes.add(_elem6);
}
}
struct.setProcessesIsSet(true);
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class validateProcess_result implements org.apache.thrift.TBase<validateProcess_result, validateProcess_result._Fields>, java.io.Serializable, Cloneable, Comparable<validateProcess_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("validateProcess_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
private static final org.apache.thrift.protocol.TField LVE_FIELD_DESC = new org.apache.thrift.protocol.TField("lve", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new validateProcess_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new validateProcess_resultTupleSchemeFactory();
public boolean success; // required
public @org.apache.thrift.annotation.Nullable org.apache.airavata.model.error.LaunchValidationException lve; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success"),
LVE((short)1, "lve");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
case 1: // LVE
return LVE;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
tmpMap.put(_Fields.LVE, new org.apache.thrift.meta_data.FieldMetaData("lve", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, org.apache.airavata.model.error.LaunchValidationException.class)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(validateProcess_result.class, metaDataMap);
}
public validateProcess_result() {
}
public validateProcess_result(
boolean success,
org.apache.airavata.model.error.LaunchValidationException lve)
{
this();
this.success = success;
setSuccessIsSet(true);
this.lve = lve;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public validateProcess_result(validateProcess_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
if (other.isSetLve()) {
this.lve = new org.apache.airavata.model.error.LaunchValidationException(other.lve);
}
}
@Override
public validateProcess_result deepCopy() {
return new validateProcess_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = false;
this.lve = null;
}
public boolean isSuccess() {
return this.success;
}
public validateProcess_result setSuccess(boolean success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
@org.apache.thrift.annotation.Nullable
public org.apache.airavata.model.error.LaunchValidationException getLve() {
return this.lve;
}
public validateProcess_result setLve(@org.apache.thrift.annotation.Nullable org.apache.airavata.model.error.LaunchValidationException lve) {
this.lve = lve;
return this;
}
public void unsetLve() {
this.lve = null;
}
/** Returns true if field lve is set (has been assigned a value) and false otherwise */
public boolean isSetLve() {
return this.lve != null;
}
public void setLveIsSet(boolean value) {
if (!value) {
this.lve = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((java.lang.Boolean)value);
}
break;
case LVE:
if (value == null) {
unsetLve();
} else {
setLve((org.apache.airavata.model.error.LaunchValidationException)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return isSuccess();
case LVE:
return getLve();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
case LVE:
return isSetLve();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof validateProcess_result)
return this.equals((validateProcess_result)that);
return false;
}
public boolean equals(validateProcess_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
boolean this_present_lve = true && this.isSetLve();
boolean that_present_lve = true && that.isSetLve();
if (this_present_lve || that_present_lve) {
if (!(this_present_lve && that_present_lve))
return false;
if (!this.lve.equals(that.lve))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((success) ? 131071 : 524287);
hashCode = hashCode * 8191 + ((isSetLve()) ? 131071 : 524287);
if (isSetLve())
hashCode = hashCode * 8191 + lve.hashCode();
return hashCode;
}
@Override
public int compareTo(validateProcess_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetSuccess(), other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetLve(), other.isSetLve());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetLve()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.lve, other.lve);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("validateProcess_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
if (!first) sb.append(", ");
sb.append("lve:");
if (this.lve == null) {
sb.append("null");
} else {
sb.append(this.lve);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class validateProcess_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateProcess_resultStandardScheme getScheme() {
return new validateProcess_resultStandardScheme();
}
}
private static class validateProcess_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme<validateProcess_result> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, validateProcess_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 1: // LVE
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.lve = new org.apache.airavata.model.error.LaunchValidationException();
struct.lve.read(iprot);
struct.setLveIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, validateProcess_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeBool(struct.success);
oprot.writeFieldEnd();
}
if (struct.lve != null) {
oprot.writeFieldBegin(LVE_FIELD_DESC);
struct.lve.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class validateProcess_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public validateProcess_resultTupleScheme getScheme() {
return new validateProcess_resultTupleScheme();
}
}
private static class validateProcess_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<validateProcess_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, validateProcess_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
if (struct.isSetLve()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetSuccess()) {
oprot.writeBool(struct.success);
}
if (struct.isSetLve()) {
struct.lve.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, validateProcess_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
}
if (incoming.get(1)) {
struct.lve = new org.apache.airavata.model.error.LaunchValidationException();
struct.lve.read(iprot);
struct.setLveIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class terminateExperiment_args implements org.apache.thrift.TBase<terminateExperiment_args, terminateExperiment_args._Fields>, java.io.Serializable, Cloneable, Comparable<terminateExperiment_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("terminateExperiment_args");
private static final org.apache.thrift.protocol.TField EXPERIMENT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("experimentId", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField GATEWAY_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("gatewayId", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new terminateExperiment_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new terminateExperiment_argsTupleSchemeFactory();
public @org.apache.thrift.annotation.Nullable java.lang.String experimentId; // required
public @org.apache.thrift.annotation.Nullable java.lang.String gatewayId; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
EXPERIMENT_ID((short)1, "experimentId"),
GATEWAY_ID((short)2, "gatewayId");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // EXPERIMENT_ID
return EXPERIMENT_ID;
case 2: // GATEWAY_ID
return GATEWAY_ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.EXPERIMENT_ID, new org.apache.thrift.meta_data.FieldMetaData("experimentId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.GATEWAY_ID, new org.apache.thrift.meta_data.FieldMetaData("gatewayId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(terminateExperiment_args.class, metaDataMap);
}
public terminateExperiment_args() {
}
public terminateExperiment_args(
java.lang.String experimentId,
java.lang.String gatewayId)
{
this();
this.experimentId = experimentId;
this.gatewayId = gatewayId;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public terminateExperiment_args(terminateExperiment_args other) {
if (other.isSetExperimentId()) {
this.experimentId = other.experimentId;
}
if (other.isSetGatewayId()) {
this.gatewayId = other.gatewayId;
}
}
@Override
public terminateExperiment_args deepCopy() {
return new terminateExperiment_args(this);
}
@Override
public void clear() {
this.experimentId = null;
this.gatewayId = null;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getExperimentId() {
return this.experimentId;
}
public terminateExperiment_args setExperimentId(@org.apache.thrift.annotation.Nullable java.lang.String experimentId) {
this.experimentId = experimentId;
return this;
}
public void unsetExperimentId() {
this.experimentId = null;
}
/** Returns true if field experimentId is set (has been assigned a value) and false otherwise */
public boolean isSetExperimentId() {
return this.experimentId != null;
}
public void setExperimentIdIsSet(boolean value) {
if (!value) {
this.experimentId = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getGatewayId() {
return this.gatewayId;
}
public terminateExperiment_args setGatewayId(@org.apache.thrift.annotation.Nullable java.lang.String gatewayId) {
this.gatewayId = gatewayId;
return this;
}
public void unsetGatewayId() {
this.gatewayId = null;
}
/** Returns true if field gatewayId is set (has been assigned a value) and false otherwise */
public boolean isSetGatewayId() {
return this.gatewayId != null;
}
public void setGatewayIdIsSet(boolean value) {
if (!value) {
this.gatewayId = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case EXPERIMENT_ID:
if (value == null) {
unsetExperimentId();
} else {
setExperimentId((java.lang.String)value);
}
break;
case GATEWAY_ID:
if (value == null) {
unsetGatewayId();
} else {
setGatewayId((java.lang.String)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case EXPERIMENT_ID:
return getExperimentId();
case GATEWAY_ID:
return getGatewayId();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case EXPERIMENT_ID:
return isSetExperimentId();
case GATEWAY_ID:
return isSetGatewayId();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof terminateExperiment_args)
return this.equals((terminateExperiment_args)that);
return false;
}
public boolean equals(terminateExperiment_args that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_experimentId = true && this.isSetExperimentId();
boolean that_present_experimentId = true && that.isSetExperimentId();
if (this_present_experimentId || that_present_experimentId) {
if (!(this_present_experimentId && that_present_experimentId))
return false;
if (!this.experimentId.equals(that.experimentId))
return false;
}
boolean this_present_gatewayId = true && this.isSetGatewayId();
boolean that_present_gatewayId = true && that.isSetGatewayId();
if (this_present_gatewayId || that_present_gatewayId) {
if (!(this_present_gatewayId && that_present_gatewayId))
return false;
if (!this.gatewayId.equals(that.gatewayId))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetExperimentId()) ? 131071 : 524287);
if (isSetExperimentId())
hashCode = hashCode * 8191 + experimentId.hashCode();
hashCode = hashCode * 8191 + ((isSetGatewayId()) ? 131071 : 524287);
if (isSetGatewayId())
hashCode = hashCode * 8191 + gatewayId.hashCode();
return hashCode;
}
@Override
public int compareTo(terminateExperiment_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetExperimentId(), other.isSetExperimentId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetExperimentId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.experimentId, other.experimentId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetGatewayId(), other.isSetGatewayId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetGatewayId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.gatewayId, other.gatewayId);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("terminateExperiment_args(");
boolean first = true;
sb.append("experimentId:");
if (this.experimentId == null) {
sb.append("null");
} else {
sb.append(this.experimentId);
}
first = false;
if (!first) sb.append(", ");
sb.append("gatewayId:");
if (this.gatewayId == null) {
sb.append("null");
} else {
sb.append(this.gatewayId);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (experimentId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'experimentId' was not present! Struct: " + toString());
}
if (gatewayId == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'gatewayId' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class terminateExperiment_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public terminateExperiment_argsStandardScheme getScheme() {
return new terminateExperiment_argsStandardScheme();
}
}
private static class terminateExperiment_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme<terminateExperiment_args> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, terminateExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // EXPERIMENT_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // GATEWAY_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.gatewayId = iprot.readString();
struct.setGatewayIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, terminateExperiment_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.experimentId != null) {
oprot.writeFieldBegin(EXPERIMENT_ID_FIELD_DESC);
oprot.writeString(struct.experimentId);
oprot.writeFieldEnd();
}
if (struct.gatewayId != null) {
oprot.writeFieldBegin(GATEWAY_ID_FIELD_DESC);
oprot.writeString(struct.gatewayId);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class terminateExperiment_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public terminateExperiment_argsTupleScheme getScheme() {
return new terminateExperiment_argsTupleScheme();
}
}
private static class terminateExperiment_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<terminateExperiment_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, terminateExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
oprot.writeString(struct.experimentId);
oprot.writeString(struct.gatewayId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, terminateExperiment_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
struct.experimentId = iprot.readString();
struct.setExperimentIdIsSet(true);
struct.gatewayId = iprot.readString();
struct.setGatewayIdIsSet(true);
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public static class terminateExperiment_result implements org.apache.thrift.TBase<terminateExperiment_result, terminateExperiment_result._Fields>, java.io.Serializable, Cloneable, Comparable<terminateExperiment_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("terminateExperiment_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new terminateExperiment_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new terminateExperiment_resultTupleSchemeFactory();
public boolean success; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(terminateExperiment_result.class, metaDataMap);
}
public terminateExperiment_result() {
}
public terminateExperiment_result(
boolean success)
{
this();
this.success = success;
setSuccessIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public terminateExperiment_result(terminateExperiment_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
}
@Override
public terminateExperiment_result deepCopy() {
return new terminateExperiment_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = false;
}
public boolean isSuccess() {
return this.success;
}
public terminateExperiment_result setSuccess(boolean success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((java.lang.Boolean)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return isSuccess();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof terminateExperiment_result)
return this.equals((terminateExperiment_result)that);
return false;
}
public boolean equals(terminateExperiment_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((success) ? 131071 : 524287);
return hashCode;
}
@Override
public int compareTo(terminateExperiment_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetSuccess(), other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("terminateExperiment_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class terminateExperiment_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public terminateExperiment_resultStandardScheme getScheme() {
return new terminateExperiment_resultStandardScheme();
}
}
private static class terminateExperiment_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme<terminateExperiment_result> {
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot, terminateExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
@Override
public void write(org.apache.thrift.protocol.TProtocol oprot, terminateExperiment_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeBool(struct.success);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class terminateExperiment_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
@Override
public terminateExperiment_resultTupleScheme getScheme() {
return new terminateExperiment_resultTupleScheme();
}
}
private static class terminateExperiment_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<terminateExperiment_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, terminateExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
oprot.writeBool(struct.success);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, terminateExperiment_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
}
| 1,204 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator/sample/OrchestratorClientSample.java | /**
*
* 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.airavata.orchestrator.sample;
//import org.apache.airavata.client.AiravataAPIFactory;
//import org.apache.airavata.client.api.AiravataAPI;
//import org.apache.airavata.client.api.exception.AiravataAPIInvocationException;
//import org.apache.airavata.client.tools.DocumentCreator;
import org.apache.airavata.model.application.io.DataType;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.util.ExperimentModelUtil;
import org.apache.airavata.orchestrator.cpi.OrchestratorService;
import org.apache.thrift.TException;
import java.util.ArrayList;
import java.util.List;
public class OrchestratorClientSample {
// private static DocumentCreator documentCreator;
private static OrchestratorService.Client orchestratorClient;
// private static Registry registry;
private static int NUM_CONCURRENT_REQUESTS = 1;
private static final String DEFAULT_USER = "default.registry.user";
private static final String DEFAULT_USER_PASSWORD = "default.registry.password";
private static final String DEFAULT_GATEWAY = "default.registry.gateway";
private static String sysUser;
private static String sysUserPwd;
private static String gateway;
/*
public static void main(String[] args) {
try {
AiravataUtils.setExecutionAsClient();
sysUser = ClientSettings.getSetting(DEFAULT_USER);
sysUserPwd = ClientSettings.getSetting(DEFAULT_USER_PASSWORD);
gateway = ClientSettings.getSetting(DEFAULT_GATEWAY);
orchestratorClient = OrchestratorClientFactory.createOrchestratorClient("localhost", 8940);
registry = RegistryFactory.getRegistry(gateway, sysUser, sysUserPwd);
documentCreator = new DocumentCreator(getAiravataAPI());
documentCreator.createLocalHostDocs();
documentCreator.createGramDocs();
documentCreator.createPBSDocsForOGCE();
storeExperimentDetail();
} catch (ApplicationSettingsException e) {
e.printStackTrace();
} catch (RegistryException e) {
e.printStackTrace();
}
}
private static AiravataAPI getAiravataAPI() {
AiravataAPI airavataAPI = null;
try {
airavataAPI = AiravataAPIFactory.getAPI(gateway, sysUser);
} catch (AiravataAPIInvocationException e) {
e.printStackTrace();
}
return airavataAPI;
}
*/
public static void storeExperimentDetail() {
for (int i = 0; i < NUM_CONCURRENT_REQUESTS; i++) {
Thread thread = new Thread() {
public void run() {
List<InputDataObjectType> exInputs = new ArrayList<InputDataObjectType>();
InputDataObjectType input = new InputDataObjectType();
input.setName("echo_input");
input.setType(DataType.STRING);
input.setValue("echo_output=Hello World");
exInputs.add(input);
List<OutputDataObjectType> exOut = new ArrayList<OutputDataObjectType>();
OutputDataObjectType output = new OutputDataObjectType();
output.setName("echo_output");
output.setType(DataType.STRING);
output.setValue("");
exOut.add(output);
ExperimentModel simpleExperiment = ExperimentModelUtil.createSimpleExperiment(DEFAULT_GATEWAY,"default", "admin", "echoExperiment", "SimpleEcho2", "SimpleEcho2", exInputs);
simpleExperiment.setExperimentOutputs(exOut);
ComputationalResourceSchedulingModel scheduling = ExperimentModelUtil.createComputationResourceScheduling("trestles.sdsc.edu", 1, 1, 1, "normal", 0, 0);
scheduling.setResourceHostId("gsissh-trestles");
UserConfigurationDataModel userConfigurationDataModel = new UserConfigurationDataModel();
userConfigurationDataModel.setComputationalResourceScheduling(scheduling);
simpleExperiment.setUserConfigurationData(userConfigurationDataModel);
String expId = null;
try {
// expId = (String) registry.add(ParentDataType.EXPERIMENT, simpleExperiment);
} catch (Exception e) {
e.printStackTrace();
}
try {
orchestratorClient.launchExperiment(expId, "airavataToken");
} catch (TException e) {
throw new RuntimeException("Error while storing experiment details", e);
}
}
};
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 1,205 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-client/src/main/java/org/apache/airavata/orchestrator/client/OrchestratorClientFactory.java | /**
*
* 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.airavata.orchestrator.client;
import org.apache.airavata.model.error.AiravataClientException;
import org.apache.airavata.orchestrator.cpi.OrchestratorService;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class OrchestratorClientFactory {
public static OrchestratorService.Client createOrchestratorClient(String serverHost, int serverPort) throws AiravataClientException {
try {
TTransport transport = new TSocket(serverHost, serverPort);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
return new OrchestratorService.Client(protocol);
} catch (TTransportException e) {
throw new AiravataClientException();
}
}
}
| 1,206 |
0 | Create_ds/cordova-plugin-file/tests/src | Create_ds/cordova-plugin-file/tests/src/android/TestContentProvider.java | /*
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.cordova.file.test;
import android.content.ContentProvider;
import android.net.Uri;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.ParcelFileDescriptor;
import org.apache.cordova.CordovaResourceApi;
import java.io.IOException;
import java.util.HashMap;
public class TestContentProvider extends ContentProvider {
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String fileName = uri.getQueryParameter("realPath");
if (fileName == null) {
fileName = uri.getPath();
}
if (fileName == null || fileName.length() < 1) {
throw new FileNotFoundException();
}
CordovaResourceApi resourceApi = new CordovaResourceApi(getContext(), null);
try {
File f = File.createTempFile("test-content-provider", ".tmp");
resourceApi.copyResource(Uri.parse("file:///android_asset" + fileName), Uri.fromFile(f));
return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
} catch (FileNotFoundException e) {
throw e;
} catch (IOException e) {
e.printStackTrace();
throw new FileNotFoundException("IO error: " + e.toString());
}
}
@Override
public boolean onCreate() {
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
throw new UnsupportedOperationException();
}
@Override
public String getType(Uri uri) {
return "text/html";
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
}
| 1,207 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/LocalFilesystem.java | /*
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.cordova.file;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
public class LocalFilesystem extends Filesystem {
private final Context context;
public LocalFilesystem(String name, Context context, CordovaResourceApi resourceApi, File fsRoot, CordovaPreferences preferences) {
super(Uri.fromFile(fsRoot).buildUpon().appendEncodedPath("").build(), name, resourceApi, preferences);
this.context = context;
}
public String filesystemPathForFullPath(String fullPath) {
return new File(rootUri.getPath(), fullPath).toString();
}
@Override
public String filesystemPathForURL(LocalFilesystemURL url) {
return filesystemPathForFullPath(url.path);
}
private String fullPathForFilesystemPath(String absolutePath) {
if (absolutePath != null && absolutePath.startsWith(rootUri.getPath())) {
return absolutePath.substring(rootUri.getPath().length() - 1);
}
return null;
}
@Override
public Uri toNativeUri(LocalFilesystemURL inputURL) {
return nativeUriForFullPath(inputURL.path);
}
@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
if (!"file".equals(inputURL.getScheme())) {
return null;
}
File f = new File(inputURL.getPath());
// Removes and duplicate /s (e.g. file:///a//b/c)
Uri resolvedUri = Uri.fromFile(f);
String rootUriNoTrailingSlash = rootUri.getEncodedPath();
rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
return null;
}
String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
// Strip leading slash
if (!subPath.isEmpty()) {
subPath = subPath.substring(1);
}
Uri.Builder b = createLocalUriBuilder();
if (!subPath.isEmpty()) {
b.appendEncodedPath(subPath);
}
if (f.isDirectory()) {
// Add trailing / for directories.
b.appendEncodedPath("");
}
return LocalFilesystemURL.parse(b.build());
}
@Override
public LocalFilesystemURL URLforFilesystemPath(String path) {
return localUrlforFullPath(fullPathForFilesystemPath(path));
}
@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
boolean create = false;
boolean exclusive = false;
if (options != null) {
create = options.optBoolean("create");
if (create) {
exclusive = options.optBoolean("exclusive");
}
}
// Check for a ":" character in the file to line up with BB and iOS
if (path.contains(":")) {
throw new EncodingException("This path has an invalid \":\" in it.");
}
LocalFilesystemURL requestedURL;
// Check whether the supplied path is absolute or relative
if (directory && !path.endsWith("/")) {
path += "/";
}
if (path.startsWith("/")) {
requestedURL = localUrlforFullPath(normalizePath(path));
} else {
requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
}
File fp = new File(this.filesystemPathForURL(requestedURL));
if (create) {
if (exclusive && fp.exists()) {
throw new FileExistsException("create/exclusive fails");
}
if (directory) {
fp.mkdir();
} else {
fp.createNewFile();
}
if (!fp.exists()) {
throw new FileExistsException("create fails");
}
}
else {
if (!fp.exists()) {
throw new FileNotFoundException("path does not exist");
}
if (directory) {
if (fp.isFile()) {
throw new TypeMismatchException("path doesn't exist or is file");
}
} else {
if (fp.isDirectory()) {
throw new TypeMismatchException("path doesn't exist or is directory");
}
}
}
// Return the directory
return makeEntryForURL(requestedURL);
}
@Override
public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException {
File fp = new File(filesystemPathForURL(inputURL));
// You can't delete a directory that is not empty
if (fp.isDirectory() && fp.list().length > 0) {
throw new InvalidModificationException("You can't delete a directory that is not empty.");
}
return fp.delete();
}
@Override
public boolean exists(LocalFilesystemURL inputURL) {
File fp = new File(filesystemPathForURL(inputURL));
return fp.exists();
}
@Override
public long getFreeSpaceInBytes() {
return DirectoryManager.getFreeSpaceInBytes(rootUri.getPath());
}
@Override
public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException {
File directory = new File(filesystemPathForURL(inputURL));
return removeDirRecursively(directory);
}
protected boolean removeDirRecursively(File directory) throws FileExistsException {
if (directory.isDirectory()) {
for (File file : directory.listFiles()) {
removeDirRecursively(file);
}
}
if (!directory.delete()) {
throw new FileExistsException("could not delete: " + directory.getName());
} else {
return true;
}
}
@Override
public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
File fp = new File(filesystemPathForURL(inputURL));
if (!fp.exists()) {
// The directory we are listing doesn't exist so we should fail.
throw new FileNotFoundException();
}
File[] files = fp.listFiles();
if (files == null) {
// inputURL is a directory
return null;
}
LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
for (int i = 0; i < files.length; i++) {
entries[i] = URLforFilesystemPath(files[i].getPath());
}
return entries;
}
@Override
public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
File file = new File(filesystemPathForURL(inputURL));
if (!file.exists()) {
throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
}
JSONObject metadata = new JSONObject();
try {
// Ensure that directories report a size of 0
metadata.put("size", file.isDirectory() ? 0 : file.length());
metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file)));
metadata.put("name", file.getName());
metadata.put("fullPath", inputURL.path);
metadata.put("lastModifiedDate", file.lastModified());
} catch (JSONException e) {
return null;
}
return metadata;
}
private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move) throws IOException, InvalidModificationException, NoModificationAllowedException {
if (move) {
String realSrcPath = srcFs.filesystemPathForURL(srcURL);
if (realSrcPath != null) {
File srcFile = new File(realSrcPath);
if (srcFile.renameTo(destFile)) {
return;
}
// Trying to rename the file failed. Possibly because we moved across file system on the device.
}
}
CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL));
resourceApi.copyResource(offr, new FileOutputStream(destFile));
if (move) {
srcFs.removeFileAtLocalURL(srcURL);
}
}
private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException {
if (move) {
String realSrcPath = srcFs.filesystemPathForURL(srcURL);
if (realSrcPath != null) {
File srcDir = new File(realSrcPath);
// If the destination directory already exists and is empty then delete it. This is according to spec.
if (dstDir.exists()) {
if (dstDir.list().length > 0) {
throw new InvalidModificationException("directory is not empty");
}
dstDir.delete();
}
// Try to rename the directory
if (srcDir.renameTo(dstDir)) {
return;
}
// Trying to rename the file failed. Possibly because we moved across file system on the device.
}
}
if (dstDir.exists()) {
if (dstDir.list().length > 0) {
throw new InvalidModificationException("directory is not empty");
}
} else {
if (!dstDir.mkdir()) {
// If we can't create the directory then fail
throw new NoModificationAllowedException("Couldn't create the destination directory");
}
}
LocalFilesystemURL[] children = srcFs.listChildren(srcURL);
for (LocalFilesystemURL childLocalUrl : children) {
File target = new File(dstDir, new File(childLocalUrl.path).getName());
if (childLocalUrl.isDirectory) {
copyDirectory(srcFs, childLocalUrl, target, false);
} else {
copyFile(srcFs, childLocalUrl, target, false);
}
}
if (move) {
srcFs.recursiveRemoveFileAtLocalURL(srcURL);
}
}
@Override
public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
// Check to see if the destination directory exists
String newParent = this.filesystemPathForURL(destURL);
File destinationDir = new File(newParent);
if (!destinationDir.exists()) {
// The destination does not exist so we should fail.
throw new FileNotFoundException("The source does not exist");
}
// Figure out where we should be copying to
final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
Uri dstNativeUri = toNativeUri(destinationURL);
Uri srcNativeUri = srcFs.toNativeUri(srcURL);
// Check to see if source and destination are the same file
if (dstNativeUri.equals(srcNativeUri)) {
throw new InvalidModificationException("Can't copy onto itself");
}
if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
throw new InvalidModificationException("Source URL is read-only (cannot move)");
}
File destFile = new File(dstNativeUri.getPath());
if (destFile.exists()) {
if (!srcURL.isDirectory && destFile.isDirectory()) {
throw new InvalidModificationException("Can't copy/move a file to an existing directory");
} else if (srcURL.isDirectory && destFile.isFile()) {
throw new InvalidModificationException("Can't copy/move a directory to an existing file");
}
}
if (srcURL.isDirectory) {
// E.g. Copy /sdcard/myDir to /sdcard/myDir/backup
if (dstNativeUri.toString().startsWith(srcNativeUri.toString() + '/')) {
throw new InvalidModificationException("Can't copy directory into itself");
}
copyDirectory(srcFs, srcURL, destFile, move);
} else {
copyFile(srcFs, srcURL, destFile, move);
}
return makeEntryForURL(destinationURL);
}
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
boolean append = false;
if (offset > 0) {
this.truncateFileAtURL(inputURL, offset);
append = true;
}
byte[] rawData;
if (isBinary) {
rawData = Base64.decode(data, Base64.DEFAULT);
} else {
rawData = data.getBytes(Charset.defaultCharset());
}
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
try
{
byte buff[] = new byte[rawData.length];
String absolutePath = filesystemPathForURL(inputURL);
FileOutputStream out = new FileOutputStream(absolutePath, append);
try {
in.read(buff, 0, buff.length);
out.write(buff, 0, rawData.length);
out.flush();
} finally {
// Always close the output
out.close();
}
if (isPublicDirectory(absolutePath)) {
broadcastNewFile(Uri.fromFile(new File(absolutePath)));
}
}
catch (NullPointerException e)
{
// This is a bug in the Android implementation of the Java Stack
NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
realException.initCause(e);
throw realException;
}
return rawData.length;
}
private boolean isPublicDirectory(String absolutePath) {
// TODO: should expose a way to scan app's private files (maybe via a flag).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Lollipop has a bug where SD cards are null.
for (File f : context.getExternalMediaDirs()) {
if(f != null && absolutePath.startsWith(f.getAbsolutePath())) {
return true;
}
}
}
String extPath = Environment.getExternalStorageDirectory().getAbsolutePath();
return absolutePath.startsWith(extPath);
}
/**
* Send broadcast of new file so files appear over MTP
*/
private void broadcastNewFile(Uri nativeUri) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri);
context.sendBroadcast(intent);
}
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
File file = new File(filesystemPathForURL(inputURL));
if (!file.exists()) {
throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
}
RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
try {
if (raf.length() >= size) {
FileChannel channel = raf.getChannel();
channel.truncate(size);
return size;
}
return raf.length();
} finally {
raf.close();
}
}
@Override
public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
String path = filesystemPathForURL(inputURL);
File file = new File(path);
return file.exists();
}
}
| 1,208 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/EncodingException.java | /*
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.cordova.file;
@SuppressWarnings("serial")
public class EncodingException extends Exception {
public EncodingException(String message) {
super(message);
}
}
| 1,209 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/DirectoryManager.java | /*
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.cordova.file;
import android.os.Environment;
import android.os.StatFs;
import java.io.File;
/**
* This class provides file directory utilities.
* All file operations are performed on the SD card.
*
* It is used by the FileUtils class.
*/
public class DirectoryManager {
@SuppressWarnings("unused")
private static final String LOG_TAG = "DirectoryManager";
/**
* Determine if a file or directory exists.
* @param name The name of the file to check.
* @return T=exists, F=not found
*/
public static boolean testFileExists(String name) {
boolean status;
// If SD card exists
if ((testSaveLocationExists()) && (!name.equals(""))) {
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), name);
status = newPath.exists();
}
// If no SD card
else {
status = false;
}
return status;
}
/**
* Get the free space in external storage
*
* @return Size in KB or -1 if not available
*/
public static long getFreeExternalStorageSpace() {
String status = Environment.getExternalStorageState();
long freeSpaceInBytes = 0;
// Check if external storage exists
if (status.equals(Environment.MEDIA_MOUNTED)) {
freeSpaceInBytes = getFreeSpaceInBytes(Environment.getExternalStorageDirectory().getPath());
} else {
// If no external storage then return -1
return -1;
}
return freeSpaceInBytes / 1024;
}
/**
* Given a path return the number of free bytes in the filesystem containing the path.
*
* @param path to the file system
* @return free space in bytes
*/
public static long getFreeSpaceInBytes(String path) {
try {
StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
} catch (IllegalArgumentException e) {
// The path was invalid. Just return 0 free bytes.
return 0;
}
}
/**
* Determine if SD card exists.
*
* @return T=exists, F=not found
*/
public static boolean testSaveLocationExists() {
String sDCardStatus = Environment.getExternalStorageState();
boolean status;
// If SD card is mounted
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
status = true;
}
// If no SD card
else {
status = false;
}
return status;
}
/**
* Create a new file object from two file paths.
*
* @param file1 Base file path
* @param file2 Remaining file path
* @return File object
*/
private static File constructFilePaths (String file1, String file2) {
File newPath;
if (file2.startsWith(file1)) {
newPath = new File(file2);
}
else {
newPath = new File(file1 + "/" + file2);
}
return newPath;
}
}
| 1,210 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/Filesystem.java | /*
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.cordova.file;
import android.net.Uri;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class Filesystem {
protected final Uri rootUri;
protected final CordovaResourceApi resourceApi;
protected final CordovaPreferences preferences;
public final String name;
private JSONObject rootEntry;
static String SCHEME_HTTPS = "https";
static String DEFAULT_HOSTNAME = "localhost";
public Filesystem(Uri rootUri, String name, CordovaResourceApi resourceApi, CordovaPreferences preferences) {
this.rootUri = rootUri;
this.name = name;
this.resourceApi = resourceApi;
this.preferences = preferences;
}
public interface ReadFileCallback {
public void handleData(InputStream inputStream, String contentType) throws IOException;
}
public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) {
try {
String path = inputURL.path;
int end = path.endsWith("/") ? 1 : 0;
String[] parts = path.substring(0, path.length() - end).split("/+");
String fileName = parts[parts.length - 1];
JSONObject entry = new JSONObject();
entry.put("isFile", !inputURL.isDirectory);
entry.put("isDirectory", inputURL.isDirectory);
entry.put("name", fileName);
entry.put("fullPath", path);
// The file system can't be specified, as it would lead to an infinite loop,
// but the filesystem name can be.
entry.put("filesystemName", inputURL.fsName);
// Backwards compatibility
entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1);
String nativeUrlStr = nativeURL.toString();
if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) {
nativeUrlStr += "/";
}
entry.put("nativeURL", nativeUrlStr);
return entry;
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) {
Uri nativeUri = toNativeUri(inputURL);
return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri);
}
public JSONObject makeEntryForNativeUri(Uri nativeUri) {
LocalFilesystemURL inputUrl = toLocalUri(nativeUri);
return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri);
}
public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
return makeEntryForURL(inputURL);
}
public JSONObject makeEntryForFile(File file) {
return makeEntryForNativeUri(Uri.fromFile(file));
}
abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path,
JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException;
abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException;
abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException;
abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException;
public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
LocalFilesystemURL[] children = listChildren(inputURL);
JSONArray entries = new JSONArray();
if (children != null) {
for (LocalFilesystemURL url : children) {
entries.put(makeEntryForURL(url));
}
}
return entries;
}
abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;
public Uri getRootUri() {
return rootUri;
}
public boolean exists(LocalFilesystemURL inputURL) {
try {
getFileMetadataForLocalURL(inputURL);
} catch (FileNotFoundException e) {
return false;
}
return true;
}
public Uri nativeUriForFullPath(String fullPath) {
Uri ret = null;
if (fullPath != null) {
String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath();
if (encodedPath.startsWith("/")) {
encodedPath = encodedPath.substring(1);
}
ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build();
}
return ret;
}
public LocalFilesystemURL localUrlforFullPath(String fullPath) {
Uri nativeUri = nativeUriForFullPath(fullPath);
if (nativeUri != null) {
return toLocalUri(nativeUri);
}
return null;
}
/**
* Removes multiple repeated //s, and collapses processes ../s.
*/
protected static String normalizePath(String rawPath) {
// If this is an absolute path, trim the leading "/" and replace it later
boolean isAbsolutePath = rawPath.startsWith("/");
if (isAbsolutePath) {
rawPath = rawPath.replaceFirst("/+", "");
}
ArrayList<String> components = new ArrayList<String>(Arrays.asList(rawPath.split("/+")));
for (int index = 0; index < components.size(); ++index) {
if (components.get(index).equals("..")) {
components.remove(index);
if (index > 0) {
components.remove(index-1);
--index;
}
}
}
StringBuilder normalizedPath = new StringBuilder();
for(String component: components) {
normalizedPath.append("/");
normalizedPath.append(component);
}
if (isAbsolutePath) {
return normalizedPath.toString();
} else {
return normalizedPath.toString().substring(1);
}
}
/**
* Gets the free space in bytes available on this filesystem.
* Subclasses may override this method to return nonzero free space.
*/
public long getFreeSpaceInBytes() {
return 0;
}
public abstract Uri toNativeUri(LocalFilesystemURL inputURL);
public abstract LocalFilesystemURL toLocalUri(Uri inputURL);
public JSONObject getRootEntry() {
if (rootEntry == null) {
rootEntry = makeEntryForNativeUri(rootUri);
}
return rootEntry;
}
public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException {
Uri parentUri = inputURL.uri;
String parentPath = new File(inputURL.uri.getPath()).getParent();
if (!"/".equals(parentPath)) {
parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build();
}
return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri));
}
protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) {
// I know this looks weird but it is to work around a JSON bug.
if ("null".equals(newName) || "".equals(newName)) {
newName = srcURL.uri.getLastPathSegment();;
}
String newDest = destURL.uri.toString();
if (newDest.endsWith("/")) {
newDest = newDest + newName;
} else {
newDest = newDest + "/" + newName;
}
if (isDirectory) {
newDest += '/';
}
return LocalFilesystemURL.parse(newDest);
}
/* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to
* the destination URL on this filesystem, optionally with a new filename.
* If move is true, then this method should either perform an atomic move operation
* or remove the source file when finished.
*/
public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
// First, check to see that we can do it
if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
throw new NoModificationAllowedException("Cannot move file at source URL");
}
final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
Uri srcNativeUri = srcFs.toNativeUri(srcURL);
CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri);
OutputStream os = null;
try {
os = getOutputStreamForURL(destination);
} catch (IOException e) {
ofrr.inputStream.close();
throw e;
}
// Closes streams.
resourceApi.copyResource(ofrr, os);
if (move) {
srcFs.removeFileAtLocalURL(srcURL);
}
return getEntryForLocalURL(destination);
}
public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException {
return resourceApi.openOutputStream(toNativeUri(inputURL));
}
public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
ReadFileCallback readFileCallback) throws IOException {
CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL));
if (end < 0) {
end = ofrr.length;
}
long numBytesToRead = end - start;
try {
if (start > 0) {
ofrr.inputStream.skip(start);
}
InputStream inputStream = ofrr.inputStream;
if (end < ofrr.length) {
inputStream = new LimitedInputStream(inputStream, numBytesToRead);
}
readFileCallback.handleData(inputStream, ofrr.mimeType);
} finally {
ofrr.inputStream.close();
}
}
abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset,
boolean isBinary) throws NoModificationAllowedException, IOException;
abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
throws IOException, NoModificationAllowedException;
// This method should return null if filesystem urls cannot be mapped to paths
abstract String filesystemPathForURL(LocalFilesystemURL url);
abstract LocalFilesystemURL URLforFilesystemPath(String path);
abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL);
protected class LimitedInputStream extends FilterInputStream {
long numBytesToRead;
public LimitedInputStream(InputStream in, long numBytesToRead) {
super(in);
this.numBytesToRead = numBytesToRead;
}
@Override
public int read() throws IOException {
if (numBytesToRead <= 0) {
return -1;
}
numBytesToRead--;
return in.read();
}
@Override
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
if (numBytesToRead <= 0) {
return -1;
}
int bytesToRead = byteCount;
if (byteCount > numBytesToRead) {
bytesToRead = (int)numBytesToRead; // Cast okay; long is less than int here.
}
int numBytesRead = in.read(buffer, byteOffset, bytesToRead);
numBytesToRead -= numBytesRead;
return numBytesRead;
}
}
protected Uri.Builder createLocalUriBuilder() {
String scheme = preferences.getString("scheme", SCHEME_HTTPS).toLowerCase();
String hostname = preferences.getString("hostname", DEFAULT_HOSTNAME).toLowerCase();
String path = LocalFilesystemURL.fsNameToCdvKeyword(name);
return new Uri.Builder()
.scheme(scheme)
.authority(hostname)
.path(path);
}
}
| 1,211 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/NoModificationAllowedException.java | /*
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.cordova.file;
@SuppressWarnings("serial")
public class NoModificationAllowedException extends Exception {
public NoModificationAllowedException(String message) {
super(message);
}
}
| 1,212 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/TypeMismatchException.java | /*
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.cordova.file;
@SuppressWarnings("serial")
public class TypeMismatchException extends Exception {
public TypeMismatchException(String message) {
super(message);
}
}
| 1,213 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/AssetFilesystem.java | /*
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.cordova.file;
import android.content.res.AssetManager;
import android.net.Uri;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaResourceApi;
import org.apache.cordova.LOG;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
public class AssetFilesystem extends Filesystem {
private final AssetManager assetManager;
// A custom gradle hook creates the cdvasset.manifest file, which speeds up asset listing a tonne.
// See: http://stackoverflow.com/questions/16911558/android-assetmanager-list-incredibly-slow
private static Object listCacheLock = new Object();
private static boolean listCacheFromFile;
private static Map<String, String[]> listCache;
private static Map<String, Long> lengthCache;
private static final String LOG_TAG = "AssetFilesystem";
private void lazyInitCaches() {
synchronized (listCacheLock) {
if (listCache == null) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(assetManager.open("cdvasset.manifest"));
listCache = (Map<String, String[]>) ois.readObject();
lengthCache = (Map<String, Long>) ois.readObject();
listCacheFromFile = true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// Asset manifest won't exist if the gradle hook isn't set up correctly.
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
}
if (listCache == null) {
LOG.w("AssetFilesystem", "Asset manifest not found. Recursive copies and directory listing will be slow.");
listCache = new HashMap<String, String[]>();
}
}
}
}
private String[] listAssets(String assetPath) throws IOException {
if (assetPath.startsWith("/")) {
assetPath = assetPath.substring(1);
}
if (assetPath.endsWith("/")) {
assetPath = assetPath.substring(0, assetPath.length() - 1);
}
lazyInitCaches();
String[] ret = listCache.get(assetPath);
if (ret == null) {
if (listCacheFromFile) {
ret = new String[0];
} else {
ret = assetManager.list(assetPath);
listCache.put(assetPath, ret);
}
}
return ret;
}
private long getAssetSize(String assetPath) throws FileNotFoundException {
if (assetPath.startsWith("/")) {
assetPath = assetPath.substring(1);
}
lazyInitCaches();
if (lengthCache != null) {
Long ret = lengthCache.get(assetPath);
if (ret == null) {
throw new FileNotFoundException("Asset not found: " + assetPath);
}
return ret;
}
CordovaResourceApi.OpenForReadResult offr = null;
try {
offr = resourceApi.openForRead(nativeUriForFullPath(assetPath));
long length = offr.length;
if (length < 0) {
// available() doesn't always yield the file size, but for assets it does.
length = offr.inputStream.available();
}
return length;
} catch (IOException e) {
FileNotFoundException fnfe = new FileNotFoundException("File not found: " + assetPath);
fnfe.initCause(e);
throw fnfe;
} finally {
if (offr != null) {
try {
offr.inputStream.close();
} catch (IOException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
}
}
public AssetFilesystem(AssetManager assetManager, CordovaResourceApi resourceApi, CordovaPreferences preferences) {
super(Uri.parse("file:///android_asset/"), "assets", resourceApi, preferences);
this.assetManager = assetManager;
}
@Override
public Uri toNativeUri(LocalFilesystemURL inputURL) {
return nativeUriForFullPath(inputURL.path);
}
@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
if (!"file".equals(inputURL.getScheme())) {
return null;
}
File f = new File(inputURL.getPath());
// Removes and duplicate /s (e.g. file:///a//b/c)
Uri resolvedUri = Uri.fromFile(f);
String rootUriNoTrailingSlash = rootUri.getEncodedPath();
rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
return null;
}
String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
// Strip leading slash
if (!subPath.isEmpty()) {
subPath = subPath.substring(1);
}
Uri.Builder b = createLocalUriBuilder();
if (!subPath.isEmpty()) {
b.appendEncodedPath(subPath);
}
if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
// Add trailing / for directories.
b.appendEncodedPath("");
}
return LocalFilesystemURL.parse(b.build());
}
private boolean isDirectory(String assetPath) {
try {
return listAssets(assetPath).length != 0;
} catch (IOException e) {
return false;
}
}
@Override
public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
String pathNoSlashes = inputURL.path.substring(1);
if (pathNoSlashes.endsWith("/")) {
pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1);
}
String[] files;
try {
files = listAssets(pathNoSlashes);
} catch (IOException e) {
FileNotFoundException fnfe = new FileNotFoundException();
fnfe.initCause(e);
throw fnfe;
}
LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
for (int i = 0; i < files.length; ++i) {
entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath());
}
return entries;
}
@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
String path, JSONObject options, boolean directory)
throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
if (options != null && options.optBoolean("create")) {
throw new UnsupportedOperationException("Assets are read-only");
}
// Check whether the supplied path is absolute or relative
if (directory && !path.endsWith("/")) {
path += "/";
}
LocalFilesystemURL requestedURL;
if (path.startsWith("/")) {
requestedURL = localUrlforFullPath(normalizePath(path));
} else {
requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
}
// Throws a FileNotFoundException if it doesn't exist.
getFileMetadataForLocalURL(requestedURL);
boolean isDir = isDirectory(requestedURL.path);
if (directory && !isDir) {
throw new TypeMismatchException("path doesn't exist or is file");
} else if (!directory && isDir) {
throw new TypeMismatchException("path doesn't exist or is directory");
}
// Return the directory
return makeEntryForURL(requestedURL);
}
@Override
public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
JSONObject metadata = new JSONObject();
long size = inputURL.isDirectory ? 0 : getAssetSize(inputURL.path);
try {
metadata.put("size", size);
metadata.put("type", inputURL.isDirectory ? "text/directory" : resourceApi.getMimeType(toNativeUri(inputURL)));
metadata.put("name", new File(inputURL.path).getName());
metadata.put("fullPath", inputURL.path);
metadata.put("lastModifiedDate", 0);
} catch (JSONException e) {
return null;
}
return metadata;
}
@Override
public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
return false;
}
@Override
long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException {
throw new NoModificationAllowedException("Assets are read-only");
}
@Override
long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException {
throw new NoModificationAllowedException("Assets are read-only");
}
@Override
String filesystemPathForURL(LocalFilesystemURL url) {
return new File(rootUri.getPath(), url.path).toString();
}
@Override
LocalFilesystemURL URLforFilesystemPath(String path) {
return null;
}
@Override
boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException {
throw new NoModificationAllowedException("Assets are read-only");
}
@Override
boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException {
throw new NoModificationAllowedException("Assets are read-only");
}
}
| 1,214 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/FileUtils.java | /*
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.cordova.file;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.webkit.WebResourceResponse;
import androidx.webkit.WebViewAssetLoader;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaPluginPathHandler;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PermissionHelper;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
/**
* This class provides file and directory services to JavaScript.
*/
public class FileUtils extends CordovaPlugin {
private static final String LOG_TAG = "FileUtils";
public static int NOT_FOUND_ERR = 1;
public static int SECURITY_ERR = 2;
public static int ABORT_ERR = 3;
public static int NOT_READABLE_ERR = 4;
public static int ENCODING_ERR = 5;
public static int NO_MODIFICATION_ALLOWED_ERR = 6;
public static int INVALID_STATE_ERR = 7;
public static int SYNTAX_ERR = 8;
public static int INVALID_MODIFICATION_ERR = 9;
public static int QUOTA_EXCEEDED_ERR = 10;
public static int TYPE_MISMATCH_ERR = 11;
public static int PATH_EXISTS_ERR = 12;
/*
* Permission callback codes
*/
public static final int ACTION_GET_FILE = 0;
public static final int ACTION_WRITE = 1;
public static final int ACTION_GET_DIRECTORY = 2;
public static final int ACTION_READ_ENTRIES = 3;
public static final int WRITE = 3;
public static final int READ = 4;
public static int UNKNOWN_ERR = 1000;
private boolean configured = false;
private PendingRequests pendingRequests;
// This field exists only to support getEntry, below, which has been deprecated
private static FileUtils filePlugin;
private interface FileOp {
void run(JSONArray args) throws Exception;
}
private ArrayList<Filesystem> filesystems;
public void registerFilesystem(Filesystem fs) {
if (fs != null && filesystemForName(fs.name) == null) {
this.filesystems.add(fs);
}
}
private Filesystem filesystemForName(String name) {
for (Filesystem fs : filesystems) {
if (fs != null && fs.name != null && fs.name.equals(name)) {
return fs;
}
}
return null;
}
protected String[] getExtraFileSystemsPreference(Activity activity) {
String fileSystemsStr = preferences.getString("androidextrafilesystems", "files,files-external,documents,sdcard,cache,cache-external,assets,root");
return fileSystemsStr.split(",");
}
protected void registerExtraFileSystems(String[] filesystems, HashMap<String, String> availableFileSystems) {
HashSet<String> installedFileSystems = new HashSet<String>();
/* Register filesystems in order */
for (String fsName : filesystems) {
if (!installedFileSystems.contains(fsName)) {
String fsRoot = availableFileSystems.get(fsName);
if (fsRoot != null) {
File newRoot = new File(fsRoot);
if (newRoot.mkdirs() || newRoot.isDirectory()) {
registerFilesystem(new LocalFilesystem(fsName, webView.getContext(), webView.getResourceApi(), newRoot, preferences));
installedFileSystems.add(fsName);
} else {
LOG.d(LOG_TAG, "Unable to create root dir for filesystem \"" + fsName + "\", skipping");
}
} else {
LOG.d(LOG_TAG, "Unrecognized extra filesystem identifier: " + fsName);
}
}
}
}
protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
Context context = activity.getApplicationContext();
HashMap<String, String> availableFileSystems = new HashMap<String, String>();
availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
availableFileSystems.put("root", "/");
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
} catch (NullPointerException e) {
LOG.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
}
}
return availableFileSystems;
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.filesystems = new ArrayList<Filesystem>();
this.pendingRequests = new PendingRequests();
String tempRoot = null;
String persistentRoot = null;
Activity activity = cordova.getActivity();
String packageName = activity.getPackageName();
String location = preferences.getString("androidpersistentfilelocation", "internal");
tempRoot = activity.getCacheDir().getAbsolutePath();
if ("internal".equalsIgnoreCase(location)) {
persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/";
this.configured = true;
} else if ("compatibility".equalsIgnoreCase(location)) {
/*
* Fall-back to compatibility mode -- this is the logic implemented in
* earlier versions of this plugin, and should be maintained here so
* that apps which were originally deployed with older versions of the
* plugin can continue to provide access to files stored under those
* versions.
*/
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/" + packageName + "/cache/";
} else {
persistentRoot = "/data/data/" + packageName;
}
this.configured = true;
}
if (this.configured) {
// Create the directories if they don't exist.
File tmpRootFile = new File(tempRoot);
File persistentRootFile = new File(persistentRoot);
tmpRootFile.mkdirs();
persistentRootFile.mkdirs();
// Register initial filesystems
// Note: The temporary and persistent filesystems need to be the first two
// registered, so that they will match window.TEMPORARY and window.PERSISTENT,
// per spec.
this.registerFilesystem(new LocalFilesystem("temporary", webView.getContext(), webView.getResourceApi(), tmpRootFile, preferences));
this.registerFilesystem(new LocalFilesystem("persistent", webView.getContext(), webView.getResourceApi(), persistentRootFile, preferences));
this.registerFilesystem(new ContentFilesystem(webView.getContext(), webView.getResourceApi(), preferences));
this.registerFilesystem(new AssetFilesystem(webView.getContext().getAssets(), webView.getResourceApi(), preferences));
registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity));
// Initialize static plugin reference for deprecated getEntry method
if (filePlugin == null) {
FileUtils.filePlugin = this;
}
} else {
LOG.e(LOG_TAG, "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
activity.finish();
}
}
public static FileUtils getFilePlugin() {
return filePlugin;
}
private Filesystem filesystemForURL(LocalFilesystemURL localURL) {
if (localURL == null) return null;
return filesystemForName(localURL.fsName);
}
@Override
public Uri remapUri(Uri uri) {
// Remap only cdvfile: URLs (not content:).
if (!LocalFilesystemURL.FILESYSTEM_PROTOCOL.equals(uri.getScheme())) {
return null;
}
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
return null;
}
String path = fs.filesystemPathForURL(inputURL);
if (path != null) {
return Uri.parse("file://" + fs.filesystemPathForURL(inputURL));
}
return null;
} catch (IllegalArgumentException e) {
return null;
}
}
public boolean execute(String action, final String rawArgs, final CallbackContext callbackContext) {
if (!configured) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File plugin is not configured. Please see the README.md file for details on how to update config.xml"));
return true;
}
if (action.equals("testSaveLocationExists")) {
threadhelper(new FileOp() {
public void run(JSONArray args) {
boolean b = DirectoryManager.testSaveLocationExists();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
}
}, rawArgs, callbackContext);
} else if (action.equals("getFreeDiskSpace")) {
threadhelper(new FileOp() {
public void run(JSONArray args) {
// The getFreeDiskSpace plugin API is not documented, but some apps call it anyway via exec().
// For compatibility it always returns free space in the primary external storage, and
// does NOT fallback to internal store if external storage is unavailable.
long l = DirectoryManager.getFreeExternalStorageSpace();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
}
}, rawArgs, callbackContext);
} else if (action.equals("testFileExists")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException {
String fname = args.getString(0);
boolean b = DirectoryManager.testFileExists(fname);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
}
}, rawArgs, callbackContext);
} else if (action.equals("testDirectoryExists")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException {
String fname = args.getString(0);
boolean b = DirectoryManager.testFileExists(fname);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
}
}, rawArgs, callbackContext);
} else if (action.equals("readAsText")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, MalformedURLException {
String encoding = args.getString(1);
int start = args.getInt(2);
int end = args.getInt(3);
String fname = args.getString(0);
readFileAs(fname, start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING);
}
}, rawArgs, callbackContext);
} else if (action.equals("readAsDataURL")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, MalformedURLException {
int start = args.getInt(1);
int end = args.getInt(2);
String fname = args.getString(0);
readFileAs(fname, start, end, callbackContext, null, -1);
}
}, rawArgs, callbackContext);
} else if (action.equals("readAsArrayBuffer")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, MalformedURLException {
int start = args.getInt(1);
int end = args.getInt(2);
String fname = args.getString(0);
readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER);
}
}, rawArgs, callbackContext);
} else if (action.equals("readAsBinaryString")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, MalformedURLException {
int start = args.getInt(1);
int end = args.getInt(2);
String fname = args.getString(0);
readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING);
}
}, rawArgs, callbackContext);
} else if (action.equals("write")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
String fname = args.getString(0);
String nativeURL = resolveLocalFileSystemURI(fname).getString("nativeURL");
String data = args.getString(1);
int offset = args.getInt(2);
Boolean isBinary = args.getBoolean(3);
if (needPermission(nativeURL, WRITE)) {
getWritePermission(rawArgs, ACTION_WRITE, callbackContext);
} else {
long fileSize = write(fname, data, offset, isBinary);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
}
}
}, rawArgs, callbackContext);
} else if (action.equals("truncate")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
String fname = args.getString(0);
int offset = args.getInt(1);
long fileSize = truncateFile(fname, offset);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
}
}, rawArgs, callbackContext);
} else if (action.equals("requestAllFileSystems")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws IOException, JSONException {
callbackContext.success(requestAllFileSystems());
}
}, rawArgs, callbackContext);
} else if (action.equals("requestAllPaths")) {
cordova.getThreadPool().execute(
new Runnable() {
public void run() {
try {
callbackContext.success(requestAllPaths());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
} else if (action.equals("requestFileSystem")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException {
int fstype = args.getInt(0);
long requiredSize = args.optLong(1);
requestFileSystem(fstype, requiredSize, callbackContext);
}
}, rawArgs, callbackContext);
} else if (action.equals("resolveLocalFileSystemURI")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws IOException, JSONException {
String fname = args.getString(0);
JSONObject obj = resolveLocalFileSystemURI(fname);
callbackContext.success(obj);
}
}, rawArgs, callbackContext);
} else if (action.equals("getFileMetadata")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
String fname = args.getString(0);
JSONObject obj = getFileMetadata(fname);
callbackContext.success(obj);
}
}, rawArgs, callbackContext);
} else if (action.equals("getParent")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, IOException {
String fname = args.getString(0);
JSONObject obj = getParent(fname);
callbackContext.success(obj);
}
}, rawArgs, callbackContext);
} else if (action.equals("getDirectory")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
String dirname = args.getString(0);
String path = args.getString(1);
String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL");
boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false);
if (containsCreate && needPermission(nativeURL, WRITE)) {
getWritePermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext);
} else if (!containsCreate && needPermission(nativeURL, READ)) {
getReadPermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext);
} else {
JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
callbackContext.success(obj);
}
}
}, rawArgs, callbackContext);
} else if (action.equals("getFile")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
String dirname = args.getString(0);
String path = args.getString(1);
if (dirname.contains(LocalFilesystemURL.CDVFILE_KEYWORD) == true) {
JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
callbackContext.success(obj);
} else {
String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL");
boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false);
if (containsCreate && needPermission(nativeURL, WRITE)) {
getWritePermission(rawArgs, ACTION_GET_FILE, callbackContext);
} else if (!containsCreate && needPermission(nativeURL, READ)) {
getReadPermission(rawArgs, ACTION_GET_FILE, callbackContext);
} else {
JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
callbackContext.success(obj);
}
}
}
}, rawArgs, callbackContext);
} else if (action.equals("remove")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, NoModificationAllowedException, InvalidModificationException, MalformedURLException {
String fname = args.getString(0);
boolean success = remove(fname);
if (success) {
callbackContext.success();
} else {
callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
}
}
}, rawArgs, callbackContext);
} else if (action.equals("removeRecursively")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, FileExistsException, MalformedURLException, NoModificationAllowedException {
String fname = args.getString(0);
boolean success = removeRecursively(fname);
if (success) {
callbackContext.success();
} else {
callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
}
}
}, rawArgs, callbackContext);
} else if (action.equals("moveTo")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
String fname = args.getString(0);
String newParent = args.getString(1);
String newName = args.getString(2);
JSONObject entry = transferTo(fname, newParent, newName, true);
callbackContext.success(entry);
}
}, rawArgs, callbackContext);
} else if (action.equals("copyTo")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
String fname = args.getString(0);
String newParent = args.getString(1);
String newName = args.getString(2);
JSONObject entry = transferTo(fname, newParent, newName, false);
callbackContext.success(entry);
}
}, rawArgs, callbackContext);
} else if (action.equals("readEntries")) {
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException, IOException {
String directory = args.getString(0);
String nativeURL = resolveLocalFileSystemURI(directory).getString("nativeURL");
if (needPermission(nativeURL, READ)) {
getReadPermission(rawArgs, ACTION_READ_ENTRIES, callbackContext);
} else {
JSONArray entries = readEntries(directory);
callbackContext.success(entries);
}
}
}, rawArgs, callbackContext);
} else if (action.equals("_getLocalFilesystemPath")) {
// Internal method for testing: Get the on-disk location of a local filesystem url.
// [Currently used for testing file-transfer]
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
String localURLstr = args.getString(0);
String fname = filesystemPathForURL(localURLstr);
callbackContext.success(fname);
}
}, rawArgs, callbackContext);
} else {
return false;
}
return true;
}
private void getReadPermission(String rawArgs, int action, CallbackContext callbackContext) {
int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
PermissionHelper.requestPermissions(this, requestCode,
new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_AUDIO});
} else {
PermissionHelper.requestPermission(this, requestCode, Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
private void getWritePermission(String rawArgs, int action, CallbackContext callbackContext) {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext);
PermissionHelper.requestPermission(this, requestCode, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
}
/**
* If your app targets Android 13 (SDK 33) or higher and needs to access media files that other apps have created,
* you must request one or more of the following granular media permissions READ_MEDIA_*
* instead of the READ_EXTERNAL_STORAGE permission:
*
* Refer to: https://developer.android.com/about/versions/13/behavior-changes-13
*
* @return
*/
private boolean hasReadPermission() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return PermissionHelper.hasPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
&& PermissionHelper.hasPermission(this, Manifest.permission.READ_MEDIA_VIDEO)
&& PermissionHelper.hasPermission(this, Manifest.permission.READ_MEDIA_AUDIO);
} else {
return PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
private boolean hasWritePermission() {
// Starting with API 33, requesting WRITE_EXTERNAL_STORAGE is an auto permission rejection
return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
? true
: PermissionHelper.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
private boolean needPermission(String nativeURL, int permissionType) throws JSONException {
JSONObject j = requestAllPaths();
ArrayList<String> allowedStorageDirectories = new ArrayList<String>();
allowedStorageDirectories.add(j.getString("applicationDirectory"));
allowedStorageDirectories.add(j.getString("applicationStorageDirectory"));
if (j.has("externalApplicationStorageDirectory")) {
allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory"));
}
if (permissionType == READ && hasReadPermission()) {
return false;
} else if (permissionType == WRITE && hasWritePermission()) {
return false;
}
// Permission required if the native url lies outside the allowed storage directories
for (String directory : allowedStorageDirectories) {
if (nativeURL.startsWith(directory)) {
return false;
}
}
return true;
}
public LocalFilesystemURL resolveNativeUri(Uri nativeUri) {
LocalFilesystemURL localURL = null;
// Try all installed filesystems. Return the best matching URL
// (determined by the shortest resulting URL)
for (Filesystem fs : filesystems) {
LocalFilesystemURL url = fs.toLocalUri(nativeUri);
if (url != null) {
// A shorter fullPath implies that the filesystem is a better
// match for the local path than the previous best.
if (localURL == null || (url.uri.toString().length() < localURL.toString().length())) {
localURL = url;
}
}
}
return localURL;
}
/*
* These two native-only methods can be used by other plugins to translate between
* device file system paths and URLs. By design, there is no direct JavaScript
* interface to these methods.
*/
public String filesystemPathForURL(String localURLstr) throws MalformedURLException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(localURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.filesystemPathForURL(inputURL);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
public LocalFilesystemURL filesystemURLforLocalPath(String localPath) {
LocalFilesystemURL localURL = null;
int shortestFullPath = 0;
// Try all installed filesystems. Return the best matching URL
// (determined by the shortest resulting URL)
for (Filesystem fs : filesystems) {
LocalFilesystemURL url = fs.URLforFilesystemPath(localPath);
if (url != null) {
// A shorter fullPath implies that the filesystem is a better
// match for the local path than the previous best.
if (localURL == null || (url.path.length() < shortestFullPath)) {
localURL = url;
shortestFullPath = url.path.length();
}
}
}
return localURL;
}
/* helper to execute functions async and handle the result codes
*
*/
private void threadhelper(final FileOp f, final String rawArgs, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
JSONArray args = new JSONArray(rawArgs);
f.run(args);
} catch (Exception e) {
if (e instanceof EncodingException) {
callbackContext.error(FileUtils.ENCODING_ERR);
} else if (e instanceof FileNotFoundException) {
callbackContext.error(FileUtils.NOT_FOUND_ERR);
} else if (e instanceof FileExistsException) {
callbackContext.error(FileUtils.PATH_EXISTS_ERR);
} else if (e instanceof NoModificationAllowedException) {
callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
} else if (e instanceof InvalidModificationException) {
callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
} else if (e instanceof MalformedURLException) {
callbackContext.error(FileUtils.ENCODING_ERR);
} else if (e instanceof IOException) {
callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
} else if (e instanceof TypeMismatchException) {
callbackContext.error(FileUtils.TYPE_MISMATCH_ERR);
} else if (e instanceof JSONException) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
} else if (e instanceof SecurityException) {
callbackContext.error(FileUtils.SECURITY_ERR);
} else {
e.printStackTrace();
callbackContext.error(FileUtils.UNKNOWN_ERR);
}
}
}
});
}
/**
* Allows the user to look up the Entry for a file or directory referred to by a local URI.
*
* @param uriString of the file/directory to look up
* @return a JSONObject representing a Entry from the filesystem
* @throws MalformedURLException if the url is not valid
* @throws FileNotFoundException if the file does not exist
* @throws IOException if the user can't read the file
* @throws JSONException
*/
private JSONObject resolveLocalFileSystemURI(String uriString) throws IOException, JSONException {
if (uriString == null) {
throw new MalformedURLException("Unrecognized filesystem URL");
}
Uri uri = Uri.parse(uriString);
boolean isNativeUri = false;
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
if (inputURL == null) {
/* Check for file://, content:// urls */
inputURL = resolveNativeUri(uri);
isNativeUri = true;
}
try {
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
if (fs.exists(inputURL)) {
if (!isNativeUri) {
// If not already resolved as native URI, resolve to a native URI and back to
// fix the terminating slash based on whether the entry is a directory or file.
inputURL = fs.toLocalUri(fs.toNativeUri(inputURL));
}
return fs.getEntryForLocalURL(inputURL);
}
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
throw new FileNotFoundException();
}
/**
* Read the list of files from this directory.
*
* @return a JSONArray containing JSONObjects that represent Entry objects.
* @throws FileNotFoundException if the directory is not found.
* @throws JSONException
* @throws MalformedURLException
*/
private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.readEntriesAtLocalURL(inputURL);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/**
* A setup method that handles the move/copy of files/directories
*
* @param newName for the file directory to be called, if null use existing file name
* @param move if false do a copy, if true do a move
* @return a Entry object
* @throws NoModificationAllowedException
* @throws IOException
* @throws InvalidModificationException
* @throws EncodingException
* @throws JSONException
* @throws FileExistsException
*/
private JSONObject transferTo(String srcURLstr, String destURLstr, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
if (srcURLstr == null || destURLstr == null) {
// either no source or no destination provided
throw new FileNotFoundException();
}
LocalFilesystemURL srcURL = LocalFilesystemURL.parse(srcURLstr);
LocalFilesystemURL destURL = LocalFilesystemURL.parse(destURLstr);
Filesystem srcFs = this.filesystemForURL(srcURL);
Filesystem destFs = this.filesystemForURL(destURL);
// Check for invalid file name
if (newName != null && newName.contains(":")) {
throw new EncodingException("Bad file name");
}
return destFs.copyFileToURL(destURL, newName, srcFs, srcURL, move);
}
/**
* Deletes a directory and all of its contents, if any. In the event of an error
* [e.g. trying to delete a directory that contains a file that cannot be removed],
* some of the contents of the directory may be deleted.
* It is an error to attempt to delete the root directory of a filesystem.
*
* @return a boolean representing success of failure
* @throws FileExistsException
* @throws NoModificationAllowedException
* @throws MalformedURLException
*/
private boolean removeRecursively(String baseURLstr) throws FileExistsException, NoModificationAllowedException, MalformedURLException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
// You can't delete the root directory.
if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
throw new NoModificationAllowedException("You can't delete the root directory");
}
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.recursiveRemoveFileAtLocalURL(inputURL);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/**
* Deletes a file or directory. It is an error to attempt to delete a directory that is not empty.
* It is an error to attempt to delete the root directory of a filesystem.
*
* @return a boolean representing success of failure
* @throws NoModificationAllowedException
* @throws InvalidModificationException
* @throws MalformedURLException
*/
private boolean remove(String baseURLstr) throws NoModificationAllowedException, InvalidModificationException, MalformedURLException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
// You can't delete the root directory.
if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
throw new NoModificationAllowedException("You can't delete the root directory");
}
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.removeFileAtLocalURL(inputURL);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/**
* Creates or looks up a file.
*
* @param baseURLstr base directory
* @param path file/directory to lookup or create
* @param options specify whether to create or not
* @param directory if true look up directory, if false look up file
* @return a Entry object
* @throws FileExistsException
* @throws IOException
* @throws TypeMismatchException
* @throws EncodingException
* @throws JSONException
*/
private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.getFileForLocalURL(inputURL, path, options, directory);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/**
* Look up the parent DirectoryEntry containing this Entry.
* If this Entry is the root of its filesystem, its parent is itself.
*/
private JSONObject getParent(String baseURLstr) throws JSONException, IOException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.getParentForLocalURL(inputURL);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/**
* Returns a File that represents the current state of the file that this FileEntry represents.
*
* @return returns a JSONObject represent a W3C File object
*/
private JSONObject getFileMetadata(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.getFileMetadataForLocalURL(inputURL);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/**
* Requests a filesystem in which to store application data.
*
* @param type of file system requested
* @param requiredSize required free space in the file system in bytes
* @param callbackContext context for returning the result or error
* @throws JSONException
*/
private void requestFileSystem(int type, long requiredSize, final CallbackContext callbackContext) throws JSONException {
Filesystem rootFs = null;
try {
rootFs = this.filesystems.get(type);
} catch (ArrayIndexOutOfBoundsException e) {
// Pass null through
}
if (rootFs == null) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR));
} else {
// If a nonzero required size was specified, check that the retrieved filesystem has enough free space.
long availableSize = 0;
if (requiredSize > 0) {
availableSize = rootFs.getFreeSpaceInBytes();
}
if (availableSize < requiredSize) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR));
} else {
JSONObject fs = new JSONObject();
fs.put("name", rootFs.name);
fs.put("root", rootFs.getRootEntry());
callbackContext.success(fs);
}
}
}
/**
* Requests a filesystem in which to store application data.
*
* @return a JSONObject representing the file system
*/
private JSONArray requestAllFileSystems() throws IOException, JSONException {
JSONArray ret = new JSONArray();
for (Filesystem fs : filesystems) {
ret.put(fs.getRootEntry());
}
return ret;
}
private static String toDirUrl(File f) {
return Uri.fromFile(f).toString() + '/';
}
private JSONObject requestAllPaths() throws JSONException {
Context context = cordova.getActivity();
JSONObject ret = new JSONObject();
ret.put("applicationDirectory", "file:///android_asset/");
ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
} catch (NullPointerException e) {
/* If external storage is unavailable, context.getExternal* returns null */
LOG.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
}
}
return ret;
}
/**
* Returns a JSON object representing the given File. Internal APIs should be modified
* to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
*
* @param file the File to convert
* @return a JSON representation of the given File
* @throws JSONException
*/
public JSONObject getEntryForFile(File file) throws JSONException {
JSONObject entry;
for (Filesystem fs : filesystems) {
entry = fs.makeEntryForFile(file);
if (entry != null) {
return entry;
}
}
return null;
}
/**
* Returns a JSON object representing the given File. Deprecated, as this is only used by
* FileTransfer, and because it is a static method that should really be an instance method,
* since it depends on the actual filesystem roots in use. Internal APIs should be modified
* to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
*
* @param file the File to convert
* @return a JSON representation of the given File
* @throws JSONException
*/
@Deprecated
public static JSONObject getEntry(File file) throws JSONException {
if (getFilePlugin() != null) {
return getFilePlugin().getEntryForFile(file);
}
return null;
}
/**
* Read the contents of a file.
* This is done in a background thread; the result is sent to the callback.
*
* @param start Start position in the file.
* @param end End position to stop at (exclusive).
* @param callbackContext The context through which to send the result.
* @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
* @param resultType The desired type of data to send to the callback.
* @return Contents of file.
*/
public void readFileAs(final String srcURLstr, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) throws MalformedURLException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() {
public void handleData(InputStream inputStream, String contentType) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
for (; ; ) {
int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
if (bytesRead <= 0) {
break;
}
os.write(buffer, 0, bytesRead);
}
PluginResult result;
switch (resultType) {
case PluginResult.MESSAGE_TYPE_STRING:
result = new PluginResult(PluginResult.Status.OK, os.toString(encoding));
break;
case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
result = new PluginResult(PluginResult.Status.OK, os.toByteArray());
break;
case PluginResult.MESSAGE_TYPE_BINARYSTRING:
result = new PluginResult(PluginResult.Status.OK, os.toByteArray(), true);
break;
default: // Base64.
byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP);
String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
result = new PluginResult(PluginResult.Status.OK, s);
}
callbackContext.sendPluginResult(result);
} catch (IOException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
}
}
});
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
} catch (FileNotFoundException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
} catch (IOException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
}
}
/**
* Write contents of file.
*
* @param data The contents of the file.
* @param offset The position to begin writing the file.
* @param isBinary True if the file contents are base64-encoded binary data
*/
/**/
public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.writeToFileAtURL(inputURL, data, offset, isBinary);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/**
* Truncate the file to size
*/
private long truncateFile(String srcURLstr, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
try {
LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
Filesystem fs = this.filesystemForURL(inputURL);
if (fs == null) {
throw new MalformedURLException("No installed handlers for this URL");
}
return fs.truncateFileAtURL(inputURL, size);
} catch (IllegalArgumentException e) {
MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
mue.initCause(e);
throw mue;
}
}
/*
* Handle the response
*/
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException {
final PendingRequests.Request req = pendingRequests.getAndRemove(requestCode);
if (req != null) {
for (int r : grantResults) {
if (r == PackageManager.PERMISSION_DENIED) {
req.getCallbackContext().sendPluginResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR));
return;
}
}
switch (req.getAction()) {
case ACTION_GET_FILE:
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
String dirname = args.getString(0);
String path = args.getString(1);
JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
req.getCallbackContext().success(obj);
}
}, req.getRawArgs(), req.getCallbackContext());
break;
case ACTION_GET_DIRECTORY:
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
String dirname = args.getString(0);
String path = args.getString(1);
JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
req.getCallbackContext().success(obj);
}
}, req.getRawArgs(), req.getCallbackContext());
break;
case ACTION_WRITE:
threadhelper(new FileOp() {
public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
String fname = args.getString(0);
String data = args.getString(1);
int offset = args.getInt(2);
Boolean isBinary = args.getBoolean(3);
long fileSize = write(fname, data, offset, isBinary);
req.getCallbackContext().sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
}
}, req.getRawArgs(), req.getCallbackContext());
break;
case ACTION_READ_ENTRIES:
threadhelper(new FileOp() {
public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
String fname = args.getString(0);
JSONArray entries = readEntries(fname);
req.getCallbackContext().success(entries);
}
}, req.getRawArgs(), req.getCallbackContext());
break;
}
} else {
LOG.d(LOG_TAG, "Received permission callback for unknown request code");
}
}
private String getMimeType(Uri uri) {
String fileExtensionFromUrl = MimeTypeMap.getFileExtensionFromUrl(uri.toString()).toLowerCase();
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtensionFromUrl);
}
public CordovaPluginPathHandler getPathHandler() {
WebViewAssetLoader.PathHandler pathHandler = path -> {
String targetFileSystem = null;
if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("persistent"))) {
targetFileSystem = "persistent";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("temporary"))) {
targetFileSystem = "temporary";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("files"))) {
targetFileSystem = "files";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("documents"))) {
targetFileSystem = "documents";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("cache"))) {
targetFileSystem = "cache";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("root"))) {
targetFileSystem = "root";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("files-external"))) {
targetFileSystem = "files-external";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("sdcard"))) {
targetFileSystem = "sdcard";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("cache-external"))) {
targetFileSystem = "cache-external";
} else if (path.startsWith(LocalFilesystemURL.fsNameToCdvKeyword("assets"))) {
targetFileSystem = "assets";
}
boolean isAssetsFS = targetFileSystem == "assets";
if (targetFileSystem != null) {
// Loop the registered file systems to find the target.
for (Filesystem fileSystem : filesystems) {
/*
* When target is discovered:
* 1. Transform the url path to the native path
* 2. Load the file contents
* 3. Get the file mime type
* 4. Return the file & mime information back we Web Resources
*/
if (fileSystem.name.equals(targetFileSystem)) {
// E.g. replace __cdvfile_persistent__ with native path "/data/user/0/com.example.file/files/files/"
String fileSystemNativeUri = fileSystem.rootUri.toString().replace("file://", "");
String fileTarget = path.replace(LocalFilesystemURL.fsNameToCdvKeyword(targetFileSystem) + "/", fileSystemNativeUri);
File file = null;
if (isAssetsFS) {
fileTarget = fileTarget.replace("/android_asset/", "");
} else {
file = new File(fileTarget);
}
try {
InputStream fileIS = !isAssetsFS ?
new FileInputStream(file) :
webView.getContext().getAssets().open(fileTarget);
String filePath = !isAssetsFS ? file.toString() : fileTarget;
Uri fileUri = Uri.parse(filePath);
String fileMimeType = getMimeType(fileUri);
return new WebResourceResponse(fileMimeType, null, fileIS);
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, e.getMessage());
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage());
}
}
}
}
return null;
};
return new CordovaPluginPathHandler(pathHandler);
}
}
| 1,215 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/FileExistsException.java | /*
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.cordova.file;
@SuppressWarnings("serial")
public class FileExistsException extends Exception {
public FileExistsException(String msg) {
super(msg);
}
}
| 1,216 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/PendingRequests.java | /*
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.cordova.file;
import android.util.SparseArray;
import org.apache.cordova.CallbackContext;
/**
* Holds pending runtime permission requests
*/
class PendingRequests {
private int currentReqId = 0;
private SparseArray<Request> requests = new SparseArray<Request>();
/**
* Creates a request and adds it to the array of pending requests. Each created request gets a
* unique result code for use with requestPermission()
* @param rawArgs The raw arguments passed to the plugin
* @param action The action this request corresponds to (get file, etc.)
* @param callbackContext The CallbackContext for this plugin call
* @return The request code that can be used to retrieve the Request object
*/
public synchronized int createRequest(String rawArgs, int action, CallbackContext callbackContext) {
Request req = new Request(rawArgs, action, callbackContext);
requests.put(req.requestCode, req);
return req.requestCode;
}
/**
* Gets the request corresponding to this request code and removes it from the pending requests
* @param requestCode The request code for the desired request
* @return The request corresponding to the given request code or null if such a
* request is not found
*/
public synchronized Request getAndRemove(int requestCode) {
Request result = requests.get(requestCode);
requests.remove(requestCode);
return result;
}
/**
* Holds the options and CallbackContext for a call made to the plugin.
*/
public class Request {
// Unique int used to identify this request in any Android permission callback
private int requestCode;
// Action to be performed after permission request result
private int action;
// Raw arguments passed to plugin
private String rawArgs;
// The callback context for this plugin request
private CallbackContext callbackContext;
private Request(String rawArgs, int action, CallbackContext callbackContext) {
this.rawArgs = rawArgs;
this.action = action;
this.callbackContext = callbackContext;
this.requestCode = currentReqId ++;
}
public int getAction() {
return this.action;
}
public String getRawArgs() {
return rawArgs;
}
public CallbackContext getCallbackContext() {
return callbackContext;
}
}
}
| 1,217 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/InvalidModificationException.java | /*
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.cordova.file;
@SuppressWarnings("serial")
public class InvalidModificationException extends Exception {
public InvalidModificationException(String message) {
super(message);
}
}
| 1,218 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/ContentFilesystem.java | /*
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.cordova.file;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONException;
import org.json.JSONObject;
public class ContentFilesystem extends Filesystem {
private final Context context;
public ContentFilesystem(Context context, CordovaResourceApi resourceApi, CordovaPreferences preferences) {
super(Uri.parse("content://"), "content", resourceApi, preferences);
this.context = context;
}
@Override
public Uri toNativeUri(LocalFilesystemURL inputURL) {
String encodedPath = inputURL.uri.getEncodedPath();
String authorityAndPath = encodedPath.substring(encodedPath.indexOf(this.name) + 1 + this.name.length() + 2);
if (authorityAndPath.length() < 2) {
return null;
}
String ret = "content://" + authorityAndPath;
String query = inputURL.uri.getEncodedQuery();
if (query != null) {
ret += '?' + query;
}
String frag = inputURL.uri.getEncodedFragment();
if (frag != null) {
ret += '#' + frag;
}
return Uri.parse(ret);
}
@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
if (!"content".equals(inputURL.getScheme())) {
return null;
}
String subPath = inputURL.getEncodedPath();
if (subPath.length() > 0) {
subPath = subPath.substring(1);
}
Uri.Builder b = createLocalUriBuilder().appendPath(inputURL.getAuthority());
if (subPath.length() > 0) {
b.appendEncodedPath(subPath);
}
Uri localUri = b.encodedQuery(inputURL.getEncodedQuery())
.encodedFragment(inputURL.getEncodedFragment())
.build();
return LocalFilesystemURL.parse(localUri);
}
@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException {
throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead.");
}
@Override
public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL)
throws NoModificationAllowedException {
Uri contentUri = toNativeUri(inputURL);
try {
context.getContentResolver().delete(contentUri, null, null);
} catch (UnsupportedOperationException t) {
// Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator.
// The ContentResolver applies only when the file was registered in the
// first case, which is generally only the case with images.
NoModificationAllowedException nmae = new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri);
nmae.initCause(t);
throw nmae;
}
return true;
}
@Override
public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL)
throws NoModificationAllowedException {
throw new NoModificationAllowedException("Cannot remove content url");
}
@Override
public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
throw new UnsupportedOperationException("readEntriesAtLocalURL() not supported for content:. Use resolveLocalFileSystemURL instead.");
}
@Override
public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
long size = -1;
long lastModified = 0;
Uri nativeUri = toNativeUri(inputURL);
String mimeType = resourceApi.getMimeType(nativeUri);
Cursor cursor = openCursorForURL(nativeUri);
try {
if (cursor != null && cursor.moveToFirst()) {
Long sizeForCursor = resourceSizeForCursor(cursor);
if (sizeForCursor != null) {
size = sizeForCursor.longValue();
}
Long modified = lastModifiedDateForCursor(cursor);
if (modified != null)
lastModified = modified.longValue();
} else {
// Some content providers don't support cursors at all!
CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(nativeUri);
size = offr.length;
}
} catch (IOException e) {
FileNotFoundException fnfe = new FileNotFoundException();
fnfe.initCause(e);
throw fnfe;
} finally {
if (cursor != null)
cursor.close();
}
JSONObject metadata = new JSONObject();
try {
metadata.put("size", size);
metadata.put("type", mimeType);
metadata.put("name", name);
metadata.put("fullPath", inputURL.path);
metadata.put("lastModifiedDate", lastModified);
} catch (JSONException e) {
return null;
}
return metadata;
}
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
int offset, boolean isBinary) throws NoModificationAllowedException {
throw new NoModificationAllowedException("Couldn't write to file given its content URI");
}
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
throws NoModificationAllowedException {
throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
}
protected Cursor openCursorForURL(Uri nativeUri) {
ContentResolver contentResolver = context.getContentResolver();
try {
return contentResolver.query(nativeUri, null, null, null, null);
} catch (UnsupportedOperationException e) {
return null;
}
}
private Long resourceSizeForCursor(Cursor cursor) {
int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
if (columnIndex != -1) {
String sizeStr = cursor.getString(columnIndex);
if (sizeStr != null) {
return Long.parseLong(sizeStr);
}
}
return null;
}
protected Long lastModifiedDateForCursor(Cursor cursor) {
int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED);
if (columnIndex == -1) {
columnIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED);
}
if (columnIndex != -1) {
String dateStr = cursor.getString(columnIndex);
if (dateStr != null) {
return Long.parseLong(dateStr);
}
}
return null;
}
@Override
public String filesystemPathForURL(LocalFilesystemURL url) {
File f = resourceApi.mapUriToFile(toNativeUri(url));
return f == null ? null : f.getAbsolutePath();
}
@Override
public LocalFilesystemURL URLforFilesystemPath(String path) {
// Returns null as we don't support reverse mapping back to content:// URLs
return null;
}
@Override
public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
return true;
}
}
| 1,219 |
0 | Create_ds/cordova-plugin-file/src | Create_ds/cordova-plugin-file/src/android/LocalFilesystemURL.java | /*
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.cordova.file;
import android.net.Uri;
public class LocalFilesystemURL {
public static final String FILESYSTEM_PROTOCOL = "cdvfile";
public static final String CDVFILE_KEYWORD = "__cdvfile_";
public final Uri uri;
public final String fsName;
public final String path;
public final boolean isDirectory;
private LocalFilesystemURL(Uri uri, String fsName, String fsPath, boolean isDirectory) {
this.uri = uri;
this.fsName = fsName;
this.path = fsPath;
this.isDirectory = isDirectory;
}
public static LocalFilesystemURL parse(Uri uri) {
if(!uri.toString().contains(CDVFILE_KEYWORD)) {
return null;
}
String path = uri.getPath();
if (path.length() < 1) {
return null;
}
int firstSlashIdx = path.indexOf('/', 1);
if (firstSlashIdx < 0) {
return null;
}
String fsName = path.substring(1, firstSlashIdx);
fsName = fsName.substring(CDVFILE_KEYWORD.length());
fsName = fsName.substring(0, fsName.length() - 2);
path = path.substring(firstSlashIdx);
boolean isDirectory = path.charAt(path.length() - 1) == '/';
return new LocalFilesystemURL(uri, fsName, path, isDirectory);
}
public static LocalFilesystemURL parse(String uri) {
return parse(Uri.parse(uri));
}
public static String fsNameToCdvKeyword(String fsName) { return CDVFILE_KEYWORD + fsName + "__"; }
public String toString() {
return uri.toString();
}
}
| 1,220 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static software.amazon.awssdk.http.Header.ACCEPT;
import static software.amazon.awssdk.http.Header.CHUNKED;
import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import java.io.IOException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import org.junit.After;
import org.junit.Test;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientTestSuite;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.utils.AttributeMap;
public final class UrlConnectionHttpClientWireMockTest extends SdkHttpClientTestSuite {
@Override
protected SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options) {
UrlConnectionHttpClient.Builder builder = UrlConnectionHttpClient.builder();
AttributeMap.Builder attributeMap = AttributeMap.builder();
if (options.tlsTrustManagersProvider() != null) {
builder.tlsTrustManagersProvider(options.tlsTrustManagersProvider());
}
if (options.trustAll()) {
attributeMap.put(TRUST_ALL_CERTIFICATES, options.trustAll());
}
return builder.buildWithDefaults(attributeMap.build());
}
@Override
public void connectionsAreNotReusedOn5xxErrors() {
// We cannot support this because the URL connection client doesn't allow us to disable connection reuse
}
// https://bugs.openjdk.org/browse/JDK-8163921
@Test
public void noAcceptHeader_shouldSet() throws IOException {
SdkHttpClient client = createSdkHttpClient();
stubForMockRequest(200);
SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST);
HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider()
.orElse(null))
.build())
.call();
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withHeader(ACCEPT, equalTo("*/*")));
}
@Test
public void hasAcceptHeader_shouldNotOverride() throws IOException {
SdkHttpClient client = createSdkHttpClient();
stubForMockRequest(200);
SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST);
req = req.toBuilder().putHeader(ACCEPT, "text/html").build();
HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider()
.orElse(null))
.build())
.call();
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withHeader(ACCEPT, equalTo("text/html")));
}
@Test
public void hasTransferEncodingHeader_shouldBeSet() throws IOException {
SdkHttpClient client = createSdkHttpClient();
stubForMockRequest(200);
SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST);
req = req.toBuilder().putHeader(TRANSFER_ENCODING, CHUNKED).build();
HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider()
.orElse(null))
.build())
.call();
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withHeader(TRANSFER_ENCODING, equalTo(CHUNKED)));
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withRequestBody(equalTo("Body")));
}
@After
public void reset() {
HttpsURLConnection.setDefaultSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
}
}
| 1,221 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/Expect100ContinueTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.Level;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.Test;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.testutils.LogCaptor;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.StringInputStream;
public class Expect100ContinueTest {
@Test
public void expect100ContinueWorksWithZeroContentLength200() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(200);
response.setContentLength(0);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(200);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWith204() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(204);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(204);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWith304() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(304);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(304);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWith417() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(417);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(417);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWithZeroContentLength500() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(500);
response.setContentLength(0);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(500);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWithPositiveContentLength500() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(500);
response.setContentLength(5);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (LogCaptor logCaptor = LogCaptor.create(Level.DEBUG);
SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(500);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
assertThat(logCaptor.loggedEvents()).anySatisfy(logEvent -> {
assertThat(logEvent.getLevel()).isEqualTo(Level.DEBUG);
assertThat(logEvent.getMessage().getFormattedMessage()).contains("response payload has been dropped");
});
}
}
@Test
public void expect100ContinueWorksWithPositiveContentLength400() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(400);
response.setContentLength(5);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (LogCaptor logCaptor = LogCaptor.create(Level.DEBUG);
SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(400);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
assertThat(logCaptor.loggedEvents()).anySatisfy(logEvent -> {
assertThat(logEvent.getLevel()).isEqualTo(Level.DEBUG);
assertThat(logEvent.getMessage().getFormattedMessage()).contains("response payload has been dropped");
});
}
}
@Test
public void expect100ContinueFailsWithPositiveContentLength200() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(200);
response.setContentLength(1);
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
assertThatThrownBy(() -> sendRequest(client, server)).isInstanceOf(UncheckedIOException.class);
}
}
@Test
public void expect100ContinueFailsWithChunkedEncoded200() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(200);
response.addHeader("Transfer-Encoding", "chunked");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
assertThatThrownBy(() -> sendRequest(client, server)).isInstanceOf(UncheckedIOException.class);
}
}
private HttpExecuteResponse sendRequest(SdkHttpClient client, EmbeddedServer server) throws IOException {
return client.prepareRequest(HttpExecuteRequest.builder()
.request(SdkHttpRequest.builder()
.uri(server.uri())
.putHeader("Expect", "100-continue")
.putHeader("Content-Length", "0")
.method(SdkHttpMethod.PUT)
.build())
.contentStreamProvider(() -> new StringInputStream(""))
.build())
.call();
}
private static class EmbeddedServer implements SdkAutoCloseable {
private final Server server;
public EmbeddedServer(Handler handler) throws Exception {
server = new Server(0);
server.setHandler(handler);
server.start();
}
public URI uri() {
return server.getURI();
}
@Override
public void close() {
try {
server.stop();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| 1,222 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientDefaultWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import org.junit.jupiter.api.AfterEach;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientDefaultTestSuite;
public class UrlConnectionHttpClientDefaultWireMockTest extends SdkHttpClientDefaultTestSuite {
@Override
protected SdkHttpClient createSdkHttpClient() {
return UrlConnectionHttpClient.create();
}
@AfterEach
public void reset() {
HttpsURLConnection.setDefaultSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
}
}
| 1,223 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import java.util.Set;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class UrlProxyConfigurationTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings, TestProxySetting expectedProxySettings,
Boolean useSystemProperty, Boolean useEnvironmentVariable, String protocol) throws URISyntaxException {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
Set<String> nonProxyHosts = userSetProxySettings.getNonProxyHosts();
if (hostName != null && portNumber != null) {
builder.endpoint(URI.create(String.format("%s://%s:%d", protocol, hostName, portNumber)));
}
Optional.ofNullable(userName).ifPresent(builder::username);
Optional.ofNullable(password).ifPresent(builder::password);
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
builder.nonProxyHosts(nonProxyHosts);
}
}
if (!"http".equals(protocol)) {
builder.scheme(protocol);
}
if (useSystemProperty != null) {
builder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
builder.useEnvironmentVariablesValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = builder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
assertThat(proxyConfiguration.nonProxyHosts()).isEqualTo(expectedProxySettings.getNonProxyHosts());
}
}
| 1,224 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ProxyConfigurationTest {
@AfterAll
public static void cleanup() {
clearProxyProperties();
}
private static void clearProxyProperties() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.nonProxyHosts");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
}
@BeforeEach
public void setup() {
clearProxyProperties();
}
@Test
void testEndpointValues_SystemPropertyEnabled() {
String host = "foo.com";
int port = 7777;
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", Integer.toString(port));
ProxyConfiguration config = ProxyConfiguration.builder().useSystemPropertyValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testEndpointValues_SystemPropertyDisabled() {
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testProxyConfigurationWithSystemPropertyDisabled() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.nonProxyHosts(nonProxyHosts)
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.username()).isNull();
}
@Test
void testProxyConfigurationWithSystemPropertyEnabled() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.nonProxyHosts(nonProxyHosts)
.build();
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.host()).isEqualTo("foo.com");
assertThat(config.username()).isEqualTo("user");
}
@Test
void testProxyConfigurationWithoutNonProxyHosts_toBuilder_shouldNotThrowNPE() {
ProxyConfiguration proxyConfiguration =
ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:4321"))
.username("username")
.password("password")
.build();
assertThat(proxyConfiguration.toBuilder()).isNotNull();
}
}
| 1,225 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientWithCustomCreateWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.FunctionalUtils.safeFunction;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.security.Permission;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.junit.Ignore;
import org.junit.Test;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientTestSuite;
public final class UrlConnectionHttpClientWithCustomCreateWireMockTest extends SdkHttpClientTestSuite {
private Function<HttpURLConnection, HttpURLConnection> connectionInterceptor = Function.identity();
@Override
protected SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options) {
return UrlConnectionHttpClient.create(uri -> invokeSafely(() -> {
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
return connectionInterceptor.apply(connection);
}));
}
// Empty test; behavior not supported when using custom factory
@Override
public void testCustomTlsTrustManager() {
}
// Empty test; behavior not supported when using custom factory
@Override
public void testTrustAllWorks() {
}
// Empty test; behavior not supported when using custom factory
@Override
public void testCustomTlsTrustManagerAndTrustAllFails() {
}
// Empty test; behavior not supported because the URL connection client does not allow disabling connection reuse
@Override
public void connectionsAreNotReusedOn5xxErrors() throws Exception {
}
@Test
public void testGetResponseCodeNpeIsWrappedAsIo() throws Exception {
connectionInterceptor = safeFunction(connection -> new DelegateHttpURLConnection(connection) {
@Override
public int getResponseCode() {
throw new NullPointerException();
}
});
assertThatThrownBy(() -> testForResponseCode(HttpURLConnection.HTTP_OK))
.isInstanceOf(IOException.class)
.hasMessage("Unexpected NullPointerException when trying to read response from HttpURLConnection")
.hasCauseInstanceOf(NullPointerException.class);
}
private class DelegateHttpURLConnection extends HttpURLConnection {
private final HttpURLConnection delegate;
private DelegateHttpURLConnection(HttpURLConnection delegate) {
super(delegate.getURL());
this.delegate = delegate;
}
@Override
public String getHeaderFieldKey(int n) {
return delegate.getHeaderFieldKey(n);
}
@Override
public void setFixedLengthStreamingMode(int contentLength) {
delegate.setFixedLengthStreamingMode(contentLength);
}
@Override
public void setFixedLengthStreamingMode(long contentLength) {
delegate.setFixedLengthStreamingMode(contentLength);
}
@Override
public void setChunkedStreamingMode(int chunklen) {
delegate.setChunkedStreamingMode(chunklen);
}
@Override
public String getHeaderField(int n) {
return delegate.getHeaderField(n);
}
@Override
public void setInstanceFollowRedirects(boolean followRedirects) {
delegate.setInstanceFollowRedirects(followRedirects);
}
@Override
public boolean getInstanceFollowRedirects() {
return delegate.getInstanceFollowRedirects();
}
@Override
public void setRequestMethod(String method) throws ProtocolException {
delegate.setRequestMethod(method);
}
@Override
public String getRequestMethod() {
return delegate.getRequestMethod();
}
@Override
public int getResponseCode() throws IOException {
return delegate.getResponseCode();
}
@Override
public String getResponseMessage() throws IOException {
return delegate.getResponseMessage();
}
@Override
public long getHeaderFieldDate(String name, long Default) {
return delegate.getHeaderFieldDate(name, Default);
}
@Override
public void disconnect() {
delegate.disconnect();
}
@Override
public boolean usingProxy() {
return delegate.usingProxy();
}
@Override
public Permission getPermission() throws IOException {
return delegate.getPermission();
}
@Override
public InputStream getErrorStream() {
return delegate.getErrorStream();
}
@Override
public void connect() throws IOException {
delegate.connect();
}
@Override
public void setConnectTimeout(int timeout) {
delegate.setConnectTimeout(timeout);
}
@Override
public int getConnectTimeout() {
return delegate.getConnectTimeout();
}
@Override
public void setReadTimeout(int timeout) {
delegate.setReadTimeout(timeout);
}
@Override
public int getReadTimeout() {
return delegate.getReadTimeout();
}
@Override
public URL getURL() {
return delegate.getURL();
}
@Override
public int getContentLength() {
return delegate.getContentLength();
}
@Override
public long getContentLengthLong() {
return delegate.getContentLengthLong();
}
@Override
public String getContentType() {
return delegate.getContentType();
}
@Override
public String getContentEncoding() {
return delegate.getContentEncoding();
}
@Override
public long getExpiration() {
return delegate.getExpiration();
}
@Override
public long getDate() {
return delegate.getDate();
}
@Override
public long getLastModified() {
return delegate.getLastModified();
}
@Override
public String getHeaderField(String name) {
return delegate.getHeaderField(name);
}
@Override
public Map<String, List<String>> getHeaderFields() {
return delegate.getHeaderFields();
}
@Override
public int getHeaderFieldInt(String name, int Default) {
return delegate.getHeaderFieldInt(name, Default);
}
@Override
public long getHeaderFieldLong(String name, long Default) {
return delegate.getHeaderFieldLong(name, Default);
}
@Override
public Object getContent() throws IOException {
return delegate.getContent();
}
@Override
public InputStream getInputStream() throws IOException {
return delegate.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return delegate.getOutputStream();
}
@Override
public String toString() {
return delegate.toString();
}
@Override
public void setDoInput(boolean doinput) {
delegate.setDoInput(doinput);
}
@Override
public boolean getDoInput() {
return delegate.getDoInput();
}
@Override
public void setDoOutput(boolean dooutput) {
delegate.setDoOutput(dooutput);
}
@Override
public boolean getDoOutput() {
return delegate.getDoOutput();
}
@Override
public void setAllowUserInteraction(boolean allowuserinteraction) {
delegate.setAllowUserInteraction(allowuserinteraction);
}
@Override
public boolean getAllowUserInteraction() {
return delegate.getAllowUserInteraction();
}
@Override
public void setUseCaches(boolean usecaches) {
delegate.setUseCaches(usecaches);
}
@Override
public boolean getUseCaches() {
return delegate.getUseCaches();
}
@Override
public void setIfModifiedSince(long ifmodifiedsince) {
delegate.setIfModifiedSince(ifmodifiedsince);
}
@Override
public long getIfModifiedSince() {
return delegate.getIfModifiedSince();
}
@Override
public boolean getDefaultUseCaches() {
return delegate.getDefaultUseCaches();
}
@Override
public void setDefaultUseCaches(boolean defaultusecaches) {
delegate.setDefaultUseCaches(defaultusecaches);
}
@Override
public void setRequestProperty(String key, String value) {
delegate.setRequestProperty(key, value);
}
@Override
public void addRequestProperty(String key, String value) {
delegate.addRequestProperty(key, value);
}
@Override
public String getRequestProperty(String key) {
return delegate.getRequestProperty(key);
}
@Override
public Map<String, List<String>> getRequestProperties() {
return delegate.getRequestProperties();
}
}
}
| 1,226 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientWithProxyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.requestMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.mockito.ArgumentMatchers.anyString;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.matching.MatchResult;
import java.io.IOException;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.AttributeMap;
class UrlConnectionHttpClientWithProxyTest {
@RegisterExtension
static WireMockExtension httpsWm = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.configureStaticDsl(true)
.build();
@RegisterExtension
static WireMockExtension httpWm = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort())
.proxyMode(true)
.build();
private SdkHttpClient client;
@Test
void Http_ProxyCallFrom_Https_Client_getsRejectedWith_404() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
WireMockRuntimeInfo wireMockRuntimeInfoHttp = httpsWm.getRuntimeInfo();
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder()
.endpoint(URI.create(httpWm.getRuntimeInfo().getHttpBaseUrl()))
.build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttps_Client(client, wireMockRuntimeInfoHttp);
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(404);
}
@Test
void Http_ProxyCallFromWithDenyList_HttpsClient_bypassesProxy_AndReturns_OK() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
WireMockRuntimeInfo wireMockRuntimeInfoHttp = httpsWm.getRuntimeInfo();
Set<String> nonProxyHost = new HashSet<>();
nonProxyHost.add(httpWm.getRuntimeInfo().getHttpBaseUrl());
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder()
.endpoint(URI.create(httpWm.getRuntimeInfo().getHttpBaseUrl()))
.nonProxyHosts(nonProxyHost)
.build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttps_Client(client, wireMockRuntimeInfoHttp);
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
}
@Test
void emptyProxyConfig_Https_Client_byPassesProxy_dReturns_OK() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
httpsWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
WireMockRuntimeInfo wireMockRuntimeInfoHttp = httpsWm.getRuntimeInfo();
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder().build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttps_Client(client, wireMockRuntimeInfoHttp);
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
}
@Test
void http_ProxyCallFrom_Http_Client_isAcceptedByHttpProxy_AndReturns_OK() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
httpsWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder()
.endpoint(URI.create(httpWm.getRuntimeInfo().getHttpBaseUrl()))
.build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttp_Client(client, httpWm.getRuntimeInfo());
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
}
private HttpExecuteResponse makeRequestWithHttps_Client(SdkHttpClient httpClient, WireMockRuntimeInfo wm) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost:" + wm.getHttpsPort())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.build();
return httpClient.prepareRequest(request).call();
}
private HttpExecuteResponse makeRequestWithHttp_Client(SdkHttpClient httpClient, WireMockRuntimeInfo wm) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host(wm.getHttpBaseUrl())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.build();
return httpClient.prepareRequest(request).call();
}
private SdkHttpClient createHttpsClientForHttpServer(ProxyConfiguration proxyConfiguration) {
UrlConnectionHttpClient.Builder builder =
UrlConnectionHttpClient.builder().proxyConfiguration(proxyConfiguration);
AttributeMap.Builder attributeMap = AttributeMap.builder();
attributeMap.put(TRUST_ALL_CERTIFICATES, true);
return builder.buildWithDefaults(attributeMap.build());
}
}
| 1,227 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/S3WithUrlHttpClientIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.AwsTestBase.CREDENTIALS_PROVIDER_CHAIN;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpHeaders;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class S3WithUrlHttpClientIntegrationTest {
/**
* The name of the bucket created, used, and deleted by these tests.
*/
private static final String BUCKET_NAME = "java-sdk-integ-" + System.currentTimeMillis();
private static final String KEY = "key";
private static final Region REGION = Region.US_WEST_2;
private static final CapturingInterceptor capturingInterceptor = new CapturingInterceptor();
private static final String SIGNED_PAYLOAD_HEADER_VALUE = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
private static final String UNSIGNED_PAYLOAD_HEADER_VALUE = "UNSIGNED-PAYLOAD";
private static S3Client s3;
private static S3Client s3Http;
/**
* Creates all the test resources for the tests.
*/
@BeforeAll
public static void createResources() throws Exception {
S3ClientBuilder s3ClientBuilder = S3Client.builder()
.region(REGION)
.httpClient(UrlConnectionHttpClient.builder().build())
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.overrideConfiguration(o -> o.addExecutionInterceptor(new UserAgentVerifyingInterceptor())
.addExecutionInterceptor(capturingInterceptor));
s3 = s3ClientBuilder.build();
s3Http = s3ClientBuilder.endpointOverride(URI.create("http://s3.us-west-2.amazonaws.com"))
.build();
createBucket(BUCKET_NAME, REGION);
}
/**
* Releases all resources created in this test.
*/
@AfterAll
public static void tearDown() {
deleteObject(BUCKET_NAME, KEY);
deleteBucket(BUCKET_NAME);
}
@BeforeEach
public void methodSetup() {
capturingInterceptor.reset();
}
@Test
public void verifyPutObject() {
assertThat(objectCount(BUCKET_NAME)).isEqualTo(0);
s3.putObject(PutObjectRequest.builder().bucket(BUCKET_NAME).key(KEY).build(), RequestBody.fromString("foobar"));
assertThat(objectCount(BUCKET_NAME)).isEqualTo(1);
assertThat(getSha256Values()).contains(UNSIGNED_PAYLOAD_HEADER_VALUE);
}
@Test
public void verifyPutObject_httpCauses_payloadSigning() {
s3Http.putObject(PutObjectRequest.builder().bucket(BUCKET_NAME).key(KEY).build(), RequestBody.fromString("foobar"));
assertThat(getSha256Values()).contains(SIGNED_PAYLOAD_HEADER_VALUE);
}
private static void createBucket(String bucket, Region region) {
s3.createBucket(CreateBucketRequest
.builder()
.bucket(bucket)
.createBucketConfiguration(
CreateBucketConfiguration.builder()
.locationConstraint(region.id())
.build())
.build());
}
private static void deleteObject(String bucket, String key) {
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder().bucket(bucket).key(key).build();
s3.deleteObject(deleteObjectRequest);
}
private static void deleteBucket(String bucket) {
DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);
}
private int objectCount(String bucket) {
ListObjectsV2Request listReq = ListObjectsV2Request.builder()
.bucket(bucket)
.build();
return s3.listObjectsV2(listReq).keyCount();
}
private List<String> getSha256Values() {
return capturingInterceptor.capturedRequests().stream()
.map(SdkHttpHeaders::headers)
.map(m -> m.getOrDefault("x-amz-content-sha256", Collections.emptyList()))
.flatMap(Collection::stream).collect(Collectors.toList());
}
private static final class UserAgentVerifyingInterceptor implements ExecutionInterceptor {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("io/sync");
assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("http/UrlConnection");
}
}
private static class CapturingInterceptor implements ExecutionInterceptor {
private final List<SdkHttpRequest> capturedRequests = new ArrayList<>();
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
capturedRequests.add(context.httpRequest());
}
public void reset() {
capturedRequests.clear();
}
public List<SdkHttpRequest> capturedRequests() {
return capturedRequests;
}
}
}
| 1,228 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/UrlHttpConnectionS3IntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.testutils.Waiter;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Base class for S3 integration tests. Loads AWS credentials from a properties
* file and creates an S3 client for callers to use.
*/
public class UrlHttpConnectionS3IntegrationTestBase extends AwsTestBase {
protected static final Region DEFAULT_REGION = Region.US_WEST_2;
/**
* The S3 client for all tests to use.
*/
protected static S3Client s3;
/**
* Loads the AWS account info for the integration tests and creates an S3
* client for tests to use.
*/
@BeforeAll
public static void setUp() throws Exception {
s3 = s3ClientBuilder().build();
}
protected static S3ClientBuilder s3ClientBuilder() {
return S3Client.builder()
.httpClient(UrlConnectionHttpClient.create())
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN);
}
protected static void createBucket(String bucket) {
Waiter.run(() -> s3.createBucket(r -> r.bucket(bucket)))
.ignoringException(NoSuchBucketException.class)
.orFail();
s3.waiter().waitUntilBucketExists(r -> r.bucket(bucket));
}
protected static void deleteBucketAndAllContents(String bucketName) {
deleteBucketAndAllContents(s3, bucketName);
}
public static void deleteBucketAndAllContents(S3Client s3, String bucketName) {
try {
System.out.println("Deleting S3 bucket: " + bucketName);
ListObjectsResponse response = Waiter.run(() -> s3.listObjects(r -> r.bucket(bucketName)))
.ignoringException(NoSuchBucketException.class)
.orFail();
List<S3Object> objectListing = response.contents();
if (objectListing != null) {
while (true) {
for (Iterator<?> iterator = objectListing.iterator(); iterator.hasNext(); ) {
S3Object objectSummary = (S3Object) iterator.next();
s3.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build());
}
if (response.isTruncated()) {
objectListing = s3.listObjects(ListObjectsRequest.builder()
.bucket(bucketName)
.marker(response.marker())
.build())
.contents();
} else {
break;
}
}
}
ListObjectVersionsResponse versions = s3
.listObjectVersions(ListObjectVersionsRequest.builder().bucket(bucketName).build());
if (versions.deleteMarkers() != null) {
versions.deleteMarkers().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder()
.versionId(v.versionId())
.bucket(bucketName)
.key(v.key())
.build()));
}
if (versions.versions() != null) {
versions.versions().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder()
.versionId(v.versionId())
.bucket(bucketName)
.key(v.key())
.build()));
}
s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build());
} catch (Exception e) {
System.err.println("Failed to delete bucket: " + bucketName);
e.printStackTrace();
}
}
}
| 1,229 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/HeadObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.zip.GZIPOutputStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class HeadObjectIntegrationTest extends UrlHttpConnectionS3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(HeadObjectIntegrationTest.class);
private static final String GZIPPED_KEY = "some-key";
@BeforeAll
public static void setupFixture() throws IOException {
createBucket(BUCKET);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write("Test".getBytes(StandardCharsets.UTF_8));
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(GZIPPED_KEY)
.contentEncoding("gzip")
.build(),
RequestBody.fromBytes(baos.toByteArray()));
}
@Test
public void syncClientSupportsGzippedObjects() {
HeadObjectResponse response = s3.headObject(r -> r.bucket(BUCKET).key(GZIPPED_KEY));
assertThat(response.contentEncoding()).isEqualTo("gzip");
}
@Test
public void syncClient_throwsRightException_withGzippedObjects() {
assertThrows(NoSuchKeyException.class,
() -> s3.headObject(r -> r.bucket(BUCKET + UUID.randomUUID()).key(GZIPPED_KEY)));
}
@AfterAll
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
}
}
| 1,230 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/EmptyFileS3IntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
public class EmptyFileS3IntegrationTest extends UrlHttpConnectionS3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(EmptyFileS3IntegrationTest.class);
@BeforeAll
public static void setup() {
createBucket(BUCKET);
}
@AfterAll
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void s3EmptyFileGetAsBytesWorksWithoutChecksumValidationEnabled() {
try (S3Client s3 = s3ClientBuilder().serviceConfiguration(c -> c.checksumValidationEnabled(false))
.build()) {
s3.putObject(r -> r.bucket(BUCKET).key("x"), RequestBody.empty());
assertThat(s3.getObjectAsBytes(r -> r.bucket(BUCKET).key("x")).asUtf8String()).isEmpty();
}
}
@Test
public void s3EmptyFileContentLengthIsCorrectWithoutChecksumValidationEnabled() {
try (S3Client s3 = s3ClientBuilder().serviceConfiguration(c -> c.checksumValidationEnabled(false))
.build()) {
s3.putObject(r -> r.bucket(BUCKET).key("x"), RequestBody.empty());
assertThat(s3.getObject(r -> r.bucket(BUCKET).key("x")).response().contentLength()).isEqualTo(0);
}
}
}
| 1,231 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/UrlConnectionFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import java.net.HttpURLConnection;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An interface that, given a {@link URI} creates a new {@link HttpURLConnection}. This allows customization
* of the creation and configuration of the {@link HttpURLConnection}.
*/
@FunctionalInterface
@SdkPublicApi
public interface UrlConnectionFactory {
/**
* For the given {@link URI} create an {@link HttpURLConnection}.
* @param uri the {@link URI} of the request
* @return a {@link HttpURLConnection} to the given {@link URI}
*/
HttpURLConnection createConnection(URI uri);
}
| 1,232 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/ProxyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static software.amazon.awssdk.utils.StringUtils.isEmpty;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ProxyConfigProvider;
import software.amazon.awssdk.utils.ProxyEnvironmentSetting;
import software.amazon.awssdk.utils.ProxySystemSetting;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Proxy configuration for {@link UrlConnectionHttpClient}. This class is used to configure an HTTP proxy to be used by
* the {@link UrlConnectionHttpClient}.
*
* @see UrlConnectionHttpClient.Builder#proxyConfiguration(ProxyConfiguration)
*/
@SdkPublicApi
public final class ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private final URI endpoint;
private final String username;
private final String password;
private final Set<String> nonProxyHosts;
private final String host;
private final int port;
private final String scheme;
private final boolean useSystemPropertyValues;
private final boolean useEnvironmentVariablesValues;
/**
* Initialize this configuration. Private to require use of {@link #builder()}.
*/
private ProxyConfiguration(DefaultClientProxyConfigurationBuilder builder) {
this.endpoint = builder.endpoint;
String resolvedScheme = resolveScheme(builder);
this.scheme = resolvedScheme;
ProxyConfigProvider proxyConfigProvider =
ProxyConfigProvider.fromSystemEnvironmentSettings(
builder.useSystemPropertyValues,
builder.useEnvironmentVariablesValues,
resolvedScheme);
this.username = resolveUsername(builder, proxyConfigProvider);
this.password = resolvePassword(builder, proxyConfigProvider);
this.nonProxyHosts = resolveNonProxyHosts(builder, proxyConfigProvider);
this.useSystemPropertyValues = builder.useSystemPropertyValues;
if (builder.endpoint != null) {
this.host = builder.endpoint.getHost();
this.port = builder.endpoint.getPort();
} else {
this.host = proxyConfigProvider != null ? proxyConfigProvider.host() : null;
this.port = proxyConfigProvider != null ? proxyConfigProvider.port() : 0;
}
this.useEnvironmentVariablesValues = builder.useEnvironmentVariablesValues;
}
private String resolveScheme(DefaultClientProxyConfigurationBuilder builder) {
if (endpoint != null) {
return endpoint.getScheme();
} else {
return builder.scheme;
}
}
private static String resolvePassword(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfigProvider) {
if (builder.password != null || proxyConfigProvider == null) {
return builder.password;
}
return proxyConfigProvider.password().orElseGet(() -> builder.password);
}
private static Set<String> resolveNonProxyHosts(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfigProvider) {
return builder.nonProxyHosts != null || proxyConfigProvider == null ? builder.nonProxyHosts :
proxyConfigProvider.nonProxyHosts();
}
private static String resolveUsername(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfigProvider) {
if (builder.username != null || proxyConfigProvider == null) {
return builder.username;
}
return proxyConfigProvider.userName().orElseGet(() -> builder.username);
}
/**
* Returns the proxy host name either from the configured endpoint or
* from the "http.proxyHost" system property if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
*/
public String host() {
return host;
}
/**
* Returns the proxy port either from the configured endpoint or
* from the "http.proxyPort" system property if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
*
* If no value is found in neither of the above options, the default value of 0 is returned.
*/
public int port() {
return port;
}
/**
* Returns the {@link URI#scheme} from the configured endpoint. Otherwise return null.
*/
public String scheme() {
return scheme;
}
/**
* The username to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String username() {
return username;
}
/**
* The password to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String password() {
return password;
}
/**
* The hosts that the client is allowed to access without going through the proxy.
*
* If the value is not set on the object, the value represent by "http.nonProxyHosts" system property is returned.
* If system property is also not set, an unmodifiable empty set is returned.
*
* @see Builder#nonProxyHosts(Set)
*/
public Set<String> nonProxyHosts() {
return Collections.unmodifiableSet(nonProxyHosts != null ? nonProxyHosts : Collections.emptySet());
}
@Override
public Builder toBuilder() {
return builder()
.endpoint(endpoint)
.username(username)
.password(password)
.nonProxyHosts(nonProxyHosts)
.useSystemPropertyValues(useSystemPropertyValues)
.scheme(scheme)
.useEnvironmentVariablesValues(useEnvironmentVariablesValues);
}
/**
* Create a {@link Builder}, used to create a {@link ProxyConfiguration}.
*/
public static Builder builder() {
return new DefaultClientProxyConfigurationBuilder();
}
@Override
public String toString() {
return ToString.builder("ProxyConfiguration")
.add("endpoint", endpoint)
.add("username", username)
.add("nonProxyHosts", nonProxyHosts)
.build();
}
public String resolveScheme() {
return endpoint != null ? endpoint.getScheme() : scheme;
}
/**
* A builder for {@link ProxyConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder extends CopyableBuilder<Builder, ProxyConfiguration> {
/**
* Configure the endpoint of the proxy server that the SDK should connect through. Currently, the endpoint is limited to
* a host and port. Any other URI components will result in an exception being raised.
*/
Builder endpoint(URI endpoint);
/**
* Configure the username to use when connecting through a proxy.
*/
Builder username(String username);
/**
* Configure the password to use when connecting through a proxy.
*/
Builder password(String password);
/**
* Configure the hosts that the client is allowed to access without going through the proxy.
*/
Builder nonProxyHosts(Set<String> nonProxyHosts);
/**
* Add a host that the client is allowed to access without going through the proxy.
*
* @see ProxyConfiguration#nonProxyHosts()
*/
Builder addNonProxyHost(String nonProxyHost);
/**
* Option whether to use system property values from {@link ProxySystemSetting} if any of the config options are missing.
* <p>
* This value is set to "true" by default which means SDK will automatically use system property values for options that
* are not provided during building the {@link ProxyConfiguration} object. To disable this behavior, set this value to
* "false".It is important to note that when this property is set to "true," all proxy settings will exclusively originate
* from system properties, and no partial settings will be obtained from EnvironmentVariableValues
*/
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
/**
* Option whether to use environment variable values from {@link ProxyEnvironmentSetting} if any of the config options are
* missing. This value is set to "true" by default, which means SDK will automatically use environment variable values for
* options that are not provided during building the {@link ProxyConfiguration} object. To disable this behavior, set this
* value to "false".It is important to note that when this property is set to "true," all proxy settings will exclusively
* originate from environment variableValues, and no partial settings will be obtained from SystemPropertyValues.
*
* @param useEnvironmentVariablesValues The option whether to use environment variable values
* @return This object for method chaining.
*/
Builder useEnvironmentVariablesValues(Boolean useEnvironmentVariablesValues);
/**
* The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}.
* <p>
* The client defaults to {@code http} if none is given.
*
* @param scheme The proxy scheme.
* @return This object for method chaining.
*/
Builder scheme(String scheme);
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultClientProxyConfigurationBuilder implements Builder {
private URI endpoint;
private String username;
private String scheme = "http";
private String password;
private Set<String> nonProxyHosts;
private Boolean useSystemPropertyValues = Boolean.TRUE;
private Boolean useEnvironmentVariablesValues = Boolean.TRUE;
@Override
public Builder endpoint(URI endpoint) {
if (endpoint != null) {
Validate.isTrue(isEmpty(endpoint.getUserInfo()), "Proxy endpoint user info is not supported.");
Validate.isTrue(isEmpty(endpoint.getPath()), "Proxy endpoint path is not supported.");
Validate.isTrue(isEmpty(endpoint.getQuery()), "Proxy endpoint query is not supported.");
Validate.isTrue(isEmpty(endpoint.getFragment()), "Proxy endpoint fragment is not supported.");
}
this.endpoint = endpoint;
return this;
}
public void setEndpoint(URI endpoint) {
endpoint(endpoint);
}
@Override
public Builder username(String username) {
this.username = username;
return this;
}
public void setUsername(String username) {
username(username);
}
@Override
public Builder password(String password) {
this.password = password;
return this;
}
public void setPassword(String password) {
password(password);
}
@Override
public Builder nonProxyHosts(Set<String> nonProxyHosts) {
this.nonProxyHosts = nonProxyHosts != null ? new HashSet<>(nonProxyHosts) : null;
return this;
}
@Override
public Builder addNonProxyHost(String nonProxyHost) {
if (this.nonProxyHosts == null) {
this.nonProxyHosts = new HashSet<>();
}
this.nonProxyHosts.add(nonProxyHost);
return this;
}
public void setNonProxyHosts(Set<String> nonProxyHosts) {
nonProxyHosts(nonProxyHosts);
}
@Override
public Builder useSystemPropertyValues(Boolean useSystemPropertyValues) {
this.useSystemPropertyValues = useSystemPropertyValues;
return this;
}
public void setUseSystemPropertyValues(Boolean useSystemPropertyValues) {
useSystemPropertyValues(useSystemPropertyValues);
}
@Override
public Builder useEnvironmentVariablesValues(Boolean useEnvironmentVariablesValues) {
this.useEnvironmentVariablesValues = useEnvironmentVariablesValues;
return this;
}
@Override
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
public void setScheme(String scheme) {
scheme(scheme);
}
public void setUseEnvironmentVariablesValues(Boolean useEnvironmentVariablesValues) {
useEnvironmentVariablesValues(useEnvironmentVariablesValues);
}
@Override
public ProxyConfiguration build() {
return new ProxyConfiguration(this);
}
}
}
| 1,233 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static software.amazon.awssdk.http.Header.ACCEPT;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.HttpStatusFamily.CLIENT_ERROR;
import static software.amazon.awssdk.http.HttpStatusFamily.SERVER_ERROR;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkHttpClient} that uses {@link HttpURLConnection} to communicate with the service. This is the
* leanest synchronous client that optimizes for minimum dependencies and startup latency in exchange for having less
* functionality than other implementations.
*
* <p>See software.amazon.awssdk.http.apache.ApacheHttpClient for an alternative implementation.</p>
*
* <p>This can be created via {@link #builder()}</p>
*/
@SdkPublicApi
public final class UrlConnectionHttpClient implements SdkHttpClient {
private static final Logger log = Logger.loggerFor(UrlConnectionHttpClient.class);
private static final String CLIENT_NAME = "UrlConnection";
private final AttributeMap options;
private final UrlConnectionFactory connectionFactory;
private final ProxyConfiguration proxyConfiguration;
private UrlConnectionHttpClient(AttributeMap options, UrlConnectionFactory connectionFactory, DefaultBuilder builder) {
this.options = options;
this.proxyConfiguration = builder != null ? builder.proxyConfiguration : null;
if (connectionFactory != null) {
this.connectionFactory = connectionFactory;
} else {
// Note: This socket factory MUST be reused between requests because the connection pool in the JVM is keyed by both
// URL and SSLSocketFactory. If the socket factory is not reused, connections will not be reused between requests.
SSLSocketFactory socketFactory = getSslContext(options).getSocketFactory();
this.connectionFactory = url -> createDefaultConnection(url, socketFactory);
}
}
private UrlConnectionHttpClient(AttributeMap options, UrlConnectionFactory connectionFactory) {
this(options, connectionFactory, null);
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Create a {@link HttpURLConnection} client with the default properties
*
* @return an {@link UrlConnectionHttpClient}
*/
public static SdkHttpClient create() {
return new DefaultBuilder().build();
}
/**
* Use this method if you want to control the way a {@link HttpURLConnection} is created.
* This will ignore SDK defaults like {@link SdkHttpConfigurationOption#CONNECTION_TIMEOUT}
* and {@link SdkHttpConfigurationOption#READ_TIMEOUT}
* @param connectionFactory a function that, given a {@link URI} will create an {@link HttpURLConnection}
* @return an {@link UrlConnectionHttpClient}
*/
public static SdkHttpClient create(UrlConnectionFactory connectionFactory) {
return new UrlConnectionHttpClient(AttributeMap.empty(), connectionFactory);
}
@Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
HttpURLConnection connection = createAndConfigureConnection(request);
return new RequestCallable(connection, request);
}
@Override
public void close() {
// Nothing to close. The connections will be closed by closing the InputStreams.
}
@Override
public String clientName() {
return CLIENT_NAME;
}
private HttpURLConnection createAndConfigureConnection(HttpExecuteRequest request) {
SdkHttpRequest sdkHttpRequest = request.httpRequest();
HttpURLConnection connection = connectionFactory.createConnection(sdkHttpRequest.getUri());
sdkHttpRequest.forEachHeader((key, values) -> values.forEach(value -> connection.setRequestProperty(key, value)));
// connection.setRequestProperty("Transfer-Encoding", "chunked") does not work, i.e., property does not get set
if (sdkHttpRequest.matchingHeaders("Transfer-Encoding").contains("chunked")) {
connection.setChunkedStreamingMode(-1);
}
if (!sdkHttpRequest.firstMatchingHeader(ACCEPT).isPresent()) {
// Override Accept header because the default one in JDK does not comply with RFC 7231
// See: https://bugs.openjdk.org/browse/JDK-8163921
connection.setRequestProperty(ACCEPT, "*/*");
}
invokeSafely(() -> connection.setRequestMethod(sdkHttpRequest.method().name()));
if (request.contentStreamProvider().isPresent()) {
connection.setDoOutput(true);
}
// Disable following redirects since it breaks SDK error handling and matches Apache.
// See: https://github.com/aws/aws-sdk-java-v2/issues/975
connection.setInstanceFollowRedirects(false);
sdkHttpRequest.firstMatchingHeader(CONTENT_LENGTH).map(Long::parseLong)
.ifPresent(connection::setFixedLengthStreamingMode);
return connection;
}
private HttpURLConnection createDefaultConnection(URI uri, SSLSocketFactory socketFactory) {
Optional<Proxy> proxy = determineProxy(uri);
HttpURLConnection connection = !proxy.isPresent() ?
invokeSafely(() -> (HttpURLConnection) uri.toURL().openConnection())
:
invokeSafely(() -> (HttpURLConnection) uri.toURL().openConnection(proxy.get()));
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
if (options.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)) {
httpsConnection.setHostnameVerifier(NoOpHostNameVerifier.INSTANCE);
}
httpsConnection.setSSLSocketFactory(socketFactory);
}
if (proxy.isPresent() && shouldProxyAuthorize()) {
connection.addRequestProperty("proxy-authorization", String.format("Basic %s", encodedAuthToken(proxyConfiguration)));
}
connection.setConnectTimeout(saturatedCast(options.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT).toMillis()));
connection.setReadTimeout(saturatedCast(options.get(SdkHttpConfigurationOption.READ_TIMEOUT).toMillis()));
return connection;
}
/**
* If a proxy is configured with username+password, then set the proxy-authorization header to authorize ourselves with the
* proxy
*/
private static String encodedAuthToken(ProxyConfiguration proxyConfiguration) {
String authToken = String.format("%s:%s", proxyConfiguration.username(), proxyConfiguration.password());
return Base64.getEncoder().encodeToString(authToken.getBytes(StandardCharsets.UTF_8));
}
private boolean shouldProxyAuthorize() {
return this.proxyConfiguration != null
&& ! StringUtils.isEmpty(this.proxyConfiguration.username())
&& ! StringUtils.isEmpty(this.proxyConfiguration.password());
}
private Optional<Proxy> determineProxy(URI uri) {
if (isProxyEnabled() && isProxyHostIncluded(uri)) {
return Optional.of(
new Proxy(Proxy.Type.HTTP,
InetSocketAddress.createUnresolved(this.proxyConfiguration.host(), this.proxyConfiguration.port())));
}
return Optional.empty();
}
private boolean isProxyHostIncluded(URI uri) {
return this.proxyConfiguration.nonProxyHosts()
.stream()
.noneMatch(uri.getHost().toLowerCase(Locale.getDefault())::matches);
}
private boolean isProxyEnabled() {
return this.proxyConfiguration != null && this.proxyConfiguration.host() != null;
}
private SSLContext getSslContext(AttributeMap options) {
Validate.isTrue(options.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) == null ||
!options.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES),
"A TlsTrustManagerProvider can't be provided if TrustAllCertificates is also set");
TrustManager[] trustManagers = null;
if (options.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) != null) {
trustManagers = options.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER).trustManagers();
}
if (options.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)) {
log.warn(() -> "SSL Certificate verification is disabled. This is not a safe setting and should only be "
+ "used for testing.");
trustManagers = new TrustManager[] { TrustAllManager.INSTANCE };
}
TlsKeyManagersProvider provider = this.options.get(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER);
KeyManager[] keyManagers = provider.keyManagers();
SSLContext context;
try {
context = SSLContext.getInstance("TLS");
context.init(keyManagers, trustManagers, null);
return context;
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
private static class RequestCallable implements ExecutableHttpRequest {
private final HttpURLConnection connection;
private final HttpExecuteRequest request;
/**
* Whether we encountered the 'bug' in the way the HttpURLConnection handles 'Expect: 100-continue' cases. See
* {@link #getAndHandle100Bug} for more information.
*/
private boolean expect100BugEncountered = false;
/**
* Result cache for {@link #responseHasNoContent()}.
*/
private Boolean responseHasNoContent;
private RequestCallable(HttpURLConnection connection, HttpExecuteRequest request) {
this.connection = connection;
this.request = request;
}
@Override
public HttpExecuteResponse call() throws IOException {
connection.connect();
Optional<ContentStreamProvider> requestContent = request.contentStreamProvider();
if (requestContent.isPresent()) {
Optional<OutputStream> outputStream = tryGetOutputStream();
if (outputStream.isPresent()) {
IoUtils.copy(requestContent.get().newStream(), outputStream.get());
}
}
int responseCode = getResponseCodeSafely(connection);
boolean isErrorResponse = HttpStatusFamily.of(responseCode).isOneOf(CLIENT_ERROR, SERVER_ERROR);
Optional<InputStream> responseContent = isErrorResponse ? tryGetErrorStream() : tryGetInputStream();
AbortableInputStream responseBody = responseContent.map(AbortableInputStream::create).orElse(null);
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(responseCode)
.statusText(connection.getResponseMessage())
// TODO: Don't ignore abort?
.headers(extractHeaders(connection))
.build())
.responseBody(responseBody)
.build();
}
private Optional<OutputStream> tryGetOutputStream() {
return getAndHandle100Bug(() -> invokeSafely(connection::getOutputStream), false);
}
private Optional<InputStream> tryGetInputStream() {
return responseHasNoContent()
? Optional.empty()
: getAndHandle100Bug(() -> invokeSafely(connection::getInputStream), true);
}
private Optional<InputStream> tryGetErrorStream() {
InputStream result = invokeSafely(connection::getErrorStream);
if (result == null && expect100BugEncountered) {
log.debug(() -> "The response payload has been dropped because of a limitation of the JDK's URL Connection "
+ "HTTP client, resulting in a less descriptive SDK exception error message. Using "
+ "the Apache HTTP client removes this limitation.");
}
return Optional.ofNullable(result);
}
/**
* This handles a bug in {@link HttpURLConnection#getOutputStream()} and {@link HttpURLConnection#getInputStream()}
* where these methods will throw a ProtocolException if we sent an "Expect: 100-continue" header, and the
* service responds with something other than a 100.
*
* HttpUrlConnection still gives us access to the response code and headers when this bug is encountered, so our
* handling of the bug is:
* <ol>
* <li>If the service returned a response status or content length that indicates there was no response payload,
* we ignore that we couldn't read the response payload, and just return the response with what we have.</li>
* <li>If the service returned a payload and we can't read it because of the bug, we throw an exception for
* non-failure cases (2xx, 3xx) or log and return the response without the payload for failure cases (4xx or 5xx)
* .</li>
* </ol>
*/
private <T> Optional<T> getAndHandle100Bug(Supplier<T> supplier, boolean failOn100Bug) {
try {
return Optional.ofNullable(supplier.get());
} catch (RuntimeException e) {
if (!exceptionCausedBy100HandlingBug(e)) {
throw e;
}
if (responseHasNoContent()) {
return Optional.empty();
}
expect100BugEncountered = true;
if (!failOn100Bug) {
return Optional.empty();
}
int responseCode = invokeSafely(connection::getResponseCode);
String message = "Unable to read response payload, because service returned response code "
+ responseCode + " to an Expect: 100-continue request. Using another HTTP client "
+ "implementation (e.g. Apache) removes this limitation.";
throw new UncheckedIOException(new IOException(message, e));
}
}
private boolean exceptionCausedBy100HandlingBug(RuntimeException e) {
return requestWasExpect100Continue() &&
e.getMessage() != null &&
e.getMessage().startsWith("java.net.ProtocolException: Server rejected operation");
}
private Boolean requestWasExpect100Continue() {
return request.httpRequest()
.firstMatchingHeader("Expect")
.map(expect -> expect.equalsIgnoreCase("100-continue"))
.orElse(false);
}
private boolean responseHasNoContent() {
// We cannot account for chunked encoded responses, because we only have access to headers and response code here,
// so we assume chunked encoded responses DO have content.
if (responseHasNoContent == null) {
responseHasNoContent = responseNeverHasPayload(invokeSafely(connection::getResponseCode)) ||
Objects.equals(connection.getHeaderField("Content-Length"), "0") ||
Objects.equals(connection.getRequestMethod(), "HEAD");
}
return responseHasNoContent;
}
private boolean responseNeverHasPayload(int responseCode) {
return responseCode == 204 || responseCode == 304 || (responseCode >= 100 && responseCode < 200);
}
/**
* {@link sun.net.www.protocol.http.HttpURLConnection#getInputStream0()} has been observed to intermittently throw
* {@link NullPointerException}s for reasons that still require further investigation, but are assumed to be due to a
* bug in the JDK. Propagating such NPEs is confusing for users and are not subject to being retried on by the default
* retry policy configuration, so instead we bias towards propagating these as {@link IOException}s.
* <p>
* TODO: Determine precise root cause of intermittent NPEs, submit JDK bug report if applicable, and consider applying
* this behavior only on unpatched JVM runtime versions.
*/
private static int getResponseCodeSafely(HttpURLConnection connection) throws IOException {
Validate.paramNotNull(connection, "connection");
try {
return connection.getResponseCode();
} catch (NullPointerException e) {
throw new IOException("Unexpected NullPointerException when trying to read response from HttpURLConnection", e);
}
}
private Map<String, List<String>> extractHeaders(HttpURLConnection response) {
return response.getHeaderFields().entrySet().stream()
.filter(e -> e.getKey() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@Override
public void abort() {
connection.disconnect();
}
}
/**
* A builder for an instance of {@link SdkHttpClient} that uses JDKs build-in {@link java.net.URLConnection} HTTP
* implementation. A builder can be created via {@link #builder()}.
*
* <pre class="brush: java">
* SdkHttpClient httpClient = UrlConnectionHttpClient.builder()
* .socketTimeout(Duration.ofSeconds(10))
* .connectionTimeout(Duration.ofSeconds(1))
* .build();
* </pre>
*/
public interface Builder extends SdkHttpClient.Builder<UrlConnectionHttpClient.Builder> {
/**
* The amount of time to wait for data to be transferred over an established, open connection before the connection is
* timed out. A duration of 0 means infinity, and is not recommended.
*/
Builder socketTimeout(Duration socketTimeout);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out. A duration of 0
* means infinity, and is not recommended.
*/
Builder connectionTimeout(Duration connectionTimeout);
/**
* Configure the {@link TlsKeyManagersProvider} that will provide the {@link javax.net.ssl.KeyManager}s to use
* when constructing the SSL context.
*/
Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider);
/**
* Configure the {@link TlsTrustManagersProvider} that will provide the {@link javax.net.ssl.TrustManager}s to use
* when constructing the SSL context.
*/
Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider);
/**
* Configuration that defines how to communicate via an HTTP proxy.
* @param proxyConfiguration proxy configuration builder object.
* @return the builder for method chaining.
*/
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
/**
* Sets the http proxy configuration to use for this client.
*
* @param proxyConfigurationBuilderConsumer The consumer of the proxy configuration builder object.
* @return the builder for method chaining.
*/
Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer);
}
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private ProxyConfiguration proxyConfiguration;
private DefaultBuilder() {
}
/**
* Sets the read timeout to a specified timeout. A timeout of zero is interpreted as an infinite timeout.
*
* @param socketTimeout the timeout as a {@link Duration}
* @return this object for method chaining
*/
@Override
public Builder socketTimeout(Duration socketTimeout) {
standardOptions.put(SdkHttpConfigurationOption.READ_TIMEOUT, socketTimeout);
return this;
}
public void setSocketTimeout(Duration socketTimeout) {
socketTimeout(socketTimeout);
}
/**
* Sets the connect timeout to a specified timeout. A timeout of zero is interpreted as an infinite timeout.
*
* @param connectionTimeout the timeout as a {@link Duration}
* @return this object for method chaining
*/
@Override
public Builder connectionTimeout(Duration connectionTimeout) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, connectionTimeout);
return this;
}
public void setConnectionTimeout(Duration connectionTimeout) {
connectionTimeout(connectionTimeout);
}
@Override
public Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER, tlsKeyManagersProvider);
return this;
}
public void setTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
tlsKeyManagersProvider(tlsKeyManagersProvider);
}
@Override
public Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER, tlsTrustManagersProvider);
return this;
}
public void setTlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
tlsTrustManagersProvider(tlsTrustManagersProvider);
}
@Override
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
@Override
public Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer) {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
proxyConfigurationBuilderConsumer.accept(builder);
return proxyConfiguration(builder.build());
}
public void setProxyConfiguration(ProxyConfiguration proxyConfiguration) {
proxyConfiguration(proxyConfiguration);
}
/**
* Used by the SDK to create a {@link SdkHttpClient} with service-default values if no other values have been configured
*
* @param serviceDefaults Service specific defaults. Keys will be one of the constants defined in
* {@link SdkHttpConfigurationOption}.
* @return an instance of {@link SdkHttpClient}
*/
@Override
public SdkHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
return new UrlConnectionHttpClient(standardOptions.build()
.merge(serviceDefaults)
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS),
null, this);
}
}
private static class NoOpHostNameVerifier implements HostnameVerifier {
static final NoOpHostNameVerifier INSTANCE = new NoOpHostNameVerifier();
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
/**
* Insecure trust manager to trust all certs. Should only be used for testing.
*/
private static class TrustAllManager implements X509TrustManager {
private static final TrustAllManager INSTANCE = new TrustAllManager();
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
log.debug(() -> "Accepting a client certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
log.debug(() -> "Accepting a server certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
| 1,234 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/UrlConnectionSdkHttpService.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpService;
/**
* Service binding for the URL Connection implementation.
*/
@SdkPublicApi
public class UrlConnectionSdkHttpService implements SdkHttpService {
@Override
public SdkHttpClient.Builder createHttpClientBuilder() {
return UrlConnectionHttpClient.builder();
}
}
| 1,235 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* @see ApacheHttpClientWireMockTest
*/
public class ApacheHttpClientTest {
@AfterEach
public void cleanup() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
}
@Test
public void connectionReaperCanBeManuallyEnabled() {
ApacheHttpClient.builder()
.useIdleConnectionReaper(true)
.build()
.close();
}
@Test
public void httpRoutePlannerCantBeUsedWithProxy() {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void httpRoutePlannerCantBeUsedWithProxy_SystemPropertiesEnabled() {
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "1234");
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void httpRoutePlannerCantBeUsedWithProxy_SystemPropertiesDisabled() {
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "1234");
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.useSystemPropertyValues(Boolean.FALSE)
.build();
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class))
.build();
}
@Test
public void credentialProviderCantBeUsedWithProxyCredentials() {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.username("foo")
.password("bar")
.build();
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.credentialsProvider(Mockito.mock(CredentialsProvider.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void credentialProviderCantBeUsedWithProxyCredentials_SystemProperties() {
System.setProperty("http.proxyUser", "foo");
System.setProperty("http.proxyPassword", "bar");
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.credentialsProvider(Mockito.mock(CredentialsProvider.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void credentialProviderCanBeUsedWithProxy() {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.build();
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.credentialsProvider(Mockito.mock(CredentialsProvider.class))
.build();
}
@Test
public void dnsResolverCanBeUsed() {
DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
if (host.equalsIgnoreCase("my.host.com")) {
return new InetAddress[] { InetAddress.getByName("127.0.0.1") };
} else {
return super.resolve(host);
}
}
};
ApacheHttpClient.builder()
.dnsResolver(dnsResolver)
.build()
.close();
}
}
| 1,236 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientTestSuite;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.impl.ConnectionManagerAwareHttpClient;
import software.amazon.awssdk.utils.AttributeMap;
@RunWith(MockitoJUnitRunner.class)
public class ApacheHttpClientWireMockTest extends SdkHttpClientTestSuite {
@Rule
public WireMockRule mockProxyServer = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort());
@Mock
private ConnectionManagerAwareHttpClient httpClient;
@Mock
private HttpClientConnectionManager connectionManager;
@Override
protected SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options) {
ApacheHttpClient.Builder builder = ApacheHttpClient.builder();
AttributeMap.Builder attributeMap = AttributeMap.builder();
if (options.tlsTrustManagersProvider() != null) {
builder.tlsTrustManagersProvider(options.tlsTrustManagersProvider());
}
if (options.trustAll()) {
attributeMap.put(TRUST_ALL_CERTIFICATES, options.trustAll());
}
return builder.buildWithDefaults(attributeMap.build());
}
@Test
public void closeClient_shouldCloseUnderlyingResources() {
ApacheHttpClient client = new ApacheHttpClient(httpClient, ApacheHttpRequestConfig.builder().build(), AttributeMap.empty());
when(httpClient.getHttpClientConnectionManager()).thenReturn(connectionManager);
client.close();
verify(connectionManager).shutdown();
}
@Test
public void routePlannerIsInvoked() throws Exception {
mockProxyServer.resetToDefaultMappings();
mockProxyServer.addStubMapping(WireMock.any(urlPathEqualTo("/"))
.willReturn(aResponse().proxiedFrom("http://localhost:" + mockServer.port()))
.build());
SdkHttpClient client = ApacheHttpClient.builder()
.httpRoutePlanner(
(host, request, context) ->
new HttpRoute(
new HttpHost("localhost", mockProxyServer.httpsPort(), "https")
)
)
.buildWithDefaults(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, Boolean.TRUE)
.build());
testForResponseCodeUsingHttps(client, HttpURLConnection.HTTP_OK);
mockProxyServer.verify(1, RequestPatternBuilder.allRequests());
}
@Test
public void credentialPlannerIsInvoked() throws Exception {
mockProxyServer.addStubMapping(WireMock.any(urlPathEqualTo("/"))
.willReturn(aResponse()
.withHeader("WWW-Authenticate", "Basic realm=\"proxy server\"")
.withStatus(401))
.build());
mockProxyServer.addStubMapping(WireMock.any(urlPathEqualTo("/"))
.withBasicAuth("foo", "bar")
.willReturn(aResponse()
.proxiedFrom("http://localhost:" + mockServer.port()))
.build());
SdkHttpClient client = ApacheHttpClient.builder()
.credentialsProvider(new CredentialsProvider() {
@Override
public void setCredentials(AuthScope authScope, Credentials credentials) {
}
@Override
public Credentials getCredentials(AuthScope authScope) {
return new UsernamePasswordCredentials("foo", "bar");
}
@Override
public void clear() {
}
})
.httpRoutePlanner(
(host, request, context) ->
new HttpRoute(
new HttpHost("localhost", mockProxyServer.httpsPort(), "https")
)
)
.buildWithDefaults(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, Boolean.TRUE)
.build());
testForResponseCodeUsingHttps(client, HttpURLConnection.HTTP_OK);
mockProxyServer.verify(2, RequestPatternBuilder.allRequests());
}
@Test
public void overrideDnsResolver_WithDnsMatchingResolver_successful() throws Exception {
overrideDnsResolver("magic.local.host");
}
@Test(expected = UnknownHostException.class)
public void overrideDnsResolver_WithUnknownHost_throwsException() throws Exception {
overrideDnsResolver("sad.local.host");
}
@Test
public void overrideDnsResolver_WithLocalhost_successful() throws Exception {
overrideDnsResolver("localhost");
}
@Test
public void explicitNullDnsResolver_WithLocalhost_successful() throws Exception {
overrideDnsResolver("localhost", true);
}
private void overrideDnsResolver(String hostName) throws IOException {
overrideDnsResolver(hostName, false);
}
private void overrideDnsResolver(String hostName, boolean nullifyResolver) throws IOException {
DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
if (host.equalsIgnoreCase("magic.local.host")) {
return new InetAddress[] { InetAddress.getByName("127.0.0.1") };
} else {
return super.resolve(host);
}
}
};
if (nullifyResolver) {
dnsResolver = null;
}
SdkHttpClient client = ApacheHttpClient.builder()
.dnsResolver(dnsResolver)
.buildWithDefaults(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, Boolean.TRUE)
.build());
mockProxyServer.resetToDefaultMappings();
mockProxyServer.stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK)));
URI uri = URI.create("https://" + hostName + ":" + mockProxyServer.httpsPort());
SdkHttpFullRequest req = SdkHttpFullRequest.builder()
.uri(uri)
.method(SdkHttpMethod.POST)
.putHeader("Host", uri.getHost())
.build();
client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider().orElse(null))
.build())
.call();
mockProxyServer.verify(1, RequestPatternBuilder.allRequests());
}
}
| 1,237 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpProxyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class ApacheHttpProxyTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings,
TestProxySetting expectedProxySettings,
Boolean useSystemProperty,
Boolean useEnvironmentVariable,
String protocol) {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
Set<String> nonProxyHosts = userSetProxySettings.getNonProxyHosts();
if (hostName != null && portNumber != null) {
builder.endpoint(URI.create(String.format("%s://%s:%d", protocol, hostName, portNumber)));
}
if (userName != null) {
builder.username(userName);
}
if (password != null) {
builder.password(password);
}
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
builder.nonProxyHosts(nonProxyHosts);
}
}
if (!"http".equals(protocol)) {
builder.scheme(protocol);
}
if (useSystemProperty != null) {
builder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
builder.useEnvironmentVariableValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = builder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
assertThat(proxyConfiguration.nonProxyHosts()).isEqualTo(expectedProxySettings.getNonProxyHosts());
}
}
| 1,238 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheMetricsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.HttpMetric.CONCURRENCY_ACQUIRE_DURATION;
import com.github.tomakehurst.wiremock.WireMockServer;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
public class ApacheMetricsTest {
private static WireMockServer wireMockServer;
private SdkHttpClient client;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUp() throws IOException {
wireMockServer = new WireMockServer();
wireMockServer.start();
}
@Before
public void methodSetup() {
wireMockServer.stubFor(any(urlMatching(".*")).willReturn(aResponse().withStatus(200).withBody("{}")));
}
@AfterClass
public static void teardown() throws IOException {
wireMockServer.stop();
}
@After
public void methodTeardown() {
if (client != null) {
client.close();
}
client = null;
}
@Test
public void concurrencyAcquireDurationIsRecorded() throws IOException {
client = ApacheHttpClient.create();
MetricCollector collector = MetricCollector.create("test");
makeRequestWithMetrics(client, collector);
MetricCollection collection = collector.collect();
assertThat(collection.metricValues(CONCURRENCY_ACQUIRE_DURATION)).isNotEmpty();
}
private HttpExecuteResponse makeRequestWithMetrics(SdkHttpClient httpClient, MetricCollector metricCollector) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host("localhost:" + wireMockServer.port())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.metricCollector(metricCollector)
.build();
return httpClient.prepareRequest(request).call();
}
}
| 1,239 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpClientDefaultWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientDefaultTestSuite;
public class ApacheHttpClientDefaultWireMockTest extends SdkHttpClientDefaultTestSuite {
@Override
protected SdkHttpClient createSdkHttpClient() {
return ApacheHttpClient.create();
}
}
| 1,240 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ClientTlsAuthTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
abstract class ClientTlsAuthTestBase {
protected static final String STORE_PASSWORD = "password";
protected static final String CLIENT_STORE_TYPE = "pkcs12";
protected static final String TEST_KEY_STORE = "/software/amazon/awssdk/http/apache/server-keystore";
protected static final String CLIENT_KEY_STORE = "/software/amazon/awssdk/http/apache/client1.p12";
protected static Path tempDir;
protected static Path serverKeyStore;
protected static Path clientKeyStore;
@BeforeAll
public static void setUp() throws IOException {
tempDir = Files.createTempDirectory(ClientTlsAuthTestBase.class.getSimpleName());
copyCertsToTmpDir();
}
@AfterAll
public static void teardown() throws IOException {
Files.deleteIfExists(serverKeyStore);
Files.deleteIfExists(clientKeyStore);
Files.deleteIfExists(tempDir);
}
private static void copyCertsToTmpDir() throws IOException {
InputStream sksStream = ClientTlsAuthTestBase.class.getResourceAsStream(TEST_KEY_STORE);
Path sks = copyToTmpDir(sksStream, "server-keystore");
InputStream cksStream = ClientTlsAuthTestBase.class.getResourceAsStream(CLIENT_KEY_STORE);
Path cks = copyToTmpDir(cksStream, "client1.p12");
serverKeyStore = sks;
clientKeyStore = cks;
}
private static Path copyToTmpDir(InputStream srcStream, String name) throws IOException {
Path dst = tempDir.resolve(name);
Files.copy(srcStream, dst);
return dst;
}
}
| 1,241 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/MetricReportingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.HttpMetric.AVAILABLE_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.HTTP_CLIENT_NAME;
import static software.amazon.awssdk.http.HttpMetric.LEASED_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.MAX_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.PENDING_CONCURRENCY_ACQUIRES;
import java.io.IOException;
import java.time.Duration;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.pool.PoolStats;
import org.apache.http.protocol.HttpContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.impl.ConnectionManagerAwareHttpClient;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.AttributeMap;
@RunWith(MockitoJUnitRunner.class)
public class MetricReportingTest {
@Mock
public ConnectionManagerAwareHttpClient mockHttpClient;
@Mock
public PoolingHttpClientConnectionManager cm;
@Before
public void methodSetup() throws IOException {
when(mockHttpClient.execute(any(HttpUriRequest.class), any(HttpContext.class)))
.thenReturn(new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"));
when(mockHttpClient.getHttpClientConnectionManager()).thenReturn(cm);
PoolStats stats = new PoolStats(1, 2, 3, 4);
when(cm.getTotalStats()).thenReturn(stats);
}
@Test
public void prepareRequest_callableCalled_metricsReported() throws IOException {
ApacheHttpClient client = newClient();
MetricCollector collector = MetricCollector.create("test");
HttpExecuteRequest executeRequest = newRequest(collector);
client.prepareRequest(executeRequest).call();
MetricCollection collected = collector.collect();
assertThat(collected.metricValues(HTTP_CLIENT_NAME)).containsExactly("Apache");
assertThat(collected.metricValues(LEASED_CONCURRENCY)).containsExactly(1);
assertThat(collected.metricValues(PENDING_CONCURRENCY_ACQUIRES)).containsExactly(2);
assertThat(collected.metricValues(AVAILABLE_CONCURRENCY)).containsExactly(3);
assertThat(collected.metricValues(MAX_CONCURRENCY)).containsExactly(4);
}
@Test
public void prepareRequest_connectionManagerNotPooling_callableCalled_metricsReported() throws IOException {
ApacheHttpClient client = newClient();
when(mockHttpClient.getHttpClientConnectionManager()).thenReturn(mock(HttpClientConnectionManager.class));
MetricCollector collector = MetricCollector.create("test");
HttpExecuteRequest executeRequest = newRequest(collector);
client.prepareRequest(executeRequest).call();
MetricCollection collected = collector.collect();
assertThat(collected.metricValues(HTTP_CLIENT_NAME)).containsExactly("Apache");
assertThat(collected.metricValues(LEASED_CONCURRENCY)).isEmpty();
assertThat(collected.metricValues(PENDING_CONCURRENCY_ACQUIRES)).isEmpty();
assertThat(collected.metricValues(AVAILABLE_CONCURRENCY)).isEmpty();
assertThat(collected.metricValues(MAX_CONCURRENCY)).isEmpty();
}
private ApacheHttpClient newClient() {
ApacheHttpRequestConfig config = ApacheHttpRequestConfig.builder()
.connectionAcquireTimeout(Duration.ofDays(1))
.connectionTimeout(Duration.ofDays(1))
.socketTimeout(Duration.ofDays(1))
.proxyConfiguration(ProxyConfiguration.builder().build())
.build();
return new ApacheHttpClient(mockHttpClient, config, AttributeMap.empty());
}
private HttpExecuteRequest newRequest(MetricCollector collector) {
final SdkHttpFullRequest sdkRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.HEAD)
.host("amazonaws.com")
.protocol("https")
.build();
HttpExecuteRequest executeRequest = HttpExecuteRequest.builder()
.request(sdkRequest)
.metricCollector(collector)
.build();
return executeRequest;
}
}
| 1,242 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class ProxyConfigurationTest {
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
@BeforeEach
public void setup() {
clearProxyProperties();
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@AfterAll
public static void cleanup() {
clearProxyProperties();
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@Test
void testEndpointValues_Http_SystemPropertyEnabled() {
String host = "foo.com";
int port = 7777;
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", Integer.toString(port));
ENVIRONMENT_VARIABLE_HELPER.set("http_proxy", "http://UserOne:passwordSecret@bar.com:555/");
ProxyConfiguration config = ProxyConfiguration.builder().useSystemPropertyValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testEndpointValues_Http_EnvironmentVariableEnabled() {
String host = "bar.com";
int port = 7777;
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", Integer.toString(8888));
ENVIRONMENT_VARIABLE_HELPER.set("http_proxy", String.format("http://%s:%d/", host, port));
ProxyConfiguration config =
ProxyConfiguration.builder().useSystemPropertyValues(false).useEnvironmentVariableValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testEndpointValues_Https_SystemPropertyEnabled() {
String host = "foo.com";
int port = 7777;
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", Integer.toString(port));
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("https://foo.com:7777"))
.useSystemPropertyValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void testEndpointValues_Https_EnvironmentVariableEnabled() {
String host = "bar.com";
int port = 7777;
System.setProperty("https.proxyHost", "foo.com");
System.setProperty("https.proxyPort", Integer.toString(8888));
ENVIRONMENT_VARIABLE_HELPER.set("http_proxy", String.format("http://%s:%d/", "foo.com", 8888));
ENVIRONMENT_VARIABLE_HELPER.set("https_proxy", String.format("http://%s:%d/", host, port));
ProxyConfiguration config =
ProxyConfiguration.builder()
.scheme("https")
.useSystemPropertyValues(false)
.useEnvironmentVariableValues(true)
.build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void testEndpointValues_SystemPropertyDisabled() {
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testProxyConfigurationWithSystemPropertyDisabled() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.nonProxyHosts(nonProxyHosts)
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.username()).isNull();
}
@Test
void testProxyConfigurationWithSystemPropertyEnabled_Http() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.nonProxyHosts(nonProxyHosts)
.build();
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.host()).isEqualTo("foo.com");
assertThat(config.username()).isEqualTo("user");
}
@Test
void testProxyConfigurationWithSystemPropertyEnabled_Https() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("https.proxyHost", "foo.com");
System.setProperty("https.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("https.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("https://foo.com:1234"))
.nonProxyHosts(nonProxyHosts)
.build();
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.host()).isEqualTo("foo.com");
assertThat(config.username()).isEqualTo("user");
}
@Test
void testProxyConfigurationWithoutNonProxyHosts_toBuilder_shouldNotThrowNPE() {
ProxyConfiguration proxyConfiguration =
ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:4321"))
.username("username")
.password("password")
.build();
assertThat(proxyConfiguration.toBuilder()).isNotNull();
}
private static void clearProxyProperties() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.nonProxyHosts");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
System.clearProperty("https.proxyHost");
System.clearProperty("https.proxyPort");
System.clearProperty("https.proxyUser");
System.clearProperty("https.proxyPassword");
}
}
| 1,243 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheClientTlsAuthTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.instanceOf;
import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE;
import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_PASSWORD;
import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_TYPE;
import com.github.tomakehurst.wiremock.WireMockServer;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import org.apache.http.NoHttpResponseException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import software.amazon.awssdk.http.FileStoreTlsKeyManagersProvider;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.apache.internal.conn.SdkTlsSocketFactory;
import software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider;
/**
* Tests to ensure that {@link ApacheHttpClient} can properly support TLS
* client authentication.
*/
public class ApacheClientTlsAuthTest extends ClientTlsAuthTestBase {
private static WireMockServer wireMockServer;
private static TlsKeyManagersProvider keyManagersProvider;
private SdkHttpClient client;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUp() throws IOException {
ClientTlsAuthTestBase.setUp();
// Will be used by both client and server to trust the self-signed
// cert they present to each other
System.setProperty("javax.net.ssl.trustStore", serverKeyStore.toAbsolutePath().toString());
System.setProperty("javax.net.ssl.trustStorePassword", STORE_PASSWORD);
System.setProperty("javax.net.ssl.trustStoreType", "jks");
wireMockServer = new WireMockServer(wireMockConfig()
.dynamicHttpsPort()
.needClientAuth(true)
.keystorePath(serverKeyStore.toAbsolutePath().toString())
.keystorePassword(STORE_PASSWORD)
);
wireMockServer.start();
keyManagersProvider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD);
}
@Before
public void methodSetup() {
wireMockServer.stubFor(any(urlMatching(".*")).willReturn(aResponse().withStatus(200).withBody("{}")));
}
@AfterClass
public static void teardown() throws IOException {
wireMockServer.stop();
System.clearProperty("javax.net.ssl.trustStore");
System.clearProperty("javax.net.ssl.trustStorePassword");
System.clearProperty("javax.net.ssl.trustStoreType");
ClientTlsAuthTestBase.teardown();
}
@After
public void methodTeardown() {
if (client != null) {
client.close();
}
client = null;
}
@Test
public void canMakeHttpsRequestWhenKeyProviderConfigured() throws IOException {
client = ApacheHttpClient.builder()
.tlsKeyManagersProvider(keyManagersProvider)
.build();
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttpClient(client);
assertThat(httpExecuteResponse.httpResponse().isSuccessful()).isTrue();
}
@Test
public void requestFailsWhenKeyProviderNotConfigured() throws IOException {
thrown.expect(anyOf(instanceOf(NoHttpResponseException.class), instanceOf(SSLException.class), instanceOf(SocketException.class)));
client = ApacheHttpClient.builder().tlsKeyManagersProvider(NoneTlsKeyManagersProvider.getInstance()).build();
makeRequestWithHttpClient(client);
}
@Test
public void authenticatesWithTlsProxy() throws IOException {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("https://localhost:" + wireMockServer.httpsPort()))
.build();
client = ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.tlsKeyManagersProvider(keyManagersProvider)
.build();
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttpClient(client);
// WireMock doesn't mock 'CONNECT' methods and will return a 404 for this
assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(404);
}
@Test
public void defaultTlsKeyManagersProviderIsSystemPropertyProvider() throws IOException {
System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString());
System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE);
System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD);
client = ApacheHttpClient.builder().build();
try {
makeRequestWithHttpClient(client);
} finally {
System.clearProperty(SSL_KEY_STORE.property());
System.clearProperty(SSL_KEY_STORE_TYPE.property());
System.clearProperty(SSL_KEY_STORE_PASSWORD.property());
}
}
@Test
public void defaultTlsKeyManagersProviderIsSystemPropertyProvider_explicitlySetToNull() throws IOException {
System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString());
System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE);
System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD);
client = ApacheHttpClient.builder().tlsKeyManagersProvider(null).build();
try {
makeRequestWithHttpClient(client);
} finally {
System.clearProperty(SSL_KEY_STORE.property());
System.clearProperty(SSL_KEY_STORE_TYPE.property());
System.clearProperty(SSL_KEY_STORE_PASSWORD.property());
}
}
@Test
public void build_notSettingSocketFactory_configuresClientWithDefaultSocketFactory() throws IOException,
NoSuchAlgorithmException,
KeyManagementException {
System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString());
System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE);
System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD);
TlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore,
CLIENT_STORE_TYPE,
STORE_PASSWORD);
KeyManager[] keyManagers = provider.keyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keyManagers, null, null);
ConnectionSocketFactory socketFactory = new SdkTlsSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
ConnectionSocketFactory socketFactoryMock = Mockito.spy(socketFactory);
client = ApacheHttpClient.builder().build();
try {
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttpClient(client);
assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
} finally {
System.clearProperty(SSL_KEY_STORE.property());
System.clearProperty(SSL_KEY_STORE_TYPE.property());
System.clearProperty(SSL_KEY_STORE_PASSWORD.property());
}
Mockito.verifyNoInteractions(socketFactoryMock);
}
@Test
public void build_settingCustomSocketFactory_configuresClientWithGivenSocketFactory() throws IOException,
NoSuchAlgorithmException,
KeyManagementException {
TlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore,
CLIENT_STORE_TYPE,
STORE_PASSWORD);
KeyManager[] keyManagers = provider.keyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keyManagers, null, null);
ConnectionSocketFactory socketFactory = new SdkTlsSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
ConnectionSocketFactory socketFactoryMock = Mockito.spy(socketFactory);
client = ApacheHttpClient.builder()
.socketFactory(socketFactoryMock)
.build();
makeRequestWithHttpClient(client);
Mockito.verify(socketFactoryMock).createSocket(Mockito.any());
}
private HttpExecuteResponse makeRequestWithHttpClient(SdkHttpClient httpClient) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost:" + wireMockServer.httpsPort())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.build();
return httpClient.prepareRequest(request).call();
}
}
| 1,244 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/SdkProxyRoutePlannerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link SdkProxyRoutePlanner}.
*/
public class SdkProxyRoutePlannerTest {
private static final HttpHost S3_HOST = new HttpHost("s3.us-west-2.amazonaws.com", 443, "https");
private static final HttpGet S3_REQUEST = new HttpGet("/my-bucket/my-object");
private static final HttpClientContext CONTEXT = new HttpClientContext();
@Test
public void testSetsCorrectSchemeBasedOnProcotol_HTTPS() throws HttpException {
SdkProxyRoutePlanner planner = new SdkProxyRoutePlanner("localhost", 1234, "https", Collections.emptySet());
HttpHost proxyHost = planner.determineRoute(S3_HOST, S3_REQUEST, CONTEXT).getProxyHost();
assertEquals("localhost", proxyHost.getHostName());
assertEquals("https", proxyHost.getSchemeName());
}
@Test
public void testSetsCorrectSchemeBasedOnProcotol_HTTP() throws HttpException {
SdkProxyRoutePlanner planner = new SdkProxyRoutePlanner("localhost", 1234, "http", Collections.emptySet());
HttpHost proxyHost = planner.determineRoute(S3_HOST, S3_REQUEST, CONTEXT).getProxyHost();
assertEquals("localhost", proxyHost.getHostName());
assertEquals("http", proxyHost.getSchemeName());
}
}
| 1,245 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/impl/ApacheHttpRequestFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.BufferedHttpEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.RepeatableInputStreamRequestEntity;
public class ApacheHttpRequestFactoryTest {
private ApacheHttpRequestConfig requestConfig;
private ApacheHttpRequestFactory instance;
@BeforeEach
public void setup() {
instance = new ApacheHttpRequestFactory();
requestConfig = ApacheHttpRequestConfig.builder()
.connectionAcquireTimeout(Duration.ZERO)
.connectionTimeout(Duration.ZERO)
.localAddress(InetAddress.getLoopbackAddress())
.socketTimeout(Duration.ZERO)
.build();
}
@Test
public void createSetsHostHeaderByDefault() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:12345/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
HttpRequestBase result = instance.create(request, requestConfig);
Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST);
assertNotNull(hostHeaders);
assertEquals(1, hostHeaders.length);
assertEquals("localhost:12345", hostHeaders[0].getValue());
}
@Test
public void putRequest_withTransferEncodingChunked_isChunkedAndDoesNotIncludeHeader() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:12345/"))
.method(SdkHttpMethod.PUT)
.putHeader("Transfer-Encoding", "chunked")
.build();
InputStream inputStream = new ByteArrayInputStream("TestStream".getBytes(StandardCharsets.UTF_8));
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.contentStreamProvider(() -> inputStream)
.build();
HttpRequestBase result = instance.create(request, requestConfig);
Header[] transferEncodingHeaders = result.getHeaders("Transfer-Encoding");
assertThat(transferEncodingHeaders).isEmpty();
HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) result;
HttpEntity httpEntity = enclosingRequest.getEntity();
assertThat(httpEntity.isChunked()).isTrue();
assertThat(httpEntity).isNotInstanceOf(BufferedHttpEntity.class);
assertThat(httpEntity).isInstanceOf(RepeatableInputStreamRequestEntity.class);
}
@Test
public void defaultHttpPortsAreNotInDefaultHostHeader() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:80/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
HttpRequestBase result = instance.create(request, requestConfig);
Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST);
assertNotNull(hostHeaders);
assertEquals(1, hostHeaders.length);
assertEquals("localhost", hostHeaders[0].getValue());
sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("https://localhost:443/"))
.method(SdkHttpMethod.HEAD)
.build();
request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
result = instance.create(request, requestConfig);
hostHeaders = result.getHeaders(HttpHeaders.HOST);
assertNotNull(hostHeaders);
assertEquals(1, hostHeaders.length);
assertEquals("localhost", hostHeaders[0].getValue());
}
@Test
public void pathWithLeadingSlash_shouldEncode() {
assertThat(sanitizedUri("/foobar")).isEqualTo("http://localhost/%2Ffoobar");
}
@Test
public void pathWithOnlySlash_shouldEncode() {
assertThat(sanitizedUri("/")).isEqualTo("http://localhost/%2F");
}
@Test
public void pathWithoutSlash_shouldReturnSameUri() {
assertThat(sanitizedUri("path")).isEqualTo("http://localhost/path");
}
@Test
public void pathWithSpecialChars_shouldPreserveEncoding() {
assertThat(sanitizedUri("/special-chars-%40%24%25")).isEqualTo("http://localhost/%2Fspecial-chars-%40%24%25");
}
private String sanitizedUri(String path) {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:80"))
.encodedPath("/" + path)
.method(SdkHttpMethod.HEAD)
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
return instance.create(request, requestConfig).getURI().toString();
}
}
| 1,246 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/conn/IdleConnectionReaperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.apache.http.conn.HttpClientConnectionManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Tests for {@link IdleConnectionReaper}.
*/
@RunWith(MockitoJUnitRunner.class)
public class IdleConnectionReaperTest {
private static final long SLEEP_PERIOD = 250;
private final Map<HttpClientConnectionManager, Long> connectionManagers = new HashMap<>();
@Mock
public ExecutorService executorService;
@Mock
public HttpClientConnectionManager connectionManager;
private IdleConnectionReaper idleConnectionReaper;
@Before
public void methodSetup() {
this.connectionManagers.clear();
idleConnectionReaper = new IdleConnectionReaper(connectionManagers, () -> executorService, SLEEP_PERIOD);
}
@Test
public void setsUpExecutorIfManagerNotPreviouslyRegistered() {
idleConnectionReaper.registerConnectionManager(connectionManager, 1L);
verify(executorService).execute(any(Runnable.class));
}
@Test
public void shutsDownExecutorIfMapEmptied() {
// use register method so it sets up the executor
idleConnectionReaper.registerConnectionManager(connectionManager, 1L);
idleConnectionReaper.deregisterConnectionManager(connectionManager);
verify(executorService).shutdownNow();
}
@Test
public void doesNotShutDownExecutorIfNoManagerRemoved() {
idleConnectionReaper.registerConnectionManager(connectionManager, 1L);
HttpClientConnectionManager someOtherConnectionManager = mock(HttpClientConnectionManager.class);
idleConnectionReaper.deregisterConnectionManager(someOtherConnectionManager);
verify(executorService, times(0)).shutdownNow();
}
@Test(timeout = 1000L)
public void testReapsConnections() throws InterruptedException {
IdleConnectionReaper reaper = new IdleConnectionReaper(new HashMap<>(),
Executors::newSingleThreadExecutor,
SLEEP_PERIOD);
final long idleTime = 1L;
reaper.registerConnectionManager(connectionManager, idleTime);
try {
Thread.sleep(SLEEP_PERIOD * 2);
verify(connectionManager, atLeastOnce()).closeIdleConnections(eq(idleTime), eq(TimeUnit.MILLISECONDS));
} finally {
reaper.deregisterConnectionManager(connectionManager);
}
}
}
| 1,247 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/conn/ClientConnectionManagerFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpClientConnection;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.protocol.HttpContext;
import org.junit.Test;
public class ClientConnectionManagerFactoryTest {
HttpClientConnectionManager noop = new HttpClientConnectionManager() {
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) throws
IOException {
}
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
}
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
}
@Override
public ConnectionRequest requestConnection(HttpRoute route,
Object state) {
return null;
}
@Override
public void releaseConnection(HttpClientConnection conn,
Object newState,
long validDuration,
TimeUnit timeUnit) {
}
@Override
public void closeIdleConnections(long idletime, TimeUnit tunit) {
}
@Override
public void closeExpiredConnections() {
}
@Override
public void shutdown() {
}
};
@Test
public void wrapOnce() {
ClientConnectionManagerFactory.wrap(noop);
}
@Test(expected = IllegalArgumentException.class)
public void wrapTwice() {
HttpClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop);
ClientConnectionManagerFactory.wrap(wrapped);
}
}
| 1,248 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/conn/SdkTlsSocketFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class SdkTlsSocketFactoryTest {
SdkTlsSocketFactory factory;
SSLSocket socket;
@BeforeEach
public void before() throws Exception {
factory = new SdkTlsSocketFactory(SSLContext.getDefault(), null);
socket = Mockito.mock(SSLSocket.class);
}
@Test
void nullProtocols() {
when(socket.getSupportedProtocols()).thenReturn(null);
when(socket.getEnabledProtocols()).thenReturn(null);
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
@Test
void amazonCorretto_8_0_292_defaultEnabledProtocols() {
when(socket.getSupportedProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello"
});
when(socket.getEnabledProtocols()).thenReturn(new String[] {
"TLSv1.2", "TLSv1.1", "TLSv1"
});
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
@Test
void amazonCorretto_11_0_08_defaultEnabledProtocols() {
when(socket.getSupportedProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello"
});
when(socket.getEnabledProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1"
});
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
@Test
void amazonCorretto_17_0_1_defaultEnabledProtocols() {
when(socket.getSupportedProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello"
});
when(socket.getEnabledProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2"
});
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
}
| 1,249 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/ProxyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static software.amazon.awssdk.utils.ProxyConfigProvider.fromSystemEnvironmentSettings;
import static software.amazon.awssdk.utils.StringUtils.isEmpty;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ProxyConfigProvider;
import software.amazon.awssdk.utils.ProxySystemSetting;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration that defines how to communicate via an HTTP or HTTPS proxy.
*/
@SdkPublicApi
public final class ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private final URI endpoint;
private final String username;
private final String password;
private final String ntlmDomain;
private final String ntlmWorkstation;
private final Set<String> nonProxyHosts;
private final Boolean preemptiveBasicAuthenticationEnabled;
private final Boolean useSystemPropertyValues;
private final String host;
private final int port;
private final String scheme;
private final Boolean useEnvironmentVariablesValues;
/**
* Initialize this configuration. Private to require use of {@link #builder()}.
*/
private ProxyConfiguration(DefaultClientProxyConfigurationBuilder builder) {
this.endpoint = builder.endpoint;
String resolvedScheme = getResolvedScheme(builder);
this.scheme = resolvedScheme;
ProxyConfigProvider proxyConfiguration = fromSystemEnvironmentSettings(builder.useSystemPropertyValues,
builder.useEnvironmentVariableValues,
resolvedScheme);
this.username = resolveUsername(builder, proxyConfiguration);
this.password = resolvePassword(builder, proxyConfiguration);
this.ntlmDomain = builder.ntlmDomain;
this.ntlmWorkstation = builder.ntlmWorkstation;
this.nonProxyHosts = resolveNonProxyHosts(builder, proxyConfiguration);
this.preemptiveBasicAuthenticationEnabled = builder.preemptiveBasicAuthenticationEnabled == null ? Boolean.FALSE :
builder.preemptiveBasicAuthenticationEnabled;
this.useSystemPropertyValues = builder.useSystemPropertyValues;
this.useEnvironmentVariablesValues = builder.useEnvironmentVariableValues;
if (this.endpoint != null) {
this.host = endpoint.getHost();
this.port = endpoint.getPort();
} else {
this.host = proxyConfiguration != null ? proxyConfiguration.host() : null;
this.port = proxyConfiguration != null ? proxyConfiguration.port() : 0;
}
}
private static String resolvePassword(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfiguration) {
return !isEmpty(builder.password) || proxyConfiguration == null ? builder.password :
proxyConfiguration.password().orElseGet(() -> builder.password);
}
private static String resolveUsername(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfiguration) {
return !isEmpty(builder.username) || proxyConfiguration == null ? builder.username :
proxyConfiguration.userName().orElseGet(() -> builder.username);
}
private static Set<String> resolveNonProxyHosts(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfiguration) {
if (builder.nonProxyHosts != null || proxyConfiguration == null) {
return builder.nonProxyHosts;
}
return proxyConfiguration.nonProxyHosts();
}
private String getResolvedScheme(DefaultClientProxyConfigurationBuilder builder) {
return endpoint != null ? endpoint.getScheme() : builder.scheme;
}
/**
* Returns the proxy host name from the configured endpoint if set, else from the "https.proxyHost" or "http.proxyHost" system
* property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
*/
public String host() {
return host;
}
/**
* Returns the proxy port from the configured endpoint if set, else from the "https.proxyPort" or "http.proxyPort" system
* property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
* If no value is found in none of the above options, the default value of 0 is returned.
*/
public int port() {
return port;
}
/**
* Returns the {@link URI#scheme} from the configured endpoint. Otherwise return null.
*/
public String scheme() {
return scheme;
}
/**
* The username to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String username() {
return username;
}
/**
* The password to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String password() {
return password;
}
/**
* For NTLM proxies: The Windows domain name to use when authenticating with the proxy.
*
* @see Builder#ntlmDomain(String)
*/
public String ntlmDomain() {
return ntlmDomain;
}
/**
* For NTLM proxies: The Windows workstation name to use when authenticating with the proxy.
*
* @see Builder#ntlmWorkstation(String)
*/
public String ntlmWorkstation() {
return ntlmWorkstation;
}
/**
* The hosts that the client is allowed to access without going through the proxy.
* If the value is not set on the object, the value represent by "http.nonProxyHosts" system property is returned.
* If system property is also not set, an unmodifiable empty set is returned.
*
* @see Builder#nonProxyHosts(Set)
*/
public Set<String> nonProxyHosts() {
return Collections.unmodifiableSet(nonProxyHosts != null ? nonProxyHosts : Collections.emptySet());
}
/**
* Whether to attempt to authenticate preemptively against the proxy server using basic authentication.
*
* @see Builder#preemptiveBasicAuthenticationEnabled(Boolean)
*/
public Boolean preemptiveBasicAuthenticationEnabled() {
return preemptiveBasicAuthenticationEnabled;
}
@Override
public Builder toBuilder() {
return builder()
.endpoint(endpoint)
.username(username)
.password(password)
.ntlmDomain(ntlmDomain)
.ntlmWorkstation(ntlmWorkstation)
.nonProxyHosts(nonProxyHosts)
.preemptiveBasicAuthenticationEnabled(preemptiveBasicAuthenticationEnabled)
.useSystemPropertyValues(useSystemPropertyValues)
.scheme(scheme)
.useEnvironmentVariableValues(useEnvironmentVariablesValues);
}
/**
* Create a {@link Builder}, used to create a {@link ProxyConfiguration}.
*/
public static Builder builder() {
return new DefaultClientProxyConfigurationBuilder();
}
@Override
public String toString() {
return ToString.builder("ProxyConfiguration")
.add("endpoint", endpoint)
.add("username", username)
.add("ntlmDomain", ntlmDomain)
.add("ntlmWorkstation", ntlmWorkstation)
.add("nonProxyHosts", nonProxyHosts)
.add("preemptiveBasicAuthenticationEnabled", preemptiveBasicAuthenticationEnabled)
.add("useSystemPropertyValues", useSystemPropertyValues)
.add("useEnvironmentVariablesValues", useEnvironmentVariablesValues)
.add("scheme", scheme)
.build();
}
public String resolveScheme() {
return endpoint != null ? endpoint.getScheme() : scheme;
}
/**
* A builder for {@link ProxyConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder extends CopyableBuilder<Builder, ProxyConfiguration> {
/**
* Configure the endpoint of the proxy server that the SDK should connect through. Currently, the endpoint is limited to
* a host and port. Any other URI components will result in an exception being raised.
*/
Builder endpoint(URI endpoint);
/**
* Configure the username to use when connecting through a proxy.
*/
Builder username(String username);
/**
* Configure the password to use when connecting through a proxy.
*/
Builder password(String password);
/**
* For NTLM proxies: Configure the Windows domain name to use when authenticating with the proxy.
*/
Builder ntlmDomain(String proxyDomain);
/**
* For NTLM proxies: Configure the Windows workstation name to use when authenticating with the proxy.
*/
Builder ntlmWorkstation(String proxyWorkstation);
/**
* Configure the hosts that the client is allowed to access without going through the proxy.
*/
Builder nonProxyHosts(Set<String> nonProxyHosts);
/**
* Add a host that the client is allowed to access without going through the proxy.
*
* @see ProxyConfiguration#nonProxyHosts()
*/
Builder addNonProxyHost(String nonProxyHost);
/**
* Configure whether to attempt to authenticate pre-emptively against the proxy server using basic authentication.
*/
Builder preemptiveBasicAuthenticationEnabled(Boolean preemptiveBasicAuthenticationEnabled);
/**
* Option whether to use system property values from {@link ProxySystemSetting} if any of the config options are missing.
* <p>
* This value is set to "true" by default which means SDK will automatically use system property values for options that
* are not provided during building the {@link ProxyConfiguration} object. To disable this behavior, set this value to
* "false".It is important to note that when this property is set to "true," all proxy settings will exclusively originate
* from system properties, and no partial settings will be obtained from EnvironmentVariableValues.
*/
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
/**
* Option whether to use environment variable values for proxy configuration if any of the config options are missing.
* <p>
* This value is set to "true" by default, which means the SDK will automatically use environment variable values for
* proxy configuration options that are not provided during the building of the {@link ProxyConfiguration} object. To
* disable this behavior, set this value to "false". It is important to note that when this property is set to "true," all
* proxy settings will exclusively originate from environment variableValues, and no partial settings will be obtained
* from SystemPropertyValues.
*
* @param useEnvironmentVariableValues The option whether to use environment variable values.
* @return This object for method chaining.
*/
Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues);
/**
* The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}.
* <p>
* The client defaults to {@code http} if none is given.
*
* @param scheme The proxy scheme.
* @return This object for method chaining.
*/
Builder scheme(String scheme);
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultClientProxyConfigurationBuilder implements Builder {
private URI endpoint;
private String username;
private String password;
private String ntlmDomain;
private String ntlmWorkstation;
private Set<String> nonProxyHosts;
private Boolean preemptiveBasicAuthenticationEnabled;
private Boolean useSystemPropertyValues = Boolean.TRUE;
private Boolean useEnvironmentVariableValues = Boolean.TRUE;
private String scheme = "http";
@Override
public Builder endpoint(URI endpoint) {
if (endpoint != null) {
Validate.isTrue(isEmpty(endpoint.getUserInfo()), "Proxy endpoint user info is not supported.");
Validate.isTrue(isEmpty(endpoint.getPath()), "Proxy endpoint path is not supported.");
Validate.isTrue(isEmpty(endpoint.getQuery()), "Proxy endpoint query is not supported.");
Validate.isTrue(isEmpty(endpoint.getFragment()), "Proxy endpoint fragment is not supported.");
}
this.endpoint = endpoint;
return this;
}
public void setEndpoint(URI endpoint) {
endpoint(endpoint);
}
@Override
public Builder username(String username) {
this.username = username;
return this;
}
public void setUsername(String username) {
username(username);
}
@Override
public Builder password(String password) {
this.password = password;
return this;
}
public void setPassword(String password) {
password(password);
}
@Override
public Builder ntlmDomain(String proxyDomain) {
this.ntlmDomain = proxyDomain;
return this;
}
public void setNtlmDomain(String ntlmDomain) {
ntlmDomain(ntlmDomain);
}
@Override
public Builder ntlmWorkstation(String proxyWorkstation) {
this.ntlmWorkstation = proxyWorkstation;
return this;
}
public void setNtlmWorkstation(String ntlmWorkstation) {
ntlmWorkstation(ntlmWorkstation);
}
@Override
public Builder nonProxyHosts(Set<String> nonProxyHosts) {
this.nonProxyHosts = nonProxyHosts != null ? new HashSet<>(nonProxyHosts) : null;
return this;
}
@Override
public Builder addNonProxyHost(String nonProxyHost) {
if (this.nonProxyHosts == null) {
this.nonProxyHosts = new HashSet<>();
}
this.nonProxyHosts.add(nonProxyHost);
return this;
}
public void setNonProxyHosts(Set<String> nonProxyHosts) {
nonProxyHosts(nonProxyHosts);
}
@Override
public Builder preemptiveBasicAuthenticationEnabled(Boolean preemptiveBasicAuthenticationEnabled) {
this.preemptiveBasicAuthenticationEnabled = preemptiveBasicAuthenticationEnabled;
return this;
}
public void setPreemptiveBasicAuthenticationEnabled(Boolean preemptiveBasicAuthenticationEnabled) {
preemptiveBasicAuthenticationEnabled(preemptiveBasicAuthenticationEnabled);
}
@Override
public Builder useSystemPropertyValues(Boolean useSystemPropertyValues) {
this.useSystemPropertyValues = useSystemPropertyValues;
return this;
}
public void setUseSystemPropertyValues(Boolean useSystemPropertyValues) {
useSystemPropertyValues(useSystemPropertyValues);
}
@Override
public Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues) {
this.useEnvironmentVariableValues = useEnvironmentVariableValues;
return this;
}
@Override
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
public void setuseEnvironmentVariableValues(Boolean useEnvironmentVariableValues) {
useEnvironmentVariableValues(useEnvironmentVariableValues);
}
@Override
public ProxyConfiguration build() {
return new ProxyConfiguration(this);
}
}
}
| 1,250 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/ApacheSdkHttpService.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpService;
/**
* Service binding for the Apache implementation.
*/
@SdkPublicApi
public class ApacheSdkHttpService implements SdkHttpService {
@Override
public SdkHttpClient.Builder createHttpClientBuilder() {
return ApacheHttpClient.builder();
}
}
| 1,251 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/ApacheHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static software.amazon.awssdk.http.HttpMetric.AVAILABLE_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.HTTP_CLIENT_NAME;
import static software.amazon.awssdk.http.HttpMetric.LEASED_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.MAX_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.PENDING_CONCURRENCY_ACQUIRES;
import static software.amazon.awssdk.http.apache.internal.conn.ClientConnectionRequestFactory.THREAD_LOCAL_REQUEST_METRIC_COLLECTOR;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.io.IOException;
import java.net.InetAddress;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLInitializationException;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.pool.PoolStats;
import org.apache.http.protocol.HttpRequestExecutor;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.SystemPropertyTlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.DefaultConfiguration;
import software.amazon.awssdk.http.apache.internal.SdkConnectionReuseStrategy;
import software.amazon.awssdk.http.apache.internal.SdkProxyRoutePlanner;
import software.amazon.awssdk.http.apache.internal.conn.ClientConnectionManagerFactory;
import software.amazon.awssdk.http.apache.internal.conn.IdleConnectionReaper;
import software.amazon.awssdk.http.apache.internal.conn.SdkConnectionKeepAliveStrategy;
import software.amazon.awssdk.http.apache.internal.conn.SdkTlsSocketFactory;
import software.amazon.awssdk.http.apache.internal.impl.ApacheHttpRequestFactory;
import software.amazon.awssdk.http.apache.internal.impl.ApacheSdkHttpClient;
import software.amazon.awssdk.http.apache.internal.impl.ConnectionManagerAwareHttpClient;
import software.amazon.awssdk.http.apache.internal.utils.ApacheUtils;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkHttpClient} that uses Apache HTTP client to communicate with the service. This is the most
* powerful synchronous client that adds an extra dependency and additional startup latency in exchange for more functionality,
* like support for HTTP proxies.
*
* <p>See software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient for an alternative implementation.</p>
*
* <p>This can be created via {@link #builder()}</p>
*/
@SdkPublicApi
public final class ApacheHttpClient implements SdkHttpClient {
public static final String CLIENT_NAME = "Apache";
private static final Logger log = Logger.loggerFor(ApacheHttpClient.class);
private final ApacheHttpRequestFactory apacheHttpRequestFactory = new ApacheHttpRequestFactory();
private final ConnectionManagerAwareHttpClient httpClient;
private final ApacheHttpRequestConfig requestConfig;
private final AttributeMap resolvedOptions;
@SdkTestInternalApi
ApacheHttpClient(ConnectionManagerAwareHttpClient httpClient,
ApacheHttpRequestConfig requestConfig,
AttributeMap resolvedOptions) {
this.httpClient = httpClient;
this.requestConfig = requestConfig;
this.resolvedOptions = resolvedOptions;
}
private ApacheHttpClient(DefaultBuilder builder, AttributeMap resolvedOptions) {
this.httpClient = createClient(builder, resolvedOptions);
this.requestConfig = createRequestConfig(builder, resolvedOptions);
this.resolvedOptions = resolvedOptions;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Create a {@link ApacheHttpClient} with the default properties
*
* @return an {@link ApacheHttpClient}
*/
public static SdkHttpClient create() {
return new DefaultBuilder().build();
}
private ConnectionManagerAwareHttpClient createClient(ApacheHttpClient.DefaultBuilder configuration,
AttributeMap standardOptions) {
ApacheConnectionManagerFactory cmFactory = new ApacheConnectionManagerFactory();
HttpClientBuilder builder = HttpClients.custom();
// Note that it is important we register the original connection manager with the
// IdleConnectionReaper as it's required for the successful deregistration of managers
// from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
HttpClientConnectionManager cm = cmFactory.create(configuration, standardOptions);
builder.setRequestExecutor(new HttpRequestExecutor())
// SDK handles decompression
.disableContentCompression()
.setKeepAliveStrategy(buildKeepAliveStrategy(standardOptions))
.disableRedirectHandling()
.disableAutomaticRetries()
.setUserAgent("") // SDK will set the user agent header in the pipeline. Don't let Apache waste time
.setConnectionReuseStrategy(new SdkConnectionReuseStrategy())
.setConnectionManager(ClientConnectionManagerFactory.wrap(cm));
addProxyConfig(builder, configuration);
if (useIdleConnectionReaper(standardOptions)) {
IdleConnectionReaper.getInstance().registerConnectionManager(
cm, standardOptions.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis());
}
return new ApacheSdkHttpClient(builder.build(), cm);
}
private void addProxyConfig(HttpClientBuilder builder,
DefaultBuilder configuration) {
ProxyConfiguration proxyConfiguration = configuration.proxyConfiguration;
Validate.isTrue(configuration.httpRoutePlanner == null || !isProxyEnabled(proxyConfiguration),
"The httpRoutePlanner and proxyConfiguration can't both be configured.");
Validate.isTrue(configuration.credentialsProvider == null || !isAuthenticatedProxy(proxyConfiguration),
"The credentialsProvider and proxyConfiguration username/password can't both be configured.");
HttpRoutePlanner routePlanner = configuration.httpRoutePlanner;
if (isProxyEnabled(proxyConfiguration)) {
log.debug(() -> "Configuring Proxy. Proxy Host: " + proxyConfiguration.host());
routePlanner = new SdkProxyRoutePlanner(proxyConfiguration.host(),
proxyConfiguration.port(),
proxyConfiguration.scheme(),
proxyConfiguration.nonProxyHosts());
}
CredentialsProvider credentialsProvider = configuration.credentialsProvider;
if (isAuthenticatedProxy(proxyConfiguration)) {
credentialsProvider = ApacheUtils.newProxyCredentialsProvider(proxyConfiguration);
}
if (routePlanner != null) {
builder.setRoutePlanner(routePlanner);
}
if (credentialsProvider != null) {
builder.setDefaultCredentialsProvider(credentialsProvider);
}
}
private ConnectionKeepAliveStrategy buildKeepAliveStrategy(AttributeMap standardOptions) {
long maxIdle = standardOptions.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis();
return maxIdle > 0 ? new SdkConnectionKeepAliveStrategy(maxIdle) : null;
}
private boolean useIdleConnectionReaper(AttributeMap standardOptions) {
return Boolean.TRUE.equals(standardOptions.get(SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS));
}
private boolean isAuthenticatedProxy(ProxyConfiguration proxyConfiguration) {
return proxyConfiguration.username() != null && proxyConfiguration.password() != null;
}
private boolean isProxyEnabled(ProxyConfiguration proxyConfiguration) {
return proxyConfiguration.host() != null
&& proxyConfiguration.port() > 0;
}
@Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
MetricCollector metricCollector = request.metricCollector().orElseGet(NoOpMetricCollector::create);
metricCollector.reportMetric(HTTP_CLIENT_NAME, clientName());
HttpRequestBase apacheRequest = toApacheRequest(request);
return new ExecutableHttpRequest() {
@Override
public HttpExecuteResponse call() throws IOException {
HttpExecuteResponse executeResponse = execute(apacheRequest, metricCollector);
collectPoolMetric(metricCollector);
return executeResponse;
}
@Override
public void abort() {
apacheRequest.abort();
}
};
}
@Override
public void close() {
HttpClientConnectionManager cm = httpClient.getHttpClientConnectionManager();
IdleConnectionReaper.getInstance().deregisterConnectionManager(cm);
cm.shutdown();
}
private HttpExecuteResponse execute(HttpRequestBase apacheRequest, MetricCollector metricCollector) throws IOException {
HttpClientContext localRequestContext = ApacheUtils.newClientContext(requestConfig.proxyConfiguration());
THREAD_LOCAL_REQUEST_METRIC_COLLECTOR.set(metricCollector);
try {
HttpResponse httpResponse = httpClient.execute(apacheRequest, localRequestContext);
return createResponse(httpResponse, apacheRequest);
} finally {
THREAD_LOCAL_REQUEST_METRIC_COLLECTOR.remove();
}
}
private HttpRequestBase toApacheRequest(HttpExecuteRequest request) {
return apacheHttpRequestFactory.create(request, requestConfig);
}
/**
* Creates and initializes an HttpResponse object suitable to be passed to an HTTP response
* handler object.
*
* @return The new, initialized HttpResponse object ready to be passed to an HTTP response handler object.
* @throws IOException If there were any problems getting any response information from the
* HttpClient method object.
*/
private HttpExecuteResponse createResponse(org.apache.http.HttpResponse apacheHttpResponse,
HttpRequestBase apacheRequest) throws IOException {
SdkHttpResponse.Builder responseBuilder =
SdkHttpResponse.builder()
.statusCode(apacheHttpResponse.getStatusLine().getStatusCode())
.statusText(apacheHttpResponse.getStatusLine().getReasonPhrase());
HeaderIterator headerIterator = apacheHttpResponse.headerIterator();
while (headerIterator.hasNext()) {
Header header = headerIterator.nextHeader();
responseBuilder.appendHeader(header.getName(), header.getValue());
}
AbortableInputStream responseBody = apacheHttpResponse.getEntity() != null ?
toAbortableInputStream(apacheHttpResponse, apacheRequest) : null;
return HttpExecuteResponse.builder().response(responseBuilder.build()).responseBody(responseBody).build();
}
private AbortableInputStream toAbortableInputStream(HttpResponse apacheHttpResponse, HttpRequestBase apacheRequest)
throws IOException {
return AbortableInputStream.create(apacheHttpResponse.getEntity().getContent(), apacheRequest::abort);
}
private ApacheHttpRequestConfig createRequestConfig(DefaultBuilder builder,
AttributeMap resolvedOptions) {
return ApacheHttpRequestConfig.builder()
.socketTimeout(resolvedOptions.get(SdkHttpConfigurationOption.READ_TIMEOUT))
.connectionTimeout(resolvedOptions.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT))
.connectionAcquireTimeout(
resolvedOptions.get(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT))
.proxyConfiguration(builder.proxyConfiguration)
.localAddress(Optional.ofNullable(builder.localAddress).orElse(null))
.expectContinueEnabled(Optional.ofNullable(builder.expectContinueEnabled)
.orElse(DefaultConfiguration.EXPECT_CONTINUE_ENABLED))
.build();
}
private void collectPoolMetric(MetricCollector metricCollector) {
HttpClientConnectionManager cm = httpClient.getHttpClientConnectionManager();
if (cm instanceof PoolingHttpClientConnectionManager && !(metricCollector instanceof NoOpMetricCollector)) {
PoolingHttpClientConnectionManager poolingCm = (PoolingHttpClientConnectionManager) cm;
PoolStats totalStats = poolingCm.getTotalStats();
metricCollector.reportMetric(MAX_CONCURRENCY, totalStats.getMax());
metricCollector.reportMetric(AVAILABLE_CONCURRENCY, totalStats.getAvailable());
metricCollector.reportMetric(LEASED_CONCURRENCY, totalStats.getLeased());
metricCollector.reportMetric(PENDING_CONCURRENCY_ACQUIRES, totalStats.getPending());
}
}
@Override
public String clientName() {
return CLIENT_NAME;
}
/**
* Builder for creating an instance of {@link SdkHttpClient}. The factory can be configured through the builder {@link
* #builder()}, once built it can create a {@link SdkHttpClient} via {@link #build()} or can be passed to the SDK
* client builders directly to have the SDK create and manage the HTTP client. See documentation on the service's respective
* client builder for more information on configuring the HTTP layer.
*
* <pre class="brush: java">
* SdkHttpClient httpClient =
* ApacheHttpClient.builder()
* .socketTimeout(Duration.ofSeconds(10))
* .build();
* </pre>
*/
public interface Builder extends SdkHttpClient.Builder<ApacheHttpClient.Builder> {
/**
* The amount of time to wait for data to be transferred over an established, open connection before the connection is
* timed out. A duration of 0 means infinity, and is not recommended.
*/
Builder socketTimeout(Duration socketTimeout);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out. A duration of 0
* means infinity, and is not recommended.
*/
Builder connectionTimeout(Duration connectionTimeout);
/**
* The amount of time to wait when acquiring a connection from the pool before giving up and timing out.
* @param connectionAcquisitionTimeout the timeout duration
* @return this builder for method chaining.
*/
Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout);
/**
* The maximum number of connections allowed in the connection pool. Each built HTTP client has its own private
* connection pool.
*/
Builder maxConnections(Integer maxConnections);
/**
* Configuration that defines how to communicate via an HTTP proxy.
*/
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
/**
* Configure the local address that the HTTP client should use for communication.
*/
Builder localAddress(InetAddress localAddress);
/**
* Configure whether the client should send an HTTP expect-continue handshake before each request.
*/
Builder expectContinueEnabled(Boolean expectContinueEnabled);
/**
* The maximum amount of time that a connection should be allowed to remain open, regardless of usage frequency.
*/
Builder connectionTimeToLive(Duration connectionTimeToLive);
/**
* Configure the maximum amount of time that a connection should be allowed to remain open while idle.
*/
Builder connectionMaxIdleTime(Duration maxIdleConnectionTimeout);
/**
* Configure whether the idle connections in the connection pool should be closed asynchronously.
* <p>
* When enabled, connections left idling for longer than {@link #connectionMaxIdleTime(Duration)} will be
* closed. This will not close connections currently in use. By default, this is enabled.
*/
Builder useIdleConnectionReaper(Boolean useConnectionReaper);
/**
* Configuration that defines a DNS resolver. If no matches are found, the default resolver is used.
*/
Builder dnsResolver(DnsResolver dnsResolver);
/**
* Configuration that defines a custom Socket factory. If set to a null value, a default factory is used.
* <p>
* When set to a non-null value, the use of a custom factory implies the configuration options TRUST_ALL_CERTIFICATES,
* TLS_TRUST_MANAGERS_PROVIDER, and TLS_KEY_MANAGERS_PROVIDER are ignored.
*/
Builder socketFactory(ConnectionSocketFactory socketFactory);
/**
* Configuration that defines an HTTP route planner that computes the route an HTTP request should take.
* May not be used in conjunction with {@link #proxyConfiguration(ProxyConfiguration)}.
*/
Builder httpRoutePlanner(HttpRoutePlanner proxyConfiguration);
/**
* Configuration that defines a custom credential provider for HTTP requests.
* May not be used in conjunction with {@link ProxyConfiguration#username()} and {@link ProxyConfiguration#password()}.
*/
Builder credentialsProvider(CredentialsProvider credentialsProvider);
/**
* Configure whether to enable or disable TCP KeepAlive.
* The configuration will be passed to the socket option {@link java.net.SocketOptions#SO_KEEPALIVE}.
* <p>
* By default, this is disabled.
* <p>
* When enabled, the actual KeepAlive mechanism is dependent on the Operating System and therefore additional TCP
* KeepAlive values (like timeout, number of packets, etc) must be configured via the Operating System (sysctl on
* Linux/Mac, and Registry values on Windows).
*/
Builder tcpKeepAlive(Boolean keepConnectionAlive);
/**
* Configure the {@link TlsKeyManagersProvider} that will provide the {@link javax.net.ssl.KeyManager}s to use
* when constructing the SSL context.
* <p>
* The default used by the client will be {@link SystemPropertyTlsKeyManagersProvider}. Configure an instance of
* {@link software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider} or another implementation of
* {@link TlsKeyManagersProvider} to override it.
*/
Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider);
/**
* Configure the {@link TlsTrustManagersProvider} that will provide the {@link javax.net.ssl.TrustManager}s to use
* when constructing the SSL context.
*/
Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider);
}
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder().build();
private InetAddress localAddress;
private Boolean expectContinueEnabled;
private HttpRoutePlanner httpRoutePlanner;
private CredentialsProvider credentialsProvider;
private DnsResolver dnsResolver;
private ConnectionSocketFactory socketFactory;
private DefaultBuilder() {
}
@Override
public Builder socketTimeout(Duration socketTimeout) {
standardOptions.put(SdkHttpConfigurationOption.READ_TIMEOUT, socketTimeout);
return this;
}
public void setSocketTimeout(Duration socketTimeout) {
socketTimeout(socketTimeout);
}
@Override
public Builder connectionTimeout(Duration connectionTimeout) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, connectionTimeout);
return this;
}
public void setConnectionTimeout(Duration connectionTimeout) {
connectionTimeout(connectionTimeout);
}
/**
* The amount of time to wait when acquiring a connection from the pool before giving up and timing out.
* @param connectionAcquisitionTimeout the timeout duration
* @return this builder for method chaining.
*/
@Override
public Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
Validate.isPositive(connectionAcquisitionTimeout, "connectionAcquisitionTimeout");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT, connectionAcquisitionTimeout);
return this;
}
public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
connectionAcquisitionTimeout(connectionAcquisitionTimeout);
}
@Override
public Builder maxConnections(Integer maxConnections) {
standardOptions.put(SdkHttpConfigurationOption.MAX_CONNECTIONS, maxConnections);
return this;
}
public void setMaxConnections(Integer maxConnections) {
maxConnections(maxConnections);
}
@Override
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
public void setProxyConfiguration(ProxyConfiguration proxyConfiguration) {
proxyConfiguration(proxyConfiguration);
}
@Override
public Builder localAddress(InetAddress localAddress) {
this.localAddress = localAddress;
return this;
}
public void setLocalAddress(InetAddress localAddress) {
localAddress(localAddress);
}
@Override
public Builder expectContinueEnabled(Boolean expectContinueEnabled) {
this.expectContinueEnabled = expectContinueEnabled;
return this;
}
public void setExpectContinueEnabled(Boolean useExpectContinue) {
this.expectContinueEnabled = useExpectContinue;
}
@Override
public Builder connectionTimeToLive(Duration connectionTimeToLive) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE, connectionTimeToLive);
return this;
}
public void setConnectionTimeToLive(Duration connectionTimeToLive) {
connectionTimeToLive(connectionTimeToLive);
}
@Override
public Builder connectionMaxIdleTime(Duration maxIdleConnectionTimeout) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, maxIdleConnectionTimeout);
return this;
}
public void setConnectionMaxIdleTime(Duration connectionMaxIdleTime) {
connectionMaxIdleTime(connectionMaxIdleTime);
}
@Override
public Builder useIdleConnectionReaper(Boolean useIdleConnectionReaper) {
standardOptions.put(SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS, useIdleConnectionReaper);
return this;
}
public void setUseIdleConnectionReaper(Boolean useIdleConnectionReaper) {
useIdleConnectionReaper(useIdleConnectionReaper);
}
@Override
public Builder dnsResolver(DnsResolver dnsResolver) {
this.dnsResolver = dnsResolver;
return this;
}
public void setDnsResolver(DnsResolver dnsResolver) {
dnsResolver(dnsResolver);
}
@Override
public Builder socketFactory(ConnectionSocketFactory socketFactory) {
this.socketFactory = socketFactory;
return this;
}
public void setSocketFactory(ConnectionSocketFactory socketFactory) {
socketFactory(socketFactory);
}
@Override
public Builder httpRoutePlanner(HttpRoutePlanner httpRoutePlanner) {
this.httpRoutePlanner = httpRoutePlanner;
return this;
}
public void setHttpRoutePlanner(HttpRoutePlanner httpRoutePlanner) {
httpRoutePlanner(httpRoutePlanner);
}
@Override
public Builder credentialsProvider(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
public void setCredentialsProvider(CredentialsProvider credentialsProvider) {
credentialsProvider(credentialsProvider);
}
@Override
public Builder tcpKeepAlive(Boolean keepConnectionAlive) {
standardOptions.put(SdkHttpConfigurationOption.TCP_KEEPALIVE, keepConnectionAlive);
return this;
}
public void setTcpKeepAlive(Boolean keepConnectionAlive) {
tcpKeepAlive(keepConnectionAlive);
}
@Override
public Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER, tlsKeyManagersProvider);
return this;
}
public void setTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
tlsKeyManagersProvider(tlsKeyManagersProvider);
}
@Override
public Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER, tlsTrustManagersProvider);
return this;
}
public void setTlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
tlsTrustManagersProvider(tlsTrustManagersProvider);
}
@Override
public SdkHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
AttributeMap resolvedOptions = standardOptions.build().merge(serviceDefaults).merge(
SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS);
return new ApacheHttpClient(this, resolvedOptions);
}
}
private static class ApacheConnectionManagerFactory {
public HttpClientConnectionManager create(ApacheHttpClient.DefaultBuilder configuration,
AttributeMap standardOptions) {
ConnectionSocketFactory sslsf = getPreferredSocketFactory(configuration, standardOptions);
PoolingHttpClientConnectionManager cm = new
PoolingHttpClientConnectionManager(
createSocketFactoryRegistry(sslsf),
null,
DefaultSchemePortResolver.INSTANCE,
configuration.dnsResolver,
standardOptions.get(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE).toMillis(),
TimeUnit.MILLISECONDS);
cm.setDefaultMaxPerRoute(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
cm.setMaxTotal(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
cm.setDefaultSocketConfig(buildSocketConfig(standardOptions));
return cm;
}
private ConnectionSocketFactory getPreferredSocketFactory(ApacheHttpClient.DefaultBuilder configuration,
AttributeMap standardOptions) {
return Optional.ofNullable(configuration.socketFactory)
.orElseGet(() -> new SdkTlsSocketFactory(getSslContext(standardOptions),
getHostNameVerifier(standardOptions)));
}
private HostnameVerifier getHostNameVerifier(AttributeMap standardOptions) {
return standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)
? NoopHostnameVerifier.INSTANCE
: SSLConnectionSocketFactory.getDefaultHostnameVerifier();
}
private SSLContext getSslContext(AttributeMap standardOptions) {
Validate.isTrue(standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) == null ||
!standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES),
"A TlsTrustManagerProvider can't be provided if TrustAllCertificates is also set");
TrustManager[] trustManagers = null;
if (standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) != null) {
trustManagers = standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER).trustManagers();
}
if (standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)) {
log.warn(() -> "SSL Certificate verification is disabled. This is not a safe setting and should only be "
+ "used for testing.");
trustManagers = trustAllTrustManager();
}
TlsKeyManagersProvider provider = standardOptions.get(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER);
KeyManager[] keyManagers = provider.keyManagers();
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
// http://download.java.net/jdk9/docs/technotes/guides/security/jsse/JSSERefGuide.html
sslcontext.init(keyManagers, trustManagers, null);
return sslcontext;
} catch (final NoSuchAlgorithmException | KeyManagementException ex) {
throw new SSLInitializationException(ex.getMessage(), ex);
}
}
/**
* Insecure trust manager to trust all certs. Should only be used for testing.
*/
private static TrustManager[] trustAllTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
log.debug(() -> "Accepting a client certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
log.debug(() -> "Accepting a client certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
}
private SocketConfig buildSocketConfig(AttributeMap standardOptions) {
return SocketConfig.custom()
.setSoKeepAlive(standardOptions.get(SdkHttpConfigurationOption.TCP_KEEPALIVE))
.setSoTimeout(
saturatedCast(standardOptions.get(SdkHttpConfigurationOption.READ_TIMEOUT)
.toMillis()))
.setTcpNoDelay(true)
.build();
}
private Registry<ConnectionSocketFactory> createSocketFactoryRegistry(ConnectionSocketFactory sslSocketFactory) {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
}
}
}
| 1,252 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/ApacheHttpRequestConfig.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import java.net.InetAddress;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.apache.ProxyConfiguration;
/**
* Configuration needed when building an Apache request. Note that at this time, we only support client level configuration so
* all of these settings are supplied when creating the client.
*/
@SdkInternalApi
public final class ApacheHttpRequestConfig {
private final Duration socketTimeout;
private final Duration connectionTimeout;
private final Duration connectionAcquireTimeout;
private final InetAddress localAddress;
private final boolean expectContinueEnabled;
private final ProxyConfiguration proxyConfiguration;
private ApacheHttpRequestConfig(Builder builder) {
this.socketTimeout = builder.socketTimeout;
this.connectionTimeout = builder.connectionTimeout;
this.connectionAcquireTimeout = builder.connectionAcquireTimeout;
this.localAddress = builder.localAddress;
this.expectContinueEnabled = builder.expectContinueEnabled;
this.proxyConfiguration = builder.proxyConfiguration;
}
public Duration socketTimeout() {
return socketTimeout;
}
public Duration connectionTimeout() {
return connectionTimeout;
}
public Duration connectionAcquireTimeout() {
return connectionAcquireTimeout;
}
public InetAddress localAddress() {
return localAddress;
}
public boolean expectContinueEnabled() {
return expectContinueEnabled;
}
public ProxyConfiguration proxyConfiguration() {
return proxyConfiguration;
}
/**
* @return Builder instance to construct a {@link ApacheHttpRequestConfig}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link ApacheHttpRequestConfig}.
*/
public static final class Builder {
private Duration socketTimeout;
private Duration connectionTimeout;
private Duration connectionAcquireTimeout;
private InetAddress localAddress;
private boolean expectContinueEnabled;
private ProxyConfiguration proxyConfiguration;
private Builder() {
}
public Builder socketTimeout(Duration socketTimeout) {
this.socketTimeout = socketTimeout;
return this;
}
public Builder connectionTimeout(Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return this;
}
public Builder connectionAcquireTimeout(Duration connectionAcquireTimeout) {
this.connectionAcquireTimeout = connectionAcquireTimeout;
return this;
}
public Builder localAddress(InetAddress localAddress) {
this.localAddress = localAddress;
return this;
}
public Builder expectContinueEnabled(boolean expectContinueEnabled) {
this.expectContinueEnabled = expectContinueEnabled;
return this;
}
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
/**
* @return An immutable {@link ApacheHttpRequestConfig} object.
*/
public ApacheHttpRequestConfig build() {
return new ApacheHttpRequestConfig(this);
}
}
}
| 1,253 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/RepeatableInputStreamRequestEntity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import static software.amazon.awssdk.http.Header.CHUNKED;
import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Optional;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.InputStreamEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.HttpExecuteRequest;
/**
* Custom implementation of {@link org.apache.http.HttpEntity} that delegates to an
* {@link RepeatableInputStreamRequestEntity}, with the one notable difference, that if
* the underlying InputStream supports being reset, this RequestEntity will
* report that it is repeatable and will reset the stream on all subsequent
* attempts to write out the request.
*/
@SdkInternalApi
public class RepeatableInputStreamRequestEntity extends BasicHttpEntity {
private static final Logger log = LoggerFactory.getLogger(RepeatableInputStreamRequestEntity.class);
/**
* True if the request entity hasn't been written out yet
*/
private boolean firstAttempt = true;
/**
* True if the "Transfer-Encoding:chunked" header is present
*/
private boolean isChunked;
/**
* The underlying InputStreamEntity being delegated to
*/
private InputStreamEntity inputStreamRequestEntity;
/**
* The InputStream containing the content to write out
*/
private InputStream content;
/**
* Record the original exception if we do attempt a retry, so that if the
* retry fails, we can report the original exception. Otherwise, we're most
* likely masking the real exception with an error about not being able to
* reset far enough back in the input stream.
*/
private IOException originalException;
/**
* Creates a new RepeatableInputStreamRequestEntity using the information
* from the specified request. If the input stream containing the request's
* contents is repeatable, then this RequestEntity will report as being
* repeatable.
*
* @param request The details of the request being written out (content type,
* content length, and content).
*/
public RepeatableInputStreamRequestEntity(final HttpExecuteRequest request) {
isChunked = request.httpRequest().matchingHeaders(TRANSFER_ENCODING).contains(CHUNKED);
setChunked(isChunked);
/*
* If we don't specify a content length when we instantiate our
* InputStreamRequestEntity, then HttpClient will attempt to
* buffer the entire stream contents into memory to determine
* the content length.
*/
long contentLength = request.httpRequest().firstMatchingHeader("Content-Length")
.map(this::parseContentLength)
.orElse(-1L);
content = getContent(request.contentStreamProvider());
// TODO v2 MetricInputStreamEntity
inputStreamRequestEntity = new InputStreamEntity(content, contentLength);
setContent(content);
setContentLength(contentLength);
request.httpRequest().firstMatchingHeader("Content-Type").ifPresent(contentType -> {
inputStreamRequestEntity.setContentType(contentType);
setContentType(contentType);
});
}
private long parseContentLength(String contentLength) {
try {
return Long.parseLong(contentLength);
} catch (NumberFormatException nfe) {
log.warn("Unable to parse content length from request. Buffering contents in memory.");
return -1;
}
}
/**
* @return The request content input stream or an empty input stream if there is no content.
*/
private InputStream getContent(Optional<ContentStreamProvider> contentStreamProvider) {
return contentStreamProvider.map(ContentStreamProvider::newStream).orElseGet(() -> new ByteArrayInputStream(new byte[0]));
}
@Override
public boolean isChunked() {
return isChunked;
}
/**
* Returns true if the underlying InputStream supports marking/reseting or
* if the underlying InputStreamRequestEntity is repeatable.
*/
@Override
public boolean isRepeatable() {
return content.markSupported() || inputStreamRequestEntity.isRepeatable();
}
/**
* Resets the underlying InputStream if this isn't the first attempt to
* write out the request, otherwise simply delegates to
* InputStreamRequestEntity to write out the data.
* <p>
* If an error is encountered the first time we try to write the request
* entity, we remember the original exception, and report that as the root
* cause if we continue to encounter errors, rather than masking the
* original error.
*/
@Override
public void writeTo(OutputStream output) throws IOException {
try {
if (!firstAttempt && isRepeatable()) {
content.reset();
}
firstAttempt = false;
inputStreamRequestEntity.writeTo(output);
} catch (IOException ioe) {
if (originalException == null) {
originalException = ioe;
}
throw originalException;
}
}
}
| 1,254 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/SdkProxyRoutePlanner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import java.util.Set;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* SdkProxyRoutePlanner delegates a Proxy Route Planner from the settings instead of the
* system properties. It will use the proxy created from proxyHost and proxyPort and
* filter the hosts who matches nonProxyHosts pattern.
*/
@SdkInternalApi
public class SdkProxyRoutePlanner extends DefaultRoutePlanner {
private HttpHost proxy;
private Set<String> hostPatterns;
public SdkProxyRoutePlanner(String proxyHost, int proxyPort, String proxyProtocol, Set<String> nonProxyHosts) {
super(DefaultSchemePortResolver.INSTANCE);
proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol);
this.hostPatterns = nonProxyHosts;
}
private boolean doesTargetMatchNonProxyHosts(HttpHost target) {
if (hostPatterns == null) {
return false;
}
String targetHost = lowerCase(target.getHostName());
for (String pattern : hostPatterns) {
if (targetHost.matches(pattern)) {
return true;
}
}
return false;
}
@Override
protected HttpHost determineProxy(
final HttpHost target,
final HttpRequest request,
final HttpContext context) throws HttpException {
return doesTargetMatchNonProxyHosts(target) ? null : proxy;
}
}
| 1,255 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/DefaultConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Default configuration values.
*/
@SdkInternalApi
public final class DefaultConfiguration {
public static final Boolean EXPECT_CONTINUE_ENABLED = Boolean.TRUE;
private DefaultConfiguration() {
}
}
| 1,256 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/SdkConnectionReuseStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultClientConnectionReuseStrategy;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Do not reuse connections that returned a 5xx error.
*
* <p>This is not strictly the behavior we would want in an AWS client, because sometimes we might want to keep a connection open
* (e.g. an undocumented service's 503 'SlowDown') and sometimes we might want to close the connection (e.g. S3's 400
* RequestTimeout or Glacier's 408 RequestTimeoutException), but this is good enough for the majority of services, and the ones
* for which it is not should not be impacted too harshly.
*/
@SdkInternalApi
public class SdkConnectionReuseStrategy extends DefaultClientConnectionReuseStrategy {
@Override
public boolean keepAlive(HttpResponse response, HttpContext context) {
if (!super.keepAlive(response, context)) {
return false;
}
if (response == null || response.getStatusLine() == null) {
return false;
}
return !is500(response);
}
private boolean is500(HttpResponse httpResponse) {
return httpResponse.getStatusLine().getStatusCode() / 100 == 5;
}
}
| 1,257 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/impl/ApacheHttpRequestFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.RepeatableInputStreamRequestEntity;
import software.amazon.awssdk.http.apache.internal.utils.ApacheUtils;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
/**
* Responsible for creating Apache HttpClient 4 request objects.
*/
@SdkInternalApi
public class ApacheHttpRequestFactory {
private static final List<String> IGNORE_HEADERS = Arrays.asList(HttpHeaders.CONTENT_LENGTH, HttpHeaders.HOST,
HttpHeaders.TRANSFER_ENCODING);
public HttpRequestBase create(final HttpExecuteRequest request, final ApacheHttpRequestConfig requestConfig) {
HttpRequestBase base = createApacheRequest(request, sanitizeUri(request.httpRequest()));
addHeadersToRequest(base, request.httpRequest());
addRequestConfig(base, request.httpRequest(), requestConfig);
return base;
}
/**
* The Apache HTTP client doesn't allow consecutive slashes in the URI. For S3
* and other AWS services, this is allowed and required. This methods replaces
* any occurrence of "//" in the URI path with "/%2F".
*
* @see SdkHttpRequest#getUri()
* @param request The existing request
* @return a new String containing the modified URI
*/
private URI sanitizeUri(SdkHttpRequest request) {
String path = request.encodedPath();
if (path.contains("//")) {
int port = request.port();
String protocol = request.protocol();
String newPath = StringUtils.replace(path, "//", "/%2F");
String encodedQueryString = request.encodedQueryParameters().map(value -> "?" + value).orElse("");
// Do not include the port in the URI when using the default port for the protocol.
String portString = SdkHttpUtils.isUsingStandardPort(protocol, port) ?
"" : ":" + port;
return URI.create(protocol + "://" + request.host() + portString + newPath + encodedQueryString);
}
return request.getUri();
}
private void addRequestConfig(final HttpRequestBase base,
final SdkHttpRequest request,
final ApacheHttpRequestConfig requestConfig) {
int connectTimeout = saturatedCast(requestConfig.connectionTimeout().toMillis());
int connectAcquireTimeout = saturatedCast(requestConfig.connectionAcquireTimeout().toMillis());
RequestConfig.Builder requestConfigBuilder = RequestConfig
.custom()
.setConnectionRequestTimeout(connectAcquireTimeout)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(saturatedCast(requestConfig.socketTimeout().toMillis()))
.setLocalAddress(requestConfig.localAddress());
ApacheUtils.disableNormalizeUri(requestConfigBuilder);
/*
* Enable 100-continue support for PUT operations, since this is
* where we're potentially uploading large amounts of data and want
* to find out as early as possible if an operation will fail. We
* don't want to do this for all operations since it will cause
* extra latency in the network interaction.
*/
if (SdkHttpMethod.PUT == request.method() && requestConfig.expectContinueEnabled()) {
requestConfigBuilder.setExpectContinueEnabled(true);
}
base.setConfig(requestConfigBuilder.build());
}
private HttpRequestBase createApacheRequest(HttpExecuteRequest request, URI uri) {
switch (request.httpRequest().method()) {
case HEAD:
return new HttpHead(uri);
case GET:
return new HttpGet(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case PATCH:
return wrapEntity(request, new HttpPatch(uri));
case POST:
return wrapEntity(request, new HttpPost(uri));
case PUT:
return wrapEntity(request, new HttpPut(uri));
default:
throw new RuntimeException("Unknown HTTP method name: " + request.httpRequest().method());
}
}
private HttpRequestBase wrapEntity(HttpExecuteRequest request,
HttpEntityEnclosingRequestBase entityEnclosingRequest) {
/*
* We should never reuse the entity of the previous request, since
* reading from the buffered entity will bypass reading from the
* original request content. And if the content contains InputStream
* wrappers that were added for validation-purpose (e.g.
* Md5DigestCalculationInputStream), these wrappers would never be
* read and updated again after AmazonHttpClient resets it in
* preparation for the retry. Eventually, these wrappers would
* return incorrect validation result.
*/
if (request.contentStreamProvider().isPresent()) {
HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
if (!request.httpRequest().firstMatchingHeader(HttpHeaders.CONTENT_LENGTH).isPresent() && !entity.isChunked()) {
entity = ApacheUtils.newBufferedHttpEntity(entity);
}
entityEnclosingRequest.setEntity(entity);
}
return entityEnclosingRequest;
}
/**
* Configures the headers in the specified Apache HTTP request.
*/
private void addHeadersToRequest(HttpRequestBase httpRequest, SdkHttpRequest request) {
httpRequest.addHeader(HttpHeaders.HOST, getHostHeaderValue(request));
// Copy over any other headers already in our request
request.forEachHeader((name, value) -> {
// HttpClient4 fills in the Content-Length header and complains if
// it's already present, so we skip it here. We also skip the Host
// header to avoid sending it twice, which will interfere with some
// signing schemes.
if (!IGNORE_HEADERS.contains(name)) {
for (String headerValue : value) {
httpRequest.addHeader(name, headerValue);
}
}
});
}
private String getHostHeaderValue(SdkHttpRequest request) {
// Apache doesn't allow us to include the port in the host header if it's a standard port for that protocol. For that
// reason, we don't include the port when we sign the message. See {@link SdkHttpRequest#port()}.
return !SdkHttpUtils.isUsingStandardPort(request.protocol(), request.port())
? request.host() + ":" + request.port()
: request.host();
}
}
| 1,258 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/impl/ApacheSdkHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An instance of {@link ConnectionManagerAwareHttpClient} that delegates all the requests to the given http client.
*/
@SdkInternalApi
public class ApacheSdkHttpClient implements ConnectionManagerAwareHttpClient {
private final HttpClient delegate;
private final HttpClientConnectionManager cm;
public ApacheSdkHttpClient(final HttpClient delegate,
final HttpClientConnectionManager cm) {
if (delegate == null) {
throw new IllegalArgumentException("delegate " +
"cannot be null");
}
if (cm == null) {
throw new IllegalArgumentException("connection manager " +
"cannot be null");
}
this.delegate = delegate;
this.cm = cm;
}
@Override
public HttpParams getParams() {
return delegate.getParams();
}
@Override
public ClientConnectionManager getConnectionManager() {
return delegate.getConnectionManager();
}
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException {
return delegate.execute(request);
}
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
return delegate.execute(request, context);
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
return delegate.execute(target, request);
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {
return delegate.execute(target, request, context);
}
@Override
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException {
return delegate.execute(request, responseHandler);
}
@Override
public <T> T execute(HttpUriRequest request,
ResponseHandler<? extends T> responseHandler,
HttpContext context) throws IOException {
return delegate.execute(request, responseHandler, context);
}
@Override
public <T> T execute(HttpHost target,
HttpRequest request,
ResponseHandler<? extends T> responseHandler) throws IOException {
return delegate.execute(target, request, responseHandler);
}
@Override
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler,
HttpContext context) throws IOException {
return delegate.execute(target, request, responseHandler, context);
}
@Override
public HttpClientConnectionManager getHttpClientConnectionManager() {
return cm;
}
}
| 1,259 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/impl/ConnectionManagerAwareHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.HttpClientConnectionManager;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An extension of Apache's HttpClient that expose the connection manager
* associated with the client.
*/
@SdkInternalApi
public interface ConnectionManagerAwareHttpClient extends HttpClient {
/**
* Returns the {@link HttpClientConnectionManager} associated with the
* http client.
*/
HttpClientConnectionManager getHttpClientConnectionManager();
}
| 1,260 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/DelegateSslSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public class DelegateSslSocket extends SSLSocket {
protected final SSLSocket sock;
public DelegateSslSocket(SSLSocket sock) {
this.sock = sock;
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
sock.connect(endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
sock.connect(endpoint, timeout);
}
@Override
public void bind(SocketAddress bindpoint) throws IOException {
sock.bind(bindpoint);
}
@Override
public InetAddress getInetAddress() {
return sock.getInetAddress();
}
@Override
public InetAddress getLocalAddress() {
return sock.getLocalAddress();
}
@Override
public int getPort() {
return sock.getPort();
}
@Override
public int getLocalPort() {
return sock.getLocalPort();
}
@Override
public SocketAddress getRemoteSocketAddress() {
return sock.getRemoteSocketAddress();
}
@Override
public SocketAddress getLocalSocketAddress() {
return sock.getLocalSocketAddress();
}
@Override
public SocketChannel getChannel() {
return sock.getChannel();
}
@Override
public InputStream getInputStream() throws IOException {
return sock.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return sock.getOutputStream();
}
@Override
public void setTcpNoDelay(boolean on) throws SocketException {
sock.setTcpNoDelay(on);
}
@Override
public boolean getTcpNoDelay() throws SocketException {
return sock.getTcpNoDelay();
}
@Override
public void setSoLinger(boolean on, int linger) throws SocketException {
sock.setSoLinger(on, linger);
}
@Override
public int getSoLinger() throws SocketException {
return sock.getSoLinger();
}
@Override
public void sendUrgentData(int data) throws IOException {
sock.sendUrgentData(data);
}
@Override
public void setOOBInline(boolean on) throws SocketException {
sock.setOOBInline(on);
}
@Override
public boolean getOOBInline() throws SocketException {
return sock.getOOBInline();
}
@Override
public void setSoTimeout(int timeout) throws SocketException {
sock.setSoTimeout(timeout);
}
@Override
public int getSoTimeout() throws SocketException {
return sock.getSoTimeout();
}
@Override
public void setSendBufferSize(int size) throws SocketException {
sock.setSendBufferSize(size);
}
@Override
public int getSendBufferSize() throws SocketException {
return sock.getSendBufferSize();
}
@Override
public void setReceiveBufferSize(int size) throws SocketException {
sock.setReceiveBufferSize(size);
}
@Override
public int getReceiveBufferSize() throws SocketException {
return sock.getReceiveBufferSize();
}
@Override
public void setKeepAlive(boolean on) throws SocketException {
sock.setKeepAlive(on);
}
@Override
public boolean getKeepAlive() throws SocketException {
return sock.getKeepAlive();
}
@Override
public void setTrafficClass(int tc) throws SocketException {
sock.setTrafficClass(tc);
}
@Override
public int getTrafficClass() throws SocketException {
return sock.getTrafficClass();
}
@Override
public void setReuseAddress(boolean on) throws SocketException {
sock.setReuseAddress(on);
}
@Override
public boolean getReuseAddress() throws SocketException {
return sock.getReuseAddress();
}
@Override
public void close() throws IOException {
sock.close();
}
@Override
public void shutdownInput() throws IOException {
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
sock.shutdownOutput();
}
@Override
public String toString() {
return sock.toString();
}
@Override
public boolean isConnected() {
return sock.isConnected();
}
@Override
public boolean isBound() {
return sock.isBound();
}
@Override
public boolean isClosed() {
return sock.isClosed();
}
@Override
public boolean isInputShutdown() {
return sock.isInputShutdown();
}
@Override
public boolean isOutputShutdown() {
return sock.isOutputShutdown();
}
@Override
public void setPerformancePreferences(int connectionTime, int latency,
int bandwidth) {
sock.setPerformancePreferences(connectionTime, latency, bandwidth);
}
@Override
public String[] getSupportedCipherSuites() {
return sock.getSupportedCipherSuites();
}
@Override
public String[] getEnabledCipherSuites() {
return sock.getEnabledCipherSuites();
}
@Override
public void setEnabledCipherSuites(String[] suites) {
sock.setEnabledCipherSuites(suites);
}
@Override
public String[] getSupportedProtocols() {
return sock.getSupportedProtocols();
}
@Override
public String[] getEnabledProtocols() {
return sock.getEnabledProtocols();
}
@Override
public void setEnabledProtocols(String[] protocols) {
sock.setEnabledProtocols(protocols);
}
@Override
public SSLSession getSession() {
return sock.getSession();
}
@Override
public void addHandshakeCompletedListener(
HandshakeCompletedListener listener) {
sock.addHandshakeCompletedListener(listener);
}
@Override
public void removeHandshakeCompletedListener(
HandshakeCompletedListener listener) {
sock.removeHandshakeCompletedListener(listener);
}
@Override
public void startHandshake() throws IOException {
sock.startHandshake();
}
@Override
public void setUseClientMode(boolean mode) {
sock.setUseClientMode(mode);
}
@Override
public boolean getUseClientMode() {
return sock.getUseClientMode();
}
@Override
public void setNeedClientAuth(boolean need) {
sock.setNeedClientAuth(need);
}
@Override
public boolean getNeedClientAuth() {
return sock.getNeedClientAuth();
}
@Override
public void setWantClientAuth(boolean want) {
sock.setWantClientAuth(want);
}
@Override
public boolean getWantClientAuth() {
return sock.getWantClientAuth();
}
@Override
public void setEnableSessionCreation(boolean flag) {
sock.setEnableSessionCreation(flag);
}
@Override
public boolean getEnableSessionCreation() {
return sock.getEnableSessionCreation();
}
}
| 1,261 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/SdkSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public class SdkSocket extends DelegateSocket {
private static final Logger log = Logger.loggerFor(SdkSocket.class);
public SdkSocket(Socket sock) {
super(sock);
log.debug(() -> "created: " + endpoint());
}
/**
* Returns the endpoint in the format of "address:port"
*/
private String endpoint() {
return sock.getInetAddress() + ":" + sock.getPort();
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint, timeout);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void close() throws IOException {
log.debug(() -> "closing " + endpoint());
sock.close();
}
@Override
public void shutdownInput() throws IOException {
log.debug(() -> "shutting down input of " + endpoint());
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
log.debug(() -> "shutting down output of " + endpoint());
sock.shutdownOutput();
}
}
| 1,262 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/DelegateSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Socket delegate class. Subclasses could extend this class, so that
* they only need to override methods they are interested in enhancing.
*/
@SdkInternalApi
public class DelegateSocket extends Socket {
protected final Socket sock;
public DelegateSocket(Socket sock) {
this.sock = sock;
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
sock.connect(endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
sock.connect(endpoint, timeout);
}
@Override
public void bind(SocketAddress bindpoint) throws IOException {
sock.bind(bindpoint);
}
@Override
public InetAddress getInetAddress() {
return sock.getInetAddress();
}
@Override
public InetAddress getLocalAddress() {
return sock.getLocalAddress();
}
@Override
public int getPort() {
return sock.getPort();
}
@Override
public int getLocalPort() {
return sock.getLocalPort();
}
@Override
public SocketAddress getRemoteSocketAddress() {
return sock.getRemoteSocketAddress();
}
@Override
public SocketAddress getLocalSocketAddress() {
return sock.getLocalSocketAddress();
}
@Override
public SocketChannel getChannel() {
return sock.getChannel();
}
@Override
public InputStream getInputStream() throws IOException {
return sock.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return sock.getOutputStream();
}
@Override
public void setTcpNoDelay(boolean on) throws SocketException {
sock.setTcpNoDelay(on);
}
@Override
public boolean getTcpNoDelay() throws SocketException {
return sock.getTcpNoDelay();
}
@Override
public void setSoLinger(boolean on, int linger) throws SocketException {
sock.setSoLinger(on, linger);
}
@Override
public int getSoLinger() throws SocketException {
return sock.getSoLinger();
}
@Override
public void sendUrgentData(int data) throws IOException {
sock.sendUrgentData(data);
}
@Override
public void setOOBInline(boolean on) throws SocketException {
sock.setOOBInline(on);
}
@Override
public boolean getOOBInline() throws SocketException {
return sock.getOOBInline();
}
@Override
public void setSoTimeout(int timeout) throws SocketException {
sock.setSoTimeout(timeout);
}
@Override
public int getSoTimeout() throws SocketException {
return sock.getSoTimeout();
}
@Override
public void setSendBufferSize(int size) throws SocketException {
sock.setSendBufferSize(size);
}
@Override
public int getSendBufferSize() throws SocketException {
return sock.getSendBufferSize();
}
@Override
public void setReceiveBufferSize(int size) throws SocketException {
sock.setReceiveBufferSize(size);
}
@Override
public int getReceiveBufferSize() throws SocketException {
return sock.getReceiveBufferSize();
}
@Override
public void setKeepAlive(boolean on) throws SocketException {
sock.setKeepAlive(on);
}
@Override
public boolean getKeepAlive() throws SocketException {
return sock.getKeepAlive();
}
@Override
public void setTrafficClass(int tc) throws SocketException {
sock.setTrafficClass(tc);
}
@Override
public int getTrafficClass() throws SocketException {
return sock.getTrafficClass();
}
@Override
public void setReuseAddress(boolean on) throws SocketException {
sock.setReuseAddress(on);
}
@Override
public boolean getReuseAddress() throws SocketException {
return sock.getReuseAddress();
}
@Override
public void close() throws IOException {
sock.close();
}
@Override
public void shutdownInput() throws IOException {
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
sock.shutdownOutput();
}
@Override
public String toString() {
return sock.toString();
}
@Override
public boolean isConnected() {
return sock.isConnected();
}
@Override
public boolean isBound() {
return sock.isBound();
}
@Override
public boolean isClosed() {
return sock.isClosed();
}
@Override
public boolean isInputShutdown() {
return sock.isInputShutdown();
}
@Override
public boolean isOutputShutdown() {
return sock.isOutputShutdown();
}
@Override
public void setPerformancePreferences(int connectionTime, int latency,
int bandwidth) {
sock.setPerformancePreferences(connectionTime, latency, bandwidth);
}
}
| 1,263 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/SdkSslSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.net.SocketAddress;
import javax.net.ssl.SSLSocket;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public class SdkSslSocket extends DelegateSslSocket {
private static final Logger log = Logger.loggerFor(SdkSslSocket.class);
public SdkSslSocket(SSLSocket sock) {
super(sock);
log.debug(() -> "created: " + endpoint());
}
/**
* Returns the endpoint in the format of "address:port"
*/
private String endpoint() {
return sock.getInetAddress() + ":" + sock.getPort();
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint, timeout);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void close() throws IOException {
log.debug(() -> "closing " + endpoint());
sock.close();
}
@Override
public void shutdownInput() throws IOException {
log.debug(() -> "shutting down input of " + endpoint());
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
log.debug(() -> "shutting down output of " + endpoint());
sock.shutdownOutput();
}
}
| 1,264 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/utils/ApacheUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.utils;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.apache.ProxyConfiguration;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.ReflectionMethodInvoker;
@SdkInternalApi
public final class ApacheUtils {
private static final Logger logger = Logger.loggerFor(ApacheUtils.class);
private static final ReflectionMethodInvoker<RequestConfig.Builder, RequestConfig.Builder> NORMALIZE_URI_INVOKER;
static {
// Attempt to initialize the invoker once on class-load. If it fails, it will not be attempted again, but we'll
// use that opportunity to log a warning.
NORMALIZE_URI_INVOKER =
new ReflectionMethodInvoker<>(RequestConfig.Builder.class,
RequestConfig.Builder.class,
"setNormalizeUri",
boolean.class);
try {
NORMALIZE_URI_INVOKER.initialize();
} catch (NoSuchMethodException ignored) {
noSuchMethodThrownByNormalizeUriInvoker();
}
}
private ApacheUtils() {
}
/**
* Utility function for creating a new BufferedEntity and wrapping any errors
* as a SdkClientException.
*
* @param entity The HTTP entity to wrap with a buffered HTTP entity.
* @return A new BufferedHttpEntity wrapping the specified entity.
*/
public static HttpEntity newBufferedHttpEntity(HttpEntity entity) {
try {
return new BufferedHttpEntity(entity);
} catch (IOException e) {
throw new UncheckedIOException("Unable to create HTTP entity: " + e.getMessage(), e);
}
}
/**
* Returns a new HttpClientContext used for request execution.
*/
public static HttpClientContext newClientContext(ProxyConfiguration proxyConfiguration) {
HttpClientContext clientContext = new HttpClientContext();
addPreemptiveAuthenticationProxy(clientContext, proxyConfiguration);
RequestConfig.Builder builder = RequestConfig.custom();
disableNormalizeUri(builder);
clientContext.setRequestConfig(builder.build());
return clientContext;
}
/**
* From Apache v4.5.8, normalization should be disabled or AWS requests with special characters in URI path will fail
* with Signature Errors.
* <p>
* setNormalizeUri is added only in 4.5.8, so customers using the latest version of SDK with old versions (4.5.6 or less)
* of Apache httpclient will see NoSuchMethodError. Hence this method will suppress the error.
*
* Do not use Apache version 4.5.7 as it breaks URI paths with special characters and there is no option
* to disable normalization.
* </p>
*
* For more information, See https://github.com/aws/aws-sdk-java/issues/1919
*/
public static void disableNormalizeUri(RequestConfig.Builder requestConfigBuilder) {
// For efficiency, do not attempt to call the invoker again if it failed to initialize on class-load
if (NORMALIZE_URI_INVOKER.isInitialized()) {
try {
NORMALIZE_URI_INVOKER.invoke(requestConfigBuilder, false);
} catch (NoSuchMethodException ignored) {
noSuchMethodThrownByNormalizeUriInvoker();
}
}
}
/**
* Returns a new Credentials Provider for use with proxy authentication.
*/
public static CredentialsProvider newProxyCredentialsProvider(ProxyConfiguration proxyConfiguration) {
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(newAuthScope(proxyConfiguration), newNtCredentials(proxyConfiguration));
return provider;
}
/**
* Returns a new instance of NTCredentials used for proxy authentication.
*/
private static Credentials newNtCredentials(ProxyConfiguration proxyConfiguration) {
return new NTCredentials(proxyConfiguration.username(),
proxyConfiguration.password(),
proxyConfiguration.ntlmWorkstation(),
proxyConfiguration.ntlmDomain());
}
/**
* Returns a new instance of AuthScope used for proxy authentication.
*/
private static AuthScope newAuthScope(ProxyConfiguration proxyConfiguration) {
return new AuthScope(proxyConfiguration.host(), proxyConfiguration.port());
}
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
ProxyConfiguration proxyConfiguration) {
if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
HttpHost targetHost = new HttpHost(proxyConfiguration.host(), proxyConfiguration.port());
CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
clientContext.setCredentialsProvider(credsProvider);
clientContext.setAuthCache(authCache);
}
}
// Just log and then swallow the exception
private static void noSuchMethodThrownByNormalizeUriInvoker() {
// setNormalizeUri method was added in httpclient 4.5.8
logger.warn(() -> "NoSuchMethodException was thrown when disabling normalizeUri. This indicates you are using "
+ "an old version (< 4.5.8) of Apache http client. It is recommended to use http client "
+ "version >= 4.5.9 to avoid the breaking change introduced in apache client 4.5.7 and "
+ "the latency in exception handling. See https://github.com/aws/aws-sdk-java/issues/1919"
+ " for more information");
}
}
| 1,265 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/SdkConnectionKeepAliveStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* The AWS SDK for Java's implementation of the
* {@code ConnectionKeepAliveStrategy} interface. Allows a user-configurable
* maximum idle time for connections.
*/
@SdkInternalApi
public class SdkConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
private final long maxIdleTime;
/**
* @param maxIdleTime the maximum time a connection may be idle
*/
public SdkConnectionKeepAliveStrategy(long maxIdleTime) {
this.maxIdleTime = maxIdleTime;
}
@Override
public long getKeepAliveDuration(
HttpResponse response,
HttpContext context) {
// If there's a Keep-Alive timeout directive in the response and it's
// shorter than our configured max, honor that. Otherwise go with the
// configured maximum.
long duration = DefaultConnectionKeepAliveStrategy.INSTANCE
.getKeepAliveDuration(response, context);
if (0 < duration && duration < maxIdleTime) {
return duration;
}
return maxIdleTime;
}
}
| 1,266 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/SdkTlsSocketFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.apache.internal.net.SdkSocket;
import software.amazon.awssdk.http.apache.internal.net.SdkSslSocket;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public class SdkTlsSocketFactory extends SSLConnectionSocketFactory {
private static final Logger log = Logger.loggerFor(SdkTlsSocketFactory.class);
private final SSLContext sslContext;
public SdkTlsSocketFactory(final SSLContext sslContext, final HostnameVerifier hostnameVerifier) {
super(sslContext, hostnameVerifier);
if (sslContext == null) {
throw new IllegalArgumentException(
"sslContext must not be null. " + "Use SSLContext.getDefault() if you are unsure.");
}
this.sslContext = sslContext;
}
@Override
protected final void prepareSocket(final SSLSocket socket) {
log.debug(() -> String.format("socket.getSupportedProtocols(): %s, socket.getEnabledProtocols(): %s",
Arrays.toString(socket.getSupportedProtocols()),
Arrays.toString(socket.getEnabledProtocols())));
}
@Override
public Socket connectSocket(
final int connectTimeout,
final Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpContext context) throws IOException {
log.trace(() -> String.format("Connecting to %s:%s", remoteAddress.getAddress(), remoteAddress.getPort()));
Socket connectedSocket = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
if (connectedSocket instanceof SSLSocket) {
return new SdkSslSocket((SSLSocket) connectedSocket);
}
return new SdkSocket(connectedSocket);
}
}
| 1,267 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/IdleConnectionReaper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.http.conn.HttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
/**
* Manages the reaping of idle connections.
*/
@SdkInternalApi
public final class IdleConnectionReaper {
private static final Logger log = LoggerFactory.getLogger(IdleConnectionReaper.class);
private static final IdleConnectionReaper INSTANCE = new IdleConnectionReaper();
private final Map<HttpClientConnectionManager, Long> connectionManagers;
private final Supplier<ExecutorService> executorServiceSupplier;
private final long sleepPeriod;
private volatile ExecutorService exec;
private volatile ReaperTask reaperTask;
private IdleConnectionReaper() {
this.connectionManagers = Collections.synchronizedMap(new WeakHashMap<>());
this.executorServiceSupplier = () -> {
ExecutorService e = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "idle-connection-reaper");
t.setDaemon(true);
return t;
});
return e;
};
this.sleepPeriod = Duration.ofMinutes(1).toMillis();
}
@SdkTestInternalApi
IdleConnectionReaper(Map<HttpClientConnectionManager, Long> connectionManagers,
Supplier<ExecutorService> executorServiceSupplier,
long sleepPeriod) {
this.connectionManagers = connectionManagers;
this.executorServiceSupplier = executorServiceSupplier;
this.sleepPeriod = sleepPeriod;
}
/**
* Register the connection manager with this reaper.
*
* @param manager The connection manager.
* @param maxIdleTime The maximum time connections in the connection manager are to remain idle before being reaped.
* @return {@code true} If the connection manager was not previously registered with this reaper, {@code false}
* otherwise.
*/
public synchronized boolean registerConnectionManager(HttpClientConnectionManager manager, long maxIdleTime) {
boolean notPreviouslyRegistered = connectionManagers.put(manager, maxIdleTime) == null;
setupExecutorIfNecessary();
return notPreviouslyRegistered;
}
/**
* Deregister this connection manager with this reaper.
*
* @param manager The connection manager.
* @return {@code true} If this connection manager was previously registered with this reaper and it was removed, {@code
* false} otherwise.
*/
public synchronized boolean deregisterConnectionManager(HttpClientConnectionManager manager) {
boolean wasRemoved = connectionManagers.remove(manager) != null;
cleanupExecutorIfNecessary();
return wasRemoved;
}
/**
* @return The singleton instance of this class.
*/
public static IdleConnectionReaper getInstance() {
return INSTANCE;
}
private void setupExecutorIfNecessary() {
if (exec != null) {
return;
}
ExecutorService e = executorServiceSupplier.get();
this.reaperTask = new ReaperTask(connectionManagers, sleepPeriod);
e.execute(this.reaperTask);
exec = e;
}
private void cleanupExecutorIfNecessary() {
if (exec == null || !connectionManagers.isEmpty()) {
return;
}
reaperTask.stop();
reaperTask = null;
exec.shutdownNow();
exec = null;
}
private static final class ReaperTask implements Runnable {
private final Map<HttpClientConnectionManager, Long> connectionManagers;
private final long sleepPeriod;
private volatile boolean stopping = false;
private ReaperTask(Map<HttpClientConnectionManager, Long> connectionManagers,
long sleepPeriod) {
this.connectionManagers = connectionManagers;
this.sleepPeriod = sleepPeriod;
}
@Override
public void run() {
while (!stopping) {
try {
Thread.sleep(sleepPeriod);
for (Map.Entry<HttpClientConnectionManager, Long> entry : connectionManagers.entrySet()) {
try {
entry.getKey().closeIdleConnections(entry.getValue(), TimeUnit.MILLISECONDS);
} catch (Exception t) {
log.warn("Unable to close idle connections", t);
}
}
} catch (Throwable t) {
log.debug("Reaper thread: ", t);
}
}
log.debug("Shutting down reaper thread.");
}
private void stop() {
stopping = true;
}
}
}
| 1,268 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/ClientConnectionRequestFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpClientConnection;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
public final class ClientConnectionRequestFactory {
/**
* {@link ThreadLocal}, request-level {@link MetricCollector}, set and removed by {@link ApacheHttpClient}.
*/
public static final ThreadLocal<MetricCollector> THREAD_LOCAL_REQUEST_METRIC_COLLECTOR = new ThreadLocal<>();
private ClientConnectionRequestFactory() {
}
/**
* Returns a wrapped instance of {@link ConnectionRequest}
* to capture the necessary performance metrics.
*
* @param orig the target instance to be wrapped
*/
static ConnectionRequest wrap(ConnectionRequest orig) {
if (orig instanceof DelegatingConnectionRequest) {
throw new IllegalArgumentException();
}
return new InstrumentedConnectionRequest(orig);
}
/**
* Measures the latency of {@link ConnectionRequest#get(long, java.util.concurrent.TimeUnit)}.
*/
private static class InstrumentedConnectionRequest extends DelegatingConnectionRequest {
private InstrumentedConnectionRequest(ConnectionRequest delegate) {
super(delegate);
}
@Override
public HttpClientConnection get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException,
ConnectionPoolTimeoutException {
Instant startTime = Instant.now();
try {
return super.get(timeout, timeUnit);
} finally {
Duration elapsed = Duration.between(startTime, Instant.now());
MetricCollector metricCollector = THREAD_LOCAL_REQUEST_METRIC_COLLECTOR.get();
metricCollector.reportMetric(HttpMetric.CONCURRENCY_ACQUIRE_DURATION, elapsed);
}
}
}
/**
* Delegates all methods to {@link ConnectionRequest}. Subclasses can override select methods to change behavior.
*/
private static class DelegatingConnectionRequest implements ConnectionRequest {
private final ConnectionRequest delegate;
private DelegatingConnectionRequest(ConnectionRequest delegate) {
this.delegate = delegate;
}
@Override
public HttpClientConnection get(long timeout, TimeUnit timeUnit)
throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
return delegate.get(timeout, timeUnit);
}
@Override
public boolean cancel() {
return delegate.cancel();
}
}
}
| 1,269 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/Wrapped.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An internal marker interface to defend against accidental recursive wrappings.
*/
@SdkInternalApi
public interface Wrapped {
}
| 1,270 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/ClientConnectionManagerFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpClientConnection;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class ClientConnectionManagerFactory {
private ClientConnectionManagerFactory() {
}
/**
* Returns a wrapped instance of {@link HttpClientConnectionManager}
* to capture the necessary performance metrics.
*
* @param orig the target instance to be wrapped
*/
public static HttpClientConnectionManager wrap(HttpClientConnectionManager orig) {
if (orig instanceof DelegatingHttpClientConnectionManager) {
throw new IllegalArgumentException();
}
return new InstrumentedHttpClientConnectionManager(orig);
}
/**
* Further wraps {@link ConnectionRequest} to capture performance metrics.
*/
private static class InstrumentedHttpClientConnectionManager extends DelegatingHttpClientConnectionManager {
private InstrumentedHttpClientConnectionManager(HttpClientConnectionManager delegate) {
super(delegate);
}
@Override
public ConnectionRequest requestConnection(HttpRoute route, Object state) {
ConnectionRequest connectionRequest = super.requestConnection(route, state);
return ClientConnectionRequestFactory.wrap(connectionRequest);
}
}
/**
* Delegates all methods to {@link HttpClientConnectionManager}. Subclasses can override select methods to change behavior.
*/
private static class DelegatingHttpClientConnectionManager implements HttpClientConnectionManager {
private final HttpClientConnectionManager delegate;
protected DelegatingHttpClientConnectionManager(HttpClientConnectionManager delegate) {
this.delegate = delegate;
}
@Override
public ConnectionRequest requestConnection(HttpRoute route, Object state) {
return delegate.requestConnection(route, state);
}
@Override
public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {
delegate.releaseConnection(conn, newState, validDuration, timeUnit);
}
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context)
throws IOException {
delegate.connect(conn, route, connectTimeout, context);
}
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
delegate.upgrade(conn, route, context);
}
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
delegate.routeComplete(conn, route, context);
}
@Override
public void closeIdleConnections(long idletime, TimeUnit timeUnit) {
delegate.closeIdleConnections(idletime, timeUnit);
}
@Override
public void closeExpiredConnections() {
delegate.closeExpiredConnections();
}
@Override
public void shutdown() {
delegate.shutdown();
}
}
}
| 1,271 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/ConnectionHealthConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class ConnectionHealthConfigurationTest {
@Test
void builder_allPropertiesSet() {
ConnectionHealthConfiguration connectionHealthConfiguration =
ConnectionHealthConfiguration.builder()
.minimumThroughputInBps(123l)
.minimumThroughputTimeout(Duration.ofSeconds(1))
.build();
assertThat(connectionHealthConfiguration.minimumThroughputInBps()).isEqualTo(123);
assertThat(connectionHealthConfiguration.minimumThroughputTimeout()).isEqualTo(Duration.ofSeconds(1));
}
@Test
void builder_nullMinimumThroughputInBps_shouldThrowException() {
assertThatThrownBy(() ->
ConnectionHealthConfiguration.builder()
.minimumThroughputTimeout(Duration.ofSeconds(1))
.build()).hasMessageContaining("minimumThroughputInBps");
}
@Test
void builder_nullMinimumThroughputTimeout() {
assertThatThrownBy(() ->
ConnectionHealthConfiguration.builder()
.minimumThroughputInBps(1L)
.build()).hasMessageContaining("minimumThroughputTimeout");
}
@Test
void builder_negativeMinimumThroughputTimeout() {
assertThatThrownBy(() ->
ConnectionHealthConfiguration.builder()
.minimumThroughputInBps(1L)
.minimumThroughputTimeout(Duration.ofSeconds(-1))
.build()).hasMessageContaining("minimumThroughputTimeout");
}
}
| 1,272 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/EmptyPublisher.java | package software.amazon.awssdk.http.crt;
import java.nio.ByteBuffer;
import java.util.Optional;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
public class EmptyPublisher implements SdkHttpContentPublisher {
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
subscriber.onSubscribe(new EmptySubscription(subscriber));
}
@Override
public Optional<Long> contentLength() {
return Optional.of(0L);
}
private static class EmptySubscription implements Subscription {
private final Subscriber subscriber;
private volatile boolean done;
EmptySubscription(Subscriber subscriber) {
this.subscriber = subscriber;
}
@Override
public void request(long l) {
if (!done) {
done = true;
if (l <= 0) {
this.subscriber.onError(new IllegalArgumentException("Demand must be positive"));
} else {
this.subscriber.onComplete();
}
}
}
@Override
public void cancel() {
done = true;
}
}
}
| 1,273 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/ProxyWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.io.EventLoopGroup;
import software.amazon.awssdk.crt.io.HostResolver;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
/**
* Tests for HTTP proxy functionality in the CRT client.
*/
public class ProxyWireMockTest {
private SdkAsyncHttpClient client;
private ProxyConfiguration proxyCfg;
private WireMockServer mockProxy = new WireMockServer(new WireMockConfiguration()
.dynamicPort()
.dynamicHttpsPort()
.enableBrowserProxying(true)); // make the mock proxy actually forward (to the mock server for our test)
private WireMockServer mockServer = new WireMockServer(new WireMockConfiguration()
.dynamicPort()
.dynamicHttpsPort());
@BeforeEach
public void setup() {
mockProxy.start();
mockServer.start();
mockServer.stubFor(get(urlMatching(".*")).willReturn(aResponse().withStatus(200).withBody("hello")));
proxyCfg = ProxyConfiguration.builder()
.host("localhost")
.port(mockProxy.port())
.build();
client = AwsCrtAsyncHttpClient.builder()
.proxyConfiguration(proxyCfg)
.build();
}
@AfterEach
public void teardown() {
mockServer.stop();
mockProxy.stop();
client.close();
EventLoopGroup.closeStaticDefault();
HostResolver.closeStaticDefault();
CrtResource.waitForNoResources();
}
/*
* Note the contrast between this test and the netty connect test. The CRT proxy implementation does not
* do a CONNECT call for requests using http, so by configuring the proxy mock to forward and the server mock
* to return success, we can actually create an end-to-end test.
*
* We have an outstanding request to change this behavior to match https (use a CONNECT call). Once that
* change happens, this test will break and need to be updated to be more like the netty one.
*/
@Test
public void proxyConfigured_httpGet() throws Throwable {
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
AtomicReference<Throwable> error = new AtomicReference<>(null);
Subscriber<ByteBuffer> subscriber = CrtHttpClientTestUtils.createDummySubscriber();
SdkAsyncHttpResponseHandler handler = CrtHttpClientTestUtils.createTestResponseHandler(response, streamReceived, error, subscriber);
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(uri, "/server/test", null, SdkHttpMethod.GET, emptyMap());
CompletableFuture future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(error.get()).isNull();
assertThat(streamReceived.get(60, TimeUnit.SECONDS)).isTrue();
assertThat(response.get().statusCode()).isEqualTo(200);
}
}
| 1,274 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/CrtHttpClientTestUtils.java | package software.amazon.awssdk.http.crt;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Collections.emptyMap;
public class CrtHttpClientTestUtils {
static Subscriber<ByteBuffer> createDummySubscriber() {
return new Subscriber<ByteBuffer>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
};
}
static SdkAsyncHttpResponseHandler createTestResponseHandler(AtomicReference<SdkHttpResponse> response,
CompletableFuture<Boolean> streamReceived,
AtomicReference<Throwable> error,
Subscriber<ByteBuffer> subscriber) {
return new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
response.compareAndSet(null, headers);
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(subscriber);
streamReceived.complete(true);
}
@Override
public void onError(Throwable t) {
error.compareAndSet(null, t);
}
};
}
public static SdkHttpFullRequest createRequest(URI endpoint) {
return createRequest(endpoint, "/", null, SdkHttpMethod.GET, emptyMap());
}
static SdkHttpFullRequest createRequest(URI endpoint,
String resourcePath,
byte[] body,
SdkHttpMethod method,
Map<String, String> params) {
String contentLength = (body == null) ? null : String.valueOf(body.length);
return SdkHttpFullRequest.builder()
.uri(endpoint)
.method(method)
.encodedPath(resourcePath)
.applyMutation(b -> params.forEach(b::putRawQueryParameter))
.applyMutation(b -> {
b.putHeader("Host", endpoint.getHost());
if (contentLength != null) {
b.putHeader("Content-Length", contentLength);
}
}).build();
}
}
| 1,275 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/AwsCrtHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.HttpTestUtils.createProvider;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.PROTOCOL;
import static software.amazon.awssdk.http.crt.CrtHttpClientTestUtils.createRequest;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.Log;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.RecordingResponseHandler;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.utils.AttributeMap;
public class AwsCrtHttpClientWireMockTest {
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort());
@BeforeClass
public static void setup() {
System.setProperty("aws.crt.debugnative", "true");
Log.initLoggingToStdout(Log.LogLevel.Warn);
}
@AfterClass
public static void tearDown() {
// Verify there is no resource leak.
CrtResource.waitForNoResources();
}
@Test
public void closeClient_reuse_throwException() throws Exception {
SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.create();
client.close();
assertThatThrownBy(() -> makeSimpleRequest(client)).hasMessageContaining("is closed");
}
@Test
public void invalidProtocol_shouldThrowException() {
AttributeMap attributeMap = AttributeMap.builder()
.put(PROTOCOL, Protocol.HTTP2)
.build();
assertThatThrownBy(() -> AwsCrtAsyncHttpClient.builder().buildWithDefaults(attributeMap))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void sendRequest_withCollector_shouldCollectMetrics() throws Exception {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder().maxConcurrency(10).build()) {
RecordingResponseHandler recorder = makeSimpleRequest(client);
MetricCollection metrics = recorder.collector().collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("AwsCommonRuntime");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).containsExactly(0);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).containsExactly(1);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
}
}
@Test
public void sharedEventLoopGroup_closeOneClient_shouldNotAffectOtherClients() throws Exception {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.create()) {
makeSimpleRequest(client);
}
try (SdkAsyncHttpClient anotherClient = AwsCrtAsyncHttpClient.create()) {
makeSimpleRequest(anotherClient);
}
}
/**
* Make a simple async request and wait for it to finish.
*
* @param client Client to make request with.
*/
private RecordingResponseHandler makeSimpleRequest(SdkAsyncHttpClient client) throws Exception {
String body = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(createProvider(""))
.responseHandler(recorder)
.metricCollector(recorder.collector())
.build());
recorder.completeFuture().get(5, TimeUnit.SECONDS);
return recorder;
}
}
| 1,276 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/SdkTestHttpContentPublisher.java | package software.amazon.awssdk.http.crt;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
public class SdkTestHttpContentPublisher implements SdkHttpContentPublisher {
private final byte[] body;
private final AtomicReference<Subscriber<? super ByteBuffer>> subscriber = new AtomicReference<>(null);
private final AtomicBoolean complete = new AtomicBoolean(false);
public SdkTestHttpContentPublisher(byte[] body) {
this.body = body;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
boolean wasFirstSubscriber = subscriber.compareAndSet(null, s);
SdkTestHttpContentPublisher publisher = this;
if (wasFirstSubscriber) {
s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
publisher.request(n);
}
@Override
public void cancel() {
// Do nothing
}
});
} else {
s.onError(new RuntimeException("Only allow one subscriber"));
}
}
protected void request(long n) {
// Send the whole body if they request >0 ByteBuffers
if (n > 0 && !complete.get()) {
complete.set(true);
subscriber.get().onNext(ByteBuffer.wrap(body));
subscriber.get().onComplete();
}
}
@Override
public Optional<Long> contentLength() {
return Optional.of((long)body.length);
}
}
| 1,277 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/H1ServerBehaviorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.Log;
import software.amazon.awssdk.http.SdkAsyncHttpClientH1TestSuite;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Testing the scenario where h1 server sends 5xx errors.
*/
public class H1ServerBehaviorTest extends SdkAsyncHttpClientH1TestSuite {
@BeforeAll
public static void beforeAll() {
System.setProperty("aws.crt.debugnative", "true");
Log.initLoggingToStdout(Log.LogLevel.Warn);
}
@AfterAll
public static void afterAll() {
CrtResource.waitForNoResources();
}
@Override
protected SdkAsyncHttpClient setupClient() {
return AwsCrtAsyncHttpClient.builder()
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
}
}
| 1,278 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/CrtHttpProxyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URISyntaxException;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class CrtHttpProxyTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings,
TestProxySetting expectedProxySettings,
Boolean useSystemProperty, Boolean useEnvironmentVariable,
String protocol) throws URISyntaxException {
ProxyConfiguration.Builder proxyBuilder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
if (hostName != null) {
proxyBuilder.host(hostName);
}
if (portNumber != null) {
proxyBuilder.port(portNumber);
}
if (userName != null) {
proxyBuilder.username(userName);
}
if (password != null) {
proxyBuilder.password(password);
}
}
if (!"http".equals(protocol)) {
proxyBuilder.scheme(protocol);
}
if (useSystemProperty != null) {
proxyBuilder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
proxyBuilder.useEnvironmentVariableValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = proxyBuilder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
}
}
| 1,279 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link ProxyConfiguration}.
*/
public class ProxyConfigurationTest {
private static final Random RNG = new Random();
private static final String TEST_HOST = "foo.com";
private static final int TEST_PORT = 7777;
private static final String TEST_USER = "testuser";
private static final String TEST_PASSWORD = "123";
@BeforeEach
public void setup() {
clearProxyProperties();
}
@AfterAll
public static void cleanup() {
clearProxyProperties();
}
@Test
void build_setsAllProperties() {
verifyAllPropertiesSet(allPropertiesSetConfig());
}
@Test
void build_systemPropertyDefault_Http() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder().build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isNull();
}
@Test
void build_systemPropertyDefault_Https() {
setHttpsProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.scheme("https")
.build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void build_systemPropertyEnabled_Http() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder().useSystemPropertyValues(Boolean.TRUE).build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isNull();
}
@Test
void build_systemPropertyEnabled_Https() {
setHttpsProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.scheme("https")
.useSystemPropertyValues(Boolean.TRUE).build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void build_systemPropertyDisabled() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.host("localhost")
.port(8888)
.username("username")
.password("password")
.useSystemPropertyValues(Boolean.FALSE).build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(8888);
assertThat(config.username()).isEqualTo("username");
assertThat(config.password()).isEqualTo("password");
assertThat(config.scheme()).isNull();
}
@Test
void build_systemPropertyOverride() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.host("localhost")
.port(8888)
.username("username")
.password("password")
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(8888);
assertThat(config.username()).isEqualTo("username");
assertThat(config.password()).isEqualTo("password");
assertThat(config.scheme()).isNull();
}
@Test
void toBuilder_roundTrip_producesExactCopy() {
ProxyConfiguration original = allPropertiesSetConfig();
ProxyConfiguration copy = original.toBuilder().build();
assertThat(copy).isEqualTo(original);
}
@Test
void toBuilderModified_doesNotModifySource() {
ProxyConfiguration original = allPropertiesSetConfig();
ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build();
assertThat(original).isNotEqualTo(modified);
}
private ProxyConfiguration allPropertiesSetConfig() {
return setAllPropertiesToRandomValues(ProxyConfiguration.builder()).build();
}
private ProxyConfiguration.Builder setAllPropertiesToRandomValues(ProxyConfiguration.Builder builder) {
Stream.of(builder.getClass().getDeclaredMethods())
.filter(m -> m.getParameterCount() == 1 && m.getReturnType().equals(ProxyConfiguration.Builder.class))
.forEach(m -> {
try {
m.setAccessible(true);
setRandomValue(builder, m);
} catch (Exception e) {
throw new RuntimeException("Could not create random proxy config", e);
}
});
return builder;
}
private void setRandomValue(Object o, Method setter) throws InvocationTargetException, IllegalAccessException {
Class<?> paramClass = setter.getParameterTypes()[0];
if (String.class.equals(paramClass)) {
setter.invoke(o, randomString());
} else if (int.class.equals(paramClass)) {
setter.invoke(o, RNG.nextInt());
} else if (Boolean.class.equals(paramClass)) {
setter.invoke(o, RNG.nextBoolean());
} else {
throw new RuntimeException("Don't know how create random value for type " + paramClass);
}
}
private void verifyAllPropertiesSet(ProxyConfiguration cfg) {
boolean hasNullProperty = Stream.of(cfg.getClass().getDeclaredMethods())
.filter(m -> !m.getReturnType().equals(Void.class) && m.getParameterCount() == 0)
.anyMatch(m -> {
m.setAccessible(true);
try {
return m.invoke(cfg) == null;
} catch (Exception e) {
return true;
}
});
if (hasNullProperty) {
throw new RuntimeException("Given configuration has unset property");
}
}
private String randomString() {
String alpha = "abcdefghijklmnopqrstuwxyz";
StringBuilder sb = new StringBuilder(16);
for (int i = 0; i < 16; ++i) {
sb.append(alpha.charAt(RNG.nextInt(16)));
}
return sb.toString();
}
private void setHttpProxyProperties() {
System.setProperty("http.proxyHost", TEST_HOST);
System.setProperty("http.proxyPort", Integer.toString(TEST_PORT));
System.setProperty("http.proxyUser", TEST_USER);
System.setProperty("http.proxyPassword", TEST_PASSWORD);
}
private void setHttpsProxyProperties() {
System.setProperty("https.proxyHost", TEST_HOST);
System.setProperty("https.proxyPort", Integer.toString(TEST_PORT));
System.setProperty("https.proxyUser", TEST_USER);
System.setProperty("https.proxyPassword", TEST_PASSWORD);
}
private static void clearProxyProperties() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
System.clearProperty("https.proxyHost");
System.clearProperty("https.proxyPort");
System.clearProperty("https.proxyUser");
System.clearProperty("https.proxyPassword");
}
}
| 1,280 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/TcpKeepAliveConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
public class TcpKeepAliveConfigurationTest {
@Test
public void builder_allPropertiesSet() {
TcpKeepAliveConfiguration tcpKeepAliveConfiguration =
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(1))
.keepAliveTimeout(Duration.ofSeconds(1))
.build();
assertThat(tcpKeepAliveConfiguration.keepAliveInterval()).isEqualTo(Duration.ofMinutes(1));
assertThat(tcpKeepAliveConfiguration.keepAliveTimeout()).isEqualTo(Duration.ofSeconds(1));
}
@Test
public void builder_nullKeepAliveTimeout_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(1))
.build())
.hasMessageContaining("keepAliveTimeout");
}
@Test
public void builder_nullKeepAliveInterval_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveTimeout(Duration.ofSeconds(1))
.build())
.hasMessageContaining("keepAliveInterval");
}
@Test
public void builder_nonPositiveKeepAliveTimeout_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(1))
.keepAliveTimeout(Duration.ofSeconds(0))
.build())
.hasMessageContaining("keepAliveTimeout");
}
@Test
public void builder_nonPositiveKeepAliveInterval_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(0))
.keepAliveTimeout(Duration.ofSeconds(1))
.build())
.hasMessageContaining("keepAliveInterval");
}
}
| 1,281 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/AwsCrtHttpClientSpiVerificationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.binaryEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.util.Collections.emptyMap;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.HttpTestUtils.createProvider;
import static software.amazon.awssdk.http.crt.CrtHttpClientTestUtils.createRequest;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.http.RecordingResponseHandler;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.utils.Logger;
public class AwsCrtHttpClientSpiVerificationTest {
private static final Logger log = Logger.loggerFor(AwsCrtHttpClientSpiVerificationTest.class);
private static final int TEST_BODY_LEN = 1024;
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort()
.dynamicHttpsPort());
private static SdkAsyncHttpClient client;
@BeforeClass
public static void setup() throws Exception {
client = AwsCrtAsyncHttpClient.builder()
.connectionHealthConfiguration(b -> b.minimumThroughputInBps(4068L)
.minimumThroughputTimeout(Duration.ofSeconds(3)))
.build();
}
@AfterClass
public static void tearDown() {
client.close();
CrtResource.waitForNoResources();
}
private byte[] generateRandomBody(int size) {
byte[] randomData = new byte[size];
new Random().nextBytes(randomData);
return randomData;
}
@Test
public void signalsErrorViaOnErrorAndFuture() throws Exception {
stubFor(any(urlEqualTo("/")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
CompletableFuture<Boolean> errorSignaled = new CompletableFuture<>();
SdkAsyncHttpResponseHandler handler = new TestResponseHandler() {
@Override
public void onError(Throwable error) {
errorSignaled.complete(true);
}
};
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(URI.create("http://localhost:" + mockServer.port()));
CompletableFuture<Void> executeFuture = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
assertThat(errorSignaled.get(1, TimeUnit.SECONDS)).isTrue();
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCauseInstanceOf(HttpException.class);
}
@Test
public void requestFailed_connectionTimeout_shouldWrapException() {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder().connectionTimeout(Duration.ofNanos(1)).build()) {
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build());
assertThatThrownBy(() -> recorder.completeFuture().get(5, TimeUnit.SECONDS)).hasCauseInstanceOf(IOException.class)
.hasRootCauseInstanceOf(HttpException.class);
}
}
@Test
public void requestFailed_notRetryable_shouldNotWrapException() {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder().build()) {
URI uri = URI.create("http://localhost:" + mockServer.port());
// make it invalid by doing a non-zero content length with no request body...
Map<String, List<String>> headers = new HashMap<>();
headers.put("host", Collections.singletonList(uri.getHost()));
List<String> contentLengthValues = new LinkedList<>();
contentLengthValues.add("1");
headers.put("content-length", contentLengthValues);
SdkHttpRequest request = createRequest(uri).toBuilder().headers(headers).build();
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(new EmptyPublisher()).responseHandler(recorder).build());
// invalid request should have returned an HttpException and not an IOException.
assertThatThrownBy(() -> recorder.completeFuture().get(5, TimeUnit.SECONDS))
.hasCauseInstanceOf(HttpException.class).hasMessageContaining("does not match the previously declared length");
}
}
@Test
public void callsOnStreamForEmptyResponseContent() throws Exception {
stubFor(any(urlEqualTo("/")).willReturn(aResponse().withStatus(204).withHeader("foo", "bar")));
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
SdkAsyncHttpResponseHandler handler = new TestResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
response.compareAndSet(null, headers);
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
super.onStream(stream);
streamReceived.complete(true);
}
};
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(URI.create("http://localhost:" + mockServer.port()));
CompletableFuture<Void> future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(streamReceived.get(1, TimeUnit.SECONDS)).isTrue();
assertThat(response.get() != null).isTrue();
assertThat(response.get().statusCode() == 204).isTrue();
assertThat(response.get().headers().get("foo").isEmpty()).isFalse();
}
@Test
public void testGetRequest() throws Exception {
String path = "/testGetRequest";
byte[] body = generateRandomBody(TEST_BODY_LEN);
String expectedBodyHash = sha256Hex(body).toUpperCase();
stubFor(any(urlEqualTo(path)).willReturn(aResponse().withStatus(200)
.withHeader("Content-Length", Integer.toString(TEST_BODY_LEN))
.withHeader("foo", "bar")
.withBody(body)));
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
Sha256BodySubscriber bodySha256Subscriber = new Sha256BodySubscriber();
AtomicReference<Throwable> error = new AtomicReference<>(null);
SdkAsyncHttpResponseHandler handler = new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
response.compareAndSet(null, headers);
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(bodySha256Subscriber);
streamReceived.complete(true);
}
@Override
public void onError(Throwable t) {
error.compareAndSet(null, t);
}
};
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(uri, path, null, SdkHttpMethod.GET, emptyMap());
CompletableFuture future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(error.get()).isNull();
assertThat(streamReceived.get(1, TimeUnit.SECONDS)).isTrue();
assertThat(bodySha256Subscriber.getFuture().get(60, TimeUnit.SECONDS)).isEqualTo(expectedBodyHash);
assertThat(response.get().statusCode()).isEqualTo(200);
assertThat(response.get().headers().get("foo").isEmpty()).isFalse();
}
private void makePutRequest(String path, byte[] reqBody, int expectedStatus) throws Exception {
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
AtomicReference<Throwable> error = new AtomicReference<>(null);
Subscriber<ByteBuffer> subscriber = CrtHttpClientTestUtils.createDummySubscriber();
SdkAsyncHttpResponseHandler handler = CrtHttpClientTestUtils.createTestResponseHandler(response,
streamReceived, error, subscriber);
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(uri, path, reqBody, SdkHttpMethod.PUT, emptyMap());
CompletableFuture future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new SdkTestHttpContentPublisher(reqBody))
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(error.get()).isNull();
assertThat(streamReceived.get(60, TimeUnit.SECONDS)).isTrue();
assertThat(response.get().statusCode()).isEqualTo(expectedStatus);
}
@Test
public void testPutRequest() throws Exception {
String pathExpect200 = "/testPutRequest/return_200_on_exact_match";
byte[] expectedBody = generateRandomBody(TEST_BODY_LEN);
stubFor(any(urlEqualTo(pathExpect200)).withRequestBody(binaryEqualTo(expectedBody)).willReturn(aResponse().withStatus(200)));
makePutRequest(pathExpect200, expectedBody, 200);
String pathExpect404 = "/testPutRequest/return_404_always";
byte[] randomBody = generateRandomBody(TEST_BODY_LEN);
stubFor(any(urlEqualTo(pathExpect404)).willReturn(aResponse().withStatus(404)));
makePutRequest(pathExpect404, randomBody, 404);
}
private static class TestResponseHandler implements SdkAsyncHttpResponseHandler {
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(new DrainingSubscriber<>());
}
@Override
public void onError(Throwable error) {
}
}
private static class DrainingSubscriber<T> implements Subscriber<T> {
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(T t) {
this.subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}
}
| 1,282 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/Sha256BodySubscriber.java | package software.amazon.awssdk.http.crt;
import static org.apache.commons.codec.binary.Hex.encodeHexString;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public class Sha256BodySubscriber implements Subscriber<ByteBuffer> {
private MessageDigest digest;
private CompletableFuture<String> future;
public Sha256BodySubscriber() throws NoSuchAlgorithmException {
digest = MessageDigest.getInstance("SHA-256");
future = new CompletableFuture<>();
}
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
digest.update(byteBuffer);
}
@Override
public void onError(Throwable t) {
future.completeExceptionally(t);
}
@Override
public void onComplete() {
future.complete(encodeHexString(digest.digest()).toUpperCase());
}
public CompletableFuture<String> getFuture() {
return future;
}
}
| 1,283 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/internal/CrtRequestExecutorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.HttpTestUtils.createProvider;
import static software.amazon.awssdk.http.crt.CrtHttpClientTestUtils.createRequest;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.crt.CrtRuntimeException;
import software.amazon.awssdk.crt.http.HttpClientConnection;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.http.SdkCancellationException;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.crt.internal.response.CrtResponseAdapter;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@RunWith(MockitoJUnitRunner.class)
public class CrtRequestExecutorTest {
private CrtRequestExecutor requestExecutor;
@Mock
private HttpClientConnectionManager connectionManager;
@Mock
private SdkAsyncHttpResponseHandler responseHandler;
@Mock
private HttpClientConnection httpClientConnection;
@Before
public void setup() {
requestExecutor = new CrtRequestExecutor();
}
@After
public void teardown() {
Mockito.reset(connectionManager, responseHandler, httpClientConnection);
}
@Test
public void acquireConnectionThrowException_shouldInvokeOnError() {
RuntimeException exception = new RuntimeException("error");
CrtRequestContext context = CrtRequestContext.builder()
.crtConnPool(connectionManager)
.request(AsyncExecuteRequest.builder()
.responseHandler(responseHandler)
.build())
.build();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.completeExceptionally(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("An exception occurred when acquiring a connection");
assertThat(actualException).hasCause(exception);
assertThat(executeFuture).hasFailedWithThrowableThat().hasCause(exception).isInstanceOf(IOException.class);
}
@Test
public void makeRequestThrowException_shouldInvokeOnError() {
CrtRuntimeException exception = new CrtRuntimeException("");
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("An exception occurred when making the request");
assertThat(actualException).hasCause(exception);
assertThat(executeFuture).hasFailedWithThrowableThat().hasCause(exception).isInstanceOf(IOException.class);
}
@Test
public void makeRequest_success() {
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
Mockito.verifyNoMoreInteractions(responseHandler);
}
@Test
public void cancelRequest_shouldInvokeOnError() {
CrtRequestContext context = CrtRequestContext.builder()
.crtConnPool(connectionManager)
.request(AsyncExecuteRequest.builder()
.responseHandler(responseHandler)
.build())
.build();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
executeFuture.cancel(true);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("The request was cancelled");
assertThat(actualException).isInstanceOf(SdkCancellationException.class);
}
@Test
public void execute_AcquireConnectionFailure_shouldAlwaysWrapIOException() {
CrtRequestContext context = crtRequestContext();
RuntimeException exception = new RuntimeException("some failure");
CompletableFuture<HttpClientConnection> completableFuture = CompletableFutureUtils.failedFuture(exception);
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCause(exception);
}
@Test
public void executeRequest_failedOfIllegalStateException_shouldWrapIOException() {
IllegalStateException exception = new IllegalStateException("connection closed");
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("An exception occurred when making the request").hasCause(exception);
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCause(exception);
}
@Test
public void executeRequest_failedOfRetryableHttpException_shouldWrapIOException() {
HttpException exception = new HttpException(0x080a); // AWS_ERROR_HTTP_CONNECTION_CLOSED
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasCause(exception);
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCause(exception);
}
@Test
public void executeRequest_failedOfNonRetryableHttpException_shouldNotWrapIOException() {
HttpException exception = new HttpException(0x0801); // AWS_ERROR_HTTP_HEADER_NOT_FOUND
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).isEqualTo(exception);
assertThatThrownBy(executeFuture::join).hasCause(exception);
}
private CrtRequestContext crtRequestContext() {
SdkHttpFullRequest request = createRequest(URI.create("http://localhost"));
return CrtRequestContext.builder()
.readBufferSize(2000)
.crtConnPool(connectionManager)
.request(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(createProvider(""))
.responseHandler(responseHandler)
.build())
.build();
}
}
| 1,284 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/internal/AwsCrtConfigurationUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.crt.io.TlsCipherPreference.TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05;
import static software.amazon.awssdk.crt.io.TlsCipherPreference.TLS_CIPHER_SYSTEM_DEFAULT;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.crt.io.TlsCipherPreference;
class AwsCrtConfigurationUtilsTest {
@ParameterizedTest
@MethodSource("cipherPreferences")
void resolveCipherPreference_pqNotSupported_shouldFallbackToSystemDefault(Boolean preferPqTls,
TlsCipherPreference tlsCipherPreference) {
Assumptions.assumeFalse(TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05.isSupported());
assertThat(AwsCrtConfigurationUtils.resolveCipherPreference(preferPqTls)).isEqualTo(tlsCipherPreference);
}
@Test
void resolveCipherPreference_pqSupported_shouldHonor() {
Assumptions.assumeTrue(TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05.isSupported());
assertThat(AwsCrtConfigurationUtils.resolveCipherPreference(true)).isEqualTo(TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05);
}
private static Stream<Arguments> cipherPreferences() {
return Stream.of(
Arguments.of(null, TLS_CIPHER_SYSTEM_DEFAULT),
Arguments.of(false, TLS_CIPHER_SYSTEM_DEFAULT),
Arguments.of(true, TLS_CIPHER_SYSTEM_DEFAULT)
);
}
}
| 1,285 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/ConnectionHealthConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.crtcore.CrtConnectionHealthConfiguration;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration that defines health checks for all connections established by
* the {@link ConnectionHealthConfiguration}.
*
*/
@SdkPublicApi
public final class ConnectionHealthConfiguration extends CrtConnectionHealthConfiguration
implements ToCopyableBuilder<ConnectionHealthConfiguration.Builder, ConnectionHealthConfiguration> {
private ConnectionHealthConfiguration(DefaultBuilder builder) {
super(builder);
}
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
/**
* A builder for {@link ConnectionHealthConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder extends CrtConnectionHealthConfiguration.Builder,
CopyableBuilder<Builder, ConnectionHealthConfiguration> {
@Override
Builder minimumThroughputInBps(Long minimumThroughputInBps);
@Override
Builder minimumThroughputTimeout(Duration minimumThroughputTimeout);
@Override
ConnectionHealthConfiguration build();
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultBuilder extends
CrtConnectionHealthConfiguration.DefaultBuilder<DefaultBuilder> implements Builder {
private DefaultBuilder() {
}
private DefaultBuilder(ConnectionHealthConfiguration configuration) {
super(configuration);
}
@Override
public ConnectionHealthConfiguration build() {
return new ConnectionHealthConfiguration(this);
}
}
}
| 1,286 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/AwsCrtSdkHttpService.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpService;
/**
* Service binding for the AWS common runtime HTTP client implementation. Allows SDK to pick this up automatically from the
* classpath.
*
*/
@SdkPublicApi
public class AwsCrtSdkHttpService implements SdkAsyncHttpService {
@Override
public SdkAsyncHttpClient.Builder createAsyncHttpClientFactory() {
return AwsCrtAsyncHttpClient.builder();
}
}
| 1,287 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/ProxyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.crtcore.CrtProxyConfiguration;
import software.amazon.awssdk.utils.ProxySystemSetting;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Proxy configuration for {@link AwsCrtAsyncHttpClient}. This class is used to configure an HTTPS or HTTP proxy to be used by the
* {@link AwsCrtAsyncHttpClient}.
*
* @see AwsCrtAsyncHttpClient.Builder#proxyConfiguration(ProxyConfiguration)
*/
@SdkPublicApi
public final class ProxyConfiguration extends CrtProxyConfiguration
implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private ProxyConfiguration(DefaultBuilder builder) {
super(builder);
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Builder for {@link ProxyConfiguration}.
*/
public interface Builder extends CrtProxyConfiguration.Builder, CopyableBuilder<Builder, ProxyConfiguration> {
/**
* Set the hostname of the proxy.
*
* @param host The proxy host.
* @return This object for method chaining.
*/
@Override
Builder host(String host);
/**
* Set the port that the proxy expects connections on.
*
* @param port The proxy port.
* @return This object for method chaining.
*/
@Override
Builder port(int port);
/**
* The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}.
* <p>
* The client defaults to {@code http} if none is given.
*
* @param scheme The proxy scheme.
* @return This object for method chaining.
*/
@Override
Builder scheme(String scheme);
/**
* The username to use for basic proxy authentication
* <p>
* If not set, the client will not use basic authentication
*
* @param username The basic authentication username.
* @return This object for method chaining.
*/
@Override
Builder username(String username);
/**
* The password to use for basic proxy authentication
* <p>
* If not set, the client will not use basic authentication
*
* @param password The basic authentication password.
* @return This object for method chaining.
*/
@Override
Builder password(String password);
/**
* The option whether to use system property values from {@link ProxySystemSetting} if any of the config options are
* missing. The value is set to "true" by default which means SDK will automatically use system property values if
* options
* are not provided during building the {@link ProxyConfiguration} object. To disable this behaviour, set this
* value to
* false.
*
* @param useSystemPropertyValues The option whether to use system property values
* @return This object for method chaining.
*/
@Override
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
@Override
Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues);
@Override
ProxyConfiguration build();
}
private static final class DefaultBuilder extends CrtProxyConfiguration.DefaultBuilder<DefaultBuilder> implements Builder {
private DefaultBuilder(ProxyConfiguration proxyConfiguration) {
super(proxyConfiguration);
}
private DefaultBuilder() {
}
@Override
public ProxyConfiguration build() {
return new ProxyConfiguration(this);
}
}
} | 1,288 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/TcpKeepAliveConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
/**
* Configuration that defines keep-alive options for all connections established by
* the {@link TcpKeepAliveConfiguration}.
*/
@SdkPublicApi
public final class TcpKeepAliveConfiguration {
private final Duration keepAliveInterval;
private final Duration keepAliveTimeout;
private TcpKeepAliveConfiguration(DefaultTcpKeepAliveConfigurationBuilder builder) {
this.keepAliveInterval = Validate.isPositive(builder.keepAliveInterval,
"keepAliveInterval");
this.keepAliveTimeout = Validate.isPositive(builder.keepAliveTimeout,
"keepAliveTimeout");
}
/**
* @return number of seconds between TCP keepalive packets being sent to the peer
*/
public Duration keepAliveInterval() {
return keepAliveInterval;
}
/**
* @return number of seconds to wait for a keepalive response before considering the connection timed out
*/
public Duration keepAliveTimeout() {
return keepAliveTimeout;
}
public static Builder builder() {
return new DefaultTcpKeepAliveConfigurationBuilder();
}
/**
* A builder for {@link TcpKeepAliveConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder {
/**
* Sets the Duration between TCP keepalive packets being sent to the peer
* @param keepAliveInterval Duration between TCP keepalive packets being sent to the peer
* @return Builder
*/
Builder keepAliveInterval(Duration keepAliveInterval);
/**
* Sets the Duration to wait for a keepalive response before considering the connection timed out
* @param keepAliveTimeout Duration to wait for a keepalive response before considering the connection timed out
* @return Builder
*/
Builder keepAliveTimeout(Duration keepAliveTimeout);
TcpKeepAliveConfiguration build();
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultTcpKeepAliveConfigurationBuilder implements Builder {
private Duration keepAliveInterval;
private Duration keepAliveTimeout;
private DefaultTcpKeepAliveConfigurationBuilder() {
}
/**
* Sets the Duration between TCP keepalive packets being sent to the peer
* @param keepAliveInterval Duration between TCP keepalive packets being sent to the peer
* @return Builder
*/
@Override
public Builder keepAliveInterval(Duration keepAliveInterval) {
this.keepAliveInterval = keepAliveInterval;
return this;
}
/**
* Sets the Duration to wait for a keepalive response before considering the connection timed out
* @param keepAliveTimeout Duration to wait for a keepalive response before considering the connection timed out
* @return Builder
*/
@Override
public Builder keepAliveTimeout(Duration keepAliveTimeout) {
this.keepAliveTimeout = keepAliveTimeout;
return this;
}
@Override
public TcpKeepAliveConfiguration build() {
return new TcpKeepAliveConfiguration(this);
}
}
}
| 1,289 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/AwsCrtAsyncHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static software.amazon.awssdk.crtcore.CrtConfigurationUtils.resolveHttpMonitoringOptions;
import static software.amazon.awssdk.crtcore.CrtConfigurationUtils.resolveProxy;
import static software.amazon.awssdk.http.HttpMetric.HTTP_CLIENT_NAME;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.PROTOCOL;
import static software.amazon.awssdk.http.crt.internal.AwsCrtConfigurationUtils.buildSocketOptions;
import static software.amazon.awssdk.http.crt.internal.AwsCrtConfigurationUtils.resolveCipherPreference;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.net.URI;
import java.time.Duration;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.crt.http.HttpClientConnectionManagerOptions;
import software.amazon.awssdk.crt.http.HttpMonitoringOptions;
import software.amazon.awssdk.crt.http.HttpProxyOptions;
import software.amazon.awssdk.crt.io.ClientBootstrap;
import software.amazon.awssdk.crt.io.SocketOptions;
import software.amazon.awssdk.crt.io.TlsContext;
import software.amazon.awssdk.crt.io.TlsContextOptions;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.crt.internal.CrtRequestContext;
import software.amazon.awssdk.http.crt.internal.CrtRequestExecutor;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkAsyncHttpClient} that uses the AWS Common Runtime (CRT) Http Client to communicate with
* Http Web Services. This client is asynchronous and uses non-blocking IO.
*
* <p>This can be created via {@link #builder()}</p>
* {@snippet :
SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder()
.maxConcurrency(100)
.connectionTimeout(Duration.ofSeconds(1))
.connectionMaxIdleTime(Duration.ofSeconds(5))
.build();
* }
*
*/
@SdkPublicApi
public final class AwsCrtAsyncHttpClient implements SdkAsyncHttpClient {
private static final Logger log = Logger.loggerFor(AwsCrtAsyncHttpClient.class);
private static final String AWS_COMMON_RUNTIME = "AwsCommonRuntime";
private static final long DEFAULT_STREAM_WINDOW_SIZE = 16L * 1024L * 1024L; // 16 MB
private final Map<URI, HttpClientConnectionManager> connectionPools = new ConcurrentHashMap<>();
private final LinkedList<CrtResource> ownedSubResources = new LinkedList<>();
private final ClientBootstrap bootstrap;
private final SocketOptions socketOptions;
private final TlsContext tlsContext;
private final HttpProxyOptions proxyOptions;
private final HttpMonitoringOptions monitoringOptions;
private final long maxConnectionIdleInMilliseconds;
private final long readBufferSize;
private final int maxConnectionsPerEndpoint;
private boolean isClosed = false;
private AwsCrtAsyncHttpClient(DefaultBuilder builder, AttributeMap config) {
if (config.get(PROTOCOL) == Protocol.HTTP2) {
throw new UnsupportedOperationException("HTTP/2 is not supported in AwsCrtAsyncHttpClient yet. Use "
+ "NettyNioAsyncHttpClient instead.");
}
try (ClientBootstrap clientBootstrap = new ClientBootstrap(null, null);
SocketOptions clientSocketOptions = buildSocketOptions(builder.tcpKeepAliveConfiguration,
config.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT));
TlsContextOptions clientTlsContextOptions =
TlsContextOptions.createDefaultClient()
.withCipherPreference(resolveCipherPreference(builder.postQuantumTlsEnabled))
.withVerifyPeer(!config.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES));
TlsContext clientTlsContext = new TlsContext(clientTlsContextOptions)) {
this.bootstrap = registerOwnedResource(clientBootstrap);
this.socketOptions = registerOwnedResource(clientSocketOptions);
this.tlsContext = registerOwnedResource(clientTlsContext);
this.readBufferSize = builder.readBufferSize == null ? DEFAULT_STREAM_WINDOW_SIZE : builder.readBufferSize;
this.maxConnectionsPerEndpoint = config.get(SdkHttpConfigurationOption.MAX_CONNECTIONS);
this.monitoringOptions = resolveHttpMonitoringOptions(builder.connectionHealthConfiguration).orElse(null);
this.maxConnectionIdleInMilliseconds = config.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis();
this.proxyOptions = resolveProxy(builder.proxyConfiguration, tlsContext).orElse(null);
}
}
/**
* Marks a Native CrtResource as owned by the current Java Object.
*
* @param subresource The Resource to own.
* @param <T> The CrtResource Type
* @return The CrtResource passed in
*/
private <T extends CrtResource> T registerOwnedResource(T subresource) {
if (subresource != null) {
subresource.addRef();
ownedSubResources.push(subresource);
}
return subresource;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Create a {@link AwsCrtAsyncHttpClient} client with the default configuration
*
* @return an {@link SdkAsyncHttpClient}
*/
public static SdkAsyncHttpClient create() {
return new DefaultBuilder().build();
}
@Override
public String clientName() {
return AWS_COMMON_RUNTIME;
}
private HttpClientConnectionManager createConnectionPool(URI uri) {
log.debug(() -> "Creating ConnectionPool for: URI:" + uri + ", MaxConns: " + maxConnectionsPerEndpoint);
HttpClientConnectionManagerOptions options = new HttpClientConnectionManagerOptions()
.withClientBootstrap(bootstrap)
.withSocketOptions(socketOptions)
.withTlsContext(tlsContext)
.withUri(uri)
.withWindowSize(readBufferSize)
.withMaxConnections(maxConnectionsPerEndpoint)
.withManualWindowManagement(true)
.withProxyOptions(proxyOptions)
.withMonitoringOptions(monitoringOptions)
.withMaxConnectionIdleInMilliseconds(maxConnectionIdleInMilliseconds);
return HttpClientConnectionManager.create(options);
}
/*
* Callers of this function MUST account for the addRef() on the pool before returning.
* Every execution path consuming the return value must guarantee an associated close().
* Currently this function is only used by execute(), which guarantees a matching close
* via the try-with-resources block.
*
* This guarantees that a returned pool will not get closed (by closing the http client) during
* the time it takes to submit a request to the pool. Acquisition requests submitted to the pool will
* be properly failed if the http client is closed before the acquisition completes.
*
* This additional complexity means we only have to keep a lock for the scope of this function, as opposed to
* the scope of calling execute(). This function will almost always just be a hash lookup and the return of an
* existing pool. If we add all of execute() to the scope, we include, at minimum a JNI call to the native
* pool implementation.
*/
private HttpClientConnectionManager getOrCreateConnectionPool(URI uri) {
synchronized (this) {
if (isClosed) {
throw new IllegalStateException("Client is closed. No more requests can be made with this client.");
}
HttpClientConnectionManager connPool = connectionPools.computeIfAbsent(uri, this::createConnectionPool);
connPool.addRef();
return connPool;
}
}
@Override
public CompletableFuture<Void> execute(AsyncExecuteRequest asyncRequest) {
paramNotNull(asyncRequest, "asyncRequest");
paramNotNull(asyncRequest.request(), "SdkHttpRequest");
paramNotNull(asyncRequest.requestContentPublisher(), "RequestContentPublisher");
paramNotNull(asyncRequest.responseHandler(), "ResponseHandler");
asyncRequest.metricCollector()
.filter(metricCollector -> !(metricCollector instanceof NoOpMetricCollector))
.ifPresent(metricCollector -> metricCollector.reportMetric(HTTP_CLIENT_NAME, clientName()));
/*
* See the note on getOrCreateConnectionPool()
*
* In particular, this returns a ref-counted object and calling getOrCreateConnectionPool
* increments the ref count by one. We add a try-with-resources to release our ref
* once we have successfully submitted a request. In this way, we avoid a race condition
* when close/shutdown is called from another thread while this function is executing (ie.
* we have a pool and no one can destroy it underneath us until we've finished submitting the
* request)
*/
try (HttpClientConnectionManager crtConnPool = getOrCreateConnectionPool(poolKey(asyncRequest))) {
CrtRequestContext context = CrtRequestContext.builder()
.crtConnPool(crtConnPool)
.readBufferSize(readBufferSize)
.request(asyncRequest)
.build();
return new CrtRequestExecutor().execute(context);
}
}
private URI poolKey(AsyncExecuteRequest asyncRequest) {
SdkHttpRequest sdkRequest = asyncRequest.request();
return invokeSafely(() -> new URI(sdkRequest.protocol(), null, sdkRequest.host(),
sdkRequest.port(), null, null, null));
}
@Override
public void close() {
synchronized (this) {
if (isClosed) {
return;
}
connectionPools.values().forEach(pool -> IoUtils.closeQuietly(pool, log.logger()));
ownedSubResources.forEach(r -> IoUtils.closeQuietly(r, log.logger()));
ownedSubResources.clear();
isClosed = true;
}
}
/**
* Builder that allows configuration of the AWS CRT HTTP implementation.
*/
public interface Builder extends SdkAsyncHttpClient.Builder<AwsCrtAsyncHttpClient.Builder> {
/**
* The Maximum number of allowed concurrent requests. For HTTP/1.1 this is the same as max connections.
* @param maxConcurrency maximum concurrency per endpoint
* @return The builder of the method chaining.
*/
Builder maxConcurrency(Integer maxConcurrency);
/**
* Configures the number of unread bytes that can be buffered in the
* client before we stop reading from the underlying TCP socket and wait for the Subscriber
* to read more data.
*
* @param readBufferSize The number of bytes that can be buffered.
* @return The builder of the method chaining.
*/
Builder readBufferSizeInBytes(Long readBufferSize);
/**
* Sets the http proxy configuration to use for this client.
* @param proxyConfiguration The http proxy configuration to use
* @return The builder of the method chaining.
*/
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
/**
* Sets the http proxy configuration to use for this client.
*
* @param proxyConfigurationBuilderConsumer The consumer of the proxy configuration builder object.
* @return the builder for method chaining.
*/
Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer);
/**
* Configure the health checks for all connections established by this client.
*
* <p>
* You can set a throughput threshold for a connection to be considered healthy.
* If a connection falls below this threshold ({@link ConnectionHealthConfiguration#minimumThroughputInBps()
* }) for the configurable amount
* of time ({@link ConnectionHealthConfiguration#minimumThroughputTimeout()}),
* then the connection is considered unhealthy and will be shut down.
*
* <p>
* By default, monitoring options are disabled. You can enable {@code healthChecks} by providing this configuration
* and specifying the options for monitoring for the connection manager.
* @param healthChecksConfiguration The health checks config to use
* @return The builder of the method chaining.
*/
Builder connectionHealthConfiguration(ConnectionHealthConfiguration healthChecksConfiguration);
/**
* A convenience method that creates an instance of the {@link ConnectionHealthConfiguration} builder, avoiding the
* need to create one manually via {@link ConnectionHealthConfiguration#builder()}.
*
* @param healthChecksConfigurationBuilder The health checks config builder to use
* @return The builder of the method chaining.
* @see #connectionHealthConfiguration(ConnectionHealthConfiguration)
*/
Builder connectionHealthConfiguration(Consumer<ConnectionHealthConfiguration.Builder>
healthChecksConfigurationBuilder);
/**
* Configure the maximum amount of time that a connection should be allowed to remain open while idle.
* @param connectionMaxIdleTime the maximum amount of connection idle time
* @return The builder of the method chaining.
*/
Builder connectionMaxIdleTime(Duration connectionMaxIdleTime);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out.
* @param connectionTimeout timeout
* @return The builder of the method chaining.
*/
Builder connectionTimeout(Duration connectionTimeout);
/**
* Configure whether to enable {@code tcpKeepAlive} and relevant configuration for all connections established by this
* client.
*
* <p>
* By default, tcpKeepAlive is disabled. You can enable {@code tcpKeepAlive} by providing this configuration
* and specifying periodic TCP keepalive packet intervals and timeouts. This may be required for certain connections for
* longer durations than default socket timeouts.
*
* @param tcpKeepAliveConfiguration The TCP keep-alive configuration to use
* @return The builder of the method chaining.
*/
Builder tcpKeepAliveConfiguration(TcpKeepAliveConfiguration tcpKeepAliveConfiguration);
/**
* Configure whether to enable {@code tcpKeepAlive} and relevant configuration for all connections established by this
* client.
*
* <p>
* A convenience method that creates an instance of the {@link TcpKeepAliveConfiguration} builder, avoiding the
* need to create one manually via {@link TcpKeepAliveConfiguration#builder()}.
*
* @param tcpKeepAliveConfigurationBuilder The TCP keep-alive configuration builder to use
* @return The builder of the method chaining.
* @see #tcpKeepAliveConfiguration(TcpKeepAliveConfiguration)
*/
Builder tcpKeepAliveConfiguration(Consumer<TcpKeepAliveConfiguration.Builder>
tcpKeepAliveConfigurationBuilder);
/**
* Configure whether to enable a hybrid post-quantum key exchange option for the Transport Layer Security (TLS) network
* encryption protocol when communicating with services that support Post Quantum TLS. If Post Quantum cipher suites are
* not supported on the platform, the SDK will use the default TLS cipher suites.
*
* <p>
* See <a href="https://docs.aws.amazon.com/kms/latest/developerguide/pqtls.html">Using hybrid post-quantum TLS with AWS KMS</a>
*
* <p>
* It's disabled by default.
*
* @param postQuantumTlsEnabled whether to prefer Post Quantum TLS
* @return The builder of the method chaining.
*/
Builder postQuantumTlsEnabled(Boolean postQuantumTlsEnabled);
}
/**
* Factory that allows more advanced configuration of the AWS CRT HTTP implementation. Use {@link #builder()} to
* configure and construct an immutable instance of the factory.
*/
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private Long readBufferSize;
private ProxyConfiguration proxyConfiguration;
private ConnectionHealthConfiguration connectionHealthConfiguration;
private TcpKeepAliveConfiguration tcpKeepAliveConfiguration;
private Boolean postQuantumTlsEnabled;
private DefaultBuilder() {
}
@Override
public SdkAsyncHttpClient build() {
return new AwsCrtAsyncHttpClient(this, standardOptions.build()
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS));
}
@Override
public SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
return new AwsCrtAsyncHttpClient(this, standardOptions.build()
.merge(serviceDefaults)
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS));
}
@Override
public Builder maxConcurrency(Integer maxConcurrency) {
Validate.isPositiveOrNull(maxConcurrency, "maxConcurrency");
standardOptions.put(SdkHttpConfigurationOption.MAX_CONNECTIONS, maxConcurrency);
return this;
}
@Override
public Builder readBufferSizeInBytes(Long readBufferSize) {
Validate.isPositiveOrNull(readBufferSize, "readBufferSize");
this.readBufferSize = readBufferSize;
return this;
}
@Override
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
@Override
public Builder connectionHealthConfiguration(ConnectionHealthConfiguration monitoringOptions) {
this.connectionHealthConfiguration = monitoringOptions;
return this;
}
@Override
public Builder connectionHealthConfiguration(Consumer<ConnectionHealthConfiguration.Builder>
configurationBuilder) {
ConnectionHealthConfiguration.Builder builder = ConnectionHealthConfiguration.builder();
configurationBuilder.accept(builder);
return connectionHealthConfiguration(builder.build());
}
@Override
public Builder connectionMaxIdleTime(Duration connectionMaxIdleTime) {
Validate.isPositive(connectionMaxIdleTime, "connectionMaxIdleTime");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, connectionMaxIdleTime);
return this;
}
@Override
public Builder connectionTimeout(Duration connectionTimeout) {
Validate.isPositive(connectionTimeout, "connectionTimeout");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, connectionTimeout);
return this;
}
@Override
public Builder tcpKeepAliveConfiguration(TcpKeepAliveConfiguration tcpKeepAliveConfiguration) {
this.tcpKeepAliveConfiguration = tcpKeepAliveConfiguration;
return this;
}
@Override
public Builder tcpKeepAliveConfiguration(Consumer<TcpKeepAliveConfiguration.Builder>
tcpKeepAliveConfigurationBuilder) {
TcpKeepAliveConfiguration.Builder builder = TcpKeepAliveConfiguration.builder();
tcpKeepAliveConfigurationBuilder.accept(builder);
return tcpKeepAliveConfiguration(builder.build());
}
@Override
public Builder postQuantumTlsEnabled(Boolean postQuantumTlsEnabled) {
this.postQuantumTlsEnabled = postQuantumTlsEnabled;
return this;
}
@Override
public Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer) {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
proxyConfigurationBuilderConsumer.accept(builder);
return proxyConfiguration(builder.build());
}
}
}
| 1,290 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/CrtRequestExecutor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal;
import static software.amazon.awssdk.http.HttpMetric.AVAILABLE_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.CONCURRENCY_ACQUIRE_DURATION;
import static software.amazon.awssdk.http.HttpMetric.LEASED_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.MAX_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.PENDING_CONCURRENCY_ACQUIRES;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.CrtRuntimeException;
import software.amazon.awssdk.crt.http.HttpClientConnection;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.crt.http.HttpManagerMetrics;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.crt.http.HttpStreamResponseHandler;
import software.amazon.awssdk.http.SdkCancellationException;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.crt.internal.request.CrtRequestAdapter;
import software.amazon.awssdk.http.crt.internal.response.CrtResponseAdapter;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public final class CrtRequestExecutor {
private static final Logger log = Logger.loggerFor(CrtRequestExecutor.class);
public CompletableFuture<Void> execute(CrtRequestContext executionContext) {
// go ahead and get a reference to the metricCollector since multiple futures will
// need it regardless.
MetricCollector metricCollector = executionContext.metricCollector();
boolean shouldPublishMetrics = metricCollector != null && !(metricCollector instanceof NoOpMetricCollector);
long acquireStartTime = 0;
if (shouldPublishMetrics) {
// go ahead and get acquireStartTime for the concurrency timer as early as possible,
// so it's as accurate as possible, but only do it in a branch since clock_gettime()
// results in a full sys call barrier (multiple mutexes and a hw interrupt).
acquireStartTime = System.nanoTime();
}
CompletableFuture<Void> requestFuture = createExecutionFuture(executionContext.sdkRequest());
// When a Connection is ready from the Connection Pool, schedule the Request on the connection
CompletableFuture<HttpClientConnection> httpClientConnectionCompletableFuture =
executionContext.crtConnPool().acquireConnection();
long finalAcquireStartTime = acquireStartTime;
httpClientConnectionCompletableFuture.whenComplete((crtConn, throwable) -> {
AsyncExecuteRequest asyncRequest = executionContext.sdkRequest();
if (shouldPublishMetrics) {
reportMetrics(executionContext, metricCollector, finalAcquireStartTime);
}
// If we didn't get a connection for some reason, fail the request
if (throwable != null) {
reportFailure(crtConn,
new IOException("An exception occurred when acquiring a connection", throwable),
requestFuture,
asyncRequest.responseHandler());
return;
}
executeRequest(executionContext, requestFuture, crtConn, asyncRequest);
});
return requestFuture;
}
private static void reportMetrics(CrtRequestContext executionContext, MetricCollector metricCollector,
long acquireStartTime) {
long acquireCompletionTime = System.nanoTime();
Duration acquireTimeTaken = Duration.ofNanos(acquireCompletionTime - acquireStartTime);
metricCollector.reportMetric(CONCURRENCY_ACQUIRE_DURATION, acquireTimeTaken);
HttpClientConnectionManager connManager = executionContext.crtConnPool();
HttpManagerMetrics managerMetrics = connManager.getManagerMetrics();
// currently this executor only handles HTTP 1.1. Until H2 is added, the max concurrency settings are 1:1 with TCP
// connections. When H2 is added, this code needs to be updated to handle stream multiplexing
metricCollector.reportMetric(MAX_CONCURRENCY, connManager.getMaxConnections());
metricCollector.reportMetric(AVAILABLE_CONCURRENCY, saturatedCast(managerMetrics.getAvailableConcurrency()));
metricCollector.reportMetric(LEASED_CONCURRENCY, saturatedCast(managerMetrics.getLeasedConcurrency()));
metricCollector.reportMetric(PENDING_CONCURRENCY_ACQUIRES, saturatedCast(managerMetrics.getPendingConcurrencyAcquires()));
}
private void executeRequest(CrtRequestContext executionContext,
CompletableFuture<Void> requestFuture,
HttpClientConnection crtConn,
AsyncExecuteRequest asyncRequest) {
HttpRequest crtRequest = CrtRequestAdapter.toCrtRequest(executionContext);
HttpStreamResponseHandler crtResponseHandler =
CrtResponseAdapter.toCrtResponseHandler(crtConn, requestFuture, asyncRequest.responseHandler());
// Submit the request on the connection
try {
crtConn.makeRequest(crtRequest, crtResponseHandler).activate();
} catch (HttpException e) {
Throwable toThrow = e;
if (HttpClientConnection.isErrorRetryable(e)) {
// IOExceptions get retried, and if the CRT says this error is retryable,
// it's semantically an IOException anyway.
toThrow = new IOException(e);
}
reportFailure(crtConn,
toThrow,
requestFuture,
asyncRequest.responseHandler());
} catch (IllegalStateException | CrtRuntimeException e) {
// CRT throws IllegalStateException if the connection is closed
reportFailure(crtConn, new IOException("An exception occurred when making the request", e),
requestFuture,
asyncRequest.responseHandler());
}
}
/**
* Create the execution future and set up the cancellation logic.
* @return The created execution future.
*/
private CompletableFuture<Void> createExecutionFuture(AsyncExecuteRequest request) {
CompletableFuture<Void> future = new CompletableFuture<>();
future.whenComplete((r, t) -> {
if (t == null) {
return;
}
// TODO: Aborting request once it's supported in CRT
if (future.isCancelled()) {
request.responseHandler().onError(new SdkCancellationException("The request was cancelled"));
}
});
return future;
}
/**
* Notify the provided response handler and future of the failure.
*/
private void reportFailure(HttpClientConnection crtConn,
Throwable cause,
CompletableFuture<Void> executeFuture,
SdkAsyncHttpResponseHandler responseHandler) {
if (crtConn != null) {
crtConn.close();
}
try {
responseHandler.onError(cause);
} catch (Exception e) {
log.error(() -> "SdkAsyncHttpResponseHandler " + responseHandler + " threw an exception in onError. It will be "
+ "ignored.", e);
}
executeFuture.completeExceptionally(cause);
}
}
| 1,291 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/CrtRequestContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
public final class CrtRequestContext {
private final AsyncExecuteRequest request;
private final long readBufferSize;
private final HttpClientConnectionManager crtConnPool;
private final MetricCollector metricCollector;
private CrtRequestContext(Builder builder) {
this.request = builder.request;
this.readBufferSize = builder.readBufferSize;
this.crtConnPool = builder.crtConnPool;
this.metricCollector = request.metricCollector().orElse(null);
}
public static Builder builder() {
return new Builder();
}
public AsyncExecuteRequest sdkRequest() {
return request;
}
public long readBufferSize() {
return readBufferSize;
}
public HttpClientConnectionManager crtConnPool() {
return crtConnPool;
}
public MetricCollector metricCollector() {
return metricCollector;
}
public static class Builder {
private AsyncExecuteRequest request;
private long readBufferSize;
private HttpClientConnectionManager crtConnPool;
private Builder() {
}
public Builder request(AsyncExecuteRequest request) {
this.request = request;
return this;
}
public Builder readBufferSize(long readBufferSize) {
this.readBufferSize = readBufferSize;
return this;
}
public Builder crtConnPool(HttpClientConnectionManager crtConnPool) {
this.crtConnPool = crtConnPool;
return this;
}
public CrtRequestContext build() {
return new CrtRequestContext(this);
}
}
}
| 1,292 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/AwsCrtConfigurationUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.io.SocketOptions;
import software.amazon.awssdk.crt.io.TlsCipherPreference;
import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient;
import software.amazon.awssdk.http.crt.TcpKeepAliveConfiguration;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.NumericUtils;
@SdkInternalApi
public final class AwsCrtConfigurationUtils {
private static final Logger log = Logger.loggerFor(AwsCrtAsyncHttpClient.class);
private AwsCrtConfigurationUtils() {
}
public static SocketOptions buildSocketOptions(TcpKeepAliveConfiguration tcpKeepAliveConfiguration,
Duration connectionTimeout) {
SocketOptions clientSocketOptions = new SocketOptions();
if (connectionTimeout != null) {
clientSocketOptions.connectTimeoutMs = NumericUtils.saturatedCast(connectionTimeout.toMillis());
}
if (tcpKeepAliveConfiguration != null) {
clientSocketOptions.keepAliveIntervalSecs =
NumericUtils.saturatedCast(tcpKeepAliveConfiguration.keepAliveInterval().getSeconds());
clientSocketOptions.keepAliveTimeoutSecs =
NumericUtils.saturatedCast(tcpKeepAliveConfiguration.keepAliveTimeout().getSeconds());
}
return clientSocketOptions;
}
public static TlsCipherPreference resolveCipherPreference(Boolean postQuantumTlsEnabled) {
TlsCipherPreference defaultTls = TlsCipherPreference.TLS_CIPHER_SYSTEM_DEFAULT;
if (postQuantumTlsEnabled == null || !postQuantumTlsEnabled) {
return defaultTls;
}
// TODO: change this to the new PQ TLS Policy that stays up to date when it's ready
TlsCipherPreference pqTls = TlsCipherPreference.TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05;
if (!pqTls.isSupported()) {
log.warn(() -> "Hybrid post-quantum cipher suites are not supported on this platform. The SDK will use the system "
+ "default cipher suites instead");
return defaultTls;
}
return pqTls;
}
}
| 1,293 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/response/CrtResponseAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal.response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.CRT;
import software.amazon.awssdk.crt.http.HttpClientConnection;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.crt.http.HttpHeader;
import software.amazon.awssdk.crt.http.HttpHeaderBlock;
import software.amazon.awssdk.crt.http.HttpStream;
import software.amazon.awssdk.crt.http.HttpStreamResponseHandler;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.async.SimplePublisher;
/**
* Implements the CrtHttpStreamHandler API and converts CRT callbacks into calls to SDK AsyncExecuteRequest methods
*/
@SdkInternalApi
public final class CrtResponseAdapter implements HttpStreamResponseHandler {
private static final Logger log = Logger.loggerFor(CrtResponseAdapter.class);
private final HttpClientConnection connection;
private final CompletableFuture<Void> completionFuture;
private final SdkAsyncHttpResponseHandler responseHandler;
private final SimplePublisher<ByteBuffer> responsePublisher = new SimplePublisher<>();
private final SdkHttpResponse.Builder responseBuilder = SdkHttpResponse.builder();
private CrtResponseAdapter(HttpClientConnection connection,
CompletableFuture<Void> completionFuture,
SdkAsyncHttpResponseHandler responseHandler) {
this.connection = Validate.paramNotNull(connection, "connection");
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
this.responseHandler = Validate.paramNotNull(responseHandler, "responseHandler");
}
public static HttpStreamResponseHandler toCrtResponseHandler(HttpClientConnection crtConn,
CompletableFuture<Void> requestFuture,
SdkAsyncHttpResponseHandler responseHandler) {
return new CrtResponseAdapter(crtConn, requestFuture, responseHandler);
}
@Override
public void onResponseHeaders(HttpStream stream, int responseStatusCode, int headerType, HttpHeader[] nextHeaders) {
if (headerType == HttpHeaderBlock.MAIN.getValue()) {
for (HttpHeader h : nextHeaders) {
responseBuilder.appendHeader(h.getName(), h.getValue());
}
}
}
@Override
public void onResponseHeadersDone(HttpStream stream, int headerType) {
if (headerType == HttpHeaderBlock.MAIN.getValue()) {
responseBuilder.statusCode(stream.getResponseStatusCode());
responseHandler.onHeaders(responseBuilder.build());
responseHandler.onStream(responsePublisher);
}
}
@Override
public int onResponseBody(HttpStream stream, byte[] bodyBytesIn) {
CompletableFuture<Void> writeFuture = responsePublisher.send(ByteBuffer.wrap(bodyBytesIn));
if (writeFuture.isDone() && !writeFuture.isCompletedExceptionally()) {
// Optimization: If write succeeded immediately, return non-zero to avoid the extra call back into the CRT.
return bodyBytesIn.length;
}
writeFuture.whenComplete((result, failure) -> {
if (failure != null) {
failResponseHandlerAndFuture(stream, failure);
return;
}
stream.incrementWindow(bodyBytesIn.length);
});
return 0;
}
@Override
public void onResponseComplete(HttpStream stream, int errorCode) {
if (errorCode == CRT.AWS_CRT_SUCCESS) {
onSuccessfulResponseComplete(stream);
} else {
onFailedResponseComplete(stream, new HttpException(errorCode));
}
}
private void onSuccessfulResponseComplete(HttpStream stream) {
responsePublisher.complete().whenComplete((result, failure) -> {
if (failure != null) {
failResponseHandlerAndFuture(stream, failure);
return;
}
if (HttpStatusFamily.of(responseBuilder.statusCode()) == HttpStatusFamily.SERVER_ERROR) {
connection.shutdown();
}
connection.close();
stream.close();
completionFuture.complete(null);
});
}
private void onFailedResponseComplete(HttpStream stream, HttpException error) {
log.debug(() -> "HTTP response encountered an error.", error);
Throwable toThrow = error;
if (HttpClientConnection.isErrorRetryable(error)) {
// IOExceptions get retried, and if the CRT says this error is retryable,
// it's semantically an IOException anyway.
toThrow = new IOException(error);
}
responsePublisher.error(toThrow);
failResponseHandlerAndFuture(stream, toThrow);
}
private void failResponseHandlerAndFuture(HttpStream stream, Throwable error) {
callResponseHandlerOnError(error);
completionFuture.completeExceptionally(error);
connection.shutdown();
connection.close();
stream.close();
}
private void callResponseHandlerOnError(Throwable error) {
try {
responseHandler.onError(error);
} catch (RuntimeException e) {
log.warn(() -> "Exception raised from SdkAsyncHttpResponseHandler#onError.", e);
}
}
}
| 1,294 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/request/CrtRequestBodyAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal.request;
import java.nio.ByteBuffer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.http.HttpRequestBodyStream;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber;
import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult;
@SdkInternalApi
final class CrtRequestBodyAdapter implements HttpRequestBodyStream {
private final SdkHttpContentPublisher requestPublisher;
private final ByteBufferStoringSubscriber requestBodySubscriber;
CrtRequestBodyAdapter(SdkHttpContentPublisher requestPublisher, long readLimit) {
this.requestPublisher = requestPublisher;
this.requestBodySubscriber = new ByteBufferStoringSubscriber(readLimit);
requestPublisher.subscribe(requestBodySubscriber);
}
@Override
public boolean sendRequestBody(ByteBuffer bodyBytesOut) {
return requestBodySubscriber.transferTo(bodyBytesOut) == TransferResult.END_OF_STREAM;
}
@Override
public long getLength() {
return requestPublisher.contentLength().orElse(0L);
}
}
| 1,295 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/request/CrtRequestAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt.internal.request;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.http.HttpHeader;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.http.Header;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.crt.internal.CrtRequestContext;
@SdkInternalApi
public final class CrtRequestAdapter {
private CrtRequestAdapter() {
}
public static HttpRequest toCrtRequest(CrtRequestContext request) {
AsyncExecuteRequest sdkExecuteRequest = request.sdkRequest();
SdkHttpRequest sdkRequest = sdkExecuteRequest.request();
String method = sdkRequest.method().name();
String encodedPath = sdkRequest.encodedPath();
if (encodedPath == null || encodedPath.isEmpty()) {
encodedPath = "/";
}
String encodedQueryString = sdkRequest.encodedQueryParameters()
.map(value -> "?" + value)
.orElse("");
HttpHeader[] crtHeaderArray = asArray(createHttpHeaderList(sdkRequest.getUri(), sdkExecuteRequest));
return new HttpRequest(method,
encodedPath + encodedQueryString,
crtHeaderArray,
new CrtRequestBodyAdapter(sdkExecuteRequest.requestContentPublisher(),
request.readBufferSize()));
}
private static HttpHeader[] asArray(List<HttpHeader> crtHeaderList) {
return crtHeaderList.toArray(new HttpHeader[0]);
}
private static List<HttpHeader> createHttpHeaderList(URI uri, AsyncExecuteRequest sdkExecuteRequest) {
SdkHttpRequest sdkRequest = sdkExecuteRequest.request();
// worst case we may add 3 more headers here
List<HttpHeader> crtHeaderList = new ArrayList<>(sdkRequest.numHeaders() + 3);
// Set Host Header if needed
if (!sdkRequest.firstMatchingHeader(Header.HOST).isPresent()) {
crtHeaderList.add(new HttpHeader(Header.HOST, uri.getHost()));
}
// Add Connection Keep Alive Header to reuse this Http Connection as long as possible
if (!sdkRequest.firstMatchingHeader(Header.CONNECTION).isPresent()) {
crtHeaderList.add(new HttpHeader(Header.CONNECTION, Header.KEEP_ALIVE_VALUE));
}
// Set Content-Length if needed
Optional<Long> contentLength = sdkExecuteRequest.requestContentPublisher().contentLength();
if (!sdkRequest.firstMatchingHeader(Header.CONTENT_LENGTH).isPresent() && contentLength.isPresent()) {
crtHeaderList.add(new HttpHeader(Header.CONTENT_LENGTH, Long.toString(contentLength.get())));
}
// Add the rest of the Headers
sdkRequest.forEachHeader((key, value) -> {
value.stream().map(val -> new HttpHeader(key, val)).forEach(crtHeaderList::add);
});
return crtHeaderList;
}
}
| 1,296 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URISyntaxException;
import java.util.Optional;
import java.util.Set;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class NettyProxyConfigurationTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings, TestProxySetting expectedProxySettings,
Boolean useSystemProperty, Boolean useEnvironmentVariable, String protocol) throws URISyntaxException {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
Set<String> nonProxyHosts = userSetProxySettings.getNonProxyHosts();
Optional.ofNullable(hostName).ifPresent(builder::host);
Optional.ofNullable(portNumber).ifPresent(builder::port);
Optional.ofNullable(userName).ifPresent(builder::username);
Optional.ofNullable(password).ifPresent(builder::password);
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
builder.nonProxyHosts(nonProxyHosts);
}
}
if (!"http".equals(protocol)) {
builder.scheme(protocol);
}
if (useSystemProperty != null) {
builder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
builder.useEnvironmentVariableValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = builder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
assertThat(proxyConfiguration.nonProxyHosts()).isEqualTo(expectedProxySettings.getNonProxyHosts());
}
}
| 1,297 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/SdkEventLoopGroupTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.channel.socket.oio.OioSocketChannel;
import org.junit.Test;
public class SdkEventLoopGroupTest {
@Test
public void creatingUsingBuilder() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.builder().numberOfThreads(1).build();
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.eventLoopGroup()).isNotNull();
}
@Test
public void creatingUsingStaticMethod_A() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.create(new NioEventLoopGroup(), NioSocketChannel::new);
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory().newChannel()).isInstanceOf(NioDatagramChannel.class);
assertThat(sdkEventLoopGroup.eventLoopGroup()).isNotNull();
}
@Test
public void creatingUsingStaticMethod_B() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.create(new OioEventLoopGroup(), OioSocketChannel::new);
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory().newChannel()).isInstanceOf(OioDatagramChannel.class);
assertThat(sdkEventLoopGroup.eventLoopGroup()).isNotNull();
}
@Test
public void notProvidingChannelFactory_channelFactoryResolved() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.create(new NioEventLoopGroup());
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory().newChannel()).isInstanceOf(NioDatagramChannel.class);
}
@Test(expected = IllegalArgumentException.class)
public void notProvidingChannelFactory_unknownEventLoopGroup() {
SdkEventLoopGroup.create(new DefaultEventLoopGroup());
}
}
| 1,298 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/Http2MetricsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2StreamFrame;
import io.netty.util.ReferenceCountUtil;
import java.net.URI;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Http2Metric;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
public class Http2MetricsTest {
private static final int H2_DEFAULT_WINDOW_SIZE = 65535;
private static final int SERVER_MAX_CONCURRENT_STREAMS = 2;
private static final int SERVER_INITIAL_WINDOW_SIZE = 65535 * 2;
private static final TestHttp2Server SERVER = new TestHttp2Server();
@BeforeAll
public static void setup() throws InterruptedException {
SERVER.start();
}
@AfterAll
public static void teardown() throws InterruptedException {
SERVER.stop();
}
@Test
public void maxClientStreamsLowerThanServerMaxStreamsReportClientMaxStreams() {
try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.maxConcurrency(10)
.http2Configuration(c -> c.maxStreams(1L)
.initialWindowSize(65535 * 3))
.build()) {
MetricCollector metricCollector = MetricCollector.create("test");
client.execute(createExecuteRequest(metricCollector)).join();
MetricCollection metrics = metricCollector.collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
assertThat(metrics.metricValues(HttpMetric.CONCURRENCY_ACQUIRE_DURATION).get(0)).isPositive();
// The stream window doesn't get initialized with the connection
// initial setting and the update appears to be asynchronous so
// this may be the default window size just based on when the
// stream window was queried or if this is the first time the
// stream is used (i.e. not previously pooled)
assertThat(metrics.metricValues(Http2Metric.LOCAL_STREAM_WINDOW_SIZE_IN_BYTES).get(0)).isIn(H2_DEFAULT_WINDOW_SIZE, 65535 * 3);
assertThat(metrics.metricValues(Http2Metric.REMOTE_STREAM_WINDOW_SIZE_IN_BYTES)).containsExactly(SERVER_INITIAL_WINDOW_SIZE);
}
}
@Test
public void maxClientStreamsHigherThanServerMaxStreamsReportServerMaxStreams() {
try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.maxConcurrency(10)
.http2Configuration(c -> c.maxStreams(3L)
.initialWindowSize(65535 * 3))
.build()) {
MetricCollector metricCollector = MetricCollector.create("test");
client.execute(createExecuteRequest(metricCollector)).join();
MetricCollection metrics = metricCollector.collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isIn(0, 2, 3);
assertThat(metrics.metricValues(HttpMetric.CONCURRENCY_ACQUIRE_DURATION).get(0)).isPositive();
// The stream window doesn't get initialized with the connection
// initial setting and the update appears to be asynchronous so
// this may be the default window size just based on when the
// stream window was queried or if this is the first time the
// stream is used (i.e. not previously pooled)
assertThat(metrics.metricValues(Http2Metric.LOCAL_STREAM_WINDOW_SIZE_IN_BYTES).get(0)).isIn(H2_DEFAULT_WINDOW_SIZE, 65535 * 3);
assertThat(metrics.metricValues(Http2Metric.REMOTE_STREAM_WINDOW_SIZE_IN_BYTES)).containsExactly(SERVER_INITIAL_WINDOW_SIZE);
}
}
private AsyncExecuteRequest createExecuteRequest(MetricCollector metricCollector) {
URI uri = URI.create("http://localhost:" + SERVER.port());
SdkHttpRequest request = createRequest(uri);
return AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(new EmptyPublisher())
.responseHandler(new RecordingResponseHandler())
.metricCollector(metricCollector)
.build();
}
private SdkHttpFullRequest createRequest(URI uri) {
return SdkHttpFullRequest.builder()
.uri(uri)
.method(SdkHttpMethod.GET)
.encodedPath("/")
.putHeader("Host", uri.getHost())
.putHeader("Content-Length", "0")
.build();
}
private static final class TestHttp2Server extends ChannelInitializer<SocketChannel> {
private ServerBootstrap bootstrap;
private ServerSocketChannel channel;
private TestHttp2Server() {
}
public void start() throws InterruptedException {
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(new NioEventLoopGroup())
.childHandler(this)
.localAddress(0)
.childOption(ChannelOption.SO_KEEPALIVE, true);
channel = ((ServerSocketChannel) bootstrap.bind().await().channel());
}
public int port() {
return channel.localAddress().getPort();
}
public void stop() throws InterruptedException {
channel.close().await();
}
@Override
protected void initChannel(SocketChannel ch) {
Http2FrameCodec codec = Http2FrameCodecBuilder.forServer()
.initialSettings(new Http2Settings()
.maxConcurrentStreams(SERVER_MAX_CONCURRENT_STREAMS)
.initialWindowSize(SERVER_INITIAL_WINDOW_SIZE))
.build();
ch.pipeline().addLast(codec);
ch.pipeline().addLast(new SuccessfulHandler());
}
}
private static class SuccessfulHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (!(msg instanceof Http2Frame)) {
ctx.fireChannelRead(msg);
return;
}
ReferenceCountUtil.release(msg);
boolean isEnd = isEndFrame(msg);
if (isEnd) {
ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers().status("204"), true)
.stream(((Http2StreamFrame) msg).stream()));
}
}
private boolean isEndFrame(Object msg) {
if (msg instanceof Http2HeadersFrame) {
return ((Http2HeadersFrame) msg).isEndStream();
}
if (msg instanceof Http2DataFrame) {
return ((Http2DataFrame) msg).isEndStream();
}
return false;
}
}
}
| 1,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.