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/camel-k-runtime/support/camel-k-catalog-model/src/main/java/org/apache/camel/k/catalog/model/k8s | Create_ds/camel-k-runtime/support/camel-k-catalog-model/src/main/java/org/apache/camel/k/catalog/model/k8s/crd/CamelCatalogSpec.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.camel.k.catalog.model.k8s.crd;
import java.util.Collections;
import java.util.SortedMap;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.camel.k.catalog.model.CamelArtifact;
import org.apache.camel.k.catalog.model.CamelLoader;
import org.immutables.value.Value;
@Value.Immutable
@Value.Style(depluralize = true)
@JsonDeserialize(builder = CamelCatalogSpec.Builder.class)
@JsonPropertyOrder({ "runtime", "artifacts" })
public interface CamelCatalogSpec {
RuntimeSpec getRuntime();
@Value.Default
@Value.NaturalOrder
default SortedMap<String, CamelArtifact> getArtifacts() {
return Collections.emptySortedMap();
}
@Value.Default
@Value.NaturalOrder
default SortedMap<String, CamelLoader> getLoaders() {
return Collections.emptySortedMap();
}
class Builder extends ImmutableCamelCatalogSpec.Builder {
public Builder putArtifact(CamelArtifact artifact) {
return putArtifact(artifact.getArtifactId(), artifact);
}
public Builder putArtifact(String groupId, String artifactId) {
return putArtifact(new CamelArtifact.Builder().groupId(groupId).artifactId(artifactId).build());
}
}
}
| 3,600 |
0 | Create_ds/camel-k-runtime/support/camel-k-catalog-model/src/main/java/org/apache/camel/k/catalog/model/k8s | Create_ds/camel-k-runtime/support/camel-k-catalog-model/src/main/java/org/apache/camel/k/catalog/model/k8s/crd/CamelCatalog.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.camel.k.catalog.model.k8s.crd;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.camel.k.catalog.model.k8s.ObjectMeta;
import org.immutables.value.Value;
@Value.Immutable
@JsonDeserialize(builder = CamelCatalog.Builder.class)
@JsonPropertyOrder({ "apiVersion", "kind", "metadata", "spec" })
public interface CamelCatalog {
@Value.Default
default String getApiVersion() {
return "camel.apache.org/v1";
}
@Value.Default
default String getKind() {
return "CamelCatalog";
}
ObjectMeta getMetadata();
CamelCatalogSpec getSpec();
class Builder extends ImmutableCamelCatalog.Builder {
}
}
| 3,601 |
0 | Create_ds/camel-k-runtime/.mvn | Create_ds/camel-k-runtime/.mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.2";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + " .jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| 3,602 |
0 | Create_ds/camel-k-runtime/camel-k-knative/impl/src/generated/java/org/apache/camel/k/knative | Create_ds/camel-k-runtime/camel-k-knative/impl/src/generated/java/org/apache/camel/k/knative/customizer/KnativeSinkBindingContextCustomizerConfigurer.java | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.k.knative.customizer;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.k.knative.customizer.KnativeSinkBindingContextCustomizer;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class KnativeSinkBindingContextCustomizerConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.k.knative.customizer.KnativeSinkBindingContextCustomizer target = (org.apache.camel.k.knative.customizer.KnativeSinkBindingContextCustomizer) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiversion":
case "ApiVersion": target.setApiVersion(property(camelContext, java.lang.String.class, value)); return true;
case "kind":
case "Kind": target.setKind(property(camelContext, java.lang.String.class, value)); return true;
case "name":
case "Name": target.setName(property(camelContext, java.lang.String.class, value)); return true;
case "type":
case "Type": target.setType(property(camelContext, org.apache.camel.component.knative.spi.Knative.Type.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiversion":
case "ApiVersion": return java.lang.String.class;
case "kind":
case "Kind": return java.lang.String.class;
case "name":
case "Name": return java.lang.String.class;
case "type":
case "Type": return org.apache.camel.component.knative.spi.Knative.Type.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.k.knative.customizer.KnativeSinkBindingContextCustomizer target = (org.apache.camel.k.knative.customizer.KnativeSinkBindingContextCustomizer) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiversion":
case "ApiVersion": return target.getApiVersion();
case "kind":
case "Kind": return target.getKind();
case "name":
case "Name": return target.getName();
case "type":
case "Type": return target.getType();
default: return null;
}
}
}
| 3,603 |
0 | Create_ds/camel-k-runtime/camel-k-knative/impl/src/main/java/org/apache/camel/k/knative | Create_ds/camel-k-runtime/camel-k-knative/impl/src/main/java/org/apache/camel/k/knative/customizer/KnativeSinkBindingContextCustomizer.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.camel.k.knative.customizer;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.camel.CamelContext;
import org.apache.camel.component.knative.spi.Knative;
import org.apache.camel.component.knative.spi.KnativeResource;
import org.apache.camel.k.ContextCustomizer;
import org.apache.camel.k.annotation.Customizer;
import org.apache.camel.spi.Configurer;
import org.apache.camel.util.ObjectHelper;
@Configurer
@Customizer("sinkbinding")
public class KnativeSinkBindingContextCustomizer implements ContextCustomizer {
private String name;
private Knative.Type type;
private String kind;
private String apiVersion;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Knative.Type getType() {
return type;
}
public void setType(Knative.Type type) {
this.type = type;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
@Override
public void apply(CamelContext camelContext) {
final String kSinkUrl = camelContext.resolvePropertyPlaceholders("{{k.sink:}}");
final String kCeOverride = camelContext.resolvePropertyPlaceholders("{{k.ce.overrides:}}");
if (ObjectHelper.isNotEmpty(kSinkUrl)) {
// create a synthetic service definition to target the K_SINK url
KnativeResource resource = new KnativeResource();
resource.setEndpointKind(Knative.EndpointKind.sink);
resource.setType(type);
resource.setName(name);
resource.setUrl(kSinkUrl);
resource.setObjectApiVersion(apiVersion);
resource.setObjectKind(kind);
if (type == Knative.Type.event) {
resource.setObjectName(name);
}
if (ObjectHelper.isNotEmpty(kCeOverride)) {
try (Reader reader = new StringReader(kCeOverride)) {
// assume K_CE_OVERRIDES is defined as simple key/val json
Knative.MAPPER.readValue(
reader,
new TypeReference<HashMap<String, String>>() {
}
).forEach(resource::addCeOverride);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
camelContext.getRegistry().bind(name, resource);
}
}
}
| 3,604 |
0 | Create_ds/camel-k-runtime/examples/java | Create_ds/camel-k-runtime/examples/java/data/MyRoutes.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.
*/
import org.apache.camel.builder.RouteBuilder;
public class MyRoutes extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:tick")
.to("log:info");
}
} | 3,605 |
0 | Create_ds/camel-k-runtime/examples/kafka-source-s3 | Create_ds/camel-k-runtime/examples/kafka-source-s3/data/MyRoutes.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.
*/
import org.apache.camel.builder.RouteBuilder;
public class MyRoutes extends RouteBuilder {
@Override
public void configure() throws Exception {
from("kafka:{{kafkatopic}}")
.setHeader("CamelAwsS3Key",simple("${date:now:yyyyMMdd-HHmmssSSS}-${exchangeId}"))
.to("aws2-s3:camel-kafka-connector");
}
}
| 3,606 |
0 | Create_ds/camel-k-runtime/camel-k-master/impl/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-master/impl/src/main/java/org/apache/camel/k/master/MasterContextCustomizer.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.camel.k.master;
import java.util.Collections;
import org.apache.camel.CamelContext;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.kubernetes.cluster.KubernetesClusterService;
import org.apache.camel.component.kubernetes.cluster.LeaseResourceType;
import org.apache.camel.k.ContextCustomizer;
import org.apache.camel.k.annotation.Customizer;
import org.apache.camel.support.cluster.RebalancingCamelClusterService;
import org.apache.camel.util.ObjectHelper;
@Customizer("master")
public class MasterContextCustomizer implements ContextCustomizer {
@Deprecated
private String configMapName;
private String kubernetesResourceName;
private LeaseResourceType leaseResourceType;
private Boolean rebalancing;
private String labelKey;
private String labelValue;
@Override
public void apply(CamelContext camelContext) {
try {
KubernetesClusterService clusterService = new KubernetesClusterService();
String resourceName = this.kubernetesResourceName;
if (ObjectHelper.isEmpty(resourceName)) {
resourceName = this.configMapName;
}
if (ObjectHelper.isNotEmpty(resourceName)) {
clusterService.setKubernetesResourceName(resourceName);
}
if (ObjectHelper.isNotEmpty(this.labelKey) && ObjectHelper.isNotEmpty(this.labelValue)) {
clusterService.setClusterLabels(Collections.singletonMap(this.labelKey, this.labelValue));
}
if (this.leaseResourceType != null) {
clusterService.setLeaseResourceType(this.leaseResourceType);
}
if (this.rebalancing == null || this.rebalancing) {
RebalancingCamelClusterService rebalancingService = new RebalancingCamelClusterService(clusterService, clusterService.getRenewDeadlineMillis());
camelContext.addService(rebalancingService);
} else {
camelContext.addService(clusterService);
}
} catch (Exception ex) {
throw new RuntimeCamelException(ex);
}
}
public String getKubernetesResourceName() {
return kubernetesResourceName;
}
public void setKubernetesResourceName(String kubernetesResourceName) {
this.kubernetesResourceName = kubernetesResourceName;
}
public LeaseResourceType getLeaseResourceType() {
return leaseResourceType;
}
public void setLeaseResourceType(LeaseResourceType leaseResourceType) {
this.leaseResourceType = leaseResourceType;
}
public Boolean getRebalancing() {
return rebalancing;
}
public void setRebalancing(Boolean rebalancing) {
this.rebalancing = rebalancing;
}
public String getConfigMapName() {
return configMapName;
}
public void setConfigMapName(String configMapName) {
this.configMapName = configMapName;
}
public String getLabelKey() {
return labelKey;
}
public void setLabelKey(String labelKey) {
this.labelKey = labelKey;
}
public String getLabelValue() {
return labelValue;
}
public void setLabelValue(String labelValue) {
this.labelValue = labelValue;
}
}
| 3,607 |
0 | Create_ds/camel-k-runtime/camel-k-master/deployment/src/main/java/org/apache/camel/k/quarkus/master | Create_ds/camel-k-runtime/camel-k-master/deployment/src/main/java/org/apache/camel/k/quarkus/master/deployment/MasterFeature.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.camel.k.quarkus.master.deployment;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.FeatureBuildItem;
public class MasterFeature {
private static final String FEATURE = "camel-k-master";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
}
| 3,608 |
0 | Create_ds/camel-k-runtime/camel-k-core/runtime/src/main/java/org/apache/camel/k/core/quarkus | Create_ds/camel-k-runtime/camel-k-core/runtime/src/main/java/org/apache/camel/k/core/quarkus/devmode/HotReplacementSetup.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.camel.k.core.quarkus.devmode;
public class HotReplacementSetup implements io.quarkus.dev.spi.HotReplacementSetup {
@Override
public void setupHotDeployment(io.quarkus.dev.spi.HotReplacementContext context) {
//TODO: TBD
}
}
| 3,609 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/generated/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/generated/java/org/apache/camel/k/listener/SourcesConfigurerConfigurer.java | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.k.listener;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.k.listener.SourcesConfigurer;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class SourcesConfigurerConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.k.listener.SourcesConfigurer target = (org.apache.camel.k.listener.SourcesConfigurer) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "sources":
case "Sources": target.setSources(property(camelContext, org.apache.camel.k.SourceDefinition[].class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "sources":
case "Sources": return org.apache.camel.k.SourceDefinition[].class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.k.listener.SourcesConfigurer target = (org.apache.camel.k.listener.SourcesConfigurer) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "sources":
case "Sources": return target.getSources();
default: return null;
}
}
}
| 3,610 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k/SourceTest.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.camel.k;
import org.apache.camel.k.support.Sources;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
public class SourceTest {
@Test
public void testResourceWithoutScheme() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(
() -> Sources.fromURI("routes.js")
);
}
@Test
public void testResourceWithIllegalScheme() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(
() -> Sources.fromURI("http:routes.js")
);
}
@Test
public void testUnsupportedLanguage() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(
() -> Sources.fromURI(" test")
);
}
@Test
public void sourceCanBeContructedFromLocation() {
SourceDefinition definition = new SourceDefinition();
definition.setLocation("classpath:MyRoutes.java");
assertThat(Sources.fromDefinition(definition))
.hasFieldOrPropertyWithValue("name", "MyRoutes")
.hasFieldOrPropertyWithValue("language", "java");
}
}
| 3,611 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k/listener/SourceConfigurerTest.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.camel.k.listener;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.k.SourceType;
import org.apache.camel.k.support.PropertiesSupport;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.camel.k.test.CamelKTestSupport.asProperties;
import static org.assertj.core.api.Assertions.assertThat;
public class SourceConfigurerTest {
@Test
public void shouldLoadMultipleSources() {
CamelContext context = new DefaultCamelContext();
context.getPropertiesComponent().setInitialProperties(asProperties(
"camel.k.sources[0].name", "templateName",
"camel.k.sources[0].location", "classpath:MyTemplate.java",
"camel.k.sources[0].type", "template",
"camel.k.sources[1].name", "src",
"camel.k.sources[1].location", "classpath:MySrc.java",
"camel.k.sources[2].name", "err",
"camel.k.sources[2].location", "classpath:Err.java",
"camel.k.sources[2].type", "errorHandler"
));
SourcesConfigurer configuration = new SourcesConfigurer();
PropertiesSupport.bindProperties(
context,
configuration,
k -> k.startsWith(SourcesConfigurer.CAMEL_K_SOURCES_PREFIX),
SourcesConfigurer.CAMEL_K_PREFIX);
assertThat(configuration.getSources()).hasSize(3);
}
@Test
public void shouldFailOnMultipleErrorHandlers() {
CamelContext context = new DefaultCamelContext();
context.getPropertiesComponent().setInitialProperties(asProperties(
"camel.k.sources[0].name", "templateName0",
"camel.k.sources[0].location", "classpath:MyTemplate1.java",
"camel.k.sources[0].type", "template",
"camel.k.sources[1].name", "err1",
"camel.k.sources[1].location", "classpath:Err1.java",
"camel.k.sources[1].type", "errorHandler",
"camel.k.sources[2].name", "err2",
"camel.k.sources[2].location", "classpath:Err2.java",
"camel.k.sources[2].type", "errorHandler"
));
SourcesConfigurer configuration = new SourcesConfigurer();
PropertiesSupport.bindProperties(
context,
configuration,
k -> k.startsWith(SourcesConfigurer.CAMEL_K_SOURCES_PREFIX),
SourcesConfigurer.CAMEL_K_PREFIX);
assertThat(configuration.getSources()).hasSize(3);
Assertions.assertThrows(IllegalArgumentException.class, () -> {
SourcesConfigurer.checkUniqueErrorHandler(configuration.getSources());
}, "java.lang.IllegalArgumentException: Expected only one error handler source type, got 2");
}
@Test
public void shouldDefaultSourcesWithEmptyType() {
CamelContext context = new DefaultCamelContext();
context.getPropertiesComponent().setInitialProperties(asProperties(
"camel.k.sources[0].name", "source0",
"camel.k.sources[1].name", "source1",
"camel.k.sources[2].name", "source2",
"camel.k.sources[2].type", "source"
));
SourcesConfigurer configuration = new SourcesConfigurer();
PropertiesSupport.bindProperties(
context,
configuration,
k -> k.startsWith(SourcesConfigurer.CAMEL_K_SOURCES_PREFIX),
SourcesConfigurer.CAMEL_K_PREFIX);
assertThat(configuration.getSources().length).isEqualTo(3);
assertThat(configuration.getSources()[0].getType()).isEqualTo(SourceType.source);
assertThat(configuration.getSources()[1].getType()).isEqualTo(SourceType.source);
assertThat(configuration.getSources()[2].getType()).isEqualTo(SourceType.source);
}
@Test
public void shouldOrderSourcesByType() {
CamelContext context = new DefaultCamelContext();
context.getPropertiesComponent().setInitialProperties(asProperties(
"camel.k.sources[0].name", "template1",
"camel.k.sources[0].type", "template",
"camel.k.sources[1].name", "source1",
"camel.k.sources[1].type", "source",
"camel.k.sources[2].name", "source2",
"camel.k.sources[3].name", "errorHandler1",
"camel.k.sources[3].type", "errorHandler"
));
SourcesConfigurer configuration = new SourcesConfigurer();
PropertiesSupport.bindProperties(
context,
configuration,
k -> k.startsWith(SourcesConfigurer.CAMEL_K_SOURCES_PREFIX),
SourcesConfigurer.CAMEL_K_PREFIX);
SourcesConfigurer.sortSources(configuration.getSources());
assertThat(configuration.getSources()).hasSize(4);
assertThat(configuration.getSources()[0].getName()).isEqualTo("errorHandler1");
assertThat(configuration.getSources()[0].getType()).isEqualTo(SourceType.errorHandler);
assertThat(configuration.getSources()[1].getName()).isEqualTo("template1");
assertThat(configuration.getSources()[1].getType()).isEqualTo(SourceType.template);
// Order for the same type does not matter
assertThat(configuration.getSources()[2].getName()).contains("source");
assertThat(configuration.getSources()[2].getType()).isEqualTo(SourceType.source);
assertThat(configuration.getSources()[3].getName()).contains("source");
assertThat(configuration.getSources()[3].getType()).isEqualTo(SourceType.source);
}
@Test
public void shouldNotFailOnEmptySources() {
SourcesConfigurer.sortSources(null);
SourcesConfigurer.checkUniqueErrorHandler(null);
}
}
| 3,612 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k/listener/PropertiesFunctionsConfigurerTest.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.camel.k.listener;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.k.Runtime;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PropertiesFunctionsConfigurerTest {
@Test
public void testKubernetesFunction() {
Runtime runtime = Runtime.on(new DefaultCamelContext());
runtime.setProperties("my.property", "{{secret:my-secret/my-property}}");
assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{secret:my-secret/my-property}}"))
.isEqualTo("my-secret-property");
assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{secret:none/my-property:my-default-secret}}"))
.isEqualTo("my-default-secret");
CamelContext context = runtime.getCamelContext();
assertThatThrownBy(() -> context.resolvePropertyPlaceholders("{{secret:none/my-property}}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("returned null value which is not allowed, from input");
assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{configmap:my-cm/my-property}}")).isEqualTo("my-cm-property");
assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{configmap:my-cm/my-property:my-default-cm}}"))
.isEqualTo("my-default-cm");
assertThatThrownBy(() -> context.resolvePropertyPlaceholders("{{configmap:none/my-property}}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("returned null value which is not allowed, from input");
assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{my.property}}")).isEqualTo("my-secret-property");
}
}
| 3,613 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k/support/PropertiesSupportTest.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.camel.k.support;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.k.SourceDefinition;
import org.apache.camel.k.listener.SourcesConfigurer;
import org.junit.jupiter.api.Test;
import static org.apache.camel.k.test.CamelKTestSupport.asProperties;
import static org.assertj.core.api.Assertions.assertThat;
public class PropertiesSupportTest {
@Test
public void propertiesAreBoundToSourcesConfigurer() {
CamelContext context = new DefaultCamelContext();
context.getPropertiesComponent().setInitialProperties(asProperties(
"camel.k.sources[0].name", "MyRoutesWithBeans",
"camel.k.sources[0].location", "classpath:MyRoutesWithBeans.java",
"camel.k.sources[1].name", "MyRoutesConfig",
"camel.k.sources[1].location", "classpath:MyRoutesConfig.java",
"camel.k.sources[1].property-names[0]", "foo",
"camel.k.sources[1].property-names[1]", "bar"
));
SourcesConfigurer configuration = new SourcesConfigurer();
PropertiesSupport.bindProperties(
context,
configuration,
k -> k.startsWith(SourcesConfigurer.CAMEL_K_SOURCES_PREFIX),
SourcesConfigurer.CAMEL_K_PREFIX);
assertThat(configuration.getSources())
.hasSize(2)
.anyMatch(byNameAndLocation("MyRoutesWithBeans", "classpath:MyRoutesWithBeans.java")
.and(d -> d.getPropertyNames() == null))
.anyMatch(byNameAndLocation("MyRoutesConfig", "classpath:MyRoutesConfig.java")
.and(d -> d.getPropertyNames() != null && d.getPropertyNames().containsAll(List.of("foo", "bar"))));
}
@Test
public void propertiesWithGapsAreBoundToSourcesConfigurer() {
CamelContext context = new DefaultCamelContext();
context.getPropertiesComponent().setInitialProperties(asProperties(
"camel.k.sources[0].name", "MyRoutesWithBeans",
"camel.k.sources[0].location", "classpath:MyRoutesWithBeans.java",
"camel.k.sources[2].name", "MyRoutesConfig",
"camel.k.sources[2].location", "classpath:MyRoutesConfig.java"
));
SourcesConfigurer configuration = new SourcesConfigurer();
PropertiesSupport.bindProperties(
context,
configuration,
k -> k.startsWith(SourcesConfigurer.CAMEL_K_SOURCES_PREFIX),
SourcesConfigurer.CAMEL_K_PREFIX);
assertThat(configuration.getSources())
.hasSize(3)
.filteredOn(Objects::nonNull)
.hasSize(2)
.anyMatch(byNameAndLocation("MyRoutesWithBeans", "classpath:MyRoutesWithBeans.java"))
.anyMatch(byNameAndLocation("MyRoutesConfig", "classpath:MyRoutesConfig.java"));
}
// ***************************
//
// Helpers
//
// ***************************
private static Predicate<SourceDefinition> byNameAndLocation(String name, String location) {
return def -> Objects.equals(def.getName(), name) && Objects.equals(def.getLocation(), location);
}
}
| 3,614 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k/support/NameCustomizer.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.camel.k.support;
import org.apache.camel.CamelContext;
import org.apache.camel.Ordered;
import org.apache.camel.impl.engine.ExplicitCamelContextNameStrategy;
import org.apache.camel.k.ContextCustomizer;
import org.apache.camel.model.ModelCamelContext;
public final class NameCustomizer implements ContextCustomizer {
private String name;
public NameCustomizer() {
this("default");
}
public NameCustomizer(String name) {
this.name = name;
}
@Override
public int getOrder() {
return Ordered.HIGHEST;
}
@Override
public void apply(CamelContext camelContexty) {
camelContexty.setNameStrategy(new ExplicitCamelContextNameStrategy(name));
}
}
| 3,615 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/test/java/org/apache/camel/k/support/RuntimeSupportTest.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.camel.k.support;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.Ordered;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.engine.ExplicitCamelContextNameStrategy;
import org.apache.camel.k.ContextCustomizer;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RuntimeSupportTest {
@Test
public void testLoadCustomizersWithPropertiesFlags() {
CamelContext context = new DefaultCamelContext();
NameCustomizer customizer = new NameCustomizer("from-registry");
context.getRegistry().bind("name", customizer);
List<ContextCustomizer> customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isNotEqualTo("from-registry");
assertThat(context.getName()).isNotEqualTo("default");
assertThat(customizers).isEmpty();
Properties properties = new Properties();
properties.setProperty("camel.k.customizer.name.enabled", "true");
context.getPropertiesComponent().setInitialProperties(properties);
customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isEqualTo("from-registry");
assertThat(customizers).hasSize(1);
}
@Test
public void testLoadCustomizersWithList() {
CamelContext context = new DefaultCamelContext();
NameCustomizer customizer = new NameCustomizer("from-registry");
context.getRegistry().bind("name", customizer);
List<ContextCustomizer> customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isNotEqualTo("from-registry");
assertThat(context.getName()).isNotEqualTo("default");
assertThat(customizers).isEmpty();
Properties properties = new Properties();
properties.setProperty(Constants.PROPERTY_CAMEL_K_CUSTOMIZER, "name");
context.getPropertiesComponent().setInitialProperties(properties);
customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isEqualTo("from-registry");
assertThat(customizers).hasSize(1);
}
@Test
public void testLoadCustomizers() {
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("converters", (ContextCustomizer)camelContext -> camelContext.setLoadTypeConverters(true));
List<ContextCustomizer> customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isNotEqualTo("from-registry");
assertThat(context.getName()).isNotEqualTo("default");
assertThat(context.isLoadTypeConverters()).isFalse();
assertThat(customizers).isEmpty();
Properties properties = new Properties();
properties.setProperty("camel.k.customizer.name.enabled", "true");
context.getPropertiesComponent().setInitialProperties(properties);
customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isEqualTo("default");
assertThat(customizers).hasSize(1);
properties.setProperty("camel.k.customizer.converters.enabled", "true");
context.getPropertiesComponent().setInitialProperties(properties);
customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isEqualTo("default");
assertThat(context.isLoadTypeConverters()).isTrue();
assertThat(customizers).hasSize(2);
}
@Test
public void testLoadCustomizersFallback() {
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("converters", (ContextCustomizer)camelContext -> camelContext.setLoadTypeConverters(true));
List<ContextCustomizer> customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isNotEqualTo("from-registry");
assertThat(context.getName()).isNotEqualTo("default");
assertThat(context.isLoadTypeConverters()).isFalse();
assertThat(customizers).isEmpty();
Properties properties = new Properties();
properties.setProperty("customizer.name.enabled", "true");
context.getPropertiesComponent().setInitialProperties(properties);
customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isEqualTo("default");
assertThat(customizers).hasSize(1);
properties.setProperty("customizer.converters.enabled", "true");
properties.setProperty("customizer.converters.enabled", "true");
context.getPropertiesComponent().setInitialProperties(properties);
customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(context.getName()).isEqualTo("default");
assertThat(context.isLoadTypeConverters()).isTrue();
assertThat(customizers).hasSize(2);
}
@Test
public void testLoadCustomizerOrder() {
DefaultCamelContext context = new DefaultCamelContext();
context.setName("camel");
context.getRegistry().bind("c1", new ContextCustomizer() {
@Override
public int getOrder() {
return Ordered.LOWEST;
}
@Override
public void apply(CamelContext camelContext) {
camelContext.setNameStrategy(new ExplicitCamelContextNameStrategy(camelContext.getName() + "-c1"));
}
});
context.getRegistry().bind("c2", new ContextCustomizer() {
@Override
public int getOrder() {
return Ordered.HIGHEST;
}
@Override
public void apply(CamelContext camelContext) {
camelContext.setNameStrategy(new ExplicitCamelContextNameStrategy(camelContext.getName() + "-c2"));
}
});
context.getRegistry().bind("c3", new ContextCustomizer() {
@Override
public void apply(CamelContext camelContext) {
camelContext.setNameStrategy(new ExplicitCamelContextNameStrategy(camelContext.getName() + "-c3"));
}
});
Properties properties = new Properties();
properties.setProperty("camel.k.customizer.c1.enabled", "true");
properties.setProperty("camel.k.customizer.c2.enabled", "true");
properties.setProperty("camel.k.customizer.c3.enabled", "true");
context.getPropertiesComponent().setInitialProperties(properties);
List<ContextCustomizer> customizers = RuntimeSupport.configureContextCustomizers(context);
assertThat(customizers).hasSize(3);
assertThat(context.getName()).isEqualTo("camel-c2-c3-c1");
}
@Test
public void shouldLoadUsePropertiesFromTextConfigMap(){
System.setProperty(Constants.PROPERTY_CAMEL_K_CONF_D, getClass().getResource("/configmaps/my-cm").getFile());
Map<String, String> loadedProperties = RuntimeSupport.loadUserProperties();
assertThat(loadedProperties).hasSize(1);
assertThat(loadedProperties.get("my-property")).isEqualTo("my-cm-property");
}
@Test
public void shouldSkipLoadUsePropertiesFromBinaryConfigMap(){
System.setProperty(Constants.PROPERTY_CAMEL_K_CONF_D, getClass().getResource("/configmaps/my-binary-cm").getFile());
Map<String, String> loadedProperties = RuntimeSupport.loadUserProperties();
assertThat(loadedProperties).isEmpty();
}
}
| 3,616 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/listener/ContextConfigurer.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.camel.k.listener;
import org.apache.camel.k.Runtime;
import org.apache.camel.k.support.RuntimeSupport;
public class ContextConfigurer extends AbstractPhaseListener {
public ContextConfigurer() {
super(Runtime.Phase.ConfigureContext);
}
@Override
protected void accept(Runtime runtime) {
//
// Programmatically configure the camel context.
//
// This is useful to configure services such as the ClusterService,
// RouteController, etc
//
RuntimeSupport.configureContextCustomizers(runtime.getCamelContext());
}
}
| 3,617 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/listener/AbstractPhaseListener.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.camel.k.listener;
import org.apache.camel.k.Runtime;
public abstract class AbstractPhaseListener implements Runtime.Listener {
private final Runtime.Phase phase;
protected AbstractPhaseListener(Runtime.Phase phase) {
this.phase = phase;
}
@Override
public boolean accept(Runtime.Phase phase, Runtime runtime) {
boolean run = this.phase == phase;
if (run) {
accept(runtime);
}
return run;
}
protected abstract void accept(Runtime runtime);
}
| 3,618 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/listener/SourcesConfigurer.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.camel.k.listener;
import java.util.Arrays;
import java.util.Comparator;
import org.apache.camel.k.Runtime;
import org.apache.camel.k.SourceDefinition;
import org.apache.camel.k.SourceType;
import org.apache.camel.k.support.Constants;
import org.apache.camel.k.support.PropertiesSupport;
import org.apache.camel.k.support.SourcesSupport;
import org.apache.camel.spi.Configurer;
import org.apache.camel.util.ObjectHelper;
@Configurer
public class SourcesConfigurer extends AbstractPhaseListener {
public static final String CAMEL_K_PREFIX = "camel.k.";
public static final String CAMEL_K_SOURCES_PREFIX = "camel.k.sources[";
private SourceDefinition[] sources;
public SourcesConfigurer() {
super(Runtime.Phase.ConfigureRoutes);
}
public SourceDefinition[] getSources() {
return sources;
}
public void setSources(SourceDefinition[] sources) {
this.sources = sources;
}
@Override
protected void accept(Runtime runtime) {
//
// load routes from env var for backward compatibility
//
String routes = System.getProperty(Constants.PROPERTY_CAMEL_K_ROUTES);
if (ObjectHelper.isEmpty(routes)) {
routes = System.getenv(Constants.ENV_CAMEL_K_ROUTES);
}
if (ObjectHelper.isNotEmpty(routes)) {
SourcesSupport.loadSources(runtime, routes.split(","));
}
//
// load routes from properties
//
// In order not to load any unwanted property, the filer remove any
// property that can't be bound to this configurer.
//
PropertiesSupport.bindProperties(
runtime.getCamelContext(),
this,
k -> k.startsWith(CAMEL_K_SOURCES_PREFIX),
CAMEL_K_PREFIX);
checkUniqueErrorHandler();
sortSources();
if (ObjectHelper.isNotEmpty(this.getSources())) {
SourcesSupport.loadSources(runtime, this.getSources());
}
}
private void checkUniqueErrorHandler() {
checkUniqueErrorHandler(this.sources);
}
static void checkUniqueErrorHandler(SourceDefinition[] sources) {
long errorHandlers = sources == null ? 0 : Arrays.stream(sources).filter(s -> s.getType() == SourceType.errorHandler).count();
if (errorHandlers > 1) {
throw new IllegalArgumentException("Expected only one error handler source type, got " + errorHandlers);
}
}
private void sortSources() {
sortSources(this.getSources());
}
static void sortSources(SourceDefinition[] sources) {
if (sources == null) {
return;
}
// We must ensure the source order as defined in SourceType enum
Arrays.sort(sources, Comparator.comparingInt(a -> a.getType().ordinal()));
}
}
| 3,619 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/SourcesSupport.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.camel.k.support;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import org.apache.camel.ErrorHandlerFactory;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.RouteBuilderLifecycleStrategy;
import org.apache.camel.k.Runtime;
import org.apache.camel.k.RuntimeAware;
import org.apache.camel.k.Source;
import org.apache.camel.k.SourceDefinition;
import org.apache.camel.k.listener.AbstractPhaseListener;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.RouteTemplateDefinition;
import org.apache.camel.spi.Resource;
import org.apache.camel.support.PluginHelper;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class SourcesSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(SourcesSupport.class);
private SourcesSupport() {
}
public static Runtime.Listener forRoutes(String... sources) {
return new AbstractPhaseListener(Runtime.Phase.ConfigureRoutes) {
@Override
protected void accept(Runtime runtime) {
loadSources(runtime, sources);
}
};
}
public static Runtime.Listener forRoutes(SourceDefinition... definitions) {
return new AbstractPhaseListener(Runtime.Phase.ConfigureRoutes) {
@Override
protected void accept(Runtime runtime) {
loadSources(runtime, definitions);
}
};
}
public static void loadSources(Runtime runtime, String... routes) {
for (String route : routes) {
if (ObjectHelper.isEmpty(route)) {
continue;
}
LOGGER.info("Loading routes from: {}", route);
try {
load(runtime, Sources.fromURI(route));
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
}
public static void loadSources(Runtime runtime, SourceDefinition... definitions) {
for (SourceDefinition definition : definitions) {
LOGGER.info("Loading routes from: {}", definition);
load(runtime, Sources.fromDefinition(definition));
}
}
public static void load(Runtime runtime, Source source) {
final List<RouteBuilderLifecycleStrategy> interceptors;
switch (source.getType()) {
case source:
interceptors = RuntimeSupport.loadInterceptors(runtime.getCamelContext(), source);
interceptors.forEach(interceptor -> {
if (interceptor instanceof RuntimeAware) {
((RuntimeAware) interceptor).setRuntime(runtime);
}
});
break;
case template:
if (!source.getInterceptors().isEmpty()) {
LOGGER.warn("Interceptors associated to the route template {} will be ignored", source.getName());
}
interceptors = List.of(new RouteBuilderLifecycleStrategy() {
@Override
public void afterConfigure(RouteBuilder builder) {
List<RouteDefinition> routes = builder.getRouteCollection().getRoutes();
List<RouteTemplateDefinition> templates = builder.getRouteTemplateCollection().getRouteTemplates();
if (routes.size() != 1) {
throw new IllegalArgumentException(
"There should be a single route definition when configuring route templates, got " + routes.size());
}
if (!templates.isEmpty()) {
throw new IllegalArgumentException(
"There should not be any template definition when configuring route templates, got " + templates.size());
}
// create a new template from the source
RouteTemplateDefinition templatesDefinition = builder.getRouteTemplateCollection().routeTemplate(source.getId());
templatesDefinition.setRoute(routes.get(0));
source.getPropertyNames().forEach(templatesDefinition::templateParameter);
// remove all routes definitions as they have been translated
// in the related route template
routes.clear();
}
});
break;
case errorHandler:
if (!source.getInterceptors().isEmpty()) {
LOGGER.warn("Interceptors associated to the error handler {} will be ignored", source.getName());
}
interceptors = List.of(new RouteBuilderLifecycleStrategy() {
@Override
public void afterConfigure(RouteBuilder builder) {
List<RouteDefinition> routes = builder.getRouteCollection().getRoutes();
List<RouteTemplateDefinition> templates = builder.getRouteTemplateCollection().getRouteTemplates();
if (!routes.isEmpty()) {
throw new IllegalArgumentException(
"There should be no route definition when configuring error handler, got " + routes.size());
}
if (!templates.isEmpty()) {
throw new IllegalArgumentException(
"There should not be any template definition when configuring error handler, got " + templates.size());
}
if (hasErrorHandlerFactory(builder)){
LOGGER.debug("Setting default error handler builder factory as type {}", builder.getErrorHandlerFactory().getClass());
runtime.getExtendedCamelContext().setErrorHandlerFactory(builder.getErrorHandlerFactory());
}
}
});
break;
default:
throw new IllegalArgumentException("Unknown source type: " + source.getType());
}
try {
final Resource resource = Sources.asResource(runtime.getCamelContext(), source);
final ExtendedCamelContext ecc = runtime.getExtendedCamelContext();
final Collection<RoutesBuilder> builders = PluginHelper.getRoutesLoader(ecc).findRoutesBuilders(resource);
builders.stream()
.map(RouteBuilder.class::cast)
.peek(b -> interceptors.forEach(b::addLifecycleInterceptor))
.forEach(runtime::addRoutes);
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
static boolean hasErrorHandlerFactory(RouteBuilder builder) {
//return builder.hasErrorHandlerFactory();
// TODO We need to replace the following workaround with the statement above once we switch to > camel-3.18
try {
Field f = RouteBuilder.class.getSuperclass().getDeclaredField("errorHandlerFactory");
f.setAccessible(true);
ErrorHandlerFactory privateErrorHandlerFactory = (ErrorHandlerFactory) f.get(builder);
LOGGER.debug("Looking up for private error handler factory: {}", privateErrorHandlerFactory);
return privateErrorHandlerFactory != null;
} catch (Exception e) {
throw new IllegalArgumentException("Something went wrong while checking the error handler factory", e);
}
}
public static void loadErrorHandlerSource(Runtime runtime, SourceDefinition errorHandlerSourceDefinition) {
LOGGER.info("Loading error handler from: {}", errorHandlerSourceDefinition);
load(runtime, Sources.fromDefinition(errorHandlerSourceDefinition));
}
}
| 3,620 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/StringSupport.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.camel.k.support;
import java.util.Collections;
import java.util.List;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.StringHelper;
public final class StringSupport {
private StringSupport() {
}
public static String substringBefore(String str, String separator) {
String answer = StringHelper.before(str, separator);
if (answer == null) {
answer = str;
}
return answer;
}
public static String substringAfter(String str, String separator) {
String answer = StringHelper.after(str, separator);
if (answer == null) {
answer = "";
}
return answer;
}
public static String substringAfterLast(String str, String separator) {
if (ObjectHelper.isEmpty(str)) {
return str;
}
if (ObjectHelper.isEmpty(separator)) {
return "";
}
int pos = str.lastIndexOf(separator);
if (pos == -1 || pos == str.length() - separator.length()) {
return "";
}
return str.substring(pos + separator.length());
}
public static String substringBeforeLast(String str, String separator) {
if (ObjectHelper.isEmpty(str) || ObjectHelper.isEmpty(separator)) {
return str;
}
int pos = str.lastIndexOf(separator);
if (pos == -1) {
return str;
}
return str.substring(0, pos);
}
public static List<String> split(String input, String regex) {
return input != null ? List.of(input.split(regex)) : Collections.emptyList();
}
}
| 3,621 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/RouteBuilders.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.camel.k.support;
import java.io.Reader;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.endpoint.EndpointRouteBuilder;
import org.apache.camel.k.Source;
import org.apache.camel.util.function.ThrowingBiConsumer;
import org.apache.camel.util.function.ThrowingConsumer;
public final class RouteBuilders {
private RouteBuilders() {
}
public static EndpointRouteBuilder endpoint(Source source, ThrowingBiConsumer<Reader, EndpointRouteBuilder, Exception> consumer) {
return new EndpointRouteBuilder() {
@Override
public void configure() throws Exception {
try (Reader reader = source.resolveAsReader(getContext())) {
consumer.accept(reader, this);
}
}
};
}
public static EndpointRouteBuilder endpoint(ThrowingConsumer<EndpointRouteBuilder, Exception> consumer) {
return new EndpointRouteBuilder() {
@Override
public void configure() throws Exception {
consumer.accept(this);
}
};
}
public static RoutesBuilder route(Source source, ThrowingBiConsumer<Reader, RouteBuilder, Exception> consumer) {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
try (Reader reader = source.resolveAsReader(getContext())) {
consumer.accept(reader, this);
}
}
};
}
public static RoutesBuilder route(ThrowingConsumer<RouteBuilder, Exception> consumer) {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
consumer.accept(this);
}
};
}
}
| 3,622 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/DelegatingRuntime.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.camel.k.support;
import java.util.Map;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.k.Runtime;
import org.apache.camel.spi.Registry;
public class DelegatingRuntime implements Runtime {
private final Runtime runtime;
public DelegatingRuntime(Runtime runtime) {
this.runtime = runtime;
}
@Override
public ExtendedCamelContext getExtendedCamelContext() {
return runtime.getExtendedCamelContext();
}
@Override
public Registry getRegistry() {
return runtime.getRegistry();
}
@Override
public void setProperties(Properties properties) {
runtime.setProperties(properties);
}
@Override
public void setProperties(Map<String, String> properties) {
runtime.setProperties(properties);
}
@Override
public void setProperties(String key, String value, String... keyVals) {
runtime.setProperties(key, value, keyVals);
}
@Override
public void addRoutes(RoutesBuilder builder) {
runtime.addRoutes(builder);
}
@Override
public void stop() throws Exception {
runtime.stop();
}
@Override
public void close() throws Exception {
runtime.close();
}
@Override
public CamelContext getCamelContext() {
return runtime.getCamelContext();
}
}
| 3,623 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/PropertiesSupport.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.camel.k.support;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.function.Predicate;
import org.apache.camel.CamelContext;
import org.apache.camel.Component;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.spi.PropertiesComponent;
import org.apache.camel.spi.PropertyConfigurer;
import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.PropertyBindingSupport;
import org.apache.camel.support.service.ServiceHelper;
public final class PropertiesSupport {
private PropertiesSupport() {
}
public static <T> T bindProperties(CamelContext context, T target, String prefix) {
return bindProperties(context, target, prefix, false);
}
public static <T> T bindProperties(CamelContext context, T target, String prefix, boolean stripPrefix) {
return bindProperties(context, target, k -> k.startsWith(prefix), prefix, stripPrefix);
}
public static <T> T bindProperties(CamelContext context, T target, Predicate<String> filter, String prefix) {
return bindProperties(context, target, filter, prefix, false);
}
public static <T> T bindProperties(CamelContext context, T target, Predicate<String> filter, String prefix, boolean stripPrefix) {
final PropertiesComponent component = context.getPropertiesComponent();
final Properties propertiesWithPrefix = component.loadProperties(filter);
final Map<String, Object> properties = new HashMap<>();
propertiesWithPrefix.stringPropertyNames().forEach(
name -> properties.put(
stripPrefix ? name.substring(prefix.length()) : name,
propertiesWithPrefix.getProperty(name))
);
PropertyConfigurer configurer = null;
if (target instanceof Component) {
// the component needs to be initialized to have the configurer ready
ServiceHelper.initService(target);
configurer = ((Component) target).getComponentPropertyConfigurer();
}
if (configurer == null) {
String name = target.getClass().getName();
if (target instanceof ExtendedCamelContext) {
// special for camel context itself as we have an extended configurer
name = ExtendedCamelContext.class.getName();
}
// see if there is a configurer for it
configurer = PluginHelper.getConfigurerResolver(context.getCamelContextExtension()).resolvePropertyConfigurer(name, context);
}
PropertyBindingSupport.build()
.withIgnoreCase(true)
.withCamelContext(context)
.withTarget(target)
.withProperties(properties)
.withRemoveParameters(true)
.withOptionPrefix(stripPrefix ? null : prefix)
.withConfigurer(configurer)
.bind();
return target;
}
}
| 3,624 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/RuntimeSupport.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.camel.k.support;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.builder.RouteBuilderLifecycleStrategy;
import org.apache.camel.k.ContextCustomizer;
import org.apache.camel.k.Source;
import org.apache.camel.spi.HasCamelContext;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class RuntimeSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(RuntimeSupport.class);
private RuntimeSupport() {
}
// *********************************
//
// Helpers - Customizers
//
// *********************************
public static List<ContextCustomizer> configureContextCustomizers(HasCamelContext hasCamelContext) {
return configureContextCustomizers(hasCamelContext.getCamelContext());
}
public static List<ContextCustomizer> configureContextCustomizers(CamelContext context) {
List<ContextCustomizer> appliedCustomizers = new ArrayList<>();
Map<String, ContextCustomizer> customizers = lookupCustomizers(context);
customizers.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(e -> {
LOGGER.debug("Apply ContextCustomizer with id={} and type={}", e.getKey(), e.getValue().getClass().getName());
PropertiesSupport.bindProperties(context, e.getValue(), Constants.CUSTOMIZER_PREFIX + e.getKey() + ".");
PropertiesSupport.bindProperties(context, e.getValue(), Constants.CUSTOMIZER_PREFIX_FALLBACK + e.getKey() + ".");
e.getValue().apply(context);
appliedCustomizers.add(e.getValue());
});
return appliedCustomizers;
}
public static Map<String, ContextCustomizer> lookupCustomizers(CamelContext context) {
Map<String, ContextCustomizer> customizers = new ConcurrentHashMap<>();
Properties properties = context.getPropertiesComponent().loadProperties(n -> n.startsWith(Constants.CUSTOMIZER_PREFIX) || n.startsWith(Constants.CUSTOMIZER_PREFIX_FALLBACK));
if (properties != null) {
//
// Lookup customizers listed in Constants.ENV_CAMEL_K_CUSTOMIZERS or Constants.PROPERTY_CAMEL_K_CUSTOMIZER
// for backward compatibility
//
for (String customizerId: lookupCustomizerIDs(context)) {
customizers.computeIfAbsent(customizerId, id -> lookupCustomizerByID(context, id));
}
Pattern pattern = Pattern.compile(Constants.ENABLE_CUSTOMIZER_PATTERN);
properties.entrySet().stream()
.filter(entry -> entry.getKey() instanceof String)
.filter(entry -> entry.getValue() != null)
.forEach(entry -> {
final String key = (String)entry.getKey();
final Object val = entry.getValue();
final Matcher matcher = pattern.matcher(key);
if (matcher.matches()) {
String customizerId = null;
if (matcher.groupCount() == 1) {
customizerId = matcher.group(1);
} else if (matcher.groupCount() == 2) {
customizerId = matcher.group(2);
}
if (customizerId != null && Boolean.parseBoolean(String.valueOf(val))) {
//
// Do not override customizers eventually found
// in the registry
//
customizers.computeIfAbsent(customizerId, id -> lookupCustomizerByID(context, id));
}
}
});
}
return customizers;
}
public static ContextCustomizer lookupCustomizerByID(CamelContext context, String customizerId) {
ContextCustomizer customizer = context.getRegistry().lookupByNameAndType(customizerId, ContextCustomizer.class);
if (customizer == null) {
customizer = context.getCamelContextExtension()
.getFactoryFinder(Constants.CONTEXT_CUSTOMIZER_RESOURCE_PATH)
.newInstance(customizerId, ContextCustomizer.class)
.orElseThrow(() -> new RuntimeException("Error creating instance for customizer: " + customizerId));
LOGGER.debug("Found customizer {} with id {} from service definition", customizer, customizerId);
} else {
LOGGER.debug("Found customizer {} with id {} from the registry", customizer, customizerId);
}
return customizer;
}
public static Set<String> lookupCustomizerIDs(CamelContext context) {
Set<String> customizers = new TreeSet<>();
String customizerIDs = System.getenv().getOrDefault(Constants.ENV_CAMEL_K_CUSTOMIZERS, "");
if (ObjectHelper.isEmpty(customizerIDs)) {
// TODO: getPropertiesComponent().resolveProperty() throws exception instead
// of returning abd empty optional
customizerIDs = context.getPropertiesComponent()
.loadProperties(Constants.PROPERTY_CAMEL_K_CUSTOMIZER::equals)
.getProperty(Constants.PROPERTY_CAMEL_K_CUSTOMIZER, "");
}
if (ObjectHelper.isNotEmpty(customizerIDs)) {
for (String customizerId : customizerIDs.split(",", -1)) {
customizers.add(customizerId);
}
}
return customizers;
}
// *********************************
//
// Helpers - Interceptors
//
// *********************************
public static List<RouteBuilderLifecycleStrategy> loadInterceptors(CamelContext context, Source source) {
ExtendedCamelContext ecc = context.getCamelContextExtension();
List<RouteBuilderLifecycleStrategy> answer = new ArrayList<>();
for (String id : source.getInterceptors()) {
try {
// first check the registry
RouteBuilderLifecycleStrategy interceptor = ecc.getRegistry()
.lookupByNameAndType(id, RouteBuilderLifecycleStrategy.class);
if (interceptor == null) {
// then try with factory finder
interceptor = ecc.getFactoryFinder(Constants.SOURCE_LOADER_INTERCEPTOR_RESOURCE_PATH)
.newInstance(id, RouteBuilderLifecycleStrategy.class)
.orElseThrow(() -> new IllegalArgumentException("Unable to find source loader interceptor for: " + id));
LOGGER.debug("Found source loader interceptor {} from service definition", id);
} else {
LOGGER.debug("Found source loader interceptor {} from registry", id);
}
PropertiesSupport.bindProperties(context, interceptor, Constants.LOADER_INTERCEPTOR_PREFIX + id + ".");
PropertiesSupport.bindProperties(context, interceptor, Constants.LOADER_INTERCEPTOR_PREFIX_FALLBACK + id + ".");
answer.add(interceptor);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to find source loader interceptor for: " + id, e);
}
}
return answer;
}
// *********************************
//
// Helpers - Misc
//
// *********************************
public static String getRuntimeVersion() {
String version = null;
InputStream is = null;
// try to load from maven properties first
try {
Properties p = new Properties();
is = RuntimeSupport.class.getResourceAsStream("/META-INF/maven/org.apache.camel.k/camel-k-runtime-core/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
} finally {
if (is != null) {
IOHelper.close(is);
}
}
// fallback to using Java API
if (version == null) {
Package aPackage = RuntimeSupport.class.getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return Objects.requireNonNull(version, "Could not determine Camel K Runtime version");
}
// *********************************
//
// Properties
//
// *********************************
public static Map<String, String> loadApplicationProperties() {
final String conf = System.getProperty(Constants.PROPERTY_CAMEL_K_CONF, System.getenv(Constants.ENV_CAMEL_K_CONF));
final Map<String, String> properties = new HashMap<>();
if (ObjectHelper.isEmpty(conf)) {
return properties;
}
try {
Path confPath = Paths.get(conf);
if (Files.exists(confPath) && !Files.isDirectory(confPath)) {
try (Reader reader = Files.newBufferedReader(confPath)) {
Properties p = new Properties();
p.load(reader);
p.forEach((key, value) -> properties.put(String.valueOf(key), String.valueOf(value)));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return properties;
}
public static Map<String, String> loadUserProperties() {
final String conf = System.getProperty(Constants.PROPERTY_CAMEL_K_CONF_D, System.getenv(Constants.ENV_CAMEL_K_CONF_D));
final Map<String, String> properties = new HashMap<>();
if (ObjectHelper.isEmpty(conf)) {
return properties;
}
FileVisitor<Path> visitor = new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Objects.requireNonNull(file);
Objects.requireNonNull(attrs);
if (Files.isDirectory(file) || Files.isSymbolicLink(file)) {
return FileVisitResult.CONTINUE;
}
if (file.toFile().getAbsolutePath().endsWith(".properties")) {
try (Reader reader = Files.newBufferedReader(file)) {
Properties p = new Properties();
p.load(reader);
p.forEach((key, value) -> properties.put(String.valueOf(key), String.valueOf(value)));
}
} else {
try {
properties.put(
file.getFileName().toString(),
Files.readString(file, StandardCharsets.UTF_8));
} catch (MalformedInputException mie){
// Just skip if it is not a UTF-8 encoded file (ie a binary)
LOGGER.info("Cannot transform {} into UTF-8 text, skipping.", file);
}
}
return FileVisitResult.CONTINUE;
}
};
Path root = Paths.get(conf);
if (Files.exists(root)) {
try {
Files.walkFileTree(root, visitor);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return properties;
}
}
| 3,625 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/Sources.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.camel.k.support;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import org.apache.camel.CamelContext;
import org.apache.camel.k.Source;
import org.apache.camel.k.SourceDefinition;
import org.apache.camel.k.SourceType;
import org.apache.camel.spi.Resource;
import org.apache.camel.support.ResourceHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
public final class Sources {
private Sources() {
}
public static Source fromURI(String uri) throws Exception {
return fromDefinition(computeDefinitionFromURI(uri));
}
public static SourceDefinition fromBytes(String id, String name, String language, String loader, List<String> interceptors, byte[] content) {
SourceDefinition answer = new SourceDefinition();
answer.setId(id);
answer.setName(name);
answer.setLanguage(language);
answer.setLoader(loader);
answer.setInterceptors(interceptors != null ? interceptors : Collections.emptyList());
answer.setContent(content);
return answer;
}
public static Source fromBytes(String name, String language, String loader, List<String> interceptors, byte[] content) {
return fromDefinition(fromBytes(null, name, language, loader, interceptors, content));
}
public static Source fromBytes(String name, String language, String loader, byte[] content) {
return fromDefinition(fromBytes(null, name, language, loader, null, content));
}
public static Source fromBytes(String language, byte[] content) {
return fromDefinition(fromBytes(null, UUID.randomUUID().toString(), language, null, null, content));
}
public static Source fromDefinition(SourceDefinition definition) {
if (definition.getLocation() == null && definition.getContent() == null) {
throw new IllegalArgumentException("Either the source location or the source content should be set");
}
return new Source() {
@Override
public String getLocation() {
return definition.getLocation();
}
@Override
public String getId() {
return ObjectHelper.supplyIfEmpty(definition.getId(), this::getName);
}
@Override
public String getName() {
String answer = definition.getName();
if (ObjectHelper.isEmpty(answer) && ObjectHelper.isNotEmpty(definition.getLocation())) {
answer = StringSupport.substringAfter(definition.getLocation(), ":");
answer = StringSupport.substringBeforeLast(answer, ".");
if (answer.contains("/")) {
answer = StringSupport.substringAfterLast(answer, "/");
}
}
return answer;
}
@Override
public String getLanguage() {
String answer = definition.getLanguage();
if (ObjectHelper.isEmpty(answer) && ObjectHelper.isNotEmpty(definition.getLocation())) {
answer = StringSupport.substringAfterLast(definition.getLocation(), ":");
answer = StringSupport.substringAfterLast(answer, ".");
}
return answer;
}
@Override
public SourceType getType() {
return ObjectHelper.supplyIfEmpty(definition.getType(), () -> SourceType.source);
}
@Override
public Optional<String> getLoader() {
return Optional.ofNullable(definition.getLoader());
}
@Override
public List<String> getInterceptors() {
return ObjectHelper.supplyIfEmpty(definition.getInterceptors(), Collections::emptyList);
}
@Override
public List<String> getPropertyNames() {
return ObjectHelper.supplyIfEmpty(definition.getPropertyNames(), Collections::emptyList);
}
/**
* Read the content of the source as {@link InputStream}.
*
* @param ctx the {@link CamelContext}
* @return the {@link InputStream} representing the source content
*/
@Override
public InputStream resolveAsInputStream(CamelContext ctx) {
try {
InputStream is;
if (definition.getContent() != null) {
is = new ByteArrayInputStream(definition.getContent());
} else {
is = ResourceHelper.resolveMandatoryResourceAsInputStream(ctx, definition.getLocation());
}
return definition.isCompressed()
? new GZIPInputStream(Base64.getDecoder().wrap(is))
: is;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
// ******************************
//
// Helpers
//
// ******************************
public static Resource asResource(CamelContext camelContext, Source source) {
return new Resource() {
@Override
public String getLocation() {
return source.getLocation();
}
@Override
public boolean exists() {
return true;
}
@Override
public InputStream getInputStream() throws IOException {
return source.resolveAsInputStream(camelContext);
}
@Override
public Reader getReader() throws Exception {
return source.resolveAsReader(camelContext);
}
@Override
public Reader getReader(Charset charset) throws Exception {
return source.resolveAsReader(camelContext, charset);
}
@Override
public String getScheme() {
return source.getLocation();
}
};
}
public static SourceDefinition computeDefinitionFromURI(String uri) throws Exception {
final String location = StringSupport.substringBefore(uri, "?");
if (!location.startsWith(Constants.SCHEME_PREFIX_CLASSPATH) && !location.startsWith(Constants.SCHEME_PREFIX_FILE)) {
throw new IllegalArgumentException("No valid resource format, expected scheme:path, found " + uri);
}
final String query = StringSupport.substringAfter(uri, "?");
final Map<String, Object> params = URISupport.parseQuery(query);
String language = (String) params.get("language");
if (ObjectHelper.isEmpty(language)) {
language = StringSupport.substringAfterLast(location, ":");
language = StringSupport.substringAfterLast(language, ".");
}
if (ObjectHelper.isEmpty(language)) {
throw new IllegalArgumentException("Unknown language " + language);
}
String name = (String) params.get("name");
if (name == null) {
name = StringSupport.substringAfter(location, ":");
name = StringSupport.substringBeforeLast(name, ".");
if (name.contains("/")) {
name = StringSupport.substringAfterLast(name, "/");
}
}
SourceDefinition answer = new SourceDefinition();
answer.setId((String) params.get("id"));
answer.setLocation(location);
answer.setName(name);
answer.setLanguage(language);
answer.setLoader((String) params.get("loader"));
answer.setInterceptors(StringSupport.split((String) params.get("interceptors"), ","));
answer.setCompressed(Boolean.parseBoolean((String) params.get("compression")));
return answer;
}
}
| 3,626 |
0 | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-core/support/src/main/java/org/apache/camel/k/support/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.camel.k.support;
public final class Constants {
public static final String ENV_CAMEL_K_ROUTES = "CAMEL_K_ROUTES";
public static final String PROPERTY_CAMEL_K_ROUTES = "camel.k.routes";
public static final String ENV_CAMEL_K_CONF = "CAMEL_K_CONF";
public static final String PROPERTY_CAMEL_K_CONF = "camel.k.conf";
public static final String ENV_CAMEL_K_CONF_D = "CAMEL_K_CONF_D";
public static final String PROPERTY_CAMEL_K_CONF_D = "camel.k.conf.d";
public static final String ENV_CAMEL_K_CUSTOMIZERS = "CAMEL_K_CUSTOMIZERS";
public static final String PROPERTY_CAMEL_K_CUSTOMIZER = "camel.k.customizer";
public static final String ENV_CAMEL_K_MOUNT_PATH_CONFIGMAPS = "CAMEL_K_MOUNT_PATH_CONFIGMAPS";
public static final String PROPERTY_CAMEL_K_MOUNT_PATH_CONFIGMAPS = "camel.k.mount-path.configmaps";
public static final String ENV_CAMEL_K_MOUNT_PATH_SECRETS = "CAMEL_K_MOUNT_PATH_SECRETS";
public static final String PROPERTY_CAMEL_K_MOUNT_PATH_SECRETS = "camel.k.mount-path.secrets";
public static final String SCHEME_REF = "ref";
public static final String SCHEME_PREFIX_REF = SCHEME_REF + ":";
public static final String SCHEME_CLASS = "class";
public static final String SCHEME_PREFIX_CLASS = SCHEME_CLASS + ":";
public static final String SCHEME_CLASSPATH = "classpath";
public static final String SCHEME_PREFIX_CLASSPATH = SCHEME_CLASSPATH + ":";
public static final String SCHEME_FILE = "file";
public static final String SCHEME_PREFIX_FILE = SCHEME_FILE + ":";
public static final String LOGGING_LEVEL_PREFIX = "logging.level.";
public static final String SOURCE_LOADER_INTERCEPTOR_RESOURCE_PATH = "META-INF/services/org/apache/camel/k/loader/interceptor/";
public static final String CONTEXT_CUSTOMIZER_RESOURCE_PATH = "META-INF/services/org/apache/camel/k/customizer/";
public static final String ENABLE_CUSTOMIZER_PATTERN = "(camel\\.k\\.)?customizer\\.([\\w][\\w-]*)\\.enabled";
public static final String PROPERTY_PREFIX_REST_COMPONENT_PROPERTY = "camel.rest.componentProperty.";
public static final String PROPERTY_PREFIX_REST_ENDPOINT_PROPERTY = "camel.rest.endpointProperty.";
public static final String CUSTOMIZER_PREFIX = "camel.k.customizer.";
public static final String CUSTOMIZER_PREFIX_FALLBACK = "customizer.";
public static final String LOADER_INTERCEPTOR_PREFIX = "camel.k.loader.interceptor.";
public static final String LOADER_INTERCEPTOR_PREFIX_FALLBACK = "loader.interceptor.";
private Constants() {
}
}
| 3,627 |
0 | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus/deployment/CoreProcessor.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.camel.k.core.quarkus.deployment;
import java.util.List;
import java.util.stream.Collectors;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem;
import org.apache.camel.builder.RouteBuilderLifecycleStrategy;
import org.apache.camel.k.ContextCustomizer;
import org.apache.camel.k.SourceDefinition;
import org.apache.camel.k.support.Constants;
import org.apache.camel.quarkus.core.deployment.spi.CamelServiceDestination;
import org.apache.camel.quarkus.core.deployment.spi.CamelServicePatternBuildItem;
import org.apache.camel.spi.StreamCachingStrategy;
import org.jboss.jandex.IndexView;
import static org.apache.camel.k.core.quarkus.deployment.support.DeploymentSupport.getAllKnownImplementors;
import static org.apache.camel.k.core.quarkus.deployment.support.DeploymentSupport.reflectiveClassBuildItem;
import static org.apache.camel.k.core.quarkus.deployment.support.DeploymentSupport.stream;
public class CoreProcessor {
@BuildStep
List<CamelServicePatternBuildItem> servicePatterns() {
return List.of(
new CamelServicePatternBuildItem(
CamelServiceDestination.REGISTRY,
true,
Constants.CONTEXT_CUSTOMIZER_RESOURCE_PATH + "/*"),
new CamelServicePatternBuildItem(
CamelServiceDestination.DISCOVERY,
true,
Constants.SOURCE_LOADER_INTERCEPTOR_RESOURCE_PATH + "/*")
);
}
@BuildStep
List<ReflectiveClassBuildItem> registerClasses(CombinedIndexBuildItem index) {
return List.of(
reflectiveClassBuildItem(SourceDefinition.class),
reflectiveClassBuildItem(getAllKnownImplementors(index.getIndex(), ContextCustomizer.class)),
reflectiveClassBuildItem(getAllKnownImplementors(index.getIndex(), RouteBuilderLifecycleStrategy.class))
);
}
@BuildStep
List<ServiceProviderBuildItem> registerServices(CombinedIndexBuildItem combinedIndexBuildItem) {
final IndexView view = combinedIndexBuildItem.getIndex();
final String serviceType = "org.apache.camel.k.Runtime$Listener";
return stream(getAllKnownImplementors(view, serviceType))
.map(i -> new ServiceProviderBuildItem(serviceType, i.name().toString()))
.collect(Collectors.toList());
}
@BuildStep
void registerStreamCachingClasses(
BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
CombinedIndexBuildItem combinedIndex) {
final IndexView view = combinedIndex.getIndex();
getAllKnownImplementors(view, StreamCachingStrategy.class)
.forEach(i-> reflectiveClass.produce(reflectiveClassBuildItem(i)));
getAllKnownImplementors(view, StreamCachingStrategy.Statistics.class)
.forEach(i-> reflectiveClass.produce(reflectiveClassBuildItem(i)));
getAllKnownImplementors(view, StreamCachingStrategy.SpoolRule.class)
.forEach(i-> reflectiveClass.produce(reflectiveClassBuildItem(i)));
reflectiveClass.produce(
new ReflectiveClassBuildItem(
true,
false,
StreamCachingStrategy.SpoolRule.class)
);
}
}
| 3,628 |
0 | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus/deployment/CoreFeature.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.camel.k.core.quarkus.deployment;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.FeatureBuildItem;
public class CoreFeature {
private static final String FEATURE = "camel-k-core";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
}
| 3,629 |
0 | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus/deployment | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus/deployment/devmode/HotDeploymentProcessor.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.camel.k.core.quarkus.deployment.devmode;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import org.apache.camel.k.support.Constants;
import org.apache.camel.util.StringHelper;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HotDeploymentProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(HotDeploymentProcessor.class);
@BuildStep
List<HotDeploymentWatchedFileBuildItem> routes() {
final Config config = ConfigProvider.getConfig();
final Optional<String> value = config.getOptionalValue(Constants.PROPERTY_CAMEL_K_ROUTES, String.class);
List<HotDeploymentWatchedFileBuildItem> items = new ArrayList<>();
if (value.isPresent()) {
for (String source : value.get().split(",", -1)) {
String path = StringHelper.after(source, ":");
if (path == null) {
path = source;
}
Path p = Paths.get(path);
if (Files.exists(p)) {
LOGGER.info("Register source for hot deployment: {}", p.toAbsolutePath());
items.add(new HotDeploymentWatchedFileBuildItem(p.toAbsolutePath().toString()));
}
}
}
return items;
}
@BuildStep
List<HotDeploymentWatchedFileBuildItem> conf() {
final Config config = ConfigProvider.getConfig();
final Optional<String> conf = config.getOptionalValue(Constants.PROPERTY_CAMEL_K_CONF, String.class);
final Optional<String> confd = config.getOptionalValue(Constants.PROPERTY_CAMEL_K_CONF_D, String.class);
List<HotDeploymentWatchedFileBuildItem> items = new ArrayList<>();
if (conf.isPresent()) {
LOGGER.info("Register conf for hot deployment: {}", conf.get());
items.add(new HotDeploymentWatchedFileBuildItem(conf.get()));
}
if (confd.isPresent()) {
FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Objects.requireNonNull(file);
Objects.requireNonNull(attrs);
String path = file.toFile().getAbsolutePath();
String ext = FilenameUtils.getExtension(path);
if (Objects.equals("properties", ext)) {
LOGGER.info("Register conf for hot deployment: {}", path);
items.add(new HotDeploymentWatchedFileBuildItem(path));
}
return FileVisitResult.CONTINUE;
}
};
Path root = Paths.get(confd.get());
if (Files.exists(root)) {
try {
Files.walkFileTree(root, visitor);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return items;
}
}
| 3,630 |
0 | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus/deployment | Create_ds/camel-k-runtime/camel-k-core/deployment/src/main/java/org/apache/camel/k/core/quarkus/deployment/support/DeploymentSupport.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.camel.k.core.quarkus.deployment.support;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
public final class DeploymentSupport {
private DeploymentSupport() {
}
public static Iterable<ClassInfo> getAllKnownImplementors(IndexView view, String name) {
return view.getAllKnownImplementors(DotName.createSimple(name));
}
public static <T> Stream<T> getAllKnownImplementors(IndexView view, String name, Function<ClassInfo, T> mapper) {
return stream(getAllKnownImplementors(view, name)).map(mapper);
}
public static Iterable<ClassInfo> getAllKnownImplementors(IndexView view, Class<?> type) {
return view.getAllKnownImplementors(DotName.createSimple(type.getName()));
}
public static <T> Stream<T> getAllKnownImplementors(IndexView view, Class<?> type, Function<ClassInfo, T> mapper) {
return stream(getAllKnownImplementors(view, type)).map(mapper);
}
public static Iterable<ClassInfo> getAllKnownImplementors(IndexView view, DotName type) {
return view.getAllKnownImplementors(type);
}
public static <T> Stream<T> getAllKnownImplementors(IndexView view, DotName type, Function<ClassInfo, T> mapper) {
return stream(getAllKnownImplementors(view, type)).map(mapper);
}
public static Iterable<ClassInfo> getAllKnownSubclasses(IndexView view, String name) {
return view.getAllKnownSubclasses(DotName.createSimple(name));
}
public static <T> Stream<T> getAllKnownSubclasses(IndexView view, String name, Function<ClassInfo, T> mapper) {
return stream(getAllKnownSubclasses(view, name)).map(mapper);
}
public static Iterable<ClassInfo> getAllKnownSubclasses(IndexView view, Class<?> type) {
return view.getAllKnownSubclasses(DotName.createSimple(type.getName()));
}
public static <T> Stream<T> getAllKnownSubclasses(IndexView view, Class<?> type, Function<ClassInfo, T> mapper) {
return stream(getAllKnownSubclasses(view, type)).map(mapper);
}
public static Iterable<ClassInfo> getAllKnownSubclasses(IndexView view, DotName type) {
return view.getAllKnownSubclasses(type);
}
public static <T> Stream<T> getAllKnownSubclasses(IndexView view, DotName type, Function<ClassInfo, T> mapper) {
return stream(getAllKnownSubclasses(view, type)).map(mapper);
}
public static Iterable<ClassInfo> getAnnotated(IndexView view, String name) {
return getAnnotated(view, DotName.createSimple(name));
}
public static <T> Stream<T> getAnnotated(IndexView view, String name, Function<ClassInfo, T> mapper) {
return stream(getAnnotated(view, name)).map(mapper);
}
public static Iterable<ClassInfo> getAnnotated(IndexView view, Class<?> type) {
return getAnnotated(view, DotName.createSimple(type.getName()));
}
public static <T> Stream<T> getAnnotated(IndexView view, Class<?> type, Function<ClassInfo, T> mapper) {
return stream(getAnnotated(view, type)).map(mapper);
}
public static Iterable<ClassInfo> getAnnotated(IndexView view, DotName type) {
return view.getAnnotations(type).stream()
.map(AnnotationInstance::target)
.filter(t -> t.kind() == AnnotationTarget.Kind.CLASS)
.map(AnnotationTarget::asClass)
.collect(Collectors.toList());
}
public static <T> Iterable<T> getAnnotated(IndexView view, DotName type, Function<ClassInfo, T> mapper) {
return stream(getAnnotated(view, type)).map(mapper).collect(Collectors.toList());
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(Class<?>... classes) {
return new ReflectiveClassBuildItem(true, false, classes);
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(boolean methods, boolean fields, Class<?>... classes) {
return new ReflectiveClassBuildItem(methods, fields, classes);
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(ClassInfo... classInfos) {
return classInfos.length == 1
? new ReflectiveClassBuildItem(
true,
false,
classInfos[0].name().toString())
: new ReflectiveClassBuildItem(
true,
false,
Stream.of(classInfos)
.map(ClassInfo::name)
.map(DotName::toString)
.toArray(String[]::new)
);
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(Collection<ClassInfo> classInfos) {
return new ReflectiveClassBuildItem(
true,
false,
classInfos.stream()
.map(ClassInfo::name)
.map(DotName::toString)
.toArray(String[]::new)
);
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(Iterable<ClassInfo> classInfos) {
return new ReflectiveClassBuildItem(
true,
false,
stream(classInfos)
.map(ClassInfo::name)
.map(DotName::toString)
.toArray(String[]::new)
);
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(boolean methods, boolean fields, ClassInfo... classInfos) {
return new ReflectiveClassBuildItem(
methods,
fields,
Stream.of(classInfos)
.map(ClassInfo::name)
.map(DotName::toString)
.toArray(String[]::new)
);
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(boolean methods, boolean fields, Collection<ClassInfo> classInfos) {
return new ReflectiveClassBuildItem(
methods,
fields,
classInfos.stream()
.map(ClassInfo::name)
.map(DotName::toString)
.toArray(String[]::new)
);
}
public static ReflectiveClassBuildItem reflectiveClassBuildItem(boolean methods, boolean fields, Iterable<ClassInfo> classInfos) {
return new ReflectiveClassBuildItem(
methods,
fields,
stream(classInfos)
.map(ClassInfo::name)
.map(DotName::toString)
.toArray(String[]::new)
);
}
public static <T> Stream<T> stream(Iterable<T> iterable) {
return StreamSupport.stream(iterable.spliterator(), false);
}
}
| 3,631 |
0 | Create_ds/camel-k-runtime/camel-k-core/api/src/generated/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/api/src/generated/java/org/apache/camel/k/SourceDefinitionConfigurer.java | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.k;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.k.SourceDefinition;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class SourceDefinitionConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.k.SourceDefinition target = (org.apache.camel.k.SourceDefinition) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "compressed":
case "Compressed": target.setCompressed(property(camelContext, boolean.class, value)); return true;
case "content":
case "Content": target.setContent(property(camelContext, byte[].class, value)); return true;
case "id":
case "Id": target.setId(property(camelContext, java.lang.String.class, value)); return true;
case "interceptors":
case "Interceptors": target.setInterceptors(property(camelContext, java.util.List.class, value)); return true;
case "language":
case "Language": target.setLanguage(property(camelContext, java.lang.String.class, value)); return true;
case "loader":
case "Loader": target.setLoader(property(camelContext, java.lang.String.class, value)); return true;
case "location":
case "Location": target.setLocation(property(camelContext, java.lang.String.class, value)); return true;
case "name":
case "Name": target.setName(property(camelContext, java.lang.String.class, value)); return true;
case "propertynames":
case "PropertyNames": target.setPropertyNames(property(camelContext, java.util.List.class, value)); return true;
case "type":
case "Type": target.setType(property(camelContext, org.apache.camel.k.SourceType.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "compressed":
case "Compressed": return boolean.class;
case "content":
case "Content": return byte[].class;
case "id":
case "Id": return java.lang.String.class;
case "interceptors":
case "Interceptors": return java.util.List.class;
case "language":
case "Language": return java.lang.String.class;
case "loader":
case "Loader": return java.lang.String.class;
case "location":
case "Location": return java.lang.String.class;
case "name":
case "Name": return java.lang.String.class;
case "propertynames":
case "PropertyNames": return java.util.List.class;
case "type":
case "Type": return org.apache.camel.k.SourceType.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.k.SourceDefinition target = (org.apache.camel.k.SourceDefinition) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "compressed":
case "Compressed": return target.isCompressed();
case "content":
case "Content": return target.getContent();
case "id":
case "Id": return target.getId();
case "interceptors":
case "Interceptors": return target.getInterceptors();
case "language":
case "Language": return target.getLanguage();
case "loader":
case "Loader": return target.getLoader();
case "location":
case "Location": return target.getLocation();
case "name":
case "Name": return target.getName();
case "propertynames":
case "PropertyNames": return target.getPropertyNames();
case "type":
case "Type": return target.getType();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "interceptors":
case "Interceptors": return java.lang.String.class;
case "propertynames":
case "PropertyNames": return java.lang.String.class;
default: return null;
}
}
}
| 3,632 |
0 | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel/k/RuntimeAware.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.camel.k;
public interface RuntimeAware {
void setRuntime(Runtime runtime);
Runtime getRuntime();
}
| 3,633 |
0 | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel/k/ContextCustomizer.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.camel.k;
import org.apache.camel.CamelContext;
import org.apache.camel.Ordered;
@FunctionalInterface
public interface ContextCustomizer extends Ordered, Comparable<ContextCustomizer> {
/**
* Perform CamelContext customization.
*
* @param camelContext the camel context to customize.
*/
void apply(CamelContext camelContext);
@Override
default int getOrder() {
return 0;
}
@Override
default int compareTo(ContextCustomizer o) {
return Integer.compare(getOrder(), o.getOrder());
}
}
| 3,634 |
0 | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel/k/SourceDefinition.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.camel.k;
import java.util.List;
import org.apache.camel.spi.Configurer;
import org.apache.camel.spi.IdAware;
@Configurer
public class SourceDefinition implements IdAware {
private String id;
private String name;
private String language;
private String loader;
private List<String> interceptors;
// Default as source type
private SourceType type = SourceType.source;
private List<String> propertyNames;
private String location;
private byte[] content;
private boolean compressed;
@Override
public String getId() {
return id;
}
/**
* Sets the id
*/
@Override
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
/**
* The name of the source.
*/
public void setName(String name) {
this.name = name;
}
public String getLanguage() {
return language;
}
/**
* The language use to define the source.
*/
public void setLanguage(String language) {
this.language = language;
}
public String getLoader() {
return loader;
}
/**
* The {@link SourceLoader} that should be used to load the content of the source.
*/
public void setLoader(String loader) {
this.loader = loader;
}
public List<String> getInterceptors() {
return interceptors;
}
/**
* The {@link org.apache.camel.k.SourceLoader.Interceptor} that should be applied.
*/
public void setInterceptors(List<String> interceptors) {
this.interceptors = interceptors;
}
public SourceType getType() {
return type;
}
/**
* The {@link SourceType} of the source.
*/
public void setType(SourceType type) {
this.type = type;
}
public List<String> getPropertyNames() {
return propertyNames;
}
/**
* The list of properties names the source requires (used only for templates).
*/
public void setPropertyNames(List<String> propertyNames) {
this.propertyNames = propertyNames;
}
public String getLocation() {
return location;
}
/**
* The location of the source.
*/
public void setLocation(String location) {
this.location = location;
}
public byte[] getContent() {
return content;
}
/**
* The content of the source.
*/
public void setContent(byte[] content) {
this.content = content;
}
public boolean isCompressed() {
return compressed;
}
/**
* If the content of the source is compressed.
*/
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
@Override
public String toString() {
String answer = "";
if (name != null) {
answer += "name='" + name + "', ";
}
if (language != null) {
answer += "language='" + language + "', ";
}
if (loader != null) {
answer += "loader='" + loader + "', ";
}
if (interceptors != null) {
answer += "interceptors='" + interceptors + "', ";
}
if (type != null) {
answer += "type='" + type + "', ";
}
if (propertyNames != null) {
answer += "propertyNames='" + propertyNames + "', ";
}
if (location != null) {
answer += "location='" + location + "', ";
}
if (compressed) {
answer += "compressed='true', ";
}
if (content != null) {
answer += "<...>";
}
return "SourceDefinition{" + answer + '}';
}
}
| 3,635 |
0 | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel/k/Source.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.camel.k;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.HasId;
public interface Source extends HasId {
String getLocation();
String getName();
String getLanguage();
SourceType getType();
Optional<String> getLoader();
List<String> getInterceptors();
List<String> getPropertyNames();
InputStream resolveAsInputStream(CamelContext ctx);
default Reader resolveAsReader(CamelContext ctx) {
return resolveAsReader(ctx, StandardCharsets.UTF_8);
}
default Reader resolveAsReader(CamelContext ctx, Charset charset) {
return new InputStreamReader(resolveAsInputStream(ctx), charset);
}
}
| 3,636 |
0 | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel/k/SourceType.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.camel.k;
public enum SourceType {
// Order matters. We want the sources to be loaded following this enum order.
errorHandler,
template,
source
}
| 3,637 |
0 | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel | Create_ds/camel-k-runtime/camel-k-core/api/src/main/java/org/apache/camel/k/Runtime.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.camel.k;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.Ordered;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.spi.HasCamelContext;
import org.apache.camel.spi.Registry;
import static org.apache.camel.util.CollectionHelper.mapOf;
public interface Runtime extends HasCamelContext, AutoCloseable {
/**
* Returns the camel context adapting it to the specialized type.
*
* @see HasCamelContext#getCamelContext()
*
* @return the extended camel context.
*/
default ExtendedCamelContext getExtendedCamelContext() {
return getCamelContext().getCamelContextExtension();
}
/**
* Returns the registry associated to this runtime.
*/
default Registry getRegistry() {
return getCamelContext().getRegistry();
}
/**
* Sets a special list of properties that take precedence and will use first, if a property exist.
*
* @see org.apache.camel.spi.PropertiesComponent#setOverrideProperties(Properties)
* @param properties the properties to set
*/
default void setProperties(Properties properties) {
getCamelContext().getPropertiesComponent().setOverrideProperties(properties);
}
/**
* Sets a special list of properties that take precedence and will use first, if a property exist.
*
* @see org.apache.camel.spi.PropertiesComponent#setOverrideProperties(Properties)
* @param properties the properties to set
*/
default void setProperties(Map<String, String> properties) {
Properties p = new Properties();
p.putAll(properties);
setProperties(p);
}
/**
* Sets a special list of properties that take precedence and will use first, if a property exist.
*
* @see org.apache.camel.spi.PropertiesComponent#setOverrideProperties(Properties)
* @param key the mapping's key
* @param value the mapping's value
* @param entries containing the keys and values from which the map is populated
*
*/
default void setProperties(String key, String value, String... entries) {
setProperties(
mapOf(HashMap::new, key, value, entries)
);
}
/**
* Sets a special list of properties that take precedence and will use first, if a property exist.
*
* @see org.apache.camel.spi.PropertiesComponent#setOverrideProperties(Properties)
* @param builder the builder which will create the routes
*/
default void addRoutes(RoutesBuilder builder) {
try {
getCamelContext().addRoutes(builder);
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
/**
* Lifecycle method used to stops the entire integration.
*/
default void stop() throws Exception {
// Stopping the Camel context in default config is enough to tear down the integration
getCamelContext().stop();
}
@Override
default void close() throws Exception {
stop();
}
enum Phase {
Initializing,
ConfigureProperties,
ConfigureContext,
ConfigureRoutes,
Starting,
Started,
Stopping,
Stopped
}
@FunctionalInterface
interface Listener extends Ordered {
boolean accept(Phase phase, Runtime runtime);
@Override
default int getOrder() {
return Ordered.LOWEST;
}
}
/**
* Helper to create a simple runtime from a given Camel Context.
*
* @param camelContext the camel context
* @return the runtime
*/
static Runtime on(CamelContext camelContext) {
return () -> camelContext;
}
/**
* Helper to create a simple runtime from a given Camel Context provider.
*
* @param provider the camel context provider
* @return the runtime
*/
static Runtime on(HasCamelContext provider) {
return provider::getCamelContext;
}
}
| 3,638 |
0 | Create_ds/camel-k-runtime/camel-k-resume-kafka/impl/src/main/java/org/apache/camel/k | Create_ds/camel-k-runtime/camel-k-resume-kafka/impl/src/main/java/org/apache/camel/k/resume/ResumeContextCustomizer.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.camel.k.resume;
import org.apache.camel.CamelContext;
import org.apache.camel.k.ContextCustomizer;
import org.apache.camel.k.annotation.Customizer;
import org.apache.camel.k.resume.kafka.KafkaResumeFactory;
import org.apache.camel.resume.ResumeStrategy;
import org.apache.camel.resume.cache.ResumeCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Customizer("resume")
public class ResumeContextCustomizer implements ContextCustomizer {
private static final Logger LOG = LoggerFactory.getLogger(ResumeContextCustomizer.class);
private String resumeStrategy;
private String resumeServer;
private String resumePath;
private String cacheFillPolicy;
@Override
public void apply(CamelContext camelContext) {
LOG.debug("Receiving context for customization");
LOG.debug("Resume strategy: {}", resumeStrategy);
LOG.debug("Resume server: {}", resumeServer);
LOG.debug("Resume path: {}", resumePath);
LOG.debug("Cache fill policy: {}", cacheFillPolicy);
ResumeCache<?> resumeCache = (ResumeCache<?>) camelContext.getRegistry().lookupByName("cache");
LOG.debug("Values from the registry (cache): {}", resumeCache);
try {
ResumeStrategy resumeStrategyInstance = KafkaResumeFactory.build(resumeStrategy, resumeServer, resumePath, cacheFillPolicy);
LOG.debug("Created resume strategy instance: {}", resumeStrategyInstance.getClass());
camelContext.getRegistry().bind("resumeStrategy", resumeStrategyInstance);
} catch (Exception e) {
LOG.error("Exception: {}", e.getMessage(), e);
}
}
public String getResumeStrategy() {
return resumeStrategy;
}
public void setResumeStrategy(String resumeStrategy) {
this.resumeStrategy = resumeStrategy;
}
public String getResumePath() {
return resumePath;
}
public void setResumePath(String resumePath) {
this.resumePath = resumePath;
}
public String getResumeServer() {
return resumeServer;
}
public void setResumeServer(String resumeServer) {
this.resumeServer = resumeServer;
}
public String getCacheFillPolicy() {
return cacheFillPolicy;
}
public void setCacheFillPolicy(String cacheFillPolicy) {
this.cacheFillPolicy = cacheFillPolicy;
}
}
| 3,639 |
0 | Create_ds/camel-k-runtime/camel-k-resume-kafka/impl/src/main/java/org/apache/camel/k/resume | Create_ds/camel-k-runtime/camel-k-resume-kafka/impl/src/main/java/org/apache/camel/k/resume/kafka/KafkaResumeFactory.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.camel.k.resume.kafka;
import org.apache.camel.processor.resume.kafka.KafkaResumeStrategyConfiguration;
import org.apache.camel.processor.resume.kafka.KafkaResumeStrategyConfigurationBuilder;
import org.apache.camel.processor.resume.kafka.SingleNodeKafkaResumeStrategy;
import org.apache.camel.resume.Cacheable;
import org.apache.camel.resume.ResumeStrategy;
import org.apache.camel.util.ObjectHelper;
public final class KafkaResumeFactory {
private KafkaResumeFactory() {
}
public static ResumeStrategy build(String name, String resumeServer, String topic, String cacheFillPolicy) {
Cacheable.FillPolicy policy = extracted(cacheFillPolicy);
final KafkaResumeStrategyConfiguration resumeStrategyConfiguration = KafkaResumeStrategyConfigurationBuilder.newBuilder()
.withBootstrapServers(resumeServer)
.withCacheFillPolicy(policy)
.withTopic(topic)
.build();
switch (name) {
case "org.apache.camel.processor.resume.kafka.SingleNodeKafkaResumeStrategy": {
return new SingleNodeKafkaResumeStrategy(resumeStrategyConfiguration);
}
default: {
throw new UnsupportedOperationException(String.format("The strategy %s is not a valid strategy", name));
}
}
}
private static Cacheable.FillPolicy extracted(String cacheFillPolicy) {
if (!ObjectHelper.isEmpty(cacheFillPolicy) && cacheFillPolicy.equals("minimizing")) {
return Cacheable.FillPolicy.MINIMIZING;
}
return Cacheable.FillPolicy.MAXIMIZING;
}
}
| 3,640 |
0 | Create_ds/camel-k-runtime/camel-k-resume-kafka/deployment/src/main/java/org/apache/camel/k/quarkus/resume | Create_ds/camel-k-runtime/camel-k-resume-kafka/deployment/src/main/java/org/apache/camel/k/quarkus/resume/deployment/ResumeFeature.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.camel.k.quarkus.resume.deployment;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.FeatureBuildItem;
public class ResumeFeature {
private static final String FEATURE = "camel-k-resume";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
}
| 3,641 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/UpdatePaymentServlet.java | // #Update Payment
package com.paypal.api.payments.servlet;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.Patch;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.apache.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.paypal.api.payments.util.SampleConstants.*;
public class UpdatePaymentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(UpdatePaymentServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
updatePayment(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public boolean updatePayment(HttpServletRequest req,
HttpServletResponse resp) {
// ### Create a Payment
// We are re-using the PaymentWithPayPalServlet to create a payment
// for us. This will make sure the samples will work all the time.
PaymentWithPayPalServlet servlet = new PaymentWithPayPalServlet();
Payment payment = servlet.createPayment(req, resp);
// ### Create Patch Request
List<Patch> patchRequest = new ArrayList<Patch>();
// ### Amount
// Let's update the payment amount as an example.
Amount amount = new Amount();
amount.setCurrency("USD");
// Total must be equal to sum of shipping, tax and subtotal.
amount.setTotal("17.50");
amount.setDetails(new Details().setShipping("11.50").setTax("1")
.setSubtotal("5"));
// ### Patch Object
// Create a patch object, and fill these 3 properties accordingly.
Patch patch1 = new Patch();
patch1.setOp("replace").setPath("/transactions/0/amount").setValue(amount);
patchRequest.add(patch1);
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// Update a payment by posting to the APIService
// using a valid apiContext
payment.update(apiContext, patchRequest);
LOGGER.info("Updated Payment with " + payment.getId());
ResultPrinter.addResult(req, resp, "Update Payment",
Payment.getLastRequest(), "", null);
return true;
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Update Payment",
Payment.getLastRequest(), null, e.getMessage());
}
return false;
}
}
| 3,642 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/VoidAuthorizationServlet.java | // #VoidAuthorization Sample
// This sample code demonstrate how you
// can do a Void on a Authorization
// resource
// API used: /v1/payments/authorization/{authorization_id}/void
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Address;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.FundingInstrument;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class VoidAuthorizationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(VoidAuthorizationServlet.class);
Map<String, String> map = new HashMap<String, String>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##VoidAuthorization
// Sample showing how to void an Authorization
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Authorization
// Retrieve a Authorization object
// by making a Payment with intent
// as 'authorize'
Authorization authorization = getAuthorization(apiContext);
// Void an Authorization
// by POSTing to
// URI v1/payments/authorization/{authorization_id}/void
Authorization returnAuthorization = authorization.doVoid(apiContext);
LOGGER.info("Authorization id = " + returnAuthorization.getId()
+ " and status = " + returnAuthorization.getState());
ResultPrinter.addResult(req, resp, "Voided Authorization", Authorization.getLastRequest(), Authorization.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Voided Authorization", Authorization.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
private Authorization getAuthorization(APIContext apiContext)
throws PayPalRESTException {
// ###Details
// Let's you specify details of a payment amount.
Details details = new Details();
details.setShipping("0.03");
details.setSubtotal("107.41");
details.setTax("0.03");
// ###Amount
// Let's you specify a payment amount.
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal("107.47");
amount.setDetails(details);
// ###Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction
.setDescription("This is the payment transaction description.");
// The Payment creation API requires a list of
// Transaction; add the created `Transaction`
// to a List
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
// ###Address
// Base Address object used as shipping or billing
// address in a payment. [Optional]
Address billingAddress = new Address();
billingAddress.setCity("Johnstown");
billingAddress.setCountryCode("US");
billingAddress.setLine1("52 N Main ST");
billingAddress.setPostalCode("43210");
billingAddress.setState("OH");
// ###CreditCard
// A resource representing a credit card that can be
// used to fund a payment.
CreditCard creditCard = new CreditCard();
creditCard.setBillingAddress(billingAddress);
creditCard.setCvv2(874);
creditCard.setExpireMonth(11);
creditCard.setExpireYear(2018);
creditCard.setFirstName("Joe");
creditCard.setLastName("Shopper");
creditCard.setNumber("4417119669820331");
creditCard.setType("visa");
// ###FundingInstrument
// A resource representing a Payeer's funding instrument.
// Use a Payer ID (A unique identifier of the payer generated
// and provided by the facilitator. This is required when
// creating or using a tokenized funding instrument)
// and the `CreditCardDetails`
FundingInstrument fundingInstrument = new FundingInstrument();
fundingInstrument.setCreditCard(creditCard);
// The Payment creation API requires a list of
// FundingInstrument; add the created `FundingInstrument`
// to a List
List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>();
fundingInstruments.add(fundingInstrument);
// ###Payer
// A resource representing a Payer that funds a payment
// Use the List of `FundingInstrument` and the Payment Method
// as 'credit_card'
Payer payer = new Payer();
payer.setFundingInstruments(fundingInstruments);
payer.setPaymentMethod("credit_card");
// ###Payment
// A Payment Resource; create one using
// the above types and intent as 'authorize'
Payment payment = new Payment();
payment.setIntent("authorize");
payment.setPayer(payer);
payment.setTransactions(transactions);
Payment responsePayment = payment.create(apiContext);
return responsePayment.getTransactions().get(0)
.getRelatedResources().get(0).getAuthorization();
}
}
| 3,643 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetPaymentServlet.java | // #GetPayment Sample
// This sample code demonstrates how you can retrieve
// the details of a payment resource.
// API used: /v1/payments/payment/{payment-id}
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetPaymentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetPaymentServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##GetPayment
// Call the method with a valid Payment ID
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// Retrieve the payment object by calling the
// static `get` method
// on the Payment class by passing a valid
// AccessToken and Payment ID
Payment payment = Payment.get(apiContext,
"PAY-0XL713371A312273YKE2GCNI");
LOGGER.info("Payment retrieved ID = " + payment.getId()
+ ", status = " + payment.getState());
ResultPrinter.addResult(req, resp, "Get Payment", Payment.getLastRequest(), Payment.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Get Payment", Payment.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,644 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/CreateCreditCardServlet.java | // #CreateCreditCard Sample
// Using the 'vault' API, you can store a
// Credit Card securely on PayPal. You can
// use a saved Credit Card to process
// a payment in the future.
// The following code demonstrates how
// can save a Credit Card on PayPal using
// the Vault API.
// API used: POST /v1/vault/credit-card
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class CreateCreditCardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(CreateCreditCardServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Create
// Sample showing how to create a CreditCard.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ###CreditCard
// A resource representing a credit card that can be
// used to fund a payment.
CreditCard creditCard = new CreditCard();
creditCard.setExpireMonth(11);
creditCard.setExpireYear(2018);
creditCard.setNumber("4669424246660779");
creditCard.setCvv2(0123);
creditCard.setType("visa");
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Save
// Creates the credit card as a resource
// in the PayPal vault. The response contains
// an 'id' that you can use to refer to it
// in the future payments.
CreditCard createdCreditCard = creditCard.create(apiContext);
LOGGER.info("Credit Card Created With ID: "
+ createdCreditCard.getId());
ResultPrinter.addResult(req, resp, "Created Credit Card", CreditCard.getLastRequest(), CreditCard.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Created Credit Card", CreditCard.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,645 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/SaleRefundServlet.java | // #SaleRefund Sample
// This sample code demonstrate how you can
// process a refund on a sale transaction created
// using the Payments API.
// API used: /v1/payments/sale/{sale-id}/refund
package com.paypal.api.payments.servlet;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.RefundRequest;
import com.paypal.api.payments.Sale;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.paypal.api.payments.util.SampleConstants.*;
public class SaleRefundServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##RefundSale
// Sample showing how to refund
// a sale
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ###Sale
// A sale transaction.
// Create a Sale object with the
// given sale transaction id.
Sale sale = new Sale();
sale.setId("9YB06173L6274542A");
// ###Refund
// A refund transaction.
// Use the amount to create
// a refund object
RefundRequest refund = new RefundRequest();
// ###Amount
// Create an Amount object to
// represent the amount to be
// refunded. Create the refund object, if the refund is partial
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal("0.01");
refund.setAmount(amount);
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// Refund by posting to the APIService
// using a valid AccessToken
sale.refund(apiContext, refund);
ResultPrinter.addResult(req, resp, "Sale Refunded", Sale.getLastRequest(), Sale.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Sale Refunded", Sale.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,646 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/ThirdPartyPaymentWithPayPalServlet.java | // #Create Payment Using PayPal Sample
// This sample code demonstrates how you can process a
// PayPal Account based Payment.
// API used: /v1/payments/payment
package com.paypal.api.payments.servlet;
import com.paypal.api.payments.*;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.apache.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import static com.paypal.api.payments.util.SampleConstants.*;
public class ThirdPartyPaymentWithPayPalServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(ThirdPartyPaymentWithPayPalServlet.class);
Map<String, String> map = new HashMap<String, String>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Create
// Sample showing to create a Payment using PayPal
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
createPayment(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public Payment createPayment(HttpServletRequest req, HttpServletResponse resp) {
Payment createdPayment = null;
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
if (req.getParameter("PayerID") != null) {
Payment payment = new Payment();
if (req.getParameter("guid") != null) {
payment.setId(map.get(req.getParameter("guid")));
}
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(req.getParameter("PayerID"));
try {
createdPayment = payment.execute(apiContext, paymentExecution);
ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), Payment.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), null, e.getMessage());
}
} else {
// ###Details
// Let's you specify details of a payment amount.
Details details = new Details();
details.setShipping("1");
details.setSubtotal("5");
details.setTax("1");
// ###Amount
// Let's you specify a payment amount.
Amount amount = new Amount();
amount.setCurrency("USD");
// Total must be equal to sum of shipping, tax and subtotal.
amount.setTotal("7");
amount.setDetails(details);
// ### Payee
// Specify a payee with that user's email or merchant id
// Merchant Id can be found at https://www.paypal.com/businessprofile/settings/
Payee payee = new Payee();
payee.setEmail("stevendcoffey-facilitator@gmail.com");
// ###Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction.setPayee(payee);
transaction
.setDescription("This is the payment transaction description.");
// ### Items
Item item = new Item();
item.setName("Ground Coffee 40 oz").setQuantity("1").setCurrency("USD").setPrice("5");
ItemList itemList = new ItemList();
List<Item> items = new ArrayList<Item>();
items.add(item);
itemList.setItems(items);
transaction.setItemList(itemList);
// The Payment creation API requires a list of
// Transaction; add the created `Transaction`
// to a List
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
// ###Payer
// A resource representing a Payer that funds a payment
// Payment Method
// as 'paypal'
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
// ###Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
// ###Redirect URLs
RedirectUrls redirectUrls = new RedirectUrls();
String guid = UUID.randomUUID().toString().replaceAll("-", "");
redirectUrls.setCancelUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/thirdpartypaymentwithpaypal?guid=" + guid);
redirectUrls.setReturnUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/thirdpartypaymentwithpaypal?guid=" + guid);
payment.setRedirectUrls(redirectUrls);
// Create a payment by posting to the APIService
// using a valid AccessToken
// The return object contains the status;
try {
createdPayment = payment.create(apiContext);
LOGGER.info("Created payment with id = "
+ createdPayment.getId() + " and status = "
+ createdPayment.getState());
// ###Payment Approval Url
Iterator<Links> links = createdPayment.getLinks().iterator();
while (links.hasNext()) {
Links link = links.next();
if (link.getRel().equalsIgnoreCase("approval_url")) {
req.setAttribute("redirectURL", link.getHref());
}
}
ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), Payment.getLastResponse(), null);
map.put(guid, createdPayment.getId());
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), null, e.getMessage());
}
}
return createdPayment;
}
}
| 3,647 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/AuthorizationCaptureServlet.java | // #AuthorizationCapture Sample
// This sample code demonstrate how you
// do a Capture on an Authorization
// API used: /v1/payments/authorization/{authorization_id}/capture
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Address;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.Capture;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.FundingInstrument;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class AuthorizationCaptureServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(AuthorizationCaptureServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##AuthorizationCapture
// Sample showing how to do a Capture using Authorization
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Authorization
// Retrieve a Authorization object
// by making a Payment with intent
// as 'authorize'
String authorizationId = "<your authorization id here>";
Authorization authorization = Authorization.get(apiContext, authorizationId);
// ###Amount
// Let's you specify a capture amount.
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal("4.54");
// ###Capture
// A capture transaction
Capture capture = new Capture();
capture.setAmount(amount);
// ##IsFinalCapture
// If set to true, all remaining
// funds held by the authorization
// will be released in the funding
// instrument. Default is �false�.
capture.setIsFinalCapture(true);
// Capture by POSTing to
// URI v1/payments/authorization/{authorization_id}/capture
Capture responseCapture = authorization.capture(apiContext, capture);
LOGGER.info("Capture id = " + responseCapture.getId()
+ " and status = " + responseCapture.getState());
ResultPrinter.addResult(req, resp, "Authorization Capture", Authorization.getLastRequest(), Authorization.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Authorization Capture", Authorization.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,648 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetSaleServlet.java | // # Get Details of a Sale Transaction Sample
// This sample code demonstrates how you can retrieve
// details of completed Sale Transaction.
// API used: /v1/payments/sale/{sale-id}
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Sale;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetSaleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(GetSaleServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// # Get Sale By SaleID Sample how to get details about a sale.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// Pass an AccessToken and the ID of the sale
// transaction from your payment resource.
Sale sale = Sale.get(apiContext, "03W403310B593121A");
LOGGER.info("Sale amount : " + sale.getAmount() + " for saleID : "
+ sale.getId());
ResultPrinter.addResult(req, resp, "Get Sale", Sale.getLastRequest(), Sale.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Get Sale", Sale.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,649 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetCaptureServlet.java | // #GetCapture Sample
// This sample code demonstrate how you
// can retrieve the details of a Capture
// resource
// API used: /v1/payments/capture/{capture_id}
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Address;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.Capture;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.FundingInstrument;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetCaptureServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetAuthorizationServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##GetCapture
// Sample showing how to Get a Capture using
// CaptureId
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
/// ###Capture
// Create a Capture object
// by doing a capture on
// Authorization object
// and retrieve the Id
String captureId = "<your capture id here>";
// Retrieve the Capture object by
// doing a GET call to
// URI v1/payments/capture/{capture_id}
Capture capture = Capture.get(apiContext, captureId);
LOGGER.info("Capture id = " + capture.getId()
+ " and status = " + capture.getState());
ResultPrinter.addResult(req, resp, "Get Capture", Capture.getLastRequest(), Capture.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Get Capture", Capture.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,650 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetPaymentHistoryServlet.java | // #GetPaymentList Sample
// This sample code demonstrate how you can
// retrieve a list of all Payment resources
// you've created using the Payments API.
// Note various query parameters that you can
// use to filter, and paginate through the
// payments list.
// API used: GET /v1/payments/payments
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.PaymentHistory;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetPaymentHistoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetPaymentHistoryServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, String> containerMap = new HashMap<String, String>();
containerMap.put("count", "10");
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Retrieve
// Retrieve the PaymentHistory object by calling the
// static `get` method
// on the Payment class, and pass the
// APIContext and a ContainerMap object that contains
// query parameters for paginations and filtering.
// Refer the API documentation
// for valid values for keys
PaymentHistory paymentHistory = Payment.list(apiContext,
containerMap);
LOGGER.info("Payment History = " + paymentHistory.toString());
ResultPrinter.addResult(req, resp, "Got Payment History", Payment.getLastRequest(), Payment.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Got Payment History", Payment.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,651 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetCreditCardServlet.java | // #GetCreditCard Sample
// This sample code demonstrates how you
// retrieve a previously saved
// Credit Card using the 'vault' API.
// API used: GET /v1/vault/credit-card/{id}
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetCreditCardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetCreditCardServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##GetCreditCardUsingId
// Call the method with a previously created Credit Card ID
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// Retrieve the CreditCard object by calling the
// static `get` method on the CreditCard class,
// and pass the APIContext and CreditCard ID
CreditCard creditCard = CreditCard.get(apiContext,
"CARD-5BT058015C739554AKE2GCEI");
LOGGER.info("Credit Card retrieved ID = " + creditCard.getId()
+ ", status = " + creditCard.getState());
ResultPrinter.addResult(req, resp, "Got Credit Card from Vault", CreditCard.getLastRequest(), CreditCard.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Got Credit Card from Vault", CreditCard.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,652 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/RefundCaptureServlet.java | // #RefundCapture Sample
// This sample code demonstrate how you
// can do a Refund on a Capture
// resource
// API used: /v1/payments/capture/{capture_id}/refund
package com.paypal.api.payments.servlet;
import com.paypal.api.payments.*;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.apache.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.paypal.api.payments.util.SampleConstants.*;
public class RefundCaptureServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetAuthorizationServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##RefundCapture
// Sample showing to how to do a Refund on
// a Capture
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
/// ###Capture
// Create a Capture object
// by doing a capture on
// Authorization object
// and retrieve the Id
String captureId = "<your capture id here>";
// Retrieve the Capture object by
// doing a GET call to
// URI v1/payments/capture/{capture_id}
Capture capture = Capture.get(apiContext, captureId);
/// ###Refund
/// Create a Refund object
RefundRequest refund = new RefundRequest();
// ###Amount
// Let's you specify a capture amount.
Amount amount = new Amount();
amount.setCurrency("USD").setTotal("1");
refund.setAmount(amount);
// Do a Refund by
// POSTing to
// URI v1/payments/capture/{capture_id}/refund
Refund responseRefund = capture.refund(apiContext, refund);
LOGGER.info("Refund id = " + responseRefund.getId()
+ " and status = " + responseRefund.getState());
ResultPrinter.addResult(req, resp, "Refund a Capture", Refund.getLastRequest(), Refund.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Refund a Capture", Refund.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
private Capture getCapture(APIContext apiContext, Authorization authorization) throws PayPalRESTException{
// ###Amount
// Let's you specify a capture amount.
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal("4.54");
// ###Capture
Capture capture = new Capture();
capture.setAmount(amount);
// ##IsFinalCapture
// If set to true, all remaining
// funds held by the authorization
// will be released in the funding
// instrument. Default is �false�.
capture.setIsFinalCapture(true);
// Capture by POSTing to
// URI v1/payments/authorization/{authorization_id}/capture
Capture responseCapture = authorization.capture(apiContext, capture);
return responseCapture;
}
private Authorization getAuthorization(APIContext apiContext)
throws PayPalRESTException {
// ###Details
// Let's you specify details of a payment amount.
Details details = new Details();
details.setShipping("0.03");
details.setSubtotal("107.41");
details.setTax("0.03");
// ###Amount
// Let's you specify a payment amount.
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal("107.47");
amount.setDetails(details);
// ###Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction
.setDescription("This is the payment transaction description.");
// The Payment creation API requires a list of
// Transaction; add the created `Transaction`
// to a List
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
// ###Address
// Base Address object used as shipping or billing
// address in a payment. [Optional]
Address billingAddress = new Address();
billingAddress.setCity("Johnstown");
billingAddress.setCountryCode("US");
billingAddress.setLine1("52 N Main ST");
billingAddress.setPostalCode("43210");
billingAddress.setState("OH");
// ###CreditCard
// A resource representing a credit card that can be
// used to fund a payment.
CreditCard creditCard = new CreditCard();
creditCard.setBillingAddress(billingAddress);
creditCard.setCvv2(874);
creditCard.setExpireMonth(11);
creditCard.setExpireYear(2018);
creditCard.setFirstName("Joe");
creditCard.setLastName("Shopper");
creditCard.setNumber("4669424246660779");
creditCard.setType("visa");
// ###FundingInstrument
// A resource representing a Payeer's funding instrument.
// Use a Payer ID (A unique identifier of the payer generated
// and provided by the facilitator. This is required when
// creating or using a tokenized funding instrument)
// and the `CreditCardDetails`
FundingInstrument fundingInstrument = new FundingInstrument();
fundingInstrument.setCreditCard(creditCard);
// The Payment creation API requires a list of
// FundingInstrument; add the created `FundingInstrument`
// to a List
List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>();
fundingInstruments.add(fundingInstrument);
// ###Payer
// A resource representing a Payer that funds a payment
// Use the List of `FundingInstrument` and the Payment Method
// as 'credit_card'
Payer payer = new Payer();
payer.setFundingInstruments(fundingInstruments);
payer.setPaymentMethod("credit_card");
// ###Payment
// A Payment Resource; create one using
// the above types and intent as 'authorize'
Payment payment = new Payment();
payment.setIntent("authorize");
payment.setPayer(payer);
payment.setTransactions(transactions);
Payment responsePayment = payment.create(apiContext);
return responsePayment.getTransactions().get(0).getRelatedResources()
.get(0).getAuthorization();
}
}
| 3,653 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/ValidateWebhookServlet.java | // #Validate Webhook Sample
// This is a sample code to demonstrate how to validate a webhook received on your web server.
// This sample assumes you are using java servlet, which returns HttpServletRequest object.
// However, this code can still be easily modified to your specific case.
package com.paypal.api.payments.servlet;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.Event;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.Constants;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.apache.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import static com.paypal.api.payments.util.SampleConstants.*;
public class ValidateWebhookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(ValidateWebhookServlet.class);
public static final String WebhookId = "4JH86294D6297924G";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Validate Webhook
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try{
// ### Api Context
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// Set the webhookId that you received when you created this webhook.
apiContext.addConfiguration(Constants.PAYPAL_WEBHOOK_ID, WebhookId);
Boolean result = Event.validateReceivedEvent(apiContext, getHeadersInfo(req), getBody(req));
System.out.println("Result is " + result);
LOGGER.info("Webhook Validated: "
+ result);
ResultPrinter.addResult(req, resp, "Webhook Validated: ", CreditCard.getLastRequest(), CreditCard.getLastResponse(), null);
} catch (PayPalRESTException e) {
LOGGER.error(e.getMessage());
ResultPrinter.addResult(req, resp, "Webhook Validated: ", CreditCard.getLastRequest(), null, e.getMessage());
} catch (InvalidKeyException e) {
LOGGER.error(e.getMessage());
ResultPrinter.addResult(req, resp, "Webhook Validated: ", CreditCard.getLastRequest(), null, e.getMessage());
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.getMessage());
ResultPrinter.addResult(req, resp, "Webhook Validated: ", CreditCard.getLastRequest(), null, e.getMessage());
} catch (SignatureException e) {
LOGGER.error(e.getMessage());
ResultPrinter.addResult(req, resp, "Webhook Validated: ", CreditCard.getLastRequest(), null, e.getMessage());
}
}
// Simple helper method to help you extract the headers from HttpServletRequest object.
private static Map<String, String> getHeadersInfo(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
@SuppressWarnings("rawtypes")
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
return map;
}
// Simple helper method to fetch request data as a string from HttpServletRequest object.
private static String getBody(HttpServletRequest request) throws IOException {
String body;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
return body;
}
}
| 3,654 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetAuthorizationServlet.java | // #GetAuthorization Sample
// This sample code demonstrate how you
// can retrieve the details of a Authorization
// resource
// API used: /v1/payments/authorization/{id}
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Address;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.FundingInstrument;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetAuthorizationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetAuthorizationServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##GetAuthorization
// Sample showing how to do a Get Authorization
// using Authorization Id
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Authorization
// Retrieve an Authorization Id
// by making a Payment with intent
// as 'authorize' and parsing through
// the Payment object
String authorizationId = "<your authorization id here>";
// Get Authorization by sending
// a GET request with authorization Id
// to the
// URI v1/payments/authorization/{id}
Authorization authorization = Authorization.get(apiContext,
authorizationId);
LOGGER.info("Authorization id = " + authorization.getId()
+ " and status = " + authorization.getState());
ResultPrinter.addResult(req, resp, "Get Authorization", Authorization.getLastRequest(), Authorization.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Get Authorization", Authorization.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,655 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithPayPalServlet.java | // #Create Payment Using PayPal Sample
// This sample code demonstrates how you can process a
// PayPal Account based Payment.
// API used: /v1/payments/payment
package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.Item;
import com.paypal.api.payments.ItemList;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.PaymentExecution;
import com.paypal.api.payments.RedirectUrls;
import com.paypal.api.payments.Transaction;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class PaymentWithPayPalServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(PaymentWithPayPalServlet.class);
Map<String, String> map = new HashMap<String, String>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Create
// Sample showing to create a Payment using PayPal
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
createPayment(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public Payment createPayment(HttpServletRequest req, HttpServletResponse resp) {
Payment createdPayment = null;
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
if (req.getParameter("PayerID") != null) {
Payment payment = new Payment();
if (req.getParameter("guid") != null) {
payment.setId(map.get(req.getParameter("guid")));
}
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(req.getParameter("PayerID"));
try {
createdPayment = payment.execute(apiContext, paymentExecution);
ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), Payment.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), null, e.getMessage());
}
} else {
// ###Details
// Let's you specify details of a payment amount.
Details details = new Details();
details.setShipping("1");
details.setSubtotal("5");
details.setTax("1");
// ###Amount
// Let's you specify a payment amount.
Amount amount = new Amount();
amount.setCurrency("USD");
// Total must be equal to sum of shipping, tax and subtotal.
amount.setTotal("7");
amount.setDetails(details);
// ###Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction
.setDescription("This is the payment transaction description.");
// ### Items
Item item = new Item();
item.setName("Ground Coffee 40 oz").setQuantity("1").setCurrency("USD").setPrice("5");
ItemList itemList = new ItemList();
List<Item> items = new ArrayList<Item>();
items.add(item);
itemList.setItems(items);
transaction.setItemList(itemList);
// The Payment creation API requires a list of
// Transaction; add the created `Transaction`
// to a List
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
// ###Payer
// A resource representing a Payer that funds a payment
// Payment Method
// as 'paypal'
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
// ###Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
// ###Redirect URLs
RedirectUrls redirectUrls = new RedirectUrls();
String guid = UUID.randomUUID().toString().replaceAll("-", "");
redirectUrls.setCancelUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/paymentwithpaypal?guid=" + guid);
redirectUrls.setReturnUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/paymentwithpaypal?guid=" + guid);
payment.setRedirectUrls(redirectUrls);
// Create a payment by posting to the APIService
// using a valid AccessToken
// The return object contains the status;
try {
createdPayment = payment.create(apiContext);
LOGGER.info("Created payment with id = "
+ createdPayment.getId() + " and status = "
+ createdPayment.getState());
// ###Payment Approval Url
Iterator<Links> links = createdPayment.getLinks().iterator();
while (links.hasNext()) {
Links link = links.next();
if (link.getRel().equalsIgnoreCase("approval_url")) {
req.setAttribute("redirectURL", link.getHref());
}
}
ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), Payment.getLastResponse(), null);
map.put(guid, createdPayment.getId());
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), null, e.getMessage());
}
}
return createdPayment;
}
}
| 3,656 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/ReauthorizationServlet.java | package com.paypal.api.payments.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class ReauthorizationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(ReauthorizationServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Reauthorization
// Sample showing how to do a reauthorization
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Reauthorization
// Retrieve a authorization id from authorization object
// by making a `Payment Using PayPal` with intent
// as `authorize`. You can reauthorize a payment only once 4 to 29
// days after 3-day honor period for the original authorization
// expires.
Authorization authorization = Authorization.get(apiContext,
"7GH53639GA425732B");
// ###Amount
// Let's you specify a capture amount.
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal("4.54");
authorization.setAmount(amount);
// Reauthorize by POSTing to
// URI v1/payments/authorization/{authorization_id}/reauthorize
Authorization reauthorization = authorization
.reauthorize(apiContext);
LOGGER.info("Reauthorization id = " + reauthorization.getId()
+ " and status = " + reauthorization.getState());
ResultPrinter.addResult(req, resp, "Reauthorized a Payment", Authorization.getLastRequest(), Authorization.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Reauthorized a Payment", Authorization.getLastRequest(), null, e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
| 3,657 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/util/SampleConstants.java | package com.paypal.api.payments.util;
public class SampleConstants {
public static final String clientID = "AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS";
public static final String clientSecret = "EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL";
public static final String mode = "sandbox";
}
| 3,658 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payments/util/ResultPrinter.java | package com.paypal.api.payments.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResultPrinter {
public static void addResult(HttpServletRequest req, HttpServletResponse resp, String message,
String request, String response, String error) {
addDataToAttributeList(req, "messages", message);
addDataToAttributeList(req, "requests", request);
response = (response != null) ? response : error;
addDataToAttributeList(req, "responses", response);
addDataToAttributeList(req, "errors", error);
if (error != null) {
try {
req.getRequestDispatcher("response.jsp").forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
private static void addDataToAttributeList(HttpServletRequest req,
String listName, String data) {
// Add Messages
List<String> list;
if ((list = (List<String>) req.getAttribute(listName)) == null) {
list = new ArrayList<String>();
}
list.add(data);
req.setAttribute(listName, list);
}
}
| 3,659 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/sample/SubscriptionSample.java | package com.paypal.api.sample;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.paypal.api.payments.ChargeModels;
import com.paypal.api.payments.Currency;
import com.paypal.api.payments.MerchantPreferences;
import com.paypal.api.payments.Patch;
import com.paypal.api.payments.PaymentDefinition;
import com.paypal.api.payments.Plan;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class SubscriptionSample{
public static final String clientID = "AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS";
public static final String clientSecret = "EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL";
protected Plan instance = null;
/**
* Create a plan.
*
* https://developer.paypal.com/webapps/developer/docs/api/#create-a-plan
*
* @return newly created Plan instance
* @throws PayPalRESTException
*/
public Plan create(APIContext context) throws PayPalRESTException, IOException {
// Build Plan object
Plan plan = new Plan();
plan.setName("T-Shirt of the Month Club Plan");
plan.setDescription("Template creation.");
plan.setType("fixed");
//payment_definitions
PaymentDefinition paymentDefinition = new PaymentDefinition();
paymentDefinition.setName("Regular Payments");
paymentDefinition.setType("REGULAR");
paymentDefinition.setFrequency("MONTH");
paymentDefinition.setFrequencyInterval("1");
paymentDefinition.setCycles("12");
//currency
Currency currency = new Currency();
currency.setCurrency("USD");
currency.setValue("20");
paymentDefinition.setAmount(currency);
//charge_models
ChargeModels chargeModels = new com.paypal.api.payments.ChargeModels();
chargeModels.setType("SHIPPING");
chargeModels.setAmount(currency);
List<ChargeModels> chargeModelsList = new ArrayList<ChargeModels>();
chargeModelsList.add(chargeModels);
paymentDefinition.setChargeModels(chargeModelsList);
//payment_definition
List<PaymentDefinition> paymentDefinitionList = new ArrayList<PaymentDefinition>();
paymentDefinitionList.add(paymentDefinition);
plan.setPaymentDefinitions(paymentDefinitionList);
//merchant_preferences
MerchantPreferences merchantPreferences = new MerchantPreferences();
merchantPreferences.setSetupFee(currency);
merchantPreferences.setCancelUrl("http://www.cancel.com");
merchantPreferences.setReturnUrl("http://www.return.com");
merchantPreferences.setMaxFailAttempts("0");
merchantPreferences.setAutoBillAmount("YES");
merchantPreferences.setInitialFailAmountAction("CONTINUE");
plan.setMerchantPreferences(merchantPreferences);
this.instance = plan.create(context);
return this.instance;
}
/**
* Update a plan
*
* https://developer.paypal.com/webapps/developer/docs/api/#update-a-plan
*
* @return updated Plan instance
* @throws PayPalRESTException
*/
public Plan update(APIContext context) throws PayPalRESTException, IOException {
List<Patch> patchRequestList = new ArrayList<Patch>();
Map<String, String> value = new HashMap<String, String>();
value.put("state", "ACTIVE");
Patch patch = new Patch();
patch.setPath("/");
patch.setValue(value);
patch.setOp("replace");
patchRequestList.add(patch);
this.instance.update(context, patchRequestList);
return this.instance;
}
/**
* Retrieve a plan
*
* https://developer.paypal.com/webapps/developer/docs/api/#retrieve-a-plan
*
* @return the retrieved plan
* @throws PayPalRESTException
*/
public Plan retrieve(APIContext context) throws PayPalRESTException {
return Plan.get(context, this.instance.getId());
}
/**
* Main method that calls all methods above in a flow.
*
* @param args
*/
public static void main(String[] args) {
try {
SubscriptionSample subscriptionSample = new SubscriptionSample();
APIContext context = new APIContext(clientID, clientSecret, "sandbox");
subscriptionSample.create(context);
System.out.println("create response:\n" + Plan.getLastResponse());
subscriptionSample.update(context);
System.out.println("plan updated");
subscriptionSample.retrieve(context);
System.out.println("retrieve response:\n" + Plan.getLastResponse());
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (JsonIOException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (PayPalRESTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 3,660 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/sample/InvoiceTemplateSample.java | package com.paypal.api.sample;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.paypal.api.payments.Template;
import com.paypal.api.payments.Templates;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
/**
* This class shows code samples for invoicing templates.
*
* https://developer.paypal.com/webapps/developer/docs/api/#invoicing
*
*/
public class InvoiceTemplateSample extends SampleBase<Template> {
public static final String clientID = "AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS";
public static final String clientSecret = "EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL";
/**
* Initialize and instantiate an Invoice object
* @throws PayPalRESTException
* @throws JsonSyntaxException
* @throws JsonIOException
* @throws FileNotFoundException
*/
public InvoiceTemplateSample() throws PayPalRESTException, JsonSyntaxException,
JsonIOException, FileNotFoundException {
super(new Template());
}
/**
* Create an invoice template
*
* https://developer.paypal.com/docs/api/invoicing/#templates
*
* @return newly created Invoice Template instance
* @throws PayPalRESTException
*/
public Template create(APIContext context) throws PayPalRESTException, IOException {
// populate Invoice object that we are going to play with
super.instance = load("template_create.json", Template.class);
// Make sure the Name of Invoice is unique.
super.instance.setName("Sample-" + UUID.randomUUID().toString());
try {
super.instance = super.instance.create(context);
} catch (PayPalRESTException ex) {
if (ex.getResponsecode() == 400 && ex.getDetails().getMessage().contains("Exceed maximum number")) {
// This could be because we have reached the maximum number of templates possible per app.
Templates templates = Template.getAll(context);
for (Template template: templates.getTemplates()) {
if (!template.getIsDefault()) {
try {
template.delete(context);
} catch (Exception e) {
// We tried our best. We will continue.
continue;
}
}
}
super.instance = super.instance.create(context);
}
}
return super.instance;
}
/**
* Update an invoice template
*
* https://developer.paypal.com/docs/api/invoicing/#templates
*
* @return updated Invoice template instance
* @throws PayPalRESTException
*/
public Template update(APIContext context) throws PayPalRESTException, IOException {
String id = super.instance.getTemplateId();
super.instance = load("template_update.json", Template.class);
super.instance.setTemplateId(id);
// There is an existing issue when you need to manually remove `custom` settings during update,
// if you are using the object returned from GET invoice.
// For internal tracking purpose only: #PPPLCONSMR-39127
super.instance.setCustom(null);
// Changing the note to some random value
super.instance.getTemplateData().setNote(UUID.randomUUID().toString().substring(0, 5));
super.instance = super.instance.update(context);
return super.instance;
}
/**
* Deletes a template
*
* https://developer.paypal.com/docs/api/invoicing/#templates
*
* @param context
* @throws PayPalRESTException
*/
public void delete(APIContext context) throws PayPalRESTException {
this.instance.delete(context);
}
/**
* Main method that calls all methods above in a flow.
*
* @param args
*/
public static void main(String[] args) {
try {
InvoiceTemplateSample invoiceSample = new InvoiceTemplateSample();
APIContext context = new APIContext(clientID, clientSecret, "sandbox");
Template template = invoiceSample.create(context);
System.out.println("create response:\n" + Template.getLastResponse());
Template.get(context, template.getTemplateId());
System.out.println("get response:\n" + Template.getLastResponse());
invoiceSample.update(context);
System.out.println("update response:\n" + Template.getLastResponse());
invoiceSample.delete(context);
System.out.println("delete response:\n" + Template.getLastResponse());
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (JsonIOException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (PayPalRESTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 3,661 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/sample/SampleBase.java | package com.paypal.api.sample;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.paypal.base.rest.JSONFormatter;
import com.paypal.base.rest.PayPalRESTException;
public class SampleBase<T> {
protected T instance = null;
/**
* Initialize sample base
*
* @throws PayPalRESTException
* @throws JsonSyntaxException
* @throws JsonIOException
* @throws FileNotFoundException
*/
public SampleBase(T instance) throws PayPalRESTException, JsonSyntaxException,
JsonIOException, FileNotFoundException {
this.instance = instance;
}
protected <C> C load(String jsonFile, Class<C> clazz) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(
getClass().getClassLoader().getResource(jsonFile).getFile())));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
line = br.readLine();
}
return (C)JSONFormatter.fromJSON(sb.toString(), clazz);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| 3,662 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/sample/FuturePaymentSample.java | package com.paypal.api.sample;
import java.util.ArrayList;
import java.util.List;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.FuturePayment;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import com.paypal.base.rest.APIContext;
public class FuturePaymentSample {
public static final String clientID = "AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS";
public static final String clientSecret = "EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL";
public static void main(String[] args) {
try {
// Authorization Code and Co-relationID retrieved from Mobile SDK.
String authorizationCode = "C101.Rya9US0s60jg-hOTMNFRTjDfbePYv3W_YjDJ49BVI6YJY80HvjL1C6apK8h3IIas.ZWOGll_Ju62T9SXRSRFHZVwZESK";
String correlationId = "123456123";
APIContext context = new APIContext(clientID, clientSecret, "sandbox");
// Fetch the long lived refresh token from authorization code.
String refreshToken = FuturePayment.fetchRefreshToken(context, authorizationCode);
// Store the refresh token in long term storage for future use.
// Set the refresh token to context to make future payments of
// pre-consented customer.
context.setRefreshToken(refreshToken);
// Create Payment Object
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
Amount amount = new Amount();
amount.setTotal("0.17");
amount.setCurrency("USD");
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction.setDescription("This is the payment tranasction description.");
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
FuturePayment futurePayment = new FuturePayment();
futurePayment.setIntent("authorize");
futurePayment.setPayer(payer);
futurePayment.setTransactions(transactions);
Payment createdPayment = futurePayment.create(context, correlationId);
System.out.println(createdPayment.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println(Payment.getLastRequest());
System.out.println(Payment.getLastResponse());
}
}
}
| 3,663 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/sample/ThirdPartyInvoice.java | package com.paypal.api.sample;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.paypal.api.payments.Invoice;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class ThirdPartyInvoice extends SampleBase<Invoice> {
public static final String clientID = "AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS";
public static final String clientSecret = "EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL";
private static final Logger log = LogManager.getLogger(ThirdPartyInvoice.class);
/**
* Initialize and instantiate an Invoice object
*
* @throws PayPalRESTException
* @throws JsonSyntaxException
* @throws JsonIOException
* @throws FileNotFoundException
*/
public ThirdPartyInvoice() throws PayPalRESTException, JsonSyntaxException, JsonIOException, FileNotFoundException {
super(new Invoice());
}
/**
* Create an invoice.
*
* https://developer.paypal.com/webapps/developer/docs/api/#create-an-
* invoice
*
* @return newly created Invoice instance
* @throws PayPalRESTException
*/
public Invoice create(APIContext context) throws PayPalRESTException, FileNotFoundException, IOException {
// populate Invoice object that we are going to play with
super.instance = load("invoice_create.json", Invoice.class);
super.instance.getMerchantInfo().setEmail("developer@sample.com");
super.instance = super.instance.create(context);
return super.instance;
}
public Invoice send(Invoice invoice, APIContext context) throws PayPalRESTException {
invoice.send(context);
return Invoice.get(context, invoice.getId());
}
public static void main(String[] args) {
try {
// Authorization Code and Co-RelationID retrieved from Mobile SDK.
String authorizationCode = "UdL0ZFrrevCFtvXHUwQNhpyboVu0qE6Lv1I6VU7TXrKPfOpvExYKVbI6iFs-AYhmMZVEWgdPXpaHD2nsv0ypk8riEgkpj-dXmmpfi_Ud9dGRt65uraIb9rKCqXpuUBNc2WbM1P8-CaOj5M6FxK_6sUh2nveShf66ZUj_fsuu1TrLTTY8";
APIContext context = new APIContext(clientID, clientSecret, "sandbox");
// Fetch the long lived refresh token from authorization code.
String refreshToken = Invoice.fetchRefreshToken(context, authorizationCode);
// Store the refresh token in long term storage for future use.
// Set the refresh token to context to create invoice on third party merchant's behalf
context.setRefreshToken(refreshToken);
ThirdPartyInvoice fps = new ThirdPartyInvoice();
log.info("creating third party invoice using refresh token " + refreshToken);
// This will create an invoice for `developer@sample.com` merchant
// whose refresh token it is.
Invoice invoice = fps.create(context);
System.out.println(Invoice.getLastRequest());
System.out.println(Invoice.getLastResponse());
invoice = fps.send(invoice, context);
System.out.println(Invoice.getLastRequest());
System.out.println(Invoice.getLastResponse());
} catch (Exception e) {
e.printStackTrace();
System.out.println(Payment.getLastRequest());
System.out.println(Payment.getLastResponse());
}
}
}
| 3,664 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/sample/ValidateCert.java | package com.paypal.api.sample;
import com.paypal.api.payments.Event;
import com.paypal.base.Constants;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;
import static com.paypal.api.payments.util.SampleConstants.*;
public class ValidateCert {
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException {
// ### Api Context
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// Set the webhook Id you were given back when you created the webhook for these events.
apiContext.addConfiguration(Constants.PAYPAL_WEBHOOK_ID, "3RN13029J36659323");
// THIS IS MOCK DATA. All the below informatio would be retrieved originally from the webhook. This is a data for sample purpose only.
Map<String, String> headers = new HashMap<String, String>();
headers.put(Constants.PAYPAL_HEADER_CERT_URL, "https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-a5cafa77");
headers.put(Constants.PAYPAL_HEADER_TRANSMISSION_ID, "b2384410-f8d2-11e4-8bf3-77339302725b");
headers.put(Constants.PAYPAL_HEADER_TRANSMISSION_TIME, "2015-05-12T18:14:14Z");
headers.put(Constants.PAYPAL_HEADER_AUTH_ALGO, "SHA256withRSA");
headers.put(Constants.PAYPAL_HEADER_TRANSMISSION_SIG, "vSOIQFIZQHv8G2vpbOpD/4fSC4/MYhdHyv+AmgJyeJQq6q5avWyHIe/zL6qO5hle192HSqKbYveLoFXGJun2od2zXN3Q45VBXwdX3woXYGaNq532flAtiYin+tQ/0pNwRDsVIufCxa3a8HskaXy+YEfXNnwCSL287esD3HgOHmuAs0mYKQdbR4e8Evk8XOOQaZzGeV7GNXXz19gzzvyHbsbHmDz5VoRl9so5OoHqvnc5RtgjZfG8KA9lXh2MTPSbtdTLQb9ikKYnOGM+FasFMxk5stJisgmxaefpO9Q1qm3rCjaJ29aAOyDNr3Q7WkeN3w4bSXtFMwyRBOF28pJg9g==");
String requestBody = "{\"id\":\"WH-2W7266712B616591M-36507203HX6402335\",\"create_time\":\"2015-05-12T18:14:14Z\",\"resource_type\":\"sale\",\"event_type\":\"PAYMENT.SALE.COMPLETED\",\"summary\":\"Payment completed for $ 20.0 USD\",\"resource\":{\"id\":\"7DW85331GX749735N\",\"create_time\":\"2015-05-12T18:13:18Z\",\"update_time\":\"2015-05-12T18:13:36Z\",\"amount\":{\"total\":\"20.00\",\"currency\":\"USD\"},\"payment_mode\":\"INSTANT_TRANSFER\",\"state\":\"completed\",\"protection_eligibility\":\"ELIGIBLE\",\"protection_eligibility_type\":\"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE\",\"parent_payment\":\"PAY-1A142943SV880364LKVJEFPQ\",\"transaction_fee\":{\"value\":\"0.88\",\"currency\":\"USD\"},\"links\":[{\"href\":\"https://api.sandbox.paypal.com/v1/payments/sale/7DW85331GX749735N\",\"rel\":\"self\",\"method\":\"GET\"},{\"href\":\"https://api.sandbox.paypal.com/v1/payments/sale/7DW85331GX749735N/refund\",\"rel\":\"refund\",\"method\":\"POST\"},{\"href\":\"https://api.sandbox.paypal.com/v1/payments/payment/PAY-1A142943SV880364LKVJEFPQ\",\"rel\":\"parent_payment\",\"method\":\"GET\"}]},\"links\":[{\"href\":\"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2W7266712B616591M-36507203HX6402335\",\"rel\":\"self\",\"method\":\"GET\"},{\"href\":\"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2W7266712B616591M-36507203HX6402335/resend\",\"rel\":\"resend\",\"method\":\"POST\"}]}";
try {
System.out.println(Event.validateReceivedEvent(apiContext, headers, requestBody));
} catch (PayPalRESTException e) {
e.printStackTrace();
}
}
}
| 3,665 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/sample/InvoiceSample.java | package com.paypal.api.sample;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.paypal.api.payments.CancelNotification;
import com.paypal.api.payments.Image;
import com.paypal.api.payments.Invoice;
import com.paypal.api.payments.Invoices;
import com.paypal.api.payments.Notification;
import com.paypal.api.payments.Search;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
/**
* This class shows code samples for invoicing.
* l
* https://developer.paypal.com/webapps/developer/docs/api/#invoicing
*
*/
public class InvoiceSample extends SampleBase<Invoice> {
public static final String clientID = "AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS";
public static final String clientSecret = "EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL";
/**
* Initialize and instantiate an Invoice object
* @throws PayPalRESTException
* @throws JsonSyntaxException
* @throws JsonIOException
* @throws FileNotFoundException
*/
public InvoiceSample() throws PayPalRESTException, JsonSyntaxException,
JsonIOException, FileNotFoundException {
super(new Invoice());
}
/**
* Create an invoice.
*
* https://developer.paypal.com/webapps/developer/docs/api/#create-an-invoice
*
* @return newly created Invoice instance
* @throws PayPalRESTException
*/
public Invoice create(APIContext context) throws PayPalRESTException, IOException {
// populate Invoice object that we are going to play with
super.instance = load("invoice_create.json", Invoice.class);
super.instance = super.instance.create(context);
return super.instance;
}
/**
* Send an invoice.
*
* https://developer.paypal.com/webapps/developer/docs/api/#send-an-invoice
*
* @throws PayPalRESTException
*/
public void send(APIContext context) throws PayPalRESTException {
super.instance.send(context);
}
/**
* Update an invoice.
*
* https://developer.paypal.com/webapps/developer/docs/api/#update-an-invoice
*
* @return updated Invoice instance
* @throws PayPalRESTException
*/
public Invoice update(APIContext context) throws PayPalRESTException, IOException {
String id = super.instance.getId();
super.instance = load("invoice_update.json", Invoice.class);
super.instance.setId(id);
// Changing the number of invoice to some random value
super.instance.setNumber(UUID.randomUUID().toString().substring(0, 5));
super.instance = super.instance.update(context);
return super.instance;
}
/**
* Retrieve an invoice.
*
* https://developer.paypal.com/webapps/developer/docs/api/#retrieve-an-invoice
*
* @return retrieved Invoice instance
* @throws PayPalRESTException
*/
public Invoice retrieve(APIContext context) throws PayPalRESTException {
super.instance = Invoice.get(context, super.instance.getId());
return super.instance;
}
/**
* Get invoices of an merchant.
*
* https://developer.paypal.com/webapps/developer/docs/api/#get-invoices-of-a-merchant
*
* @return Invoices instance that contains invoices for merchant
* @throws PayPalRESTException
*/
public Invoices getMerchantInvoices(APIContext context) throws PayPalRESTException {
// Lets add some options.
Map<String, String> options = new HashMap<String, String>() {{
put("total_count_required", "true");
}};
return Invoice.getAll(context, options);
}
/**
* Search for invoices.
*
* https://developer.paypal.com/webapps/developer/docs/api/#search-for-invoices
*
* @return Invoices instance that contains found invoices
* @throws PayPalRESTException
*/
public Invoices search(APIContext context) throws PayPalRESTException {
Search search = new Search();
search.setStartInvoiceDate("2010-05-10 PST");
search.setEndInvoiceDate("2014-04-10 PST");
search.setPage(1);
search.setPageSize(20);
search.setTotalCountRequired(true);
return super.instance.search(context, search);
}
/**
* Send an invoice reminder.
*
* https://developer.paypal.com/webapps/developer/docs/api/#send-an-invoice-reminder
*
* @throws PayPalRESTException
*/
public void sendReminder(APIContext context) throws PayPalRESTException {
Notification notification = new Notification();
notification.setSubject("Past due");
notification.setNote("Please pay soon");
notification.setSendToMerchant(true);
super.instance.remind(context, notification);
}
/**
* Cancel an invoice.
*
* https://developer.paypal.com/webapps/developer/docs/api/#cancel-an-invoice
*
* @throws PayPalRESTException
*/
public void cancel(APIContext context) throws PayPalRESTException {
CancelNotification cancelNotification = new CancelNotification();
cancelNotification.setSubject("Past due");
cancelNotification.setNote("Canceling invoice");
cancelNotification.setSendToMerchant(true);
cancelNotification.setSendToPayer(true);
super.instance.cancel(context, cancelNotification);
}
/**
* Delete an invoice.
*
* https://developer.paypal.com/webapps/developer/docs/api/#delete-an-invoice
*
* @throws PayPalRESTException
*/
public void delete(APIContext context) throws PayPalRESTException, IOException {
Invoice newInvoice = this.create(context);
newInvoice.delete(context);
}
/**
* Gets a QR Code Image object.
* @param context {@link APIContext}
* @return Image
* @throws PayPalRESTException
* @throws IOException
*/
public Image getQRCode(APIContext context) throws PayPalRESTException, IOException {
//Lets add some options. These are optional, but added for demo purposes.
Map<String, String> options = new HashMap<String, String>() {{
put("width", "400");
put("height", "350");
}};
// Replace the given Id with your invoice Id.
Image image = Invoice.qrCode(context, super.instance.getId(), options);
// You can also save the image to file as shown here.
image.saveToFile("invoice.png");
return image;
}
/**
* Main method that calls all methods above in a flow.
*
* @param args
*/
public static void main(String[] args) {
try {
InvoiceSample invoiceSample = new InvoiceSample();
APIContext context = new APIContext(clientID, clientSecret, "sandbox");
invoiceSample.create(context);
System.out.println("create response:\n" + Invoice.getLastResponse());
invoiceSample.update(context);
System.out.println("update response:\n" + Invoice.getLastResponse());
invoiceSample.send(context);
System.out.println("send response:\n" + Invoice.getLastResponse());
invoiceSample.getQRCode(context);
invoiceSample.retrieve(context);
System.out.println("retrieve response:\n" + Invoice.getLastResponse());
invoiceSample.getMerchantInvoices(context);
System.out.println("getall response:\n" + Invoice.getLastResponse());
invoiceSample.search(context);
System.out.println("search response:\n" + Invoice.getLastResponse());
invoiceSample.sendReminder(context);
System.out.println("remind response:\n" + Invoice.getLastResponse());
invoiceSample.cancel(context);
System.out.println("cancel response:\n" + Invoice.getLastResponse());
invoiceSample.delete(context);
System.out.println("delete response:\n" + Invoice.getLastResponse());
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (JsonIOException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (PayPalRESTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 3,666 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts/servlet/CancelPayoutItemServlet.java | // #Cancel Unclaimed Payout
// Use this call to cancel an existing, unclaimed transaction. If an unclaimed item is not claimed within 30 days, the funds will be automatically returned to the sender.
// This call can be used to cancel the unclaimed item prior to the automatic 30-day return.
// API used: POST /v1/payments/payouts-item/<Payout-Item-Id>/cancel
package com.paypal.api.payouts.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.PayoutBatch;
import com.paypal.api.payments.PayoutItem;
import com.paypal.api.payments.PayoutItemDetails;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class CancelPayoutItemServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(CancelPayoutItemServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Get Payout Item Status
// Sample showing how to get a Payout Item Status
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
cancelPayoutItem(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public PayoutItemDetails cancelPayoutItem(HttpServletRequest req,
HttpServletResponse resp) {
// ### Get a Payout Batch
// We are re-using the CreateSinglePayoutServlet to get a batch payout
// for us. This will make sure the samples will work all the time.
CreateSinglePayoutServlet servlet = new CreateSinglePayoutServlet();
PayoutBatch batch = servlet.createSynchronousSinglePayout(req, resp);
// ### Retrieve PayoutItem ID
// In the samples, we are extractingt he payoutItemId of a payout we
// just created.
// In reality, you might be using the payoutItemId stored in your
// database, or passed manually.
PayoutItemDetails itemDetails = batch.getItems().get(0);
String payoutItemId = itemDetails.getPayoutItemId();
// Initiate the response object
PayoutItemDetails response = null;
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Cancel Payout Item if it is unclaimed
if (itemDetails.getTransactionStatus().equalsIgnoreCase("UNCLAIMED")) {
response = PayoutItem.cancel(apiContext, payoutItemId);
LOGGER.info("Payout Item With ID: "
+ response.getPayoutItemId());
ResultPrinter.addResult(req, resp, "Cancelled Unclaimed Payout Item",
PayoutItem.getLastRequest(),
PayoutItem.getLastResponse(), null);
} else {
LOGGER.info("Payout Item needs to be Unclaimed");
ResultPrinter.addResult(req, resp, "Cancelled Unclaimed Payout Item",
null,
null, "Payout Item needs to be Unclaimed");
}
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Cancelled Unclaimed Payout Item",
PayoutItem.getLastRequest(), null, e.getMessage());
}
return response;
}
}
| 3,667 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts/servlet/CreateSinglePayoutServlet.java | // #Create Single Payout
// You can make payouts to multiple PayPal accounts or to a single PayPal account.
// If you are submitting a single payout, you can make a synchronous payout call, which immediately returns the results of the payout.
// In a synchronous payout call, the response is similar to a batch payout status response.
// To make a synchronous payout, specify sync_mode=true in the URL: /v1/payments/payouts?sync_mode=true
// API used: POST /v1/payments/payouts
package com.paypal.api.payouts.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Currency;
import com.paypal.api.payments.Payout;
import com.paypal.api.payments.PayoutBatch;
import com.paypal.api.payments.PayoutItem;
import com.paypal.api.payments.PayoutSenderBatchHeader;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class CreateSinglePayoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(CreateSinglePayoutServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Create
// Sample showing how to create a Single Payout with Synchronous Mode.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
createSynchronousSinglePayout(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public PayoutBatch createSynchronousSinglePayout(HttpServletRequest req,
HttpServletResponse resp) {
// ###Payout
// A resource representing a payout
Payout payout = new Payout();
PayoutSenderBatchHeader senderBatchHeader = new PayoutSenderBatchHeader();
// ### NOTE:
// You can prevent duplicate batches from being processed. If you
// specify a `sender_batch_id` that was used in the last 30 days, the
// batch will not be processed. For items, you can specify a
// `sender_item_id`. If the value for the `sender_item_id` is a
// duplicate of a payout item that was processed in the last 30 days,
// the item will not be processed.
// #### Batch Header Instance
Random random = new Random();
senderBatchHeader.setSenderBatchId(
new Double(random.nextDouble()).toString()).setEmailSubject(
"You have a Payout!");
// ### Currency
Currency amount = new Currency();
amount.setValue("1.00").setCurrency("USD");
// #### Sender Item
// Please note that if you are using single payout with sync mode, you
// can only pass one Item in the request
PayoutItem senderItem = new PayoutItem();
senderItem.setRecipientType("Email")
.setNote("Thanks for your patronage")
.setReceiver("shirt-supplier-one@gmail.com")
.setSenderItemId("201404324234").setAmount(amount);
List<PayoutItem> items = new ArrayList<PayoutItem>();
items.add(senderItem);
payout.setSenderBatchHeader(senderBatchHeader).setItems(items);
PayoutBatch batch = null;
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Create Payout Synchronous
batch = payout.createSynchronous(apiContext);
LOGGER.info("Payout Batch With ID: "
+ batch.getBatchHeader().getPayoutBatchId());
ResultPrinter.addResult(req, resp,
"Created Single Synchronous Payout",
Payout.getLastRequest(), Payout.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp,
"Created Single Synchronous Payout",
Payout.getLastRequest(), null, e.getMessage());
}
return batch;
}
}
| 3,668 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts/servlet/GetPayoutBatchStatusServlet.java | // #Get Payout Batch Status
// This call can be used to periodically to get the latest status of a batch, along with the transaction status and other data for individual items.
// API used: GET /v1/payments/payouts/<Payout-Batch-Id>
package com.paypal.api.payouts.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Payout;
import com.paypal.api.payments.PayoutBatch;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetPayoutBatchStatusServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetPayoutBatchStatusServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##GetPayoutBatchStatus
// Sample showing how to get a Payout Batch Status
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
getPayoutBatchStatus(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public PayoutBatch getPayoutBatchStatus(HttpServletRequest req,
HttpServletResponse resp) {
// ### Create a Payout Batch
// We are re-using the CreateBatchPayoutServlet to create a batch payout
// for us. This will make sure the samples will work all the time.
CreateBatchPayoutServlet servlet = new CreateBatchPayoutServlet();
PayoutBatch batch = servlet.createBatchPayout(req, resp);
String payoutBatchId = batch.getBatchHeader().getPayoutBatchId();
PayoutBatch response = null;
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Get Payout Batch Status
response = Payout.get(apiContext, payoutBatchId);
LOGGER.info("Payout Batch With ID: "
+ response.getBatchHeader().getPayoutBatchId());
ResultPrinter.addResult(req, resp, "Get Payout Batch Status",
Payout.getLastRequest(), Payout.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Get Payout Batch Status",
Payout.getLastRequest(), null, e.getMessage());
}
return response;
}
}
| 3,669 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts/servlet/CreateBatchPayoutServlet.java | // #Create Batch Payout
// The asynchronous payout mode (sync_mode=false, which is the default) enables a maximum of 500 individual payouts to be specified in one API call.
// Exceeding 500 payouts in one call returns an HTTP response message with status code 400 (Bad Request).
// API used: POST /v1/payments/payouts
package com.paypal.api.payouts.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Currency;
import com.paypal.api.payments.Payout;
import com.paypal.api.payments.PayoutBatch;
import com.paypal.api.payments.PayoutItem;
import com.paypal.api.payments.PayoutSenderBatchHeader;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class CreateBatchPayoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(CreateBatchPayoutServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Create
// Sample showing how to create a Single Payout with Synchronous Mode.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
createBatchPayout(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public PayoutBatch createBatchPayout(HttpServletRequest req,
HttpServletResponse resp) {
// ###Payout
// A resource representing a payout
// This is how our body should look like:
/*
* { "sender_batch_header": { "sender_batch_id": "random_uniq_id",
* "email_subject": "You have a payment" }, "items": [ {
* "recipient_type": "EMAIL", "amount": { "value": 0.99, "currency":
* "USD" }, "receiver": "shirt-supplier-one@mail.com", "note":
* "Thank you.", "sender_item_id": "item_1" }, { "recipient_type":
* "EMAIL", "amount": { "value": 0.90, "currency": "USD" }, "receiver":
* "shirt-supplier-two@mail.com", "note": "Thank you.",
* "sender_item_id": "item_2" }, { "recipient_type": "EMAIL", "amount":
* { "value": 2.00, "currency": "USD" }, "receiver":
* "shirt-supplier-three@mail.com", "note": "Thank you.",
* "sender_item_id": "item_3" } ] }
*/
Payout payout = new Payout();
PayoutSenderBatchHeader senderBatchHeader = new PayoutSenderBatchHeader();
// ### NOTE:
// You can prevent duplicate batches from being processed. If you
// specify a `sender_batch_id` that was used in the last 30 days, the
// batch will not be processed. For items, you can specify a
// `sender_item_id`. If the value for the `sender_item_id` is a
// duplicate of a payout item that was processed in the last 30 days,
// the item will not be processed.
// #### Batch Header Instance
Random random = new Random();
senderBatchHeader.setSenderBatchId(
new Double(random.nextDouble()).toString()).setEmailSubject(
"You have a Payment!");
// ### Currency
Currency amount1 = new Currency();
amount1.setValue("1.00").setCurrency("USD");
// ### Currency
Currency amount2 = new Currency();
amount2.setValue("2.00").setCurrency("USD");
// ### Currency
Currency amount3 = new Currency();
amount3.setValue("4.00").setCurrency("USD");
// #### Sender Item 1
// Please note that if you are using single payout with sync mode, you
// can only pass one Item in the request
PayoutItem senderItem1 = new PayoutItem();
senderItem1.setRecipientType("Email")
.setNote("Thanks for your patronage")
.setReceiver("shirt-supplier-one@gmail.com")
.setSenderItemId("201404324234").setAmount(amount1);
// #### Sender Item 1
// Please note that if you are using single payout with sync mode, you
// can only pass one Item in the request
PayoutItem senderItem2 = new PayoutItem();
senderItem2.setRecipientType("Email")
.setNote("Thanks for your patronage")
.setReceiver("shirt-supplier-two@gmail.com")
.setSenderItemId("201404324235").setAmount(amount2);
// #### Sender Item 1
// Please note that if you are using single payout with sync mode, you
// can only pass one Item in the request
PayoutItem senderItem3 = new PayoutItem();
senderItem3.setRecipientType("Email")
.setNote("Thanks for your patronage")
.setReceiver("shirt-supplier-three@gmail.com")
.setSenderItemId("201404324236").setAmount(amount3);
List<PayoutItem> items = new ArrayList<PayoutItem>();
items.add(senderItem1);
items.add(senderItem2);
items.add(senderItem3);
payout.setSenderBatchHeader(senderBatchHeader).setItems(items);
PayoutBatch batch = null;
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Create Batch Payout
batch = payout.create(apiContext, new HashMap<String, String>());
LOGGER.info("Payout Batch With ID: "
+ batch.getBatchHeader().getPayoutBatchId());
ResultPrinter.addResult(req, resp, "Payout Batch Create",
Payout.getLastRequest(), Payout.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Payout Batch Create",
Payout.getLastRequest(), null, e.getMessage());
}
return batch;
}
}
| 3,670 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts | Create_ds/PayPal-Java-SDK/rest-api-sample/src/main/java/com/paypal/api/payouts/servlet/GetPayoutItemStatusServlet.java | // #Get Payout Item Status
// Use this call to get data about a payout item, including the status, without retrieving an entire batch.
// You can get the status of an individual payout item in a batch in order to review the current status of a previously-unclaimed, or pending, payout item.
// API used: GET /v1/payments/payouts-item/<Payout-Item-Id>
package com.paypal.api.payouts.servlet;
import static com.paypal.api.payments.util.SampleConstants.clientID;
import static com.paypal.api.payments.util.SampleConstants.clientSecret;
import static com.paypal.api.payments.util.SampleConstants.mode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.PayoutBatch;
import com.paypal.api.payments.PayoutItem;
import com.paypal.api.payments.PayoutItemDetails;
import com.paypal.api.payments.util.ResultPrinter;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
public class GetPayoutItemStatusServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetPayoutItemStatusServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
// ##Get Payout Item Status
// Sample showing how to get a Payout Item Status
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
getPayoutItemStatus(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
public PayoutItemDetails getPayoutItemStatus(HttpServletRequest req,
HttpServletResponse resp) {
// ### Get a Payout Batch
// We are re-using the GetPayoutBatchStatusServlet to get a batch payout
// for us. This will make sure the samples will work all the time.
GetPayoutBatchStatusServlet servlet = new GetPayoutBatchStatusServlet();
PayoutBatch batch = servlet.getPayoutBatchStatus(req, resp);
// ### Retrieve PayoutItem ID
// In the samples, we are extractingt he payoutItemId of a payout we
// just created.
// In reality, you might be using the payoutItemId stored in your
// database, or passed manually.
PayoutItemDetails itemDetails = batch.getItems().get(0);
String payoutItemId = itemDetails.getPayoutItemId();
// Initiate the response object
PayoutItemDetails response = null;
try {
// ### Api Context
// Pass in a `ApiContext` object to authenticate
// the call and to send a unique request id
// (that ensures idempotency). The SDK generates
// a request id if you do not pass one explicitly.
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
// ###Get Payout Item
response = PayoutItem.get(apiContext, payoutItemId);
LOGGER.info("Payout Item With ID: " + response.getPayoutItemId());
ResultPrinter.addResult(req, resp, "Got Payout Item Status",
PayoutItem.getLastRequest(), PayoutItem.getLastResponse(),
null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Got Payout Item Status",
PayoutItem.getLastRequest(), null, e.getMessage());
}
return response;
}
}
| 3,671 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/AuthorizationTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.util.TestConstants;
public class AuthorizationTestCase {
private static final Logger logger = Logger
.getLogger(AuthorizationTestCase.class);
public static final String ID = "12345";
public static final String PARENTPAYMENT = "12345";
public static final String STATE = "Approved";
public static final Amount AMOUNT = AmountTestCase.createAmount("120.00");
public static final String CREATEDTIME = "2013-01-17T18:12:02.347Z";
public String authorizationId = null;
public Authorization authorization = null;
public static Authorization createAuthorization() {
List<Links> links = new ArrayList<Links>();
links.add(LinksTestCase.createLinks());
Authorization authorization = new Authorization();
authorization.setId(ID);
authorization.setParentPayment(PARENTPAYMENT);
authorization.setState(STATE);
authorization.setAmount(AMOUNT);
authorization.setCreateTime(CREATEDTIME);
authorization.setLinks(links);
return authorization;
}
@Test(groups = "unit")
public void testConstruction() {
Authorization authorization = createAuthorization();
Assert.assertEquals(authorization.getId(), ID);
Assert.assertEquals(authorization.getCreateTime(), CREATEDTIME);
Assert.assertEquals(authorization.getLinks().size(), 1);
Assert.assertEquals(authorization.getParentPayment(), PARENTPAYMENT);
Assert.assertEquals(authorization.getState(), STATE);
Assert.assertEquals(authorization.getAmount().getCurrency(),
AmountTestCase.CURRENCY);
}
@Test(groups = "integration")
public void testGetAuthorization() throws PayPalRESTException {
Payment payment = getPaymentAgainstAuthorization();
Payment authPayment = payment.create(TestConstants.SANDBOX_CONTEXT);
authorizationId = authPayment.getTransactions().get(0)
.getRelatedResources().get(0).getAuthorization().getId();
authorization = Authorization.get(TestConstants.SANDBOX_CONTEXT, authorizationId);
Assert.assertEquals(authorization.getId(), authPayment.getTransactions().get(0)
.getRelatedResources().get(0).getAuthorization().getId());
logger.info("Authorization State: " + authorization.getState());
}
@Test(groups = "integration", dependsOnMethods = { "testGetAuthorization" }, expectedExceptions = { PayPalRESTException.class })
public void testGetReauthorization() throws PayPalRESTException{
authorization = Authorization.get(TestConstants.SANDBOX_CONTEXT, "7GH53639GA425732B");
Amount amount = new Amount();
amount.setCurrency("USD").setTotal("1");
authorization.setAmount(amount);
Authorization reauthorization = authorization.reauthorize(TestConstants.SANDBOX_CONTEXT);
logger.info("Reauthorization ID: " + reauthorization.getId());
}
@Test(groups = "integration", dependsOnMethods = { "testGetAuthorization" })
public void testAuthorizationCapture() throws PayPalRESTException {
Capture capture = new Capture();
Amount amount = new Amount();
amount.setCurrency("USD").setTotal("1");
capture.setAmount(amount);
capture.setIsFinalCapture(true);
Capture responsecapture = authorization.capture(TestConstants.SANDBOX_CONTEXT, capture);
Assert.assertEquals(responsecapture.getState(), "completed");
logger.info("Returned Capture state: " + responsecapture.getState());
}
@Test(groups = "integration", dependsOnMethods = { "testAuthorizationCapture" })
public void testAuthorizationVoid() throws PayPalRESTException {
getAuthorization();
}
@Test(groups = "integration", dependsOnMethods = { "testAuthorizationCapture" }, expectedExceptions = { IllegalArgumentException.class })
public void testAuthorizationNullAccessToken() throws PayPalRESTException {
Authorization.get((String) null, "123");
}
@Test(groups = "integration", dependsOnMethods = { "testAuthorizationCapture" }, expectedExceptions = { IllegalArgumentException.class })
public void testAuthorizationNullAuthId() throws PayPalRESTException {
Authorization.get(TestConstants.SANDBOX_CONTEXT, null);
}
@Test(groups = "integration", dependsOnMethods = { "testAuthorizationCapture" }, expectedExceptions = { IllegalArgumentException.class })
public void testAuthorizationNullCapture() throws PayPalRESTException {
getAuthorization().capture(TestConstants.SANDBOX_CONTEXT, null);
}
@Test
public void testTOJSON() {
Authorization authorization = createAuthorization();
Assert.assertEquals(authorization.toJSON().length() == 0, false);
}
@Test
public void testTOString() {
Authorization authorization = createAuthorization();
Assert.assertEquals(authorization.toString().length() == 0, false);
}
private Payment getPaymentAgainstAuthorization() {
Address billingAddress = AddressTestCase.createAddress();
CreditCard creditCard = new CreditCard();
creditCard.setBillingAddress(billingAddress);
creditCard.setCvv2(874);
creditCard.setExpireMonth(11);
creditCard.setExpireYear(2018);
creditCard.setFirstName("Joe");
creditCard.setLastName("Shopper");
// Created random credit card number using https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1413
// If this test fails, it could be related to excessive use of this credit card number. Replace with a new one, and test again.
creditCard.setNumber("4915910926483716");
creditCard.setType("visa");
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal("7");
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction
.setDescription("This is the payment transaction description.");
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
FundingInstrument fundingInstrument = new FundingInstrument();
fundingInstrument.setCreditCard(creditCard);
List<FundingInstrument> fundingInstrumentList = new ArrayList<FundingInstrument>();
fundingInstrumentList.add(fundingInstrument);
Payer payer = new Payer();
payer.setFundingInstruments(fundingInstrumentList);
payer.setPaymentMethod("credit_card");
Payment payment = new Payment();
payment.setIntent("authorize");
payment.setPayer(payer);
payment.setTransactions(transactions);
return payment;
}
private Authorization getAuthorization() throws PayPalRESTException {
Payment payment = getPaymentAgainstAuthorization();
Payment authPayment = payment.create(TestConstants.SANDBOX_CONTEXT);
Authorization authorization = authPayment.getTransactions().get(0)
.getRelatedResources().get(0).getAuthorization();
return authorization;
}
}
| 3,672 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/ErrorTestCase.java | package com.paypal.api.payments;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.paypal.base.rest.JSONFormatter;
public class ErrorTestCase {
public static final String NAME = "VALIDATION_ERROR";
public static final String MESSAGE = "Invalid request - see details";
public static final String INFORMATION_LINK = "https://developer.paypal.com/docs/api/#VALIDATION_ERROR";
public static final String DEBUG_ID = "5c16c7e108c14";
public static final String DETAILS_FIELD = "number";
public static final String DETAILS_ISSUE = "Value is invalid";
public static Error loadError() {
try {
BufferedReader br = new BufferedReader(new FileReader("src/test/resources/error.json"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
line = br.readLine();
}
br.close();
return JSONFormatter.fromJSON(sb.toString(), Error.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Test(groups = "unit")
public void fromJSON() {
Error error = loadError();
Assert.assertNotNull(error);
Assert.assertEquals(error.getName(), NAME);
Assert.assertEquals(error.getMessage(), MESSAGE);
Assert.assertEquals(error.getInformationLink(), INFORMATION_LINK);
Assert.assertEquals(error.getDebugId(), DEBUG_ID);
Assert.assertNotNull(error.getDetails());
Assert.assertEquals(error.getDetails().size(), 1);
Assert.assertEquals(error.getDetails().get(0).getField(), DETAILS_FIELD);
Assert.assertEquals(error.getDetails().get(0).getIssue(), DETAILS_ISSUE);
}
}
| 3,673 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/RelatedResourcesTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class RelatedResourcesTestCase {
public static final Sale SALE = SaleTestCase.createSale();
public static final Authorization AUTHORIZATION = AuthorizationTestCase
.createAuthorization();
public static final Refund REFUND = RefundTestCase.createRefund();
public static final Capture CAPTURE = CaptureTestCase.createCapture();
public static RelatedResources createRelatedResources() {
RelatedResources subTransaction = new RelatedResources();
subTransaction.setAuthorization(AUTHORIZATION);
subTransaction.setCapture(CAPTURE);
subTransaction.setRefund(REFUND);
subTransaction.setSale(SALE);
return subTransaction;
}
@Test(groups = "unit")
public void testConstruction() {
RelatedResources subTransaction = createRelatedResources();
Assert.assertEquals(subTransaction.getAuthorization().getId(),
AuthorizationTestCase.ID);
Assert.assertEquals(subTransaction.getSale().getId(), SaleTestCase.ID);
Assert.assertEquals(subTransaction.getRefund().getId(),
RefundTestCase.ID);
Assert.assertEquals(subTransaction.getCapture().getId(),
CaptureTestCase.ID);
}
@Test(groups = "unit")
public void testTOJSON() {
RelatedResources subTransaction = createRelatedResources();
Assert.assertEquals(subTransaction.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
RelatedResources subTransaction = createRelatedResources();
Assert.assertEquals(subTransaction.toString().length() == 0, false);
}
}
| 3,674 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/AddressTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class AddressTestCase {
public static final String CITY = "Niagara Falls";
public static final String COUNTRYCODE = "US";
public static final String LINE1 = "3909 Witmer Road";
public static final String LINE2 = "Niagara Falls";
public static final String POSTALCODE = "14305";
public static final String PHONE = "716-298-1822";
public static final String STATE = "NY";
public static Address createAddress() {
Address billingAddress = new Address();
billingAddress.setCity(CITY);
billingAddress.setCountryCode(COUNTRYCODE);
billingAddress.setLine1(LINE1);
billingAddress.setLine2(LINE2);
billingAddress.setPostalCode(POSTALCODE);
billingAddress.setPhone(PHONE);
billingAddress.setState(STATE);
return billingAddress;
}
public static ShippingAddress createShippingAddress() {
ShippingAddress address = new ShippingAddress();
address.setCity(CITY);
address.setCountryCode(COUNTRYCODE);
address.setLine1(LINE1);
address.setLine2(LINE2);
address.setPostalCode(POSTALCODE);
address.setPhone(PHONE);
address.setState(STATE);
return address;
}
@Test(groups = "unit")
public void testConstruction() {
Address address = createAddress();
Assert.assertEquals(address.getCity(), CITY);
Assert.assertEquals(address.getCountryCode(), COUNTRYCODE);
Assert.assertEquals(address.getLine1(), LINE1);
Assert.assertEquals(address.getLine2(), LINE2);
Assert.assertEquals(address.getPostalCode(), POSTALCODE);
Assert.assertEquals(address.getPhone(), PHONE);
Assert.assertEquals(address.getState(), STATE);
}
@Test(groups = "unit")
public void testTOJSON() {
Address address = createAddress();
Assert.assertEquals(address.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
Address address = createAddress();
Assert.assertEquals(address.toString().length() == 0, false);
}
}
| 3,675 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/ItemListTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ItemListTestCase {
public static ItemList createItemList() {
List<Item> items = new ArrayList<Item>();
items.add(ItemTestCase.createItem());
items.add(ItemTestCase.createItem());
ItemList itemList = new ItemList();
itemList.setItems(items);
itemList.setShippingAddress(ShippingAddressTestCase
.createShippingAddress());
return itemList;
}
@Test(groups = "unit")
public void testConstruction() {
ItemList itemList = createItemList();
Assert.assertEquals(itemList.getShippingAddress().getRecipientName(),
ShippingAddressTestCase.RECIPIENTSNAME);
Assert.assertEquals(itemList.getItems().size(), 2);
}
@Test(groups = "unit")
public void testTOJSON() {
ItemList itemList = createItemList();
Assert.assertEquals(itemList.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
ItemList itemList = createItemList();
Assert.assertEquals(itemList.toString().length() == 0, false);
}
}
| 3,676 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/CreditCardTokenTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CreditCardTokenTestCase {
public static final String CREDITCARDID = "CARD-8PV12506MG6587946KEBHH4A";
public static final String PAYERID = "12345";
public static CreditCardToken createCreditCardToken() {
CreditCardToken creditCardToken = new CreditCardToken();
creditCardToken.setCreditCardId(CREDITCARDID);
creditCardToken.setPayerId(PAYERID);
return creditCardToken;
}
@Test(groups = "unit")
public void testConstruction() {
CreditCardToken creditCardToken = createCreditCardToken();
Assert.assertEquals(creditCardToken.getCreditCardId(), "CARD-8PV12506MG6587946KEBHH4A");
Assert.assertEquals(creditCardToken.getPayerId(), "12345");
}
@Test(groups = "unit")
public void testTOJSON() {
CreditCardToken creditCardToken = createCreditCardToken();
Assert.assertEquals(creditCardToken.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
CreditCardToken creditCardToken = createCreditCardToken();
Assert.assertEquals(creditCardToken.toString().length() == 0, false);
}
}
| 3,677 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentExecutionTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PaymentExecutionTestCase {
public static PaymentExecution createPaymentExecution(){
List<Transactions> transactions = new ArrayList<Transactions>();
transactions.add(TransactionsTestCase.createTransactions());
PaymentExecution pae=new PaymentExecution();
pae.setPayerId(PayerInfoTestCase.PAYERID);
pae.setTransactions(transactions);
return pae;
}
@Test(groups = "unit")
public void testConstruction(){
PaymentExecution pae = createPaymentExecution();
Assert.assertEquals(pae.getPayerId(), PayerInfoTestCase.PAYERID);
Assert.assertEquals(pae.getTransactions().get(0).getAmount().getTotal(),"100.00");
Assert.assertEquals(pae.getTransactions().get(0).getAmount().getCurrency(),AmountTestCase.CURRENCY);
}
@Test(groups = "unit")
public void testToJson(){
PaymentExecution pae = createPaymentExecution();
Assert.assertEquals(pae.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testToString(){
PaymentExecution pae = createPaymentExecution();
Assert.assertEquals(pae.toString().length() == 0, false);
}
}
| 3,678 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/RefundTestCase.java | package com.paypal.api.payments;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.util.TestConstants;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Properties;
public class RefundTestCase {
private static final Logger logger = Logger.getLogger(RefundTestCase.class);
public static final String CAPTUREID = "12345";
public static final String ID = "12345";
public static final String PARENTPAYMENT = "12345";
public static final String SALEID = "12345";
public static final String STATE = "Approved";
public static final Amount AMOUNT = AmountTestCase.createAmount("100.00");
public static final String CREATEDTIME = "2013-01-17T18:12:02.347Z";
public static Refund createRefund() {
List<Links> links = new ArrayList<Links>();
links.add(LinksTestCase.createLinks());
Refund refund = new Refund();
refund.setCaptureId(CAPTUREID);
refund.setId(ID);
refund.setParentPayment(PARENTPAYMENT);
refund.setSaleId(SALEID);
refund.setState(STATE);
refund.setAmount(AMOUNT);
refund.setCreateTime(CREATEDTIME);
refund.setLinks(links);
return refund;
}
@Test(groups = "unit")
public void testConstruction() {
Refund refund = createRefund();
Assert.assertEquals(refund.getId(), ID);
Assert.assertEquals(refund.getCaptureId(), CAPTUREID);
Assert.assertEquals(refund.getParentPayment(), PARENTPAYMENT);
Assert.assertEquals(refund.getSaleId(), SALEID);
Assert.assertEquals(refund.getState(), STATE);
Assert.assertEquals(refund.getAmount().getCurrency(),
AmountTestCase.CURRENCY);
Assert.assertEquals(refund.getCreateTime(), CREATEDTIME);
Assert.assertEquals(refund.getLinks().size(), 1);
}
@Test(groups = "integration")
public void testGetRefund() throws PayPalRESTException {
if (ObjectHolder.refundId == null) {
new SaleTestCase().testSaleRefundAPI();
}
try {
Refund refund = Refund.get(TestConstants.SANDBOX_CONTEXT, ObjectHolder.refundId);
logger.info("Refund ID = " + refund.getId());
} catch (PayPalRESTException e) {
Assert.fail();
}
}
@Test(groups = "integration", dependsOnMethods = { "testGetRefund" })
public void testGetRefundForNull() {
try {
Refund.get(TestConstants.SANDBOX_CONTEXT, null);
} catch (IllegalArgumentException e) {
Assert.assertTrue(e != null,
"IllegalArgument exception not thrown for null Refund Id");
} catch (PayPalRESTException e) {
Assert.fail();
}
}
@Test(groups = "unit")
public void testRefundUnknownFileConfiguration() {
try {
Refund.initConfig(new File("unknown.properties"));
} catch (PayPalRESTException e) {
Assert.assertEquals(e.getCause().getClass().getSimpleName(),
"FileNotFoundException");
} catch (ConcurrentModificationException e) {}
}
@Test(groups = "unit")
public void testRefundInputStreamConfiguration() {
try {
File testFile = new File(".",
"src/test/resources/sdk_config.properties");
FileInputStream fis = new FileInputStream(testFile);
Refund.initConfig(fis);
} catch (PayPalRESTException e) {
Assert.fail("[sdk_config.properties] stream loading failed");
} catch (FileNotFoundException e) {
Assert.fail("[sdk_config.properties] file is not available");
} catch (ConcurrentModificationException e) {}
}
@Test(groups = "unit")
public void testRefundPropertiesConfiguration() {
try {
File testFile = new File(".",
"src/test/resources/sdk_config.properties");
Properties props = new Properties();
FileInputStream fis = new FileInputStream(testFile);
props.load(fis);
Refund.initConfig(props);
} catch (FileNotFoundException e) {
Assert.fail("[sdk_config.properties] file is not available");
} catch (IOException e) {
Assert.fail("[sdk_config.properties] file is not loaded into properties");
} catch (ConcurrentModificationException e) {}
}
@Test(groups = "unit")
public void testTOJSON() {
Refund refund = createRefund();
Assert.assertEquals(refund.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
Refund refund = createRefund();
Assert.assertEquals(refund.toString().length() == 0, false);
}
}
| 3,679 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/DetailsTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DetailsTestCase {
public static final String FEE = "100.00";
public static final String SHIPPING = "12.50";
public static final String SUBTOTAL = "200.00";
public static final String TAX = "20.00";
public static Details createDetails() {
Details amountDetails = new Details();
amountDetails.setFee(FEE);
amountDetails.setShipping(SHIPPING);
amountDetails.setSubtotal(SUBTOTAL);
amountDetails.setTax(TAX);
return amountDetails;
}
@Test(groups = "unit")
public void testConstruction() {
Details amountDetails = createDetails();
Assert.assertEquals(amountDetails.getFee(), FEE);
Assert.assertEquals(amountDetails.getShipping(), SHIPPING);
Assert.assertEquals(amountDetails.getSubtotal(), SUBTOTAL);
Assert.assertEquals(amountDetails.getTax(), TAX);
}
@Test(groups = "unit")
public void testTOJSON() {
Details amountDetails = createDetails();
Assert.assertEquals(amountDetails.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
Details amountDetails = createDetails();
Assert.assertEquals(amountDetails.toString().length() == 0, false);
}
}
| 3,680 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/RedirectUrlsTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class RedirectUrlsTestCase {
public static final String CANCELURL = "http://somedomain.com";
public static final String RETURNURL = "http://somedomain.com";
public static RedirectUrls createRedirectUrls() {
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(CANCELURL);
redirectUrls.setReturnUrl(RETURNURL);
return redirectUrls;
}
@Test(groups = "unit")
public void testConstruction() {
RedirectUrls redirectUrls = createRedirectUrls();
Assert.assertEquals(redirectUrls.getCancelUrl(), CANCELURL);
Assert.assertEquals(redirectUrls.getReturnUrl(), RETURNURL);
}
@Test(groups = "unit")
public void testTOJSON() {
RedirectUrls redirectUrls = createRedirectUrls();
Assert.assertEquals(redirectUrls.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
RedirectUrls redirectUrls = createRedirectUrls();
Assert.assertEquals(redirectUrls.toString().length() == 0, false);
}
}
| 3,681 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/PayerTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PayerTestCase {
public static final String PAYMENTMETHOD = "credit_card";
public static Payer createPayer() {
List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>();
fundingInstruments.add(FundingInstrumentTestCase
.createFundingInstrument());
Payer payer = new Payer();
payer.setFundingInstruments(fundingInstruments);
payer.setPayerInfo(PayerInfoTestCase.createPayerInfo());
payer.setPaymentMethod(PAYMENTMETHOD);
return payer;
}
@Test(groups = "unit")
public void testConstruction() {
Payer payer = createPayer();
Assert.assertEquals(payer.getPaymentMethod(), PAYMENTMETHOD);
Assert.assertEquals(payer.getFundingInstruments().get(0)
.getCreditCardToken().getCreditCardId(),
CreditCardTokenTestCase.CREDITCARDID);
Assert.assertEquals(payer.getPayerInfo().getFirstName(),
PayerInfoTestCase.FIRSTNAME);
}
@Test(groups = "unit")
public void testTOJSON() {
Payer payer = createPayer();
Assert.assertEquals(payer.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
Payer payer = createPayer();
Assert.assertEquals(payer.toString().length() == 0, false);
}
}
| 3,682 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/LinksTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.paypal.base.rest.JSONFormatter;
public class LinksTestCase {
public static final String HREF = "http://sample.com";
public static final String METHOD = "POST";
public static final String REL = "authorize";
public static String getJson() {
return "{\"href\":\"http://localhost/\",\"method\":\"POST\",\"rel\":\"self\"}";
}
public static Links getObject() {
return JSONFormatter.fromJSON(getJson(), Links.class);
}
public static Links createLinks() {
Links link = new Links();
link.setHref(HREF);
link.setMethod(METHOD);
link.setRel(REL);
return link;
}
@Test(groups = "unit")
public void testConstruction() {
Links link = LinksTestCase.createLinks();
Assert.assertEquals(link.getHref(), HREF);
Assert.assertEquals(link.getRel(), REL);
Assert.assertEquals(link.getMethod(), METHOD);
}
@Test(groups = "unit")
public void testTOJSON() {
Links link = LinksTestCase.createLinks();
Assert.assertEquals(link.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
Links link = LinksTestCase.createLinks();
Assert.assertEquals(link.toString().length() == 0, false);
}
}
| 3,683 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/BillingPlanTestCase.java | package com.paypal.api.payments;
import static org.testng.Assert.assertNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.util.TestConstants;
public class BillingPlanTestCase {
private String id = null;
public static Plan buildPlan() {
// Build Plan object
Plan plan = new Plan();
plan.setName("T-Shirt of the Month Club Plan");
plan.setDescription("Template creation.");
plan.setType("fixed");
//payment_definitions
PaymentDefinition paymentDefinition = new PaymentDefinition();
paymentDefinition.setName("Regular Payments");
paymentDefinition.setType("REGULAR");
paymentDefinition.setFrequency("MONTH");
paymentDefinition.setFrequencyInterval("1");
paymentDefinition.setCycles("12");
//currency
Currency currency = new Currency();
currency.setCurrency("USD");
currency.setValue("20");
paymentDefinition.setAmount(currency);
//charge_models
ChargeModels chargeModels = new com.paypal.api.payments.ChargeModels();
chargeModels.setType("SHIPPING");
chargeModels.setAmount(currency);
List<ChargeModels> chargeModelsList = new ArrayList<ChargeModels>();
chargeModelsList.add(chargeModels);
paymentDefinition.setChargeModels(chargeModelsList);
//payment_definition
List<PaymentDefinition> paymentDefinitionList = new ArrayList<PaymentDefinition>();
paymentDefinitionList.add(paymentDefinition);
plan.setPaymentDefinitions(paymentDefinitionList);
//merchant_preferences
MerchantPreferences merchantPreferences = new MerchantPreferences();
merchantPreferences.setSetupFee(currency);
merchantPreferences.setCancelUrl("http://www.cancel.com");
merchantPreferences.setReturnUrl("http://www.return.com");
merchantPreferences.setMaxFailAttempts("0");
merchantPreferences.setAutoBillAmount("YES");
merchantPreferences.setInitialFailAmountAction("CONTINUE");
plan.setMerchantPreferences(merchantPreferences);
return plan;
}
@Test(groups = "integration")
public void testCreatePlan() throws PayPalRESTException {
Plan plan = buildPlan();
plan = plan.create(TestConstants.SANDBOX_CONTEXT);
this.id = plan.getId();
Assert.assertNotNull(plan.getId());
}
@Test(groups = "integration", dependsOnMethods = {"testCreatePlan"})
public void testUpdatePlan() throws PayPalRESTException {
// get original plan
Plan plan = buildPlan();
plan.setId(this.id);
// set up new plan
Plan newPlan = new Plan();
newPlan.setState("ACTIVE");
// incorporate new plan in Patch object
Patch patch = new Patch();
patch.setOp("replace");
patch.setPath("/");
patch.setValue(newPlan);
// wrap the Patch object with PatchRequest
List<Patch> patchRequest = new ArrayList<Patch>();
patchRequest.add(patch);
// execute update
plan.update(TestConstants.SANDBOX_CONTEXT, patchRequest);
Plan updatedPlan = Plan.get(TestConstants.SANDBOX_CONTEXT, plan.getId());
Assert.assertEquals(plan.getId(), updatedPlan.getId());
Assert.assertEquals(updatedPlan.getState(), "ACTIVE");
}
@Test(groups = "integration", dependsOnMethods = {"testUpdatePlan"})
public void testRetrievePlan() throws PayPalRESTException {
Plan plan = Plan.get(TestConstants.SANDBOX_CONTEXT, this.id);
Assert.assertEquals(plan.getId(), this.id);
}
@Test(groups = "integration", dependsOnMethods = {"testRetrievePlan"})
public void testEmptyListPlan() throws PayPalRESTException {
// store all required parameters in Map
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("page_size", "3");
parameters.put("status", "INACTIVE");
parameters.put("page", "2");
parameters.put("total_required", "yes");
// retrieve plans that match the specified criteria
PlanList planList = Plan.list(TestConstants.SANDBOX_CONTEXT, parameters);
assertNull(planList);
}
@Test(groups = "integration", dependsOnMethods = {"testRetrievePlan"})
public void testListPlan() throws PayPalRESTException {
// store all required parameters in Map
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("page_size", "3");
parameters.put("status", "ACTIVE");
parameters.put("page", "2");
parameters.put("total_required", "yes");
// retrieve plans that match the specified criteria
PlanList planList = Plan.list(TestConstants.SANDBOX_CONTEXT, parameters);
List<Plan> plans = planList.getPlans();
for (int i = 0; i < plans.size(); ++i) {
Assert.assertEquals(plans.get(i).getState(), "ACTIVE");
}
}
}
| 3,684 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/PayoutItemTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.paypal.base.rest.JSONFormatter;
public class PayoutItemTestCase {
public static String getJson() {
return "{\"recipient_type\":\"TestSample\",\"amount\":"
+ CurrencyTestCase.getJson()
+ ",\"note\":\"TestSample\",\"receiver\":\"TestSample\",\"sender_item_id\":\"TestSample\"}";
}
public static PayoutItem getObject() {
return JSONFormatter.fromJSON(getJson(), PayoutItem.class);
}
@Test(groups = "unit")
public void testJsontoObject() {
PayoutItem obj = PayoutItemTestCase.getObject();
Assert.assertEquals(obj.getRecipientType(), "TestSample");
Assert.assertEquals(obj.getAmount().toJSON(), CurrencyTestCase.getObject().toJSON());
}
}
| 3,685 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/PayoutsTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.paypal.base.rest.JSONFormatter;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.util.TestConstants;
public class PayoutsTestCase {
PayoutBatch result;
public static String getJson() {
return "{\"sender_batch_header\":" + PayoutSenderBatchHeaderTestCase.getJson() + ",\"items\":[" + PayoutItemTestCase.getJson() + "],\"links\":[" + LinksTestCase.getJson() + "]}";
}
public static Payout getObject() {
return JSONFormatter.fromJSON(getJson(), Payout.class);
}
@Test(groups = "unit")
public void testJsontoObject() {
Payout payout = PayoutsTestCase.getObject();
Assert.assertEquals(payout.getSenderBatchHeader().toJSON(), PayoutSenderBatchHeaderTestCase.getObject().toJSON());
Assert.assertEquals(payout.getItems().get(0).toJSON(), PayoutItemTestCase.getObject().toJSON());
Assert.assertEquals(payout.getLinks().get(0).toJSON(), LinksTestCase.getObject().toJSON());
}
@Test(groups = "integration")
public void testCreate() throws PayPalRESTException {
Random random = new Random();
PayoutSenderBatchHeader senderBatchHeader = new PayoutSenderBatchHeader();
senderBatchHeader.setSenderBatchId(
new Double(random.nextDouble()).toString()).setEmailSubject(
"You have a Payout!");
Currency amount = new Currency();
amount.setValue("1.00").setCurrency("USD");
PayoutItem senderItem = new PayoutItem();
senderItem.setRecipientType("Email")
.setNote("Thanks for your patronage")
.setReceiver("shirt-supplier-one@gmail.com")
.setSenderItemId("201404324234").setAmount(amount);
List<PayoutItem> items = new ArrayList<PayoutItem>();
items.add(senderItem);
Payout payout = new Payout();
payout.setSenderBatchHeader(senderBatchHeader).setItems(items);
this.result = payout.create(TestConstants.SANDBOX_CONTEXT, null);
Assert.assertNotNull(this.result);
Assert.assertNotNull(this.result.getBatchHeader());
Assert.assertNotNull(this.result.getBatchHeader().getBatchStatus());
}
@Test(groups = "integration")
public void testCreateSync() throws PayPalRESTException {
Random random = new Random();
PayoutSenderBatchHeader senderBatchHeader = new PayoutSenderBatchHeader();
senderBatchHeader.setSenderBatchId(
new Double(random.nextDouble()).toString()).setEmailSubject(
"You have a Payout!");
Currency amount = new Currency();
amount.setValue("1.00").setCurrency("USD");
PayoutItem senderItem = new PayoutItem();
senderItem.setRecipientType("Email")
.setNote("Thanks for your patronage")
.setReceiver("shirt-supplier-one@gmail.com")
.setSenderItemId("201404324234").setAmount(amount);
List<PayoutItem> items = new ArrayList<PayoutItem>();
items.add(senderItem);
Payout payout = new Payout();
payout.setSenderBatchHeader(senderBatchHeader).setItems(items);
PayoutBatch result = payout.createSynchronous(TestConstants.SANDBOX_CONTEXT);
Assert.assertNotNull(result);
Assert.assertNotNull(result.getBatchHeader());
Assert.assertNotNull(result.getBatchHeader().getBatchStatus());
}
@Test(groups = "integration")
public void testGetPayout() throws PayPalRESTException {
String payoutBatchId = "XR3H37QDELPZS";
this.result = Payout.get(TestConstants.SANDBOX_CONTEXT, payoutBatchId);
Assert.assertNotNull(this.result);
Assert.assertEquals(this.result.getBatchHeader().getPayoutBatchId(), payoutBatchId);
Assert.assertEquals(this.result.getItems().size(), 1);
}
@Test(groups = "integration")
public void testGetPayoutItemError() throws PayPalRESTException {
PayoutItemDetails payoutItem = this.result.getItems().get(0);
String payoutItemId = "BYGU98D9Z8SQG";
PayoutItemDetails result = PayoutItem.get(TestConstants.SANDBOX_CONTEXT, payoutItemId);
Assert.assertNotNull(result);
Assert.assertEquals(result.getPayoutItemId(), payoutItemId);
Assert.assertEquals(result.getPayoutItemFee().getValue(), payoutItem.getPayoutItemFee().getValue());
Assert.assertEquals(result.getPayoutItemFee().getCurrency(), payoutItem.getPayoutItemFee().getCurrency());
Assert.assertEquals(result.getErrors().getName(), "RECEIVER_UNREGISTERED");
}
@Test(groups = "integration")
public void testGetPayoutItem() throws PayPalRESTException {
PayoutItemDetails payoutItem = this.result.getItems().get(0);
String payoutItemId = payoutItem.getPayoutItemId();
PayoutItemDetails result = PayoutItem.get(TestConstants.SANDBOX_CONTEXT, payoutItemId);
Assert.assertNotNull(result);
Assert.assertEquals(result.getPayoutItemId(), payoutItemId);
Assert.assertEquals(result.getPayoutItemFee().getValue(), payoutItem.getPayoutItemFee().getValue());
Assert.assertEquals(result.getPayoutItemFee().getCurrency(), payoutItem.getPayoutItemFee().getCurrency());
}
@Test(groups = "integration")
public void testPayoutItemCancel() throws PayPalRESTException {
PayoutItemDetails payoutItem = this.result.getItems().get(0);
String payoutItemId = payoutItem.getPayoutItemId();
if (payoutItem.getTransactionStatus() == "UNCLAIMED") {
PayoutItemDetails result = PayoutItem.cancel(TestConstants.SANDBOX_CONTEXT, payoutItemId);
Assert.assertNotNull(result);
Assert.assertEquals(result.getPayoutItemId(), payoutItemId);
Assert.assertEquals(result.getPayoutItemFee().getValue(), payoutItem.getPayoutItemFee().getValue());
Assert.assertEquals(result.getPayoutItemFee().getCurrency(), payoutItem.getPayoutItemFee().getCurrency());
Assert.assertEquals("RETURNED", result.getTransactionStatus());
}
}
}
| 3,686 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/InvoiceTestCase.java | package com.paypal.api.payments;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.paypal.base.util.TestConstants;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import com.paypal.base.rest.JSONFormatter;
import com.paypal.base.rest.PayPalRESTException;
public class InvoiceTestCase {
private static final Logger logger = Logger
.getLogger(InvoiceTestCase.class);
private String id = null;
public static Invoice loadInvoice() {
try {
BufferedReader br = new BufferedReader(new FileReader("src/test/resources/invoice_test.json"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
line = br.readLine();
}
br.close();
return JSONFormatter.fromJSON(sb.toString(), Invoice.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Test(groups = "integration", enabled=false)
public void testCreateInvoice() throws PayPalRESTException {
Invoice invoice = loadInvoice();
invoice = invoice.create(TestConstants.SANDBOX_CONTEXT);
logger.info("Invoice created: ID=" + invoice.getId());
this.id = invoice.getId();
}
@Test(groups = "integration", enabled=false, dependsOnMethods = { "testCreateInvoice" })
public void testGetInvoice() throws PayPalRESTException {
Invoice invoice = Invoice.get(TestConstants.SANDBOX_CONTEXT, this.id);
logger.info("Invoice returned: ID=" + invoice.getId());
this.id = invoice.getId();
}
@Test(groups = "integration", enabled=false, dependsOnMethods = { "testGetInvoice" })
public void testSendInvoice() throws PayPalRESTException {
Invoice invoice = Invoice.get(TestConstants.SANDBOX_CONTEXT, this.id);
invoice.send(TestConstants.SANDBOX_CONTEXT);
}
}
| 3,687 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/WebhookTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.paypal.base.util.TestConstants;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.paypal.base.rest.PayPalRESTException;
public class WebhookTestCase {
private static final Logger logger = Logger.getLogger(WebhookTestCase.class);
public static final String WEBHOOK_ID = "WH-ID-SDK-1S115631EN580315E-9KH94552VF7913711";
public static String webhookId = "";
public static String webhookUrl = "";
public static Webhook createWebhook() {
Webhook webhook = new Webhook();
webhook.setId(WEBHOOK_ID);
webhook.setUrl(WebhooksInputData.WEBHOOK_URL);
webhook.setLinks(createWebhookHATEOASLinks());
webhook.setEventTypes(EventTypeListTestCase.createAuthEventTypeList());
return webhook;
}
public static Webhook createWebhookWithAllEvents() {
Webhook webhook = new Webhook();
webhook.setId(WEBHOOK_ID);
webhook.setUrl(WebhooksInputData.WEBHOOK_URL);
webhook.setLinks(createWebhookHATEOASLinks());
webhook.setEventTypes(EventTypeListTestCase.createAllEventTypeList());
return webhook;
}
public static List<Links> createWebhookHATEOASLinks() {
List<Links> linksList = new ArrayList<Links>();
Links link1 = new Links();
link1.setHref(WebhooksInputData.WEBHOOK_HATEOAS_URL + WEBHOOK_ID);
link1.setRel("self");
link1.setMethod("GET");
Links link2 = new Links();
link1.setHref(WebhooksInputData.WEBHOOK_HATEOAS_URL + WEBHOOK_ID);
link2.setRel("update");
link2.setMethod("PATCH");
Links link3 = new Links();
link1.setHref(WebhooksInputData.WEBHOOK_HATEOAS_URL + WEBHOOK_ID);
link3.setRel("delete");
link3.setMethod("DELETE");
linksList.add(link1);
linksList.add(link2);
linksList.add(link3);
return linksList;
}
@Test(groups = "unit")
public void testWebhookConstruction() {
Webhook webhook = createWebhook();
Assert.assertEquals(webhook.getId(), WEBHOOK_ID);
Assert.assertEquals(webhook.getUrl(), WebhooksInputData.WEBHOOK_URL);
Assert.assertEquals(webhook.getLinks().size(), 3);
Assert.assertEquals(webhook.getEventTypes().size(), 2);
Assert.assertEquals(webhook.getEventTypes().get(0).getName(), WebhooksInputData.availableEvents[1][0]);
Assert.assertEquals(webhook.getEventTypes().get(1).getName(), WebhooksInputData.availableEvents[2][0]);
Assert.assertNotEquals(webhook.getEventTypes().size(), WebhooksInputData.availableEvents.length);
}
@Test(groups = "unit")
public void testWebhookWithAllEventsConstruction() {
Webhook webhook = createWebhookWithAllEvents();
Assert.assertEquals(webhook.getId(), WEBHOOK_ID);
Assert.assertEquals(webhook.getUrl(), WebhooksInputData.WEBHOOK_URL);
Assert.assertEquals(webhook.getLinks().size(), 3);
Assert.assertEquals(webhook.getEventTypes().size(), WebhooksInputData.availableEvents.length);
for(int i=0; i < webhook.getEventTypes().size(); i++) {
Assert.assertEquals(webhook.getEventTypes().get(i).getName(), WebhooksInputData.availableEvents[i][0]);
}
}
@Test(groups = "unit")
public void testTOJSON() {
Webhook webhook = createWebhook();
Assert.assertEquals(webhook.toJSON().length() == 0, false);
logger.info("EventTypeJSON = " + webhook.toJSON());
}
@Test(groups = "unit")
public void testTOString() {
Webhook webhook = createWebhook();
Assert.assertEquals(webhook.toString().length() == 0, false);
}
@Test(groups = "integration")
public void testCreateWebhook() throws PayPalRESTException {
Webhook webhookRequest = new Webhook();
String uuid = UUID.randomUUID().toString();
webhookRequest.setUrl(WebhooksInputData.WEBHOOK_URL + uuid);
webhookRequest.setEventTypes(EventTypeListTestCase.createAuthEventTypeList());
logger.info("Request = " + webhookRequest.toJSON());
Webhook webhookResponse = webhookRequest.create(TestConstants.SANDBOX_CONTEXT, webhookRequest);
logger.info("Response = " + webhookResponse.toJSON());
webhookId = webhookResponse.getId();
webhookUrl = webhookResponse.getUrl();
Assert.assertNotNull(webhookResponse.getId());
Assert.assertEquals(webhookResponse.getUrl(), WebhooksInputData.WEBHOOK_URL + uuid);
Assert.assertEquals(webhookResponse.getLinks().size(), 3);
Assert.assertEquals(webhookResponse.getEventTypes().size(), 2);
Assert.assertEquals(webhookResponse.getEventTypes().get(0).getName(), WebhooksInputData.availableEvents[1][0]);
Assert.assertEquals(webhookResponse.getEventTypes().get(1).getName(), WebhooksInputData.availableEvents[2][0]);
Assert.assertNotEquals(webhookResponse.getEventTypes().size(), WebhooksInputData.availableEvents.length);
}
@Test(groups = "integration", dependsOnMethods = { "testCreateWebhook" })
public void testGetWebhook() throws PayPalRESTException {
Webhook webhookRequest = new Webhook();
Webhook webhookGetResponse = webhookRequest.get(TestConstants.SANDBOX_CONTEXT, webhookId);
logger.info("Response = " + webhookGetResponse.toJSON());
Assert.assertNotNull(webhookGetResponse.getId());
Assert.assertNotNull(webhookGetResponse.getUrl());
Assert.assertEquals(webhookGetResponse.getLinks().size(), 3);
Assert.assertEquals(webhookGetResponse.getEventTypes().size(), 2);
Assert.assertEquals(webhookGetResponse.getEventTypes().get(0).getName(), WebhooksInputData.availableEvents[2][0]);
Assert.assertEquals(webhookGetResponse.getEventTypes().get(1).getName(), WebhooksInputData.availableEvents[1][0]);
Assert.assertNotEquals(webhookGetResponse.getEventTypes().size(), WebhooksInputData.availableEvents.length);
}
@Test(groups = "integration", dependsOnMethods = { "testGetWebhook" })
public void testUpdateWebhook() throws PayPalRESTException {
String webhookUpdatedUrl = webhookUrl + "/new_url";
JsonObject patchUrl = new JsonObject();
patchUrl.addProperty("op", "replace");
patchUrl.addProperty("path", "/url");
patchUrl.addProperty("value", webhookUpdatedUrl);
JsonObject eventType = new JsonObject();
eventType.addProperty("name", WebhooksInputData.availableEvents[4][0]);
JsonArray eventTypeArray = new JsonArray();
eventTypeArray.add(eventType);
JsonObject patchEventType = new JsonObject();
patchEventType.addProperty("op", "replace");
patchEventType.addProperty("path", "/event_types");
patchEventType.add("value", eventTypeArray);
JsonArray patchArray = new JsonArray();
patchArray.add(patchUrl);
patchArray.add(patchEventType);
String patchRequest = patchArray.toString();
logger.info("Request" + patchRequest);
Webhook webhookRequest = new Webhook();
Webhook webhookGetResponse = webhookRequest.update(TestConstants.SANDBOX_CONTEXT, webhookId, patchRequest);
logger.info("Response = " + webhookGetResponse.toJSON());
Assert.assertNotNull(webhookGetResponse);
Assert.assertEquals(webhookGetResponse.getUrl(), webhookUpdatedUrl);
Assert.assertEquals(webhookGetResponse.getLinks().size(), 3);
Assert.assertEquals(webhookGetResponse.getEventTypes().size(), 1);
Assert.assertEquals(webhookGetResponse.getEventTypes().get(0).getName(), WebhooksInputData.availableEvents[4][0]);
}
@Test(groups = "integration", dependsOnMethods= { "testUpdateWebhook" }, expectedExceptions = {PayPalRESTException.class} )
public void testDeleteWebhook() throws PayPalRESTException {
Webhook webhookRequest = new Webhook();
webhookRequest.delete(TestConstants.SANDBOX_CONTEXT, webhookId);
webhookRequest.get(TestConstants.SANDBOX_CONTEXT, webhookId); //This should throw PayPalRESTException since Resource does not exist
}
}
| 3,688 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/EventListTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
public class EventListTestCase {
public static final String EVENTTYPE_PAYMENT_AUTH = "PAYMENT.AUTHORIZATION.CREATED";
public static final String RESOURCETYPE_AUTHORIZATION = "authorization";
public static final String EVENT_ID = "WH-SDK-1S115631EN580315E-9KH94552VF7913711";
public static final String EVENT_SUMMARY = "A successful payment authorization was created";
private static final Logger logger = Logger.getLogger(EventListTestCase.class);
public static EventList createEventList() {
EventList eventList = new EventList();
List<Event> events = new ArrayList<Event>();
Event authEvent = EventTestCase.createEvent();
Event saleEvent = EventTestCase.createSaleEvent();
events.add(authEvent);
events.add(saleEvent);
eventList.setEvents(events);
eventList.setCount(events.size());
eventList.setLinks(WebhooksInputData.createLinksList());
return eventList;
}
@Test(groups = "unit")
public void testEventListConstruction() {
EventList eventListt = createEventList();
Assert.assertNotEquals(eventListt.getEvents(), null);
Assert.assertEquals(eventListt.getCount(), 2);
Assert.assertNotEquals(eventListt.getLinks(), null);
}
@Test(groups = "unit")
public void testTOJSON() {
EventList eventList = createEventList();
Assert.assertEquals(eventList.toJSON().length() == 0, false);
logger.info("EventListJSON = " + eventList.toJSON());
}
@Test(groups = "unit")
public void testTOString() {
EventList eventList = createEventList();
Assert.assertEquals(eventList.toString().length() == 0, false);
}
}
| 3,689 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/ShippingAddressTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ShippingAddressTestCase {
public static final String RECIPIENTSNAME = "TestUser";
public static ShippingAddress createShippingAddress() {
ShippingAddress shippingAddress = new ShippingAddress();
shippingAddress.setRecipientName(RECIPIENTSNAME);
return shippingAddress;
}
@Test(groups = "unit")
public void testConstruction() {
ShippingAddress shippingAddress = createShippingAddress();
Assert.assertEquals(shippingAddress.getRecipientName(), RECIPIENTSNAME);
}
@Test(groups = "unit")
public void testTOJSON() {
ShippingAddress address = createShippingAddress();
Assert.assertEquals(address.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
ShippingAddress address = createShippingAddress();
Assert.assertEquals(address.toString().length() == 0, false);
}
}
| 3,690 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/CaptureTestCase.java | package com.paypal.api.payments;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.util.TestConstants;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import java.util.ArrayList;
import java.util.List;
@Test
public class CaptureTestCase {
private static final Logger logger = Logger
.getLogger(CaptureTestCase.class);
public static final String AUTHID = "12345";
public static final String ID = "12345";
public static final String PARENTPAYMENT = "12345";
public static final String STATE = "Approved";
public static final Amount AMOUNT = AmountTestCase.createAmount("120.00");
public static final String CREATEDTIME = "2013-01-17T18:12:02.347Z";
private Capture retrievedCapture = null;
public static Capture createCapture() {
List<Links> links = new ArrayList<Links>();
links.add(LinksTestCase.createLinks());
Capture capture = new Capture();
capture.setId(ID);
capture.setParentPayment(PARENTPAYMENT);
capture.setState(STATE);
capture.setAmount(AMOUNT);
capture.setCreateTime(CREATEDTIME);
capture.setLinks(links);
return capture;
}
@Test(groups = "unit")
public void testConstruction() {
Capture capture = createCapture();
Assert.assertEquals(capture.getId(), ID);
Assert.assertEquals(capture.getParentPayment(), PARENTPAYMENT);
Assert.assertEquals(capture.getState(), STATE);
Assert.assertEquals(capture.getAmount().getCurrency(),
AMOUNT.getCurrency());
Assert.assertEquals(capture.getCreateTime(), CREATEDTIME);
Assert.assertEquals(capture.getLinks().size(), 1);
}
@Test(groups = "integration")
public void testGetCapture() throws PayPalRESTException {
Payment payment = getPaymentAgainstAuthorization("9.00");
Payment authPayment = payment.create(TestConstants.SANDBOX_CONTEXT);
String authorizationId = authPayment.getTransactions().get(0)
.getRelatedResources().get(0).getAuthorization().getId();
Authorization authorization = Authorization.get(
TestConstants.SANDBOX_CONTEXT, authorizationId);
Capture capture = new Capture();
Amount amount = new Amount();
amount.setCurrency("USD").setTotal("1");
capture.setAmount(amount).setIsFinalCapture(true);
Capture responsecapture = authorization.capture(TestConstants.SANDBOX_CONTEXT, capture);
retrievedCapture = Capture.get(TestConstants.SANDBOX_CONTEXT, responsecapture.getId());
}
@Test(groups = "integration", dependsOnMethods = { "testGetCapture" })
public void testRefundCapture() throws PayPalRESTException {
/* testing */
Refund refund = new Refund();
Amount amount = new Amount();
amount.setCurrency("USD").setTotal("1");
refund.setAmount(amount);
Refund responseRefund = retrievedCapture.refund(TestConstants.SANDBOX_CONTEXT, refund);
Assert.assertEquals("completed", responseRefund.getState());
}
@Test(groups = "integration", expectedExceptions = { IllegalArgumentException.class })
public void testGetCaptureNullCaptureId() throws PayPalRESTException {
Capture.get(TestConstants.SANDBOX_CONTEXT, null);
}
@Test(groups = "integration", expectedExceptions = { IllegalArgumentException.class })
public void testCaptureNullRefund() throws PayPalRESTException {
Payment payment = getPaymentAgainstAuthorization("2.50");
Payment authPayment = payment.create(TestConstants.SANDBOX_CONTEXT);
String authorizationId = authPayment.getTransactions().get(0)
.getRelatedResources().get(0).getAuthorization().getId();
Authorization authorization = Authorization.get(TestConstants.SANDBOX_CONTEXT, authorizationId);
Capture capture = new Capture();
Amount amount = new Amount();
amount.setCurrency("USD").setTotal("1");
capture.setAmount(amount).setIsFinalCapture(true);
Capture responsecapture = authorization.capture(TestConstants.SANDBOX_CONTEXT, capture);
logger.info("Generated Capture Id = " + responsecapture.getId());
Capture rCapture = Capture.get(TestConstants.SANDBOX_CONTEXT,
responsecapture.getId());
rCapture.refund(TestConstants.SANDBOX_CONTEXT, new Refund());
}
@Test
public void testTOJSON() {
Capture capture = createCapture();
Assert.assertEquals(capture.toJSON().length() == 0, false);
}
@Test
public void testTOString() {
Capture capture = createCapture();
Assert.assertEquals(capture.toString().length() == 0, false);
}
private Payment getPaymentAgainstAuthorization(String totalAmount) {
Address billingAddress = AddressTestCase.createAddress();
CreditCard creditCard = new CreditCard();
creditCard.setBillingAddress(billingAddress);
creditCard.setCvv2(617);
creditCard.setExpireMonth(01);
creditCard.setExpireYear(2020);
creditCard.setFirstName("Joe");
creditCard.setLastName("Shopper");
creditCard.setNumber("4422009910903049");
creditCard.setType("visa");
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal(totalAmount);
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction
.setDescription("This is the payment transaction description.");
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
FundingInstrument fundingInstrument = new FundingInstrument();
fundingInstrument.setCreditCard(creditCard);
List<FundingInstrument> fundingInstrumentList = new ArrayList<FundingInstrument>();
fundingInstrumentList.add(fundingInstrument);
Payer payer = new Payer();
payer.setFundingInstruments(fundingInstrumentList);
payer.setPaymentMethod("credit_card");
Payment payment = new Payment();
payment.setIntent("authorize");
payment.setPayer(payer);
payment.setTransactions(transactions);
return payment;
}
}
| 3,691 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/PayerInfoTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PayerInfoTestCase {
public static final String EMAIL = "somename@somedomain.com";
public static final String FIRSTNAME = "Joe";
public static final String LASTNAME = "Shopper";
public static final String PAYERID = "12345";
public static final String PHONE = "716-298-1822";
public static final ShippingAddress SHIPPINGADDRESS = AddressTestCase
.createShippingAddress();
public static PayerInfo createPayerInfo() {
PayerInfo payerInfo = new PayerInfo();
payerInfo.setFirstName(FIRSTNAME);
payerInfo.setLastName(LASTNAME);
payerInfo.setEmail(EMAIL);
payerInfo.setPayerId(PAYERID);
payerInfo.setPhone(PHONE);
payerInfo.setShippingAddress(SHIPPINGADDRESS);
return payerInfo;
}
@Test(groups = "unit")
public void testConstruction() {
PayerInfo payerInfo = createPayerInfo();
Assert.assertEquals(payerInfo.getFirstName(), FIRSTNAME);
Assert.assertEquals(payerInfo.getLastName(), LASTNAME);
Assert.assertEquals(payerInfo.getEmail(), EMAIL);
Assert.assertEquals(payerInfo.getPayerId(), PAYERID);
Assert.assertEquals(payerInfo.getPhone(), PHONE);
Assert.assertEquals(payerInfo.getShippingAddress().getCity(),
AddressTestCase.CITY);
}
@Test(groups = "unit")
public void testTOJSON() {
PayerInfo payerInfo = createPayerInfo();
Assert.assertEquals(payerInfo.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
PayerInfo payerInfo = createPayerInfo();
Assert.assertEquals(payerInfo.toString().length() == 0, false);
}
}
| 3,692 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TransactionTestCase {
public static final Amount AMOUNT = AmountTestCase.createAmount("100.00");
public static final Payee PAYEE = PayeeTestCase.createPayee();
public static final String DESCRIPTION = "sample description";
public static final String CUSTOM = "custom field value 1";
public static final String INVOICE = "invoice 1";
public static final String SOFT_DESCRIPTOR = "soft descriptor 1";
public static Transaction createTransaction() {
ItemList itemList = ItemListTestCase.createItemList();
List<RelatedResources> relResources = new ArrayList<RelatedResources>();
relResources.add(RelatedResourcesTestCase.createRelatedResources());
Transaction transaction = new Transaction();
transaction.setAmount(AMOUNT);
transaction.setPayee(PAYEE);
transaction.setDescription(DESCRIPTION);
transaction.setItemList(itemList);
transaction.setRelatedResources(relResources);
transaction.setCustom( CUSTOM );
transaction.setInvoiceNumber( INVOICE );
transaction.setSoftDescriptor( SOFT_DESCRIPTOR );
return transaction;
}
@Test(groups = "unit")
public void testConstruction() {
Transaction transaction = createTransaction();
Assert.assertEquals(transaction.getAmount().getTotal(), "100.00");
Assert.assertEquals(transaction.getDescription(), DESCRIPTION);
Assert.assertEquals(transaction.getPayee().getMerchantId(),
PayeeTestCase.MERCHANTID);
Assert.assertEquals(transaction.getItemList().getItems().get(0)
.getName(), ItemTestCase.NAME);
Assert.assertEquals(transaction.getRelatedResources().get(0)
.getAuthorization().getId(), AuthorizationTestCase.ID);
Assert.assertEquals(transaction.getAmount().getCurrency(),
AmountTestCase.CURRENCY);
Assert.assertEquals(transaction.getCustom(), CUSTOM);
Assert.assertEquals(transaction.getInvoiceNumber(), INVOICE);
Assert.assertEquals(transaction.getSoftDescriptor(), SOFT_DESCRIPTOR);
}
@Test(groups = "unit")
public void testTOJSON() {
Transaction transaction = createTransaction();
Assert.assertEquals(transaction.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
Transaction transaction = createTransaction();
Assert.assertEquals(transaction.toString().length() == 0, false);
}
}
| 3,693 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/WebhookListTestCase.java | package com.paypal.api.payments;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.paypal.base.util.TestConstants;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import com.paypal.base.rest.PayPalRESTException;
public class WebhookListTestCase {
private static final Logger logger = Logger.getLogger(WebhookTestCase.class);
public WebhookList createWebhookList() {
WebhookList webhookList = new WebhookList();
List<Webhook> webhooks = new ArrayList<Webhook>();
Webhook webhook1 = WebhookTestCase.createWebhook();
Webhook webhook2 = WebhookTestCase.createWebhookWithAllEvents();
webhooks.add(webhook1);
webhooks.add(webhook2);
webhookList.setWebhooks(webhooks);
return webhookList;
}
@Test(groups = "unit")
public void testWebhooksListConstruction() {
WebhookList webhookList = createWebhookList();
Assert.assertEquals(webhookList.getWebhooks().size(), 2);
Assert.assertNotEquals(webhookList.getWebhooks().get(0), webhookList.getWebhooks().get(1));
}
@Test(groups = "unit")
public void testTOJSON() {
WebhookList webhookList = createWebhookList();
Assert.assertEquals(webhookList.toJSON().length() == 0, false);
logger.info("WebhookListJSON = " + webhookList.toJSON());
}
@Test(groups = "unit")
public void testTOString() {
WebhookList webhookList = createWebhookList();
Assert.assertEquals(webhookList.toJSON().length() == 0, false);
}
@Test(groups = "integration", dependsOnMethods = {"testDeleteAllWebhooks"})
public void testListWebhooks() throws PayPalRESTException {
for(int i=0; i<2; i++) {
Webhook webhookRequest = new Webhook();
String uuid = UUID.randomUUID().toString();
webhookRequest.setUrl(WebhooksInputData.WEBHOOK_URL + uuid);
webhookRequest.setEventTypes(EventTypeListTestCase.createAuthEventTypeList());
webhookRequest.create(TestConstants.SANDBOX_CONTEXT, webhookRequest);
}
WebhookList webhookList = new WebhookList();
WebhookList webhookResponse = webhookList.getAll(TestConstants.SANDBOX_CONTEXT);
logger.info("Response = " + webhookResponse.toJSON());
Assert.assertTrue(webhookResponse.getWebhooks().size() >= 2, "Webhook List contains Two or More Webhooks");
}
@Test(groups = "integration")
public void testDeleteAllWebhooks() throws PayPalRESTException {
WebhookList webhookList = new WebhookList();
WebhookList webhookRequest = webhookList.getAll(TestConstants.SANDBOX_CONTEXT);
for(int i=0; i<webhookRequest.getWebhooks().size(); i++) {
Webhook webhook = new Webhook();
webhook.delete(TestConstants.SANDBOX_CONTEXT, webhookRequest.getWebhooks().get(i).getId());
}
webhookRequest = webhookList.getAll(TestConstants.SANDBOX_CONTEXT);
logger.info("Response = " + webhookRequest.toJSON());
Assert.assertEquals(webhookRequest.getWebhooks().size(), 0);
}
}
| 3,694 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/EventTypeTestCase.java | package com.paypal.api.payments;
import java.util.UUID;
import com.paypal.base.util.TestConstants;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import com.paypal.base.rest.PayPalRESTException;
public class EventTypeTestCase {
private static final Logger logger = Logger.getLogger(EventTypeTestCase.class);
public static EventType createEventType() {
EventType eventType = new EventType();
eventType.setName(WebhooksInputData.availableEvents[0][0]);
eventType.setDescription(WebhooksInputData.availableEvents[0][1]);
return eventType;
}
@Test(groups = "unit")
public void testEventConstruction() {
EventType eventType = createEventType();
Assert.assertEquals(eventType.getName(), WebhooksInputData.availableEvents[0][0]);
Assert.assertEquals(eventType.getDescription(), WebhooksInputData.availableEvents[0][1]);
}
@Test(groups = "unit")
public void testTOJSON() {
EventType eventType = createEventType();
Assert.assertEquals(eventType.toJSON().length() == 0, false);
logger.info("EventTypeJSON = " + eventType.toJSON());
}
@Test(groups = "unit")
public void testTOString() {
EventType eventType = createEventType();
Assert.assertEquals(eventType.toString().length() == 0, false);
}
@Test(groups = "integration")
public void testSubscribedEventTypes() throws PayPalRESTException {
Webhook webhookRequest = new Webhook();
String uuid = UUID.randomUUID().toString();
webhookRequest.setUrl(WebhooksInputData.WEBHOOK_URL + uuid);
webhookRequest.setEventTypes(EventTypeListTestCase.createAuthEventTypeList());
Webhook webhookResponse = webhookRequest.create(TestConstants.SANDBOX_CONTEXT, webhookRequest);
String webhookId = webhookResponse.getId();
EventTypeList eventTypeList = EventType.subscribedEventTypes(TestConstants.SANDBOX_CONTEXT, webhookId);
logger.info("Response = " + eventTypeList.toJSON());
Assert.assertNotNull(eventTypeList.getEventTypes());
Assert.assertEquals(eventTypeList.getEventTypes().size(), 2);
Assert.assertEquals(eventTypeList.getEventTypes().get(0).getName(), WebhooksInputData.availableEvents[2][0]);
Assert.assertEquals(eventTypeList.getEventTypes().get(1).getName(), WebhooksInputData.availableEvents[1][0]);
Assert.assertNotEquals(eventTypeList.getEventTypes().size(), WebhooksInputData.availableEvents.length);
}
@Test(groups = "integration")
public void testAvailableEventTypes() throws PayPalRESTException {
EventTypeList eventTypeList = EventType.availableEventTypes(TestConstants.SANDBOX_CONTEXT);
Assert.assertNotNull(eventTypeList.getEventTypes());
Assert.assertTrue(eventTypeList.getEventTypes().size() > WebhooksInputData.availableEvents.length);
}
}
| 3,695 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/CreditCardTestCase.java | package com.paypal.api.payments;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.util.TestConstants;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class CreditCardTestCase {
private static final Logger logger = Logger
.getLogger(CreditCardTestCase.class);
public CreditCard creditCard;
public static String createdCreditCardId = null;
public static final String TYPE = "visa";
public static final String NUMBER = "4329685037393232";
public static final String FIRSTNAME = "Joe";
public static final String LASTNAME = "Shopper";
public static final int EXPMONTH = 11;
public static final int EXPYEAR = 2018;
public static final String CVV2 = "874";
public static final String ID = "12345";
public static final String EXTERNAL_CUSTOMER_ID = "12345";
public static final String STATE = "Approved";
public static final String VALIDUNTIL = "2020";
public static final Address BILLING_ADDRESS = AddressTestCase.createAddress();
public static CreditCard createCreditCard() {
CreditCard creditCard = new CreditCard();
creditCard.setBillingAddress(BILLING_ADDRESS).setExpireMonth(EXPMONTH)
.setExpireYear(EXPYEAR).setFirstName(FIRSTNAME)
.setLastName(LASTNAME).setNumber(NUMBER).setType(TYPE)
.setCvv2(CVV2).setBillingAddress(BILLING_ADDRESS).setId(ID)
.setState(STATE).setValidUntil(VALIDUNTIL);
return creditCard;
}
public static CreditCard createDummyCreditCard() {
CreditCard creditCard = new CreditCard();
creditCard.setBillingAddress(BILLING_ADDRESS);
creditCard.setExpireMonth(EXPMONTH);
creditCard.setExpireYear(EXPYEAR);
creditCard.setFirstName(FIRSTNAME);
creditCard.setLastName(LASTNAME);
creditCard.setNumber(NUMBER);
creditCard.setType(TYPE);
creditCard.setCvv2(CVV2);
creditCard.setBillingAddress(BILLING_ADDRESS);
creditCard.setId(ID);
creditCard.setExternalCustomerId(EXTERNAL_CUSTOMER_ID);
creditCard.setState(STATE);
creditCard.setValidUntil(VALIDUNTIL);
List<Links> links = new ArrayList<Links>();
links.add(LinksTestCase.createLinks());
creditCard.setLinks(links);
return creditCard;
}
@Test(groups = "unit")
public void testConstruction() {
CreditCard creditCard = createDummyCreditCard();
Assert.assertEquals(creditCard.getCvv2String(), CVV2);
Assert.assertEquals(creditCard.getExpireMonth(), EXPMONTH);
Assert.assertEquals(creditCard.getExpireYear(), EXPYEAR);
Assert.assertEquals(creditCard.getFirstName(), FIRSTNAME);
Assert.assertEquals(creditCard.getLastName(), LASTNAME);
Assert.assertEquals(creditCard.getNumber(), NUMBER);
Assert.assertEquals(creditCard.getType(), TYPE);
Assert.assertEquals(creditCard.getBillingAddress().getCity(),
AddressTestCase.CITY);
Assert.assertEquals(creditCard.getId(), ID);
Assert.assertEquals(creditCard.getExternalCustomerId(), EXTERNAL_CUSTOMER_ID);
Assert.assertEquals(creditCard.getState(), STATE);
Assert.assertEquals(creditCard.getValidUntil(), VALIDUNTIL);
Assert.assertEquals(creditCard.getLinks().size(), 1);
}
@Test(groups = "unit")
public void testCvv2() {
logger.info("**** Test CreditCard CVV2 ****");
CreditCard creditCard = createDummyCreditCard();
// empty CVV2
creditCard.setCvv2("");
Assert.assertEquals("", creditCard.getCvv2String());
// valid CVV2
creditCard.setCvv2(123);
Assert.assertEquals("123", creditCard.getCvv2String());
// CVV2 starting with 0
creditCard.setCvv2("012");
Assert.assertEquals("012", creditCard.getCvv2String());
}
@Test(groups = "integration")
public void createCreditCardTest() throws PayPalRESTException {
CreditCard creditCard = new CreditCard();
creditCard.setExpireMonth(EXPMONTH);
creditCard.setExpireYear(EXPYEAR);
creditCard.setNumber(NUMBER);
creditCard.setType(TYPE);
this.creditCard = creditCard.create(TestConstants.SANDBOX_CONTEXT);
Assert.assertEquals(true,
"ok".equalsIgnoreCase(this.creditCard.getState()));
logger.info("Created Credit Card status = "
+ this.creditCard.getState());
createdCreditCardId = this.creditCard.getId();
}
@Test(groups = "integration", dependsOnMethods = { "createCreditCardTest" })
public void testGetCreditCard() throws PayPalRESTException {
CreditCard retrievedCreditCard = CreditCard.get(TestConstants.SANDBOX_CONTEXT, createdCreditCardId);
Assert.assertEquals(
true,
this.creditCard.getId().equalsIgnoreCase(
retrievedCreditCard.getId()));
}
@Test(groups = "integration", dependsOnMethods = { "testGetCreditCard" })
public void testUpdateCreditCard() throws PayPalRESTException {
// set up patch request
Patch patch = new Patch();
patch.setOp("replace");
patch.setPath("/expire_year");
patch.setValue(new Integer(2020));
List<Patch> patchRequest = new ArrayList<Patch>();
patchRequest.add(patch);
// send patch request
CreditCard creditCard = new CreditCard();
creditCard.setId(createdCreditCardId);
CreditCard retrievedCreditCard = creditCard.update(TestConstants.SANDBOX_CONTEXT, patchRequest);
Assert.assertEquals(2020, retrievedCreditCard.getExpireYear());
}
@Test(groups = "integration", dependsOnMethods = { "testUpdateCreditCard" })
public void deleteCreditCard() throws PayPalRESTException {
CreditCard retrievedCreditCard = CreditCard.get(TestConstants.SANDBOX_CONTEXT, createdCreditCardId);
retrievedCreditCard.delete(TestConstants.SANDBOX_CONTEXT);
try {
CreditCard.get(TestConstants.SANDBOX_CONTEXT, createdCreditCardId);
} catch (Exception e) {
e.printStackTrace();
}
}
// Pass empty HashMap
@Test(groups = "integration", dependsOnMethods = { "createCreditCardTest" })
public void testListCreditCardContextOnly() throws PayPalRESTException {
CreditCardHistory creditCards = CreditCard.list(TestConstants.SANDBOX_CONTEXT);
Assert.assertTrue(creditCards.getTotalItems() > 0);
}
// Pass empty HashMap
@Test(groups = "integration", dependsOnMethods = { "createCreditCardTest" })
public void testListCreditCard() throws PayPalRESTException {
Map<String, String> containerMap = new HashMap<String, String>();
CreditCardHistory creditCards = CreditCard.list(TestConstants.SANDBOX_CONTEXT, containerMap);
Assert.assertTrue(creditCards.getTotalItems() > 0);
}
// Pass HashMap with count
@Test(groups = "integration", dependsOnMethods = { "createCreditCardTest" })
public void testListCreditCardwithCount() throws PayPalRESTException {
Map<String, String> containerMap = new HashMap<String, String>();
containerMap.put("count", "10");
CreditCardHistory creditCards = CreditCard.list(TestConstants.SANDBOX_CONTEXT, containerMap);
Assert.assertTrue(creditCards.getTotalItems() > 0);
}
@Test(groups = "integration", dependsOnMethods = { "testGetCreditCard" })
public void getCreditCardForNull() {
try {
CreditCard.get(TestConstants.SANDBOX_CONTEXT, null);
} catch (IllegalArgumentException e) {
Assert.assertTrue(e != null,
"Illegal Argument Exception not thrown for null arguments");
} catch (PayPalRESTException e) {
Assert.fail();
}
}
@Test
public void testCreditCardUnknownFileConfiguration() {
try {
CreditCard.initConfig(new File("unknown.properties"));
} catch (PayPalRESTException e) {
Assert.assertEquals(e.getCause().getClass().getSimpleName(),
"FileNotFoundException");
}
}
@Test
public void testCreditCardInputStreamConfiguration() {
try {
File testFile = new File(".",
"src/test/resources/sdk_config.properties");
FileInputStream fis = new FileInputStream(testFile);
CreditCard.initConfig(fis);
} catch (PayPalRESTException e) {
Assert.fail("[sdk_config.properties] stream loading failed");
} catch (FileNotFoundException e) {
Assert.fail("[sdk_config.properties] file is not available");
}
}
@Test
public void testCreditCardPropertiesConfiguration() {
try {
File testFile = new File(".",
"src/test/resources/sdk_config.properties");
Properties props = new Properties();
FileInputStream fis = new FileInputStream(testFile);
props.load(fis);
CreditCard.initConfig(props);
} catch (FileNotFoundException e) {
Assert.fail("[sdk_config.properties] file is not available");
} catch (IOException e) {
Assert.fail("[sdk_config.properties] file is not loaded into properties");
}
}
@Test
public void testTOJSON() {
CreditCard creditCard = createCreditCard();
Assert.assertEquals(creditCard.toJSON().length() == 0, false);
}
@Test
public void testTOString() {
CreditCard creditCard = createCreditCard();
Assert.assertEquals(creditCard.toString().length() == 0, false);
}
}
| 3,696 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/CurrencyTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.paypal.base.rest.JSONFormatter;
public class CurrencyTestCase {
public static String getJson() {
return "{\"currency\":\"TestSample\",\"value\":\"12.34\"}";
}
public static Currency getObject() {
return JSONFormatter.fromJSON(getJson(), Currency.class);
}
@Test(groups = "unit")
public void testJsontoObject() {
Currency obj = CurrencyTestCase.getObject();
Assert.assertEquals(obj.getCurrency(), "TestSample");
Assert.assertEquals(obj.getValue(), "12.34");
}
}
| 3,697 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/FundingInstrumentTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
public class FundingInstrumentTestCase {
public static final CreditCard CREDITCARD = CreditCardTestCase
.createCreditCard();
public static FundingInstrument createFundingInstrument() {
FundingInstrument fundingInstrument = new FundingInstrument();
CreditCard creditCard = CreditCardTestCase.createCreditCard();
fundingInstrument.setCreditCard(creditCard);
CreditCardToken creditCardToken = CreditCardTokenTestCase
.createCreditCardToken();
fundingInstrument.setCreditCardToken(creditCardToken);
return fundingInstrument;
}
@Test(groups = "unit")
public void testConstruction() {
FundingInstrument fundingInsturment = createFundingInstrument();
Assert.assertEquals(fundingInsturment.getCreditCardToken()
.getCreditCardId(), CreditCardTokenTestCase.CREDITCARDID);
Assert.assertEquals(fundingInsturment.getCreditCard().getCvv2String(),
CreditCardTestCase.CVV2);
}
@Test(groups = "unit")
public void testTOJSON() {
FundingInstrument fundingInsturment = createFundingInstrument();
Assert.assertEquals(fundingInsturment.toJSON().length() == 0, false);
}
@Test(groups = "unit")
public void testTOString() {
FundingInstrument fundingInsturment = createFundingInstrument();
Assert.assertEquals(fundingInsturment.toString().length() == 0, false);
}
}
| 3,698 |
0 | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api | Create_ds/PayPal-Java-SDK/rest-api-sdk/src/test/java/com/paypal/api/payments/PayoutSenderBatchHeaderTestCase.java | package com.paypal.api.payments;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.paypal.base.rest.JSONFormatter;
public class PayoutSenderBatchHeaderTestCase {
public static String getJson() {
return "{\"sender_batch_id\":\"TestSample\",\"email_subject\":\"TestSample\",\"recipient_type\":\"TestSample\"}";
}
public static PayoutSenderBatchHeader getObject() {
return JSONFormatter.fromJSON(getJson(), PayoutSenderBatchHeader.class);
}
@Test(groups = "unit")
public void testJsontoObject() {
PayoutSenderBatchHeader obj = PayoutSenderBatchHeaderTestCase.getObject();
Assert.assertEquals(obj.getRecipientType(), "TestSample");
Assert.assertEquals(obj.getEmailSubject(), "TestSample");
Assert.assertEquals(obj.getSenderBatchId(), "TestSample");
}
}
| 3,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.