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/cxf-build-utils/xml2fastinfoset-plugin/src/main/java/org/apache/cxf/maven_plugin | Create_ds/cxf-build-utils/xml2fastinfoset-plugin/src/main/java/org/apache/cxf/maven_plugin/xml2fastinfoset/XML2FastInfosetCompilerMojo.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.cxf.maven_plugin.xml2fastinfoset;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.sonatype.plexus.build.incremental.BuildContext;
import org.xml.sax.SAXException;
import com.sun.xml.fastinfoset.sax.SAXDocumentSerializer;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.Scanner;
/**
* Compile XML resources to FastInfoset XML resources.
*
* @goal xml2fastinfoset
* @phase process-resources
* @threadSafe
*/
public class XML2FastInfosetCompilerMojo extends AbstractMojo {
private static final String[] EMPTY_STRING_ARRAY = {};
private static final String[] DEFAULT_INCLUDES = {"**/*.xml"};
/**
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The resource directories containing the XML files to be compiled.
*
* @parameter expression="${project.resources}"
* @required
* @readonly
*/
private List resources;
/**
* A list of inclusion filters.
*
* @parameter
*/
private Set includes = new HashSet();
/**
* A list of exclusion filters.
*
* @parameter
*/
private Set excludes = new HashSet();
/**
* The directory for the results.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File outputDirectory;
/** @component */
protected BuildContext buildContext;
@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
for (Iterator it = resources.iterator(); it.hasNext();) {
Resource resource = (Resource)it.next();
String targetPath = resource.getTargetPath();
File resourceDirectory = new File(resource.getDirectory());
if (!resourceDirectory.isAbsolute()) {
resourceDirectory = new File(project.getBasedir(), resourceDirectory.getPath());
}
if (!resourceDirectory.exists()) {
getLog().debug("Resource directory does not exist: " + resourceDirectory);
continue;
}
Scanner scanner = buildContext.newScanner(resourceDirectory);
if (includes != null && !includes.isEmpty()) {
scanner.setIncludes((String[])includes.toArray(EMPTY_STRING_ARRAY));
} else {
scanner.setIncludes(DEFAULT_INCLUDES);
}
if (excludes != null && !excludes.isEmpty()) {
scanner.setExcludes((String[])excludes.toArray(EMPTY_STRING_ARRAY));
}
scanner.addDefaultExcludes();
scanner.scan();
List includedFiles = Arrays.asList(scanner.getIncludedFiles());
getLog().debug("FastInfosetting " + includedFiles.size() + " resource"
+ (includedFiles.size() > 1 ? "s" : "")
+ (targetPath == null ? "" : " to " + targetPath));
if (includedFiles.size() > 0) {
// this part is required in case the user specified "../something"
// as destination
// see MNG-1345
if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
throw new MojoExecutionException("Cannot create resource output directory: "
+ outputDirectory);
}
}
for (Iterator j = includedFiles.iterator(); j.hasNext();) {
String name = (String)j.next();
String destination = name.replaceFirst("\\.xml$", ".fixml");
if (targetPath != null) {
destination = targetPath + "/" + name;
}
File source = new File(resourceDirectory, name);
File destinationFile = new File(outputDirectory, destination);
if (!destinationFile.getParentFile().exists()) {
destinationFile.getParentFile().mkdirs();
}
try {
compileFile(source, destinationFile);
} catch (Exception e) {
throw new MojoExecutionException("Error copying resource " + source, e);
}
buildContext.refresh(destinationFile);
}
}
}
private void compileFile(File sourceFile, File destinationFile) throws ParserConfigurationException,
SAXException, IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sourceFile);
fos = new FileOutputStream(destinationFile);
dehydrate(fis, fos);
fis.close();
fos.close();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
// nothing.
}
}
}
private void dehydrate(InputStream input, OutputStream output) throws ParserConfigurationException,
SAXException, IOException {
// Create Fast Infoset SAX serializer
SAXDocumentSerializer saxDocumentSerializer = new SAXDocumentSerializer();
// Set the output stream
saxDocumentSerializer.setOutputStream(output);
// Instantiate JAXP SAX parser factory
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
/*
* Set parser to be namespace aware Very important to do otherwise
* invalid FI documents will be created by the SAXDocumentSerializer
*/
saxParserFactory.setNamespaceAware(true);
// Instantiate the JAXP SAX parser
SAXParser saxParser = saxParserFactory.newSAXParser();
// Set the lexical handler
saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", saxDocumentSerializer);
// Parse the XML document and convert to a fast infoset document
saxParser.parse(input, saxDocumentSerializer);
}
}
| 7,600 |
0 | Create_ds/paypal-sample-merchant-server/.mvn | Create_ds/paypal-sample-merchant-server/.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.5";
/**
* 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();
}
}
| 7,601 |
0 | Create_ds/paypal-sample-merchant-server/src/test/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/test/java/com/braintree/braintreep4psamplemerchant/SampleMerchantApplicationTests.java | package com.braintree.braintreep4psamplemerchant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class SampleMerchantApplicationTests {
@Test
public void contextLoads() {
}
}
| 7,602 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/TokenUtil.java | package com.braintree.braintreep4psamplemerchant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Base64;
@Component
class TokenUtil {
private String clientIdUS;
private String clientSecretUS;
private String clientIdUK;
private String clientSecretUK;
@Autowired
public TokenUtil(@Value("${us.client.id}") String clientIdUS,
@Value("${us.client.secret}") String clientSecretUS,
@Value("${uk.client.id}") String clientIdUK,
@Value("${uk.client.secret}") String clientSecretUK) {
this.clientIdUS = clientIdUS;
this.clientSecretUS = clientSecretUS;
this.clientIdUK = clientIdUK;
this.clientSecretUK = clientSecretUK;
}
String getTokenAuthorizationHeaderForLowScope(String countryCode) {
String clientId = "UK".equalsIgnoreCase(countryCode) ? clientIdUK : clientIdUS;
return "Basic " + Base64.getEncoder().encodeToString(clientId.getBytes());
}
String getTokenAuthorizationHeaderForFullScope(String countryCode) {
String clientId = "UK".equalsIgnoreCase(countryCode) ? clientIdUK : clientIdUS;
String clientSecret = "UK".equalsIgnoreCase(countryCode) ? clientSecretUK : clientSecretUS;
return "Basic " + Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
}
}
| 7,603 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/Order.java | package com.braintree.braintreep4psamplemerchant;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order {
private String id;
private String status;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| 7,604 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/SampleMerchantApplication.java | package com.braintree.braintreep4psamplemerchant;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class SampleMerchantApplication {
public static void main(String[] args) {
SpringApplication.run(SampleMerchantApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
| 7,605 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/ProcessOrderRequest.java | package com.braintree.braintreep4psamplemerchant;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ProcessOrderRequest {
private String orderId;
private String intent;
private String countryCode;
public String getOrderId() {
return orderId;
}
public void setOrderId(final String orderId) {
this.orderId = orderId;
}
public String getIntent() {
return intent;
}
public void setIntent(final String intent) {
this.intent = intent;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(final String countryCode) {
this.countryCode = countryCode;
}
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
}
| 7,606 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/OrdersV2Client.java | package com.braintree.braintreep4psamplemerchant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class OrdersV2Client {
private static final String ORDERS_V2_PATH = "/v2/checkout/orders";
private RestTemplate restTemplate;
private PayPalTokenClient payPalTokenService;
private String url;
@Autowired
public OrdersV2Client(RestTemplate restTemplate,
PayPalTokenClient payPalTokenService,
@Value("${url}") String url) {
this.restTemplate = restTemplate;
this.payPalTokenService = payPalTokenService;
this.url = url;
}
Order createOrder(CreateOrderRequest orderBody, String countryCode) {
HttpHeaders orderHeaders = new HttpHeaders();
orderHeaders.add("Authorization", "Bearer " + payPalTokenService.getFullScopedToken(countryCode).getToken());
orderHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<CreateOrderRequest> orderRequest = new HttpEntity<>(orderBody, orderHeaders);
ResponseEntity<Order> orderResponse = restTemplate.postForEntity(url + ORDERS_V2_PATH, orderRequest, Order.class);
System.out.println("OrderID: " + orderResponse.getBody().getId());
System.out.println("HTTP status code: " + orderResponse.getStatusCode());
System.out.println("Order response headers" + orderResponse.getHeaders());
// TODO: add error handling or logging?
return orderResponse.getBody();
}
Order processOrder(ProcessOrderRequest processOrderRequest) {
HttpHeaders orderHeaders = new HttpHeaders();
orderHeaders.add("Authorization", "Bearer " + payPalTokenService.getFullScopedToken(processOrderRequest.getCountryCode()).getToken());
orderHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> orderRequest = new HttpEntity<>("", orderHeaders);
ResponseEntity<Order> orderResponse = restTemplate.postForEntity(url + ORDERS_V2_PATH +"/"+ processOrderRequest.getOrderId() +"/" + processOrderRequest.getIntent(),
orderRequest,
Order.class);
System.out.println("OrderID: " + orderResponse.getBody().getId());
System.out.println("HTTP status code: " + orderResponse.getStatusCode());
System.out.println("Order response headers" + orderResponse.getHeaders());
// TODO: add error handling or logging?
return orderResponse.getBody();
}
}
| 7,607 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/PayPalTokenClient.java | package com.braintree.braintreep4psamplemerchant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
@Component
public class PayPalTokenClient {
private static final String TOKEN_PATH = "/v1/oauth2/token";
private final RestTemplate restTemplate;
private final TokenUtil tokenUtil;
private final String url;
@Autowired
public PayPalTokenClient(RestTemplate restTemplate, TokenUtil tokenUtil, @Value("${url}") String url) {
this.restTemplate = restTemplate;
this.tokenUtil = tokenUtil;
this.url = url;
}
public IdToken getLowScopedToken(final String countryCode) {
return getToken(tokenUtil.getTokenAuthorizationHeaderForLowScope(countryCode));
}
public IdToken getFullScopedToken(final String countryCode) {
return getToken(tokenUtil.getTokenAuthorizationHeaderForFullScope(countryCode));
}
private IdToken getToken(final String authorizationHeader) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", authorizationHeader);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("grant_type", "client_credentials");
body.add("response_type", "id_token");
body.add("entry_point", "paypal_native_sdk");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
ResponseEntity<IdToken> response = restTemplate.postForEntity(
url + TOKEN_PATH,
request,
IdToken.class);
System.out.println("id_token: " + response.getBody().getToken());
return response.getBody();
}
}
| 7,608 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/IdToken.java | package com.braintree.braintreep4psamplemerchant;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class IdToken {
private String token;
@JsonProperty("id_token")
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| 7,609 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/RestController.java | package com.braintree.braintreep4psamplemerchant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@org.springframework.web.bind.annotation.RestController
public class RestController {
private OrdersV2Client ordersV2Client;
private PayPalTokenClient payPalTokenClient;
@Autowired
public RestController(OrdersV2Client ordersV2Client, PayPalTokenClient payPalTokenClient) {
this.ordersV2Client = ordersV2Client;
this.payPalTokenClient = payPalTokenClient;
}
@GetMapping(path = "/id-token")
IdToken getIDToken(@RequestParam(value = "countryCode") String countryCode) {
System.out.println("******************************");
System.out.println("REQUEST to /v1/oauth2/token:");
System.out.println("Country code: " + countryCode);
return payPalTokenClient.getLowScopedToken(countryCode);
}
@PostMapping(path = "/order")
Order createOrder(@RequestBody CreateOrderRequest createOrderRequest,
@RequestParam(value = "countryCode") String countryCode) {
System.out.println("******************************");
System.out.println("REQUEST to /v2/checkout/orders:");
System.out.println("Order Request body: " + createOrderRequest.toString());
System.out.println("Country code: " + countryCode);
return ordersV2Client.createOrder(createOrderRequest, countryCode);
}
@PostMapping(path = "/capture-order")
Order captureOrder(@RequestBody ProcessOrderRequest processOrderRequest) {
System.out.println("******************************");
System.out.println("REQUEST to /v2/checkout/capture-order:");
System.out.println("Process Order Request body: " + processOrderRequest.toString());
return ordersV2Client.processOrder(processOrderRequest);
}
@PostMapping("/authorize-order")
Order authorizeOrder(@RequestBody ProcessOrderRequest processOrderRequest) {
System.out.println("******************************");
System.out.println("REQUEST to /v2/checkout/authorize-order:");
System.out.println("Process Order Request body: " + processOrderRequest.toString());
return ordersV2Client.processOrder(processOrderRequest);
}
}
| 7,610 |
0 | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree | Create_ds/paypal-sample-merchant-server/src/main/java/com/braintree/braintreep4psamplemerchant/CreateOrderRequest.java | package com.braintree.braintreep4psamplemerchant;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreateOrderRequest {
private String intent;
private List<PurchaseUnit> purchaseUnits;
private ApplicationContext applicationContext;
public String getIntent() {
return intent;
}
public void setIntent(String intent) {
this.intent = intent;
}
@JsonProperty("purchase_units")
public List<PurchaseUnit> getPurchaseUnits() {
return purchaseUnits;
}
@JsonProperty("purchase_units")
public void setPurchaseUnits(List<PurchaseUnit> purchaseUnits) {
this.purchaseUnits = purchaseUnits;
}
@JsonProperty("application_context")
public ApplicationContext getApplicationContext() { return applicationContext; }
@JsonProperty("application_context")
public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; }
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
public static class PurchaseUnit {
private Amount amount;
private Payee payee;
public Amount getAmount() {
return amount;
}
public void setAmount(Amount amount) {
this.amount = amount;
}
public Payee getPayee() { return payee; }
public void setPayee(Payee payee) { this.payee = payee; }
public static class Amount {
private String currencyCode;
private String value;
@JsonProperty("currency_code")
public String getCurrencyCode() {
return currencyCode;
}
@JsonProperty("currency_code")
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
static class Payee {
private String emailAddress;
@JsonProperty("email_address")
public String getEmailAddress() {
return emailAddress;
}
@JsonProperty("email_address")
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
}
public static class ApplicationContext {
private String returnURL;
private String cancelURL;
@JsonProperty("return_url")
public String getReturnURL() { return returnURL; }
@JsonProperty("return_url")
public void setReturnURL(String returnURL) { this.returnURL = returnURL; }
@JsonProperty("cancel_url")
public String getCancelURL() { return cancelURL; }
@JsonProperty("cancel_url")
public void setCancelURL(String cancelURL) { this.cancelURL = cancelURL; }
}
}
| 7,611 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/androidTest/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/androidTest/java/com/miracl/mpinsdk/test/MPinSDKTest.java | package com.miracl.mpinsdk.test;
import android.test.InstrumentationTestCase;
import com.miracl.mpinsdk.MPinSDK;
import com.miracl.mpinsdk.model.Status;
import com.miracl.mpinsdk.model.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
public class MPinSDKTest extends InstrumentationTestCase {
private static final String USER_ID = "testUser";
private static final String BACKEND = "http://ec2-52-28-120-46.eu-central-1.compute.amazonaws.com";
static {
System.loadLibrary("AndroidMpinSDK");
}
private MPinSDK m_sdk = null;
private User m_user = null;
@Before
public void setUp() {
// Init the sdk
m_sdk = new MPinSDK();
HashMap<String, String> config = new HashMap<String, String>();
config.put(MPinSDK.CONFIG_BACKEND, BACKEND);
Status s = m_sdk.Init(config, getInstrumentation().getTargetContext());
assertEquals("MPinSDK::Init failed: '" + s.getErrorMessage() + "'.", Status.Code.OK, s.getStatusCode());
// Delete the USER_ID user if it was leftover in sdk for some reason (probably from previous test run)
LinkedList<User> users = new LinkedList<User>();
m_sdk.ListUsers(users);
Iterator<User> i = users.iterator();
while (i.hasNext()) {
User user = i.next();
if (user.getId().equals(USER_ID)) {
m_sdk.DeleteUser(user);
}
}
m_user = null;
}
@After
public void tearDown() {
if (m_user != null) {
m_sdk.DeleteUser(m_user);
m_user = null;
}
m_sdk.close();
m_sdk = null;
}
@Test
public void testUserShouldRegisterAndAuthenticate() {
m_user = m_sdk.MakeNewUser(USER_ID);
Status s = m_sdk.StartRegistration(m_user);
assertEquals("MPinSDK::StartRegistration failed: '" + s.getErrorMessage() + "'.", Status.Code.OK, s.getStatusCode());
assertEquals("Unexpected user state after MPinSDKv2::StartRegistration (should be force activated).", User.State.ACTIVATED, m_user.getState());
s = m_sdk.ConfirmRegistration(m_user);
assertEquals("MPinSDK::ConfirmRegistration failed: '" + s.getErrorMessage() + "'.", Status.Code.OK, s.getStatusCode());
s = m_sdk.FinishRegistration(m_user, "1234");
assertEquals("MPinSDK::FinishRegistration failed: '" + s.getErrorMessage() + "'.", Status.Code.OK, s.getStatusCode());
assertEquals("Unexpected user state after MPinSDKv2::FinishRegistration.", User.State.REGISTERED, m_user.getState());
s = m_sdk.StartAuthentication(m_user);
assertEquals("MPinSDK::StartAuthentication failed: '" + s.getErrorMessage() + "'.", Status.Code.OK, s.getStatusCode());
StringBuilder authResultData = new StringBuilder();
s = m_sdk.FinishAuthentication(m_user, "1234", authResultData);
assertEquals("MPinSDK::FinishAuthentication failed: '" + s.getErrorMessage() + "'.", Status.Code.OK, s.getStatusCode());
}
}
| 7,612 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/MPinSDK.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 com.miracl.mpinsdk;
import android.content.Context;
import com.miracl.mpinsdk.model.OTP;
import com.miracl.mpinsdk.model.ServiceDetails;
import com.miracl.mpinsdk.model.SessionDetails;
import com.miracl.mpinsdk.model.Status;
import com.miracl.mpinsdk.model.User;
import java.io.Closeable;
import java.util.List;
import java.util.Map;
public class MPinSDK implements Closeable {
public static final String CONFIG_BACKEND = "backend";
private long mPtr;
public MPinSDK() {
mPtr = nConstruct();
}
@Override
public void close() {
synchronized (this) {
nDestruct(mPtr);
mPtr = 0;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
public Status Init(Map<String, String> config, Context context) {
return nInit(mPtr, config, context);
}
public Status Init(Map<String, String> config, Context context, Map<String, String> customHeaders) {
return nInitWithCustomHeaders(mPtr, config, context, customHeaders);
}
public void SetClientId(String clientId) {
nSetClientId(mPtr, clientId);
}
public Status TestBackend(String server) {
return nTestBackend(mPtr, server);
}
public Status TestBackend(String server, String rpsPrefix) {
return nTestBackendRPS(mPtr, server, rpsPrefix);
}
public Status SetBackend(String server) {
return nSetBackend(mPtr, server);
}
public Status SetBackend(String server, String rpsPrefix) {
return nSetBackendRPS(mPtr, server, rpsPrefix);
}
public User MakeNewUser(String id) {
return nMakeNewUser(mPtr, id, "");
}
public User MakeNewUser(String id, String deviceName) {
return nMakeNewUser(mPtr, id, deviceName);
}
public Status StartRegistration(User user) {
return nStartRegistration(mPtr, user, "", "");
}
public Status StartRegistration(User user, String activateCode) {
return nStartRegistration(mPtr, user, activateCode, "");
}
public Status StartRegistration(User user, String activateCode, String userData) {
return nStartRegistration(mPtr, user, activateCode, userData);
}
public Status RestartRegistration(User user) {
return nRestartRegistration(mPtr, user, "");
}
public Status RestartRegistration(User user, String userData) {
return nRestartRegistration(mPtr, user, userData);
}
public Status ConfirmRegistration(User user) {
return nConfirmRegistration(mPtr, user, "");
}
public Status ConfirmRegistration(User user, String pushMessageIdentifier) {
return nConfirmRegistration(mPtr, user, pushMessageIdentifier);
}
public Status FinishRegistration(User user, String pin) {
return nFinishRegistration(mPtr, user, pin);
}
public Status StartAuthentication(User user) {
return nStartAuthentication(mPtr, user);
}
public Status StartAuthentication(User user, String accessCode) {
return nStartAuthenticationAccessCode(mPtr, user, accessCode);
}
public Status CheckAccessNumber(String accessNumber) {
return nCheckAccessNumber(mPtr, accessNumber);
}
public Status FinishAuthentication(User user, String pin) {
return nFinishAuthentication(mPtr, user, pin);
}
public Status FinishAuthentication(User user, String pin, StringBuilder authResultData) {
return nFinishAuthenticationResultData(mPtr, user, pin, authResultData);
}
public Status FinishAuthenticationOTP(User user, String pin, OTP otp) {
return nFinishAuthenticationOTP(mPtr, user, pin, otp);
}
public Status FinishAuthenticationAN(User user, String pin, String accessNumber) {
return nFinishAuthenticationAN(mPtr, user, pin, accessNumber);
}
public Status FinishAuthenticationMFA(User user, String pin, StringBuilder authzCode) {
return nFinishAuthenticationMFA(mPtr, user, pin, authzCode);
}
public Status GetSessionDetails(String accessCode, SessionDetails sessionDetails) {
return nGetSessionDetails(mPtr, accessCode, sessionDetails);
}
public Status GetServiceDetails(String url, ServiceDetails serviceDetails) {
return nGetServiceDetails(mPtr, url, serviceDetails);
}
public void DeleteUser(User user) {
nDeleteUser(mPtr, user);
}
public Status ListUsers(List<User> users) {
return nListUsers(mPtr, users);
}
public Status ListAllUsers(List<User> users) {
return nListAllUsers(mPtr, users);
}
public Status ListUsers(List<User> users, String backend) {
return nListUsersForBackend(mPtr, users, backend);
}
public Status ListBackends(List<String> backends) {
return nListBackends(mPtr, backends);
}
public String GetVersion() {
return nGetVersion(mPtr);
}
public boolean CanLogout(User user) {
return nCanLogout(mPtr, user);
}
public boolean Logout(User user) {
return nLogout(mPtr, user);
}
public String GetClientParam(String key) {
return nGetClientParam(mPtr, key);
}
private native long nConstruct();
private native void nDestruct(long ptr);
private native Status nInit(long ptr, Map<String, String> config, Context context);
private native Status nInitWithCustomHeaders(long ptr, Map<String, String> config, Context context,
Map<String, String> customHeaders);
private native void nSetClientId(long ptr, String clientId);
private native Status nTestBackend(long ptr, String server);
private native Status nTestBackendRPS(long ptr, String server, String rpsPrefix);
private native Status nSetBackend(long ptr, String server);
private native Status nSetBackendRPS(long ptr, String server, String rpsPrefix);
private native User nMakeNewUser(long ptr, String id, String deviceName);
private native Status nStartRegistration(long ptr, User user, String activateCode, String userData);
private native Status nRestartRegistration(long ptr, User user, String userData);
private native Status nConfirmRegistration(long ptr, User user, String pushMessageIdentifier);
private native Status nFinishRegistration(long ptr, User user, String pin);
private native Status nStartAuthentication(long ptr, User user);
private native Status nStartAuthenticationAccessCode(long ptr, User user, String accessCode);
private native Status nCheckAccessNumber(long ptr, String accessNumber);
private native Status nFinishAuthentication(long ptr, User user, String pin);
private native Status nFinishAuthenticationResultData(long ptr, User user, String pin, StringBuilder authResultData);
private native Status nFinishAuthenticationOTP(long ptr, User user, String pin, OTP otp);
private native Status nFinishAuthenticationAN(long ptr, User user, String pin, String accessNumber);
private native Status nFinishAuthenticationMFA(long ptr, User user, String pin, StringBuilder authzCode);
private native Status nGetSessionDetails(long ptr, String accessCode, SessionDetails sessionDetails);
private native Status nGetServiceDetails(long ptr, String url, ServiceDetails serviceDetails);
private native void nDeleteUser(long ptr, User user);
private native Status nListUsers(long ptr, List<User> users);
private native Status nListAllUsers(long ptr, List<User> users);
private native Status nListUsersForBackend(long ptr, List<User> users, String backend);
private native Status nListBackends(long ptr, List<String> backends);
private native String nGetVersion(long ptr);
private native boolean nCanLogout(long ptr, User user);
private native boolean nLogout(long ptr, User user);
private native String nGetClientParam(long ptr, String key);
}
| 7,613 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/net/HTTPConnector.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 com.miracl.mpinsdk.net;
import android.net.Uri;
import android.text.TextUtils;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
public class HTTPConnector implements IHTTPRequest {
private final static String OS_CLASS_HEADER = "X-MIRACL-OS-Class";
private final static String OS_CLASS_VALUE = "android";
private Hashtable<String, String> requestHeaders;
private Hashtable<String, String> queryParams;
private String requestBody;
private int timeout = DEFAULT_TIMEOUT;
private String errorMessage;
private int statusCode;
private Hashtable<String, String> responseHeaders;
private String responseData;
public HTTPConnector() {
super();
}
private static String toString(InputStream is) throws IOException {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, "UTF-8");
char[] buf = new char[512];
StringBuilder str = new StringBuilder();
int i = 0;
while ((i = isr.read(buf)) != -1)
str.append(buf, 0, i);
return str.toString();
} finally {
if (isr != null) {
isr.close();
}
}
}
// / only for test !!!!
public String getContent() {
return requestBody;
}
public Hashtable<String, String> RequestHeaders() {
return requestHeaders;
}
protected HttpURLConnection getConnection(String serviceURL, boolean output)
throws MalformedURLException, IOException {
if (serviceURL.startsWith("/")) {
serviceURL = "http://ec2-54-77-232-113.eu-west-1.compute.amazonaws.com" + serviceURL;
}
HttpURLConnection httpConnection = (HttpURLConnection) new URL(serviceURL).openConnection();
httpConnection.setDoInput(true);
httpConnection.setDoOutput(output);
return httpConnection;
}
protected String HttpMethodMapper(int method) {
switch (method) {
case GET:
return HTTP_GET;
case POST:
return HTTP_POST;
case PUT:
return HTTP_PUT;
case DELETE:
return HTTP_DELETE;
case OPTIONS:
return HTTP_OPTIONS;
default:
return HTTP_PATCH;
}
}
protected String sendRequest(String serviceURL, String http_method, String requestBody,
Hashtable<String, String> requestProperties) throws IOException, HTTPErrorException {
HttpURLConnection connection = null;
DataOutputStream dos = null;
String response = "200 OK";
try {
connection = getConnection(serviceURL, !TextUtils.isEmpty(requestBody));
connection.setRequestMethod(http_method);
connection.setConnectTimeout(timeout);
if (requestProperties != null) {
if (!requestProperties.isEmpty()) {
Enumeration<String> keyEnum = requestProperties.keys();
while (keyEnum.hasMoreElements()) {
String key = keyEnum.nextElement();
connection.setRequestProperty(key, requestProperties.get(key));
}
}
}
connection.setRequestProperty(OS_CLASS_HEADER, OS_CLASS_VALUE);
if (!TextUtils.isEmpty(requestBody)) {
dos = new DataOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(dos, "UTF-8"));
writer.write(requestBody);
writer.close();
}
// Starts the query
connection.connect();
try {
statusCode = connection.getResponseCode();
} catch (IOException e) {
statusCode = connection.getResponseCode();
if (statusCode != 401) {
throw e;
}
}
responseHeaders = new Hashtable<String, String>();
Map<String, List<String>> map = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> propertyList = entry.getValue();
String properties = "";
for (String s : propertyList) {
properties += s;
}
String key = entry.getKey();
if (key == null)
continue;
responseHeaders.put(entry.getKey(), properties);
}
response = toString(connection.getInputStream());
} finally {
if (dos != null) {
dos.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response;
}
protected String sendRequest(String serviceURL, String http_method, String requestBody)
throws IOException, HTTPErrorException {
return sendRequest(serviceURL, http_method, requestBody, null);
}
protected String sendRequest(String serviceURL, String http_method) throws IOException, HTTPErrorException {
return sendRequest(serviceURL, http_method, null);
}
@Override
public void SetHeaders(Hashtable<String, String> headers) {
this.requestHeaders = headers;
}
@Override
public void SetQueryParams(Hashtable<String, String> queryParams) {
this.queryParams = queryParams;
}
@Override
public void SetContent(String data) {
this.requestBody = data;
}
@Override
public void SetTimeout(int seconds) {
if (seconds <= 0)
throw new IllegalArgumentException();
this.timeout = seconds;
}
@Override
public boolean Execute(int method, String url) {
if (TextUtils.isEmpty(url))
throw new IllegalArgumentException();
String fullUrl = url;
if (queryParams != null) {
if (!queryParams.isEmpty()) {
Enumeration<String> keyEnum = queryParams.keys();
fullUrl += "?";
while (keyEnum.hasMoreElements()) {
String key = keyEnum.nextElement();
fullUrl = key + "=" + queryParams.get(key) + "&";
}
fullUrl = fullUrl.substring(0, fullUrl.length() - 1);
}
}
// TODO temporary hack
Uri uri = Uri.parse(fullUrl);
if ("wss".equals(uri.getScheme()))
fullUrl = uri.buildUpon().scheme("https").build().toString();
try {
responseData = sendRequest(fullUrl, HttpMethodMapper(method), requestBody, requestHeaders);
} catch (FileNotFoundException e) {
// No data in response
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
errorMessage = e.getLocalizedMessage();
return false;
}
return true;
}
@Override
public String GetExecuteErrorMessage() {
return errorMessage;
}
@Override
public int GetHttpStatusCode() {
return statusCode;
}
@Override
public Hashtable<String, String> GetResponseHeaders() {
return responseHeaders;
}
@Override
public String GetResponseData() {
return responseData;
}
@SuppressWarnings("serial")
public class HTTPErrorException extends Exception {
private int statusCode;
public HTTPErrorException() {
// TODO Auto-generated constructor stub
}
public HTTPErrorException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public HTTPErrorException(String message, int statusCode) {
super(message);
setStatusCode(statusCode);
}
public HTTPErrorException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public HTTPErrorException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
}
}
| 7,614 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/net/IHTTPRequest.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 com.miracl.mpinsdk.net;
import java.util.Hashtable;
public interface IHTTPRequest {
public static final int GET = 0;
public static final int POST = 1;
public static final int PUT = 2;
public static final int DELETE = 3;
public static final int OPTIONS = 4;
public static final String HTTP_GET = "GET";
public static final String HTTP_POST = "POST";
public static final String HTTP_PUT = "PUT";
public static final String HTTP_DELETE = "DELETE";
public static final String HTTP_OPTIONS = "OPTIONS";
public static final String HTTP_PATCH = "PATCH";
public static final int DEFAULT_TIMEOUT = 10 * 1000;
public void SetHeaders(Hashtable<String, String> headers);
public void SetQueryParams(Hashtable<String, String> queryParams);
public void SetContent(String data);
public void SetTimeout(int seconds);
public boolean Execute(int method, String url);
public String GetExecuteErrorMessage();
public int GetHttpStatusCode();
public Hashtable<String, String> GetResponseHeaders();
public String GetResponseData();
}
| 7,615 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/storage/Storage.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 com.miracl.mpinsdk.storage;
import android.content.Context;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Storage implements IStorage {
public static final String MPIN_STORAGE = "MpinStorage";
public static final String USER_STORAGE = "UserStorage";
public static int chunkSize = 255;
private final Context context;
private final String path;
private String errorMessage = null;
public Storage(Context context, boolean isMpinType) {
super();
this.context = context.getApplicationContext();
path = isMpinType ? MPIN_STORAGE : USER_STORAGE;
}
@Override
public boolean SetData(String data) {
errorMessage = null;
FileOutputStream fos = null;
try {
fos = context.openFileOutput(path, Context.MODE_PRIVATE);
fos.write(data.getBytes());
} catch (FileNotFoundException e) {
errorMessage = e.getLocalizedMessage();
} catch (IOException e) {
errorMessage = e.getLocalizedMessage();
} finally {
if (fos == null)
return false;
try {
fos.close();
} catch (IOException e) {
errorMessage = e.getLocalizedMessage();
}
}
return (errorMessage == null);
}
@Override
public String GetData() {
String data = "";
errorMessage = null;
FileInputStream fis = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
fis = context.openFileInput(path);
byte[] buffer = new byte[chunkSize];
int nbread;
while ((nbread = fis.read(buffer, 0, chunkSize)) > 0) {
bos.write(buffer, 0, nbread);
}
data = new String(bos.toByteArray());
} catch (FileNotFoundException e) {
errorMessage = e.getLocalizedMessage();
} catch (IOException e) {
errorMessage = e.getLocalizedMessage();
} finally {
if (fis != null) {
try {
fis.close();
bos.close();
} catch (IOException e) {
errorMessage = e.getLocalizedMessage();
}
}
}
return data;
}
@Override
public String GetErrorMessage() {
return errorMessage;
}
}
| 7,616 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/storage/IStorage.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 com.miracl.mpinsdk.storage;
public interface IStorage {
boolean SetData(String data);
String GetData();
String GetErrorMessage();
}
| 7,617 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/model/Status.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 com.miracl.mpinsdk.model;
import java.io.Serializable;
public class Status implements Serializable {
private final Code mStatusCode;
private final String mErrorMessage;
public Status(int statusCode, String error) {
this(Code.values()[statusCode], error);
}
public Status(Code statusCode, String error) {
mStatusCode = statusCode;
mErrorMessage = error;
}
public Code getStatusCode() {
return mStatusCode;
}
public String getErrorMessage() {
return mErrorMessage;
}
@Override
public String toString() {
return "Status [StatusCode=" + mStatusCode + ", ErrorMessage='" + mErrorMessage + "']";
}
public enum Code {
OK, CANCELED_BY_USER, // Local error, returned when user cancels pin entering
CRYPTO_ERROR, // Local error in crypto functions
STORAGE_ERROR, // Local storage related error
NETWORK_ERROR, // Local error - cannot connect to remote server (no internet, or invalid server/port)
RESPONSE_PARSE_ERROR, // Local error - cannot parse json response from remote server (invalid json or unexpected
// json structure)
FLOW_ERROR, // Local error - improper MPinSDK class usage
IDENTITY_NOT_AUTHORIZED, // Remote error - the remote server refuses user registration
IDENTITY_NOT_VERIFIED, // Remote error - the remote server refuses user registration because identity is not
// verified
REQUEST_EXPIRED, // Remote error - the register/authentication request expired
REVOKED, // Remote error - cannot get time permit (probably the user is temporary suspended)
INCORRECT_PIN, // Remote error - user entered wrong pin
INCORRECT_ACCESS_NUMBER, // Remote/local error - wrong access number (checksum failed or RPS returned 412)
HTTP_SERVER_ERROR, // Remote error, that was not reduced to one of the above - the remote server returned
// internal server error status (5xx)
HTTP_REQUEST_ERROR, // Remote error, that was not reduced to one of the above - invalid data sent to server, the
// remote server returned 4xx error status
BAD_USER_AGENT, // Remote error - user agent not supported
CLIENT_SECRET_EXPIRED // Remote error - re-registration required because server master secret expired
}
}
| 7,618 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/model/ServiceDetails.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 com.miracl.mpinsdk.model;
public class ServiceDetails {
public String name;
public String backendUrl;
public String rpsPrefix;
public String logoUrl;
}
| 7,619 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/model/User.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 com.miracl.mpinsdk.model;
import java.io.Closeable;
public class User implements Closeable {
public enum State {
INVALID, STARTED_REGISTRATION, ACTIVATED, REGISTERED, BLOCKED
}
private boolean isUserSelected;
private long mPtr;
public String getId() {
return nGetId(mPtr);
}
public State getState() {
switch (nGetState(mPtr)) {
case 1:
return State.STARTED_REGISTRATION;
case 2:
return State.ACTIVATED;
case 3:
return State.REGISTERED;
case 4:
return State.BLOCKED;
default:
return State.INVALID;
}
}
public String getBackend() {
return nGetBackend(mPtr);
}
public boolean isUserSelected() {
return isUserSelected;
}
public void setUserSelected(boolean isUserSelected) {
this.isUserSelected = isUserSelected;
}
@Override
public void close() {
synchronized (this) {
nDestruct(mPtr);
mPtr = 0;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
@Override
public String toString() {
return getId();
}
private User(long ptr) {
mPtr = ptr;
}
private native void nDestruct(long ptr);
private native String nGetId(long ptr);
private native int nGetState(long ptr);
private native String nGetBackend(long ptr);
}
| 7,620 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/model/OTP.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 com.miracl.mpinsdk.model;
import java.io.Serializable;
public class OTP implements Serializable {
public String otp;
public long expireTime;
public int ttlSeconds;
public long nowTime;
public Status status;
}
| 7,621 |
0 | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk | Create_ds/incubator-milagro-mfa-sdk-android/mpinsdk/src/main/java/com/miracl/mpinsdk/model/SessionDetails.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 com.miracl.mpinsdk.model;
public class SessionDetails {
public String prerollId;
public String appName;
public String appIconUrl;
}
| 7,622 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/dto/JsonlinesStandardOutputTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
public class JsonlinesStandardOutputTest {
private ObjectMapper mapper = new ObjectMapper();
@Test
public void testStandardJsonOutputObjectCreation() {
List<Object> featureList = Lists.newArrayList(new Integer("1"), new Double("2.0"), "3");
JsonlinesStandardOutput jsonlinesStandardOutputTest = new JsonlinesStandardOutput(featureList);
Assert.assertNotNull(jsonlinesStandardOutputTest.getFeatures());
Assert.assertTrue(jsonlinesStandardOutputTest.getFeatures().get(0) instanceof Integer);
Assert.assertTrue(jsonlinesStandardOutputTest.getFeatures().get(1) instanceof Double);
Assert.assertTrue(jsonlinesStandardOutputTest.getFeatures().get(2) instanceof String);
}
@Test(expected = NullPointerException.class)
public void testNullInputPassedToConstructor() {
new JsonlinesStandardOutput(null);
}
@Test
public void testParseStandardJsonOutput() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("standard_json_out.json"), "UTF-8");
JsonlinesStandardOutput sjo = mapper.readValue(inputJson, JsonlinesStandardOutput.class);
Assert.assertEquals(sjo.getFeatures(), Lists.newArrayList(1.0, 2.0, 4.0));
}
}
| 7,623 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/dto/SageMakerRequestObjectTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class SageMakerRequestObjectTest {
private ObjectMapper mapper = new ObjectMapper();
@Test
public void testSageMakerRequestObjectCreation() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("basic_input_schema.json"), "UTF-8");
DataSchema schema = mapper.readValue(inputJson, DataSchema.class);
SageMakerRequestObject sro = new SageMakerRequestObject(schema, Lists.newArrayList(1, "C", 38.0));
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().get(0).getName(), "name_1");
Assert.assertEquals(sro.getSchema().getInput().get(1).getName(), "name_2");
Assert.assertEquals(sro.getSchema().getInput().get(2).getName(), "name_3");
Assert.assertEquals(sro.getSchema().getInput().get(0).getType(), "int");
Assert.assertEquals(sro.getSchema().getInput().get(1).getType(), "string");
Assert.assertEquals(sro.getSchema().getInput().get(2).getType(), "double");
Assert.assertEquals(sro.getSchema().getInput().get(0).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(1).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(2).getStruct(), "basic");
Assert.assertEquals(sro.getData(), Lists.newArrayList(1, "C", 38.0));
Assert.assertEquals(sro.getSchema().getOutput().getName(), "features");
Assert.assertEquals(sro.getSchema().getOutput().getType(), "double");
}
@Test(expected = NullPointerException.class)
public void testNullDataPassedToConstructor() {
new SageMakerRequestObject(null, null);
}
@Test
public void testParseBasicInputJson() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("basic_input.json"), "UTF-8");
SageMakerRequestObject sro = mapper.readValue(inputJson, SageMakerRequestObject.class);
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().get(0).getName(), "name_1");
Assert.assertEquals(sro.getSchema().getInput().get(1).getName(), "name_2");
Assert.assertEquals(sro.getSchema().getInput().get(2).getName(), "name_3");
Assert.assertEquals(sro.getSchema().getInput().get(0).getType(), "int");
Assert.assertEquals(sro.getSchema().getInput().get(1).getType(), "string");
Assert.assertEquals(sro.getSchema().getInput().get(2).getType(), "double");
Assert.assertEquals(sro.getSchema().getInput().get(0).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(1).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(2).getStruct(), "basic");
Assert.assertEquals(sro.getData(), Lists.newArrayList(1, "C", 38.0));
Assert.assertEquals(sro.getSchema().getOutput().getName(), "features");
Assert.assertEquals(sro.getSchema().getOutput().getType(), "double");
}
@Test
public void testParseCompleteInputJson() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("complete_input.json"), "UTF-8");
SageMakerRequestObject sro = mapper.readValue(inputJson, SageMakerRequestObject.class);
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().get(0).getName(), "name_1");
Assert.assertEquals(sro.getSchema().getInput().get(1).getName(), "name_2");
Assert.assertEquals(sro.getSchema().getInput().get(2).getName(), "name_3");
Assert.assertEquals(sro.getSchema().getInput().get(0).getType(), "double");
Assert.assertEquals(sro.getSchema().getInput().get(1).getType(), "string");
Assert.assertEquals(sro.getSchema().getInput().get(2).getType(), "double");
Assert.assertEquals(sro.getSchema().getInput().get(0).getStruct(), "vector");
Assert.assertEquals(sro.getSchema().getInput().get(1).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(2).getStruct(), "array");
Assert.assertEquals(sro.getData(),
Lists.newArrayList(Lists.newArrayList(1.0, 2.0, 3.0), "C", Lists.newArrayList(38.0, 24.0)));
Assert.assertEquals(sro.getSchema().getOutput().getName(), "features");
Assert.assertEquals(sro.getSchema().getOutput().getType(), "double");
Assert.assertEquals(sro.getSchema().getOutput().getStruct(), "vector");
}
}
| 7,624 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/dto/JsonlinesTextOutputTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
public class JsonlinesTextOutputTest {
private ObjectMapper mapper = new ObjectMapper();
@Test
public void testStandardJsonOutputObjectCreation() {
JsonlinesTextOutput jsonlinesTextOutputTest = new JsonlinesTextOutput("this is spark ml server");
Assert.assertEquals(jsonlinesTextOutputTest.getSource(), "this is spark ml server");
}
@Test(expected = NullPointerException.class)
public void testNullInputPassedToConstructor() {
new JsonlinesTextOutput(null);
}
@Test
public void testParseStandardJsonOutput() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("text_json_out.json"), "UTF-8");
JsonlinesTextOutput sjo = mapper.readValue(inputJson, JsonlinesTextOutput.class);
Assert.assertEquals(sjo.getSource(), "this is spark ml server");
}
}
| 7,625 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/dto/DataSchemaTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
public class DataSchemaTest {
private ObjectMapper mapper = new ObjectMapper();
List<ColumnSchema> inputCols = Lists.newArrayList(new ColumnSchema("name_1", "type_1", "struct_1"),
new ColumnSchema("name_2", "type_2", "struct_2"));
ColumnSchema outputCol = new ColumnSchema("name_out_1", "type_out_1", "struct_out_1");
@Test
public void testDataSchemaObjectCreation() {
DataSchema ds = new DataSchema(inputCols, outputCol);
Assert.assertEquals(ds.getInput().get(0).getName(), "name_1");
Assert.assertEquals(ds.getInput().get(0).getType(), "type_1");
Assert.assertEquals(ds.getInput().get(0).getStruct(), "struct_1");
Assert.assertEquals(ds.getInput().get(1).getName(), "name_2");
Assert.assertEquals(ds.getInput().get(1).getType(), "type_2");
Assert.assertEquals(ds.getInput().get(1).getStruct(), "struct_2");
Assert.assertEquals(ds.getOutput().getName(), "name_out_1");
Assert.assertEquals(ds.getOutput().getType(), "type_out_1");
Assert.assertEquals(ds.getOutput().getStruct(), "struct_out_1");
}
@Test(expected = NullPointerException.class)
public void testEmptyInputColumnsPassedToConstructor() {
new DataSchema(null, outputCol);
}
@Test(expected = NullPointerException.class)
public void testEmptyOutputColumnsPassedToConstructor() {
new DataSchema(inputCols, null);
}
@Test
public void testParseBasicInputJson() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("basic_input_schema.json"), "UTF-8");
DataSchema schema = mapper.readValue(inputJson, DataSchema.class);
Assert.assertEquals(schema.getInput().size(), 3);
Assert.assertEquals(schema.getInput().get(0).getName(), "name_1");
Assert.assertEquals(schema.getInput().get(1).getName(), "name_2");
Assert.assertEquals(schema.getInput().get(2).getName(), "name_3");
Assert.assertEquals(schema.getInput().get(0).getType(), "int");
Assert.assertEquals(schema.getInput().get(1).getType(), "string");
Assert.assertEquals(schema.getInput().get(2).getType(), "double");
Assert.assertEquals(schema.getInput().get(0).getStruct(), "basic");
Assert.assertEquals(schema.getInput().get(1).getStruct(), "basic");
Assert.assertEquals(schema.getInput().get(2).getStruct(), "basic");
Assert.assertEquals(schema.getOutput().getName(), "features");
Assert.assertEquals(schema.getOutput().getType(), "double");
}
}
| 7,626 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/dto/ColumnSchemaTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.amazonaws.sagemaker.type.DataStructureType;
import org.junit.Assert;
import org.junit.Test;
public class ColumnSchemaTest {
@Test
public void testSingleColumnObjectCreation() {
ColumnSchema columnSchemaTest = new ColumnSchema("test_name", "test_type", "test_struct");
Assert.assertEquals(columnSchemaTest.getName(), "test_name");
Assert.assertEquals(columnSchemaTest.getType(), "test_type");
Assert.assertEquals(columnSchemaTest.getStruct(), "test_struct");
}
@Test(expected = NullPointerException.class)
public void testNullNamePassedToConstructor() {
new ColumnSchema(null, "test_type", "test_struct");
}
@Test(expected = NullPointerException.class)
public void testNullTypePassedToConstructor() {
new ColumnSchema("test_name", null, "test_struct");
}
@Test
public void testNullStructPassedToConstructor() {
ColumnSchema columnSchemaTest = new ColumnSchema("test_name", "test_type", null);
Assert.assertEquals(columnSchemaTest.getStruct(), DataStructureType.BASIC);
}
}
| 7,627 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/dto/BatchExecutionParameterTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import org.junit.Assert;
import org.junit.Test;
public class BatchExecutionParameterTest {
@Test
public void testBatchExecutionParameterObjectCreation() {
BatchExecutionParameter testBatchExecution = new BatchExecutionParameter(1, "SINGLE_RECORD", 5);
Assert.assertEquals(testBatchExecution.getBatchStrategy(), "SINGLE_RECORD");
Assert.assertEquals(new Integer("1"), testBatchExecution.getMaxConcurrentTransforms());
Assert.assertEquals(new Integer("5"), testBatchExecution.getMaxPayloadInMB());
}
@Test(expected = NullPointerException.class)
public void testNullBatchStrategyPassedToConstructor() {
new BatchExecutionParameter(1, null, 5);
}
@Test(expected = NullPointerException.class)
public void testNullConcurrentTransformsPassedToConstructor() {
new BatchExecutionParameter(null, "SINGLE_RECORD", 5);
}
@Test(expected = NullPointerException.class)
public void testNullMaxPayloadPassedToConstructor() {
new BatchExecutionParameter(1, "SINGLE_RECORD", null);
}
}
| 7,628 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/dto/SageMakerRequestListObjectTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class SageMakerRequestListObjectTest {
private ObjectMapper mapper = new ObjectMapper();
private List<List<Object>> listOfListInputForBasicInput;
private List<List<Object>> listOfListInputForMultipleInput;
@Before
public void setup(){
listOfListInputForBasicInput = new ArrayList<>();
listOfListInputForBasicInput.add(Lists.newArrayList(1, "C", 38.0));
listOfListInputForBasicInput.add(Lists.newArrayList(2, "D", 39.0));
listOfListInputForMultipleInput = new ArrayList<>();
listOfListInputForMultipleInput.add(Lists.newArrayList(Lists.newArrayList(1, 2, 3), "C",
Lists.newArrayList(38.0, 24.0)));
listOfListInputForMultipleInput.add(Lists.newArrayList(Lists.newArrayList(4, 5, 6), "D",
Lists.newArrayList(39.0, 25.0)));
}
@Test
public void testSageMakerRequestListObjectCreation() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("basic_input_schema.json"), "UTF-8");
DataSchema schema = mapper.readValue(inputJson, DataSchema.class);
SageMakerRequestListObject sro = new SageMakerRequestListObject(schema, listOfListInputForBasicInput);
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().get(0).getName(), "name_1");
Assert.assertEquals(sro.getSchema().getInput().get(1).getName(), "name_2");
Assert.assertEquals(sro.getSchema().getInput().get(2).getName(), "name_3");
Assert.assertEquals(sro.getSchema().getInput().get(0).getType(), "int");
Assert.assertEquals(sro.getSchema().getInput().get(1).getType(), "string");
Assert.assertEquals(sro.getSchema().getInput().get(2).getType(), "double");
Assert.assertEquals(sro.getSchema().getInput().get(0).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(1).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(2).getStruct(), "basic");
Assert.assertEquals(sro.getData(),listOfListInputForBasicInput);
Assert.assertEquals(sro.getSchema().getOutput().getName(), "features");
Assert.assertEquals(sro.getSchema().getOutput().getType(), "double");
}
@Test(expected = NullPointerException.class)
public void testNullDataPassedToConstructor() {
new SageMakerRequestListObject(null, null);
}
@Test
public void testParseBasicMultipleLinesInputJson() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("basic_multipleLines_input.json"), "UTF-8");
SageMakerRequestListObject sro = mapper.readValue(inputJson, SageMakerRequestListObject.class);
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().get(0).getName(), "name_1");
Assert.assertEquals(sro.getSchema().getInput().get(1).getName(), "name_2");
Assert.assertEquals(sro.getSchema().getInput().get(2).getName(), "name_3");
Assert.assertEquals(sro.getSchema().getInput().get(0).getType(), "int");
Assert.assertEquals(sro.getSchema().getInput().get(1).getType(), "string");
Assert.assertEquals(sro.getSchema().getInput().get(2).getType(), "double");
Assert.assertEquals(sro.getSchema().getInput().get(0).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(1).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(2).getStruct(), "basic");
Assert.assertEquals(sro.getData(), listOfListInputForBasicInput);
Assert.assertEquals(sro.getSchema().getOutput().getName(), "features");
Assert.assertEquals(sro.getSchema().getOutput().getType(), "double");
}
@Test
public void testParseCompleteMultipleLinesInputJson() throws IOException {
String inputJson = IOUtils.toString(this.getClass().getResourceAsStream("complete_multipleLines_input.json"), "UTF-8");
SageMakerRequestListObject sro = mapper.readValue(inputJson, SageMakerRequestListObject.class);
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().size(), 3);
Assert.assertEquals(sro.getSchema().getInput().get(0).getName(), "name_1");
Assert.assertEquals(sro.getSchema().getInput().get(1).getName(), "name_2");
Assert.assertEquals(sro.getSchema().getInput().get(2).getName(), "name_3");
Assert.assertEquals(sro.getSchema().getInput().get(0).getType(), "int");
Assert.assertEquals(sro.getSchema().getInput().get(1).getType(), "string");
Assert.assertEquals(sro.getSchema().getInput().get(2).getType(), "double");
Assert.assertEquals(sro.getSchema().getInput().get(0).getStruct(), "vector");
Assert.assertEquals(sro.getSchema().getInput().get(1).getStruct(), "basic");
Assert.assertEquals(sro.getSchema().getInput().get(2).getStruct(), "array");
Assert.assertEquals(sro.getData(), listOfListInputForMultipleInput);
Assert.assertEquals(sro.getSchema().getOutput().getName(), "features");
Assert.assertEquals(sro.getSchema().getOutput().getType(), "double");
Assert.assertEquals(sro.getSchema().getOutput().getStruct(), "vector");
}
}
| 7,629 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/configuration/ContextLoaderTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.configuration;
import com.amazonaws.sagemaker.configuration.ContextLoaderTest.TestConfig;
import java.io.File;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class ContextLoaderTest {
@Autowired
ApplicationContext context;
@Configuration
@Import(BeanConfiguration.class) // the actual configuration
public static class TestConfig {
@Bean
public File provideModelFile() {
return new File(this.getClass().getResource("model").getFile());
}
}
@Test
public void testApplicationContextSetup() {
//Checks ApplicationContext is initialized and a random Bean is instantiated properly
Assert.assertNotNull(context.getBean(LeapFrameBuilder.class));
}
}
| 7,630 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/configuration/BeanConfigurationTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.configuration;
import com.amazonaws.sagemaker.utils.SystemUtils;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
@RunWith(PowerMockRunner.class)
@PrepareForTest(SystemUtils.class)
public class BeanConfigurationTest {
public BeanConfigurationTest() {
}
private BeanConfiguration configuration = new BeanConfiguration();
@Test
public void testModelLocationNotNull() {
Assert.assertNotNull(configuration.provideModelFile());
Assert.assertEquals(configuration.provideModelFile(), new File("/opt/ml/model"));
}
@Test
public void testContextBuilderNotNull() {
Assert.assertNotNull(configuration.provideContextBuilder());
}
@Test
public void testBundleBuilderNotNull() {
Assert.assertNotNull(configuration.provideBundleBuilder());
}
@Test
public void testMleapContextNotNull() {
Assert.assertNotNull(configuration.provideMleapContext(configuration.provideContextBuilder()));
}
@Test
public void testLeapFrameBuilderNotNull() {
Assert.assertNotNull(configuration.provideLeapFrameBuilder());
}
@Test
public void testLeapFrameBuilderSupportNotNull() {
Assert.assertNotNull(configuration.provideLeapFrameBuilderSupport());
}
@Test
public void testTransformerNotNull() {
File dummyMLeapFile = new File(this.getClass().getResource("model").getFile());
Assert.assertNotNull(configuration.provideTransformer(dummyMLeapFile, configuration.provideBundleBuilder(),
configuration.provideMleapContext(configuration.provideContextBuilder())));
}
@Test
public void testObjectMapperNotNull() {
Assert.assertNotNull(configuration.provideObjectMapper());
}
@Test
public void testJettyServletWebServerFactoryNotNull() {
JettyServletWebServerFactory jettyServletTest = configuration.provideJettyServletWebServerFactory();
final String listenerPort =
(System.getenv("SAGEMAKER_BIND_TO_PORT") != null) ? System.getenv("SAGEMAKER_BIND_TO_PORT") : "8080";
Assert.assertEquals((int) new Integer(listenerPort), jettyServletTest.getPort());
Assert.assertNotNull(jettyServletTest.getServerCustomizers());
}
@Test
public void testParsePortFromEnvironment() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_BIND_TO_PORT")).thenReturn("7070");
Assert.assertEquals(configuration.getHttpListenerPort(), "7070");
}
}
| 7,631 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/utils/SystemUtilsTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.utils;
import org.junit.Assert;
import org.junit.Test;
public class SystemUtilsTest {
@Test
public void testGetNumberOfThreads() {
Assert.assertEquals(2 * Runtime.getRuntime().availableProcessors(), SystemUtils.getNumberOfThreads(2));
}
}
| 7,632 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/controller/ServingControllerTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.controller;
import com.amazonaws.sagemaker.dto.BatchExecutionParameter;
import com.amazonaws.sagemaker.dto.ColumnSchema;
import com.amazonaws.sagemaker.dto.DataSchema;
import com.amazonaws.sagemaker.dto.SageMakerRequestObject;
import com.amazonaws.sagemaker.helper.DataConversionHelper;
import com.amazonaws.sagemaker.helper.ResponseHelper;
import com.amazonaws.sagemaker.type.AdditionalMediaType;
import com.amazonaws.sagemaker.utils.ScalaUtils;
import com.amazonaws.sagemaker.utils.SystemUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import ml.combust.mleap.runtime.frame.ArrayRow;
import ml.combust.mleap.runtime.frame.DefaultLeapFrame;
import ml.combust.mleap.runtime.frame.Transformer;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilder;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilderSupport;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ScalaUtils.class, SystemUtils.class})
class ServingControllerTest {
private ServingController controller;
private DataConversionHelper converter = new DataConversionHelper(new LeapFrameBuilderSupport(),
new LeapFrameBuilder());
private Transformer mleapTransformerMock;
private SageMakerRequestObject sro;
private DefaultLeapFrame responseLeapFrame;
private ArrayRow outputArrayRow;
private List<ColumnSchema> inputColumns;
private ColumnSchema outputColumn;
private List<Object> inputData;
private String schemaInJson;
private ObjectMapper mapper = new ObjectMapper();
private ResponseHelper responseHelper = new ResponseHelper(mapper);
//PowerMock needs zero arugment constructor
public ServingControllerTest() {
}
private void buildDefaultSageMakerRequestObject() {
schemaInJson = "{\"input\":[{\"name\":\"test_name_1\",\"type\":\"int\"},{\"name\":\"test_name_2\","
+ "\"type\":\"double\"}],\"output\":{\"name\":\"out_name\",\"type\":\"int\"}}";
inputColumns = Lists.newArrayList(new ColumnSchema("test_name_1", "int", null),
new ColumnSchema("test_name_2", "double", null));
outputColumn = new ColumnSchema("out_name", "int", null);
inputData = Lists.newArrayList(new Integer("1"), new Double("2.0"));
sro = new SageMakerRequestObject(new DataSchema(inputColumns, outputColumn), inputData);
}
private void buildResponseLeapFrame() {
responseLeapFrame = new DataConversionHelper(new LeapFrameBuilderSupport(), new LeapFrameBuilder())
.convertInputToLeapFrame(sro.getSchema(), sro.getData());
outputArrayRow = new ArrayRow(Lists.newArrayList(new Integer("1")));
}
@Before
public void setup() {
responseHelper = new ResponseHelper(mapper);
mleapTransformerMock = Mockito.mock(Transformer.class);
this.buildDefaultSageMakerRequestObject();
this.buildResponseLeapFrame();
controller = new ServingController(mleapTransformerMock, responseHelper, converter, mapper);
PowerMockito.mockStatic(ScalaUtils.class);
PowerMockito.mockStatic(SystemUtils.class);
PowerMockito
.when(ScalaUtils.transformLeapFrame(Mockito.any(Transformer.class), Mockito.any(DefaultLeapFrame.class)))
.thenReturn(responseLeapFrame);
PowerMockito.when(ScalaUtils.selectFromLeapFrame(Mockito.any(DefaultLeapFrame.class), Mockito.anyString()))
.thenReturn(responseLeapFrame);
PowerMockito.when(ScalaUtils.getOutputArrayRow(Mockito.any(DefaultLeapFrame.class))).thenReturn(outputArrayRow);
}
@Test
public void testPerformShallowHealthCheck() {
Assert.assertEquals(controller.performShallowHealthCheck().getStatusCode(), HttpStatus.OK);
}
@Test
public void testReturnBatchExecutionParameter() throws Exception {
ResponseEntity response = controller.returnBatchExecutionParameter();
Assert.assertEquals(response.getStatusCode(), HttpStatus.OK);
BatchExecutionParameter batchParam = new ObjectMapper()
.readValue(Objects.requireNonNull(response.getBody()).toString(), BatchExecutionParameter.class);
Assert.assertEquals((int) batchParam.getMaxConcurrentTransforms(), SystemUtils.getNumberOfThreads(1));
Assert.assertEquals(batchParam.getBatchStrategy(), "SINGLE_RECORD");
Assert.assertEquals((int) batchParam.getMaxPayloadInMB(), 5);
}
@Test
public void testSingleValueCsvAcceptResponse() {
final ResponseEntity<String> output = controller.transformRequestJson(sro, AdditionalMediaType.TEXT_CSV_VALUE);
Assert.assertEquals(output.getBody(), "1");
Assert.assertEquals(Objects.requireNonNull(output.getHeaders().getContentType()).toString(),
AdditionalMediaType.TEXT_CSV_VALUE);
}
@Test
public void testSingleValueJsonlinesAcceptResponse() {
final ResponseEntity<String> output = controller
.transformRequestJson(sro, AdditionalMediaType.APPLICATION_JSONLINES_VALUE);
Assert.assertEquals(output.getBody(), "1");
Assert.assertEquals(Objects.requireNonNull(output.getHeaders().getContentType()).toString(),
AdditionalMediaType.APPLICATION_JSONLINES_VALUE);
}
@Test
public void testSingleValueNoAcceptResponse() {
final ResponseEntity<String> output = controller.transformRequestJson(sro, null);
Assert.assertEquals(output.getBody(), "1");
Assert.assertEquals(Objects.requireNonNull(output.getHeaders().getContentType()).toString(),
AdditionalMediaType.TEXT_CSV_VALUE);
}
@Test
public void testListValueCsvAcceptResponse() {
outputColumn = new ColumnSchema("out_name", "int", "array");
List<Object> outputResponse = Lists.newArrayList(1, 2);
sro = new SageMakerRequestObject(new DataSchema(inputColumns, outputColumn), inputData);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponse.iterator());
final ResponseEntity<String> output = controller.transformRequestJson(sro, "text/csv");
Assert.assertEquals(output.getBody(), "1,2");
}
@Test
public void testListValueJsonLinesAcceptResponse() {
outputColumn = new ColumnSchema("out_name", "int", "vector");
List<Object> outputResponse = Lists.newArrayList(1, 2);
sro = new SageMakerRequestObject(new DataSchema(inputColumns, outputColumn), inputData);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponse.iterator());
final ResponseEntity<String> output = controller.transformRequestJson(sro, "application/jsonlines");
Assert.assertEquals(output.getBody(), "{\"features\":[1,2]}");
}
@Test
public void testListValueNoAcceptResponse() {
outputColumn = new ColumnSchema("out_name", "int", "array");
List<Object> outputResponse = Lists.newArrayList(1, 2);
sro = new SageMakerRequestObject(new DataSchema(inputColumns, outputColumn), inputData);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponse.iterator());
final ResponseEntity<String> output = controller.transformRequestJson(sro, null);
Assert.assertEquals(output.getBody(), "1,2");
}
@Test
public void testListValueMLeapThrowsException() {
outputColumn = new ColumnSchema("out_name", "int", "array");
sro = new SageMakerRequestObject(new DataSchema(inputColumns, outputColumn), inputData);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenThrow(new RuntimeException("input data is not valid"));
final ResponseEntity<String> output = controller.transformRequestJson(sro, "text/csv");
Assert.assertEquals(output.getStatusCode(), HttpStatus.BAD_REQUEST);
Assert.assertEquals(output.getBody(), "input data is not valid");
}
@Test
public void testInputNull() {
final ResponseEntity<String> output = controller.transformRequestJson(null, "text/csv");
Assert.assertEquals(output.getStatusCode(), HttpStatus.NO_CONTENT);
}
@Test
public void testCsvApiWithListInput() {
schemaInJson = "{\"input\":[{\"name\":\"test_name_1\",\"type\":\"int\"},{\"name\":\"test_name_2\","
+ "\"type\":\"double\"}],\"output\":{\"name\":\"out_name\",\"type\":\"int\",\"struct\":\"vector\"}}";
List<Object> outputResponse = Lists.newArrayList(1, 2);
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponse.iterator());
final ResponseEntity<String> output = controller.transformRequestCsv("1,2.0".getBytes(), "text/csv");
Assert.assertEquals(output.getBody(), "1,2");
}
@Test
public void testCsvApiWithNullInput() {
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
final ResponseEntity<String> output = controller.transformRequestCsv(null, "text/csv");
Assert.assertEquals(output.getStatusCode(), HttpStatus.NO_CONTENT);
}
@Test
public void testListValueMLeapThrowsExceptionCsvApi() {
schemaInJson = "{\"input\":[{\"name\":\"test_name_1\",\"type\":\"int\"},{\"name\":\"test_name_2\","
+ "\"type\":\"double\"}],\"output\":{\"name\":\"out_name\",\"type\":\"int\",\"struct\":\"vector\"}}";
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenThrow(new RuntimeException("input data is not valid"));
final ResponseEntity<String> output = controller.transformRequestCsv("1,2.0".getBytes(), "text/csv");
Assert.assertEquals(output.getStatusCode(), HttpStatus.BAD_REQUEST);
Assert.assertEquals(output.getBody(), "input data is not valid");
}
@Test
public void testJsonLinesApiWithListInputCsvOutput() {
schemaInJson = "{"
+ "\"input\":["
+ "{\"name\":\"test_name_1\",\"type\":\"int\"},"
+ "{\"name\":\"test_name_2\",\"type\":\"double\"},"
+ "{\"name\":\"test_name_3\",\"type\":\"string\"}"
+ "],"
+ "\"output\":"
+ "{\"name\":\"out_name\",\"type\":\"int\",\"struct\":\"vector\"}"
+ "}";
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA"))
.thenReturn(schemaInJson);
List<Object> outputResponseForFirstInput = Lists.newArrayList(1, 2);
List<Object> outputResponseForSecondInput = Lists.newArrayList(3, 4);
List<Object> outputResponseForThirdInput = Lists.newArrayList(5, 6);
List<Object> outputResponseForFourthInput = Lists.newArrayList(7, 8);
List<Object> outputResponseForFifthInput = Lists.newArrayList(9, 10);
List<Object> outputResponseForSixthInput = Lists.newArrayList(11, 12);
List<Object> outputResponseForSeventhInput = Lists.newArrayList(13, 14);
List<Object> outputResponseForEighthInput = Lists.newArrayList(15, 16);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponseForFirstInput.iterator())
.thenReturn(outputResponseForSecondInput.iterator())
.thenReturn(outputResponseForThirdInput.iterator())
.thenReturn(outputResponseForFourthInput.iterator())
.thenReturn(outputResponseForFifthInput.iterator())
.thenReturn(outputResponseForSixthInput.iterator())
.thenReturn(outputResponseForSeventhInput.iterator())
.thenReturn(outputResponseForEighthInput.iterator());
final String expectOutput = "[[1,2], [3,4]]";
final ResponseEntity<String> output =
controller.transformRequestJsonLines(
"{\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}".getBytes(), "text/csv");
Assert.assertEquals(expectOutput, output.getBody());
final String expectOutput1 = "[[5,6], [7,8]]";
final ResponseEntity<String> output1 =
controller.transformRequestJsonLines(
"{\"data\":[1,2.0,\"TEST1\"]}\n{\"data\":[2,3.0,\"TEST\"]}".getBytes(), "text/csv");
Assert.assertEquals(expectOutput1, output1.getBody());
final String expectOutput2 = "[[9,10], [11,12], [13,14], [15,16]]";
final ResponseEntity<String> output2 =
controller.transformRequestJsonLines(
("{\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}\n"
+ "{\"data\":[1,2.0,\"TEST1\"]}\n"
+ "{\"data\":[2,3.0,\"TEST\"]}"
).getBytes(),
"text/csv");
Assert.assertEquals(expectOutput2, output2.getBody());
}
@Test
public void testJsonLinesApiWithListInputJsonOutput() {
schemaInJson = "{"
+ "\"input\":["
+ "{\"name\":\"test_name_1\",\"type\":\"int\"},"
+ "{\"name\":\"test_name_2\",\"type\":\"double\"},"
+ "{\"name\":\"test_name_3\",\"type\":\"string\"}"
+ "],"
+ "\"output\":"
+ "{\"name\":\"out_name\",\"type\":\"int\",\"struct\":\"vector\"}"
+ "}";
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA"))
.thenReturn(schemaInJson);
List<Object> outputResponseForFirstInput = Lists.newArrayList(1, 2);
List<Object> outputResponseForSecondInput = Lists.newArrayList(3, 4);
List<Object> outputResponseForThirdInput = Lists.newArrayList(5, 6);
List<Object> outputResponseForFourthInput = Lists.newArrayList(7, 8);
List<Object> outputResponseForFifthInput = Lists.newArrayList(9, 10);
List<Object> outputResponseForSixthInput = Lists.newArrayList(11, 12);
List<Object> outputResponseForSeventhInput = Lists.newArrayList(13, 14);
List<Object> outputResponseForEighthInput = Lists.newArrayList(15, 16);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponseForFirstInput.iterator())
.thenReturn(outputResponseForSecondInput.iterator())
.thenReturn(outputResponseForThirdInput.iterator())
.thenReturn(outputResponseForFourthInput.iterator())
.thenReturn(outputResponseForFifthInput.iterator())
.thenReturn(outputResponseForSixthInput.iterator())
.thenReturn(outputResponseForSeventhInput.iterator())
.thenReturn(outputResponseForEighthInput.iterator());
final String expectOutput = "[[{\"features\":[1,2]}], [{\"features\":[3,4]}]]";
final ResponseEntity<String> output =
controller.transformRequestJsonLines(
"{\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}".getBytes(),
"application/jsonlines");
Assert.assertEquals(expectOutput, output.getBody());
final String expectOutput1 = "[[{\"features\":[5,6]}], [{\"features\":[7,8]}]]";
final ResponseEntity<String> output1 =
controller.transformRequestJsonLines(
"{\"data\":[1,2.0,\"TEST1\"]}\n{\"data\":[2,3.0,\"TEST\"]}".getBytes(),
"application/jsonlines");
Assert.assertEquals(expectOutput1, output1.getBody());
final String expectOutput2 =
"[[{\"features\":[9,10]}], [{\"features\":[11,12]}], "
+ "[{\"features\":[13,14]}], [{\"features\":[15,16]}]]";
final ResponseEntity<String> output2 =
controller.transformRequestJsonLines(
("{\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}\n"
+ "{\"data\":[1,2.0,\"TEST1\"]}\n"
+ "{\"data\":[2,3.0,\"TEST\"]}"
).getBytes(),
"application/jsonlines");
Assert.assertEquals(expectOutput2, output2.getBody());
}
@Test
public void testJsonLinesApiWithListInputJsonTextOutput() {
schemaInJson = "{"
+ "\"input\":["
+ "{\"name\":\"test_name_1\",\"type\":\"int\"},"
+ "{\"name\":\"test_name_2\",\"type\":\"double\"},"
+ "{\"name\":\"test_name_3\",\"type\":\"string\"}"
+ "],"
+ "\"output\":"
+ "{\"name\":\"out_name\",\"type\":\"int\",\"struct\":\"vector\"}"
+ "}";
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA"))
.thenReturn(schemaInJson);
List<Object> outputResponseForFirstInput = Lists.newArrayList(1, 2);
List<Object> outputResponseForSecondInput = Lists.newArrayList(3, 4);
List<Object> outputResponseForThirdInput = Lists.newArrayList(5, 6);
List<Object> outputResponseForFourthInput = Lists.newArrayList(7, 8);
List<Object> outputResponseForFifthInput = Lists.newArrayList(9, 10);
List<Object> outputResponseForSixthInput = Lists.newArrayList(11, 12);
List<Object> outputResponseForSeventhInput = Lists.newArrayList(13, 14);
List<Object> outputResponseForEighthInput = Lists.newArrayList(15, 16);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponseForFirstInput.iterator())
.thenReturn(outputResponseForSecondInput.iterator())
.thenReturn(outputResponseForThirdInput.iterator())
.thenReturn(outputResponseForFourthInput.iterator())
.thenReturn(outputResponseForFifthInput.iterator())
.thenReturn(outputResponseForSixthInput.iterator())
.thenReturn(outputResponseForSeventhInput.iterator())
.thenReturn(outputResponseForEighthInput.iterator());
final String expectOutput = "[[{\"source\":\"1 2\"}], [{\"source\":\"3 4\"}]]";
final ResponseEntity<String> output =
controller.transformRequestJsonLines(
"{\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}".getBytes(),
"application/jsonlines;data=text");
Assert.assertEquals(expectOutput, output.getBody());
final String expectOutput1 = "[[{\"source\":\"5 6\"}], [{\"source\":\"7 8\"}]]";
final ResponseEntity<String> output1 =
controller.transformRequestJsonLines(
"{\"data\":[1,2.0,\"TEST1\"]}\n{\"data\":[2,3.0,\"TEST\"]}".getBytes(),
"application/jsonlines;data=text");
Assert.assertEquals(expectOutput1, output1.getBody());
final String expectOutput2 =
"[[{\"source\":\"9 10\"}], [{\"source\":\"11 12\"}], "
+ "[{\"source\":\"13 14\"}], [{\"source\":\"15 16\"}]]";
final ResponseEntity<String> output2 =
controller.transformRequestJsonLines(
("{\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}\n{\"data\":[1,2.0,\"TEST1\"]}\n{\"data\":[2,3.0,\"TEST\"]}"
).getBytes(),
"application/jsonlines;data=text");
Assert.assertEquals(expectOutput2, output2.getBody());
}
@Test
public void testProcessInputDataForJsonLines() throws IOException {
String jsonLinesAsString =
"{\"schema\":"
+ "{\"input\":[{\"name\":\"test_name_1\",\"type\":\"int\"},{\"name\":\"test_name_2\","
+ "\"type\":\"double\"},{\"name\":\"test_name_3\",\"type\":\"string\"}],"
+ "\"output\":{\"name\":\"out_name\",\"type\":\"int\",\"struct\":\"vector\"}},"
+ "\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}"
+ "\n{\"data\":[1,2.0,\"TEST1\"]}"
+ "\n{\"data\":[2,3.0,\"TEST\"]}";
List<Object> outputResponseForFirstInput = Lists.newArrayList(1, 2);
List<Object> outputResponseForSecondInput = Lists.newArrayList(3, 4);
List<Object> outputResponseForThirdInput = Lists.newArrayList(5, 6);
List<Object> outputResponseForFourthInput = Lists.newArrayList(7, 8);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenReturn(outputResponseForFirstInput.iterator())
.thenReturn(outputResponseForSecondInput.iterator())
.thenReturn(outputResponseForThirdInput.iterator())
.thenReturn(outputResponseForFourthInput.iterator());
final String expectOutput = "[[1,2], [3,4], [5,6], [7,8]]";
final ResponseEntity<String> output = controller.transformRequestJsonLines(
jsonLinesAsString.getBytes(), "text/csv");
Assert.assertEquals(expectOutput, output.getBody());
}
@Test
public void testJsonLinesApiWithListInputThrowsException() {
schemaInJson = "{\"input\":[{\"name\":\"test_name_1\",\"type\":\"int\"},{\"name\":\"test_name_2\","
+ "\"type\":\"double\"},{\"name\":\"test_name_3\",\"type\":\"string\"}],\"output\":{\"name\":\"out_name\",\"type\":\"int\",\"struct\":\"vector\"}}";
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
PowerMockito
.when(ScalaUtils.getJavaObjectIteratorFromArrayRow(Mockito.any(ArrayRow.class), Mockito.anyString()))
.thenThrow(new RuntimeException("input data is not valid"));
final ResponseEntity<String> output = controller.transformRequestJsonLines("{\"data\":[[1,2.0,\"TEST1\"], [2,3.0,\"TEST\"]]}".getBytes(), "text/csv");
Assert.assertEquals(output.getStatusCode(), HttpStatus.BAD_REQUEST);
Assert.assertEquals(output.getBody(), "input data is not valid");
}
@Test
public void testJsonLinesApiWithNullInput() {
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
final ResponseEntity<String> output = controller.transformRequestJsonLines(null, "text/csv");
Assert.assertEquals(output.getStatusCode(), HttpStatus.BAD_REQUEST);
}
@Test
public void testJsonLinesApiWithEmptyInput() {
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
final ResponseEntity<String> output = controller.transformRequestJsonLines(new byte[0], "text/csv");
Assert.assertEquals(output.getStatusCode(), HttpStatus.NO_CONTENT);
}
@Test
public void testParseAcceptEmptyFromRequestEnvironmentPresent() {
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT"))
.thenReturn("application/jsonlines;data=text");
Assert.assertEquals(controller.retrieveAndVerifyAccept(null), "application/jsonlines;data=text");
}
@Test
public void testParseAcceptAnyFromRequestEnvironmentPresent() {
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT"))
.thenReturn("application/jsonlines;data=text");
Assert.assertEquals(controller.retrieveAndVerifyAccept("*/*"), "application/jsonlines;data=text");
}
@Test
public void testParseAcceptEmptyFromRequestEnvironmentNotPresent() {
Assert.assertEquals(controller.retrieveAndVerifyAccept(null), "text/csv");
}
@Test
public void testParseAcceptAnyFromRequestEnvironmentNotPresent() {
Assert.assertEquals(controller.retrieveAndVerifyAccept("*/*"), "text/csv");
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidAcceptInEnvironment() {
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT"))
.thenReturn("application/json");
controller.retrieveAndVerifyAccept("application/json");
}
@Test
public void testSchemaPresentInRequestAndEnvironment() throws IOException {
inputColumns = Lists.newArrayList(new ColumnSchema("name_1", "type_1", "struct_1"),
new ColumnSchema("name_2", "type_2", "struct_2"));
outputColumn = new ColumnSchema("name_out_1", "type_out_1", "struct_out_1");
DataSchema ds = new DataSchema(inputColumns, outputColumn);
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
DataSchema outputSchema = controller.retrieveAndVerifySchema(ds, mapper);
Assert.assertEquals(outputSchema.getInput().size(), 2);
Assert.assertEquals(outputSchema.getInput().get(0).getName(), "name_1");
Assert.assertEquals(outputSchema.getOutput().getName(), "name_out_1");
}
@Test
public void testSchemaPresentOnlyInEnvironment() throws IOException {
schemaInJson = "{\"input\":[{\"name\":\"i_1\",\"type\":\"int\"}],\"output\":{\"name\":\"o_1\","
+ "\"type\":\"double\"}}";
PowerMockito.when(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA")).thenReturn(schemaInJson);
DataSchema outputSchema = controller.retrieveAndVerifySchema(null, mapper);
Assert.assertEquals(outputSchema.getInput().size(), 1);
Assert.assertEquals(outputSchema.getInput().get(0).getName(), "i_1");
Assert.assertEquals(outputSchema.getOutput().getName(), "o_1");
}
@Test(expected = RuntimeException.class)
public void testSchemaAbsentEverywhere() throws IOException {
controller.retrieveAndVerifySchema(null, mapper);
}
}
| 7,633 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/type/BasicDataTypeTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.type;
import org.junit.Assert;
import org.junit.Test;
public class BasicDataTypeTest {
@Test
public void testBasicDataType() {
Assert.assertEquals(BasicDataType.BOOLEAN, "boolean");
Assert.assertEquals(BasicDataType.INTEGER, "int");
Assert.assertEquals(BasicDataType.FLOAT, "float");
Assert.assertEquals(BasicDataType.LONG, "long");
Assert.assertEquals(BasicDataType.DOUBLE, "double");
Assert.assertEquals(BasicDataType.SHORT, "short");
Assert.assertEquals(BasicDataType.BYTE, "byte");
Assert.assertEquals(BasicDataType.STRING, "string");
}
}
| 7,634 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/type/AdditionalMediaTypeTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.type;
import org.junit.Assert;
import org.junit.Test;
public class AdditionalMediaTypeTest {
@Test
public void testAdditionalMimeType() {
Assert.assertEquals(AdditionalMediaType.TEXT_CSV_VALUE, "text/csv");
Assert.assertEquals(AdditionalMediaType.APPLICATION_JSONLINES_VALUE, "application/jsonlines");
Assert.assertEquals(AdditionalMediaType.APPLICATION_JSONLINES_TEXT_VALUE, "application/jsonlines;data=text");
}
}
| 7,635 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/type/DataStructureTypeTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.type;
import org.junit.Assert;
import org.junit.Test;
public class DataStructureTypeTest {
@Test
public void testStructureType() {
Assert.assertEquals(DataStructureType.BASIC, "basic");
Assert.assertEquals(DataStructureType.VECTOR, "vector");
Assert.assertEquals(DataStructureType.ARRAY, "array");
}
}
| 7,636 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/helper/DataConversionHelperTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.helper;
import com.amazonaws.sagemaker.dto.DataSchema;
import com.amazonaws.sagemaker.dto.SageMakerRequestObject;
import com.amazonaws.sagemaker.type.BasicDataType;
import com.amazonaws.sagemaker.type.DataStructureType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import ml.combust.mleap.core.types.ListType;
import ml.combust.mleap.core.types.ScalarType;
import ml.combust.mleap.core.types.TensorType;
import ml.combust.mleap.runtime.frame.ArrayRow;
import ml.combust.mleap.runtime.frame.DefaultLeapFrame;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilder;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilderSupport;
import org.apache.commons.io.IOUtils;
import org.apache.spark.ml.linalg.Vectors;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class DataConversionHelperTest {
private ObjectMapper mapper = new ObjectMapper();
private DataConversionHelper dataConversionHelper = new DataConversionHelper(new LeapFrameBuilderSupport(),
new LeapFrameBuilder());
@Test
public void testParseCsvToObjectList() throws IOException {
String csvInput = "2,C,34.5";
String inputJson = IOUtils
.toString(this.getClass().getResourceAsStream("../dto/basic_input_schema.json"), "UTF-8");
DataSchema schema = mapper.readValue(inputJson, DataSchema.class);
List<Object> expectedOutput = Lists.newArrayList(new Integer("2"), "C", new Double("34.5"));
Assert.assertEquals(dataConversionHelper.convertCsvToObjectList(csvInput, schema), expectedOutput);
}
@Test
public void testParseCsvQuotesToObjectList() throws IOException {
String csvInput = "2,\"C\",34.5";
String inputJson = IOUtils
.toString(this.getClass().getResourceAsStream("../dto/basic_input_schema.json"), "UTF-8");
DataSchema schema = mapper.readValue(inputJson, DataSchema.class);
List<Object> expectedOutput = Lists.newArrayList(new Integer("2"), "C", new Double("34.5"));
Assert.assertEquals(dataConversionHelper.convertCsvToObjectList(csvInput, schema), expectedOutput);
}
@Test
public void testCastingInputToLeapFrame() throws Exception {
String inputJson = IOUtils
.toString(this.getClass().getResourceAsStream("../dto/complete_input.json"), "UTF-8");
SageMakerRequestObject sro = mapper.readValue(inputJson, SageMakerRequestObject.class);
DefaultLeapFrame leapframeTest = dataConversionHelper.convertInputToLeapFrame(sro.getSchema(), sro.getData());
Assert.assertNotNull(leapframeTest.schema());
Assert.assertNotNull(leapframeTest.dataset());
}
@Test
public void testCastingMLeapBasicTypeToJavaType() {
ArrayRow testRow = new ArrayRow(Lists.newArrayList(new Integer("1")));
Assert.assertEquals(new Integer("1"),
dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.INTEGER));
testRow = new ArrayRow(Lists.newArrayList(new Double("1.0")));
Assert.assertEquals(new Double("1.0"),
dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.FLOAT));
testRow = new ArrayRow(Lists.newArrayList(new Long("1")));
Assert.assertEquals(new Long("1"),
dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.LONG));
testRow = new ArrayRow(Lists.newArrayList(new Double("1.0")));
Assert.assertEquals(new Double("1"),
dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.DOUBLE));
testRow = new ArrayRow(Lists.newArrayList(new Short("1")));
Assert.assertEquals(new Short("1"),
dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.SHORT));
testRow = new ArrayRow(Lists.newArrayList(new Byte("1")));
Assert.assertEquals(new Byte("1"),
dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.BYTE));
testRow = new ArrayRow(Lists.newArrayList(Boolean.valueOf("1")));
Assert.assertEquals(Boolean.valueOf("1"),
dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.BOOLEAN));
testRow = new ArrayRow(Lists.newArrayList("1"));
Assert.assertEquals("1", dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, BasicDataType.STRING));
}
@Test(expected = IllegalArgumentException.class)
public void testCastingMleapBasicTypeToJavaTypeWrongInput() {
ArrayRow testRow = new ArrayRow(Lists.newArrayList(new Integer("1")));
Assert
.assertEquals(new Integer("1"), dataConversionHelper.convertMLeapBasicTypeToJavaType(testRow, "intvalue"));
}
@Test
public void testCastingInputToJavaTypeSingle() {
Assert.assertEquals(new Integer("1"), dataConversionHelper
.convertInputDataToJavaType(BasicDataType.INTEGER, DataStructureType.BASIC, new Integer("1")));
Assert.assertEquals(new Float("1.0"), dataConversionHelper
.convertInputDataToJavaType(BasicDataType.FLOAT, DataStructureType.BASIC, new Float("1.0")));
Assert.assertEquals(new Double("1.0"), dataConversionHelper
.convertInputDataToJavaType(BasicDataType.DOUBLE, DataStructureType.BASIC, new Double("1.0")));
Assert.assertEquals(new Byte("1"),
dataConversionHelper
.convertInputDataToJavaType(BasicDataType.BYTE, DataStructureType.BASIC, new Byte("1")));
Assert.assertEquals(new Long("1"),
dataConversionHelper.convertInputDataToJavaType(BasicDataType.LONG, null, new Long("1")));
Assert.assertEquals(new Short("1"),
dataConversionHelper.convertInputDataToJavaType(BasicDataType.SHORT, null, new Short("1")));
Assert.assertEquals("1", dataConversionHelper.convertInputDataToJavaType(BasicDataType.STRING, null, "1"));
Assert.assertEquals(Boolean.valueOf("1"),
dataConversionHelper.convertInputDataToJavaType(BasicDataType.BOOLEAN, null, Boolean.valueOf("1")));
}
@Test
public void testCastingInputToJavaTypeList() {
//Check vector struct and double type returns a Spark vector
Assert.assertEquals(Vectors.dense(new double[]{1.0, 2.0}),dataConversionHelper
.convertInputDataToJavaType(BasicDataType.DOUBLE, DataStructureType.VECTOR,
Lists.newArrayList(new Double("1.0"), new Double("2.0"))));
Assert.assertEquals(Lists.newArrayList(1L, 2L), dataConversionHelper
.convertInputDataToJavaType(BasicDataType.LONG, DataStructureType.ARRAY,
Lists.newArrayList(new Long("1"), new Long("2"))));
Assert.assertEquals(Lists.newArrayList(new Short("1")), dataConversionHelper
.convertInputDataToJavaType(BasicDataType.SHORT, DataStructureType.ARRAY,
Lists.newArrayList(new Short("1"))));
Assert.assertEquals(Lists.newArrayList("1"), dataConversionHelper
.convertInputDataToJavaType(BasicDataType.STRING, DataStructureType.ARRAY, Lists.newArrayList("1")));
Assert.assertEquals(Lists.newArrayList(Boolean.valueOf("1")), dataConversionHelper
.convertInputDataToJavaType(BasicDataType.BOOLEAN, DataStructureType.ARRAY,
Lists.newArrayList(Boolean.valueOf("1"))));
}
@Test(expected = IllegalArgumentException.class)
public void testConvertInputToJavaTypeNonDoibleVector() {
dataConversionHelper
.convertInputDataToJavaType(BasicDataType.INTEGER, DataStructureType.VECTOR, new Integer("1"));
}
@Test(expected = IllegalArgumentException.class)
public void testCastingInputToJavaTypeNonList() {
dataConversionHelper
.convertInputDataToJavaType(BasicDataType.INTEGER, DataStructureType.VECTOR, new Integer("1"));
}
@Test(expected = IllegalArgumentException.class)
public void testCastingInputToJavaTypeWrongType() {
dataConversionHelper.convertInputDataToJavaType("intvalue", DataStructureType.BASIC, new Integer("1"));
}
@Test(expected = IllegalArgumentException.class)
public void testCastingInputToJavaTypeListWrongType() {
dataConversionHelper.convertInputDataToJavaType("intvalue", DataStructureType.VECTOR, Lists.newArrayList(1, 2));
}
@Test
public void testCastingInputToMLeapType() {
Assert.assertTrue(dataConversionHelper
.convertInputToMLeapInputType(BasicDataType.INTEGER, DataStructureType.BASIC) instanceof ScalarType);
Assert.assertTrue(
dataConversionHelper.convertInputToMLeapInputType(BasicDataType.FLOAT, null) instanceof ScalarType);
Assert.assertTrue(dataConversionHelper
.convertInputToMLeapInputType(BasicDataType.DOUBLE, DataStructureType.VECTOR) instanceof TensorType);
Assert.assertTrue(dataConversionHelper
.convertInputToMLeapInputType(BasicDataType.LONG, DataStructureType.ARRAY) instanceof ListType);
Assert.assertTrue(dataConversionHelper
.convertInputToMLeapInputType(BasicDataType.STRING, DataStructureType.BASIC) instanceof ScalarType);
Assert.assertTrue(
dataConversionHelper.convertInputToMLeapInputType(BasicDataType.SHORT, null) instanceof ScalarType);
Assert.assertTrue(dataConversionHelper
.convertInputToMLeapInputType(BasicDataType.BYTE, DataStructureType.ARRAY) instanceof ListType);
Assert.assertTrue(dataConversionHelper
.convertInputToMLeapInputType(BasicDataType.BOOLEAN, DataStructureType.VECTOR) instanceof TensorType);
}
@Test(expected = IllegalArgumentException.class)
public void testCastingInputToMLeapTypeWrongType() {
dataConversionHelper.convertInputToMLeapInputType("intvalue", DataStructureType.VECTOR);
}
}
| 7,637 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/test/java/com/amazonaws/sagemaker/helper/ResponseHelperTest.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.helper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Objects;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
public class ResponseHelperTest {
private List<Object> dummyResponse = Lists.newArrayList();
private ResponseHelper responseHelperTest = new ResponseHelper(new ObjectMapper());
@Before
public void setup() {
dummyResponse = Lists.newArrayList(new Integer("1"), new Float("0.2"));
}
@Test
public void testSingleOutput() {
ResponseEntity<String> outputTest = responseHelperTest.sendResponseForSingleValue("1", "text/csv");
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"text/csv");
Assert.assertEquals(outputTest.getBody(), "1");
}
@Test
public void testSingleJsonlines() {
ResponseEntity<String> outputTest = responseHelperTest
.sendResponseForSingleValue("1", "application/jsonlines");
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"application/jsonlines");
Assert.assertEquals(outputTest.getBody(), "1");
}
@Test
public void testSingleOutputNoContentType() {
ResponseEntity<String> outputTest = responseHelperTest.sendResponseForSingleValue("1", null);
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"text/csv");
Assert.assertEquals(outputTest.getBody(), "1");
}
@Test
public void testListOutputCsv() throws JsonProcessingException {
ResponseEntity<String> outputTest = responseHelperTest
.sendResponseForList(dummyResponse.iterator(), "text/csv");
Assert.assertEquals(outputTest.getBody(), "1,0.2");
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"text/csv");
}
@Test
public void testListOutputJsonlines() throws JsonProcessingException {
ResponseEntity<String> outputTest = responseHelperTest
.sendResponseForList(dummyResponse.iterator(), "application/jsonlines");
Assert.assertEquals(outputTest.getBody(), "{\"features\":[1,0.2]}");
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"application/jsonlines");
}
@Test
public void testTextOutputJsonlines() throws JsonProcessingException {
dummyResponse = Lists.newArrayList("this", "is", "spark", "ml", "server");
ResponseEntity<String> outputTest = responseHelperTest
.sendResponseForList(dummyResponse.iterator(), "application/jsonlines;data=text");
Assert.assertEquals(outputTest.getBody(), "{\"source\":\"this is spark ml server\"}");
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"application/jsonlines");
}
@Test
public void testListOutputInvalidAccept() throws JsonProcessingException {
ResponseEntity<String> outputTest = responseHelperTest
.sendResponseForList(dummyResponse.iterator(), "application/json");
Assert.assertEquals(outputTest.getBody(), "1,0.2");
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"text/csv");
}
@Test
public void testTextOutputInvalidAccept() throws JsonProcessingException {
dummyResponse = Lists.newArrayList("this", "is", "spark", "ml", "server");
ResponseEntity<String> outputTest = responseHelperTest
.sendResponseForList(dummyResponse.iterator(), "application/json");
Assert.assertEquals(outputTest.getBody(), "this,is,spark,ml,server");
Assert.assertEquals(Objects.requireNonNull(outputTest.getHeaders().get(HttpHeaders.CONTENT_TYPE)).get(0),
"text/csv");
}
}
| 7,638 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/App.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Spring Boot starter application
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
} | 7,639 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/dto/SageMakerRequestListObject.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.List;
/**
* Request object POJO to which data field of input request in JSONLINES format will be mapped to by Spring (using Jackson).
* For sample input, please see test/resources/com/amazonaws/sagemaker/dto
*/
public class SageMakerRequestListObject {
private DataSchema schema;
private List<List<Object>> data;
@JsonCreator
public SageMakerRequestListObject(@JsonProperty("schema") final DataSchema schema,
@JsonProperty("data") final List<List<Object>> data) {
// schema can be retrieved from environment variable as well, hence it is not enforced to be null
this.schema = schema;
this.data = Preconditions.checkNotNull(data);
}
public DataSchema getSchema() {
return schema;
}
public List<List<Object>> getData() {
return data;
}
}
| 7,640 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/dto/ColumnSchema.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.amazonaws.sagemaker.type.DataStructureType;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.Optional;
/**
* POJO to represent single column of Spark data that MLeap will transform. Each column can be a basic value or a List
* of basic values (for Spark Array or Vector).
*/
public class ColumnSchema {
private String name;
private String type;
private String struct;
@JsonCreator
public ColumnSchema(@JsonProperty("name") final String name, @JsonProperty("type") final String type,
@JsonProperty("struct") final String struct) {
this.name = Preconditions.checkNotNull(name);
this.type = Preconditions.checkNotNull(type);
this.struct = Optional.ofNullable(struct).orElse(DataStructureType.BASIC);
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getStruct() {
return struct;
}
}
| 7,641 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/dto/SageMakerRequestObject.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.List;
/**
* Request object POJO to which input request in JSON format will be mapped to by Spring (using Jackson). For sample
* input, please see test/resources/com/amazonaws/sagemaker/dto
*/
public class SageMakerRequestObject {
private DataSchema schema;
private List<Object> data;
@JsonCreator
public SageMakerRequestObject(@JsonProperty("schema") final DataSchema schema,
@JsonProperty("data") final List<Object> data) {
// schema can be retrieved from environment variable as well, hence it is not enforced to be null
this.schema = schema;
this.data = Preconditions.checkNotNull(data);
}
public DataSchema getSchema() {
return schema;
}
public List<Object> getData() {
return data;
}
}
| 7,642 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/dto/DataSchema.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.List;
/**
* Input schema for the request paylod. This can either be passed via an environment variable or part of a request.
* If the schema is present in both the environment variable and the request, the one in request will take precedence.
*/
public class DataSchema {
private List<ColumnSchema> input;
private ColumnSchema output;
@JsonCreator
public DataSchema(@JsonProperty("input") final List<ColumnSchema> input,
@JsonProperty("output") final ColumnSchema output) {
this.input = Preconditions.checkNotNull(input);
this.output = Preconditions.checkNotNull(output);
}
public List<ColumnSchema> getInput() {
return input;
}
public ColumnSchema getOutput() {
return output;
}
}
| 7,643 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/dto/JsonlinesTextOutput.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
/**
* POJO class to represent the standard JSONlines output format for SageMaker NLP algorithms (BlazingText, Seq2Seq)
*/
public class JsonlinesTextOutput {
private String source;
@JsonCreator
public JsonlinesTextOutput(@JsonProperty("source") final String source) {
this.source = Preconditions.checkNotNull(source);
}
public String getSource() {
return source;
}
}
| 7,644 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/dto/BatchExecutionParameter.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
/**
* POJO class corresponding to the execution-parameters API call that Batch requires
*/
public class BatchExecutionParameter {
@JsonProperty("MaxConcurrentTransforms")
private Integer maxConcurrentTransforms;
@JsonProperty("BatchStrategy")
private String batchStrategy;
@JsonProperty("MaxPayloadInMB")
private Integer maxPayloadInMB;
@JsonCreator
public BatchExecutionParameter(@JsonProperty("MaxConcurrentTransforms") Integer maxConcurrentTransforms,
@JsonProperty("BatchStrategy") String batchStrategy, @JsonProperty("MaxPayloadInMB") Integer maxPayloadInMB) {
this.maxConcurrentTransforms = Preconditions.checkNotNull(maxConcurrentTransforms);
this.batchStrategy = Preconditions.checkNotNull(batchStrategy);
this.maxPayloadInMB = Preconditions.checkNotNull(maxPayloadInMB);
}
public Integer getMaxConcurrentTransforms() {
return maxConcurrentTransforms;
}
public String getBatchStrategy() {
return batchStrategy;
}
public Integer getMaxPayloadInMB() {
return maxPayloadInMB;
}
}
| 7,645 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/dto/JsonlinesStandardOutput.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.dto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.List;
/**
* POJO class to represent the standard JSONlines output format for SageMaker built-in algorithms.
*/
public class JsonlinesStandardOutput {
private List<Object> features;
@JsonCreator
public JsonlinesStandardOutput(@JsonProperty("features") final List<Object> features) {
this.features = Preconditions.checkNotNull(features);
}
public List<Object> getFeatures() {
return features;
}
}
| 7,646 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/configuration/BeanConfiguration.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.configuration;
import com.amazonaws.sagemaker.utils.SystemUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import java.io.File;
import java.util.List;
import ml.combust.mleap.runtime.MleapContext;
import ml.combust.mleap.runtime.frame.Transformer;
import ml.combust.mleap.runtime.javadsl.BundleBuilder;
import ml.combust.mleap.runtime.javadsl.ContextBuilder;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilder;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilderSupport;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.context.annotation.Bean;
/**
* Contains all Spring bean configurations
*/
@SpringBootConfiguration
public class BeanConfiguration {
private static final String DEFAULT_HTTP_LISTENER_PORT = "8080";
private static final String DEFAULT_MODEL_LOCATION = "/opt/ml/model";
private static final Integer MAX_CORE_TO_THREAD_RATIO = 10;
private static final Integer MIN_CORE_TO_THREAD_RATIO = 2;
@Bean
public File provideModelFile() {
return new File(DEFAULT_MODEL_LOCATION);
}
@Bean
public ContextBuilder provideContextBuilder() {
return new ContextBuilder();
}
@Bean
public MleapContext provideMleapContext(ContextBuilder contextBuilder) {
return contextBuilder.createMleapContext();
}
@Bean
public BundleBuilder provideBundleBuilder() {
return new BundleBuilder();
}
@Bean
public LeapFrameBuilder provideLeapFrameBuilder() {
return new LeapFrameBuilder();
}
@Bean
public LeapFrameBuilderSupport provideLeapFrameBuilderSupport() {
return new LeapFrameBuilderSupport();
}
@Bean
public Transformer provideTransformer(final File modelFile, final BundleBuilder bundleBuilder,
final MleapContext mleapContext) {
return bundleBuilder.load(modelFile, mleapContext).root();
}
@Bean
public ObjectMapper provideObjectMapper() {
return new ObjectMapper();
}
@Bean
public JettyServletWebServerFactory provideJettyServletWebServerFactory() {
final JettyServletWebServerFactory jettyServlet = new JettyServletWebServerFactory(
new Integer(this.getHttpListenerPort()));
final List<JettyServerCustomizer> serverCustomizerList = Lists.newArrayList();
final JettyServerCustomizer serverCustomizer = server -> {
final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
threadPool.setMinThreads(SystemUtils.getNumberOfThreads(MIN_CORE_TO_THREAD_RATIO));
threadPool.setMaxThreads(SystemUtils.getNumberOfThreads(MAX_CORE_TO_THREAD_RATIO));
};
serverCustomizerList.add(serverCustomizer);
jettyServlet.setServerCustomizers(serverCustomizerList);
return jettyServlet;
}
@VisibleForTesting
protected String getHttpListenerPort() {
return (SystemUtils.getEnvironmentVariable("SAGEMAKER_BIND_TO_PORT") != null) ? SystemUtils
.getEnvironmentVariable("SAGEMAKER_BIND_TO_PORT") : DEFAULT_HTTP_LISTENER_PORT;
}
}
| 7,647 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/utils/SystemUtils.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.utils;
/**
* Utility class for dealing with System or Environment related functionalities. These methofs are moved to this class
* so that they can be easily mocked out by PowerMockito.mockStatic while testing the actual classes.
*/
public class SystemUtils {
/**
* Computes the number of threads to use based on number of available processors in the host
*
* @param coreToThreadRatio, the multiplicative factor per core
* @return coreToThreadRatio multiplied by available cores in the host
*/
public static int getNumberOfThreads(final Integer coreToThreadRatio) {
final int numberOfCores = Runtime.getRuntime().availableProcessors();
return coreToThreadRatio * numberOfCores;
}
/**
* Retrieves environment variable pertaining to a key
*
* @param key, the environment variable key
* @return the value corresponding to the key from environment settings
*/
public static String getEnvironmentVariable(final String key) {
return System.getenv(key);
}
}
| 7,648 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/utils/ScalaUtils.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.utils;
import com.amazonaws.sagemaker.type.DataStructureType;
import java.util.Collections;
import java.util.Iterator;
import ml.combust.mleap.runtime.frame.ArrayRow;
import ml.combust.mleap.runtime.frame.DefaultLeapFrame;
import ml.combust.mleap.runtime.frame.Row;
import ml.combust.mleap.runtime.frame.Transformer;
import ml.combust.mleap.runtime.javadsl.LeapFrameSupport;
import org.apache.commons.lang3.StringUtils;
import scala.collection.JavaConverters;
/**
* Utility class for dealing with Scala to Java conversion related issues. These functionalities are moved to this
* class so that they can be easily mocked out by PowerMockito.mockStatic while testing the actual classes.
*/
public class ScalaUtils {
private final static LeapFrameSupport leapFrameSupport = new LeapFrameSupport();
/**
* Invokes MLeap transformer object with DefaultLeapFrame and returns DefaultLeapFrame from MLeap helper Try Monad
*
* @param transformer, the MLeap transformer which performs the inference
* @param leapFrame, input to MLeap
* @return the DefaultLeapFrame in helper
*/
public static DefaultLeapFrame transformLeapFrame(final Transformer transformer, final DefaultLeapFrame leapFrame) {
return transformer.transform(leapFrame).get();
}
/**
* Selects a value corresponding to a key from DefaultLeapFrame and returns DefaultLeapFrame from MLeap helper Try
* Monad
*
* @param key, the value corresponding to key to be retrieved
* @param leapFrame, input to MLeap
* @return the DefaultLeapFrame in helper
*/
public static DefaultLeapFrame selectFromLeapFrame(final DefaultLeapFrame leapFrame, final String key) {
return leapFrameSupport.select(leapFrame, Collections.singletonList(key));
}
/**
* Returns an ArrayRow object from DefaultLeapFrame Try Monad after converting Scala collections to Java
* collections
*
* @param leapFrame, the DefaultLeapFrame from which output to be extracted
* @return ArrayRow which can be used to retrieve the original output
*/
public static ArrayRow getOutputArrayRow(final DefaultLeapFrame leapFrame) {
final Iterator<Row> rowIterator = leapFrameSupport.collect(leapFrame).iterator();
// SageMaker input structure only allows to call MLeap transformer for single data point
return (ArrayRow) (rowIterator.next());
}
/**
* Retrieves the raw output value from ArrayRow for Vector/Array use cases.
*
* @param predictionRow, the output ArrayRow
* @param structure, whether it is Spark Vector or Array
* @return Iterator to raw values of the Vector or Array
*/
public static Iterator<Object> getJavaObjectIteratorFromArrayRow(final ArrayRow predictionRow,
final String structure) {
return (StringUtils.equals(structure, DataStructureType.VECTOR)) ? JavaConverters
.asJavaIteratorConverter(predictionRow.getTensor(0).toDense().rawValuesIterator()).asJava()
: predictionRow.getList(0).iterator();
}
}
| 7,649 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/controller/ServingController.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.controller;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import com.amazonaws.sagemaker.dto.BatchExecutionParameter;
import com.amazonaws.sagemaker.dto.DataSchema;
import com.amazonaws.sagemaker.dto.SageMakerRequestListObject;
import com.amazonaws.sagemaker.dto.SageMakerRequestObject;
import com.amazonaws.sagemaker.helper.DataConversionHelper;
import com.amazonaws.sagemaker.helper.ResponseHelper;
import com.amazonaws.sagemaker.type.AdditionalMediaType;
import com.amazonaws.sagemaker.type.DataStructureType;
import com.amazonaws.sagemaker.utils.ScalaUtils;
import com.amazonaws.sagemaker.utils.SystemUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import ml.combust.mleap.runtime.frame.ArrayRow;
import ml.combust.mleap.runtime.frame.DefaultLeapFrame;
import ml.combust.mleap.runtime.frame.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* The Spring controller class which implements the APIs
*/
@RestController
public class ServingController {
private static final Logger LOG = LogManager.getLogger(ServingController.class);
private static final List<String> VALID_ACCEPT_LIST = Lists
.newArrayList(AdditionalMediaType.TEXT_CSV_VALUE, AdditionalMediaType.APPLICATION_JSONLINES_VALUE,
AdditionalMediaType.APPLICATION_JSONLINES_TEXT_VALUE);
private final Transformer mleapTransformer;
private final ResponseHelper responseHelper;
private final DataConversionHelper dataConversionHelper;
private final ObjectMapper mapper;
@Autowired
public ServingController(final Transformer mleapTransformer, final ResponseHelper responseHelper,
final DataConversionHelper dataConversionHelper, final ObjectMapper mapper) {
this.mleapTransformer = Preconditions.checkNotNull(mleapTransformer);
this.responseHelper = Preconditions.checkNotNull(responseHelper);
this.dataConversionHelper = Preconditions.checkNotNull(dataConversionHelper);
this.mapper = Preconditions.checkNotNull(mapper);
}
/**
* Implements the health check GET API
*
* @return ResponseEntity with status 200
*/
@RequestMapping(path = "/ping", method = GET)
public ResponseEntity performShallowHealthCheck() {
return ResponseEntity.ok().build();
}
/**
* Implements the Batch Execution GET Parameter API
*
* @return ResponseEntity with body as the expected payload JSON & status 200
*/
@RequestMapping(path = "/execution-parameters", method = GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity returnBatchExecutionParameter() throws JsonProcessingException {
final BatchExecutionParameter batchParam = new BatchExecutionParameter(SystemUtils.getNumberOfThreads(1),
"SINGLE_RECORD", 5);
final String responseStr = mapper.writeValueAsString(batchParam);
return ResponseEntity.ok(responseStr);
}
/**
* Implements the invocations POST API for application/json input
*
* @param sro, the request object
* @param accept, indicates the content types that the http method is able to understand
* @return ResponseEntity with body as the expected payload JSON & proper statuscode based on the input
*/
@RequestMapping(path = "/invocations", method = POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> transformRequestJson(@RequestBody final SageMakerRequestObject sro,
@RequestHeader(value = HttpHeaders.ACCEPT, required = false) final String accept) {
if (sro == null) {
LOG.error("Input passed to the request is empty");
return ResponseEntity.noContent().build();
}
try {
final String acceptVal = this.retrieveAndVerifyAccept(accept);
final DataSchema schema = this.retrieveAndVerifySchema(sro.getSchema(), mapper);
return this.processInputData(sro.getData(), schema, acceptVal);
} catch (final Exception ex) {
LOG.error("Error in processing current request", ex);
return ResponseEntity.badRequest().body(ex.getMessage());
}
}
/**
* Implements the invocations POST API for text/csv input
*
* @param csvRow, data in row format in CSV
* @param accept, indicates the content types that the http method is able to understand
* @return ResponseEntity with body as the expected payload JSON & proper statuscode based on the input
*/
@RequestMapping(path = "/invocations", method = POST, consumes = AdditionalMediaType.TEXT_CSV_VALUE)
public ResponseEntity<String> transformRequestCsv(@RequestBody final byte[] csvRow,
@RequestHeader(value = HttpHeaders.ACCEPT, required = false) String accept) {
if (csvRow == null) {
LOG.error("Input passed to the request is empty");
return ResponseEntity.noContent().build();
}
try {
final String acceptVal = this.retrieveAndVerifyAccept(accept);
final DataSchema schema = this.retrieveAndVerifySchema(null, mapper);
return this
.processInputData(dataConversionHelper.convertCsvToObjectList(new String(csvRow), schema), schema,
acceptVal);
} catch (final Exception ex) {
LOG.error("Error in processing current request", ex);
return ResponseEntity.badRequest().body(ex.getMessage());
}
}
/**
* Implements the invocations POST API for application/jsonlines input
*
* @param jsonLines, lines of json values
* @param accept, indicates the content types that the http method is able to understand
* @return ResponseEntity with body as the expected payload JSON & proper statuscode based on the input
*/
@RequestMapping(path = "/invocations", method = POST, consumes = AdditionalMediaType.APPLICATION_JSONLINES_VALUE)
public ResponseEntity<String> transformRequestJsonLines(
@RequestBody final byte[] jsonLines,
@RequestHeader(value = HttpHeaders.ACCEPT, required = false)
final String accept) {
if (jsonLines == null) {
LOG.error("Input passed to the request is null");
return ResponseEntity.badRequest().build();
} else if (jsonLines.length == 0) {
LOG.error("Input passed to the request is empty");
return ResponseEntity.noContent().build();
}
try {
final String acceptVal = this.retrieveAndVerifyAccept(accept);
return this.processInputDataForJsonLines(new String(jsonLines), acceptVal);
} catch (final Exception ex) {
LOG.error("Error in processing current request", ex);
return ResponseEntity.badRequest().body(ex.getMessage());
}
}
@VisibleForTesting
protected String retrieveAndVerifyAccept(final String acceptFromRequest) {
final String acceptVal = checkEmptyAccept(acceptFromRequest) ? SystemUtils
.getEnvironmentVariable("SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT") : acceptFromRequest;
if (StringUtils.isNotEmpty(acceptVal) && !VALID_ACCEPT_LIST.contains(acceptVal)) {
throw new IllegalArgumentException("Accept value passed via request or environment variable is not valid");
}
return StringUtils.isNotEmpty(acceptVal) ? acceptVal : AdditionalMediaType.TEXT_CSV_VALUE;
}
@VisibleForTesting
protected DataSchema retrieveAndVerifySchema(final DataSchema schemaFromPayload, final ObjectMapper mapper)
throws IOException {
if ((schemaFromPayload == null) && (SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA") == null)) {
throw new RuntimeException(
"Input schema has to be provided either via environment variable or " + "via the request");
}
return (schemaFromPayload != null) ? schemaFromPayload
: mapper.readValue(SystemUtils.getEnvironmentVariable("SAGEMAKER_SPARKML_SCHEMA"), DataSchema.class);
}
private ResponseEntity<String> processInputData(final List<Object> inputData, final DataSchema schema,
final String acceptVal) throws JsonProcessingException {
final DefaultLeapFrame leapFrame = dataConversionHelper.convertInputToLeapFrame(schema, inputData);
// Making call to the MLeap executor to get the output
final DefaultLeapFrame totalLeapFrame = ScalaUtils.transformLeapFrame(mleapTransformer, leapFrame);
final DefaultLeapFrame predictionsLeapFrame = ScalaUtils
.selectFromLeapFrame(totalLeapFrame, schema.getOutput().getName());
final ArrayRow outputArrayRow = ScalaUtils.getOutputArrayRow(predictionsLeapFrame);
return transformToHttpResponse(schema, outputArrayRow, acceptVal);
}
/**
* Helper method to interpret the JSONLines input and return the response in the expected output format.
*
* @param jsonLinesAsString
* The JSON lines input.
*
* @param acceptVal
* The output format in which the response is to be returned.
*
* @return
* The transformed output for the JSONlines input.
*
* @throws IOException
* If there is an exception during object mapping and validation.
*
*/
ResponseEntity<String> processInputDataForJsonLines(
final String jsonLinesAsString, final String acceptVal) throws IOException {
final String lines[] = jsonLinesAsString.split("\\r?\\n");
final ObjectMapper mapper = new ObjectMapper();
// first line is special since it could contain the schema as well. Extract the schema.
final SageMakerRequestObject firstLine = mapper.readValue(lines[0], SageMakerRequestObject.class);
final DataSchema schema = this.retrieveAndVerifySchema(firstLine.getSchema(), mapper);
List<List<Object>> inputDatas = Lists.newArrayList();
for(String jsonStringLine : lines) {
try {
final SageMakerRequestListObject sro = mapper.readValue(jsonStringLine, SageMakerRequestListObject.class);
for(int idx = 0; idx < sro.getData().size(); ++idx) {
inputDatas.add(sro.getData().get(idx));
}
} catch (final JsonMappingException ex) {
final SageMakerRequestObject sro = mapper.readValue(jsonStringLine, SageMakerRequestObject.class);
inputDatas.add(sro.getData());
}
}
List<ResponseEntity<String>> responseList = Lists.newArrayList();
// Process each input separately and add response to a list
for (int idx = 0; idx < inputDatas.size(); ++idx) {
responseList.add(this.processInputData(inputDatas.get(idx), schema, acceptVal));
}
// Merge response body to a new output response
List<List<String>> bodyList = Lists.newArrayList();
// All response should be valid if no exception got catch
// which all headers should be the same and extract the first one to construct responseEntity
HttpHeaders headers = responseList.get(0).getHeaders();
//combine body in responseList
for (ResponseEntity<String> response: responseList) {
bodyList.add(Lists.newArrayList(response.getBody()));
}
return ResponseEntity.ok().headers(headers).body(bodyList.toString());
}
private boolean checkEmptyAccept(final String acceptFromRequest) {
//Spring may send the Accept as "*\/*" (star/star) in case accept is not passed via request
return (StringUtils.isBlank(acceptFromRequest) || StringUtils.equals(acceptFromRequest, MediaType.ALL_VALUE));
}
private ResponseEntity<String> transformToHttpResponse(final DataSchema schema, final ArrayRow predictionRow,
final String accept) throws JsonProcessingException {
if (StringUtils.equals(schema.getOutput().getStruct(), DataStructureType.BASIC)) {
final Object output = dataConversionHelper
.convertMLeapBasicTypeToJavaType(predictionRow, schema.getOutput().getType());
return responseHelper.sendResponseForSingleValue(output.toString(), accept);
} else {
// If not basic type, it can be vector or array type from Spark
return responseHelper.sendResponseForList(
ScalaUtils.getJavaObjectIteratorFromArrayRow(predictionRow, schema.getOutput().getStruct()), accept);
}
}
}
| 7,650 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/type/DataStructureType.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.type;
/**
* Each column in the input and output can be a single value (basic), Spark ArrayType(array) or Spark Vector type
* (vector)
*/
public final class DataStructureType {
public static final String BASIC = "basic";
public static final String VECTOR = "vector";
public static final String ARRAY = "array";
}
| 7,651 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/type/BasicDataType.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.type;
/**
* Basic data types supported for each column in the input. Each column can be an individual value or an Array/Vector
* (List) * of this.
*/
public final class BasicDataType {
public static final String BOOLEAN = "boolean";
public static final String BYTE = "byte";
public static final String SHORT = "short";
public static final String INTEGER = "int";
public static final String FLOAT = "float";
public static final String LONG = "long";
public static final String DOUBLE = "double";
public static final String STRING = "string";
}
| 7,652 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/type/AdditionalMediaType.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.type;
/**
* This class contains MIME types which are not part of Spring officially provided MIME types
*/
public final class AdditionalMediaType {
public static final String TEXT_CSV_VALUE = "text/csv";
public static final String APPLICATION_JSONLINES_VALUE = "application/jsonlines";
public static final String APPLICATION_JSONLINES_TEXT_VALUE = "application/jsonlines;data=text";
}
| 7,653 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/helper/ResponseHelper.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.helper;
import com.amazonaws.sagemaker.dto.JsonlinesStandardOutput;
import com.amazonaws.sagemaker.dto.JsonlinesTextOutput;
import com.amazonaws.sagemaker.type.AdditionalMediaType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
/**
* This class contains the logic for converting MLeap helper into SageMaker specific helper along with status-codes
*/
@Component
public class ResponseHelper {
private final ObjectMapper mapper;
@Autowired
public ResponseHelper(final ObjectMapper mapper) {
this.mapper = Preconditions.checkNotNull(mapper);
}
/**
* Sends the helper when the output is a single value (e.g. prediction)
*
* @param value, the helper value
* @param acceptVal, the accept customer has passed or default (text/csv) if not passed
* @return Spring ResponseEntity which contains the body and the header
*/
public ResponseEntity<String> sendResponseForSingleValue(final String value, String acceptVal) {
if (StringUtils.isEmpty(acceptVal)) {
acceptVal = AdditionalMediaType.TEXT_CSV_VALUE;
}
return StringUtils.equals(acceptVal, AdditionalMediaType.TEXT_CSV_VALUE) ? this.getCsvOkResponse(value)
: this.getJsonlinesOkResponse(value);
}
/**
* This method is responsible for sending the values in the appropriate format so that it can be parsed by other 1P
* algorithms. Currently, it supports two formats, standard jsonlines and jsonlines for text. Please see
* test/resources/com/amazonaws/sagemaker/dto for example output format or SageMaker built-in algorithms
* documentaiton to know about the output format.
*
* @param outputDataIterator, data iterator for raw output values in case output is an Array or Vector
* @param acceptVal, the accept customer has passed or default (text/csv) if not passed
* @return Spring ResponseEntity which contains the body and the header.
*/
public ResponseEntity<String> sendResponseForList(final Iterator<Object> outputDataIterator, String acceptVal)
throws JsonProcessingException {
if (StringUtils.equals(acceptVal, AdditionalMediaType.APPLICATION_JSONLINES_VALUE)) {
return this.buildStandardJsonOutputForList(outputDataIterator);
} else if (StringUtils.equals(acceptVal, AdditionalMediaType.APPLICATION_JSONLINES_TEXT_VALUE)) {
return this.buildTextJsonOutputForList(outputDataIterator);
} else {
return this.buildCsvOutputForList(outputDataIterator);
}
}
private ResponseEntity<String> buildCsvOutputForList(final Iterator<Object> outputDataIterator) {
final StringJoiner sj = new StringJoiner(",");
while (outputDataIterator.hasNext()) {
sj.add(outputDataIterator.next().toString());
}
return this.getCsvOkResponse(sj.toString());
}
private ResponseEntity<String> buildStandardJsonOutputForList(final Iterator<Object> outputDataIterator)
throws JsonProcessingException {
final List<Object> columns = Lists.newArrayList();
while (outputDataIterator.hasNext()) {
columns.add(outputDataIterator.next());
}
final JsonlinesStandardOutput jsonOutput = new JsonlinesStandardOutput(columns);
final String jsonRepresentation = mapper.writeValueAsString(jsonOutput);
return this.getJsonlinesOkResponse(jsonRepresentation);
}
private ResponseEntity<String> buildTextJsonOutputForList(final Iterator<Object> outputDataIterator)
throws JsonProcessingException {
final StringJoiner stringJoiner = new StringJoiner(" ");
while (outputDataIterator.hasNext()) {
stringJoiner.add(outputDataIterator.next().toString());
}
final JsonlinesTextOutput jsonOutput = new JsonlinesTextOutput(stringJoiner.toString());
final String jsonRepresentation = mapper.writeValueAsString(jsonOutput);
return this.getJsonlinesOkResponse(jsonRepresentation);
}
private ResponseEntity<String> getCsvOkResponse(final String responseBody) {
final HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_TYPE, AdditionalMediaType.TEXT_CSV_VALUE);
return ResponseEntity.ok().headers(headers).body(responseBody);
}
// We are always responding with the valid format for application/jsonlines, whicth is a valid JSON
private ResponseEntity<String> getJsonlinesOkResponse(final String responseBody) {
final HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_TYPE, AdditionalMediaType.APPLICATION_JSONLINES_VALUE);
return ResponseEntity.ok().headers(headers).body(responseBody);
}
}
| 7,654 |
0 | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker | Create_ds/sagemaker-sparkml-serving-container/src/main/java/com/amazonaws/sagemaker/helper/DataConversionHelper.java | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazonaws.sagemaker.helper;
import com.amazonaws.sagemaker.dto.ColumnSchema;
import com.amazonaws.sagemaker.dto.DataSchema;
import com.amazonaws.sagemaker.type.BasicDataType;
import com.amazonaws.sagemaker.type.DataStructureType;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import ml.combust.mleap.core.types.*;
import ml.combust.mleap.runtime.frame.ArrayRow;
import ml.combust.mleap.runtime.frame.DefaultLeapFrame;
import ml.combust.mleap.runtime.frame.Row;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilder;
import ml.combust.mleap.runtime.javadsl.LeapFrameBuilderSupport;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.ml.linalg.Vectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.stream.Collectors;
/**
* Converter class to convert data between input to MLeap expected types and convert back MLeap helper to Java types
* for output.
*/
@Component
public class DataConversionHelper {
private final LeapFrameBuilderSupport support;
private final LeapFrameBuilder leapFrameBuilder;
@Autowired
public DataConversionHelper(final LeapFrameBuilderSupport support, final LeapFrameBuilder leapFrameBuilder) {
this.support = Preconditions.checkNotNull(support);
this.leapFrameBuilder = Preconditions.checkNotNull(leapFrameBuilder);
}
/**
* Parses the input payload in CSV format to a list of Objects
* @param csvInput, the input received from the request in CSV format
* @param schema, the data schema retrieved from environment variable
* @return List of Objects, where each Object correspond to one feature of the input data
* @throws IOException, if there is an exception thrown in the try-with-resources block
*/
public List<Object> convertCsvToObjectList(final String csvInput, final DataSchema schema) throws IOException {
try (final StringReader sr = new StringReader(csvInput)) {
final List<Object> valueList = Lists.newArrayList();
final CSVParser parser = CSVFormat.DEFAULT.parse(sr);
// We don not supporting multiple CSV lines as input currently
final CSVRecord record = parser.getRecords().get(0);
final int inputLength = schema.getInput().size();
for (int idx = 0; idx < inputLength; ++idx) {
ColumnSchema sc = schema.getInput().get(idx);
// For CSV input, each value is treated as an individual feature by default
valueList.add(this.convertInputDataToJavaType(sc.getType(), DataStructureType.BASIC, record.get(idx)));
}
return valueList;
}
}
/**
* Convert input object to DefaultLeapFrame
*
* @param schema, the input schema received from request or environment variable
* @param data , the input data received from request as a list of objects
* @return the DefaultLeapFrame object which MLeap transformer expects
*/
public DefaultLeapFrame convertInputToLeapFrame(final DataSchema schema, final List<Object> data) {
final int inputLength = schema.getInput().size();
final List<StructField> structFieldList = Lists.newArrayList();
final List<Object> valueList = Lists.newArrayList();
for (int idx = 0; idx < inputLength; ++idx) {
ColumnSchema sc = schema.getInput().get(idx);
structFieldList
.add(new StructField(sc.getName(), this.convertInputToMLeapInputType(sc.getType(), sc.getStruct())));
valueList.add(this.convertInputDataToJavaType(sc.getType(), sc.getStruct(), data.get(idx)));
}
final StructType mleapSchema = leapFrameBuilder.createSchema(structFieldList);
final Row currentRow = support.createRowFromIterable(valueList);
final List<Row> rows = Lists.newArrayList();
rows.add(currentRow);
return leapFrameBuilder.createFrame(mleapSchema, rows);
}
/**
* Convert basic types in the MLeap helper to Java types for output.
*
* @param predictionRow, the ArrayRow from MLeapResponse
* @param type, the basic type to which the helper should be casted, provided by user via input
* @return the proper Java type
*/
public Object convertMLeapBasicTypeToJavaType(final ArrayRow predictionRow, final String type) {
switch (type) {
case BasicDataType.INTEGER:
return predictionRow.getInt(0);
case BasicDataType.LONG:
return predictionRow.getLong(0);
case BasicDataType.FLOAT:
case BasicDataType.DOUBLE:
return predictionRow.getDouble(0);
case BasicDataType.BOOLEAN:
return predictionRow.getBool(0);
case BasicDataType.BYTE:
return predictionRow.getByte(0);
case BasicDataType.SHORT:
return predictionRow.getShort(0);
case BasicDataType.STRING:
return predictionRow.getString(0);
default:
throw new IllegalArgumentException("Given type is not supported");
}
}
@SuppressWarnings("unchecked")
@VisibleForTesting
protected Object convertInputDataToJavaType(final String type, final String structure, final Object value) {
if (StringUtils.isBlank(structure) || StringUtils.equals(structure, DataStructureType.BASIC)) {
switch (type) {
case BasicDataType.INTEGER:
return new Integer(value.toString());
case BasicDataType.LONG:
return new Long(value.toString());
case BasicDataType.FLOAT:
return new Float(value.toString());
case BasicDataType.DOUBLE:
return new Double(value.toString());
case BasicDataType.BOOLEAN:
return Boolean.valueOf(value.toString());
case BasicDataType.BYTE:
return new Byte(value.toString());
case BasicDataType.SHORT:
return new Short(value.toString());
case BasicDataType.STRING:
return value.toString();
default:
throw new IllegalArgumentException("Given type is not supported");
}
} else if (!StringUtils.isBlank(structure) && StringUtils.equals(structure, DataStructureType.ARRAY)) {
List<Object> listOfObjects;
try {
listOfObjects = (List<Object>) value;
} catch (ClassCastException cce) {
throw new IllegalArgumentException("Input val is not a list but struct passed is array");
}
switch (type) {
case BasicDataType.INTEGER:
return listOfObjects.stream().map(elem -> (Integer) elem).collect(Collectors.toList());
case BasicDataType.LONG:
return listOfObjects.stream().map(elem -> (Long) elem).collect(Collectors.toList());
case BasicDataType.FLOAT:
case BasicDataType.DOUBLE:
return listOfObjects.stream().map(elem -> (Double) elem).collect(Collectors.toList());
case BasicDataType.BOOLEAN:
return listOfObjects.stream().map(elem -> (Boolean) elem).collect(Collectors.toList());
case BasicDataType.BYTE:
return listOfObjects.stream().map(elem -> (Byte) elem).collect(Collectors.toList());
case BasicDataType.SHORT:
return listOfObjects.stream().map(elem -> (Short) elem).collect(Collectors.toList());
case BasicDataType.STRING:
return listOfObjects.stream().map(elem -> (String) elem).collect(Collectors.toList());
default:
throw new IllegalArgumentException("Given type is not supported");
}
} else {
if(!type.equals(BasicDataType.DOUBLE))
throw new IllegalArgumentException("Only Double type is supported for vector");
List<Double> vectorValues;
try {
vectorValues = (List<Double>)value;
} catch (ClassCastException cce) {
throw new IllegalArgumentException("Input val is not a list but struct passed is vector");
}
double[] primitiveVectorValues = vectorValues.stream().mapToDouble(d -> d).toArray();
return Vectors.dense(primitiveVectorValues);
}
}
@VisibleForTesting
protected DataType convertInputToMLeapInputType(final String type, final String structure) {
BasicType basicType;
switch (type) {
case BasicDataType.INTEGER:
basicType = support.createInt();
break;
case BasicDataType.LONG:
basicType = support.createLong();
break;
case BasicDataType.FLOAT:
basicType = support.createFloat();
break;
case BasicDataType.DOUBLE:
basicType = support.createDouble();
break;
case BasicDataType.BOOLEAN:
basicType = support.createBoolean();
break;
case BasicDataType.BYTE:
basicType = support.createByte();
break;
case BasicDataType.SHORT:
basicType = support.createShort();
break;
case BasicDataType.STRING:
basicType = support.createString();
break;
default:
basicType = null;
}
if (basicType == null) {
throw new IllegalArgumentException("Data type passed in the request is wrong for one or more columns");
}
if (StringUtils.isNotBlank(structure)) {
switch (structure) {
case DataStructureType.VECTOR:
return new TensorType(basicType, true);
case DataStructureType.ARRAY:
return new ListType(basicType, true);
case DataStructureType.BASIC:
return new ScalarType(basicType, true);
}
}
// if structure field is not passed, it is by default basic
return new ScalarType(basicType, true);
}
}
| 7,655 |
0 | Create_ds/jetpack/java/src/test/java/jetpack | Create_ds/jetpack/java/src/test/java/jetpack/ssl/VersionedFileResolverTest.java | package jetpack.ssl;
import java.io.File;
import java.io.FileNotFoundException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.fest.assertions.api.Assertions.assertThat;
public class VersionedFileResolverTest {
@Rule public TemporaryFolder tempDir = new TemporaryFolder();
@Test public void loadsLatest() throws Exception {
File base = tempDir.newFile("foo.txt");
FileResolver fileResolver = new VersionedFileResolver(base);
assertThat(fileResolver.resolve()).isEqualTo(base);
File v2 = tempDir.newFile("foo.txt..2");
assertThat(fileResolver.resolve()).isEqualTo(v2);
File v4 = tempDir.newFile("foo.txt..4");
assertThat(fileResolver.resolve()).isEqualTo(v4);
tempDir.newFile("foo.txt..3");
assertThat(fileResolver.resolve()).isEqualTo(v4);
}
@Test public void testIgnoresFilesWithoutVersionIdentifier() throws Exception {
File base = tempDir.newFile("bar.txt");
FileResolver fileResolver = new VersionedFileResolver(base);
// This should get ignored because it doesn't contain the versioned file prefix
tempDir.newFile("bar.txt.bak");
assertThat(fileResolver.resolve()).isEqualTo(base);
}
@Test(expected = FileNotFoundException.class)
public void testThrowsWhenFileNotFound() throws Exception {
FileResolver fileResolver = new VersionedFileResolver(
new File(tempDir.getRoot(), "dne.txt"));
fileResolver.resolve();
}
@Test public void resolvesVersionsIfBaseFileDoesNotExist() throws Exception {
File v1 = tempDir.newFile("baz.txt..v1");
FileResolver fileResolver = new VersionedFileResolver(
new File(tempDir.getRoot(), "baz.txt"));
assertThat(fileResolver.resolve()).isEqualTo(v1);
}
@Test(expected = IllegalArgumentException.class)
public void testThrowsWhenBasePathIsDirectory() throws Exception {
new VersionedFileResolver(tempDir.getRoot());
}
@Test(expected = IllegalArgumentException.class)
public void testThrowsWhenParentDirectoryDoesNotExist() throws Exception {
new VersionedFileResolver(new File(tempDir.getRoot(), "food/donut.txt"));
}
}
| 7,656 |
0 | Create_ds/jetpack/java/src/test/java/jetpack | Create_ds/jetpack/java/src/test/java/jetpack/ssl/ReloadingKeyManagerTest.java | package jetpack.ssl;
import com.google.common.io.Resources;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.security.cert.X509Certificate;
import java.util.NoSuchElementException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.fest.assertions.api.Assertions.assertThat;
public class ReloadingKeyManagerTest {
final char[] password = "password".toCharArray();
@Rule public TemporaryFolder tempDir = new TemporaryFolder();
@Test public void managesKeyStoreWithSingleKey() throws Exception {
File file = tempDir.newFile("managesKeyStoreWithSingleKey.jceks");
Resources.copy(Resources.getResource("singleKey.jceks"), new FileOutputStream(file));
ReloadingKeyManager keyManager =
new ReloadingKeyManager(staticResolver(file), password, "JCEKS", null);
assertThat(keyManager.getClientAliases(null, null)).containsOnly("singlekey");
assertThat(keyManager.getServerAliases(null, null)).containsOnly("singlekey");
X509Certificate[] certChain = keyManager.getCertificateChain("singlekey");
assertThat(certChain).hasSize(1);
assertThat(certChain[0].getSubjectDN().getName()).isEqualTo("CN=singleKey");
assertThat(keyManager.getPrivateKey("singlekey")).isNotNull();
}
@Test(expected = NoSuchElementException.class)
public void failsForTruststore() throws Exception {
File file = tempDir.newFile("failsForTruststore.jceks");
Resources.copy(Resources.getResource("singleCert.jceks"), new FileOutputStream(file));
new ReloadingKeyManager(staticResolver(file), password, "JCEKS", null);
}
@Test(expected = IllegalArgumentException.class)
public void failsForKeystoreWithMultipleKeys() throws Exception {
File file = tempDir.newFile("failsForKeystoreWithMultipleKeys.jceks");
Resources.copy(Resources.getResource("multipleKeys.jceks"), new FileOutputStream(file));
new ReloadingKeyManager(staticResolver(file), password, "JCEKS", null);
}
/** @return FileResolver that always resolves the same file. */
private static FileResolver staticResolver(final File file) {
return new FileResolver() {
@Override public File resolve() throws FileNotFoundException { return file; }
@Override public String getSearchPath() { return file.getPath(); }
};
}
}
| 7,657 |
0 | Create_ds/jetpack/java/src/main/java/jetpack | Create_ds/jetpack/java/src/main/java/jetpack/ssl/ReloadingSslContextFactory.java | package jetpack.ssl;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import static com.google.common.base.Preconditions.checkArgument;
import static jetpack.ssl.ReloadingKeyManager.loadKeyStore;
/**
* Builds {@link SSLContext}s from the given configs.
*/
public class ReloadingSslContextFactory {
private ReloadingSslContextFactory() {}
private static final String TRUST_ALG = TrustManagerFactory.getDefaultAlgorithm();
/**
* Builds a TLS/SunJSSE SSL context given the key and trust store configs.
*/
public static SSLContext create(String keyStorePath, String keyStorePassword, String keyStoreType,
String trustStoreFilename, String trustStorePassword)
throws GeneralSecurityException, IOException {
checkArgument(!keyStorePath.isEmpty(), "keyStorePath must not be empty.");
checkArgument(!trustStoreFilename.isEmpty(), "trustStoreFilename must not be empty.");
// Load the trust store.
String trustStoreType = Files.getFileExtension(trustStoreFilename).toUpperCase();
KeyStore trustStore = loadKeyStore(new File(trustStoreFilename), trustStoreType, trustStorePassword);
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TRUST_ALG);
trustFactory.init(trustStore);
// Load the key managers.
char[] passPhrase = Strings.nullToEmpty(keyStorePassword).toCharArray();
VersionedFileResolver fileResolver = new VersionedFileResolver(new File(keyStorePath));
X509KeyManager reloadingKeyManager = new ReloadingKeyManager(fileResolver, passPhrase,
keyStoreType);
KeyManager[] keyManagers = new KeyManager[] { reloadingKeyManager };
// Build the SSL context for TLS.
SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
sslContext.init(keyManagers, trustFactory.getTrustManagers(), null);
return sslContext;
}
}
| 7,658 |
0 | Create_ds/jetpack/java/src/main/java/jetpack | Create_ds/jetpack/java/src/main/java/jetpack/ssl/FileResolver.java | package jetpack.ssl;
import java.io.File;
import java.io.FileNotFoundException;
/** Simple interface to resolve {@link java.io.File}s. */
public interface FileResolver {
/**
* @return resolved File object.
* @throws java.io.FileNotFoundException when file not found.
*/
File resolve() throws FileNotFoundException;
/** @return The path to search for files. */
String getSearchPath();
}
| 7,659 |
0 | Create_ds/jetpack/java/src/main/java/jetpack | Create_ds/jetpack/java/src/main/java/jetpack/ssl/VersionedFileResolver.java | package jetpack.ssl;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
/**
* Utility for loading the latest version of a file.
*
* File names are composed of basename + separator + version, where the separator is <tt>..</tt>.
* Valid names include <tt>hello.txt</tt>, <tt>hello.txt..0aae825a73e161d8</tt>, and
* <tt>hello.txt..bafe155a72e1aadb</tt>. The latest version is determined as the lexicographically
* greatest.
*
* {@code
* VersionedFiledResolver versionedFileResolver = new VersionedFileResolver("/tmp/hello.txt");
* // Assuming /tmp/ contains hello.txt and hello.txt..0aae825a73e161d8
* versionedFiledLoader.resolve() // returns new File("/tmp/hello.txt..0aae825a73e161d8");
* // Assuming /tmp/ contains only hello.txt
* versionedFiledLoader.resolve() // returns new File("/tmp/hello.txt");
* }
*/
public class VersionedFileResolver implements FileResolver {
public static final String VERSIONED_FILE_PREFIX = "..";
private final FilenameFilter filenameFilter;
private final File baseDirPath;
private final File basePath;
/**
* @param basePath The basename of the versioned file to resolve.
*/
public VersionedFileResolver(File basePath) {
checkArgument(!basePath.isDirectory() && basePath.getParentFile().isDirectory());
this.basePath = basePath;
this.baseDirPath = basePath.getParentFile();
final String basename = basePath.getName();
filenameFilter = new FilenameFilter() {
@Override public boolean accept(File file, String s) {
return s.equals(basename) || s.startsWith(basename + VERSIONED_FILE_PREFIX);
}
};
}
/**
* @return File path of the lexicographically latest version of the filename, or the base file if
* it exists and no other versions do.
* @throws FileNotFoundException if no version of the file can be found
*/
@Override public File resolve() throws FileNotFoundException {
String[] list = baseDirPath.list(filenameFilter);
if (list == null) {
throw new RuntimeException(
format("Error performing partial directory listing of '%s', returned null.", baseDirPath));
}
List<File> files = Lists.newArrayList();
for (String filename : list) {
files.add(new File(baseDirPath, filename));
}
if (files.isEmpty()) {
throw new FileNotFoundException("Could not find any version of \"" + basePath + "\".");
}
return Ordering.natural().max(files);
}
/** @return The path where versioned files are being searched for. */
@Override public String getSearchPath() {
return basePath.getPath();
}
}
| 7,660 |
0 | Create_ds/jetpack/java/src/main/java/jetpack | Create_ds/jetpack/java/src/main/java/jetpack/ssl/ReloadingKeyManager.java | package jetpack.ssl;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.io.Closer;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
/** X509KeyManager which periodically looks for a newer key and transparently reloads. */
public class ReloadingKeyManager extends X509ExtendedKeyManager {
public static final Duration DEFAULT_RELOAD_INTERVAL = Duration.standardHours(2);
private static final Logger logger = LoggerFactory.getLogger(ReloadingKeyManager.class);
private final ThreadFactory namedThreadFactory =
new ThreadFactoryBuilder().setNameFormat("reloading-key-manager").build();
private final ScheduledExecutorService reloadScheduler =
Executors.newSingleThreadScheduledExecutor(namedThreadFactory);
private final FileResolver fileResolver;
private final char[] pin;
private final String keyStoreType;
private final Duration reloadInterval;
private volatile KeyStore keyStore;
private volatile String keyName;
/**
* @param fileResolver which resolves a {@link java.io.File} for a {@link java.security.KeyStore}.
* @param pin KeyStore password.
* @param keyStoreType KeyStore type.
*/
public ReloadingKeyManager(FileResolver fileResolver, char[] pin, String keyStoreType) {
this(fileResolver, pin, keyStoreType, DEFAULT_RELOAD_INTERVAL);
}
/**
* @param fileResolver which resolves a {@link File} for a {@link KeyStore}.
* @param pin KeyStore password.
* @param keyStoreType KeyStore type.
* @param reloadInterval custom interval to re-resolve and reload the KeyStore.
* If null or Duration.ZERO, the KeyStore is loaded once.
*/
public ReloadingKeyManager(FileResolver fileResolver, char[] pin, String keyStoreType,
Duration reloadInterval) {
this.fileResolver = checkNotNull(fileResolver);
this.pin = checkNotNull(pin);
this.keyStoreType = checkNotNull(keyStoreType);
this.reloadInterval = reloadInterval;
loadKeyStore();
reloadKeyStoreOnInterval();
}
/** @return interval between keystore reloads. */
public Duration getReloadInterval() {
return reloadInterval;
}
@Override
public String[] getClientAliases(String string, Principal[] principals) {
return new String[] {keyName};
}
@Override
public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
return keyName;
}
@Override
public String[] getServerAliases(String string, Principal[] principals) {
return new String[] {keyName};
}
@Override
public String chooseServerAlias(String string, Principal[] principals, Socket socket) {
return keyName;
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
checkArgument(!alias.isEmpty());
try {
Certificate[] certs = keyStore.getCertificateChain(alias);
if (certs == null) {
logger.error("No certificate chain is found for alias: %s", alias);
throw new KeyStoreException("No certificate chain is found for alias: " + alias);
}
List<X509Certificate> x509Certs = Lists.newArrayList();
for (Certificate cert : certs) {
if (cert instanceof X509Certificate) {
x509Certs.add((X509Certificate) cert);
}
}
return x509Certs.toArray(new X509Certificate[x509Certs.size()]);
} catch (KeyStoreException e) {
throw Throwables.propagate(e);
}
}
@Override
public PrivateKey getPrivateKey(String keyAlias) {
checkArgument(!keyAlias.isEmpty());
try {
return (PrivateKey) keyStore.getKey(keyAlias, pin);
} catch (KeyStoreException e) {
// KeyStore is initialized at construction, so this should not occur.
throw new AssertionError(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Algorithm for reading key not available", e);
} catch (UnrecoverableKeyException e) {
throw new RuntimeException("Invalid password for reading key " + keyAlias, e);
}
}
@Override
public String chooseEngineClientAlias(String[] strings, Principal[] principals, SSLEngine sslEngine) {
return keyName;
}
@Override
public String chooseEngineServerAlias(String s, Principal[] principals, SSLEngine sslEngine) {
return keyName;
}
private void reloadKeyStoreOnInterval() {
if (Duration.ZERO.isEqual(reloadInterval)) return;
Runnable loader = new Runnable() {
public void run() {
logger.info("Checking for new keystore to load at path {}", fileResolver.getSearchPath());
try {
loadKeyStore();
logger.info("Completed reloading keystore.");
} catch (Exception e) {
logger.error("Keystore reload failed", e);
}
}
};
reloadScheduler.scheduleAtFixedRate(loader,
reloadInterval.getStandardSeconds(),
reloadInterval.getStandardSeconds(),
SECONDS);
}
private void loadKeyStore() {
File latest;
try {
latest = fileResolver.resolve();
} catch (FileNotFoundException e) {
throw Throwables.propagate(e);
}
logger.info("Resolved latest keystore {}", latest);
try {
keyStore = loadKeyStore(latest, keyStoreType, new String(pin));
} catch (IOException e) {
throw Throwables.propagate(e);
}
List<String> keyAliases = findAliasesOfType(KeyStore.PrivateKeyEntry.class, keyStore);
keyName = Iterables.getOnlyElement(keyAliases);
}
/**
* Finds all aliases present in the keystore of a given entry type.
*
* @param entryClass one of {@link KeyStore.PrivateKeyEntry}, {@link KeyStore.SecretKeyEntry}, or
* {@link KeyStore.TrustedCertificateEntry}.
* @param keyStore keystore containing all the entries.
* @return List of aliases present of the given type.
*/
private static List<String> findAliasesOfType(final Class<? extends KeyStore.Entry> entryClass,
final KeyStore keyStore) {
Iterator<String> aliasIterator;
try {
aliasIterator = Iterators.forEnumeration(keyStore.aliases());
} catch (KeyStoreException e) {
throw new RuntimeException("KeyStore not initialized.", e);
}
Iterator<String> results = Iterators.filter(aliasIterator,
new Predicate<String>() {
@Override public boolean apply(String alias) {
try {
return keyStore.entryInstanceOf(alias, entryClass);
} catch (KeyStoreException e) {
throw Throwables.propagate(e);
}
}
});
return ImmutableList.copyOf(results);
}
/**
* Loads an existing keystore from a file.
*
* @param keyStoreFile file to load from
* @param type keystore type
* @param password optional password to protect keys and keystore with
* @return the loaded keystore
* @throws IOException on I/O errors
*/
public static KeyStore loadKeyStore(File keyStoreFile, String type, String password)
throws IOException {
checkNotNull(keyStoreFile);
checkNotNull(type);
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance(type);
} catch (KeyStoreException e) {
throw new RuntimeException("no provider exists for the keystore type " + type, e);
}
Closer closer = Closer.create();
InputStream stream = closer.register(new BufferedInputStream(new FileInputStream(keyStoreFile)));
try {
keyStore.load(stream, (password == null) ? null : password.toCharArray());
} catch (CertificateException e) {
throw new RuntimeException("some certificates could not be loaded", e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("integrity check algorithm is unavailable", e);
} catch (IOException e) {
throw new RuntimeException("I/O error or a bad password", e);
} catch (Throwable e) { // Prescribed Closer pattern.
throw closer.rethrow(e);
} finally {
closer.close();
}
return keyStore;
}
}
| 7,661 |
0 | Create_ds/jetpack/java/src/main/java/jetpack | Create_ds/jetpack/java/src/main/java/jetpack/filter/IgnoreUnknownHttpMethodsFilter.java | package jetpack.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IgnoreUnknownHttpMethodsFilter implements Filter {
java.util.List<String> allowedMethodList;
public void init(FilterConfig filterConfig) throws ServletException {
allowedMethodList = new java.util.ArrayList<String>();
allowedMethodList.add("GET");
allowedMethodList.add("PUT");
allowedMethodList.add("DELETE");
allowedMethodList.add("POST");
allowedMethodList.add("HEAD");
}
public void destroy() {
allowedMethodList = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
if ( allowedMethodList.contains(req.getMethod()) ) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse)response;
res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
}
} | 7,662 |
0 | Create_ds/jetpack/java/src/main/java/jetpack | Create_ds/jetpack/java/src/main/java/jetpack/filter/ValidUrlFilter.java | package jetpack.filter;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.validator.routines.RegexValidator;
import org.apache.commons.validator.routines.UrlValidator;
public class ValidUrlFilter implements Filter {
UrlValidator urlValidator;
public void init(FilterConfig filterConfig) throws ServletException {
String[] schemes = {"http","https"};
RegexValidator authorityValidator = new RegexValidator("^([\\p{Alnum}\\-\\.]*)(:\\d*)?(.*)?", false);
urlValidator = new UrlValidator(schemes, authorityValidator, UrlValidator.ALLOW_LOCAL_URLS);
}
public void destroy() {
urlValidator = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
String requestUrl = req.getRequestURL().toString();
String queryString = req.getQueryString();
if (queryString != null) {
requestUrl += "?" + queryString;
}
if (urlValidator.isValid(requestUrl) && isValidQuery(queryString)) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse)response;
res.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
}
// commons validator allows any character in query string, we want to restrict it a bit
// and not allow unescaped angle brackets for example.
private static final String QUERY_REGEX = "^([-\\w:@&=~+,.!*'%$_;\\(\\)]*)$";
private static final Pattern QUERY_PATTERN = Pattern.compile(QUERY_REGEX);
protected boolean isValidQuery(String query) {
if (query == null) {
return true;
}
return QUERY_PATTERN.matcher(query).matches();
}
}
| 7,663 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/TestBean.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.aries.transaction.test;
import java.sql.SQLException;
/**
* This interface is used by the transactions integration tests
*
*/
public interface TestBean {
void delegateInsertRow(String name, int value) throws SQLException;
void insertRow(String name, int value, Exception e) throws SQLException;
void throwApplicationException() throws SQLException;
void throwRuntimeException();
}
| 7,664 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/Counter.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.aries.transaction.test;
/**
* Allows to count the rows in the test table
*/
public interface Counter {
int countRows();
}
| 7,665 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/RollbackOnBean.java | package org.apache.aries.transaction.test;
import java.sql.SQLException;
public interface RollbackOnBean {
void throwException(String name, int value) throws Exception;
void throwExceptionRollbackOnException(String name, int value) throws Exception;
void throwRuntimeExceptionRollbackOnException(String name, int value) throws SQLException;
void throwRuntimeExceptionDontRollbackOnException(String name, int value) throws SQLException;
void throwRuntimeExceptionDontRollbackOnAppException(String name, int value) throws SQLException;
void throwRuntimeExceptionRollbackOnAppException(String name, int value) throws SQLException;
void throwApplicationExceptionRollbackOnException(String name, int value) throws SQLException;
void throwApplicationExceptionRollbackOnAppException(String name, int value) throws SQLException;
void throwApplicationExceptionDontRollbackOnException(String name, int value) throws SQLException;
void throwApplicationExceptionDontRollbackOnAppException(String name, int value) throws SQLException;
void throwExceptionRollbackOnExceptionDontRollbackOnAppException(String name, int value) throws SQLException;
void throwExceptionRollbackOnAppExceptionDontRollbackOnException(String name, int value) throws SQLException;
void throwAppExceptionRollbackOnExceptionDontRollbackOnAppException(String name, int value) throws SQLException;
void throwAppExceptionRollbackOnAppExceptionDontRollbackOnException(String name, int value) throws SQLException;
void setrBean(TestBean rBean);
}
| 7,666 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/TestBeanImpl.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.aries.transaction.test.impl;
import java.sql.SQLException;
import org.apache.aries.transaction.test.TestBean;
public class TestBeanImpl implements TestBean {
private Connector connector;
private TestBean bean;
@Override
public void insertRow(String name, int value, Exception e) throws SQLException {
connector.insertRow(name, value);
if (e instanceof SQLException) {
throw (SQLException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
}
@Override
public void delegateInsertRow(String name, int value) throws SQLException {
bean.insertRow(name, value, null);
}
@Override
public void throwApplicationException() throws SQLException {
throw new SQLException("Test exception");
}
@Override
public void throwRuntimeException() {
throw new RuntimeException("Test exception"); // NOSONAR
}
public void setTestBean(TestBean bean) {
this.bean = bean;
}
public void setConnector(Connector connector) {
this.connector = connector;
}
}
| 7,667 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/NeverTestBeanImpl.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.aries.transaction.test.impl;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import java.sql.SQLException;
public class NeverTestBeanImpl extends TestBeanImpl {
@Override
@Transactional(value=TxType.NEVER)
public void insertRow(String name, int value, Exception e) throws SQLException {
super.insertRow(name, value, e);
}
@Override
@Transactional(value=TxType.NEVER)
public void delegateInsertRow(String name, int value) throws SQLException {
super.delegateInsertRow(name, value);
}
}
| 7,668 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/NotSupportedTestBeanImpl.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.aries.transaction.test.impl;
import java.sql.SQLException;
import javax.transaction.Transactional;
@Transactional(Transactional.TxType.NOT_SUPPORTED)
public class NotSupportedTestBeanImpl extends TestBeanImpl {
@Transactional(Transactional.TxType.NOT_SUPPORTED)
@Override
public void delegateInsertRow(String name, int value) throws SQLException {
super.delegateInsertRow(name, value);
}
@Transactional(Transactional.TxType.NOT_SUPPORTED)
@Override
public void throwApplicationException() throws SQLException {
super.throwApplicationException();
}
@Transactional(Transactional.TxType.NOT_SUPPORTED)
@Override
public void throwRuntimeException() {
super.throwRuntimeException();
}
}
| 7,669 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/RollbackOnBeanImpl.java | package org.apache.aries.transaction.test.impl;
import org.apache.aries.transaction.test.RollbackOnBean;
import org.apache.aries.transaction.test.TestBean;
import javax.transaction.Transactional;
import java.sql.SQLException;
import static javax.transaction.Transactional.TxType;
public class RollbackOnBeanImpl implements RollbackOnBean {
private TestBean rBean;
@Override
@Transactional(value = TxType.REQUIRED)
public void throwException(String name, int value) throws Exception {
rBean.insertRow(name, value, null);
throw new Exception("Test exception");
}
@Override
@Transactional(value = TxType.REQUIRED, rollbackOn = Exception.class)
public void throwExceptionRollbackOnException(String name, int value) throws Exception {
rBean.insertRow(name, value, null);
throw new Exception("Test exception");
}
@Override
@Transactional(value = TxType.REQUIRED, rollbackOn = Exception.class)
public void throwRuntimeExceptionRollbackOnException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new RuntimeException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, rollbackOn = SQLException.class)
public void throwRuntimeExceptionRollbackOnAppException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new RuntimeException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = Exception.class)
public void throwRuntimeExceptionDontRollbackOnException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new RuntimeException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = SQLException.class)
public void throwRuntimeExceptionDontRollbackOnAppException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new RuntimeException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, rollbackOn = Exception.class)
public void throwApplicationExceptionRollbackOnException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new SQLException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, rollbackOn = SQLException.class)
public void throwApplicationExceptionRollbackOnAppException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new SQLException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = Exception.class)
public void throwApplicationExceptionDontRollbackOnException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new SQLException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = SQLException.class)
public void throwApplicationExceptionDontRollbackOnAppException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new SQLException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = Exception.class, rollbackOn = SQLException.class)
public void throwExceptionRollbackOnExceptionDontRollbackOnAppException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new RuntimeException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = SQLException.class, rollbackOn = Exception.class)
public void throwExceptionRollbackOnAppExceptionDontRollbackOnException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new RuntimeException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = SQLException.class, rollbackOn = Exception.class)
public void throwAppExceptionRollbackOnExceptionDontRollbackOnAppException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new SQLException("Test exception"));
}
@Override
@Transactional(value = TxType.REQUIRED, dontRollbackOn = Exception.class, rollbackOn = SQLException.class)
public void throwAppExceptionRollbackOnAppExceptionDontRollbackOnException(String name, int value) throws SQLException {
rBean.insertRow(name, value, new SQLException("Test exception"));
}
@Override
public void setrBean(TestBean rBean) {
this.rBean = rBean;
}
}
| 7,670 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/RequiresNewTestBeanImpl.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.aries.transaction.test.impl;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import java.sql.SQLException;
public class RequiresNewTestBeanImpl extends TestBeanImpl {
@Override
@Transactional(value=TxType.REQUIRES_NEW)
public void insertRow(String name, int value, Exception e) throws SQLException {
super.insertRow(name, value, e);
}
@Override
@Transactional(value=TxType.REQUIRES_NEW)
public void delegateInsertRow(String name, int value) throws SQLException {
super.delegateInsertRow(name, value);
}
}
| 7,671 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/RequiredTestBeanImpl.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.aries.transaction.test.impl;
import java.sql.SQLException;
import javax.transaction.Transactional;
public class RequiredTestBeanImpl extends TestBeanImpl {
@Override
@Transactional(Transactional.TxType.REQUIRED)
public void insertRow(String name, int value, Exception e) throws SQLException {
super.insertRow(name, value, e);
}
@Override
@Transactional(Transactional.TxType.REQUIRED)
public void delegateInsertRow(String name, int value) throws SQLException {
super.delegateInsertRow(name, value);
}
}
| 7,672 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/Connector.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.aries.transaction.test.impl;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.apache.aries.transaction.test.Counter;
public class Connector implements Counter {
private DataSource xads;
private String user;
private String password;
private Connection conn;
public void setXads(DataSource xads) {
this.xads = xads;
}
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
private Connection connect() throws SQLException {
return xads.getConnection(user, password);
}
public Connection getConn() {
return conn;
}
public void initialize() throws SQLException {
conn = connect();
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, "", "TESTTABLE", null);
if (!rs.next()) {
executeUpdate("CREATE TABLE TESTTABLE (NAME VARCHAR(64), VALUE INTEGER, PRIMARY KEY(NAME, VALUE))");
}
}
public void executeUpdate(String sql) {
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
conn.commit();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e); // NOSONAR
} finally {
safeClose(stmt);
}
}
@Override
public int countRows() {
PreparedStatement stmt = null;
ResultSet rs = null;
int count = -1;
try {
stmt = conn.prepareStatement("SELECT * FROM TESTTABLE", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery();
rs.last();
count = rs.getRow();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e); // NOSONAR
}
finally {
safeClose(rs);
safeClose(stmt);
}
return count;
}
public void insertRow(String name, int value) throws SQLException {
PreparedStatement stmt = null;
Connection con2 = null;
try {
// Need to create a new connection to participate in transaction
con2 = connect();
stmt = con2.prepareStatement("INSERT INTO TESTTABLE VALUES (?, ?)");
stmt.setString(1, name);
stmt.setInt(2, value);
stmt.executeUpdate();
}
finally {
safeClose(stmt);
safeClose(con2);
}
}
public void close() {
safeClose(conn);
}
private static void safeClose(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
}
private static void safeClose(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
}
private static void safeClose(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
}
}
| 7,673 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/SupportsTestBeanImpl.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.aries.transaction.test.impl;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import java.sql.SQLException;
public class SupportsTestBeanImpl extends TestBeanImpl {
@Override
@Transactional(value=TxType.SUPPORTS)
public void insertRow(String name, int value, Exception e) throws SQLException {
super.insertRow(name, value, e);
}
@Override
@Transactional(value=TxType.SUPPORTS)
public void delegateInsertRow(String name, int value) throws SQLException {
super.delegateInsertRow(name, value);
}
}
| 7,674 |
0 | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test | Create_ds/aries/transaction/transaction-testbundle/src/main/java/org/apache/aries/transaction/test/impl/MandatoryTestBeanImpl.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.aries.transaction.test.impl;
import javax.transaction.Transactional;
import java.sql.SQLException;
public class MandatoryTestBeanImpl extends TestBeanImpl {
@Override
@Transactional(Transactional.TxType.MANDATORY)
public void insertRow(String name, int value, Exception e) throws SQLException {
super.insertRow(name, value, e);
}
@Override
@Transactional(Transactional.TxType.MANDATORY)
public void delegateInsertRow(String name, int value) throws SQLException {
super.delegateInsertRow(name, value);
}
}
| 7,675 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/RecoverableDataSource.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.aries.transaction.jdbc;
import org.apache.aries.transaction.AriesTransactionManager;
import org.apache.aries.transaction.jdbc.internal.AbstractMCFFactory;
import org.apache.aries.transaction.jdbc.internal.ConnectionManagerFactory;
import org.apache.aries.transaction.jdbc.internal.DataSourceMCFFactory;
import org.apache.aries.transaction.jdbc.internal.Recovery;
import org.apache.aries.transaction.jdbc.internal.XADataSourceMCFFactory;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import javax.sql.CommonDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
/**
* Defines a JDBC DataSource that will auto-enlist into existing XA transactions.
* The DataSource will also be registered with the Aries/Geronimo transaction
* manager in order to provide proper transaction recovery at startup.
* Other considerations such as connection pooling and error handling are
* completely ignored.
*
* @org.apache.xbean.XBean
*/
public class RecoverableDataSource implements DataSource, RecoverableDataSourceMBean {
private CommonDataSource dataSource;
private AriesTransactionManager transactionManager;
private String name;
private String exceptionSorter = "all";
private String username = "";
private String password = "";
private boolean allConnectionsEquals = true;
private int connectionMaxIdleMinutes = 15;
private int connectionMaxWaitMilliseconds = 5000;
private String partitionStrategy = "none";
private boolean pooling = true;
private int poolMaxSize = 10;
private int poolMinSize = 0;
private String transaction;
private boolean validateOnMatch = true;
private boolean backgroundValidation = false;
private int backgroundValidationMilliseconds = 600000;
private ConnectionManagerFactory cm;
private DataSource delegate;
/**
* The unique name for this managed XAResource. This name will be used
* by the transaction manager to recover transactions.
*/
public void setName(String name) {
this.name = name;
}
/**
* The CommonDataSource to wrap.
*
* @org.apache.xbean.Property required=true
*/
public void setDataSource(CommonDataSource dataSource) {
this.dataSource = dataSource;
}
/**
* The XA TransactionManager to use to enlist the JDBC connections into.
*
* @org.apache.xbean.Property required=true
*/
public void setTransactionManager(AriesTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* Specify which SQL exceptions are fatal.
* Can be all, none, known or custom(xx,yy...).
*/
public void setExceptionSorter(String exceptionSorter) {
this.exceptionSorter = exceptionSorter;
}
/**
* The user name used to establish the connection.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* The password credential used to establish the connection.
*/
public void setPassword(String password) {
this.password = password;
}
public void setAllConnectionsEquals(boolean allConnectionsEquals) {
this.allConnectionsEquals = allConnectionsEquals;
}
public void setConnectionMaxIdleMinutes(int connectionMaxIdleMinutes) {
this.connectionMaxIdleMinutes = connectionMaxIdleMinutes;
}
public void setConnectionMaxWaitMilliseconds(int connectionMaxWaitMilliseconds) {
this.connectionMaxWaitMilliseconds = connectionMaxWaitMilliseconds;
}
/**
* Pool partition strategy.
* Can be none, by-connector-properties or by-subject (defaults to none).
*/
public void setPartitionStrategy(String partitionStrategy) {
this.partitionStrategy = partitionStrategy;
}
/**
* If pooling is enabled (defaults to true).
* @param pooling
*/
public void setPooling(boolean pooling) {
this.pooling = pooling;
}
/**
* Maximum pool size (defaults to 10).
*/
public void setPoolMaxSize(int poolMaxSize) {
this.poolMaxSize = poolMaxSize;
}
/**
* Minimum pool size (defaults to 0).
*/
public void setPoolMinSize(int poolMinSize) {
this.poolMinSize = poolMinSize;
}
/**
* If validation on connection matching is enabled (defaults to true).
* @param validateOnMatch
*/
public void setValidateOnMatch(boolean validateOnMatch) {
this.validateOnMatch = validateOnMatch;
}
/**
* If periodically background validation is enabled (defaults to false).
* @param backgroundValidation
*/
public void setBackgroundValidation(boolean backgroundValidation) {
this.backgroundValidation = backgroundValidation;
}
/**
* Background validation period (defaults to 600000)
* @param backgroundValidationMilliseconds
*/
public void setBackgroundValidationMilliseconds(int backgroundValidationMilliseconds) {
this.backgroundValidationMilliseconds = backgroundValidationMilliseconds;
}
/**
* Transaction support.
* Can be none, local or xa (defaults to xa).
*/
public void setTransaction(String transaction) {
this.transaction = transaction;
}
/**
* @org.apache.xbean.InitMethod
*/
public void start() throws Exception {
AbstractMCFFactory mcf;
if (("xa".equals(transaction) || "local".equals(transaction)) && transactionManager == null) {
throw new IllegalArgumentException("xa or local transactions specified, but no TransactionManager set");
}
if ("xa".equals(transaction) && !(dataSource instanceof XADataSource)) {
throw new IllegalArgumentException("xa transactions specified, but DataSource does not implement javax.sql.XADataSource");
}
if ("xa".equals(transaction) || (transactionManager != null && dataSource instanceof XADataSource)) {
mcf = new XADataSourceMCFFactory();
if (transaction == null) {
transaction = "xa";
}
} else if (dataSource instanceof DataSource) {
mcf = new DataSourceMCFFactory();
if (transaction == null) {
transaction = transactionManager != null ? "local" : "none";
}
} else {
throw new IllegalArgumentException("dataSource must be of type javax.sql.DataSource/XADataSource");
}
mcf.setDataSource(dataSource);
mcf.setExceptionSorterAsString(exceptionSorter);
mcf.setUserName(username);
mcf.setPassword(password);
mcf.init();
cm = new ConnectionManagerFactory();
cm.setManagedConnectionFactory(mcf.getConnectionFactory());
cm.setTransactionManager(transactionManager);
cm.setAllConnectionsEqual(allConnectionsEquals);
cm.setConnectionMaxIdleMinutes(connectionMaxIdleMinutes);
cm.setConnectionMaxWaitMilliseconds(connectionMaxWaitMilliseconds);
cm.setPartitionStrategy(partitionStrategy);
cm.setPooling(pooling);
cm.setPoolMaxSize(poolMaxSize);
cm.setPoolMinSize(poolMinSize);
cm.setValidateOnMatch(validateOnMatch);
cm.setBackgroundValidation(backgroundValidation);
cm.setBackgroundValidationMilliseconds(backgroundValidationMilliseconds);
cm.setTransaction(transaction);
cm.setName(name);
cm.init();
delegate = (DataSource) cm.getManagedConnectionFactory().createConnectionFactory(cm.getConnectionManager());
if (dataSource instanceof XADataSource) {
Recovery.recover(name, (XADataSource) dataSource, transactionManager);
}
}
/**
* @org.apache.xbean.DestroyMethod
*/
public void stop() throws Exception {
if (cm != null) {
cm.destroy();
}
}
//---------------------------
// MBean implementation
//---------------------------
public String getName() {
return name;
}
public String getExceptionSorter() {
return exceptionSorter;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public boolean isAllConnectionsEquals() {
return allConnectionsEquals;
}
public int getConnectionMaxIdleMinutes() {
return connectionMaxIdleMinutes;
}
public int getConnectionMaxWaitMilliseconds() {
return connectionMaxWaitMilliseconds;
}
public String getPartitionStrategy() {
return partitionStrategy;
}
public boolean isPooling() {
return pooling;
}
public int getPoolMaxSize() {
return poolMaxSize;
}
public int getPoolMinSize() {
return poolMinSize;
}
public boolean isValidateOnMatch() {
return validateOnMatch;
}
public boolean isBackgroundValidation() {
return backgroundValidation;
}
public int getBackgroundValidationMilliseconds() {
return backgroundValidationMilliseconds;
}
public String getTransaction() {
return transaction;
}
public int getConnectionCount() {
return cm.getPoolingSupport().getConnectionCount();
}
public int getIdleConnectionCount() {
return cm.getPoolingSupport().getIdleConnectionCount();
}
//---------------------------
// DataSource implementation
//---------------------------
public Connection getConnection() throws SQLException {
return delegate.getConnection();
}
public Connection getConnection(String username, String password) throws SQLException {
return delegate.getConnection(username, password);
}
public PrintWriter getLogWriter() throws SQLException {
return delegate.getLogWriter();
}
/**
* @org.apache.xbean.Property hidden=true
*/
public void setLogWriter(PrintWriter out) throws SQLException {
delegate.setLogWriter(out);
}
/**
* @org.apache.xbean.Property hidden=true
*/
public void setLoginTimeout(int seconds) throws SQLException {
delegate.setLoginTimeout(seconds);
}
public int getLoginTimeout() throws SQLException {
return delegate.getLoginTimeout();
}
@IgnoreJRERequirement
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
| 7,676 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/RecoverableDataSourceMBean.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.aries.transaction.jdbc;
public interface RecoverableDataSourceMBean {
String getName();
String getExceptionSorter();
String getUsername();
String getPassword();
boolean isAllConnectionsEquals();
int getConnectionMaxIdleMinutes();
int getConnectionMaxWaitMilliseconds();
String getPartitionStrategy();
boolean isPooling();
int getPoolMaxSize();
int getPoolMinSize();
boolean isValidateOnMatch();
boolean isBackgroundValidation();
int getBackgroundValidationMilliseconds();
String getTransaction();
int getConnectionCount();
int getIdleConnectionCount();
}
| 7,677 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/ManagedDataSourceFactory.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.aries.transaction.jdbc.internal;
import org.apache.aries.transaction.AriesTransactionManager;
import org.apache.aries.transaction.jdbc.RecoverableDataSource;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import javax.sql.CommonDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import java.util.Hashtable;
import java.util.Map;
@SuppressWarnings({"rawtypes", "unchecked"})
public class ManagedDataSourceFactory {
private final ServiceReference reference;
private final AriesTransactionManager transactionManager;
private final CommonDataSource dataSource;
private final Map<String, Object> properties;
private ServiceRegistration<DataSource> registration;
private RecoverableDataSource ds;
public ManagedDataSourceFactory(ServiceReference reference,
AriesTransactionManager transactionManager) {
this.reference = reference;
this.transactionManager = transactionManager;
this.properties = new Hashtable<String, Object>();
for (String key : reference.getPropertyKeys()) {
this.properties.put(key, reference.getProperty(key));
}
this.dataSource = (CommonDataSource) reference.getBundle().getBundleContext().getService(reference);
}
public AriesTransactionManager getTransactionManager() {
return transactionManager;
}
public CommonDataSource getDataSource() {
return dataSource;
}
public String getResourceName() {
return getString("aries.xa.name", null);
}
private String getString(String name, String def) {
Object v = properties.get(name);
if (v instanceof String) {
return (String) v;
} else {
return def;
}
}
private int getInt(String name, int def) {
Object v = properties.get(name);
if (v instanceof Integer) {
return (Integer) v;
} else if (v instanceof String) {
return Integer.parseInt((String) v);
} else {
return def;
}
}
private boolean getBool(String name, boolean def) {
Object v = properties.get(name);
if (v instanceof Boolean) {
return (Boolean) v;
} else if (v instanceof String) {
return Boolean.parseBoolean((String) v);
} else {
return def;
}
}
public void register() throws Exception {
boolean isXaDataSource = (dataSource instanceof XADataSource);
Hashtable<String, Object> props = new Hashtable<String, Object>(this.properties);
props.put("aries.managed", "true");
if (isXaDataSource) {
props.put("aries.xa.aware", "true");
}
props.put("jmx.objectname", "org.apache.aries.transaction:type=jdbc,name=" + getResourceName());
props.put(Constants.SERVICE_RANKING, getInt(Constants.SERVICE_RANKING, 0) + 1000);
ds = new RecoverableDataSource();
ds.setDataSource(dataSource);
ds.setExceptionSorter(getString("aries.xa.exceptionSorter", "all"));
ds.setUsername(getString("aries.xa.username", null));
ds.setPassword(getString("aries.xa.password", null));
ds.setTransactionManager(transactionManager);
ds.setAllConnectionsEquals(getBool("aries.xa.allConnectionsEquals", true));
ds.setConnectionMaxIdleMinutes(getInt("aries.xa.connectionMadIdleMinutes", 15));
ds.setConnectionMaxWaitMilliseconds(getInt("aries.xa.connectionMaxWaitMilliseconds", 5000));
ds.setPartitionStrategy(getString("aries.xa.partitionStrategy", null));
ds.setPooling(getBool("aries.xa.pooling", true));
ds.setPoolMaxSize(getInt("aries.xa.poolMaxSize", 10));
ds.setPoolMinSize(getInt("aries.xa.poolMinSize", 0));
ds.setValidateOnMatch(getBool("aries.xa.validateOnMatch", true));
ds.setBackgroundValidation(getBool("aries.xa.backgroundValidation", false));
ds.setBackgroundValidationMilliseconds(getInt("aries.xa.backgroundValidationMilliseconds", 600000));
ds.setTransaction(getString("aries.xa.transaction", isXaDataSource ? "xa" : "local"));
ds.setName(getResourceName());
ds.start();
BundleContext context = reference.getBundle().getBundleContext();
registration = context.registerService(DataSource.class, ds, props);
}
public void unregister() throws Exception {
if (registration != null) {
registration.unregister();
registration = null;
}
if (ds != null) {
ds.stop();
}
}
}
| 7,678 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/Recovery.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.aries.transaction.jdbc.internal;
import org.apache.geronimo.transaction.manager.NamedXAResource;
import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.SystemException;
import javax.transaction.xa.XAResource;
import java.io.IOException;
/**
* This class will ensure the broker is properly recovered when wired with
* the Geronimo transaction manager.
*/
public class Recovery {
private static final Logger LOGGER = LoggerFactory.getLogger(Recovery.class);
public static boolean recover(final String name,
final XADataSource dataSource,
final RecoverableTransactionManager transactionManager) throws IOException {
if (name != null && name.length() > 0) {
transactionManager.registerNamedXAResourceFactory(new NamedXAResourceFactory() {
public String getName() {
return name;
}
public NamedXAResource getNamedXAResource() throws SystemException {
try {
final XAConnection connection = dataSource.getXAConnection();
LOGGER.debug("new namedXAResource's connection: " + connection);
return new ConnectionAndWrapperNamedXAResource(connection.getXAResource(), getName(), connection);
} catch (Exception e) {
SystemException se = new SystemException("Failed to create ConnectionAndWrapperNamedXAResource, " + e.getLocalizedMessage());
se.initCause(e);
LOGGER.error(se.getLocalizedMessage(), se);
throw se;
}
}
public void returnNamedXAResource(NamedXAResource namedXaResource) {
if (namedXaResource instanceof ConnectionAndWrapperNamedXAResource) {
try {
LOGGER.debug("closing returned namedXAResource's connection: " + ((ConnectionAndWrapperNamedXAResource)namedXaResource).connection);
((ConnectionAndWrapperNamedXAResource)namedXaResource).connection.close();
} catch (Exception ignored) {
LOGGER.debug("failed to close returned namedXAResource: " + namedXaResource, ignored);
}
}
}
});
return true;
} else {
LOGGER.warn("Unable to recover XADataSource: aries.xa.name property not set");
return false;
}
}
public static class ConnectionAndWrapperNamedXAResource extends WrapperNamedXAResource {
final XAConnection connection;
public ConnectionAndWrapperNamedXAResource(XAResource xaResource, String name, XAConnection connection) {
super(xaResource, name);
this.connection = connection;
}
}
}
| 7,679 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/XADataSourceMCFFactory.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.aries.transaction.jdbc.internal;
import java.sql.SQLException;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ResourceAdapterInternalException;
import javax.resource.spi.TransactionSupport;
import javax.security.auth.Subject;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import org.tranql.connector.CredentialExtractor;
import org.tranql.connector.jdbc.AbstractXADataSourceMCF;
import org.tranql.connector.jdbc.ManagedXAConnection;
public class XADataSourceMCFFactory extends AbstractMCFFactory {
public void init() throws Exception {
if (getDataSource() == null) {
throw new IllegalArgumentException("dataSource must be set");
}
if (connectionFactory == null) {
connectionFactory = new XADataSourceMCF();
}
}
@SuppressWarnings("serial")
public class XADataSourceMCF extends AbstractXADataSourceMCF<XADataSource> implements TransactionSupport {
public XADataSourceMCF() {
super((XADataSource) XADataSourceMCFFactory.this.getDataSource(), XADataSourceMCFFactory.this.getExceptionSorter());
}
public String getUserName() {
return XADataSourceMCFFactory.this.getUserName();
}
@Override
public String getPassword() {
return XADataSourceMCFFactory.this.getPassword();
}
@Override
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo connectionRequestInfo) throws ResourceException {
CredentialExtractor credentialExtractor = new CredentialExtractor(subject, connectionRequestInfo, this);
XAConnection sqlConnection = getPhysicalConnection(credentialExtractor);
try {
return new ManagedXAConnection(this, sqlConnection, credentialExtractor, exceptionSorter) {
@Override
public void cleanup() throws ResourceException {
// ARIES-1279 - Transaction does not work on error SQLException
// that's why we don't call super.cleanup() which calls con.setAutocommit(true)
// super.cleanup();
dissociateConnections();
}
};
} catch (SQLException e) {
throw new ResourceAdapterInternalException("Could not set up ManagedXAConnection", e);
}
}
@Override
protected XAConnection getPhysicalConnection(CredentialExtractor credentialExtractor) throws ResourceException {
try {
String userName = credentialExtractor.getUserName();
String password = credentialExtractor.getPassword();
if (userName != null) {
return xaDataSource.getXAConnection(userName, password);
} else {
return xaDataSource.getXAConnection();
}
} catch (SQLException e) {
throw new ResourceAdapterInternalException("Unable to obtain physical connection to " + xaDataSource, e);
}
}
@Override
public TransactionSupportLevel getTransactionSupport() {
return TransactionSupportLevel.XATransaction;
}
}
}
| 7,680 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/Reflections.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.aries.transaction.jdbc.internal;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
public final class Reflections {
private Reflections() {
// no-op
}
public static Object get(final Object instance, String field) {
Class<?> clazz = instance.getClass();
while (clazz != null) {
try {
final Field f = clazz.getDeclaredField(field);
final boolean acc = f.isAccessible();
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
f.setAccessible(true);
try {
return f.get(instance);
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException(ex);
} finally {
f.setAccessible(acc);
}
}
});
} catch (NoSuchFieldException nsfe) {
// no-op
}
clazz = clazz.getSuperclass();
}
throw new RuntimeException(new NoSuchFieldException(field));
}
}
| 7,681 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/Activator.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.aries.transaction.jdbc.internal;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.transaction.AriesTransactionManager;
import org.apache.aries.util.tracker.SingleServiceTracker;
import org.apache.xbean.blueprint.context.impl.XBeanNamespaceHandler;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.CommonDataSource;
import java.util.Hashtable;
@SuppressWarnings("rawtypes")
public class Activator implements BundleActivator,
ServiceTrackerCustomizer<CommonDataSource, ManagedDataSourceFactory>,
SingleServiceTracker.SingleServiceListener
{
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class);
private ServiceTracker<CommonDataSource, ManagedDataSourceFactory> t;
private SingleServiceTracker<AriesTransactionManager> tm;
private BundleContext context;
private ServiceRegistration[] nshReg;
public void start(BundleContext ctx) {
context = ctx;
// Expose blueprint namespace handler if xbean is present
try {
nshReg = JdbcNamespaceHandler.register(ctx);
} catch (NoClassDefFoundError e) {
LOGGER.warn("Unable to register JDBC blueprint namespace handler (xbean-blueprint not available).");
} catch (Exception e) {
LOGGER.error("Unable to register JDBC blueprint namespace handler", e);
}
Filter filter;
String flt = "(&(|(objectClass=javax.sql.XADataSource)(objectClass=javax.sql.DataSource))(!(aries.managed=true)))";
try {
filter = context.createFilter(flt);
} catch (InvalidSyntaxException e) {
throw new IllegalStateException(e);
}
t = new ServiceTracker<CommonDataSource, ManagedDataSourceFactory>(ctx, filter, this);
tm = new SingleServiceTracker<AriesTransactionManager>(ctx, AriesTransactionManager.class, this);
tm.open();
}
public void stop(BundleContext ctx) {
tm.close();
t.close();
if (nshReg != null) {
for (ServiceRegistration reg : nshReg) {
safeUnregisterService(reg);
}
}
}
public ManagedDataSourceFactory addingService(ServiceReference<CommonDataSource> ref) {
try {
LOGGER.info("Wrapping DataSource " + ref);
ManagedDataSourceFactory mdsf = new ManagedDataSourceFactory(ref, tm.getService());
mdsf.register();
return mdsf;
} catch (Exception e) {
LOGGER.warn("Error wrapping DataSource " + ref, e);
return null;
}
}
public void modifiedService(ServiceReference<CommonDataSource> ref, ManagedDataSourceFactory service) {
try {
service.unregister();
} catch (Exception e) {
LOGGER.warn("Error closing DataSource " + ref, e);
}
try {
service.register();
} catch (Exception e) {
LOGGER.warn("Error wrapping DataSource " + ref, e);
}
}
public void removedService(ServiceReference<CommonDataSource> ref, ManagedDataSourceFactory service) {
try {
service.unregister();
} catch (Exception e) {
LOGGER.warn("Error closing DataSource " + ref, e);
}
}
static void safeUnregisterService(ServiceRegistration reg) {
if (reg != null) {
try {
reg.unregister();
} catch (IllegalStateException e) {
//This can be safely ignored
}
}
}
@Override
public void serviceFound()
{
t.open();
}
@Override
public void serviceLost()
{
t.close();
}
@Override
public void serviceReplaced()
{
t.close();
t.open();
}
static class JdbcNamespaceHandler {
public static ServiceRegistration[] register(BundleContext context) throws Exception {
XBeanNamespaceHandler nsh20 = new XBeanNamespaceHandler(
"http://aries.apache.org/xmlns/transaction-jdbc/2.0",
"org.apache.aries.transaction.jdbc-2.0.xsd",
context.getBundle(),
"META-INF/services/org/apache/xbean/spring/http/aries.apache.org/xmlns/transaction-jdbc/2.0"
);
Hashtable<String, Object> props20 = new Hashtable<String, Object>();
props20.put("osgi.service.blueprint.namespace", "http://aries.apache.org/xmlns/transaction-jdbc/2.0");
ServiceRegistration reg20 = context.registerService(NamespaceHandler.class.getName(), nsh20, props20);
XBeanNamespaceHandler nsh21 = new XBeanNamespaceHandler(
"http://aries.apache.org/xmlns/transaction-jdbc/2.1",
"org.apache.aries.transaction.jdbc.xsd",
context.getBundle(),
"META-INF/services/org/apache/xbean/spring/http/aries.apache.org/xmlns/transaction-jdbc/2.1"
);
Hashtable<String, Object> props21 = new Hashtable<String, Object>();
props21.put("osgi.service.blueprint.namespace", "http://aries.apache.org/xmlns/transaction-jdbc/2.1");
ServiceRegistration reg21 = context.registerService(NamespaceHandler.class.getName(), nsh21, props21);
return new ServiceRegistration[] { reg20, reg21 };
}
}
}
| 7,682 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/AbstractMCFFactory.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.aries.transaction.jdbc.internal;
import java.util.ArrayList;
import java.util.List;
import javax.resource.spi.ManagedConnectionFactory;
import javax.sql.CommonDataSource;
import org.tranql.connector.AllExceptionsAreFatalSorter;
import org.tranql.connector.ExceptionSorter;
import org.tranql.connector.NoExceptionsAreFatalSorter;
import org.tranql.connector.jdbc.ConfigurableSQLStateExceptionSorter;
import org.tranql.connector.jdbc.KnownSQLStateExceptionSorter;
public abstract class AbstractMCFFactory {
private CommonDataSource dataSource;
private ExceptionSorter exceptionSorter = new AllExceptionsAreFatalSorter();
private String userName;
private String password;
ManagedConnectionFactory connectionFactory;
public ManagedConnectionFactory getConnectionFactory() {
return connectionFactory;
}
public abstract void init() throws Exception;
public void setExceptionSorterAsString(String sorter) {
if ("all".equalsIgnoreCase(sorter)) {
this.exceptionSorter = new AllExceptionsAreFatalSorter();
} else if ("none".equalsIgnoreCase(sorter)) {
this.exceptionSorter = new NoExceptionsAreFatalSorter();
} else if ("known".equalsIgnoreCase(sorter)) {
this.exceptionSorter = new KnownSQLStateExceptionSorter();
} else if (sorter.toLowerCase().startsWith("custom(") && sorter.endsWith(")")) {
List<String> states = new ArrayList<String>();
for (String s : sorter.substring(7, sorter.length() - 2).split(",")) {
if (s != null && s.length() > 0) {
states.add(s);
}
}
this.exceptionSorter = new ConfigurableSQLStateExceptionSorter(states);
} else {
throw new IllegalArgumentException("Unknown exceptionSorter " + sorter);
}
}
public CommonDataSource getDataSource() {
return dataSource;
}
public void setDataSource(CommonDataSource dataSource) {
this.dataSource = dataSource;
}
public ExceptionSorter getExceptionSorter() {
return exceptionSorter;
}
public void setExceptionSorter(ExceptionSorter exceptionSorter) {
this.exceptionSorter = exceptionSorter;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 7,683 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/ConnectionManagerFactory.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.aries.transaction.jdbc.internal;
import org.apache.aries.transaction.AriesTransactionManager;
import org.apache.geronimo.connector.outbound.GenericConnectionManager;
import org.apache.geronimo.connector.outbound.SubjectSource;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.LocalTransactions;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.NoPool;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.NoTransactions;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PartitionedPool;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.SinglePool;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.TransactionSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.XATransactions;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTrackingCoordinator;
import org.apache.geronimo.connector.outbound.connectiontracking.GeronimoTransactionListener;
import org.apache.geronimo.transaction.manager.TransactionManagerMonitor;
import org.tranql.connector.UserPasswordManagedConnectionFactory;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ManagedConnectionFactory;
public class ConnectionManagerFactory {
private AriesTransactionManager transactionManager;
private ManagedConnectionFactory managedConnectionFactory;
private String name;
private TransactionSupport transactionSupport;
private String transaction;
private PoolingSupport poolingSupport;
private boolean pooling = true;
private String partitionStrategy; //: none, by-subject, by-connector-properties
private int poolMaxSize = 10;
private int poolMinSize = 0;
private boolean allConnectionsEqual = true;
private int connectionMaxWaitMilliseconds = 5000;
private int connectionMaxIdleMinutes = 15;
private boolean validateOnMatch = true;
private boolean backgroundValidation = false;
private int backgroundValidationMilliseconds = 600000;
private SubjectSource subjectSource;
private ConnectionTrackingCoordinator connectionTracker;
private TransactionManagerMonitor transactionManagerMonitor;
private GenericConnectionManager connectionManager;
public ConnectionManager getConnectionManager() {
return connectionManager;
}
public void init() throws Exception {
if (transactionManager == null && ("xa".equals(transaction) || "local".equals(transaction))) {
throw new IllegalArgumentException("transactionManager must be set");
}
if (managedConnectionFactory == null) {
throw new IllegalArgumentException("managedConnectionFactory must be set");
}
if (validateOnMatch || backgroundValidation) {
// Validation requires per-connection matching, see #ARIES-1790
allConnectionsEqual = false;
}
// Apply the default value for property if necessary
if (transactionSupport == null) {
// No transaction
if ("local".equalsIgnoreCase(transaction)) {
transactionSupport = LocalTransactions.INSTANCE;
} else if ("none".equalsIgnoreCase(transaction)) {
transactionSupport = NoTransactions.INSTANCE;
} else if ("xa".equalsIgnoreCase(transaction)) {
transactionSupport = new XATransactions(true, false);
} else {
throw new IllegalArgumentException("Unknown transaction type " + transaction + " (must be local, none or xa)");
}
}
if (poolingSupport == null) {
// No pool
if (!pooling) {
poolingSupport = new NoPool();
} else {
if (partitionStrategy == null || "none".equalsIgnoreCase(partitionStrategy)) {
// unpartitioned pool
poolingSupport = new SinglePool(poolMaxSize,
poolMinSize,
connectionMaxWaitMilliseconds,
connectionMaxIdleMinutes,
allConnectionsEqual,
!allConnectionsEqual,
false);
} else if ("by-connector-properties".equalsIgnoreCase(partitionStrategy)) {
// partition by connector properties such as username and password on a jdbc connection
poolingSupport = new PartitionedPool(poolMaxSize,
poolMinSize,
connectionMaxWaitMilliseconds,
connectionMaxIdleMinutes,
allConnectionsEqual,
!allConnectionsEqual,
false,
true,
false);
} else if ("by-subject".equalsIgnoreCase(partitionStrategy)) {
// partition by caller subject
poolingSupport = new PartitionedPool(poolMaxSize,
poolMinSize,
connectionMaxWaitMilliseconds,
connectionMaxIdleMinutes,
allConnectionsEqual,
!allConnectionsEqual,
false,
false,
true);
} else {
throw new IllegalArgumentException("Unknown partition strategy " + partitionStrategy + " (must be none, by-connector-properties or by-subject)");
}
}
}
if (connectionTracker == null) {
connectionTracker = new ConnectionTrackingCoordinator();
}
if (transactionManagerMonitor == null && transactionManager != null) {
transactionManagerMonitor = new GeronimoTransactionListener(connectionTracker);
transactionManager.addTransactionAssociationListener(transactionManagerMonitor);
}
if (connectionManager == null) {
if (validateOnMatch || backgroundValidation) {
// Wrap the original ManagedConnectionFactory to add validation capability
managedConnectionFactory = new ValidatingDelegatingManagedConnectionFactory((UserPasswordManagedConnectionFactory) managedConnectionFactory);
}
if (backgroundValidation) {
// Instantiate the Validating Connection Manager
connectionManager = new ValidatingGenericConnectionManager(
transactionSupport,
poolingSupport,
subjectSource,
connectionTracker,
transactionManager,
managedConnectionFactory,
name != null ? name : getClass().getName(),
getClass().getClassLoader(),
backgroundValidationMilliseconds);
} else {
// Instantiate the Geronimo Connection Manager
connectionManager = new GenericConnectionManager(
transactionSupport,
poolingSupport,
subjectSource,
connectionTracker,
transactionManager,
managedConnectionFactory,
name != null ? name : getClass().getName(),
getClass().getClassLoader());
}
connectionManager.doStart();
}
}
public void destroy() throws Exception {
if (connectionManager != null) {
connectionManager.doStop();
connectionManager = null;
}
if (transactionManagerMonitor != null && transactionManager != null) {
transactionManager.removeTransactionAssociationListener(transactionManagerMonitor);
}
}
public AriesTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(AriesTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public ManagedConnectionFactory getManagedConnectionFactory() {
return managedConnectionFactory;
}
public void setManagedConnectionFactory(ManagedConnectionFactory managedConnectionFactory) {
this.managedConnectionFactory = managedConnectionFactory;
}
public TransactionSupport getTransactionSupport() {
return transactionSupport;
}
public void setTransactionSupport(TransactionSupport transactionSupport) {
this.transactionSupport = transactionSupport;
}
public String getTransaction() {
return transaction;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setTransaction(String transaction) {
this.transaction = transaction;
}
public PoolingSupport getPoolingSupport() {
return poolingSupport;
}
public void setPoolingSupport(PoolingSupport poolingSupport) {
this.poolingSupport = poolingSupport;
}
public boolean isPooling() {
return pooling;
}
public void setPooling(boolean pooling) {
this.pooling = pooling;
}
public String getPartitionStrategy() {
return partitionStrategy;
}
public void setPartitionStrategy(String partitionStrategy) {
this.partitionStrategy = partitionStrategy;
}
public int getPoolMaxSize() {
return poolMaxSize;
}
public void setPoolMaxSize(int poolMaxSize) {
this.poolMaxSize = poolMaxSize;
}
public int getPoolMinSize() {
return poolMinSize;
}
public void setPoolMinSize(int poolMinSize) {
this.poolMinSize = poolMinSize;
}
public boolean isAllConnectionsEqual() {
return allConnectionsEqual;
}
public void setAllConnectionsEqual(boolean allConnectionsEqual) {
this.allConnectionsEqual = allConnectionsEqual;
}
public int getConnectionMaxWaitMilliseconds() {
return connectionMaxWaitMilliseconds;
}
public void setConnectionMaxWaitMilliseconds(int connectionMaxWaitMilliseconds) {
this.connectionMaxWaitMilliseconds = connectionMaxWaitMilliseconds;
}
public int getConnectionMaxIdleMinutes() {
return connectionMaxIdleMinutes;
}
public void setConnectionMaxIdleMinutes(int connectionMaxIdleMinutes) {
this.connectionMaxIdleMinutes = connectionMaxIdleMinutes;
}
public boolean isValidateOnMatch() {
return validateOnMatch;
}
public void setValidateOnMatch(boolean validateOnMatch) {
this.validateOnMatch = validateOnMatch;
}
public boolean isBackgroundValidation() {
return backgroundValidation;
}
public void setBackgroundValidation(boolean backgroundValidation) {
this.backgroundValidation = backgroundValidation;
}
public int getBackgroundValidationMilliseconds() {
return backgroundValidationMilliseconds;
}
public void setBackgroundValidationMilliseconds(int backgroundValidationMilliseconds) {
this.backgroundValidationMilliseconds = backgroundValidationMilliseconds;
}
public SubjectSource getSubjectSource() {
return subjectSource;
}
public void setSubjectSource(SubjectSource subjectSource) {
this.subjectSource = subjectSource;
}
}
| 7,684 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/DataSourceMCFFactory.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.aries.transaction.jdbc.internal;
import org.tranql.connector.CredentialExtractor;
import org.tranql.connector.jdbc.AbstractLocalDataSourceMCF;
import javax.resource.ResourceException;
import javax.resource.spi.ResourceAdapterInternalException;
import javax.resource.spi.TransactionSupport;
import javax.security.auth.Subject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DataSourceMCFFactory extends AbstractMCFFactory {
@Override
public void init() throws Exception {
if (getDataSource() == null) {
throw new IllegalArgumentException("dataSource must be set");
}
if (connectionFactory == null) {
connectionFactory = new DataSourceMCF();
}
}
@SuppressWarnings("serial")
public class DataSourceMCF extends AbstractLocalDataSourceMCF<DataSource> implements TransactionSupport {
public DataSourceMCF() {
super((DataSource) DataSourceMCFFactory.this.getDataSource(), DataSourceMCFFactory.this.getExceptionSorter(), true);
}
public String getUserName() {
return DataSourceMCFFactory.this.getUserName();
}
public String getPassword() {
return DataSourceMCFFactory.this.getPassword();
}
@Override
protected Connection getPhysicalConnection(Subject subject, CredentialExtractor credentialExtractor) throws ResourceException {
try {
String userName = credentialExtractor.getUserName();
String password = credentialExtractor.getPassword();
if (userName != null) {
return dataSource.getConnection(userName, password);
} else {
return dataSource.getConnection();
}
} catch (SQLException e) {
throw new ResourceAdapterInternalException("Unable to obtain physical connection to " + dataSource, e);
}
}
@Override
public TransactionSupportLevel getTransactionSupport() {
return TransactionSupportLevel.LocalTransaction;
}
}
}
| 7,685 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/ValidatingGenericConnectionManager.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.aries.transaction.jdbc.internal;
import org.apache.geronimo.connector.outbound.AbstractSinglePoolConnectionInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionReturnAction;
import org.apache.geronimo.connector.outbound.GenericConnectionManager;
import org.apache.geronimo.connector.outbound.ManagedConnectionInfo;
import org.apache.geronimo.connector.outbound.MultiPoolConnectionInterceptor;
import org.apache.geronimo.connector.outbound.SinglePoolConnectionInterceptor;
import org.apache.geronimo.connector.outbound.SinglePoolMatchAllConnectionInterceptor;
import org.apache.geronimo.connector.outbound.SubjectSource;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.TransactionSupport;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTracker;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import javax.resource.ResourceException;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.ValidatingManagedConnectionFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.ReadWriteLock;
@SuppressWarnings({
"unchecked", "serial"
})
public final class ValidatingGenericConnectionManager extends GenericConnectionManager {
private static final Timer TIMER = new Timer("ValidatingGenericConnectionManagerTimer", true);
private transient final TimerTask validatingTask;
private final long validatingInterval;
private final ReadWriteLock lock;
private final Object pool;
public ValidatingGenericConnectionManager(TransactionSupport transactionSupport, PoolingSupport pooling, SubjectSource subjectSource, ConnectionTracker connectionTracker, RecoverableTransactionManager transactionManager, ManagedConnectionFactory mcf, String name, ClassLoader classLoader, long interval) {
super(transactionSupport, pooling, subjectSource, connectionTracker, transactionManager, mcf, name, classLoader);
validatingInterval = interval;
ConnectionInterceptor stack = interceptors.getStack();
ReadWriteLock foundLock = null;
ConnectionInterceptor current = stack;
do {
if (current instanceof AbstractSinglePoolConnectionInterceptor) {
try {
foundLock = (ReadWriteLock) Reflections.get(current, "resizeLock");
} catch (Exception e) {
// no-op
}
break;
}
// look next
try {
current = (ConnectionInterceptor) Reflections.get(current, "next");
} catch (Exception e) {
current = null;
}
} while (current != null);
this.lock = foundLock;
Object foundPool = null;
if (current instanceof AbstractSinglePoolConnectionInterceptor) {
foundPool = Reflections.get(current, "pool");
} else if (current instanceof MultiPoolConnectionInterceptor) {
log.warn("validation on stack {} not supported", stack);
}
this.pool = foundPool;
if (pool != null) {
validatingTask = new ValidatingTask(current, lock, pool);
} else {
validatingTask = null;
}
}
@Override
public void doStart() throws Exception {
super.doStart();
if (validatingTask != null) {
TIMER.schedule(validatingTask, validatingInterval, validatingInterval);
}
}
@Override
public void doStop() throws Exception {
if (validatingTask != null) {
validatingTask.cancel();
}
super.doStop();
}
private class ValidatingTask extends TimerTask {
private final ConnectionInterceptor stack;
private final ReadWriteLock lock;
private final Object pool;
public ValidatingTask(ConnectionInterceptor stack, ReadWriteLock lock, Object pool) {
this.stack = stack;
this.lock = lock;
this.pool = pool;
}
@Override
public void run() {
if (lock != null) {
lock.writeLock().lock();
}
try {
final Map<ManagedConnection, ManagedConnectionInfo> connections;
if (stack instanceof SinglePoolConnectionInterceptor) {
connections = new HashMap<ManagedConnection, ManagedConnectionInfo>();
for (ManagedConnectionInfo info : (List<ManagedConnectionInfo>) pool) {
connections.put(info.getManagedConnection(), info);
}
} else if (stack instanceof SinglePoolMatchAllConnectionInterceptor) {
connections = (Map<ManagedConnection, ManagedConnectionInfo>) pool;
} else {
log.warn("stack {} currently not supported", stack);
return;
}
// destroy invalid connections
try {
Set<ManagedConnection> invalids = ValidatingManagedConnectionFactory.class.cast(getManagedConnectionFactory()).getInvalidConnections(connections.keySet());
if (invalids != null) {
for (ManagedConnection invalid : invalids) {
stack.returnConnection(new ConnectionInfo(connections.get(invalid)), ConnectionReturnAction.DESTROY);
}
}
} catch (ResourceException e) {
log.error(e.getMessage(), e);
}
} finally {
if (lock != null) {
lock.writeLock().unlock();
}
}
}
}
}
| 7,686 |
0 | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc | Create_ds/aries/transaction/transaction-jdbc/src/main/java/org/apache/aries/transaction/jdbc/internal/ValidatingDelegatingManagedConnectionFactory.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.aries.transaction.jdbc.internal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tranql.connector.AbstractManagedConnection;
import org.tranql.connector.ManagedConnectionHandle;
import org.tranql.connector.UserPasswordManagedConnectionFactory;
import org.tranql.connector.jdbc.ConnectionHandle;
import org.tranql.connector.jdbc.TranqlDataSource;
import javax.resource.NotSupportedException;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.TransactionSupport;
import javax.resource.spi.ValidatingManagedConnectionFactory;
import javax.security.auth.Subject;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
@SuppressWarnings({
"rawtypes", "serial", "unchecked"
})
public final class ValidatingDelegatingManagedConnectionFactory implements UserPasswordManagedConnectionFactory, ValidatingManagedConnectionFactory, TransactionSupport {
private static final Logger LOG = LoggerFactory.getLogger(ValidatingDelegatingManagedConnectionFactory.class);
private final ManagedConnectionFactory delegate;
public ValidatingDelegatingManagedConnectionFactory(ManagedConnectionFactory managedConnectionFactory) {
this.delegate = managedConnectionFactory;
}
private boolean isValidConnection(Connection c) {
try {
if (c.isValid(0)) {
LOG.debug("Connection validation succeeded for managed connection {}.", c);
return true;
} else {
LOG.debug("Connection validation failed for managed connection {}.", c);
}
} catch (SQLException e) {
// no-op
}
return false;
}
@Override
public TransactionSupportLevel getTransactionSupport() {
return TransactionSupport.class.cast(delegate).getTransactionSupport();
}
@Override
public Set getInvalidConnections(Set connectionSet) throws ResourceException {
Set<ManagedConnection> invalid = new HashSet<ManagedConnection>();
for (Object o : connectionSet) {
if (o instanceof AbstractManagedConnection) {
AbstractManagedConnection<Connection, ConnectionHandle> amc = AbstractManagedConnection.class.cast(o);
if (!isValidConnection(amc.getPhysicalConnection())) {
invalid.add(amc);
}
}
}
return invalid;
}
@Override
public String getUserName() {
return UserPasswordManagedConnectionFactory.class.cast(delegate).getUserName();
}
@Override
public String getPassword() {
return UserPasswordManagedConnectionFactory.class.cast(delegate).getPassword();
}
@Override
public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException {
return new TranqlDataSource(this, cxManager);
}
@Override
public Object createConnectionFactory() throws ResourceException {
throw new NotSupportedException("ConnectionManager is required");
}
@Override
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
return delegate.createManagedConnection(subject, cxRequestInfo);
}
@Override
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
for (Object o : connectionSet) {
if (o instanceof ManagedConnectionHandle) {
ManagedConnectionHandle mch = ManagedConnectionHandle.class.cast(o);
if (mch.matches(this, subject, cxRequestInfo)) {
if (mch instanceof AbstractManagedConnection) {
AbstractManagedConnection<Connection, ConnectionHandle> amc = AbstractManagedConnection.class.cast(mch);
if (isValidConnection(amc.getPhysicalConnection())) {
return amc;
}
} else {
return mch;
}
}
}
}
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws ResourceException {
delegate.setLogWriter(out);
}
@Override
public PrintWriter getLogWriter() throws ResourceException {
return delegate.getLogWriter();
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object other) {
return delegate.equals(other);
}
}
| 7,687 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/DummyNamespaceHandlerRegistry.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.aries.transaction;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.container.NamespaceHandlerRegistry;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.osgi.framework.Bundle;
public class DummyNamespaceHandlerRegistry implements NamespaceHandlerRegistry {
Map<URI, NamespaceHandler> handlers = new HashMap<URI, NamespaceHandler>();
@Override
public NamespaceHandlerSet getNamespaceHandlers(Set<URI> uriSet, Bundle bundle) {
Map<URI, NamespaceHandler> matching = new HashMap<URI, NamespaceHandler>();
for (URI uri : uriSet) {
if (handlers.containsKey(uri)) {
matching.put(uri, handlers.get(uri));
}
}
return new DummyNamespaceHandlerSet(matching);
}
@Override
public void destroy() {
}
public void addNamespaceHandlers(String[] namespaces, NamespaceHandler namespaceHandler) {
for (String namespace : namespaces) {
try {
handlers.put(new URI(namespace), namespaceHandler);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
}
}
| 7,688 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/AnnotationEnablingNameSpaceHandlerTest.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.aries.transaction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.transaction.parsing.TxNamespaceHandler;
import org.junit.Test;
import org.osgi.service.blueprint.reflect.BeanMetadata;
public class AnnotationEnablingNameSpaceHandlerTest extends BaseNameSpaceHandlerSetup {
@Test
public void testAnnotationEnabled() throws Exception
{
ComponentDefinitionRegistry cdr = parseCDR("enable-annotations.xml");
checkCompTop(cdr);
BeanMetadata pmd = (BeanMetadata) cdr.getComponentDefinition(TxNamespaceHandler.ANNOTATION_PARSER_BEAN_NAME);
assertNotNull(pmd);
assertEquals(3, pmd.getArguments().size());
assertEquals(cdr, ((PassThroughMetadata)pmd.getArguments().get(0).getValue()).getObject());
// assertEquals(tm, ((PassThroughMetadata) pmd.getArguments().get(2).getValue()).getObject());
}
@Test
public void testAnnotationDisabled() throws Exception
{
ComponentDefinitionRegistry cdr = parseCDR("enable-annotations2.xml");
checkCompTop(cdr);
BeanMetadata pmd = (BeanMetadata) cdr.getComponentDefinition(TxNamespaceHandler.ANNOTATION_PARSER_BEAN_NAME);
assertNull(pmd);
}
private void checkCompTop(ComponentDefinitionRegistry cdr) {
BeanMetadata compTop = (BeanMetadata) cdr.getComponentDefinition("top");
assertNotNull(compTop);
assertEquals(0, cdr.getInterceptors(compTop).size());
//assertNull(txenhancer.getComponentMethodTxAttribute(compTop, "increment"));
}
}
| 7,689 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/InterceptorTest.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.aries.transaction;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import java.io.IOException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.apache.aries.transaction.pojo.AnnotatedPojo;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Test;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.CoordinationException;
import org.osgi.service.coordinator.Coordinator;
public class InterceptorTest {
@Test
public void testRollbackOnException() throws Throwable {
runPostCall(false);
runPostCall(true);
}
private void runPostCall(boolean failCoordination) throws Throwable {
postCallWithTransaction(new IllegalStateException(), true, failCoordination);
postCallWithTransaction(new Error(), true, failCoordination);
postCallWithTransaction(new Exception(), false, failCoordination);
postCallWithTransaction(new IOException(), false, failCoordination);
}
private CoordinationException coordinationException(Throwable th) {
Coordination coordination = EasyMock.createMock(Coordination.class);
expect(coordination.getId()).andReturn(1l);
expect(coordination.getName()).andReturn("Test");
replay(coordination);
CoordinationException cex = new CoordinationException("Simulating exception",
coordination ,
CoordinationException.FAILED,
th);
return cex;
}
private void postCallWithTransaction(Throwable th, boolean expectRollback, boolean failCoordination) throws Throwable {
IMocksControl c = EasyMock.createControl();
TransactionManager tm = c.createMock(TransactionManager.class);
Coordinator coordinator = c.createMock(Coordinator.class);
ComponentTxData txData = new ComponentTxData(AnnotatedPojo.class);
TxInterceptorImpl sut = new TxInterceptorImpl(tm, coordinator, txData );
Transaction tran = c.createMock(Transaction.class);
if (expectRollback) {
tran.setRollbackOnly();
EasyMock.expectLastCall();
}
Coordination coordination = c.createMock(Coordination.class);
coordination.end();
if (failCoordination) {
EasyMock.expectLastCall().andThrow(coordinationException(th));
} else {
EasyMock.expectLastCall();
}
c.replay();
TransactionToken tt = new TransactionToken(tran, null, TransactionAttribute.REQUIRED);
tt.setCoordination(coordination );
sut.postCallWithException(null, this.getClass().getMethods()[0], th, tt);
c.verify();
}
}
| 7,690 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/ComponentTxDataTest.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.aries.transaction;
import static org.junit.Assert.*;
import java.lang.reflect.Method;
import java.sql.BatchUpdateException;
import java.sql.SQLDataException;
import java.util.List;
import javax.transaction.Transactional.TxType;
import org.apache.aries.transaction.pojo.BadlyAnnotatedPojo1;
import org.apache.aries.transaction.pojo.AnnotatedPojo;
import org.apache.aries.transaction.pojo.ExtendedPojo;
import org.apache.aries.transaction.pojo.ExtendedPojo2;
import org.apache.aries.transaction.pojo.ExtendedPojo3;
import org.apache.aries.transaction.pojo.OnRollbackPojo;
import org.junit.Assert;
import org.junit.Test;
public class ComponentTxDataTest {
@Test
public void testFindAnnotation() throws NoSuchMethodException, SecurityException {
ComponentTxData txData = new ComponentTxData(AnnotatedPojo.class);
Assert.assertTrue(txData.isTransactional());
assertEquals(TxType.REQUIRED, getEffectiveType(txData, "increment").getTxType());
assertEquals(TxType.SUPPORTS, getEffectiveType(txData, "checkValue").getTxType());
assertEquals(TxType.MANDATORY, getEffectiveType(txData, "getRealObject").getTxType());
}
@Test
public void testFindAnnotationExtended() throws Exception {
ComponentTxData txData = new ComponentTxData(ExtendedPojo.class);
assertEquals(TxType.REQUIRED, getEffectiveType(txData, "defaultType").getTxType());
assertEquals(TxType.SUPPORTS, getEffectiveType(txData, "supports").getTxType());
}
@Test
public void testFindAnnotationExtended2() throws Exception {
ComponentTxData txData = new ComponentTxData(ExtendedPojo2.class);
assertEquals(TxType.MANDATORY, getEffectiveType(txData, "defaultType").getTxType());
assertEquals(TxType.SUPPORTS, getEffectiveType(txData, "supports").getTxType());
}
@Test
public void testFindAnnotationExtended3() throws Exception {
ComponentTxData txData = new ComponentTxData(ExtendedPojo3.class);
assertEquals(TxType.MANDATORY, getEffectiveType(txData, "defaultType").getTxType());
assertEquals(TxType.REQUIRED, getEffectiveType(txData, "supports").getTxType());
}
@Test(expected=IllegalArgumentException.class)
public void testNoPrivateAnnotation() {
new ComponentTxData(BadlyAnnotatedPojo1.class);
}
@Test(expected=IllegalArgumentException.class)
public void testNoStaticAnnotation() {
new ComponentTxData(BadlyAnnotatedPojo1.class);
}
@Test
public void testOnRollback() {
ComponentTxData txData = new ComponentTxData(OnRollbackPojo.class);
List<Class> rollbackOnBatchUpdateException = getEffectiveType(txData, "throwBatchUpdateException").getRollbackOn();
assertFalse(rollbackOnBatchUpdateException.contains(SQLDataException.class));
assertTrue(rollbackOnBatchUpdateException.contains(BatchUpdateException.class));
List<Class> rollbackOnSQLDataException = getEffectiveType(txData, "throwSQLDataException").getRollbackOn();
assertTrue(rollbackOnSQLDataException.contains(SQLDataException.class));
assertFalse(rollbackOnSQLDataException.contains(BatchUpdateException.class));
}
private TransactionalAnnotationAttributes getEffectiveType(ComponentTxData txData, String methodName) {
Class<?> c = txData.getBeanClass();
Method m;
try {
m = c.getDeclaredMethod(methodName, String.class);
} catch (NoSuchMethodException e) {
try {
m = c.getMethod(methodName, String.class);
} catch (NoSuchMethodException e1) {
throw new IllegalArgumentException(e1);
}
}
return txData.getEffectiveType(m).get();
}
}
| 7,691 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/DummyNamespaceHandlerSet.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.aries.transaction;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import javax.xml.validation.Schema;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.xml.sax.SAXException;
public class DummyNamespaceHandlerSet implements NamespaceHandlerSet {
private Map<URI, NamespaceHandler> nsHandlers;
public DummyNamespaceHandlerSet(Map<URI, NamespaceHandler> nsHandlers) {
this.nsHandlers = nsHandlers;
}
@Override
public void addListener(Listener listener) {
throw new IllegalStateException("Not implemented");
}
@Override
public void destroy() {
}
@Override
public NamespaceHandler getNamespaceHandler(URI nsuri) {
return nsHandlers.get(nsuri);
}
@Override
public Set<URI> getNamespaces() {
return nsHandlers.keySet();
}
@Override
public Schema getSchema() throws SAXException, IOException {
throw new IllegalStateException("Not implemented");
}
@Override
public boolean isComplete() {
return true;
}
@Override
public void removeListener(Listener listener) {
throw new IllegalStateException("Not implemented");
}
}
| 7,692 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/BaseNameSpaceHandlerSetup.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.aries.transaction;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Set;
import javax.transaction.TransactionManager;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.apache.aries.blueprint.parser.Parser;
import org.apache.aries.blueprint.reflect.PassThroughMetadataImpl;
import org.apache.aries.transaction.parsing.TxNamespaceHandler;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.After;
import org.junit.Before;
import org.osgi.framework.Bundle;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.coordinator.Coordinator;
public class BaseNameSpaceHandlerSetup {
protected Bundle b;
protected DummyNamespaceHandlerRegistry nhri;
protected TxNamespaceHandler namespaceHandler;
protected IMocksControl control;
@Before
public void setUp() throws InvalidSyntaxException {
control = EasyMock.createControl();
b = control.createMock(Bundle.class);
TransactionManager tm = control.createMock(TransactionManager.class);
Coordinator coordinator = control.createMock(Coordinator.class);
control.replay();
namespaceHandler = new TxNamespaceHandler();
namespaceHandler.setTm(tm);
namespaceHandler.setCoordinator(coordinator);
String[] namespaces = new String[] { "http://aries.apache.org/xmlns/transactions/v2.0.0" };
nhri = new DummyNamespaceHandlerRegistry();
nhri.addNamespaceHandlers(namespaces, namespaceHandler);
}
@After
public void tearDown() throws Exception{
control.verify();
b = null;
nhri = null;
}
protected ComponentDefinitionRegistry parseCDR(String name) throws Exception {
Parser p = new Parser();
URL bpxml = this.getClass().getResource(name);
p.parse(Arrays.asList(bpxml));
Set<URI> nsuris = p.getNamespaces();
NamespaceHandlerSet nshandlers = nhri.getNamespaceHandlers(nsuris, b);
ComponentDefinitionRegistry cdr = new ComponentDefinitionRegistryImpl();
cdr.registerComponentDefinition(new PassThroughMetadataImpl("blueprintBundle", b));
p.populate(nshandlers, cdr);
return cdr;
}
}
| 7,693 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/TranStrategyTest.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.aries.transaction;
import static org.easymock.EasyMock.createControl;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.transaction.NotSupportedException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Before;
import org.junit.Test;
public class TranStrategyTest {
TransactionManager tm;
Transaction t;
private IMocksControl c;
@Before
public void clean()
{
c = createControl();
tm = c.createMock(TransactionManager.class);
t = c.createMock(Transaction.class);
}
@Test
public void testMandatoryBegin() throws Exception
{
// MANDATORY strategy should throw IllegalStateException when tran manager
// status is Status.STATUS_NO_TRANSACTION it should not return null.
expect(tm.getStatus()).andReturn(Status.STATUS_NO_TRANSACTION);
try {
assertNotNull("TransactionStrategy.MANDATORY.begin(tm) returned null when manager " +
"status is STATUS_NO_TRANSACTION", TransactionAttribute.MANDATORY.begin(tm).getActiveTransaction());
} catch (IllegalStateException ise) {
// Expected to be in here
} catch (Exception e) {
fail("TransactionStrategy.MANDATORY.begin() threw an unexpected exception when tran manager status is STATUS_NO_TRANSACTION");
}
// MANDATORY strategy should return null for all tran manager states other
// than Status.STATUS_NO_TRANSACTION.
int[] invalids = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_MARKED_ROLLBACK,
Status.STATUS_ACTIVE, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
for (int i = 0; i < invalids.length ; i++) {
c.reset();
expect(tm.getStatus()).andReturn(invalids[i]);
expect(tm.getTransaction()).andReturn(null);
c.replay();
try {
Transaction tran = TransactionAttribute.MANDATORY.begin(tm).getActiveTransaction();
assertNull("TransactionStrategy.MANDATORY.begin() did not return null when manager status value is " + invalids[i], tran);
} catch (Exception ise) {
fail("TransactionStrategy.MANDATORY.begin() threw Exception when manager status value is " + invalids[i]);
}
c.verify();
}
}
@Test
public void testMandatoryFinish()
{
try {
TransactionToken tranToken = new TransactionToken(t, null, TransactionAttribute.MANDATORY);
TransactionAttribute.MANDATORY.finish(tm, tranToken);
} catch (Exception e) {
fail("TransactionStrategy.MANDATORY.finish() threw an unexpected exception");
}
}
@Test
public void testNeverBegin() throws Exception
{
// NEVER strategy should throw IllegalStateException when tran manager
// status is Status.STATUS_ACTIVE it should not return null.
expect(tm.getStatus()).andReturn(Status.STATUS_ACTIVE);
try {
assertNotNull("TransactionStrategy.NEVER.begin() returned null when manager status is STATUS_ACTIVE", TransactionAttribute.NEVER.begin(tm));
} catch (IllegalStateException ise) {
// Expect to be in here
} catch (Exception e) {
fail("TransactionStrategy.NEVER.begin() threw an unexpected exception when tran manager status is STATUS_ACTIVE");
}
// NEVER strategy should return null for all tran manager states other
// than Status.STATUS_ACTIVE.
int[] invalids = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_MARKED_ROLLBACK,
Status.STATUS_NO_TRANSACTION, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
for (int i = 0; i < invalids.length ; i++) {
c.reset();
expect(tm.getStatus()).andReturn(invalids[i]);
expect(tm.getTransaction()).andReturn(null).anyTimes();
c.replay();
try {
assertNull("TransactionStrategy.NEVER.begin() did not return null when manager status value is " + invalids[i], TransactionAttribute.NEVER.begin(tm).getActiveTransaction());
} catch (Exception ise) {
fail("TransactionStrategy.NEVER.begin() threw unexpected exception when manager status value is " + invalids[i]);
}
c.verify();
}
}
@Test
public void testNeverFinish()
{
try {
TransactionToken tranToken = new TransactionToken(null, null, TransactionAttribute.NEVER);
TransactionAttribute.NEVER.finish(tm, tranToken);
} catch (Exception e) {
fail("TransactionStrategy.NEVER.finish() threw an unexpected exception");
}
}
@Test
public void testNotSupportedBegin() throws Exception
{
// NOT_SUPPORTED strategy should suspend an active transaction
// and _NOT_ begin a new one
expect(tm.getStatus()).andReturn(Status.STATUS_ACTIVE);
expect(tm.suspend()).andReturn(null);
c.replay();
TransactionAttribute.NOT_SUPPORTED.begin(tm);
c.verify();
// For all situations where there is no active transaction the
// NOT_SUPPORTED strategy should return null
int[] invalids = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_MARKED_ROLLBACK,
Status.STATUS_NO_TRANSACTION, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
for (int i = 0; i < invalids.length ; i++) {
c.reset();
expect(tm.getStatus()).andReturn(invalids[i]);
expect(tm.getTransaction()).andReturn(null).anyTimes();
c.replay();
try {
assertNull("TransactionStrategy.NOT_SUPPORTED.begin() did not return null when manager status value is " + invalids[i], TransactionAttribute.NOT_SUPPORTED.begin(tm).getActiveTransaction());
} catch (Exception ise) {
fail("TransactionStrategy.NOT_SUPPORTED.begin() threw unexpected exception when manager status value is " + invalids[i]);
}
c.verify();
}
}
@Test
public void testNotSupportedFinish()
{
// If finish is called with a previously active transaction, then
// we expect this transaction to be resumed for a NOT_SUPPORTED strategy
try {
tm.resume(t);
EasyMock.expectLastCall();
c.replay();
TransactionToken tranToken = new TransactionToken(null, t, TransactionAttribute.NOT_SUPPORTED);
TransactionAttribute.NOT_SUPPORTED.finish(tm, tranToken);
c.verify();
c.reset();
tranToken = new TransactionToken(null, null, TransactionAttribute.NOT_SUPPORTED);
TransactionAttribute.NOT_SUPPORTED.finish(tm, tranToken);
} catch (Exception e) {
fail("TransactionStrategy.NOT_SUPPORTED.finish() threw unexpected exception, " + e);
}
}
@Test
public void testRequiredBegin() throws Exception
{
// If there is no previously active transaction when the REQUIRED strategy
// is invoked then we expect a call to begin one
expect(tm.getStatus()).andReturn(Status.STATUS_NO_TRANSACTION);
expect(tm.getTransaction()).andReturn(null);
tm.begin();
expectLastCall();
c.replay();
TransactionAttribute.REQUIRED.begin(tm);
c.verify();
c.reset();
// For all cases where there is a transaction we expect REQUIRED to return null
int[] invalids = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_MARKED_ROLLBACK,
Status.STATUS_ACTIVE, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
for (int i = 0; i < invalids.length ; i++) {
c.reset();
expect(tm.getStatus()).andReturn(invalids[i]);
expect(tm.getTransaction()).andReturn(null);
c.replay();
try {
assertNull("TransactionStrategy.REQUIRED.begin() did not return null when manager status value is " + invalids[i], TransactionAttribute.REQUIRED.begin(tm).getActiveTransaction());
} catch (Exception ise) {
fail("TransactionStrategy.REQUIRED.begin() threw unexpected exception when manager status value is " + invalids[i]);
}
c.verify();
}
}
@Test
public void testRequiredFinish() throws Exception
{
// In the REQUIRED strategy we expect a call to rollback when a call to finish()
// is made with a tran where the tran manager status shows Status.STATUS_MARKED_ROLLBACK
expect(tm.getStatus()).andReturn(Status.STATUS_MARKED_ROLLBACK);
TransactionToken tranToken = new TransactionToken(t, null, TransactionAttribute.REQUIRED, true);
tm.rollback();
expectLastCall();
c.replay();
TransactionAttribute.REQUIRED.finish(tm, tranToken);
c.verify();
int[] invalids = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
// For all other tran manager states we expect a call to commit
for (int i = 0; i < invalids.length ; i++) {
c.reset();
expect(tm.getStatus()).andReturn(invalids[i]);
tm.commit();
expectLastCall();
c.replay();
TransactionAttribute.REQUIRED.finish(tm, tranToken);
c.verify();
}
// If null is passed instead of a tran we expect nothing to happen
c.reset();
c.replay();
tranToken = new TransactionToken(null, null, TransactionAttribute.REQUIRED);
c.verify();
TransactionAttribute.REQUIRED.finish(tm, tranToken);
}
@Test
public void testRequiresNew_BeginActiveTran() throws Exception
{
// Suspend case (no exception from tm.begin())
expect(tm.getStatus()).andReturn(Status.STATUS_ACTIVE);
// In the case of the REQUIRES_NEW strategy we expect an active tran to be suspended
// a new new transaction to begin
expect(tm.suspend()).andReturn(null);
expectLastCall();
tm.begin();
expectLastCall();
expect(tm.getTransaction()).andReturn(null);
c.replay();
TransactionAttribute.REQUIRES_NEW.begin(tm);
c.verify();
}
@Test
public void testRequiresNew_BeginNoActiveTran() throws Exception
{
// No active tran cases (no exception from tm.begin())
int[] manStatus = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_MARKED_ROLLBACK,
Status.STATUS_NO_TRANSACTION, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
// For all cases where the tran manager state is _not_ Status.STATUS_ACTIVE
// we expect a call to begin a new tran, no call to suspend and null to be
// returned from TransactionStrategy.REQUIRES_NEW.begin(tm)
for (int i = 0; i < manStatus.length ; i++) {
c.reset();
expect(tm.getStatus()).andReturn(manStatus[i]);
expect(tm.getTransaction()).andReturn(null);
tm.begin();
expectLastCall();
c.replay();
try {
assertNull("TransactionStrategy.REQUIRES_NEW.begin() did not return null when manager status value is " + manStatus[i], TransactionAttribute.REQUIRES_NEW.begin(tm).getActiveTransaction());
} catch (Exception ise) {
fail("TransactionStrategy.REQUIRES_NEW.begin() threw unexpected exception when manager status value is " + manStatus[i]);
}
c.verify();
}
}
@Test
public void testRequiresNew_TmExceptions() throws Exception
{
int[] allStates = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_MARKED_ROLLBACK, Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
// SystemException and NotSupportedException from tm.begin()
Set<Exception> ees = new HashSet<Exception>();
ees.add(new SystemException("KABOOM!"));
ees.add(new NotSupportedException("KABOOM!"));
// Loop through all states states twice changing the exception thrown
// from tm.begin()
for (int i = 0 ; i < allStates.length ; i++ ) {
Iterator<Exception> iterator = ees.iterator();
while (iterator.hasNext()) {
Exception e = iterator.next();
c.reset();
expect(tm.getStatus()).andReturn(allStates[i]);
expect(tm.getTransaction()).andReturn(null).anyTimes();
tm.begin();
expectLastCall().andThrow(e);
requiresNewExceptionCheck(tm, allStates[i]);
}
}
}
private void requiresNewExceptionCheck(TransactionManager tm, int managerStatus) throws Exception
{
// If an ACTIVE tran is already present we expect a call to suspend this tran.
// All states should call begin(), whereupon we receive our exception resulting
// in calls to resume(t)
if (managerStatus == Status.STATUS_ACTIVE) {
expect(tm.suspend()).andReturn(null);
}
tm.resume(EasyMock.anyObject(Transaction.class));
expectLastCall();
c.replay();
try {
TransactionAttribute.REQUIRES_NEW.begin(tm);
} catch (SystemException se) {
// Expect to be in here
} catch (NotSupportedException nse) {
// or to be in here
} catch (Exception thrownE) {
fail("TransactionStrategy.REQUIRES_NEW.begin() threw unexpected exception when manager status is " + managerStatus);
} finally {
// If Status.STATUS_ACTIVE
}
c.verify();
c.reset();
}
@Test
public void testRequiresNew_Finish() throws Exception
{
int[] allStates = new int[]{ Status.STATUS_COMMITTED, Status.STATUS_COMMITTING, Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLEDBACK,
Status.STATUS_MARKED_ROLLBACK, Status.STATUS_ROLLING_BACK, Status.STATUS_UNKNOWN };
// Loop through all states calling TransactionStrategy.REQUIRES_NEW.finish
// passing tran manager and a tran, then passing tran manager and null
for (int i = 0 ; i < allStates.length ; i++ ) {
c.reset();
expect(tm.getStatus()).andReturn(allStates[i]);
requiresNew_assertion(tm, allStates[i]);
tm.resume(EasyMock.anyObject(Transaction.class));
expectLastCall();
c.replay();
try {
TransactionToken tranToken = new TransactionToken(t, t, TransactionAttribute.REQUIRES_NEW, true);
TransactionAttribute.REQUIRES_NEW.finish(tm, tranToken);
} catch (Exception e) {
fail("TransactionStrategy.REQUIRES_NEW.finish() threw unexpected exception when manager status is " + allStates[i]);
}
c.verify();
c.reset();
try {
expect(tm.getStatus()).andReturn(allStates[i]);
requiresNew_assertion(tm, allStates[i]);
c.replay();
TransactionToken tranToken = new TransactionToken(t, null, TransactionAttribute.REQUIRES_NEW, true);
TransactionAttribute.REQUIRES_NEW.finish(tm, tranToken);
} catch (Throwable e) {
e.printStackTrace();
fail("TransactionStrategy.REQUIRES_NEW.finish() threw unexpected exception when manager status is " + allStates[i]);
} finally {
}
c.verify();
}
}
// If tran manager status reports Status.STATUS_MARKED_ROLLBACK we expect
// a call to rollback ... otherwise we expect a call to commit
private void requiresNew_assertion(TransactionManager tm, int status) throws Exception
{
if (status == Status.STATUS_MARKED_ROLLBACK) {
tm.rollback();
}
else {
tm.commit();
}
expectLastCall();
}
@Test
public void testSupports() throws Exception
{
expect(tm.getTransaction()).andReturn(null);
expect(tm.getStatus()).andReturn(Status.STATUS_ACTIVE);
c.replay();
assertNull("TransTransactionStrategy.SUPPORTS.begin(tm) did not return null", TransactionAttribute.SUPPORTS.begin(tm).getActiveTransaction());
c.verify();
}
}
| 7,694 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/OnRollbackPojo.java | package org.apache.aries.transaction.pojo;
import java.sql.BatchUpdateException;
import java.sql.SQLDataException;
import javax.transaction.Transactional;
@Transactional(rollbackOn = SQLDataException.class)
public class OnRollbackPojo {
@Transactional(rollbackOn = BatchUpdateException.class)
public void throwBatchUpdateException(String s) throws BatchUpdateException {
throw new BatchUpdateException();
}
public void throwSQLDataException(String s) throws SQLDataException {
throw new SQLDataException();
}
}
| 7,695 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/ExtendedPojo3.java | package org.apache.aries.transaction.pojo;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
@Transactional(value=TxType.MANDATORY)
public class ExtendedPojo3 extends BaseClass {
@Override
public void defaultType(String test) {
super.defaultType(test);
}
}
| 7,696 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/ExtendedPojo2.java | package org.apache.aries.transaction.pojo;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
@Transactional(value=TxType.MANDATORY)
public class ExtendedPojo2 extends BaseClass {
@Override
public void defaultType(String test) {
}
@Transactional(value=TxType.SUPPORTS)
@Override
public void supports(String test) {
}
}
| 7,697 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/BadlyAnnotatedPojo2.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.aries.transaction.pojo;
import javax.transaction.Transactional;
public class BadlyAnnotatedPojo2 {
@Transactional
public static void alsoDoesNotWork() {
}
}
| 7,698 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/AnnotatedPojo.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.aries.transaction.pojo;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
@Transactional(TxType.REQUIRED)
public class AnnotatedPojo {
public void increment(String key) {
}
@Transactional(TxType.SUPPORTS)
protected int checkValue(String key) {
return 0;
}
@Transactional(TxType.MANDATORY)
Object getRealObject(String key) {
return null;
}
}
| 7,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.