repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
hyc/BerkeleyDB | lang/java/src/com/sleepycat/persist/raw/RawStore.java | 5359 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2013 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.persist.raw;
import java.io.Closeable;
import com.sleepycat.compat.DbCompat;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Environment;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.StoreExistsException;
import com.sleepycat.persist.StoreNotFoundException;
import com.sleepycat.persist.evolve.IncompatibleClassException;
import com.sleepycat.persist.evolve.Mutations;
import com.sleepycat.persist.impl.Store;
import com.sleepycat.persist.model.EntityModel;
/**
* Provides access to the raw data in a store for use by general purpose tools.
* A <code>RawStore</code> provides access to stored entities without using
* entity classes or key classes. Keys are represented as simple type objects
* or, for composite keys, as {@link RawObject} instances, and entities are
* represented as {@link RawObject} instances.
*
* <p>{@code RawStore} objects are thread-safe. Multiple threads may safely
* call the methods of a shared {@code RawStore} object.</p>
*
* <p>When using a {@code RawStore}, the current persistent class definitions
* are not used. Instead, the previously stored metadata and class definitions
* are used. This has several implications:</p>
* <ol>
* <li>An {@code EntityModel} may not be specified using {@link
* StoreConfig#setModel}. In other words, the configured model must be
* null (the default).</li>
* <li>When storing entities, their format will not automatically be evolved
* to the current class definition, even if the current class definition has
* changed.</li>
* </ol>
*
* @author Mark Hayes
*/
public class RawStore
{
private Store store;
/**
* Opens an entity store for raw data access.
*
* @param env an open Berkeley DB environment.
*
* @param storeName the name of the entity store within the given
* environment.
*
* @param config the store configuration, or null to use default
* configuration properties.
*
* @throws IllegalArgumentException if the <code>Environment</code> is
* read-only and the <code>config ReadOnly</code> property is false.
*/
public RawStore(Environment env, String storeName, StoreConfig config)
throws StoreNotFoundException, DatabaseException {
try {
store = new Store(env, storeName, config, true /*rawAccess*/);
} catch (StoreExistsException e) {
/* Should never happen, ExclusiveCreate not used. */
throw DbCompat.unexpectedException(e);
} catch (IncompatibleClassException e) {
/* Should never happen, evolution is not performed. */
throw DbCompat.unexpectedException(e);
}
}
/**
* Opens the primary index for a given entity class.
*
* @throws DatabaseException the base class for all BDB exceptions.
*/
public PrimaryIndex<Object, RawObject> getPrimaryIndex(String entityClass)
throws DatabaseException {
return store.getPrimaryIndex
(Object.class, null, RawObject.class, entityClass);
}
/**
* Opens the secondary index for a given entity class and secondary key
* name.
*
* @throws DatabaseException the base class for all BDB exceptions.
*/
public SecondaryIndex<Object, Object, RawObject>
getSecondaryIndex(String entityClass, String keyName)
throws DatabaseException {
return store.getSecondaryIndex
(getPrimaryIndex(entityClass), RawObject.class, entityClass,
Object.class, null, keyName);
}
/**
* Returns the environment associated with this store.
*/
public Environment getEnvironment() {
return store.getEnvironment();
}
/**
* Returns a copy of the entity store configuration.
*/
public StoreConfig getConfig() {
return store.getConfig();
}
/**
* Returns the name of this store.
*/
public String getStoreName() {
return store.getStoreName();
}
/**
* Returns the last configured and stored entity model for this store.
*/
public EntityModel getModel() {
return store.getModel();
}
/**
* Returns the set of mutations that were configured and stored previously.
*/
public Mutations getMutations() {
return store.getMutations();
}
/**
* Closes all databases and sequences that were opened by this model. No
* databases opened via this store may be in use.
*
* <p>WARNING: To guard against memory leaks, the application should
* discard all references to the closed handle. While BDB makes an effort
* to discard references from closed objects to the allocated memory for an
* environment, this behavior is not guaranteed. The safe course of action
* for an application is to discard all references to closed BDB
* objects.</p>
*
* @throws DatabaseException the base class for all BDB exceptions.
*/
public void close()
throws DatabaseException {
store.close();
}
}
| agpl-3.0 |
fpuna-cia/karaku | src/main/java/py/una/pol/karaku/util/DateProvider.java | 1635 | /*-
* Copyright (c)
*
* 2012-2014, Facultad Politécnica, Universidad Nacional de Asunción.
* 2012-2014, Facultad de Ciencias Médicas, Universidad Nacional de Asunción.
* 2012-2013, Centro Nacional de Computación, Universidad Nacional de Asunción.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package py.una.pol.karaku.util;
import java.util.Calendar;
import java.util.Date;
import org.springframework.stereotype.Component;
/**
* Componente que sirve para proveer fechas de Karaku.
*
* @author Arturo Volpe
* @since 2.2.8
* @version 1.0 Nov 14, 2013
*
*/
@Component
public class DateProvider {
/**
* Retorna la fecha actual.
*
* @return fecha actual
*/
public Date getNow() {
return getNowCalendar().getTime();
}
/**
* Retorna la fecha actual en forma de un {@link Calendar}.
*
* @return fecha actual.
*/
public Calendar getNowCalendar() {
return Calendar.getInstance();
}
}
| lgpl-2.1 |
drhee/toxoMine | intermine/web/test/src/org/intermine/webservice/server/output/JSONRowIteratorTest.java | 21836 | /**
*
*/
package org.intermine.webservice.server.output;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.intermine.api.InterMineAPI;
import org.intermine.api.query.MainHelper;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.metadata.Model;
import org.intermine.model.testmodel.Address;
import org.intermine.model.testmodel.CEO;
import org.intermine.model.testmodel.Company;
import org.intermine.model.testmodel.Contractor;
import org.intermine.model.testmodel.Department;
import org.intermine.model.testmodel.Employee;
import org.intermine.model.testmodel.Manager;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.dummy.DummyResults;
import org.intermine.objectstore.dummy.ObjectStoreDummyImpl;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OuterJoinStatus;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.DynamicUtil;
import org.intermine.util.IteratorIterable;
import org.json.JSONArray;
/**
* A test for the JSONRowIterator
* @author Alex Kalderimis
*
*/
public class JSONRowIteratorTest extends TestCase {
private ObjectStoreDummyImpl os;
private final InterMineAPI apiWithRedirection = new DummyAPI();
private final InterMineAPI apiWithoutRedirection = new DummyAPI(false);
private Company wernhamHogg;
private CEO jennifer;
private Manager david;
private Manager taffy;
private Employee tim;
private Employee gareth;
private Employee dawn;
private Employee keith;
private Employee lee;
private Employee alex;
private Department sales;
private Department reception;
private Department accounts;
private Department distribution;
private Address address;
private Contractor rowan;
private Contractor ray;
private Contractor jude;
private Department swindon;
private Manager neil;
private Employee rachel;
private Employee trudy;
private Company bms;
private Address address2;
@Override
protected void setUp() {
os = new ObjectStoreDummyImpl();
wernhamHogg = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
wernhamHogg.setId(new Integer(1));
wernhamHogg.setName("Wernham-Hogg");
wernhamHogg.setVatNumber(101);
jennifer = new CEO();
jennifer.setId(new Integer(2));
jennifer.setName("Jennifer Taylor-Clarke");
jennifer.setAge(42);
david = new Manager();
david.setId(new Integer(3));
david.setName("David Brent");
david.setAge(39);
taffy = new Manager();
taffy.setId(new Integer(4));
taffy.setName("Glynn");
taffy.setAge(38);
tim = new Employee();
tim.setId(new Integer(5));
tim.setName("Tim Canterbury");
tim.setAge(30);
gareth = new Employee();
gareth.setId(new Integer(6));
gareth.setName("Gareth Keenan");
gareth.setAge(32);
dawn = new Employee();
dawn.setId(new Integer(7));
dawn.setName("Dawn Tinsley");
dawn.setAge(26);
keith = new Employee();
keith.setId(new Integer(8));
keith.setName("Keith Bishop");
keith.setAge(41);
lee = new Employee();
lee.setId(new Integer(9));
lee.setName("Lee");
lee.setAge(28);
alex = new Employee();
alex.setId(new Integer(10));
alex.setName("Alex");
alex.setAge(24);
sales = new Department();
sales.setId(new Integer(11));
sales.setName("Sales");
accounts = new Department();
accounts.setId(new Integer(12));
accounts.setName("Accounts");
distribution = new Department();
distribution.setId(new Integer(13));
distribution.setName("Warehouse");
reception = new Department();
reception.setId(new Integer(14));
reception.setName("Reception");
address = new Address();
address.setId(new Integer(15));
address.setAddress("42 Friendly St, Betjeman Trading Estate, Slough");
rowan = new Contractor();
rowan.setId(new Integer(16));
rowan.setName("Rowan");
ray = new Contractor();
ray.setId(new Integer(17));
ray.setName("Ray");
jude = new Contractor();
jude.setId(new Integer(18));
jude.setName("Jude");
swindon = new Department();
swindon.setId(new Integer(19));
swindon.setName("Swindon");
neil = new Manager();
neil.setId(new Integer(20));
neil.setName("Neil Godwin");
neil.setAge(35);
rachel = new Employee();
rachel.setId(new Integer(21));
rachel.setName("Rachel");
rachel.setAge(34);
trudy = new Employee();
trudy.setId(new Integer(22));
trudy.setName("Trudy");
trudy.setAge(25);
bms = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
bms.setId(new Integer(23));
bms.setName("Business Management Seminars");
bms.setVatNumber(102);
address2 = new Address();
address2.setId(new Integer(24));
address2.setAddress("19 West Oxford St, Reading");
}
private final Model model = Model.getInstanceByName("testmodel");
/**
* Empty constructor
*/
public JSONRowIteratorTest() {
// Empty Constructor
}
/**
* Constructor with name.
* @param name
*/
public JSONRowIteratorTest(String name) {
super(name);
}
public void testSingleSimpleObject() throws Exception {
os.setResultsSize(1);
String jsonString = "[" +
"{id: 3, class: 'Manager', value: 'David Brent', url: '/report.do?id=3'}," +
"{id: 3, class: 'Manager', value: '39', url: '/report.do?id=3'}" +
"]";
JSONArray expected = new JSONArray(jsonString);
ResultsRow row = new ResultsRow();
row.add(david);
os.addRow(row);
PathQuery pq = new PathQuery(model);
pq.addViews("Manager.name", "Manager.age");
Map pathToQueryNode = new HashMap();
Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null);
List resultList = os.execute(q, 0, 5, true, true, new HashMap());
Results results = new DummyResults(q, resultList);
ExportResultsIterator iter = new ExportResultsIterator(pq, q, results, pathToQueryNode);
JSONRowIterator jsonIter = new JSONRowIterator(iter, apiWithoutRedirection);
List<JSONArray> got = new ArrayList<JSONArray>();
for (JSONArray gotRow : new IteratorIterable<JSONArray>(jsonIter)) {
got.add(gotRow);
}
assertEquals(1, got.size());
assertEquals(null, JSONObjTester.getProblemsComparing(expected, got.get(0)));
jsonString = "[" +
"{id: 3, class: 'Manager', value: 'David Brent', url: 'Link for:Manager [address=null, age=\"39\", department=null, departmentThatRejectedMe=null, end=\"null\", fullTime=\"false\", id=\"3\", name=\"David Brent\", seniority=\"null\", title=\"null\"]'}," +
"{id: 3, class: 'Manager', value: '39', url: 'Link for:Manager [address=null, age=\"39\", department=null, departmentThatRejectedMe=null, end=\"null\", fullTime=\"false\", id=\"3\", name=\"David Brent\", seniority=\"null\", title=\"null\"]'}," +
"]";
expected = new JSONArray(jsonString);
iter = new ExportResultsIterator(pq, q, results, pathToQueryNode);
jsonIter = new JSONRowIterator(iter, apiWithRedirection);
got = new ArrayList<JSONArray>();
for (JSONArray gotRow : new IteratorIterable<JSONArray>(jsonIter)) {
got.add(gotRow);
}
assertEquals(1, got.size());
assertEquals(null, JSONObjTester.getProblemsComparing(expected, got.get(0)));
}
public void testResultsWithNulls() throws Exception {
os.setResultsSize(2);
List<String> jsonStrings = Arrays.asList(
"[" +
"{id: 3, class: 'Manager', value: 'David Brent', url: '/report.do?id=3'}," +
"{id: 3, class: 'Manager', value: '39', url: '/report.do?id=3'}" +
"]",
"[" +
"{value: null, url: null}," +
"{value: null, url: null}" +
"]");
ResultsRow row = new ResultsRow();
row.add(david);
ResultsRow emptyRow = new ResultsRow();
emptyRow.add(null);
os.addRow(row);
os.addRow(emptyRow);
PathQuery pq = new PathQuery(model);
pq.addViews("Manager.name", "Manager.age");
ExportResultsIterator iter = getIterator(pq);
JSONRowIterator jsonIter = new JSONRowIterator(iter, apiWithoutRedirection);
List<JSONArray> got = new ArrayList<JSONArray>();
for (JSONArray gotRow : new IteratorIterable<JSONArray>(jsonIter)) {
got.add(gotRow);
}
assertEquals(2, got.size());
for (int i = 0; i < got.size(); i++) {
JSONArray expected = new JSONArray(jsonStrings.get(i));
assertEquals(null, JSONObjTester.getProblemsComparing(expected, got.get(i)));
}
}
private ExportResultsIterator getIterator(PathQuery pq) throws ObjectStoreException {
Map pathToQueryNode = new HashMap();
Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null);
List resultList = os.execute(q, 0, 5, true, true, new HashMap());
Results results = new DummyResults(q, resultList);
ExportResultsIterator iter = new ExportResultsIterator(pq, q, results, pathToQueryNode);
return iter;
}
public void testMultipleSimpleObjects() throws Exception {
os.setResultsSize(5);
List<String> jsonStrings = new ArrayList<String>();
jsonStrings.add("[" +
"{id: 5, class: 'Employee', url: '/report.do?id=5', value:30}," +
"{id: 5, class: 'Employee', url: '/report.do?id=5', value:'Tim Canterbury'}" +
"]");
jsonStrings.add("[" +
"{id: 6, class: 'Employee', url: '/report.do?id=6', value:32}," +
"{id: 6, class: 'Employee', url: '/report.do?id=6', value:'Gareth Keenan'}" +
"]");
jsonStrings.add("[" +
"{id: 7, class: 'Employee', url: '/report.do?id=7', value:26}," +
"{id: 7, class: 'Employee', url: '/report.do?id=7', value:'Dawn Tinsley'}" +
"]");
jsonStrings.add("[" +
"{id: 8, class: 'Employee', url: '/report.do?id=8', value:41}," +
"{id: 8, class: 'Employee', url: '/report.do?id=8', value:'Keith Bishop'}" +
"]");
jsonStrings.add("[" +
"{id: 9, class: 'Employee', url: '/report.do?id=9', value:28}," +
"{id: 9, class: 'Employee', url: '/report.do?id=9', value:'Lee'}" +
"]");
ResultsRow row1 = new ResultsRow();
row1.add(tim);
ResultsRow row2 = new ResultsRow();
row2.add(gareth);
ResultsRow row3 = new ResultsRow();
row3.add(dawn);
ResultsRow row4 = new ResultsRow();
row4.add(keith);
ResultsRow row5 = new ResultsRow();
row5.add(lee);
os.addRow(row1);
os.addRow(row2);
os.addRow(row3);
os.addRow(row4);
os.addRow(row5);
PathQuery pq = new PathQuery(model);
pq.addViews("Employee.age", "Employee.name");
ExportResultsIterator iter = getIterator(pq);
JSONRowIterator jsonIter = new JSONRowIterator(iter, apiWithoutRedirection);
List<JSONArray> got = new ArrayList<JSONArray>();
for (JSONArray gotRow : new IteratorIterable<JSONArray>(jsonIter)) {
got.add(gotRow);
}
assertEquals(5, got.size());
for (int i = 0; i < jsonStrings.size(); i++) {
JSONArray jo = new JSONArray(jsonStrings.get(i));
assertEquals(null, JSONObjTester.getProblemsComparing(jo, got.get(i)));
}
}
public void testSingleObjectWithNestedCollections() throws Exception {
os.setResultsSize(4);
ResultsRow row = new ResultsRow();
row.add(wernhamHogg);
List sub1 = new ArrayList();
ResultsRow subRow1 = new ResultsRow();
subRow1.add(sales);
List sub2 = new ArrayList();
ResultsRow subRow2 = new ResultsRow();
subRow2.add(tim);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(gareth);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
subRow1 = new ResultsRow();
subRow1.add(distribution);
sub2 = new ArrayList();
subRow2 = new ResultsRow();
subRow2.add(lee);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(alex);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
row.add(sub1);
os.addRow(row);
PathQuery pq = new PathQuery(model);
pq.addViews("Company.name", "Company.vatNumber", "Company.departments.name", "Company.departments.employees.name");
pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER);
pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER);
ExportResultsIterator iter = getIterator(pq);
JSONRowIterator jsonIter = new JSONRowIterator(iter, apiWithoutRedirection);
List<JSONArray> got = new ArrayList<JSONArray>();
for (JSONArray gotRow : new IteratorIterable<JSONArray>(jsonIter)) {
got.add(gotRow);
}
assertEquals(got.size(), 4);
List<String> jsonStrings = new ArrayList<String>();
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 11, class: 'Department', value:'Sales',url:'/report.do?id=11'}," +
"{id: 5, class: 'Employee', value:'Tim Canterbury',url:'/report.do?id=5'}" +
"]");
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 11, class: 'Department', value:'Sales',url:'/report.do?id=11'}," +
"{id: 6, class: 'Employee', value:'Gareth Keenan',url:'/report.do?id=6'}" +
"]");
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 13, class: 'Department', value:'Warehouse',url:'/report.do?id=13'}," +
"{id: 9, class: 'Employee', value:'Lee',url:'/report.do?id=9'}" +
"]");
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 13, class: 'Department', value:'Warehouse',url:'/report.do?id=13'}," +
"{id: 10, class: 'Employee', value:'Alex',url:'/report.do?id=10'}" +
"]");
for (int index = 0; index < jsonStrings.size(); index++) {
JSONArray ja = new JSONArray(jsonStrings.get(index));
assertEquals(null, JSONObjTester.getProblemsComparing(ja, got.get(index)));
}
}
// Should be ok with a result set of size 0, and produce no objects
public void testZeroResults() throws ObjectStoreException {
PathQuery pq = new PathQuery(model);
pq.addViews(
"Employee.age", "Employee.name",
"Employee.department.name",
"Employee.department.manager.name",
"Employee.department.manager.address.address",
"Employee.department.manager.department.name",
"Employee.department.company.id",
"Employee.department.company.contractors.id",
"Employee.department.company.contractors.companys.name",
"Employee.department.company.contractors.companys.vatNumber",
"Employee.department.manager.department.company.name",
"Employee.department.company.contractors.companys.address.address");
ExportResultsIterator iter = getIterator(pq);
JSONRowIterator jsonIter = new JSONRowIterator(iter, apiWithoutRedirection);
assert(!jsonIter.hasNext());
}
public void testSingleObjectWithNestedCollectionsAndMultipleAttributes() throws Exception {
os.setResultsSize(1);
ResultsRow row = new ResultsRow();
row.add(wernhamHogg);
List sub1 = new ArrayList();
ResultsRow subRow1 = new ResultsRow();
subRow1.add(sales);
List sub2 = new ArrayList();
ResultsRow subRow2 = new ResultsRow();
subRow2.add(tim);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(gareth);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
subRow1 = new ResultsRow();
subRow1.add(distribution);
sub2 = new ArrayList();
subRow2 = new ResultsRow();
subRow2.add(lee);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(alex);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
row.add(sub1);
os.addRow(row);
PathQuery pq = new PathQuery(model);
pq.addViews("Company.name", "Company.vatNumber",
"Company.departments.name",
"Company.departments.employees.name",
"Company.departments.employees.age");
pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER);
pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER);
ExportResultsIterator iter = getIterator(pq);
JSONRowIterator jsonIter = new JSONRowIterator(iter, apiWithoutRedirection);
List<JSONArray> got = new ArrayList<JSONArray>();
for (JSONArray gotRow : new IteratorIterable<JSONArray>(jsonIter)) {
got.add(gotRow);
}
assertEquals(got.size(), 4);
List<String> jsonStrings = new ArrayList<String>();
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 11, class: 'Department', value:'Sales',url:'/report.do?id=11'}," +
"{id: 5, class: 'Employee', value:'Tim Canterbury',url:'/report.do?id=5'}," +
"{id: 5, class: 'Employee', value:'30',url:'/report.do?id=5'}" +
"]");
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 11, class: 'Department', value:'Sales',url:'/report.do?id=11'}," +
"{id: 6, class: 'Employee', value:'Gareth Keenan',url:'/report.do?id=6'}," +
"{id: 6, class: 'Employee', value:'32',url:'/report.do?id=6'}" +
"]");
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 13, class: 'Department', value:'Warehouse',url:'/report.do?id=13'}," +
"{id: 9, class: 'Employee', value:'Lee',url:'/report.do?id=9'}," +
"{id: 9, class: 'Employee', value:'28',url:'/report.do?id=9'}" +
"]");
jsonStrings.add(
"[" +
"{id: 1, class: 'Company', value:'Wernham-Hogg',url:'/report.do?id=1'}," +
"{id: 1, class: 'Company', value:101,url:'/report.do?id=1'}," +
"{id: 13, class: 'Department', value:'Warehouse',url:'/report.do?id=13'}," +
"{id: 10, class: 'Employee', value:'Alex',url:'/report.do?id=10'}," +
"{id: 10, class: 'Employee', value:'24',url:'/report.do?id=10'}" +
"]");
for (int index = 0; index < jsonStrings.size(); index++) {
JSONArray ja = new JSONArray(jsonStrings.get(index));
assertEquals(null, JSONObjTester.getProblemsComparing(ja, got.get(index)));
}
}
public void testRemove() throws ObjectStoreException {
ResultsRow row = new ResultsRow();
row.add(wernhamHogg);
PathQuery pq = new PathQuery(model);
pq.addViews("Company.name", "Company.vatNumber");
ExportResultsIterator iter = getIterator(pq);
JSONRowIterator jsonIter = new JSONRowIterator(iter, apiWithoutRedirection);
try {
jsonIter.remove();
fail("Expected an UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
}
}
}
| lgpl-2.1 |
Andrew0701/checkstyle | src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/AbstractParenPadCheck.java | 3502 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2014 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.whitespace;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.Utils;
import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck;
/**
* <p>Abstract class for checking the padding of parentheses. That is whether a
* space is required after a left parenthesis and before a right parenthesis,
* or such spaces are forbidden.
* </p>
* @author Oliver Burn
* @version 1.0
*/
abstract class AbstractParenPadCheck
extends AbstractOptionCheck<PadOption>
{
/**
* Sets the paren pad otion to nospace.
*/
AbstractParenPadCheck()
{
super(PadOption.NOSPACE, PadOption.class);
}
/**
* Process a token representing a left parentheses.
* @param aAST the token representing a left parentheses
*/
protected void processLeft(DetailAST aAST)
{
final String line = getLines()[aAST.getLineNo() - 1];
final int after = aAST.getColumnNo() + 1;
if (after < line.length()) {
if ((PadOption.NOSPACE == getAbstractOption())
&& (Character.isWhitespace(line.charAt(after))))
{
log(aAST.getLineNo(), after, "ws.followed", "(");
}
else if ((PadOption.SPACE == getAbstractOption())
&& !Character.isWhitespace(line.charAt(after))
&& (line.charAt(after) != ')'))
{
log(aAST.getLineNo(), after, "ws.notFollowed", "(");
}
}
}
/**
* Process a token representing a right parentheses.
* @param aAST the token representing a right parentheses
*/
protected void processRight(DetailAST aAST)
{
final String line = getLines()[aAST.getLineNo() - 1];
final int before = aAST.getColumnNo() - 1;
if (before >= 0) {
if ((PadOption.NOSPACE == getAbstractOption())
&& Character.isWhitespace(line.charAt(before))
&& !Utils.whitespaceBefore(before, line))
{
log(aAST.getLineNo(), before, "ws.preceded", ")");
}
else if ((PadOption.SPACE == getAbstractOption())
&& !Character.isWhitespace(line.charAt(before))
&& (line.charAt(before) != '('))
{
log(aAST.getLineNo(), aAST.getColumnNo(),
"ws.notPreceded", ")");
}
}
}
}
| lgpl-2.1 |
Qingbao/PasswdManagerAndroid | src/noconflict/org/bouncycastle/asn1/x509/qualified/RFC3739QCObjectIdentifiers.java | 478 | package noconflict.org.bouncycastle.asn1.x509.qualified;
import noconflict.org.bouncycastle.asn1.ASN1ObjectIdentifier;
public interface RFC3739QCObjectIdentifiers
{
//
// base id
//
static final ASN1ObjectIdentifier id_qcs = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.11");
static final ASN1ObjectIdentifier id_qcs_pkixQCSyntax_v1 = id_qcs.branch("1");
static final ASN1ObjectIdentifier id_qcs_pkixQCSyntax_v2 = id_qcs.branch("2");
}
| lgpl-2.1 |
tomazzupan/wildfly | testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/SFSBHibernate2LcacheStats.java | 6665 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate;
import static org.junit.Assert.assertEquals;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import javax.annotation.Resource;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.stat.Statistics;
import org.infinispan.manager.CacheContainer;
/**
* @author Madhumita Sadhukhan
*/
@Stateful
@TransactionManagement(TransactionManagementType.CONTAINER)
public class SFSBHibernate2LcacheStats {
private static SessionFactory sessionFactory;
/**
* Lookup the Infinispan cache container to start it.
* <p>
* We also could change the following line in standalone.xml: <cache-container name="hibernate" default-cache="local-query">
* To: <cache-container name="hibernate" default-cache="local-query" start="EAGER">
*/
private static final String CONTAINER_JNDI_NAME = "java:jboss/infinispan/container/hibernate";
@Resource(lookup = CONTAINER_JNDI_NAME)
private CacheContainer container;
public void cleanup() {
sessionFactory.close();
}
@TransactionAttribute(TransactionAttributeType.NEVER)
public void setupConfig() {
// static {
try {
// prepare the configuration
Configuration configuration = new Configuration().setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS,
"true");
configuration.getProperties().put(AvailableSettings.JTA_PLATFORM, JBossAppServerJtaPlatform.class);
configuration.getProperties().put(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta");
configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS");
// set property to enable statistics
configuration.setProperty("hibernate.generate_statistics", "true");
// fetch the properties
Properties properties = new Properties();
configuration = configuration.configure("hibernate.cfg.xml");
properties.putAll(configuration.getProperties());
Environment.verifyProperties(properties);
ConfigurationHelper.resolvePlaceHolders(properties);
// build the serviceregistry
sessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
//System.out.println("setupConfig: done");
}
// create planet
public Planet prepareData(String planetName, String galaxyName, String starName, Set<Satellite> satellites, Integer id) {
Session session = sessionFactory.openSession();
Planet planet = new Planet();
planet.setPlanetId(id);
planet.setPlanetName(planetName);
planet.setGalaxy(galaxyName);
planet.setStar(starName);
// Transaction trans = session.beginTransaction();
try {
session.save(planet);
if (satellites != null && satellites.size() > 0) {
Iterator<Satellite> itrSat = satellites.iterator();
while (itrSat.hasNext()) {
Satellite sat = itrSat.next();
session.save(sat);
}
planet.setSatellites(new HashSet<Satellite>());
planet.getSatellites().addAll(satellites);
}
session.saveOrUpdate(planet);
SessionStatistics stats = session.getStatistics();
assertEquals(2, stats.getEntityKeys().size());
assertEquals(2, stats.getEntityCount());
// session.flush();
// session.close();
} catch (Exception e) {
throw new RuntimeException("transactional failure while persisting planet entity", e);
}
// trans.commit();
session.close();
return planet;
}
// fetch planet
public Planet getPlanet(Integer id) {
Planet planet = sessionFactory.openSession().get(Planet.class, id);
return planet;
}
// fetch satellites
public boolean isSatellitesPresentInCache(Integer id) {
boolean indicator = sessionFactory.getCache().containsCollection(
org.jboss.as.test.integration.hibernate.Planet.class.getName() + ".satellites", id);
return indicator;
}
// fetch statistics
public Statistics getStatistics() {
Statistics sessionStats = sessionFactory.getStatistics();
return sessionStats;
}
// fetch statistics after eviction of collection from cache
public Statistics getStatisticsAfterEviction() {
sessionFactory.getCache().evictCollection(
org.jboss.as.test.integration.hibernate.Planet.class.getName() + ".satellites", new Integer(1));
Statistics sessionStats = sessionFactory.getStatistics();
return sessionStats;
}
}
| lgpl-2.1 |
yuan39/TuxGuitar | TuxGuitar/src/org/herac/tuxguitar/app/system/plugins/base/TGToolItemPlugin.java | 1926 | package org.herac.tuxguitar.app.system.plugins.base;
import org.herac.tuxguitar.app.TuxGuitar;
import org.herac.tuxguitar.app.actions.Action;
import org.herac.tuxguitar.app.actions.ActionData;
import org.herac.tuxguitar.app.system.plugins.TGPluginException;
import org.herac.tuxguitar.app.tools.custom.TGCustomTool;
import org.herac.tuxguitar.app.tools.custom.TGCustomToolManager;
public abstract class TGToolItemPlugin extends TGPluginAdapter{
private boolean loaded;
private TGCustomTool tool;
private TGCustomToolAction toolAction;
protected abstract void doAction();
protected abstract String getItemName() throws TGPluginException ;
public void init() throws TGPluginException {
String name = getItemName();
this.tool = new TGCustomTool(name,name);
this.toolAction = new TGCustomToolAction(this.tool.getName());
}
public void close() throws TGPluginException {
this.removePlugin();
}
public void setEnabled(boolean enabled) throws TGPluginException {
if(enabled){
addPlugin();
}else{
removePlugin();
}
}
protected void addPlugin() throws TGPluginException {
if(!this.loaded){
TuxGuitar.instance().getActionManager().addAction(this.toolAction);
TGCustomToolManager.instance().addCustomTool(this.tool);
TuxGuitar.instance().getItemManager().createMenu();
this.loaded = true;
}
}
protected void removePlugin() throws TGPluginException {
if(this.loaded){
TGCustomToolManager.instance().removeCustomTool(this.tool);
TuxGuitar.instance().getActionManager().removeAction(this.tool.getAction());
TuxGuitar.instance().getItemManager().createMenu();
this.loaded = false;
}
}
protected class TGCustomToolAction extends Action{
public TGCustomToolAction(String name) {
super(name, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | KEY_BINDING_AVAILABLE);
}
protected int execute(ActionData actionData) {
doAction();
return 0;
}
}
} | lgpl-2.1 |
Techern/carpentersblocks | src/main/java/com/carpentersblocks/renderer/BlockHandlerBase.java | 33980 | package com.carpentersblocks.renderer;
import net.minecraft.block.Block;
import net.minecraft.block.BlockGrass;
import net.minecraft.block.BlockRailBase;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.common.util.ForgeDirection;
import org.lwjgl.opengl.GL11;
import com.carpentersblocks.block.BlockCoverable;
import com.carpentersblocks.data.Slope;
import com.carpentersblocks.renderer.helper.LightingHelper;
import com.carpentersblocks.renderer.helper.RenderHelper;
import com.carpentersblocks.renderer.helper.RoutableFluidsHelper;
import com.carpentersblocks.renderer.helper.VertexHelper;
import com.carpentersblocks.tileentity.TEBase;
import com.carpentersblocks.util.BlockProperties;
import com.carpentersblocks.util.handler.DesignHandler;
import com.carpentersblocks.util.handler.DyeHandler;
import com.carpentersblocks.util.handler.OptifineHandler;
import com.carpentersblocks.util.handler.OverlayHandler;
import com.carpentersblocks.util.handler.OverlayHandler.Overlay;
import com.carpentersblocks.util.registry.FeatureRegistry;
import com.carpentersblocks.util.registry.IconRegistry;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class BlockHandlerBase implements ISimpleBlockRenderingHandler {
public static final int PASS_OPAQUE = 0;
public static final int PASS_ALPHA = 1;
public static final int DOWN = 0;
public static final int UP = 1;
public static final int NORTH = 2;
public static final int SOUTH = 3;
public static final int WEST = 4;
public static final int EAST = 5;
public Tessellator tessellator = Tessellator.instance;
public RenderBlocks renderBlocks;
public LightingHelper lightingHelper;
public Block srcBlock;
public TEBase TE;
public boolean suppressOverlay;
public boolean suppressChiselDesign;
public boolean suppressDyeColor;
public boolean disableAO;
public boolean hasDyeOverride;
public int dyeOverride;
public boolean[] hasIconOverride = new boolean[6];
public IIcon[] iconOverride = new IIcon[6];
public int renderPass;
/** 0-5 are side covers, with 6 being the block itself. */
public int coverRendering = 6;
@Override
public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderBlocks)
{
Tessellator tessellator = Tessellator.instance;
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
tessellator.startDrawingQuads();
if (block instanceof BlockCoverable) {
IIcon icon = renderBlocks.getIconSafe(((BlockCoverable)block).getIcon());
tessellator.setNormal(0.0F, -1.0F, 0.0F);
renderBlocks.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, icon);
tessellator.setNormal(0.0F, 1.0F, 0.0F);
renderBlocks.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, icon);
tessellator.setNormal(0.0F, 0.0F, -1.0F);
renderBlocks.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, icon);
tessellator.setNormal(0.0F, 0.0F, 1.0F);
renderBlocks.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, icon);
tessellator.setNormal(-1.0F, 0.0F, 0.0F);
renderBlocks.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, icon);
tessellator.setNormal(1.0F, 0.0F, 0.0F);
renderBlocks.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, icon);
} else {
tessellator.setNormal(0.0F, -1.0F, 0.0F);
renderBlocks.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, renderBlocks.getIconSafe(block.getIcon(0, metadata)));
tessellator.setNormal(0.0F, 1.0F, 0.0F);
renderBlocks.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, renderBlocks.getIconSafe(block.getIcon(1, metadata)));
tessellator.setNormal(0.0F, 0.0F, -1.0F);
renderBlocks.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, renderBlocks.getIconSafe(block.getIcon(2, metadata)));
tessellator.setNormal(0.0F, 0.0F, 1.0F);
renderBlocks.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, renderBlocks.getIconSafe(block.getIcon(3, metadata)));
tessellator.setNormal(-1.0F, 0.0F, 0.0F);
renderBlocks.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, renderBlocks.getIconSafe(block.getIcon(4, metadata)));
tessellator.setNormal(1.0F, 0.0F, 0.0F);
renderBlocks.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, renderBlocks.getIconSafe(block.getIcon(5, metadata)));
}
tessellator.draw();
GL11.glTranslatef(0.5F, 0.5F, 0.5F);
GL11.glRotatef(90.0F, 0.0F, -1.0F, 0.0F);
}
@Override
public boolean renderWorldBlock(IBlockAccess blockAccess, int x, int y, int z, Block block, int modelID, RenderBlocks renderBlocks)
{
VertexHelper.vertexCount = 0;
renderPass = MinecraftForgeClient.getRenderPass();
TileEntity TE_default = blockAccess.getTileEntity(x, y, z);
if (TE_default != null && TE_default instanceof TEBase) {
TE = (TEBase) TE_default;
srcBlock = block;
this.renderBlocks = renderBlocks;
lightingHelper = new LightingHelper(renderBlocks);
renderCarpentersBlock(x, y, z);
renderSideBlocks(x, y, z);
if (FeatureRegistry.enableRoutableFluids) {
VertexHelper.vertexCount += RoutableFluidsHelper.render(TE, renderBlocks, x, y, z) ? 4 : 0;
}
if (FeatureRegistry.enableRailSlopes)
{
Block blockYP = blockAccess.getBlock(x, y + 1, z);
if (blockAccess.isSideSolid(x, y, z, ForgeDirection.UP, false) && blockYP instanceof BlockRailBase)
{
int metadata = ((BlockRailBase)blockYP).getBasicRailMetadata(blockAccess, null, x, y + 1, z);
BlockHandlerCarpentersSlope slopeHandler = new BlockHandlerCarpentersSlope();
slopeHandler.renderBlocks = this.renderBlocks;
slopeHandler.TE = TE;
slopeHandler.lightingHelper = lightingHelper;
slopeHandler.srcBlock = srcBlock;
slopeHandler.suppressOverlay = true;
switch (metadata)
{
case 2: // Sloping down -X (West)
slopeHandler.renderSlope(getCoverForRendering(TE), Slope.WEDGE_POS_W, x, y + 1, z, true);
break;
case 3: // Sloping down +X (East)
slopeHandler.renderSlope(getCoverForRendering(TE), Slope.WEDGE_POS_E, x, y + 1, z, true);
break;
case 4: // Sloping down +Z (South)
slopeHandler.renderSlope(getCoverForRendering(TE), Slope.WEDGE_POS_S, x, y + 1, z, true);
break;
case 5: // Sloping down -Z (North)
slopeHandler.renderSlope(getCoverForRendering(TE), Slope.WEDGE_POS_N, x, y + 1, z, true);
break;
default: {}
}
}
}
}
return VertexHelper.vertexCount > 0;
}
@Override
public boolean shouldRender3DInInventory(int modelId)
{
return true;
}
@Override
public int getRenderId()
{
return 0;
}
/**
* For South-facing block, sets render bounds, rotates them and renders.
*/
protected void renderBlockWithRotation(ItemStack itemStack, int x, int y, int z, double xMin, double yMin, double zMin, double xMax, double yMax, double zMax, ForgeDirection ... dir)
{
renderBlocks.setRenderBounds(xMin, yMin, zMin, xMax, yMax, zMax);
for (ForgeDirection rot : dir) {
rotateBounds(renderBlocks, rot);
}
renderBlock(itemStack, x, y, z);
}
/**
* For South-facing blocks, rotates bounds for a single directional input.
*/
protected void rotateBounds(RenderBlocks renderBlocks, ForgeDirection dir)
{
switch (dir) {
case DOWN:
renderBlocks.setRenderBounds(
renderBlocks.renderMinX,
1.0D - renderBlocks.renderMaxZ,
renderBlocks.renderMinY,
renderBlocks.renderMaxX,
1.0D - renderBlocks.renderMinZ,
renderBlocks.renderMaxY
);
break;
case UP:
renderBlocks.setRenderBounds(
renderBlocks.renderMinX,
renderBlocks.renderMinZ,
renderBlocks.renderMinY,
renderBlocks.renderMaxX,
renderBlocks.renderMaxZ,
renderBlocks.renderMaxY
);
break;
case NORTH:
renderBlocks.setRenderBounds(
1.0D - renderBlocks.renderMaxX,
renderBlocks.renderMinY,
1.0D - renderBlocks.renderMaxZ,
1.0D - renderBlocks.renderMinX,
renderBlocks.renderMaxY,
1.0D - renderBlocks.renderMinZ
);
break;
case EAST:
renderBlocks.setRenderBounds(
renderBlocks.renderMinZ,
renderBlocks.renderMinY,
1.0D - renderBlocks.renderMaxX,
renderBlocks.renderMaxZ,
renderBlocks.renderMaxY,
1.0D - renderBlocks.renderMinX
);
break;
case WEST:
renderBlocks.setRenderBounds(
1.0D - renderBlocks.renderMaxZ,
renderBlocks.renderMinY,
renderBlocks.renderMinX,
1.0D - renderBlocks.renderMinZ,
renderBlocks.renderMaxY,
renderBlocks.renderMaxX
);
break;
default: {}
}
}
/**
* Gets cover {@link ItemStack} suitable for pulling block textures
* from, regardless if it has an {@link NBTTagCompound}.
*
* @param TE [optional] the {@link TEBase}, if not {@link #srcBlock}
* @return the {@link ItemStack}
*/
protected ItemStack getCoverForRendering(TEBase ... TE)
{
TEBase temp = TE.length == 0 ? this.TE : TE[0];
return BlockProperties.getCoverSafe(temp, coverRendering);
}
/**
* Sets texture rotation for side.
*/
protected void setTextureRotation(int side, int rotation)
{
switch (side)
{
case DOWN:
renderBlocks.uvRotateBottom = rotation;
break;
case UP:
renderBlocks.uvRotateTop = rotation;
break;
case NORTH:
renderBlocks.uvRotateNorth = rotation;
break;
case SOUTH:
renderBlocks.uvRotateSouth = rotation;
break;
case WEST:
renderBlocks.uvRotateWest = rotation;
break;
default:
renderBlocks.uvRotateEast = rotation;
break;
}
}
/**
* Sets directional block side rotation in RenderBlocks for
* directional blocks like pillars and logs.
*/
protected void setTextureRotationForDirectionalBlock(int side)
{
int metadata = getCoverForRendering().getItemDamage();
int dir = metadata & 12;
switch (side)
{
case DOWN:
if (metadata == 3 || dir == 4) {
renderBlocks.uvRotateBottom = 1;
}
break;
case UP:
if (metadata == 3 || dir == 4) {
renderBlocks.uvRotateTop = 1;
}
break;
case NORTH:
if (metadata == 3 || dir == 4) {
renderBlocks.uvRotateNorth = 1;
}
break;
case SOUTH:
if (metadata == 3 || dir == 4) {
renderBlocks.uvRotateSouth = 1;
}
break;
case WEST:
if (metadata == 3 || dir == 8) {
renderBlocks.uvRotateWest = 1;
}
break;
case EAST:
if (metadata == 3 || dir == 8) {
renderBlocks.uvRotateEast = 1;
}
break;
}
}
/**
* Resets side rotation in RenderBlocks back to default values.
*/
protected void resetTextureRotation(int side)
{
switch (side)
{
case DOWN:
renderBlocks.uvRotateBottom = 0;
break;
case UP:
renderBlocks.uvRotateTop = 0;
break;
case NORTH:
renderBlocks.uvRotateNorth = 0;
break;
case SOUTH:
renderBlocks.uvRotateSouth = 0;
break;
case WEST:
renderBlocks.uvRotateWest = 0;
break;
case EAST:
renderBlocks.uvRotateEast = 0;
break;
}
}
/**
* Returns texture rotation for side.
*/
protected int getTextureRotation(int side)
{
int[] rotations = {
renderBlocks.uvRotateBottom,
renderBlocks.uvRotateTop,
renderBlocks.uvRotateNorth,
renderBlocks.uvRotateSouth,
renderBlocks.uvRotateWest,
renderBlocks.uvRotateEast
};
return rotations[side];
}
/**
* Sets dye override.
*/
protected void setDyeOverride(int color)
{
hasDyeOverride = true;
dyeOverride = color;
}
/**
* Clears dye override.
*/
protected void clearDyeOverride()
{
hasDyeOverride = false;
}
/**
* Sets icon override.
* Using side 6 overrides all sides.
* RenderBlocks' icon override will override this one
* when breaking animation is played.
*/
protected void setIconOverride(int side, IIcon icon)
{
if (side == 6) {
for (int count = 0; count < 6; ++count) {
hasIconOverride[count] = true;
iconOverride[count] = icon;
}
} else {
hasIconOverride[side] = true;
iconOverride[side] = icon;
}
}
/**
* Clears icon override.
*/
protected void clearIconOverride(int side)
{
if (side == 6) {
for (int count = 0; count < 6; ++count) {
hasIconOverride[count] = false;
}
} else {
hasIconOverride[side] = false;
}
}
/**
* Sets up side cover rendering bounds.
* Will return block location where side cover should be rendered.
*/
protected int[] getSideCoverRenderBounds(int x, int y, int z, int side)
{
double offset = 1.0D / 16.0D;
/*
* Make snow match vanilla snow depth for continuity.
*/
if (side == UP)
{
Block block = BlockProperties.toBlock(getCoverForRendering());
if (block.equals(Blocks.snow) || block.equals(Blocks.snow_layer)) {
offset = 1.0D / 8.0D;
}
}
/*
* Adjust bounds of side cover to accommodate
* partial rendered blocks (slabs, stair steps)
*/
switch (side) {
case DOWN:
if (renderBlocks.renderMinY > 0.0D) {
renderBlocks.renderMaxY = renderBlocks.renderMinY;
renderBlocks.renderMinY -= offset;
} else {
renderBlocks.renderMaxY = 1.0D;
renderBlocks.renderMinY = renderBlocks.renderMaxY - offset;
y -= 1;
}
break;
case UP:
if (renderBlocks.renderMaxY < 1.0D) {
renderBlocks.renderMinY = renderBlocks.renderMaxY;
renderBlocks.renderMaxY += offset;
} else {
renderBlocks.renderMaxY = offset;
renderBlocks.renderMinY = 0.0D;
y += 1;
}
break;
case NORTH:
if (renderBlocks.renderMinZ > 0.0D) {
renderBlocks.renderMaxZ = renderBlocks.renderMinZ;
renderBlocks.renderMinZ -= offset;
} else {
renderBlocks.renderMaxZ = 1.0D;
renderBlocks.renderMinZ = renderBlocks.renderMaxZ - offset;
z -= 1;
}
break;
case SOUTH:
if (renderBlocks.renderMaxZ < 1.0D) {
renderBlocks.renderMinZ = renderBlocks.renderMaxZ;
renderBlocks.renderMaxZ += offset;
} else {
renderBlocks.renderMaxZ = offset;
renderBlocks.renderMinZ = 0.0D;
z += 1;
}
break;
case WEST:
if (renderBlocks.renderMinX > 0.0D) {
renderBlocks.renderMaxX = renderBlocks.renderMinX;
renderBlocks.renderMinX -= offset;
} else {
renderBlocks.renderMaxX = 1.0D;
renderBlocks.renderMinX = renderBlocks.renderMaxX - offset;
x -= 1;
}
break;
case EAST:
if (renderBlocks.renderMaxX < 1.0D) {
renderBlocks.renderMinX = renderBlocks.renderMaxX;
renderBlocks.renderMaxX += offset;
} else {
renderBlocks.renderMaxX = offset;
renderBlocks.renderMinX = 0.0D;
x += 1;
}
break;
}
return new int[] { x, y, z };
}
/**
* Renders side covers.
*/
protected void renderSideBlocks(int x, int y, int z)
{
renderBlocks.renderAllFaces = true;
srcBlock.setBlockBoundsBasedOnState(renderBlocks.blockAccess, x, y, z);
for (int side = 0; side < 6; ++side)
{
if (TE.hasAttribute(TE.ATTR_COVER[side]))
{
coverRendering = side;
int[] renderOffset = getSideCoverRenderBounds(x, y, z, side);
renderBlock(getCoverForRendering(), renderOffset[0], renderOffset[1], renderOffset[2]);
renderBlocks.setRenderBoundsFromBlock(srcBlock);
}
}
renderBlocks.renderAllFaces = false;
coverRendering = 6;
}
/**
* Override to provide custom icons.
*/
protected IIcon getUniqueIcon(ItemStack itemStack, int side, IIcon icon)
{
return icon;
}
/**
* Returns icon for face.
*/
protected IIcon getIcon(ItemStack itemStack, int side)
{
BlockProperties.prepareItemStackForRendering(itemStack);
IIcon icon = renderBlocks.getIconSafe(getUniqueIcon(itemStack, side, BlockProperties.toBlock(itemStack).getIcon(side, itemStack.getItemDamage())));
if (hasIconOverride[side]) {
icon = renderBlocks.getIconSafe(iconOverride[side]);
}
return icon;
}
/**
* Renders multiple textures to side.
*/
protected void renderMultiTexturedSide(ItemStack itemStack, int x, int y, int z, int side)
{
Block block = BlockProperties.toBlock(itemStack);
boolean renderCover = (block instanceof BlockCoverable ? renderPass == 0 : block.canRenderInPass(renderPass));
boolean hasDesign = TE.hasChiselDesign(coverRendering);
boolean hasOverlay = TE.hasAttribute(TE.ATTR_OVERLAY[coverRendering]);
double overlayOffset = 0.0D;
if (hasOverlay) {
if (hasDesign) {
overlayOffset = RenderHelper.OFFSET_MAX;
} else if (renderPass == PASS_OPAQUE && block.getRenderBlockPass() == PASS_ALPHA && !(block instanceof BlockCoverable)) {
overlayOffset = RenderHelper.OFFSET_MIN;
}
}
/* Render side */
if (renderCover) {
int tempRotation = getTextureRotation(side);
if (BlockProperties.blockRotates(itemStack)) {
setTextureRotationForDirectionalBlock(side);
}
setColorAndRender(itemStack, x, y, z, side, getIcon(itemStack, side));
setTextureRotation(side, tempRotation);
}
/* Render BlockGrass side overlay here, if needed. */
if (renderPass == PASS_OPAQUE && block.equals(Blocks.grass) && side > 0 && !isPositiveFace(side)) {
if (Minecraft.isFancyGraphicsEnabled()) {
setColorAndRender(new ItemStack(Blocks.grass), x, y, z, side, BlockGrass.getIconSideOverlay());
} else {
setColorAndRender(new ItemStack(Blocks.dirt), x, y, z, side, IconRegistry.icon_overlay_fast_grass_side);
}
}
boolean temp_dye_state = suppressDyeColor;
suppressDyeColor = true;
if (hasDesign && !suppressChiselDesign && renderPass == PASS_ALPHA) {
RenderHelper.setOffset(RenderHelper.OFFSET_MIN);
renderChiselDesign(x, y, z, side);
RenderHelper.clearOffset();
}
if (hasOverlay && !suppressOverlay && renderPass == PASS_OPAQUE) {
RenderHelper.setOffset(overlayOffset);
renderOverlay(x, y, z, side);
RenderHelper.clearOffset();
}
suppressDyeColor = temp_dye_state;
}
/**
* Sets side icon, draws any attributes needed, and hands to appropriate render method.
* This will bypass typical draw behavior if breaking animation is being drawn.
*/
protected void delegateSideRender(ItemStack itemStack, int x, int y, int z, int side)
{
/*
* A texture override in the context of this mod indicates the breaking
* animation is being drawn. If this is the case, draw side without
* decorations. Can also check icon name for beginsWith("destroy_stage_").
*/
if (renderBlocks.hasOverrideBlockTexture()) {
setColorAndRender(itemStack, x, y, z, side, renderBlocks.overrideBlockTexture);
} else {
renderMultiTexturedSide(itemStack, x, y, z, side);
}
}
/**
* Renders overlay on side.
*/
protected void renderOverlay(int x, int y, int z, int side)
{
side = isPositiveFace(side) ? 1 : side;
Overlay overlay = OverlayHandler.getOverlayType(TE.getAttribute(TE.ATTR_OVERLAY[coverRendering]));
IIcon icon = OverlayHandler.getOverlayIcon(overlay, side);
if (icon != null) {
setColorAndRender(overlay.getItemStack(), x, y, z, side, icon);
}
}
/**
* Renders chisel design on side.
*/
protected void renderChiselDesign(int x, int y, int z, int side)
{
String design = TE.getChiselDesign(coverRendering);
IIcon icon = renderBlocks.getIconSafe(IconRegistry.icon_design_chisel.get(DesignHandler.listChisel.indexOf(design)));
setColorAndRender(new ItemStack(Blocks.glass), x, y, z, side, icon);
}
/**
* Sets color, lightness, and brightness in {@link LightingHelper} and
* renders side.
* <p>
* Also calls {@link VertexHelper#postRender} and thus cannot be overridden.
*
* @param itemStack the cover ItemStack
* @param block the block inside the ItemStack
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @param side the side currently being worked on
* @param icon the icon for the side
* @return nothing
*/
public final void setColorAndRender(ItemStack itemStack, int x, int y, int z, int side, IIcon icon)
{
int color = getBlockColor(BlockProperties.toBlock(itemStack), itemStack.getItemDamage(), x, y, z, side, icon);
if (!suppressDyeColor && (TE.hasAttribute(TE.ATTR_DYE[coverRendering]) || hasDyeOverride)) {
color = hasDyeOverride ? dyeOverride : DyeHandler.getColor(TE.getAttribute(TE.ATTR_DYE[coverRendering]));
}
lightingHelper.setupColor(x, y, z, side, color, icon);
render(x, y, z, side, icon);
VertexHelper.postRender();
}
/**
* Returns a integer with hex for 0xrrggbb for block. Color is most
* commonly different for {@link Blocks#grass}
* <p>
* If using our custom render helpers, be sure to use {@link #applyAnaglyph(float[])}.
*
* @param itemStack the cover {@link ItemStack}
* @param block the {@link Block} inside the {@link ItemStack}
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @return a integer with hex for 0xrrggbb
*/
public int getBlockColor(Block block, int metadata, int x, int y, int z, int side, IIcon icon)
{
if (block.hasTileEntity(metadata)) {
block = Blocks.dirt;
}
TE.setMetadata(metadata);
int color = OptifineHandler.enableOptifineIntegration ? OptifineHandler.getColorMultiplier(block, TE.getWorldObj(), x, y, z) : block.colorMultiplier(TE.getWorldObj(), x, y, z);
TE.restoreMetadata();
if (block.equals(Blocks.grass) && !isPositiveFace(side) && !icon.equals(BlockGrass.getIconSideOverlay())) {
color = 16777215;
}
return color;
}
/**
* Returns whether side is considered a top face.
*
* @param TE the {@link TEBase}
* @param block the {@link Block}
* @param side the side
* @param icon the {@link IIcon}
* @return true if positive y face
*/
protected boolean isPositiveFace(int side)
{
return side == 1;
}
/**
* Renders a side.
*
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @param side the side currently being worked on
* @param icon the icon for the side
* @return nothing
*/
protected void render(int x, int y, int z, int side, IIcon icon)
{
switch (side) {
case DOWN:
RenderHelper.renderFaceYNeg(renderBlocks, x, y, z, icon);
break;
case UP:
RenderHelper.renderFaceYPos(renderBlocks, x, y, z, icon);
break;
case NORTH:
RenderHelper.renderFaceZNeg(renderBlocks, x, y, z, icon);
break;
case SOUTH:
RenderHelper.renderFaceZPos(renderBlocks, x, y, z, icon);
break;
case WEST:
RenderHelper.renderFaceXNeg(renderBlocks, x, y, z, icon);
break;
case EAST:
RenderHelper.renderFaceXPos(renderBlocks, x, y, z, icon);
break;
}
}
/**
* Renders single-sided face using current render bounds.
* <p>
* This is needed for panes and screens, and will render if current
* render pass and {@link FeatureRegistry#enableAlphaPanes} are compatible.
*/
protected void renderPane(IIcon icon, int x, int y, int z, ForgeDirection facing, boolean enableAO, boolean flipped)
{
if (renderPass == PASS_OPAQUE ? !FeatureRegistry.enableAlphaPanes : FeatureRegistry.enableAlphaPanes)
{
doLightAndRenderSide(icon, x, y, z, facing, enableAO);
if (flipped) {
doLightAndRenderSide(icon, x, y, z, facing.getOpposite(), enableAO);
}
}
}
/**
* Lights and renders a side.
* <p>
* Used primarily for rendering panes to help cut down on code.
*
* @param icon
* @param x
* @param y
* @param z
* @param facing
*/
private void doLightAndRenderSide(IIcon icon, int x, int y, int z, ForgeDirection facing, boolean enableAO)
{
ItemStack itemStack = new ItemStack(Blocks.glass);
int blockColor = getBlockColor(Blocks.glass, 0, x, y, z, facing.ordinal(), null);
boolean hasAO = renderBlocks.enableAO;
renderBlocks.enableAO = enableAO;
switch (facing)
{
case DOWN:
lightingHelper.setupLightingYNeg(itemStack, x, y, z);
lightingHelper.setupColor(x, y, z, facing.ordinal(), blockColor, null);
RenderHelper.renderFaceYNeg(renderBlocks, x, y, z, icon);
break;
case UP:
lightingHelper.setupLightingYPos(itemStack, x, y, z);
lightingHelper.setupColor(x, y, z, facing.ordinal(), blockColor, null);
RenderHelper.renderFaceYPos(renderBlocks, x, y, z, icon);
break;
case NORTH:
lightingHelper.setupLightingZNeg(itemStack, x, y, z);
lightingHelper.setupColor(x, y, z, facing.ordinal(), blockColor, null);
RenderHelper.renderFaceZNeg(renderBlocks, x, y, z, icon);
break;
case SOUTH:
lightingHelper.setupLightingZPos(itemStack, x, y, z);
lightingHelper.setupColor(x, y, z, facing.ordinal(), blockColor, null);
RenderHelper.renderFaceZPos(renderBlocks, x, y, z, icon);
break;
case WEST:
lightingHelper.setupLightingXNeg(itemStack, x, y, z);
lightingHelper.setupColor(x, y, z, facing.ordinal(), blockColor, null);
RenderHelper.renderFaceXNeg(renderBlocks, x, y, z, icon);
break;
case EAST:
lightingHelper.setupLightingXPos(itemStack, x, y, z);
lightingHelper.setupColor(x, y, z, facing.ordinal(), blockColor, null);
RenderHelper.renderFaceXPos(renderBlocks, x, y, z, icon);
break;
default: {}
}
renderBlocks.enableAO = hasAO;
}
/**
* Blocks override this in order to render everything they need.
*/
protected void renderCarpentersBlock(int x, int y, int z)
{
renderBlock(getCoverForRendering(), x, y, z);
}
/**
* Sets renderBlocks enableAO state to true depending on
* rendering environment and block requirements.
*/
public boolean getEnableAO(ItemStack itemStack)
{
Block block = BlockProperties.toBlock(itemStack);
return Minecraft.isAmbientOcclusionEnabled() && !disableAO && block.getLightValue() == 0;
}
/**
* Renders block.
* Coordinates may change since side covers render here.
*/
protected void renderBlock(ItemStack itemStack, int x, int y, int z)
{
if (BlockProperties.toBlock(itemStack) == null) {
return;
}
renderBlocks.enableAO = getEnableAO(itemStack);
if (renderBlocks.renderAllFaces || srcBlock.shouldSideBeRendered(TE.getWorldObj(), x, y - 1, z, DOWN) || renderBlocks.renderMinY > 0.0D)
{
lightingHelper.setupLightingYNeg(itemStack, x, y, z);
delegateSideRender(itemStack, x, y, z, DOWN);
}
if (renderBlocks.renderAllFaces || srcBlock.shouldSideBeRendered(TE.getWorldObj(), x, y + 1, z, UP) || renderBlocks.renderMaxY < 1.0D)
{
lightingHelper.setupLightingYPos(itemStack, x, y, z);
delegateSideRender(itemStack, x, y, z, UP);
}
if (renderBlocks.renderAllFaces || srcBlock.shouldSideBeRendered(TE.getWorldObj(), x, y, z - 1, NORTH) || renderBlocks.renderMinZ > 0.0D)
{
lightingHelper.setupLightingZNeg(itemStack, x, y, z);
delegateSideRender(itemStack, x, y, z, NORTH);
}
if (renderBlocks.renderAllFaces || srcBlock.shouldSideBeRendered(TE.getWorldObj(), x, y, z + 1, SOUTH) || renderBlocks.renderMaxZ < 1.0D)
{
lightingHelper.setupLightingZPos(itemStack, x, y, z);
delegateSideRender(itemStack, x, y, z, SOUTH);
}
if (renderBlocks.renderAllFaces || srcBlock.shouldSideBeRendered(TE.getWorldObj(), x - 1, y, z, WEST) || renderBlocks.renderMinX > 0.0D)
{
lightingHelper.setupLightingXNeg(itemStack, x, y, z);
delegateSideRender(itemStack, x, y, z, WEST);
}
if (renderBlocks.renderAllFaces || srcBlock.shouldSideBeRendered(TE.getWorldObj(), x + 1, y, z, EAST) || renderBlocks.renderMaxX < 1.0D)
{
lightingHelper.setupLightingXPos(itemStack, x, y, z);
delegateSideRender(itemStack, x, y, z, EAST);
}
renderBlocks.enableAO = false;
}
}
| lgpl-2.1 |
sharang108/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanExpressionCheckTest.java | 2656 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import static com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanExpressionCheck.MSG_KEY;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
public class SimplifyBooleanExpressionCheckTest
extends BaseCheckTestSupport {
@Override
protected String getPath(String filename) throws IOException {
return super.getPath("checks" + File.separator
+ "coding" + File.separator
+ "simplifybooleanexpression" + File.separator
+ filename);
}
@Test
public void testIt() throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(SimplifyBooleanExpressionCheck.class);
final String[] expected = {
"20:18: " + getCheckMessage(MSG_KEY),
"41:36: " + getCheckMessage(MSG_KEY),
"42:36: " + getCheckMessage(MSG_KEY),
"43:16: " + getCheckMessage(MSG_KEY),
"43:32: " + getCheckMessage(MSG_KEY),
};
verify(checkConfig, getPath("InputSimplifyBooleanExpression.java"), expected);
}
@Test
public void testTokensNotNull() {
final SimplifyBooleanExpressionCheck check = new SimplifyBooleanExpressionCheck();
Assert.assertNotNull(check.getAcceptableTokens());
Assert.assertNotNull(check.getDefaultTokens());
Assert.assertNotNull(check.getRequiredTokens());
}
}
| lgpl-2.1 |
pombredanne/jna | src/com/sun/jna/Union.java | 9988 | /* Copyright (c) 2007-2012 Timothy Wall, All Rights Reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package com.sun.jna;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.lang.reflect.Field;
/** Represents a native union. When writing to native memory, the field
* corresponding to the type passed to {@link #setType} will be written
* to native memory. Upon reading from native memory, Structure, String,
* or WString fields will <em>not</em> be initialized unless they are
* the current field as identified by a call to {@link #setType}. The current
* field is always unset by default to avoid accidentally attempting to read
* a field that is not valid. In the case of a String, for instance, an
* invalid pointer may result in a memory fault when attempting to initialize
* the String.
*/
public abstract class Union extends Structure {
private StructField activeField;
StructField biggestField;
/** Create a Union whose size and alignment will be calculated
* automatically.
*/
protected Union() { }
/** Create a Union of the given size, using default alignment. */
protected Union(Pointer p) {
super(p);
}
/** Create a Union of the given size and alignment type. */
protected Union(Pointer p, int alignType) {
super(p, alignType);
}
/** Create a Union of the given size and alignment type. */
protected Union(TypeMapper mapper) {
super(mapper);
}
/** Create a Union of the given size and alignment type. */
protected Union(Pointer p, int alignType, TypeMapper mapper) {
super(p, alignType, mapper);
}
/** Invalid operation on unions. */
protected void setFieldOrder(String[] fields) {
throw new RuntimeException("Unions do not need to specify field order");
}
/** Unions do not need a field order, so automatically provide a value to
* satisfy checking in the Structure superclass.
*/
protected List getFieldOrder() {
List flist = getFieldList();
ArrayList list = new ArrayList();
for (Iterator i=flist.iterator();i.hasNext();) {
Field f = (Field)i.next();
list.add(f.getName());
}
return list;
}
/** Indicates by type which field will be used to write to native memory.
* If there are multiple fields of the same type, use {@link
* #setType(String)} instead with the field name.
* @throws IllegalArgumentException if the type does not correspond to
* any declared union field.
*/
public void setType(Class type) {
ensureAllocated();
for (Iterator i=fields().values().iterator();i.hasNext();) {
StructField f = (StructField)i.next();
if (f.type == type) {
activeField = f;
return;
}
}
throw new IllegalArgumentException("No field of type " + type + " in " + this);
}
/**
* Indicates which field will be used to write to native memory.
* @throws IllegalArgumentException if the name does not correspond to
* any declared union field.
*/
public void setType(String fieldName) {
ensureAllocated();
StructField f = (StructField) fields().get(fieldName);
if (f != null) {
activeField = f;
}
else {
throw new IllegalArgumentException("No field named " + fieldName
+ " in " + this);
}
}
/** Force a read of the given field from native memory.
* @return the new field value, after updating
* @throws IllegalArgumentException if no field exists with the given name
*/
public Object readField(String fieldName) {
ensureAllocated();
setType(fieldName);
return super.readField(fieldName);
}
/** Write the given field value to native memory.
* The given field will become the active one.
* @throws IllegalArgumentException if no field exists with the given name
*/
public void writeField(String fieldName) {
ensureAllocated();
setType(fieldName);
super.writeField(fieldName);
}
/** Write the given field value to the field and native memory.
* The given field will become the active one.
* @throws IllegalArgumentException if no field exists with the given name
*/
public void writeField(String fieldName, Object value) {
ensureAllocated();
setType(fieldName);
super.writeField(fieldName, value);
}
/** Reads the Structure field of the given type from memory, sets it as
* the active type and returns it. Convenience method for
* <pre><code>
* Union u;
* Class type;
* u.setType(type);
* u.read();
* value = u.<i>field</i>;
* </code></pre>
* @param type class type of the Structure field to read
* @return the Structure field with the given type
*/
public Object getTypedValue(Class type) {
ensureAllocated();
for (Iterator i=fields().values().iterator();i.hasNext();) {
StructField f = (StructField)i.next();
if (f.type == type) {
activeField = f;
read();
return getFieldValue(activeField.field);
}
}
throw new IllegalArgumentException("No field of type " + type + " in " + this);
}
/** Set the active type and its value. Convenience method for
* <pre><code>
* Union u;
* Class type;
* u.setType(type);
* u.<i>field</i> = value;
* </code></pre>
* @param object instance of a class which is part of the union
* @return this Union object
*/
public Object setTypedValue(Object object) {
StructField f = findField(object.getClass());
if (f != null) {
activeField = f;
setFieldValue(f.field, object);
return this;
}
throw new IllegalArgumentException("No field of type " + object.getClass() + " in " + this);
}
/** Returns the field in this union with the same type as <code>type</code>,
* if any, null otherwise.
* @param type type to search for
* @return StructField of matching type
*/
private StructField findField(Class type) {
ensureAllocated();
for (Iterator i=fields().values().iterator();i.hasNext();) {
StructField f = (StructField)i.next();
if (f.type.isAssignableFrom(type)) {
return f;
}
}
return null;
}
/** Only the currently selected field will be written. */
void writeField(StructField field) {
if (field == activeField) {
super.writeField(field);
}
}
/** Avoid reading pointer-based fields and structures unless explicitly
* selected. Structures may contain pointer-based fields which can
* crash the VM if not properly initialized.
*/
Object readField(StructField field) {
if (field == activeField
|| (!Structure.class.isAssignableFrom(field.type)
&& !String.class.isAssignableFrom(field.type)
&& !WString.class.isAssignableFrom(field.type))) {
return super.readField(field);
}
// Field not accessible
// TODO: read structure, to the extent possible; need a "recursive"
// flag to "read"
return null;
}
/** Adjust the size to be the size of the largest element, and ensure
* all fields begin at offset zero.
*/
int calculateSize(boolean force, boolean avoidFFIType) {
int size = super.calculateSize(force, avoidFFIType);
if (size != CALCULATE_SIZE) {
int fsize = 0;
for (Iterator i=fields().values().iterator();i.hasNext();) {
StructField f = (StructField)i.next();
f.offset = 0;
if (f.size > fsize
// Prefer aggregate types to simple types, since they
// will have more complex packing rules (some platforms
// have specific methods for packing small structs into
// registers, which may not match the packing of bytes
// for a primitive type).
|| (f.size == fsize
&& Structure.class.isAssignableFrom(f.type))) {
fsize = f.size;
biggestField = f;
}
}
size = calculateAlignedSize(fsize);
if (size > 0) {
// Update native FFI type information, if needed
if (this instanceof ByValue && !avoidFFIType) {
getTypeInfo();
}
}
}
return size;
}
/** All fields are considered the "first" element. */
protected int getNativeAlignment(Class type, Object value, boolean isFirstElement) {
return super.getNativeAlignment(type, value, true);
}
/** Avoid calculating type information until we know our biggest field.
* Return type information for the largest field to ensure all available
* bits are used.
*/
Pointer getTypeInfo() {
if (biggestField == null) {
// Not calculated yet
return null;
}
return super.getTypeInfo();
}
}
| lgpl-2.1 |
datacleaner/DataCleaner | engine/core/src/main/java/org/datacleaner/repository/vfs/VfsRepository.java | 1494 | /**
* DataCleaner (community edition)
* Copyright (C) 2014 Free Software Foundation, Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.datacleaner.repository.vfs;
import org.apache.commons.vfs2.FileObject;
import org.datacleaner.repository.file.FileRepository;
import org.datacleaner.util.VFSUtils;
/**
* Repository implementation based of commons VFS.
*
* TODO: For now this is a really simple implementation that will only work on
* local file based {@link FileObject}s. A proper implementation would be much
* better but this is sufficient for current initial needs.
*/
public class VfsRepository extends FileRepository {
private static final long serialVersionUID = 1L;
public VfsRepository(final FileObject rootFolder) {
super(VFSUtils.toFile(rootFolder));
}
}
| lgpl-3.0 |
colomoto/bioLQM | src/main/java/org/colomoto/biolqm/metadata/constants/TagsKeysAvailable.java | 1194 | package org.colomoto.biolqm.metadata.constants;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import java.util.ArrayList;
/**
* One instance per model opened to store the keys and tags used in the model
*
* @author Martin Boutroux
*/
public class TagsKeysAvailable {
// variables
public Set<String> tags;
public Map<String, ArrayList<String>> keysValues;
// constructors
public TagsKeysAvailable() {
this.tags = new HashSet<String>();
this.keysValues = new HashMap<String, ArrayList<String>>();
}
// functions
public void updateTagsAvailable(String newTag) {
this.tags.add(newTag);
}
public void updateKeysValuesAvailable(String newKey, ArrayList<String> newValues) {
// if the key doesn't exist, we create it and populate it with the values
// if it exists, we add to the keys the values missing
if (!this.keysValues.containsKey(newKey)) {
this.keysValues.put(newKey, newValues);
}
else {
ArrayList<String> currentValues = this.keysValues.get(newKey);
for (String newValue: newValues) {
if (!currentValues.contains(newValue)) {
currentValues.add(newValue);
}
}
}
}
}
| lgpl-3.0 |
simeshev/parabuild-ci | test/src/org/parabuild/ci/webui/admin/SSTestParallelSourceControlPanel.java | 1736 | /*
* Parabuild CI licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.parabuild.ci.webui.admin;
import java.util.*;
import org.apache.cactus.*;
import junit.framework.*;
import org.parabuild.ci.TestHelper;
import org.parabuild.ci.configuration.*;
/**
* Tests home page
*/
public class SSTestParallelSourceControlPanel extends ServletTestCase {
private ParallelSourceControlPanel panel = null;
public SSTestParallelSourceControlPanel(final String s) {
super(s);
}
/**
* Makes sure that it doesn't throw the exception
*/
public void test_setSettings() throws Exception {
load();
}
/**
*/
public void test_getUpdatedSettings() throws Exception {
load();
final List updatedSettings = panel.getUpdatedSettings();
assertTrue(!updatedSettings.isEmpty());
}
private void load() {
panel.load(ConfigurationManager.getInstance().getActiveBuildConfig(TestHelper.TEST_DEPENDENT_PARALLEL_BUILD_ID_1));
}
/**
* Required by JUnit
*/
public static TestSuite suite() {
return new TestSuite(SSTestParallelSourceControlPanel.class);
}
protected void setUp() throws Exception {
super.setUp();
panel = new ParallelSourceControlPanel();
}
}
| lgpl-3.0 |
agry/NGECore2 | src/services/reverseengineering/ReverseEngineeringService.java | 313039 | /*******************************************************************************
* Copyright (c) 2013 <Project SWG>
*
* This File is part of NGECore2.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Using NGEngine to work with NGECore2 is making a combined work based on NGEngine.
* Therefore all terms and conditions of the GNU Lesser General Public License cover the combination.
******************************************************************************/
package services.reverseengineering;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;
import resources.datatables.Options;
import resources.objects.creature.CreatureObject;
import resources.objects.player.PlayerObject;
import resources.objects.tangible.TangibleObject;
import engine.resources.container.Traverser;
import engine.resources.objects.SWGObject;
import engine.resources.service.INetworkDispatch;
import engine.resources.service.INetworkRemoteEvent;
import main.NGECore;
/**
* @author Charon
*/
public class ReverseEngineeringService implements INetworkDispatch {
private NGECore core;
private ArrayList<String> statNameList = new ArrayList<String>(Arrays.asList("cat_stat_mod_bonus.@stat_n:agility_modified",
"cat_stat_mod_bonus.@stat_n:constitution_modified",
"cat_stat_mod_bonus.@stat_n:precision_modified",
"cat_stat_mod_bonus.@stat_n:stamina_modified",
"cat_stat_mod_bonus.@stat_n:strength_modified",
"cat_stat_mod_bonus.@stat_n:luck_modified"
));
private Vector<RE_Combination> re_Combinations = new Vector<RE_Combination>();
private Map<String,String> skillModMapping = new HashMap<String,String>();
public class RE_Combination{
private String ingredient1 = "";
private String ingredient2 = "";
private String result = "";
public RE_Combination(String ingredient1, String ingredient2, String result){
this.ingredient1 = ingredient1;
this.ingredient2 = ingredient2;
this.result = result;
}
public String getIngredient1(){
return this.ingredient1;
}
public String getIngredient2(){
return this.ingredient2;
}
public String getResult(){
return this.result;
}
}
public ReverseEngineeringService(NGECore core) {
this.core = core;
createReCombinations();
createMappings();
}
public void createReCombinations(){
re_Combinations.add(new RE_Combination("Launcher Tube","Used Wiring","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Unpowered Survey Pad","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Wiring (White)","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Mark V Vocab Module","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Wiring (Red/Yellow)","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Servo Joint","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Medical Device","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Wiring (Blue)","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Wiring (Green)","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Wiring (Black)","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Unpowered Installation Repair Device","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Wiring (Orange)","1-H Light Saber Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Medical Console","1-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Tranceiver","Used Vidscreen","1-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Mark V Vocab Module","1-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Shield Module","Tubing","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Tubing","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Used Notebook","Servo Joint","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Remote Transmitter","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Shield Module","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Impulse Detector","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Shield Module","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Used Notebook","1-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Ledger","Plugged Hydraulics System","1-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Tubing","1-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Comlink","Laser Trap","1-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Newsfilter Module","1-H Melee Damage (10)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Used Wiring","2-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Wiring (White)","2-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Medical Console","Wire Element","2-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Wiring (Red/Yellow)","2-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Demagnetized Datadisk","2-H Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Software Module","Tranceiver","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Power Output Analyzer","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Power Output Device","Servo Joint","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Power Output Device","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Tranceiver","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Servo Joint","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Tranceiver","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Console","Vocabulator","2-H Melee Action Cost (10)"));
re_Combinations.add(new RE_Combination("Used Notebook","Droid Motor (Yellow)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Used Notebook","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Locomotor","Used Notebook","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Motor","Used Notebook","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Wiring (Black)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Wiring (Orange)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Used Wiring","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Wiring (White)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Used Notebook","2-H Melee Critical Chance (14)"));
re_Combinations.add(new RE_Combination("Used Notebook","Droid Motor (Red)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Wiring (Red/Yellow)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Wiring (Blue)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Ledger","Wiring (Green)","2-H Melee Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Wiring (Orange)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (Blue)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (Teal)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (Green)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (Red/Yellow)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Control Box","Speederdrive","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (White)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (Blue)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (Green)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (Purple)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (Red/Yellow)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Launcher Tube","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (Teal)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (Black)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Used Wiring","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (Orange)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Used Wiring","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (White)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Wiring (Blue)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Wiring (Green)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Control Box","Hyperdrive Unit","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (Black)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wiring (Orange)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wiring (Purple)","2-H Melee Damage (14)"));
re_Combinations.add(new RE_Combination("Shield Module","Frequency Jamming Wired","Advanced Component Experimentation (4)"));
re_Combinations.add(new RE_Combination("Shield Module","Wire Element","Advanced Component Experimentation (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Wire Element","Advanced Component Experimentation (4)"));
re_Combinations.add(new RE_Combination("Software Module","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Survival Gear","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Mark VII Vocabulation Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Ledger","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Rapid Program Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Software Module","Mark V Vocab Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wire Element","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Control Box","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Software Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Used Wiring","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Software Module","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Tubing","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Canceled Travel Ticket","Frequency Jamming Wired","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Used Notebook","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Used Vidscreen","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Rapid Program Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Control Box","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","A Damaged Droid Power Cell","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","A Damaged Droid Power Cell","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Tubing","Agility (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Shield Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Shield Module","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","A Small Mining Tool","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Software Module","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Used Notebook","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Differential Regulator","Agility (1)"));
re_Combinations.add(new RE_Combination("Aeromagnifier","Differential Regulator","Agility (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Used Notebook","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Used Vidscreen","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Chassis Blueprints","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Control Box","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Software Module","Tubing","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","A Small Mining Tool","Agility (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","A Small Mining Tool","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Ledger","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Servo Joint","Used Wiring","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Used Vidscreen","Agility (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Used Vidscreen","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Mark V Vocab Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Differential Regulator","Mark V Vocab Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","A Damaged Droid Swivel Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Remote Transmitter","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Shield Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Impulse Detector","Agility (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Ledger","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Ledger","Agility (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Software Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Software Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Software Module","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Survival Gear","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Mark VII Vocabulation Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Ledger","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Rapid Program Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Software Module","Mark V Vocab Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wire Element","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Control Box","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Software Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Used Wiring","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Software Module","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Tubing","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Droid Battery (Black/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Canceled Travel Ticket","Frequency Jamming Wired","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Used Notebook","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Used Vidscreen","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Rapid Program Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Control Box","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","A Damaged Droid Power Cell","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","A Damaged Droid Power Cell","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Tubing","Agility (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Shield Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Shield Module","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","A Small Mining Tool","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Software Module","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Unpowered Memory Encryptor","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Used Notebook","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Ledger","Differential Regulator","Agility (1)"));
re_Combinations.add(new RE_Combination("Servo Joint","Differential Regulator","Agility (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Used Notebook","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Rapid Program Module","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Mark V Vocab Module","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Collapsed Artifact","Agility (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Comlink","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Weak Droid Battery","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Droid Battery (Teal)","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wire Element","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Tubing","Agility (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Tubing","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Impulse Detector","Agility (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","A Small Mining Tool","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","A Small Mining Tool","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Used Wiring","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Servo Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Newsfilter Module","Canceled Travel Ticket","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Medical Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Control Box","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Outdated Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Ledger","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Used ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Plugged Hydraulics System","Agility (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Power Output Analyzer","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Power Output Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Used Vidscreen","Agility (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Used Vidscreen","Agility (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Rations Kit","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","A Damaged Droid Swivel Joint","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Remote Transmitter","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Remote Transmitter","Agility (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Droid Battery (Purple/Green)","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wire Element","Agility (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Wire Element","Agility (1)"));
re_Combinations.add(new RE_Combination("Datapad","Explosive Dud","Agility (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wire Element","Agility (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Ledger","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Self Analysis Circuit","Agility (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Tubing","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","ID Chip","Agility (1)"));
re_Combinations.add(new RE_Combination("Comlink","Impulse Detector","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Launcher Tube","Agility (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","A Small Mining Tool","Agility (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Unpowered Installation Repair Device","Agility (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Aeromagnifier","Agility (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Shield Module","Armor Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Mark V Circuit Board","Armor Assembly (3)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Shield Module","Armor Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Mark I Circuit Board","Armor Assembly (3)"));
re_Combinations.add(new RE_Combination("Shield Module","Mark V Vocab Module","Armor Assembly (3)"));
re_Combinations.add(new RE_Combination("Circuit Board","A Damaged Droid Swivel Joint","Armor Assembly (3)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Wire Element","Armor Experimentation (4)"));
re_Combinations.add(new RE_Combination("Restraining Device","Power Supply","Armor Experimentation (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Self Analysis Circuit","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Demagnetized Datadisk","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Circuit Board","Explosive Dud","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Used Notebook","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Circuit Board","Demagnetized Datadisk","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Mark V Circuit Board","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Unpowered Survey Pad","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Worklight","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Demagnetized Datadisk","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Mark I Circuit Board","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Unpowered Survey Pad","Artisan Assembly (3)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Outdated Aeromagnifier","Artisan Experimentation (4)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Aeromagnifier","Artisan Experimentation (4)"));
re_Combinations.add(new RE_Combination("Locomotor","Unpowered Survey Pad","Assassinate Action Cost (9)"));
re_Combinations.add(new RE_Combination("Motor","Unpowered Survey Pad","Assassinate Action Cost (9)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Survival Gear","Assassinate Action Cost (10)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Unpowered Survey Pad","Assassinate Action Cost (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Unpowered Survey Pad","Assassinate Action Cost (8)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Droid Motor (Yellow)","Assassinate Action Cost (8)"));
re_Combinations.add(new RE_Combination("Shield Module","Survival Gear","Assassinate Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Console","Droid Motor (Yellow)","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Laser Trap","Droid Motor (Red)","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Laser Trap","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Ledger","Mark X Vocab Module","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Medical Console","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Medical Console","Droid Motor (Red)","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Laser Trap","Unpowered Survey Pad","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Laser Trap","Motor","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Laser Trap","Locomotor","Assassinate Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Motor","Rations Kit","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Survival Gear","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Motor","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Locomotor","Rations Kit","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Explosive Dud","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Explosive Dud","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Locomotor","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Survival Gear","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Rations Kit","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Droid Motor (Red)","Assassinate Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Unpowered Survey Pad","Assault Action Cost (8)"));
re_Combinations.add(new RE_Combination("Laser Trap","Droid Motor (Yellow)","Assault Critical Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Laser Trap","Assault Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Power Output Analyzer","Assault Damage (8)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Power Output Device","Assault Damage (8)"));
re_Combinations.add(new RE_Combination("Rations Kit","Droid Motor (Red)","Assault Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Vocabulator","Assault Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Rations Kit","Assault Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Vocabulator","Assault Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Software Module","Vocabulator","Assault Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Rations Kit","Droid Motor (Yellow)","Assault Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Shield Module","Used ID Chip","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Power Output Analyzer","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Power Output Device","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Wiring (Black)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Wiring (Orange)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","ID Chip","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Used Wiring","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Used ID Chip","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Wiring (White)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Wiring (Purple)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("ID Chip","Shield Module","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Frequency Jamming Wired","Wiring (Teal)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Wiring (Red/Yellow)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Wiring (Blue)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Wire Element","Wiring (Green)","Bleed Resistance (4)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Power Supply","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Droid Motor (Yellow)","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("ID Chip","Motor","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("ID Chip","Locomotor","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("ID Chip","Droid Motor (Yellow)","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Locomotor","Used ID Chip","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Motor","Used ID Chip","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Vocabulator","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","ID Chip","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","ID Chip","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("ID Chip","Droid Motor (Red)","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Used ID Chip","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Used ID Chip","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Droid Motor (Red)","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Used Vidscreen","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Power Supply","Tubing","Bleeding Absorption (4)"));
re_Combinations.add(new RE_Combination("Data Housing","Droid Motor (Red)","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Data Housing","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Tranceiver","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Data Housing","Motor","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Data Housing","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Data Housing","Locomotor","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Power Supply","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Tranceiver","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Data Housing","Droid Motor (Yellow)","Booster Assembly (3)"));
re_Combinations.add(new RE_Combination("Control Box","Wiring (Orange)","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Medical Console","Unpowered Installation Repair Device","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Control Box","Wiring (Purple)","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Control Box","Wiring (Green)","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Restraining Device","Shield Module","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Restraining Device","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Control Box","Wiring (Red/Yellow)","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Control Box","Wiring (Blue)","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Medical Console","A Small Mining Tool","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Control Box","Used Wiring","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Control Box","Wiring (White)","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Control Box","Wiring (Black)","Booster Experimentation (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Servo Joint","Camouflage (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Medical Device","Camouflage (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Droid Memory Module","Carbine Action Cost (10)"));
re_Combinations.add(new RE_Combination("Survival Gear","Circuit","Carbine Action Cost (14)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Rapid Program Module","Carbine Damage (14)"));
re_Combinations.add(new RE_Combination("Circuit Board","Electronics Module","Carbine Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","A Damaged Droid Power Cell","Carbine Damage (14)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Datapad","Carbine Damage (14)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Unpowered Memory Encryptor","Chassis Assembly (3)"));
re_Combinations.add(new RE_Combination("Shield Module","Unpowered Memory Encryptor","Chassis Assembly (3)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Remote Transmitter","Chassis Experimentation (4)"));
re_Combinations.add(new RE_Combination("Software Module","Circuit","Chassis Experimentation (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Circuit","Chassis Experimentation (4)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Magseal Detector","Chassis Experimentation (4)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Circuit","Chassis Experimentation (4)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Tubing","Chassis Experimentation (4)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Frequency Jamming Wired","Clothing Assembly (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Vocabulator","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Droid Motor (Red)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Locomotor","Weak Droid Battery","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Motor","Weak Droid Battery","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Droid Battery (Teal)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wire Element","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Power Supply","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Droid Motor (Red)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Motor","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Frequency Jamming Wired","Clothing Assembly (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Plugged Hydraulics System","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Droid Battery (Purple/Green)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wire Element","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Locomotor","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Droid Battery (Black/Green)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("ID Chip","Power Supply","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Droid Motor (Yellow)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Weak Droid Battery","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Droid Battery (Black/Green)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Motor","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Droid Battery (Black/Green)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Locomotor","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Droid Motor (Red)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Tubing","Frequency Jamming Wired","Clothing Assembly (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Droid Battery (Teal)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Wire Element","Tubing","Clothing Assembly (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Droid Battery (Black/Green)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Motor","Droid Battery (Black/Green)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Weak Droid Battery","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Droid Battery (Purple/Green)","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Tubing","Clothing Assembly (3)"));
re_Combinations.add(new RE_Combination("Medical Device","Droid Memory Module","Clothing Experimentation (4)"));
re_Combinations.add(new RE_Combination("Servo Joint","Circuit","Clothing Experimentation (4)"));
re_Combinations.add(new RE_Combination("Comlink","Unpowered Survey Pad","Clothing Experimentation (4)"));
re_Combinations.add(new RE_Combination("Medical Device","Circuit","Clothing Experimentation (4)"));
re_Combinations.add(new RE_Combination("Servo Joint","Droid Memory Module","Clothing Experimentation (4)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Medical Console","Constitution (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Droid Battery (Black/Green)","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Servo Joint","Droid Battery (Black/Green)","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Plugged Hydraulics System","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Comlink","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Remote Transmitter","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Emergency Reactivator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wire Element","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wire Element","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Self Analysis Circuit","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Shield Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Shield Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","A Small Mining Tool","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Launcher Tube","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Software Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Ledger","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Ledger","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Plugged Hydraulics System","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Used Notebook","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Mark V Vocab Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Rapid Program Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Aeromagnifier","Mark V Vocab Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","A Damaged Droid Memory Unit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","A Damaged Droid Power Cell","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Remote Transmitter","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Droid Battery (Teal)","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wire Element","Constitution (1)"));
re_Combinations.add(new RE_Combination("Datapad","Self Analysis Circuit","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Software Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Software Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Mark V Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Survival Gear","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Mark V Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Survival Gear","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Mark VII Vocabulation Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Droid Battery (Black/Green)","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Datapad","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Remote Transmitter","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Droid Battery (Purple/Green)","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Wire Element","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Self Analysis Circuit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Mark I Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Mark V Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Mark V Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Plugged Hydraulics System","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Used Notebook","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Ledger","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Mark V Vocab Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Mark V Vocab Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Rapid Program Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Weak Droid Battery","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Weak Droid Battery","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Remote Transmitter","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Self Analysis Circuit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Self Analysis Circuit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Self Analysis Circuit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","A Small Mining Tool","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Mark I Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Servo Joint","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Medical Console","Constitution (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Droid Battery (Black/Green)","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Datapad","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Wire Element","Constitution (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Shield Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Shield Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","A Small Mining Tool","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","A Small Mining Tool","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","A Small Mining Tool","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Unpowered Installation Repair Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Mark I Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Mark I Circuit Board","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Survival Gear","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Ledger","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Medical Console","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Ledger","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Frequency Jamming Wired","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Droid Battery (Black/Green)","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Droid Battery (Black/Green)","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Ledger","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Software Module","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Plugged Hydraulics System","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Used Notebook","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Used Notebook","Constitution (1)"));
re_Combinations.add(new RE_Combination("Unpowered Installation Repair Device","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Comlink","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Rapid Program Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Rapid Program Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Weak Droid Battery","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Remote Transmitter","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Wire Element","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Self Analysis Circuit","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Shield Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Launcher Tube","Constitution (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Launcher Tube","Constitution (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","A Small Mining Tool","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Ledger","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Mark VII Vocabulation Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Used ID Chip","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Plugged Hydraulics System","Constitution (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Plugged Hydraulics System","Constitution (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Used Notebook","Constitution (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Comlink","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Rapid Program Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Weak Droid Battery","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Weak Droid Battery","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Shield Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Launcher Tube","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Launcher Tube","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Demagnetized Datadisk","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Mark VII Vocabulation Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Plugged Hydraulics System","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Power Output Analyzer","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Power Output Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Differential Regulator","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Used Notebook","Constitution (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Used Vidscreen","Constitution (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Comlink","Constitution (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Rapid Program Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Rations Kit","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Weak Droid Battery","Constitution (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Weak Droid Battery","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Explosive Dud","Constitution (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Tubing","Constitution (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Shield Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Launcher Tube","Constitution (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Launcher Tube","Constitution (1)"));
re_Combinations.add(new RE_Combination("Control Box","Demagnetized Datadisk","Constitution (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Mark VII Vocabulation Module","Constitution (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Servo Joint","Constitution (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Medical Device","Constitution (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Unpowered Memory Encryptor","Constitution (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Outdated Aeromagnifier","Constitution (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Shield Module","Creature Critical Chance (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Rations Kit","Creature Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Data Housing","Wire Element","Dance Prop Assembly (3)"));
re_Combinations.add(new RE_Combination("Survival Gear","Worklight","Dance Prop Assembly (3)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","A Damaged Droid Swivel Joint","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Shield Module","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Datapad","ID Chip","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Datapad","Used ID Chip","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Shield Module","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Rapid Program Module","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Tranceiver","Demagnetized Datadisk","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Control Box","Self Analysis Circuit","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Medical Console","Dancing Enhancement (3)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Remote Transmitter","Dancing Knowledge (3)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Impulse Detector","Dancing Knowledge (3)"));
re_Combinations.add(new RE_Combination("Data Housing","Emergency Reactivator","Dancing Knowledge (3)"));
re_Combinations.add(new RE_Combination("Wire Element","Demagnetized Datadisk","Dancing Knowledge (3)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Remote Transmitter","Disease Absorption (4)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Impulse Detector","Disease Absorption (4)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Tubing","Disease Absorption (4)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Wire Element","Droid Assembly (3)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Wire Element","Droid Assembly (3)"));
re_Combinations.add(new RE_Combination("Comlink","Unpowered Memory Encryptor","Droid Assembly (3)"));
re_Combinations.add(new RE_Combination("Medical Device","Plugged Hydraulics System","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Tubing","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Power Output Device","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Power Output Device","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Tubing","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Power Output Analyzer","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Power Output Analyzer","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Locomotor","Power Output Analyzer","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Motor","Power Output Analyzer","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Servo Joint","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Power Output Device","Droid Motor (Yellow)","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Locomotor","Power Output Device","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Motor","Power Output Device","Droid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Data Housing","Droid Battery (Purple/Green)","Droid Experimentation (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Worklight","Droid Experimentation (4)"));
re_Combinations.add(new RE_Combination("Data Housing","Weak Droid Battery","Droid Experimentation (4)"));
re_Combinations.add(new RE_Combination("Data Housing","Droid Battery (Black/Green)","Droid Experimentation (4)"));
re_Combinations.add(new RE_Combination("Data Housing","Droid Battery (Teal)","Droid Experimentation (4)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Demagnetized Datadisk","Droid Experimentation (4)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Worklight","Droid Speed (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Worklight","Droid Speed (3)"));
re_Combinations.add(new RE_Combination("Battery","Holorecorder","Droid Speed (10)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Worklight","Droid Speed (3)"));
re_Combinations.add(new RE_Combination("Worklight","Droid Battery (Black/Green)","Droid Speed (3)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Wire Element","Engine Assembly (3)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Unpowered Memory Encryptor","Engine Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Unpowered Memory Encryptor","Engine Assembly (3)"));
re_Combinations.add(new RE_Combination("Software Module","Unpowered Memory Encryptor","Engine Assembly (3)"));
re_Combinations.add(new RE_Combination("Power Output Device","Used Vidscreen","Engine Experimentation (4)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Used Notebook","Engine Experimentation (4)"));
re_Combinations.add(new RE_Combination("Speederdrive","Used Notebook","Engine Experimentation (4)"));
re_Combinations.add(new RE_Combination("Medical Console","Tranceiver","Engine Experimentation (4)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Used Vidscreen","Engine Experimentation (4)"));
re_Combinations.add(new RE_Combination("Shield Module","Unpowered Survey Pad","Fast Draw Action Cost (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Unpowered Survey Pad","Fast Draw Action Cost (8)"));
re_Combinations.add(new RE_Combination("Medical Console","Shield Module","Fast Draw Critical Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Medical Console","Fast Draw Critical Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Software Module","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Locomotor","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Motor","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Locomotor","Motor","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Locomotor","Droid Motor (Yellow)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Shield Module","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Droid Motor (Yellow)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Locomotor","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Motor","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Droid Motor (Yellow)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","A Damaged Droid Motivator","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Droid Motor (Red)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Locomotor","Droid Motor (Red)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Motor","Droid Motor (Red)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","A Damaged Droid Swivel Joint","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Shield Module","Software Module","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Motor","Droid Motor (Yellow)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Shield Module","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Mark VII Vocabulation Module","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Droid Motor (Red)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Droid Motor (Red)","Fast Draw Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Tranceiver","Fire Absorption (4)"));
re_Combinations.add(new RE_Combination("Shield Module","Tranceiver","Fire Absorption (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Rations Kit","Fire Resistance (4)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Speederdrive","Fire Resistance (4)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Mark X Vocab Module","Fire Resistance (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Mark V Vocab Module","Focused Fire Action Cost (8)"));
re_Combinations.add(new RE_Combination("Motor","Mark V Vocab Module","Focused Fire Action Cost (8)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Software Module","Focused Fire Action Cost (8)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Survival Gear","Focused Fire Action Cost (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Mark VII Vocabulation Module","Focused Fire Action Cost (8)"));
re_Combinations.add(new RE_Combination("Droid Motor (Yellow)","Mark V Vocab Module","Focused Fire Action Cost (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Software Module","Focused Fire Action Cost (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Wiring (Black)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wiring (Red/Yellow)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Wiring (Orange)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wiring (Blue)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wiring (Green)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Wiring (White)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Used Wiring","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wiring (Black)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wiring (Orange)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wiring (White)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Wiring (Red/Yellow)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Used Wiring","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Wiring (Blue)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Wiring (Green)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Power Output Device","Wiring (Purple)","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Rations Kit","Unpowered Survey Pad","Focused Fire Damage (8)"));
re_Combinations.add(new RE_Combination("Survival Gear","Used Notebook","Focused Fire Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Power Output Device","Focused Fire Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Tranceiver","Food Assembly (3)"));
re_Combinations.add(new RE_Combination("Rations Kit","Demagnetized Datadisk","Food Assembly (3)"));
re_Combinations.add(new RE_Combination("Comlink","Software Module","Food Experimentation (4)"));
re_Combinations.add(new RE_Combination("Comlink","A Damaged Droid Memory Unit","Food Experimentation (4)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Laser Trap","Food Experimentation (4)"));
re_Combinations.add(new RE_Combination("Comlink","Mark VII Vocabulation Module","Food Experimentation (4)"));
re_Combinations.add(new RE_Combination("Restraining Device","Tranceiver","Food Experimentation (4)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Tubing","Glancing Blow Increase (18)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Remote Transmitter","Glancing Blow Increase (18)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Mark X Vocab Module","Glancing Blow Increase (18)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Mark V Vocab Module","Glancing Blow Increase (Melee) (14)"));
re_Combinations.add(new RE_Combination("Rations Kit","Servo Joint","Glancing Blow Increase (Melee) (14)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Ledger","Glancing Blow Increase (Melee) (14)"));
re_Combinations.add(new RE_Combination("Medical Device","Rations Kit","Glancing Blow Increase (Melee) (14)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Unpowered Installation Repair Device","Glancing Blow Increase (Melee) (14)"));
re_Combinations.add(new RE_Combination("Unpowered Installation Repair Device","Mark V Vocab Module","Glancing Blow Increase (Melee) (14)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Plugged Hydraulics System","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Tubing","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("Speederdrive","Tubing","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Speederdrive","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("Vocabulator","Servo Joint","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("ID Chip","Unpowered Survey Pad","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Used ID Chip","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("Medical Device","Vocabulator","Glancing Blow Increase (Ranged) (14)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Power Supply","Healing Potency (8)"));
re_Combinations.add(new RE_Combination("Power Supply","Droid Battery (Black/Green)","Healing Potency (8)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","ID Chip","Healing Potency (8)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Power Supply","Healing Potency (8)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Used ID Chip","Healing Potency (8)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Power Supply","Healing Potency (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Speederdrive","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Droid Motor (Red)","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Droid Motor (Red)","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Hyperdrive Unit","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Hyperdrive Unit","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Locomotor","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Speederdrive","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Locomotor","Speederdrive","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Motor","Speederdrive","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Motor","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Droid Motor (Yellow)","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Droid Motor (Yellow)","Heavy Weapon Action Cost (10)"));
re_Combinations.add(new RE_Combination("Ledger","Survival Gear","Heavy Weapon Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Wiring (Orange)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Wiring (Red/Yellow)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Wiring (White)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Wiring (Blue)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Wiring (Green)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Wiring (Purple)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Wiring (Purple)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Wiring (Black)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Wiring (Orange)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Wiring (Red/Yellow)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Servo Joint","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Wiring (White)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Wiring (Blue)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Servo Joint","Wiring (Green)","Humanoid Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Used Notebook","Instrument Assembly (3)"));
re_Combinations.add(new RE_Combination("Datapad","Power Supply","Instrument Assembly (3)"));
re_Combinations.add(new RE_Combination("Data Housing","Restraining Device","Instrument Assembly (3)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Worklight","Instrument Assembly (3)"));
re_Combinations.add(new RE_Combination("Locomotor","Mark X Vocab Module","Jedi Strike Action Cost (8)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Droid Motor (Red)","Jedi Strike Action Cost (8)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Mark X Vocab Module","Jedi Strike Action Cost (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Mark X Vocab Module","Jedi Strike Action Cost (8)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Droid Motor (Yellow)","Jedi Strike Action Cost (8)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Motor","Jedi Strike Action Cost (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wiring (Purple)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wiring (Purple)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wiring (Green)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wiring (Red/Yellow)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Survival Gear","Tranceiver","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wiring (Blue)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wiring (Green)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Tubing","Wiring (Red/Yellow)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wiring (Red/Yellow)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Laser Trap","Mark V Vocab Module","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wiring (Blue)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wiring (Black)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wiring (White)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wiring (Orange)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Used Wiring","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Wiring (White)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wiring (Black)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Used Wiring","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Medical Console","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Wiring (Orange)","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Tubing","Used Wiring","Jedi Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Rations Kit","Survival Gear","Jedi Strike Damage (8)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Shield Module","Jedi Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Tubing","Jedi Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Used Notebook","Jedi Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (Teal)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Control Box","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (Black)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (Orange)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Rapid Program Module","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (Blue)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (Green)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (White)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Emergency Reactivator","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (Purple)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Wiring (Red/Yellow)","Lightsaber Assembly (3)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Aeromagnifier","Lightsaber Experimentation (5)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Self Analysis Circuit","Lightsaber Experimentation (5)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Outdated Aeromagnifier","Lightsaber Experimentation (5)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","A Damaged Droid Memory Unit","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Droid Battery (Purple/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Ledger","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Ledger","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Ledger","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Unpowered Installation Repair Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Mark I Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Mark I Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Ledger","Mark I Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Mark V Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Mark VII Vocabulation Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Medical Console","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Medical Console","Luck (1)"));
re_Combinations.add(new RE_Combination("Ledger","Medical Console","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Used Notebook","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Ledger","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Mark V Vocab Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Collapsed Artifact","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Rapid Program Module","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Datapad","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Emergency Reactivator","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Tubing","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Shield Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Ledger","Luck (1)"));
re_Combinations.add(new RE_Combination("Shield Module","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Unpowered Installation Repair Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Mark I Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Mark VII Vocabulation Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Medical Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Mark V Vocab Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Rapid Program Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Software Module","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Droid Battery (Teal)","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Emergency Reactivator","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Tubing","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Shield Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Unpowered Installation Repair Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Mark I Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Mark VII Vocabulation Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Mark VII Vocabulation Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Ledger","Mark VII Vocabulation Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Medical Console","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Software Module","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Used Notebook","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Rapid Program Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Tubing","Mark V Vocab Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Datapad","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Droid Battery (Purple/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Droid Battery (Teal)","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Tubing","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Tubing","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Unpowered Installation Repair Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Survival Gear","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Mark V Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Palm Diary","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Newsfilter Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Used Notebook","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Used Notebook","Luck (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Used Notebook","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Rapid Program Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Rapid Program Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Droid Battery (Purple/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Tubing","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Tubing","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Impulse Detector","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Unpowered Installation Repair Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Ledger","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Unpowered Installation Repair Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Survival Gear","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Mark VII Vocabulation Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Frequency Jamming Wired","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Used Notebook","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Rapid Program Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Control Box","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Datapad","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Emergency Reactivator","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Tubing","Luck (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Impulse Detector","Luck (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Impulse Detector","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Mark I Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Aeromagnifier","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Survival Gear","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Mark V Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Survival Gear","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Medical Console","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Used Vidscreen","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Mark V Vocab Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","A Damaged Droid Memory Unit","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Impulse Detector","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Software Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Control Box","Mark V Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Mark V Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Ledger","Mark V Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Droid Battery (Black/Green)","Luck (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Mark V Vocab Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Rapid Program Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","A Damaged Droid Memory Unit","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Datapad","Luck (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Remote Transmitter","Luck (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Droid Battery (Teal)","Luck (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Weak Droid Battery","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Emergency Reactivator","Luck (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wire Element","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","A Small Mining Tool","Luck (1)"));
re_Combinations.add(new RE_Combination("Datapad","Ledger","Luck (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Unpowered Installation Repair Device","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Mark I Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Mark V Circuit Board","Luck (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Survival Gear","Luck (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Survival Gear","Luck (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Mark VII Vocabulation Module","Luck (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Used Wiring","Luck (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Medical Console","Luck (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Rapid Program Module","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","A Small Mining Tool","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Circuit Board","Unpowered Installation Repair Device","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Servo Joint","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Medical Device","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Electronics Module","Differential Regulator","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Circuit Board","A Small Mining Tool","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Launcher Tube","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","A Small Mining Tool","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Unpowered Installation Repair Device","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Comlink","Power Supply","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Control Box","Data Housing","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Medical Console","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Unpowered Installation Repair Device","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Servo Joint","Music Knowledge (3)"));
re_Combinations.add(new RE_Combination("Comlink","Medical Console","Musical Enhancement (3)"));
re_Combinations.add(new RE_Combination("Control Box","Power Supply","Musical Enhancement (3)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Rations Kit","Pistol Action Cost (10)"));
re_Combinations.add(new RE_Combination("Rations Kit","Tubing","Pistol Action Cost (10)"));
re_Combinations.add(new RE_Combination("Rations Kit","Remote Transmitter","Pistol Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Console","Software Module","Pistol Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Survival Gear","Power Supply","Pistol Critical Chance (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Medical Console","Pistol Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Laser Trap","Survival Gear","Pistol Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Medical Console","Pistol Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Mark I Circuit Board","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Laser Trap","Rapid Program Module","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Circuit Board","Hyperdrive Unit","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Speederdrive","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Software Module","Used Wiring","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Laser Trap","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Circuit Board","Speederdrive","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Speederdrive","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Mark V Circuit Board","Pistol Damage (14)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Survival Gear","Poison Absorption (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Used Notebook","Poison Absorption (4)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Restraining Device","Poison Resistance (4)"));
re_Combinations.add(new RE_Combination("Laser Trap","Used Notebook","Poison Resistance (4)"));
re_Combinations.add(new RE_Combination("Tranceiver","Vocabulator","Poison Resistance (4)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Rations Kit","Polearm Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Unpowered Survey Pad","Polearm Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Tranceiver","Wire Element","Polearm Damage (14)"));
re_Combinations.add(new RE_Combination("Circuit Board","A Damaged Droid Power Cell","Polearm Lightsaber Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Mark I Circuit Board","Polearm Lightsaber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Tubing","Polearm Lightsaber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Weak Droid Battery","Polearm Lightsaber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Droid Battery (Black/Green)","Polearm Lightsaber Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Mark V Circuit Board","Polearm Lightsaber Action Cost (10)"));
re_Combinations.add(new RE_Combination("Datapad","Wiring (White)","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Used Wiring","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Wiring (Black)","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Wiring (Orange)","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Wiring (Green)","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Used Notebook","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Wiring (Red/Yellow)","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Wiring (Blue)","Polearm Lightsaber Damage (14)"));
re_Combinations.add(new RE_Combination("Data Housing","Mark V Vocab Module","Power Systems Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Power Output Device","Power Systems Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Power Output Analyzer","Power Systems Assembly (3)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Used Vidscreen","Power Systems Assembly (3)"));
re_Combinations.add(new RE_Combination("Medical Device","A Small Mining Tool","Power Systems Experimentation (4)"));
re_Combinations.add(new RE_Combination("Servo Joint","Unpowered Installation Repair Device","Power Systems Experimentation (4)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Servo Joint","Power Systems Experimentation (4)"));
re_Combinations.add(new RE_Combination("Medical Device","Unpowered Installation Repair Device","Power Systems Experimentation (4)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Circuit","Power Systems Experimentation (4)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Servo Joint","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Installation Repair Device","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Differential Regulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Used Notebook","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Collapsed Artifact","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Mark V Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Rations Kit","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","A Damaged Droid Swivel Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Remote Transmitter","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wire Element","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wire Element","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Wire Element","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Impulse Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Unpowered Installation Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Survival Gear","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Survival Gear","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Survival Gear","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Mark VII Vocabulation Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Mark VII Vocabulation Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Aeromagnifier","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Newsfilter Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Electronics Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Newsfilter Module","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Power Output Analyzer","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Clothing Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Mark V Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Hyperdrive Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Laser Trap","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","A Small Mining Tool","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Launcher Tube","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Datapad","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Mark V Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Mark X Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Datapad","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Medical Console","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Aeromagnifier","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Electronics Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Memory Module","Frequency Jamming Wired","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Droid Battery (Black/Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Tubing","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Holorecorder","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Differential Regulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Differential Regulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Power Output Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Chemical Dispersion Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Comlink","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","A Damaged Droid Memory Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Shield Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Shield Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Laser Trap","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Launcher Tube","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Launcher Tube","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Software Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Software Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Mark X Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Memory Module","Newsfilter Module","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Software Module","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Holorecorder","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Electronics Module","Holorecorder","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Droid Battery (Black/Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Aeromagnifier","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Differential Regulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Power Output Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Power Output Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Rapid Program Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Comlink","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Rapid Program Module","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Rations Kit","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","A Damaged Droid Swivel Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Remote Transmitter","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Data Housing","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Weak Droid Battery","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Hyperdrive Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Shield Module","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Impulse Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","A Small Mining Tool","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","A Small Mining Tool","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","A Small Mining Tool","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Ledger","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Ledger","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Mark I Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Green)","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Survival Gear","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Software Module","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Survival Gear","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Mark VII Vocabulation Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Mark X Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Mark X Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Medical Console","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Medical Console","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Droid Battery (Black/Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Droid Battery (Black/Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Software Module","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Differential Regulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Power Output Analyzer","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Used Vidscreen","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Used Vidscreen","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Chassis Blueprints","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Clothing Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Control Box","Precision (1)"));
re_Combinations.add(new RE_Combination("Holorecorder","Mark V Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","A Damaged Droid Memory Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Rations Kit","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Weak Droid Battery","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Explosive Dud","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Explosive Dud","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Green)","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Launcher Tube","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Software Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Unpowered Installation Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Mark V Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Mark V Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Mark V Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Mark X Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Newsfilter Module","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Memory Module","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Memory Module","Electronics Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Servo Joint","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Memory Module","Holorecorder","Precision (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Red/Yellow)","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Power Output Analyzer","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Differential Regulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Power Output Analyzer","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Power Output Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Chemical Dispersion Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Purple)","Mark V Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Rations Kit","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","A Damaged Droid Power Cell","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","A Damaged Droid Swivel Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Remote Transmitter","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Remote Transmitter","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Remote Transmitter","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Emergency Reactivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wire Element","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wire Element","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Hyperdrive Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Shield Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Shield Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Impulse Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Shield Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Laser Trap","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Launcher Tube","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Software Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Mark VII Vocabulation Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Mark VII Vocabulation Module","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Newsfilter Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Electronics Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Datapad","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Plugged Hydraulics System","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Wiring","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Used Notebook","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Differential Regulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Survey Pad","Used Notebook","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Power Output Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Rapid Program Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Tubing","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Burnt Out Droid Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Rapid Program Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Collapsed Artifact","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Wiring (Orange)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Rapid Program Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Rations Kit","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Vocabulator","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Data Housing","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Datapad","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Device","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Hyperdrive Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","A Small Mining Tool","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Launcher Tube","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","A Small Mining Tool","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Unpowered Installation Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Unpowered Installation Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Unpowered Installation Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Unpowered Installation Repair Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Mark I Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Mark I Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Mark I Circuit Board","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Survival Gear","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Red/Yellow)","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Droid Memory Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Newsfilter Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Medical Console","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Electronics Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Demagnetized Datadisk","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Software Module","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Outdated Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Tranceiver","Used ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Wiring (Green)","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Electronics Module","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Wiring (White)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Used Vidscreen","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Used Vidscreen","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Yellow)","Wiring (Purple)","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Chemical Dispersion Unit","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Mark V Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Mark V Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Circuitry","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","A Damaged Droid Motivator","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","A Damaged Droid Power Cell","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","A Damaged Droid Power Cell","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wiring (Blue)","Precision (1)"));
re_Combinations.add(new RE_Combination("Chemical Dispersion Unit","Data Housing","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Data Housing","Precision (1)"));
re_Combinations.add(new RE_Combination("Comlink","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Rations Kit","Wiring (Green)","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Restraining Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Tubing","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Self Analysis Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","ID Chip","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Wiring (Black)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Laser Trap","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Self Analysis Circuit","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Wiring (Red/Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Software Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Worklight","Precision (1)"));
re_Combinations.add(new RE_Combination("Armor Repair Device","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Locomotor","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Software Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Software Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Locomotor","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Datapad","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Demagnetized Datadisk","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Magseal Detector","Precision (1)"));
re_Combinations.add(new RE_Combination("ID Chip","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Speederdrive","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Motor (Red)","Aeromagnifier","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Worklight","Power Supply","Precision (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Control Box","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Mark X Vocab Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Power Supply","Used Wiring","Precision (1)"));
re_Combinations.add(new RE_Combination("Ledger","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Medical Device","Tranceiver","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Palm Diary","Precision (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Servo Joint","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Unpowered Memory Encryptor","Precision (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Motor","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("Outdated Aeromagnifier","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Medical Device","Precision (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Circuit","Precision (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Electronics Module","Precision (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Droid Motor (Red)","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Motor","Precision (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Circuit","Holorecorder","Precision (1)"));
re_Combinations.add(new RE_Combination("Unpowered Memory Encryptor","Unpowered Survey Pad","Precision (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Droid Motor (Yellow)","Precision (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Servo Joint","PVP Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Survival Gear","PVP Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Console","Circuit","Reverse Engineering Chance (10)"));
re_Combinations.add(new RE_Combination("Used Notebook","Electronics Module","Reverse Engineering Chance (10)"));
re_Combinations.add(new RE_Combination("Used Notebook","Differential Regulator","Reverse Engineering Chance (10)"));
re_Combinations.add(new RE_Combination("Medical Console","Droid Memory Module","Reverse Engineering Chance (10)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Locomotor","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Motor","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("ID Chip","Servo Joint","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("ID Chip","Medical Device","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Tubing","Differential Regulator","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Emergency Reactivator","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Emergency Reactivator","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Power Supply","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Used ID Chip","Servo Joint","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Droid Motor (Red)","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Power Output Device","Power Supply","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Device","Used ID Chip","Rifle Action Cost (10)"));
re_Combinations.add(new RE_Combination("Medical Console","Mark V Vocab Module","Rifle Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","ID Chip","Rifle Damage (14)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Used ID Chip","Rifle Damage (14)"));
re_Combinations.add(new RE_Combination("Datapad","Worklight","Rifle Damage (14)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Speederdrive","Shield Assembly (3)"));
re_Combinations.add(new RE_Combination("Data Housing","Unpowered Survey Pad","Shield Assembly (3)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Magseal Detector","Shield Assembly (3)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Survival Gear","Shield Experimentation (4)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Used Vidscreen","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Used Vidscreen","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Control Box","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Data Housing","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Weak Droid Battery","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Weak Droid Battery","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Shield Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Green)","Unpowered Installation Repair Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Mark V Circuit Board","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Survival Gear","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Datapad","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Holorecorder","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Droid Battery (Black/Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Red/Yellow)","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Rapid Program Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Wiring (Teal)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","A Damaged Droid Swivel Joint","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Remote Transmitter","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Data Housing","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Datapad","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Wire Element","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Shield Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Impulse Detector","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Shield Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Control Box","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","A Small Mining Tool","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Mark VII Vocabulation Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Medical Console","Stamina (1)"));
re_Combinations.add(new RE_Combination("Tubing","Holorecorder","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Unpowered Survey Pad","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Used Notebook","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Used Vidscreen","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Mark V Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Rapid Program Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Data Housing","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Data Housing","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Weak Droid Battery","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Datapad","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Tubing","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","A Small Mining Tool","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","A Small Mining Tool","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Unpowered Installation Repair Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Mark I Circuit Board","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Red/Yellow)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Medical Console","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Medical Console","Stamina (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Droid Battery (Black/Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Used Notebook","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Used Vidscreen","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Used Vidscreen","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Green)","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Used Vidscreen","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Remote Transmitter","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Wire Element","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Impulse Detector","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Datapad","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","A Small Mining Tool","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Software Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Unpowered Installation Repair Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Red/Yellow)","Unpowered Installation Repair Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Ledger","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Mark VII Vocabulation Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Unpowered Memory Encryptor","Stamina (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Holorecorder","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Droid Battery (Black/Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Wiring","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Used Vidscreen","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Collapsed Artifact","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Data Housing","Stamina (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Remote Transmitter","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Emergency Reactivator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Wire Element","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Wire Element","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Wire Element","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wire Element","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Tubing","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Control Box","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Ledger","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Ledger","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Ledger","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Survival Gear","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Survival Gear","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Mark VII Vocabulation Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Green)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Power Output Analyzer","Stamina (1)"));
re_Combinations.add(new RE_Combination("Software Module","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Power Output Analyzer","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Control Box","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Ledger","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Data Housing","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Weak Droid Battery","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Worklight","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wire Element","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Software Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Blue)","Unpowered Installation Repair Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Datapad","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Mark V Circuit Board","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Medical Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Holorecorder","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Droid Battery (Black/Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Wiring (Purple)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Weak Droid Battery","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Used Vidscreen","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Shield Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Shield Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Laser Trap","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Ledger","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Software Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Survival Gear","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Control Box","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Black)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Orange)","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Holorecorder","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Droid Battery (Black/Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Droid Battery (Black/Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Used Notebook","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Used Notebook","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Wiring (White)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Rapid Program Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Rapid Program Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Clothing Repair Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Wiring (Orange)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Datapad","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Vocabulator","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Wiring (Blue)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Weak Droid Battery","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Control Box","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Ledger","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Restraining Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Wiring (Green)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Hyperdrive Unit","Stamina (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Wiring (Black)","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","A Small Mining Tool","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","A Small Mining Tool","Stamina (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Worklight","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (Green)","Wiring (Red/Yellow)","Stamina (1)"));
re_Combinations.add(new RE_Combination("Laser Trap","Ledger","Stamina (1)"));
re_Combinations.add(new RE_Combination("Wiring (White)","Unpowered Installation Repair Device","Stamina (1)"));
re_Combinations.add(new RE_Combination("Restraining Device","Software Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Mark I Circuit Board","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Speederdrive","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Survival Gear","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Speederdrive","Survival Gear","Stamina (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Used Wiring","Stamina (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Mark X Vocab Module","Stamina (1)"));
re_Combinations.add(new RE_Combination("Data Housing","Medical Console","Stamina (1)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Frequency Jamming Wired","Stamina (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Wiring (Black)","Stealth (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Wiring (Orange)","Stealth (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Wiring (Purple)","Stealth (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Wiring (Green)","Stealth (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Wiring (Red/Yellow)","Stealth (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Wiring (Blue)","Stealth (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Power Cell","Wiring (White)","Stealth (1)"));
re_Combinations.add(new RE_Combination("Control Box","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Rapid Program Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Software Module","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Rapid Program Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Rapid Program Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Remote Transmitter","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Datapad","Strength (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Droid Battery (Teal)","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Emergency Reactivator","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Tubing","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Impulse Detector","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Software Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Software Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Unpowered Installation Repair Device","Strength (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Software Module","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Mark V Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Wire Element","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Rapid Program Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Remote Transmitter","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Datapad","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Droid Battery (Purple/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Emergency Reactivator","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Shield Module","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Ledger","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Mark V Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Mark V Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Palm Diary","Strength (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Newsfilter Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Medical Console","Strength (1)"));
re_Combinations.add(new RE_Combination("Palm Diary","Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Rapid Program Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","A Damaged Droid Swivel Joint","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Remote Transmitter","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Remote Transmitter","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Remote Transmitter","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Droid Battery (Teal)","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Wire Element","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Wire Element","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Wire Element","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Impulse Detector","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Impulse Detector","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","A Small Mining Tool","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Ledger","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Unpowered Installation Repair Device","Strength (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Unpowered Installation Repair Device","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Mark I Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Mark V Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Medical Console","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Palm Diary","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Medical Console","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Collapsed Artifact","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Control Box","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Droid Battery (Purple/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","A Small Mining Tool","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","A Small Mining Tool","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Mark I Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Mark I Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Mark VII Vocabulation Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Medical Console","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Remote Transmitter","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","A Damaged Droid Swivel Joint","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Remote Transmitter","Strength (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Droid Battery (Teal)","Strength (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Droid Battery (Teal)","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Wire Element","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Shield Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Impulse Detector","Strength (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Ledger","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Mark I Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Mark VII Vocabulation Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Software Module","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Palm Diary","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Medical Console","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Medical Console","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Shield Module","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Plugged Hydraulics System","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("A Small Mining Tool","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Rapid Program Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","A Damaged Droid Memory Unit","Strength (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Droid Battery (Purple/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Swivel Joint","Droid Battery (Purple/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Droid Battery (Teal)","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Ledger","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Ledger","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Unpowered Installation Repair Device","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Software Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Software Module","Unpowered Installation Repair Device","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Mark VII Vocabulation Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Unpowered Installation Repair Device","Used Wiring","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Black/Green)","Palm Diary","Strength (1)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Rapid Program Module","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Survival Gear","Used Vidscreen","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Weak Droid Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wire Element","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Ledger","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Software Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("Circuit Board","Mark VII Vocabulation Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark V Circuit Board","Mark VII Vocabulation Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Palm Diary","Strength (1)"));
re_Combinations.add(new RE_Combination("Tubing","Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Used Notebook","Strength (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Rapid Program Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Control Box","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Remote Transmitter","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Wire Element","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Emergency Reactivator","Strength (1)"));
re_Combinations.add(new RE_Combination("Weak Droid Battery","Wire Element","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Shield Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Shield Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Ledger","Shield Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Impulse Detector","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","A Small Mining Tool","Strength (1)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Ledger","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Software Module","Strength (1)"));
re_Combinations.add(new RE_Combination("Datapad","Survival Gear","Strength (1)"));
re_Combinations.add(new RE_Combination("Mark I Circuit Board","Mark V Circuit Board","Strength (1)"));
re_Combinations.add(new RE_Combination("Impulse Detector","Battery","Strength (1)"));
re_Combinations.add(new RE_Combination("Control Box","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Battery","Frequency Jamming Wired","Strength (1)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Droid Battery (Black/Green)","Strength (1)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Servo Joint","Structure Assembly (3)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Medical Device","Structure Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Demagnetized Datadisk","Structure Assembly (3)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Demagnetized Datadisk","Structure Assembly (3)"));
re_Combinations.add(new RE_Combination("Software Module","Demagnetized Datadisk","Structure Assembly (3)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Differential Regulator","Structure Assembly (3)"));
re_Combinations.add(new RE_Combination("Power Output Device","Differential Regulator","Structure Assembly (3)"));
re_Combinations.add(new RE_Combination("Burnt Out Droid Motor","Datapad","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Survival Gear","Weak Droid Battery","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Datapad","Droid Motor (Yellow)","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Survival Gear","Droid Battery (Black/Green)","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Survival Gear","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Motivator","Datapad","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Datapad","Droid Motor (Red)","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Survival Gear","Battery","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Survival Gear","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Datapad","Locomotor","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("Datapad","Motor","Structure Experimentation (4)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Mark X Vocab Module","Sure Shot Action Cost (8)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Mark X Vocab Module","Sure Shot Action Cost (8)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Software Module","Sure Shot Action Cost (8)"));
re_Combinations.add(new RE_Combination("Mark X Vocab Module","Rations Kit","Sure Shot Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Circuit Board","Clothing Repair Device","Tracking Droids (4)"));
re_Combinations.add(new RE_Combination("Collapsed Artifact","Laser Trap","Tracking Droids (4)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Mark V Circuit Board","Tracking Droids (4)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Mark I Circuit Board","Tracking Droids (4)"));
re_Combinations.add(new RE_Combination("Speederdrive","Wiring (White)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Wiring (Black)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Used Wiring","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Wiring (Orange)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("ID Chip","Survival Gear","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Wiring (Green)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Wiring (Red/Yellow)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Survival Gear","Used ID Chip","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Wiring (Blue)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Wiring (Green)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Wiring (Red/Yellow)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Wiring (Blue)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Wiring (Black)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Wiring (White)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Speederdrive","Wiring (Orange)","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Used Wiring","Unarmed Action Cost (10)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Used Notebook","Unarmed Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Used Notebook","Unarmed Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Software Module","Used Notebook","Unarmed Critical Chance (10)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Mark VII Vocabulation Module","Unarmed Damage (14)"));
re_Combinations.add(new RE_Combination("Clothing Repair Device","Software Module","Unarmed Damage (14)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Plugged Hydraulics System","Vital Strike Action Cost (8)"));
re_Combinations.add(new RE_Combination("Plugged Hydraulics System","Tranceiver","Vital Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Tranceiver","Tubing","Vital Strike Critical Chance (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wiring (Purple)","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wiring (Red/Yellow)","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wiring (Blue)","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wiring (Green)","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wiring (Black)","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wiring (Orange)","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Mark X Vocab Module","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Wiring (White)","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Vocabulator","Used Wiring","Vital Strike Damage (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wiring (Purple)","Vital Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wiring (Red/Yellow)","Vital Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wiring (Blue)","Vital Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wiring (Green)","Vital Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wiring (Black)","Vital Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wiring (Orange)","Vital Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Used Notebook","Wiring (White)","Vital Strike Freeshot Chance (8)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Droid Battery (Black/Green)","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Control Box","A Small Mining Tool","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Power Output Device","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","ID Chip","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Emergency Reactivator","Used ID Chip","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Power Output Analyzer","Weak Droid Battery","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Comlink","Emergency Reactivator","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Power Output Device","Droid Battery (Black/Green)","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Purple/Green)","Power Output Analyzer","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Power Output Device","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Data Housing","Datapad","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Power Output Device","Weak Droid Battery","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Droid Battery (Teal)","Power Output Analyzer","Weapon Assembly (3)"));
re_Combinations.add(new RE_Combination("Hyperdrive Unit","Restraining Device","Weapon Experimentation (4)"));
re_Combinations.add(new RE_Combination("Chassis Blueprints","Launcher Tube","Weapon Experimentation (4)"));
re_Combinations.add(new RE_Combination("Datapad","Used Notebook","Weapon Experimentation (4)"));
re_Combinations.add(new RE_Combination("Comlink","Explosive Dud","Weapon Experimentation (4)"));
re_Combinations.add(new RE_Combination("Launcher Tube","Rapid Program Module","Weapon Experimentation (4)"));
re_Combinations.add(new RE_Combination("Restraining Device","Speederdrive","Weapon Experimentation (4)"));
re_Combinations.add(new RE_Combination("Mark VII Vocabulation Module","Differential Regulator","Weapon Systems Assembly (3)"));
re_Combinations.add(new RE_Combination("A Damaged Droid Memory Unit","Differential Regulator","Weapon Systems Assembly (3)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Droid Memory Module","Weapon Systems Assembly (3)"));
re_Combinations.add(new RE_Combination("Explosive Dud","Restraining Device","Weapon Systems Experimentation (4)"));
re_Combinations.add(new RE_Combination("Magseal Detector","Tranceiver","Weapon Systems Experimentation (4)"));
}
public void createMappings(){
skillModMapping.put("1-H Light Saber Action Cost","expertise_action_weapon_9");
skillModMapping.put("1-H Lightsaber Damage","expertise_damage_weapon_9");
skillModMapping.put("1-H Melee Action Cost","expertise_action_weapon_4");
skillModMapping.put("1-H Melee Critical Chance","expertise_critical_1h");
skillModMapping.put("1-H Melee Damage","onehandmelee_damage");
skillModMapping.put("2-H Lightsaber Damage","expertise_damage_weapon_10");
skillModMapping.put("2-H Melee Action Cost","expertise_action_weapon_5");
skillModMapping.put("2-H Melee Critical Chance","expertise_critical_2h");
skillModMapping.put("2-H Melee Damage","expertise_damage_weapon_5");
skillModMapping.put("Advanced Component Experimentation","advanced_ship_experimentation");
skillModMapping.put("Agility","agility_modified");
skillModMapping.put("Armor Assembly","armor_assembly");
skillModMapping.put("Armor Experimentation","armor_experimentation");
skillModMapping.put("Artisan Assembly","general_assembly");
skillModMapping.put("Artisan Experimentation","general_experimentation");
skillModMapping.put("Assassinate Action Cost","expertise_action_line_sp_dm");
skillModMapping.put("Assassinate Critical Chance","expertise_critical_line_sp_dm");
skillModMapping.put("Assassinate Freeshot Chance","expertise_freeshot_sp_dm");
skillModMapping.put("Assault Action Cost","expertise_action_line_dm");
skillModMapping.put("Assault Critical Chance","expertise_critical_line_dm");
skillModMapping.put("Assault Damage","expertise_damage_line_dm");
skillModMapping.put("Assault Freeshot Chance","expertise_freeshot_dm");
skillModMapping.put("Bleed Resistance","resistance_bleeding");
skillModMapping.put("Bleeding Absorption","absorption_bleeding");
skillModMapping.put("Booster Assembly","booster_assembly");
skillModMapping.put("Booster Experimentation","booster_experimentation");
skillModMapping.put("Camouflage","camouflage");
skillModMapping.put("Carbine Action Cost","expertise_action_weapon_1");
skillModMapping.put("Carbine Damage","expertise_damage_weapon_1");
skillModMapping.put("Chassis Assembly","chassis_assembly");
skillModMapping.put("Chassis Experimentation","chassis_experimentation");
skillModMapping.put("Clothing Assembly","clothing_assembly");
skillModMapping.put("Clothing Experimentation","clothing_experimentation");
skillModMapping.put("Constitution","constitution_modified");
skillModMapping.put("Creature Critical Chance","expertise_critical_niche_creature");
skillModMapping.put("Dance Prop Assembly","prop_assembly");
skillModMapping.put("Dancing Enhancement","healing_dance_mind");
skillModMapping.put("Dancing Knowledge","healing_dance_ability");
skillModMapping.put("Disease Absorption","absorption_disease");
skillModMapping.put("Droid Assembly","droid_assembly");
skillModMapping.put("Droid Critical Chance","expertise_critical_niche_droid");
skillModMapping.put("Droid Experimentation","droid_experimentation");
skillModMapping.put("Droid Speed","droid_find_speed");
skillModMapping.put("Engine Assembly","engine_assembly");
skillModMapping.put("Engine Experimentation","engine_experimentation");
skillModMapping.put("Fast Draw Action Cost","expertise_action_line_sm_dm");
skillModMapping.put("Fast Draw Critical Chance","expertise_critical_line_sm_dm");
skillModMapping.put("Fast Draw Damage","expertise_damage_line_sm_dm");
skillModMapping.put("Fire Absorption","absorption_fire");
skillModMapping.put("Fire Resistance","resistance_fire");
skillModMapping.put("Focused Fire Action Cost","expertise_action_line_co_dm");
skillModMapping.put("Focused Fire Damage","expertise_damage_line_co_dm");
skillModMapping.put("Focused Fire Freeshot Chance","expertise_freeshot_co_dm");
skillModMapping.put("Food Assembly","food_assembly");
skillModMapping.put("Food Experimentation","food_experimentation");
skillModMapping.put("Glancing Blow Increase","glancing_blow_vulnerable");
skillModMapping.put("Glancing Blow Increase (Melee)","expertise_glancing_blow_melee");
skillModMapping.put("Glancing Blow Increase (Ranged)","expertise_glancing_blow_ranged");
skillModMapping.put("Healing Potency","expertise_healing_all");
skillModMapping.put("Heavy Weapon Action Cost","expertise_action_weapon_12");
skillModMapping.put("Heavy Weapon Critical Chance","expertise_critical_heavy");
skillModMapping.put("Humanoid Critical Chance","expertise_critical_niche_npc");
skillModMapping.put("Instrument Assembly","instrument_assembly");
skillModMapping.put("Jedi Strike Action Cost","expertise_action_line_fs_dm");
skillModMapping.put("Jedi Strike Critical Chance","expertise_critical_line_fs_dm");
skillModMapping.put("Jedi Strike Damage","expertise_damage_line_fs_dm");
skillModMapping.put("Jedi Strike Freeshot Chance","expertise_freeshot_fs_dm");
skillModMapping.put("Lightsaber Assembly","jedi_saber_assembly");
skillModMapping.put("Lightsaber Experimentation","jedi_saber_experimentation");
skillModMapping.put("Luck","luck_modified");
skillModMapping.put("Music Knowledge","healing_music_ability");
skillModMapping.put("Musical Enhancement","healing_music_mind");
skillModMapping.put("Pistol Action Cost","expertise_action_weapon_2");
skillModMapping.put("Pistol Critical Chance","expertise_critical_pistol");
skillModMapping.put("Pistol Damage","expertise_damage_weapon_2");
skillModMapping.put("Poison Absorption","absorption_poison");
skillModMapping.put("Poison Resistance","resistance_poison");
skillModMapping.put("Polearm Critical Chance","expertise_critical_polearm");
skillModMapping.put("Polearm Damage","expertise_damage_weapon_7");
skillModMapping.put("Polearm Lightsaber Action Cost","expertise_action_weapon_11");
skillModMapping.put("Polearm Lightsaber Damage","expertise_damage_weapon_11");
skillModMapping.put("Power Systems Assembly","power_systems");
skillModMapping.put("Power Systems Experimentation","power_systems_experimentation");
skillModMapping.put("Precision","precision_modified");
skillModMapping.put("PVP Critical Chance","expertise_critical_niche_pvp");
skillModMapping.put("Reverse Engineering Chance","expertise_reverse_engineering_bonus");
skillModMapping.put("Rifle Action Cost","expertise_action_weapon_0");
skillModMapping.put("Rifle Critical Chance","expertise_critical_rifle");
skillModMapping.put("Rifle Damage","expertise_damage_weapon_0");
skillModMapping.put("Shield Assembly","shields_assembly");
skillModMapping.put("Shield Experimentation","shields_experimentation");
skillModMapping.put("Stamina","stamina_modified");
skillModMapping.put("Stealth","stealth");
skillModMapping.put("Strength","strength_modified");
skillModMapping.put("Structure Assembly","structure_assembly");
skillModMapping.put("Structure Experimentation","structure_experimentation");
skillModMapping.put("Sure Shot Action Cost","expertise_action_line_of_sure");
skillModMapping.put("Sure Shot Freeshot Chance","expertise_freeshot_of_sure");
skillModMapping.put("Tracking Droids","droid_tracks");
skillModMapping.put("Unarmed Action Cost","expertise_action_weapon_6");
skillModMapping.put("Unarmed Critical Chance","expertise_critical_unarmed");
skillModMapping.put("Unarmed Damage","expertise_damage_weapon_6");
skillModMapping.put("Vital Strike Action Cost","expertise_action_line_me_dm");
skillModMapping.put("Vital Strike Critical Chance","expertise_critical_line_me_dm");
skillModMapping.put("Vital Strike Damage","expertise_damage_line_me_dm");
skillModMapping.put("Vital Strike Freeshot Chance","expertise_freeshot_me_dm");
skillModMapping.put("Weapon Assembly","weapon_assembly");
skillModMapping.put("Weapon Experimentation","weapon_experimentation");
skillModMapping.put("Weapon Systems Assembly","weapon_systems");
skillModMapping.put("Weapon Systems Experimentation","weapon_systems_experimentation");
}
public void reverseEngineer(CreatureObject engineer, TangibleObject retool){
// First determine what's inside the RE Tool
final Vector<SWGObject> reToolContentList = new Vector<SWGObject>();
SWGObject engineerInventory = engineer.getSlottedObject("inventory");
retool.viewChildren(engineer, false, false, new Traverser() {
@Override
public void process(SWGObject obj) {
reToolContentList.add(obj);
//System.out.println(obj.getTemplate());
}
});
if (reToolContentList.size()==0)
return;
// Power-Bit Creation
if (reToolContentList.size()==1){
TangibleObject piece = (TangibleObject) reToolContentList.get(0);
if (piece.getStringAttribute("bio_link")!=null)
return;
if (! piece.getTemplate().contains("object/tangible/wearables/"))
return;
if (piece.getTemplate().contains("object/tangible/wearables/")){
// Determine how powerful the bit will be
int highestStat = getHighestStat(piece);
int numberOfStats = getNumberOfStats(piece);
//System.out.println("highestStat " + highestStat);
//System.out.println("numberOfStats " + numberOfStats);
int powerBitOrder = 1;
String powerBitOrderString = "1st";
int powerBitValue = 1;
// Determine the quality factor based on total buffs (RE Chance, Luck etc.)
float qualityfactor = 1.0F; // For now it's 1
int luck = engineer.getLuck();
qualityfactor += luck/1000; // around 1200 luck was top
qualityfactor = Math.max(1.0F, qualityfactor);
int itemCL = 1;
if (piece.getAttributes().get("required_combat_level")!=null)
itemCL = piece.getIntAttribute("required_combat_level");
float CLFactor = itemCL/85.71F; // item Combat Level adds a small amount too
if (CLFactor>1.0F)
qualityfactor += (CLFactor-1.0F);
int re_Chance = engineer.getSkillModBase("expertise_reverse_engineering_bonus");
float re_factor = re_Chance/140 * qualityfactor; // 159 RE-Chance was top
qualityfactor = Math.max(re_factor, qualityfactor);
powerBitValue = Math.round(highestStat * qualityfactor);
if (numberOfStats==1){
int roll = new Random().nextInt()*100;
if (roll<20){
powerBitOrder=2;
powerBitOrderString="2nd";
}
}
if (numberOfStats==2){
powerBitOrder=2;
powerBitOrderString="2nd";
}
if (numberOfStats==3 || numberOfStats==4){
powerBitOrder=3;
powerBitOrderString="3rd";
}
core.objectService.destroyObject(piece.getObjectID());
String powerBitTemplate = "object/tangible/component/reverse_engineering/shared_power_bit.iff";
TangibleObject powerBit = (TangibleObject) core.objectService.createObject(powerBitTemplate, engineer.getPlanet());
powerBit.setCustomName("+" + powerBitValue + " " + powerBitOrderString + " Order Power Bit");
powerBit.setAttachment("PowerBitValue", powerBitValue);
powerBit.setAttachment("PowerBitOrder", powerBitOrder);
engineerInventory.add(powerBit);
}
}
// Modifier-Bit Creation
String pcr = "";
String modifierBitNameResult = null;
if (reToolContentList.size()==2){
TangibleObject piece1 = (TangibleObject) reToolContentList.get(0);
TangibleObject piece2 = (TangibleObject) reToolContentList.get(1);
//if (! piece1.getTemplate().contains("lootItems/npc_loot/") || piece2.getTemplate().contains("lootItems/npc_loot/"))
//return; // No junk loot
// if (piece1.getTemplate().contains("modifier_bit") && piece2.getTemplate().contains("power_bit")
// || piece1.getTemplate().contains("power_bit") && piece2.getTemplate().contains("modifier_bit")){
// return; // Fail-safe if someone wants to RE bits
// }
String modifierBitName = null;
String piece1Name = getCorrectJunkName(piece1);
String piece2Name = getCorrectJunkName(piece2);
for (RE_Combination comb : re_Combinations){
if (comb.getIngredient1().contains(piece1Name) && comb.getIngredient2().contains(piece2Name)
|| comb.getIngredient1().contains(piece2Name) && comb.getIngredient2().contains(piece1Name)){
modifierBitNameResult = comb.getResult(); // "Rifle Critical Chance (10)"
String[] modNameArr = modifierBitNameResult.split("\\(");
modifierBitName = modNameArr[0].replace("\\(", "").trim();
String[] modArr2 = modNameArr[1].split("\\)");
pcr = modArr2[0].replace("\\)","").trim();
}
}
System.out.println("modifierBitNameResult " + modifierBitNameResult);
System.out.println("modifierBitName " + modifierBitName);
if (modifierBitNameResult==null){
return;
}
String skillModName = skillModMapping.get(modifierBitName);
System.out.println("skillModName " + skillModName);
if (skillModName==null){
engineer.sendSystemMessage("Junkloot combination wrong/not registered yet or Junkloot names don't conform to http://www.nova-inside.com naming convention",(byte) 0);
return;
}
// core.objectService.destroyObject(piece1.getObjectID());
// core.objectService.destroyObject(piece2.getObjectID());
int piece1Uses = piece1.getUses()-1;
int piece2Uses = piece2.getUses()-1;
piece1.setUses(piece1Uses);
piece2.setUses(piece2Uses);
if (piece1Uses==0)
core.objectService.destroyObject(piece1.getObjectID());
if (piece2Uses==0)
core.objectService.destroyObject(piece2.getObjectID());
int pcrIntValue = Integer.parseInt(pcr);
String modifierBitTemplate = "object/tangible/component/reverse_engineering/shared_modifier_bit.iff";
TangibleObject modifierBit = (TangibleObject) core.objectService.createObject(modifierBitTemplate, engineer.getPlanet());
modifierBit.setCustomName(modifierBitName);
modifierBit.setStringAttribute("serial_number", createSerialNumber());
modifierBit.setStringAttribute("@crafting:mod_bit_type", "@stat_n:"+skillModName);
modifierBit.setIntAttribute("@crafting:mod_bit_ratio", pcrIntValue);
engineerInventory.add(modifierBit);
}
}
public String createSerialNumber(){
String serialNumber = "(";
char ascii;
int numberOfSerialDigits=8;
int numbersStart=48;
int lettersStart=97;
for (int k=0;k<numberOfSerialDigits;k++){
ascii = (char) new Random().nextInt(34);
if (ascii < 9)
ascii = (char)(ascii+numbersStart);
else {
ascii -= 9;
ascii =(char)(ascii+lettersStart);
}
serialNumber += ascii;
}
serialNumber += ")";
return serialNumber;
}
public void createPowerup(CreatureObject engineer, TangibleObject retool){
PlayerObject player = (PlayerObject) engineer.getSlottedObject("ghost");
String profession = player.getProfession();
if (profession.equals("trader_0b")) // Structures can't make PUPs
return;
final Vector<SWGObject> reToolContentList = new Vector<SWGObject>();
SWGObject engineerInventory = engineer.getSlottedObject("inventory");
retool.viewChildren(engineer, false, false, new Traverser() {
@Override
public void process(SWGObject obj) {
reToolContentList.add(obj);
//System.out.println(obj.getTemplate());
}
});
if (reToolContentList.size()==0)
return;
// Power Up Creation
if (reToolContentList.size()==2){
TangibleObject bit1 = (TangibleObject) reToolContentList.get(0);
TangibleObject bit2 = (TangibleObject) reToolContentList.get(1);
if (bit1.getTemplate().contains("modifier_bit") && bit2.getTemplate().contains("power_bit")
|| bit1.getTemplate().contains("power_bit") && bit2.getTemplate().contains("modifier_bit")){
int amount = 200 + new Random().nextInt(50); // Needs to be randomized and skillmod-related
int luck = engineer.getLuck();
float factor = luck/700;
float multiplier = Math.max(1.0F, factor);
amount = (int) (multiplier * amount); // around 1200 luck was top
int powerValue = 1;
String effectName = null;
int ratio = 1;
int powerBitValue = 1;
if (bit1.getTemplate().contains("modifier_bit")){
effectName = bit1.getStringAttribute("@crafting:mod_bit_type");
ratio = bit1.getIntAttribute("@crafting:mod_bit_ratio");
}
if (bit2.getTemplate().contains("modifier_bit")){
effectName = bit2.getStringAttribute("@crafting:mod_bit_type");
ratio = bit2.getIntAttribute("@crafting:mod_bit_ratio");
}
if (bit1.getTemplate().contains("power_bit")){
powerBitValue = (int) bit1.getAttachment("PowerBitValue");
}
if (bit2.getTemplate().contains("power_bit")){
powerBitValue = (int) bit2.getAttachment("PowerBitValue");
}
int re_Chance = engineer.getSkillModBase("expertise_reverse_engineering_bonus");
float X = (float) (new Random().nextFloat() * (1.1 - 0.85) + 0.85); // Magic number
//powerValue = 3*powerBitValue/ratio; // rough
powerValue = (int) Math.floor( 2 * powerBitValue / ratio * re_Chance / 100 * X );
// Assuming munition
String powerUpLabel = "item_reverse_engineering_powerup_armor_02_01";
String powerUpDescription = "item_reverse_engineering_powerup_armor_02_01";
String powerUpTemplate = "object/tangible/loot/generic_usable/shared_copper_battery_usuable.iff";
if (profession.equals("trader_0a")){ // Domestic
powerUpLabel = "item_reverse_engineering_powerup_clothing_02_01";
powerUpDescription = "item_reverse_engineering_powerup_clothing_02_01";
powerUpTemplate = "object/tangible/loot/generic_usable/shared_chassis_blueprint_usuable.iff";
}
if (profession.equals("trader_0d")){ // Engineer
powerUpLabel = "item_reverse_engineering_powerup_weapon_02_01";
powerUpDescription = "item_reverse_engineering_powerup_weapon_02_01";
powerUpTemplate = "object/tangible/powerup/base/shared_weapon_base.iff";
}
core.objectService.destroyObject(bit1.getObjectID());
core.objectService.destroyObject(bit2.getObjectID());
TangibleObject powerUp = (TangibleObject) core.objectService.createObject(powerUpTemplate, engineer.getPlanet());
powerUp.setStfFilename("static_item_n");
powerUp.setStfName(powerUpLabel);
powerUp.setDetailFilename("static_item_d");
powerUp.setDetailName(powerUpDescription);
powerUp.setIntAttribute(effectName, powerValue);
powerUp.setAttachment("effectName",effectName);
powerUp.setAttachment("powerValue",powerValue);
powerUp.setIntAttribute("num_in_stack", amount);
powerUp.setAttachment("radial_filename", "item/item");
engineerInventory.add(powerUp);
}
}
}
@SuppressWarnings({ "unchecked", "unused" })
public void createSEA(CreatureObject engineer, TangibleObject retool){
PlayerObject player = (PlayerObject) engineer.getSlottedObject("ghost");
String profession = player.getProfession();
if (profession.equals("trader_0b")) // Structures can't make SEAs
return;
final Vector<SWGObject> reToolContentList = new Vector<SWGObject>();
SWGObject engineerInventory = engineer.getSlottedObject("inventory");
retool.viewChildren(engineer, false, false, new Traverser() {
@Override
public void process(SWGObject obj) {
reToolContentList.add(obj);
//System.out.println(obj.getTemplate());
}
});
if (reToolContentList.size()==0)
return;
// SEA Creation
if (reToolContentList.size()==2){
TangibleObject bit1 = (TangibleObject) reToolContentList.get(0);
TangibleObject bit2 = (TangibleObject) reToolContentList.get(1);
if (bit1.getTemplate().contains("modifier_bit") && bit2.getTemplate().contains("power_bit")
|| bit1.getTemplate().contains("power_bit") && bit2.getTemplate().contains("modifier_bit")){
String customName = "";
String effectName = "";
int ratio = 1;
int modifierValue = 1;
if (bit1.getTemplate().contains("modifier_bit")){
customName = bit1.getCustomName();
effectName = bit1.getStringAttribute("@crafting:mod_bit_type");
ratio = bit1.getIntAttribute("@crafting:mod_bit_ratio");
}
if (bit2.getTemplate().contains("modifier_bit")){
customName = bit2.getCustomName();
effectName = bit2.getStringAttribute("@crafting:mod_bit_type");
ratio = bit2.getIntAttribute("@crafting:mod_bit_ratio");
}
if (bit1.getTemplate().contains("power_bit")){
modifierValue = (int) bit1.getAttachment("PowerBitValue");
}
if (bit2.getTemplate().contains("power_bit")){
modifierValue = (int) bit2.getAttachment("PowerBitValue");
}
modifierValue = modifierValue/ratio; // int cast truncates
// Assuming munition
String SEALabel = "socket_gem_armor";
String SEADescription = "socket_gem";
String SEATemplate = "object/tangible/gem/shared_armor.iff";
if (profession.equals("trader_0a")){
SEALabel = "socket_gem_clothing";
SEADescription = "socket_gem";
SEATemplate = "object/tangible/gem/shared_clothing.iff";
}
if (profession.equals("trader_0d")){
SEALabel = "socket_gem_weapon";
SEADescription = "socket_gem";
SEATemplate = "object/tangible/gem/shared_weapon.iff";
}
core.objectService.destroyObject(bit1.getObjectID());
core.objectService.destroyObject(bit2.getObjectID());
TangibleObject skillEnhancingAttachment = (TangibleObject) core.objectService.createObject(SEATemplate, engineer.getPlanet());
skillEnhancingAttachment.setStfFilename("item_n");
skillEnhancingAttachment.setStfName(SEALabel);
skillEnhancingAttachment.setDetailFilename("item_n");
skillEnhancingAttachment.setDetailName(SEADescription);
skillEnhancingAttachment.setIntAttribute(effectName, modifierValue);
Vector<String> effectNameList = new Vector<String>();
effectNameList.add(effectName);
Vector<Integer> effectValueList = new Vector<Integer>();
effectValueList.add(modifierValue);
skillEnhancingAttachment.setAttachment("SEAeffectNameList", effectNameList);
skillEnhancingAttachment.setAttachment("SEAmodifierValueList", effectValueList);
skillEnhancingAttachment.setAttachment("radial_filename", "item/item");
//skillEnhancingAttachment.setOptions(Options.SOCKETED, true);
skillEnhancingAttachment.setOptions(Options.USABLE, true);
engineerInventory.add(skillEnhancingAttachment);
}
}
// Multi-stat SEA
if (reToolContentList.size()==3){
TangibleObject bit1 = (TangibleObject) reToolContentList.get(0);
TangibleObject bit2 = (TangibleObject) reToolContentList.get(1);
TangibleObject bit3 = (TangibleObject) reToolContentList.get(2);
String effectName = "";
int ratio = 1;
int powermodifierValue = 1;
int modifierValue = 1;
int powerBitOrder = 1;
Vector<String> effectNameList = new Vector<String>();
Vector<Integer> effectValueList = new Vector<Integer>();
String SEASTFName = "";
//verify RE tool content requirement
List<String> contentVerification = new ArrayList<String>();
contentVerification.add("modifier_bit");
contentVerification.add("power_bit");
contentVerification.add("sea");
if (bit1.getTemplate().contains("modifier_bit")){
effectName = bit1.getStringAttribute("@crafting:mod_bit_type");
ratio = bit1.getIntAttribute("@crafting:mod_bit_ratio");
contentVerification.remove("modifier_bit");
}
if (bit1.getTemplate().contains("power_bit")){
powermodifierValue = (int) bit1.getAttachment("PowerBitValue");
powerBitOrder = (int) bit1.getAttachment("PowerBitOrder");
contentVerification.remove("power_bit");
}
if (bit1.getTemplate().contains("object/tangible/gem/shared_clothing.iff")){
effectNameList = (Vector<String>) bit1.getAttachment("SEAeffectNameList");
effectValueList = (Vector<Integer>) bit1.getAttachment("SEAmodifierValueList");
SEASTFName = bit1.getStfName();
if (effectNameList.size()==3)
return;
contentVerification.remove("sea");
}
if (bit2.getTemplate().contains("modifier_bit")){
effectName = bit2.getStringAttribute("@crafting:mod_bit_type");
ratio = bit2.getIntAttribute("@crafting:mod_bit_ratio");
contentVerification.remove("modifier_bit");
}
if (bit2.getTemplate().contains("power_bit")){
powermodifierValue = (int) bit2.getAttachment("PowerBitValue");
powerBitOrder = (int) bit2.getAttachment("PowerBitOrder");
contentVerification.remove("power_bit");
}
if (bit2.getTemplate().contains("object/tangible/gem/shared_clothing.iff")){
effectNameList = (Vector<String>) bit2.getAttachment("SEAeffectNameList");
effectValueList = (Vector<Integer>) bit2.getAttachment("SEAmodifierValueList");
SEASTFName = bit2.getStfName();
if (effectNameList.size()==3)
return;
contentVerification.remove("sea");
}
if (bit3.getTemplate().contains("modifier_bit")){
effectName = bit3.getStringAttribute("@crafting:mod_bit_type");
ratio = bit3.getIntAttribute("@crafting:mod_bit_ratio");
contentVerification.remove("modifier_bit");
}
if (bit3.getTemplate().contains("power_bit")){
powermodifierValue = (int) bit3.getAttachment("PowerBitValue");
powerBitOrder = (int) bit3.getAttachment("PowerBitOrder");
contentVerification.remove("power_bit");
}
if (bit3.getTemplate().contains("object/tangible/gem/shared_clothing.iff")){
effectNameList = (Vector<String>) bit3.getAttachment("SEAeffectNameList");
effectValueList = (Vector<Integer>) bit3.getAttachment("SEAmodifierValueList");
SEASTFName = bit3.getStfName();
if (effectNameList.size()==3)
return;
contentVerification.remove("sea");
}
if (contentVerification.size()==0){
modifierValue = powermodifierValue;
modifierValue = modifierValue/ratio; // int cast truncates
// Assuming munition
String SEALabel = "socket_gem_armor";
String SEADescription = "socket_gem";
String SEATemplate = "object/tangible/gem/shared_armor.iff";
if (profession.equals("trader_0c")){ // QA
if (! SEASTFName.equals("socket_gem_armor"))
return; // Wrong SEA type inserted
}
if (profession.equals("trader_0a")){
if (! SEASTFName.equals("socket_gem_clothing"))
return; // Wrong SEA type inserted
SEALabel = "socket_gem_clothing";
SEADescription = "socket_gem";
SEATemplate = "object/tangible/gem/shared_clothing.iff";
}
if (profession.equals("trader_0d")){
if (! SEASTFName.equals("socket_gem_weapon"))
return; // Wrong SEA type inserted
SEALabel = "socket_gem_weapon";
SEADescription = "socket_gem";
SEATemplate = "object/tangible/gem/shared_weapon.iff";
}
// SEA --- this item can have max 3 modifiers; it is not possible to stack the same kind of modifier in one SEA.
if (effectNameList.contains(effectName))
return;
core.objectService.destroyObject(bit1.getObjectID());
core.objectService.destroyObject(bit2.getObjectID());
core.objectService.destroyObject(bit3.getObjectID());
int attachmentUpgrade = engineer.getSkillModBase("expertise_attachment_upgrade");
System.out.println("attachmentUpgrade " + attachmentUpgrade);
System.out.println("player.getProfession() " + player.getProfession());
if (powerBitOrder>effectNameList.size() && attachmentUpgrade>=1){ // Only add a stat if the power bit is higher
effectNameList.add(effectName);
effectValueList.add(modifierValue);
}
TangibleObject skillEnhancingAttachment = (TangibleObject) core.objectService.createObject(SEATemplate, engineer.getPlanet());
skillEnhancingAttachment.setStfFilename("item_n");
skillEnhancingAttachment.setStfName(SEALabel);
skillEnhancingAttachment.setDetailFilename("item_n");
skillEnhancingAttachment.setDetailName(SEADescription);
for (int i=0;i<effectNameList.size();i++){
skillEnhancingAttachment.setIntAttribute(effectNameList.get(i), effectValueList.get(i));
}
skillEnhancingAttachment.setAttachment("SEAeffectNameList", effectNameList);
skillEnhancingAttachment.setAttachment("SEAmodifierValueList", effectValueList);
skillEnhancingAttachment.setAttachment("radial_filename", "item/item");
//skillEnhancingAttachment.setOptions(Options.SOCKETED, true);
skillEnhancingAttachment.setOptions(Options.USABLE, true);
engineerInventory.add(skillEnhancingAttachment);
}
}
}
public void applyPowerUp(TangibleObject powerUpObject, long objectID){
@SuppressWarnings("unused") TangibleObject object = (TangibleObject)core.objectService.getObject(objectID);
}
public int getHighestStat(TangibleObject piece){
int highestStat = 0;
Map<String,String> attributesMap = piece.getAttributes();
for (Map.Entry<String, String> entry : attributesMap.entrySet())
{
if (statNameList.contains(entry.getKey())){
int currentStat = Integer.parseInt(entry.getValue());
if (currentStat>highestStat)
highestStat=currentStat;
}
}
return highestStat;
}
public int getNumberOfStats(TangibleObject piece){
int numberOfStats = 0;
Map<String,String> attributesMap = piece.getAttributes();
for (Map.Entry<String, String> entry : attributesMap.entrySet())
{
if (statNameList.contains(entry.getKey())){
numberOfStats++;
}
}
return numberOfStats;
}
private String getCorrectJunkName(TangibleObject piece){
String junkName = piece.getCustomName();
if (piece.getTemplate().contains("shared_wiring_generic.iff")){
String colorCombo = (String)piece.getAttachment("reverse_engineering_name");
if (colorCombo!=null)
junkName = "Wiring (" + colorCombo + ")";
}
if (piece.getTemplate().contains("Droid Motor Template")){
String colorCombo = (String)piece.getAttachment("reverse_engineering_name");
if (colorCombo!=null)
junkName = "Droid Motor (" + colorCombo + ")";
}
if (piece.getTemplate().contains("Droid Battery Template")){
String colorCombo = (String)piece.getAttachment("reverse_engineering_name");
if (colorCombo!=null)
junkName = "Droid Battery (" + colorCombo + ")";
}
return junkName;
}
@Override
public void insertOpcodes(Map<Integer, INetworkRemoteEvent> arg0,
Map<Integer, INetworkRemoteEvent> arg1) {
// TODO Auto-generated method stub
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
}
| lgpl-3.0 |
dresden-ocl/dresdenocl | tests/org.dresdenocl.modelinstancetype.java.test/src/org/dresdenocl/modelinstancetype/test/testmodel/StaticPropertyAndOperationClass.java | 1882 | /*
Copyright (C) 2009 by Claas Wilke (info@claaswilke.de)
This file is part of the Java Model Instance Type Test Suite of Dresden
OCL2 for Eclipse.
Dresden OCL2 for Eclipse is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
Dresden OCL2 for Eclipse is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License along
with Dresden OCL2 for Eclipse. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dresdenocl.modelinstancetype.test.testmodel;
import java.util.List;
import org.dresdenocl.modelinstance.IModelInstance;
import org.dresdenocl.modelinstancetype.types.IModelInstanceObject;
import org.dresdenocl.pivotmodel.Operation;
import org.dresdenocl.pivotmodel.Property;
/**
* <p>
* A {@link Class} used to testing adaptations to {@link IModelInstanceObject}s.
* This class is used to test the invocation of static {@link Property}s and
* {@link Operation}s.
* </p>
* <
*
* @author Claas Wilke
*/
public class StaticPropertyAndOperationClass {
/**
* A field to test the method
* {@link IModelInstance#getStaticPropert(Property)}.
*/
protected static String staticProperty =
StaticPropertyAndOperationClass.class.getCanonicalName();
/**
* A method to test the method
* {@link IModelInstance#invokeStaticOperation(Operation, List)}.
*/
protected static String staticOperation() {
return StaticPropertyAndOperationClass.class.getCanonicalName();
}
} | lgpl-3.0 |
osbitools/OsBiToolsWs | OsBiWsDsShared/src/main/java/com/osbitools/ws/shared/binding/ds/SortTypes.java | 1440 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.07 at 01:35:19 AM EDT
//
package com.osbitools.ws.shared.binding.ds;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SortTypes.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="SortTypes">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="asc"/>
* <enumeration value="desc"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "SortTypes")
@XmlEnum
public enum SortTypes {
@XmlEnumValue("asc")
ASC("asc"),
@XmlEnumValue("desc")
DESC("desc");
private final String value;
SortTypes(String v) {
value = v;
}
public String value() {
return value;
}
public static SortTypes fromValue(String v) {
for (SortTypes c: SortTypes.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| lgpl-3.0 |
simeshev/parabuild-ci | src/org/parabuild/ci/webui/admin/displaygroup/DisplayGroupListPage.java | 2337 | /*
* Parabuild CI licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.parabuild.ci.webui.admin.displaygroup;
import org.parabuild.ci.webui.admin.system.NavigatableSystemConfigurationPage;
import org.parabuild.ci.webui.common.CommonCommandLink;
import org.parabuild.ci.webui.common.CommonLink;
import org.parabuild.ci.webui.common.GridIterator;
import org.parabuild.ci.webui.common.Pages;
import org.parabuild.ci.webui.common.WebuiUtils;
import org.parabuild.ci.webui.CommonCommandLinkWithImage;
import viewtier.ui.Layout;
import viewtier.ui.Parameters;
import viewtier.ui.StatelessTierlet;
/**
* This page shows list List of display groups.
*/
public final class DisplayGroupListPage extends NavigatableSystemConfigurationPage implements StatelessTierlet {
private static final long serialVersionUID = -2472052514871569348L; // NOPMD
public DisplayGroupListPage() {
setTitle(makeTitle("Display Groups"));
}
protected Result executeSystemConfigurationPage(final Parameters params) {
// add new group link - top
final GridIterator gi = new GridIterator(getRightPanel(), 1);
// add admin builds table
final DisplayGroupTable groupsTable = new DisplayGroupTable();
gi.add(groupsTable, 1);
// add new group link - bottom
gi.add(WebuiUtils.makeHorizontalDivider(5), 1);
gi.add(makeNewDisplayGroupLink());
return Result.Done();
}
private CommonCommandLinkWithImage makeNewDisplayGroupLink() {
final CommonCommandLinkWithImage lnkAddNewDisplayGroup = new AddDisplayGroupLink();
lnkAddNewDisplayGroup.setAlignY(Layout.TOP);
return lnkAddNewDisplayGroup;
}
private static final class AddDisplayGroupLink extends CommonCommandLinkWithImage {
AddDisplayGroupLink() {
super("Add Display Group", Pages.ADMIN_EDIT_DISPLAY_GROUP);
}
}
}
| lgpl-3.0 |
Alfresco/explorer | web-client/source/java/org/alfresco/web/forms/XSLTRenderingEngine.java | 19865 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */
package org.alfresco.web.forms;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.XMLUtil;
import org.apache.bsf.BSFManager;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xml.dtm.ref.DTMNodeProxy;
import org.apache.xml.utils.Constants;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.SAXException;
/**
* A rendering engine which uses xsl templates to render renditions of
* form instance data.
*
* @author Ariel Backenroth
*/
public class XSLTRenderingEngine
implements RenderingEngine
{
/////////////////////////////////////////////////////////////////////////////
public static class ProcessorMethodInvoker
{
private final static HashMap<String, TemplateProcessorMethod> PROCESSOR_METHODS =
new HashMap<String, TemplateProcessorMethod>();
public ProcessorMethodInvoker() { }
private Object[] convertArguments(final Object[] arguments)
{
final List result = new LinkedList();
for (int i = 0; i < arguments.length; i++)
{
LOGGER.debug("args[" + i + "] = " + arguments[i] +
"(" + (arguments[i] != null
? arguments[i].getClass().getName()
: "null") + ")");
if (arguments[i] == null ||
arguments[i] instanceof String ||
arguments[i] instanceof Number)
{
result.add(arguments[i]);
}
else if (arguments[i] instanceof DTMNodeProxy)
{
result.add(((DTMNodeProxy)arguments[i]).getStringValue());
}
else if (arguments[i] instanceof Node)
{
LOGGER.debug("node type is " + ((Node)arguments[i]).getNodeType() +
" content " + ((Node)arguments[i]).getTextContent());
result.add(((Node)arguments[i]).getNodeValue());
}
else if (arguments[i] instanceof NodeIterator)
{
Node n = ((NodeIterator)arguments[i]).nextNode();
while (n != null)
{
LOGGER.debug("iterated to node " + n + " type " + n.getNodeType() +
" value " + n.getNodeValue() +
" tc " + n.getTextContent() +
" nn " + n.getNodeName() +
" sv " + ((org.apache.xml.dtm.ref.DTMNodeProxy)n).getStringValue());
if (n instanceof DTMNodeProxy)
{
result.add(((DTMNodeProxy)n).getStringValue());
}
else
{
result.add(n);
}
n = ((NodeIterator)arguments[i]).nextNode();
}
}
else
{
throw new IllegalArgumentException("unable to convert argument " + arguments[i]);
}
}
return result.toArray(new Object[result.size()]);
}
public Object invokeMethod(final String id, Object[] arguments)
throws Exception
{
if (!PROCESSOR_METHODS.containsKey(id))
{
throw new NullPointerException("unable to find method " + id);
}
final TemplateProcessorMethod method = PROCESSOR_METHODS.get(id);
arguments = this.convertArguments(arguments);
LOGGER.debug("invoking " + id + " with " + arguments.length);
Object result = method.exec(arguments);
LOGGER.debug(id + " returned a " + result);
if (result == null)
{
return null;
}
else if (result.getClass().isArray() &&
Node.class.isAssignableFrom(result.getClass().getComponentType()))
{
LOGGER.debug("converting " + result + " to a node iterator");
final Node[] array = (Node[])result;
return new NodeIterator()
{
private int index = 0;
private boolean detached = false;
public void detach()
{
if (LOGGER.isDebugEnabled())
LOGGER.debug("detaching NodeIterator");
this.detached = true;
}
public boolean getExpandEntityReferences() { return true; }
public int getWhatToShow() { return NodeFilter.SHOW_ALL; }
public Node getRoot()
{
return (array.length == 0
? null
: array[0].getOwnerDocument().getDocumentElement());
}
public NodeFilter getFilter()
{
return new NodeFilter()
{
public short acceptNode(final Node n)
{
return NodeFilter.FILTER_ACCEPT;
}
};
}
public Node nextNode()
throws DOMException
{
if (LOGGER.isDebugEnabled())
LOGGER.debug("NodeIterator.nextNode(" + index + ")");
if (this.detached)
throw new DOMException(DOMException.INVALID_STATE_ERR, null);
return index == array.length ? null : array[index++];
}
public Node previousNode()
throws DOMException
{
if (LOGGER.isDebugEnabled())
LOGGER.debug("NodeIterator.previousNode(" + index + ")");
if (this.detached)
throw new DOMException(DOMException.INVALID_STATE_ERR, null);
return index == -1 ? null : array[index--];
}
};
}
else if (result instanceof String ||
result instanceof Number ||
result instanceof Node)
{
LOGGER.debug("returning " + result + " as is");
return result;
}
else
{
throw new IllegalArgumentException("unable to convert " + result.getClass().getName());
}
}
}
/////////////////////////////////////////////////////////////////////////////
private static final Log LOGGER = LogFactory.getLog(XSLTRenderingEngine.class);
public XSLTRenderingEngine() { }
public String getName() { return "XSLT"; }
public String getDefaultTemplateFileExtension() { return "xsl"; }
/**
* Adds a script element to the xsl which makes static methods on this
* object available to the xsl tempalte.
*
* @param xslTemplate the xsl template
*/
protected List<String> addScripts(final Map<QName, Object> model,
final Document xslTemplate)
{
final Map<QName, List<Map.Entry<QName, Object>>> methods =
new HashMap<QName, List<Map.Entry<QName, Object>>>();
for (final Map.Entry<QName, Object> entry : model.entrySet())
{
if (entry.getValue() instanceof TemplateProcessorMethod)
{
final String prefix = QName.splitPrefixedQName(entry.getKey().toPrefixString())[0];
final QName qn = QName.createQName(entry.getKey().getNamespaceURI(),
prefix);
if (!methods.containsKey(qn))
{
methods.put(qn, new LinkedList());
}
methods.get(qn).add(entry);
}
}
final Element docEl = xslTemplate.getDocumentElement();
final String XALAN_NS = Constants.S_BUILTIN_EXTENSIONS_URL;
final String XALAN_NS_PREFIX = "xalan";
docEl.setAttribute("xmlns:" + XALAN_NS_PREFIX, XALAN_NS);
final Set<String> excludePrefixes = new HashSet<String>();
if (docEl.hasAttribute("exclude-result-prefixes"))
{
excludePrefixes.addAll(Arrays.asList(docEl.getAttribute("exclude-result-prefixes").split(" ")));
}
excludePrefixes.add(XALAN_NS_PREFIX);
final List<String> result = new LinkedList<String>();
for (QName ns : methods.keySet())
{
final String prefix = ns.getLocalName();
docEl.setAttribute("xmlns:" + prefix, ns.getNamespaceURI());
excludePrefixes.add(prefix);
final Element compEl = xslTemplate.createElementNS(XALAN_NS,
XALAN_NS_PREFIX + ":component");
compEl.setAttribute("prefix", prefix);
docEl.appendChild(compEl);
String functionNames = null;
final Element scriptEl = xslTemplate.createElementNS(XALAN_NS,
XALAN_NS_PREFIX + ":script");
scriptEl.setAttribute("lang", "javascript");
final StringBuilder js =
new StringBuilder("var _xsltp_invoke = java.lang.Class.forName('" + ProcessorMethodInvoker.class.getName() +
"').newInstance();\n" +
"function _xsltp_to_java_array(js_array) {\n" +
"var java_array = java.lang.reflect.Array.newInstance(java.lang.Object, js_array.length);\n" +
"for (var i = 0; i < js_array.length; i++) { java_array[i] = js_array[i]; }\n" +
"return java_array; }\n");
for (final Map.Entry<QName, Object> entry : methods.get(ns))
{
if (functionNames == null)
{
functionNames = entry.getKey().getLocalName();
}
else
{
functionNames += " " + entry.getKey().getLocalName();
}
final String id = entry.getKey().getLocalName() + entry.getValue().hashCode();
js.append("function " + entry.getKey().getLocalName() +
"() { return _xsltp_invoke.invokeMethod('" + id +
"', _xsltp_to_java_array(arguments)); }\n");
ProcessorMethodInvoker.PROCESSOR_METHODS.put(id, (TemplateProcessorMethod)entry.getValue());
result.add(id);
}
LOGGER.debug("generated JavaScript bindings:\n" + js);
scriptEl.appendChild(xslTemplate.createTextNode(js.toString()));
compEl.setAttribute("functions", functionNames);
compEl.appendChild(scriptEl);
}
docEl.setAttribute("exclude-result-prefixes",
StringUtils.join(excludePrefixes.toArray(new String[excludePrefixes.size()]), " "));
return result;
}
/**
* Adds the specified parameters to the xsl template as variables within the
* alfresco namespace.
*
* @param model the variables to place within the xsl template
* @param xslTemplate the xsl template
*/
protected void addParameters(final Map<QName, Object> model,
final Document xslTemplate)
{
final Element docEl = xslTemplate.getDocumentElement();
final String XSL_NS = docEl.getNamespaceURI();
final String XSL_NS_PREFIX = docEl.getPrefix();
for (Map.Entry<QName, Object> e : model.entrySet())
{
if (RenderingEngine.ROOT_NAMESPACE.equals(e.getKey()))
{
continue;
}
final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable");
el.setAttribute("name", e.getKey().toPrefixString());
final Object o = e.getValue();
if (o instanceof String || o instanceof Number || o instanceof Boolean)
{
el.appendChild(xslTemplate.createTextNode(o.toString()));
docEl.insertBefore(el, docEl.getFirstChild());
}
}
}
protected Source getXMLSource(final Map<QName, Object> model)
{
if (!model.containsKey(RenderingEngine.ROOT_NAMESPACE))
{
return null;
}
final Object o = model.get(RenderingEngine.ROOT_NAMESPACE);
if (!(o instanceof Document))
{
throw new IllegalArgumentException("expected root namespace object to be a " + Document.class.getName() +
". found a " + o.getClass().getName());
}
return new DOMSource((Document)o);
}
public void render(final Map<QName, Object> model,
final RenderingEngineTemplate ret,
final OutputStream out)
throws IOException,
RenderingEngine.RenderingException,
SAXException
{
this.render(model, ret, new StreamResult(out));
}
public void render(final Map<QName, Object> model,
final RenderingEngineTemplate ret,
final Result result)
throws IOException,
RenderingEngine.RenderingException,
SAXException
{
System.setProperty("org.apache.xalan.extensions.bsf.BSFManager",
BSFManager.class.getName());
Document xslTemplate = null;
try
{
xslTemplate = XMLUtil.parse(ret.getInputStream());
}
catch (final SAXException sax)
{
throw new RenderingEngine.RenderingException(sax);
}
this.addScripts(model, xslTemplate);
this.addParameters(model, xslTemplate);
final LinkedList<TransformerException> errors = new LinkedList<TransformerException>();
final ErrorListener errorListener = new ErrorListener()
{
public void error(final TransformerException te)
throws TransformerException
{
LOGGER.debug("error " + te.getMessageAndLocation());
errors.add(te);
}
public void fatalError(final TransformerException te)
throws TransformerException
{
LOGGER.debug("fatalError " + te.getMessageAndLocation());
throw te;
}
public void warning(final TransformerException te)
throws TransformerException
{
LOGGER.debug("warning " + te.getMessageAndLocation());
errors.add(te);
}
};
// create a uri resolver to resolve document() calls to the virtualized
// web application
final URIResolver uriResolver = new URIResolver()
{
public Source resolve(final String href, String base)
throws TransformerException
{
LOGGER.debug("request to resolve href " + href +
" using base " + base);
final RenderingEngine.TemplateResourceResolver trr = (RenderingEngine.TemplateResourceResolver)
model.get(RenderingEngineTemplateImpl.PROP_RESOURCE_RESOLVER);
InputStream in = null;
try
{
in = trr.resolve(href);
}
catch (Exception e)
{
throw new TransformerException("unable to load " + href, e);
}
if (in == null)
{
throw new TransformerException("unable to resolve href " + href);
}
try
{
final Document d = XMLUtil.parse(in);
if (LOGGER.isDebugEnabled())
LOGGER.debug("loaded " + XMLUtil.toString(d));
return new DOMSource(d);
}
catch (Exception e)
{
throw new TransformerException("unable to load " + href, e);
}
}
};
Source xmlSource = this.getXMLSource(model);
Transformer t = null;
try
{
final TransformerFactory tf = TransformerFactory.newInstance();
tf.setErrorListener(errorListener);
tf.setURIResolver(uriResolver);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("xslTemplate: \n" + XMLUtil.toString(xslTemplate));
}
t = tf.newTransformer(new DOMSource(xslTemplate));
if (errors.size() != 0)
{
final StringBuilder msg = new StringBuilder("errors encountered creating tranformer ... \n");
for (TransformerException te : errors)
{
msg.append(te.getMessageAndLocation()).append("\n");
}
throw new RenderingEngine.RenderingException(msg.toString());
}
t.setErrorListener(errorListener);
t.setURIResolver(uriResolver);
t.setParameter("versionParam", "2.0");
}
catch (TransformerConfigurationException tce)
{
LOGGER.error(tce);
throw new RenderingEngine.RenderingException(tce);
}
try
{
t.transform(xmlSource, result);
}
catch (TransformerException te)
{
LOGGER.error(te.getMessageAndLocation());
throw new RenderingEngine.RenderingException(te);
}
catch (Exception e)
{
LOGGER.error("unexpected error " + e);
throw new RenderingEngine.RenderingException(e);
}
if (errors.size() != 0)
{
final StringBuilder msg = new StringBuilder("errors encountered during transformation ... \n");
for (TransformerException te : errors)
{
msg.append(te.getMessageAndLocation()).append("\n");
}
throw new RenderingEngine.RenderingException(msg.toString());
}
}
}
| lgpl-3.0 |
SonarQubeCommunity/sonar-css | sonar-css-plugin/src/test/java/org/sonar/plugins/css/CssProfileTest.java | 2240 | /*
* SonarQube CSS Plugin
* Copyright (C) 2013-2016 Tamas Kende and David RACODON
* mailto: kende.tamas@gmail.com and david.racodon@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.css;
import org.junit.Test;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.css.checks.CheckList;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CssProfileTest {
@Test
public void should_create_sonarqube_way_profile() {
ValidationMessages validation = ValidationMessages.create();
CssProfile definition = new CssProfile(universalRuleFinder());
RulesProfile profile = definition.createProfile(validation);
assertThat(profile.getName()).isEqualTo(CssProfile.SONARQUBE_WAY_PROFILE_NAME);
assertThat(profile.getLanguage()).isEqualTo(CssLanguage.KEY);
assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY)).hasSize(55);
assertThat(validation.hasErrors()).isFalse();
}
private RuleFinder universalRuleFinder() {
RuleFinder ruleFinder = mock(RuleFinder.class);
when(ruleFinder.findByKey(anyString(), anyString())).thenAnswer(
iom -> Rule.create((String) iom.getArguments()[0], (String) iom.getArguments()[1], (String) iom.getArguments()[1]));
return ruleFinder;
}
}
| lgpl-3.0 |
simeshev/parabuild-ci | test/src/org/parabuild/ci/webui/common/SSTestContinueButton.java | 1249 | /*
* Parabuild CI licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.parabuild.ci.webui.common;
import org.apache.cactus.*;
import junit.framework.*;
/**
* Tests ContinueButton
*/
public final class SSTestContinueButton extends ServletTestCase {
/** @noinspection UNUSED_SYMBOL,FieldCanBeLocal*/
private ContinueButton btnContinue = null;
public SSTestContinueButton(final String s) {
super(s);
}
public void test_create() {
// do nothing, created in setUp
}
/**
* Required by JUnit
*/
public static TestSuite suite() {
return new TestSuite(SSTestContinueButton.class);
}
protected void setUp() throws Exception {
super.setUp();
btnContinue = new ContinueButton ();
}
}
| lgpl-3.0 |
martintreurnicht/ethereumj | ethereumj-core/src/main/java/org/ethereum/validator/BlockHeaderRule.java | 2182 | /*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.validator;
import org.ethereum.core.BlockHeader;
import org.slf4j.Logger;
/**
* Parent class for {@link BlockHeader} validators
*
* @author Mikhail Kalinin
* @since 02.09.2015
*/
public abstract class BlockHeaderRule extends AbstractValidationRule {
@Override
public Class getEntityClass() {
return BlockHeader.class;
}
/**
* Runs header validation and returns its result
*
* @param header block header
*/
abstract public ValidationResult validate(BlockHeader header);
protected ValidationResult fault(String error) {
return new ValidationResult(false, error);
}
public static final ValidationResult Success = new ValidationResult(true, null);
public boolean validateAndLog(BlockHeader header, Logger logger) {
ValidationResult result = validate(header);
if (!result.success && logger.isErrorEnabled()) {
logger.warn("{} invalid {}", getEntityClass(), result.error);
}
return result.success;
}
/**
* Validation result is either success or fault
*/
public static final class ValidationResult {
public final boolean success;
public final String error;
public ValidationResult(boolean success, String error) {
this.success = success;
this.error = error;
}
}
}
| lgpl-3.0 |
djun100/afreechart | src/org/afree/chart/axis/LogarithmicAxis.java | 46140 | /* ===========================================================
* AFreeChart : a free chart library for Android(tm) platform.
* (based on JFreeChart and JCommon)
* ===========================================================
*
* (C) Copyright 2010, by ICOMSYSTECH Co.,Ltd.
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info:
* AFreeChart: http://code.google.com/p/afreechart/
* JFreeChart: http://www.jfree.org/jfreechart/index.html
* JCommon : http://www.jfree.org/jcommon/index.html
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* [Android is a trademark of Google Inc.]
*
* --------------------
* LogarithmicAxis.java
* --------------------
*
* (C) Copyright 2010, by ICOMSYSTECH Co.,Ltd.
*
* Original Author: shiraki (for ICOMSYSTECH Co.,Ltd);
* Contributor(s): Sato Yoshiaki ;
* Niwano Masayoshi;
*
* Changes (from 19-Nov-2010)
* --------------------------
* 19-Nov-2010 : port JFreeChart 1.0.13 to Android as "AFreeChart"
*
* ------------- JFreeChart ---------------------------------------------
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Original Author: Michael Duffy / Eric Thomas;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* David M. O'Donnell;
* Scott Sams;
* Sergei Ivanov;
*
* Changes
* -------
* 14-Mar-2002 : Version 1 contributed by Michael Duffy (DG);
* 19-Apr-2002 : drawVerticalString() is now drawRotatedString() in
* RefineryUtilities (DG);
* 23-Apr-2002 : Added a range property (DG);
* 15-May-2002 : Modified to be able to deal with negative and zero values (via
* new 'adjustedLog10()' method); occurrences of "Math.log(10)"
* changed to "LOG10_VALUE"; changed 'intValue()' to
* 'longValue()' in 'refreshTicks()' to fix label-text value
* out-of-range problem; removed 'draw()' method; added
* 'autoRangeMinimumSize' check; added 'log10TickLabelsFlag'
* parameter flag and implementation (ET);
* 25-Jun-2002 : Removed redundant import (DG);
* 25-Jul-2002 : Changed order of parameters in ValueAxis constructor (DG);
* 16-Jul-2002 : Implemented support for plotting positive values arbitrarily
* close to zero (added 'allowNegativesFlag' flag) (ET).
* 05-Sep-2002 : Updated constructor reflecting changes in the Axis class (DG);
* 02-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 22-Nov-2002 : Bug fixes from David M. O'Donnell (DG);
* 14-Jan-2003 : Changed autoRangeMinimumSize from Number --> double (DG);
* 20-Jan-2003 : Removed unnecessary constructors (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 08-May-2003 : Fixed plotting of datasets with lower==upper bounds when
* 'minAutoRange' is very small; added 'strictValuesFlag'
* and default functionality of throwing a runtime exception
* if 'allowNegativesFlag' is false and any values are less
* than or equal to zero; added 'expTickLabelsFlag' and
* changed to use "1e#"-style tick labels by default
* ("10^n"-style tick labels still supported via 'set'
* method); improved generation of tick labels when range of
* values is small; changed to use 'NumberFormat.getInstance()'
* to create 'numberFormatterObj' (ET);
* 14-May-2003 : Merged HorizontalLogarithmicAxis and
* VerticalLogarithmicAxis (DG);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 07-Nov-2003 : Modified to use new NumberTick class (DG);
* 08-Apr-2004 : Use numberFormatOverride if set - see patch 930139 (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
* 21-Apr-2005 : Added support for upper and lower margins; added
* get/setAutoRangeNextLogFlag() methods and changed
* default to 'autoRangeNextLogFlag'==false (ET);
* 22-Apr-2005 : Removed refreshTicks() and fixed names and parameters for
* refreshHorizontalTicks() & refreshVerticalTicks();
* changed javadoc on setExpTickLabelsFlag() to specify
* proper default (ET);
* 22-Apr-2005 : Renamed refreshHorizontalTicks --> refreshTicksHorizontal
* (and likewise the vertical version) for consistency with
* other axis classes (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG);
* 02-Mar-2007 : Applied patch 1671069 to fix zooming (DG);
* 22-Mar-2007 : Use new defaultAutoRange attribute (DG);
*
*/
package org.afree.chart.axis;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import android.graphics.Canvas;
import org.afree.ui.RectangleEdge;
import org.afree.ui.TextAnchor;
import org.afree.data.Range;
import org.afree.chart.plot.Plot;
import org.afree.chart.plot.ValueAxisPlot;
import org.afree.graphics.geom.RectShape;
/**
* A numerical axis that uses a logarithmic scale.
*/
public class LogarithmicAxis extends NumberAxis {
/** For serialization. */
private static final long serialVersionUID = 2502918599004103054L;
/** Useful constant for log(10). */
public static final double LOG10_VALUE = Math.log(10.0);
/** Smallest arbitrarily-close-to-zero value allowed. */
public static final double SMALL_LOG_VALUE = 1e-100;
/** Flag set true to allow negative values in data. */
protected boolean allowNegativesFlag = false;
/**
* Flag set true make axis throw exception if any values are
* <= 0 and 'allowNegativesFlag' is false.
*/
protected boolean strictValuesFlag = true;
/** Number formatter for generating numeric strings. */
protected final NumberFormat numberFormatterObj
= NumberFormat.getInstance();
/** Flag set true for "1e#"-style tick labels. */
protected boolean expTickLabelsFlag = false;
/** Flag set true for "10^n"-style tick labels. */
protected boolean log10TickLabelsFlag = false;
/** True to make 'autoAdjustRange()' select "10^n" values. */
protected boolean autoRangeNextLogFlag = false;
/** Helper flag for log axis processing. */
protected boolean smallLogFlag = false;
/**
* Creates a new axis.
*
* @param label the axis label.
*/
public LogarithmicAxis(String label) {
super(label);
setupNumberFmtObj(); //setup number formatter obj
}
/**
* Sets the 'allowNegativesFlag' flag; true to allow negative values
* in data, false to be able to plot positive values arbitrarily close to
* zero.
*
* @param flgVal the new value of the flag.
*/
public void setAllowNegativesFlag(boolean flgVal) {
this.allowNegativesFlag = flgVal;
}
/**
* Returns the 'allowNegativesFlag' flag; true to allow negative values
* in data, false to be able to plot positive values arbitrarily close
* to zero.
*
* @return The flag.
*/
public boolean getAllowNegativesFlag() {
return this.allowNegativesFlag;
}
/**
* Sets the 'strictValuesFlag' flag; if true and 'allowNegativesFlag'
* is false then this axis will throw a runtime exception if any of its
* values are less than or equal to zero; if false then the axis will
* adjust for values less than or equal to zero as needed.
*
* @param flgVal true for strict enforcement.
*/
public void setStrictValuesFlag(boolean flgVal) {
this.strictValuesFlag = flgVal;
}
/**
* Returns the 'strictValuesFlag' flag; if true and 'allowNegativesFlag'
* is false then this axis will throw a runtime exception if any of its
* values are less than or equal to zero; if false then the axis will
* adjust for values less than or equal to zero as needed.
*
* @return <code>true</code> if strict enforcement is enabled.
*/
public boolean getStrictValuesFlag() {
return this.strictValuesFlag;
}
/**
* Sets the 'expTickLabelsFlag' flag. If the 'log10TickLabelsFlag'
* is false then this will set whether or not "1e#"-style tick labels
* are used. The default is to use regular numeric tick labels.
*
* @param flgVal true for "1e#"-style tick labels, false for
* log10 or regular numeric tick labels.
*/
public void setExpTickLabelsFlag(boolean flgVal) {
this.expTickLabelsFlag = flgVal;
setupNumberFmtObj(); //setup number formatter obj
}
/**
* Returns the 'expTickLabelsFlag' flag.
*
* @return <code>true</code> for "1e#"-style tick labels,
* <code>false</code> for log10 or regular numeric tick labels.
*/
public boolean getExpTickLabelsFlag() {
return this.expTickLabelsFlag;
}
/**
* Sets the 'log10TickLabelsFlag' flag. The default value is false.
*
* @param flag true for "10^n"-style tick labels, false for "1e#"-style
* or regular numeric tick labels.
*/
public void setLog10TickLabelsFlag(boolean flag) {
this.log10TickLabelsFlag = flag;
}
/**
* Returns the 'log10TickLabelsFlag' flag.
*
* @return <code>true</code> for "10^n"-style tick labels,
* <code>false</code> for "1e#"-style or regular numeric tick
* labels.
*/
public boolean getLog10TickLabelsFlag() {
return this.log10TickLabelsFlag;
}
/**
* Sets the 'autoRangeNextLogFlag' flag. This determines whether or
* not the 'autoAdjustRange()' method will select the next "10^n"
* values when determining the upper and lower bounds. The default
* value is false.
*
* @param flag <code>true</code> to make the 'autoAdjustRange()'
* method select the next "10^n" values, <code>false</code> to not.
*/
public void setAutoRangeNextLogFlag(boolean flag) {
this.autoRangeNextLogFlag = flag;
}
/**
* Returns the 'autoRangeNextLogFlag' flag.
*
* @return <code>true</code> if the 'autoAdjustRange()' method will
* select the next "10^n" values, <code>false</code> if not.
*/
public boolean getAutoRangeNextLogFlag() {
return this.autoRangeNextLogFlag;
}
/**
* Overridden version that calls original and then sets up flag for
* log axis processing.
*
* @param range the new range.
*/
public void setRange(Range range) {
super.setRange(range); // call parent method
setupSmallLogFlag(); // setup flag based on bounds values
}
/**
* Sets up flag for log axis processing. Set true if negative values
* not allowed and the lower bound is between 0 and 10.
*/
protected void setupSmallLogFlag() {
// set flag true if negative values not allowed and the
// lower bound is between 0 and 10:
double lowerVal = getRange().getLowerBound();
this.smallLogFlag = (!this.allowNegativesFlag && lowerVal < 10.0
&& lowerVal > 0.0);
}
/**
* Sets up the number formatter object according to the
* 'expTickLabelsFlag' flag.
*/
protected void setupNumberFmtObj() {
if (this.numberFormatterObj instanceof DecimalFormat) {
//setup for "1e#"-style tick labels or regular
// numeric tick labels, depending on flag:
((DecimalFormat) this.numberFormatterObj).applyPattern(
this.expTickLabelsFlag ? "0E0" : "0.###");
}
}
/**
* Returns the log10 value, depending on if values between 0 and
* 1 are being plotted. If negative values are not allowed and
* the lower bound is between 0 and 10 then a normal log is
* returned; otherwise the returned value is adjusted if the
* given value is less than 10.
*
* @param val the value.
*
* @return log<sub>10</sub>(val).
*
* @see #switchedPow10(double)
*/
protected double switchedLog10(double val) {
return this.smallLogFlag ? Math.log(val)
/ LOG10_VALUE : adjustedLog10(val);
}
/**
* Returns a power of 10, depending on if values between 0 and
* 1 are being plotted. If negative values are not allowed and
* the lower bound is between 0 and 10 then a normal power is
* returned; otherwise the returned value is adjusted if the
* given value is less than 1.
*
* @param val the value.
*
* @return 10<sup>val</sup>.
*
* @since JFreeChart 1.0.5
* @see #switchedLog10(double)
*/
public double switchedPow10(double val) {
return this.smallLogFlag ? Math.pow(10.0, val) : adjustedPow10(val);
}
/**
* Returns an adjusted log10 value for graphing purposes. The first
* adjustment is that negative values are changed to positive during
* the calculations, and then the answer is negated at the end. The
* second is that, for values less than 10, an increasingly large
* (0 to 1) scaling factor is added such that at 0 the value is
* adjusted to 1, resulting in a returned result of 0.
*
* @param val value for which log10 should be calculated.
*
* @return An adjusted log<sub>10</sub>(val).
*
* @see #adjustedPow10(double)
*/
public double adjustedLog10(double val) {
boolean negFlag = (val < 0.0);
if (negFlag) {
val = -val; // if negative then set flag and make positive
}
if (val < 10.0) { // if < 10 then
val += (10.0 - val) / 10.0; //increase so 0 translates to 0
}
//return value; negate if original value was negative:
double res = Math.log(val) / LOG10_VALUE;
return negFlag ? (-res) : res;
}
/**
* Returns an adjusted power of 10 value for graphing purposes. The first
* adjustment is that negative values are changed to positive during
* the calculations, and then the answer is negated at the end. The
* second is that, for values less than 1, a progressive logarithmic
* offset is subtracted such that at 0 the returned result is also 0.
*
* @param val value for which power of 10 should be calculated.
*
* @return An adjusted 10<sup>val</sup>.
*
* @since JFreeChart 1.0.5
* @see #adjustedLog10(double)
*/
public double adjustedPow10(double val) {
boolean negFlag = (val < 0.0);
if (negFlag) {
val = -val; // if negative then set flag and make positive
}
double res;
if (val < 1.0) {
res = (Math.pow(10, val + 1.0) - 10.0) / 9.0; //invert adjustLog10
}
else {
res = Math.pow(10, val);
}
return negFlag ? (-res) : res;
}
/**
* Returns the largest (closest to positive infinity) double value that is
* not greater than the argument, is equal to a mathematical integer and
* satisfying the condition that log base 10 of the value is an integer
* (i.e., the value returned will be a power of 10: 1, 10, 100, 1000, etc.).
*
* @param lower a double value below which a floor will be calcualted.
*
* @return 10<sup>N</sup> with N .. { 1 ... }
*/
protected double computeLogFloor(double lower) {
double logFloor;
if (this.allowNegativesFlag) {
//negative values are allowed
if (lower > 10.0) { //parameter value is > 10
// The Math.log() function is based on e not 10.
logFloor = Math.log(lower) / LOG10_VALUE;
logFloor = Math.floor(logFloor);
logFloor = Math.pow(10, logFloor);
}
else if (lower < -10.0) { //parameter value is < -10
//calculate log using positive value:
logFloor = Math.log(-lower) / LOG10_VALUE;
//calculate floor using negative value:
logFloor = Math.floor(-logFloor);
//calculate power using positive value; then negate
logFloor = -Math.pow(10, -logFloor);
}
else {
//parameter value is -10 > val < 10
logFloor = Math.floor(lower); //use as-is
}
}
else {
//negative values not allowed
if (lower > 0.0) { //parameter value is > 0
// The Math.log() function is based on e not 10.
logFloor = Math.log(lower) / LOG10_VALUE;
logFloor = Math.floor(logFloor);
logFloor = Math.pow(10, logFloor);
}
else {
//parameter value is <= 0
logFloor = Math.floor(lower); //use as-is
}
}
return logFloor;
}
/**
* Returns the smallest (closest to negative infinity) double value that is
* not less than the argument, is equal to a mathematical integer and
* satisfying the condition that log base 10 of the value is an integer
* (i.e., the value returned will be a power of 10: 1, 10, 100, 1000, etc.).
*
* @param upper a double value above which a ceiling will be calcualted.
*
* @return 10<sup>N</sup> with N .. { 1 ... }
*/
protected double computeLogCeil(double upper) {
double logCeil;
if (this.allowNegativesFlag) {
//negative values are allowed
if (upper > 10.0) {
//parameter value is > 10
// The Math.log() function is based on e not 10.
logCeil = Math.log(upper) / LOG10_VALUE;
logCeil = Math.ceil(logCeil);
logCeil = Math.pow(10, logCeil);
}
else if (upper < -10.0) {
//parameter value is < -10
//calculate log using positive value:
logCeil = Math.log(-upper) / LOG10_VALUE;
//calculate ceil using negative value:
logCeil = Math.ceil(-logCeil);
//calculate power using positive value; then negate
logCeil = -Math.pow(10, -logCeil);
}
else {
//parameter value is -10 > val < 10
logCeil = Math.ceil(upper); //use as-is
}
}
else {
//negative values not allowed
if (upper > 0.0) {
//parameter value is > 0
// The Math.log() function is based on e not 10.
logCeil = Math.log(upper) / LOG10_VALUE;
logCeil = Math.ceil(logCeil);
logCeil = Math.pow(10, logCeil);
}
else {
//parameter value is <= 0
logCeil = Math.ceil(upper); //use as-is
}
}
return logCeil;
}
/**
* Rescales the axis to ensure that all data is visible.
*/
public void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data.
}
if (plot instanceof ValueAxisPlot) {
ValueAxisPlot vap = (ValueAxisPlot) plot;
double lower;
Range r = vap.getDataRange(this);
if (r == null) {
//no real data present
r = getDefaultAutoRange();
lower = r.getLowerBound(); //get lower bound value
}
else {
//actual data is present
lower = r.getLowerBound(); //get lower bound value
if (this.strictValuesFlag
&& !this.allowNegativesFlag && lower <= 0.0) {
//strict flag set, allow-negatives not set and values <= 0
throw new RuntimeException("Values less than or equal to "
+ "zero not allowed with logarithmic axis");
}
}
//apply lower margin by decreasing lower bound:
final double lowerMargin;
if (lower > 0.0 && (lowerMargin = getLowerMargin()) > 0.0) {
//lower bound and margin OK; get log10 of lower bound
final double logLower = (Math.log(lower) / LOG10_VALUE);
double logAbs; //get absolute value of log10 value
if ((logAbs = Math.abs(logLower)) < 1.0) {
logAbs = 1.0; //if less than 1.0 then make it 1.0
} //subtract out margin and get exponential value:
lower = Math.pow(10, (logLower - (logAbs * lowerMargin)));
}
//if flag then change to log version of lowest value
// to make range begin at a 10^n value:
if (this.autoRangeNextLogFlag) {
lower = computeLogFloor(lower);
}
if (!this.allowNegativesFlag && lower >= 0.0
&& lower < SMALL_LOG_VALUE) {
//negatives not allowed and lower range bound is zero
lower = r.getLowerBound(); //use data range bound instead
}
double upper = r.getUpperBound();
//apply upper margin by increasing upper bound:
final double upperMargin;
if (upper > 0.0 && (upperMargin = getUpperMargin()) > 0.0) {
//upper bound and margin OK; get log10 of upper bound
final double logUpper = (Math.log(upper) / LOG10_VALUE);
double logAbs; //get absolute value of log10 value
if ((logAbs = Math.abs(logUpper)) < 1.0) {
logAbs = 1.0; //if less than 1.0 then make it 1.0
} //add in margin and get exponential value:
upper = Math.pow(10, (logUpper + (logAbs * upperMargin)));
}
if (!this.allowNegativesFlag && upper < 1.0 && upper > 0.0
&& lower > 0.0) {
//negatives not allowed and upper bound between 0 & 1
//round up to nearest significant digit for bound:
//get negative exponent:
double expVal = Math.log(upper) / LOG10_VALUE;
expVal = Math.ceil(-expVal + 0.001); //get positive exponent
expVal = Math.pow(10, expVal); //create multiplier value
//multiply, round up, and divide for bound value:
upper = (expVal > 0.0) ? Math.ceil(upper * expVal) / expVal
: Math.ceil(upper);
}
else {
//negatives allowed or upper bound not between 0 & 1
//if flag then change to log version of highest value to
// make range begin at a 10^n value; else use nearest int
upper = (this.autoRangeNextLogFlag) ? computeLogCeil(upper)
: Math.ceil(upper);
}
// ensure the autorange is at least <minRange> in size...
double minRange = getAutoRangeMinimumSize();
if (upper - lower < minRange) {
upper = (upper + lower + minRange) / 2;
lower = (upper + lower - minRange) / 2;
//if autorange still below minimum then adjust by 1%
// (can be needed when minRange is very small):
if (upper - lower < minRange) {
double absUpper = Math.abs(upper);
//need to account for case where upper==0.0
double adjVal = (absUpper > SMALL_LOG_VALUE) ? absUpper
/ 100.0 : 0.01;
upper = (upper + lower + adjVal) / 2;
lower = (upper + lower - adjVal) / 2;
}
}
setRange(new Range(lower, upper), false, false);
setupSmallLogFlag(); //setup flag based on bounds values
}
}
/**
* Converts a data value to a coordinate in Java2D space, assuming that
* the axis runs along one edge of the specified plotArea.
* Note that it is possible for the coordinate to fall outside the
* plotArea.
*
* @param value the data value.
* @param plotArea the area for plotting the data.
* @param edge the axis location.
*
* @return The Java2D coordinate.
*/
public double valueToJava2D(double value, RectShape plotArea,
RectangleEdge edge) {
Range range = getRange();
double axisMin = switchedLog10(range.getLowerBound());
double axisMax = switchedLog10(range.getUpperBound());
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = plotArea.getMinX();
max = plotArea.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = plotArea.getMaxY();
max = plotArea.getMinY();
}
value = switchedLog10(value);
if (isInverted()) {
return max - (((value - axisMin) / (axisMax - axisMin))
* (max - min));
}
else {
return min + (((value - axisMin) / (axisMax - axisMin))
* (max - min));
}
}
/**
* Converts a coordinate in Java2D space to the corresponding data
* value, assuming that the axis runs along one edge of the specified
* plotArea.
*
* @param java2DValue the coordinate in Java2D space.
* @param plotArea the area in which the data is plotted.
* @param edge the axis location.
*
* @return The data value.
*/
public double java2DToValue(double java2DValue, RectShape plotArea,
RectangleEdge edge) {
Range range = getRange();
double axisMin = switchedLog10(range.getLowerBound());
double axisMax = switchedLog10(range.getUpperBound());
double plotMin = 0.0;
double plotMax = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
plotMin = plotArea.getX();
plotMax = plotArea.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
plotMin = plotArea.getMaxY();
plotMax = plotArea.getMinY();
}
if (isInverted()) {
return switchedPow10(axisMax - ((java2DValue - plotMin)
/ (plotMax - plotMin)) * (axisMax - axisMin));
}
else {
return switchedPow10(axisMin + ((java2DValue - plotMin)
/ (plotMax - plotMin)) * (axisMax - axisMin));
}
}
/**
* Zooms in on the current range.
*
* @param lowerPercent the new lower bound.
* @param upperPercent the new upper bound.
*/
public void zoomRange(double lowerPercent, double upperPercent) {
double startLog = switchedLog10(getRange().getLowerBound());
double lengthLog = switchedLog10(getRange().getUpperBound()) - startLog;
Range adjusted;
if (isInverted()) {
adjusted = new Range(
switchedPow10(
startLog + (lengthLog * (1 - upperPercent))),
switchedPow10(
startLog + (lengthLog * (1 - lowerPercent))));
}
else {
adjusted = new Range(
switchedPow10(startLog + (lengthLog * lowerPercent)),
switchedPow10(startLog + (lengthLog * upperPercent)));
}
setRange(adjusted);
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param canvas the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List refreshTicksHorizontal(Canvas canvas,
RectShape dataArea,
RectangleEdge edge) {
List ticks = new java.util.ArrayList();
Range range = getRange();
//get lower bound value:
double lowerBoundVal = range.getLowerBound();
//if small log values and lower bound value too small
// then set to a small value (don't allow <= 0):
if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
lowerBoundVal = SMALL_LOG_VALUE;
}
//get upper bound value
double upperBoundVal = range.getUpperBound();
//get log10 version of lower bound and round to integer:
int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
//get log10 version of upper bound and round to integer:
int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));
if (iBegCount == iEndCount && iBegCount > 0
&& Math.pow(10, iBegCount) > lowerBoundVal) {
//only 1 power of 10 value, it's > 0 and its resulting
// tick value will be larger than lower bound of data
--iBegCount; //decrement to generate more ticks
}
double currentTickValue;
String tickLabel;
boolean zeroTickFlag = false;
for (int i = iBegCount; i <= iEndCount; i++) {
//for each power of 10 value; create ten ticks
for (int j = 0; j < 10; ++j) {
//for each tick to be displayed
if (this.smallLogFlag) {
//small log values in use; create numeric value for tick
currentTickValue = Math.pow(10, i) + (Math.pow(10, i) * j);
if (this.expTickLabelsFlag
|| (i < 0 && currentTickValue > 0.0
&& currentTickValue < 1.0)) {
//showing "1e#"-style ticks or negative exponent
// generating tick value between 0 & 1; show fewer
if (j == 0 || (i > -4 && j < 2)
|| currentTickValue >= upperBoundVal) {
//first tick of series, or not too small a value and
// one of first 3 ticks, or last tick to be displayed
// set exact number of fractional digits to be shown
// (no effect if showing "1e#"-style ticks):
this.numberFormatterObj
.setMaximumFractionDigits(-i);
//create tick label (force use of fmt obj):
tickLabel = makeTickLabel(currentTickValue, true);
}
else { //no tick label to be shown
tickLabel = "";
}
}
else { //tick value not between 0 & 1
//show tick label if it's the first or last in
// the set, or if it's 1-5; beyond that show
// fewer as the values get larger:
tickLabel = (j < 1 || (i < 1 && j < 5) || (j < 4 - i)
|| currentTickValue >= upperBoundVal)
? makeTickLabel(currentTickValue) : "";
}
}
else { //not small log values in use; allow for values <= 0
if (zeroTickFlag) { //if did zero tick last iter then
--j; //decrement to do 1.0 tick now
} //calculate power-of-ten value for tick:
currentTickValue = (i >= 0)
? Math.pow(10, i) + (Math.pow(10, i) * j)
: -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
if (!zeroTickFlag) { // did not do zero tick last iteration
if (Math.abs(currentTickValue - 1.0) < 0.0001
&& lowerBoundVal <= 0.0 && upperBoundVal >= 0.0) {
//tick value is 1.0 and 0.0 is within data range
currentTickValue = 0.0; //set tick value to zero
zeroTickFlag = true; //indicate zero tick
}
}
else { //did zero tick last iteration
zeroTickFlag = false; //clear flag
} //create tick label string:
//show tick label if "1e#"-style and it's one
// of the first two, if it's the first or last
// in the set, or if it's 1-5; beyond that
// show fewer as the values get larger:
tickLabel = ((this.expTickLabelsFlag && j < 2)
|| j < 1
|| (i < 1 && j < 5) || (j < 4 - i)
|| currentTickValue >= upperBoundVal)
? makeTickLabel(currentTickValue) : "";
}
if (currentTickValue > upperBoundVal) {
return ticks; // if past highest data value then exit
// method
}
if (currentTickValue >= lowerBoundVal - SMALL_LOG_VALUE) {
//tick value not below lowest data value
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
}
else {
angle = -Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
}
else {
anchor = TextAnchor.TOP_CENTER;
rotationAnchor = TextAnchor.TOP_CENTER;
}
}
Tick tick = new NumberTick(new Double(currentTickValue),
tickLabel, anchor, rotationAnchor, angle);
ticks.add(tick);
}
}
}
return ticks;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param canvas the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List refreshTicksVertical(Canvas canvas,
RectShape dataArea,
RectangleEdge edge) {
List ticks = new java.util.ArrayList();
//get lower bound value:
double lowerBoundVal = getRange().getLowerBound();
//if small log values and lower bound value too small
// then set to a small value (don't allow <= 0):
if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
lowerBoundVal = SMALL_LOG_VALUE;
}
//get upper bound value
double upperBoundVal = getRange().getUpperBound();
//get log10 version of lower bound and round to integer:
int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
//get log10 version of upper bound and round to integer:
int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));
if (iBegCount == iEndCount && iBegCount > 0
&& Math.pow(10, iBegCount) > lowerBoundVal) {
//only 1 power of 10 value, it's > 0 and its resulting
// tick value will be larger than lower bound of data
--iBegCount; //decrement to generate more ticks
}
double tickVal;
String tickLabel;
boolean zeroTickFlag = false;
for (int i = iBegCount; i <= iEndCount; i++) {
//for each tick with a label to be displayed
int jEndCount = 10;
if (i == iEndCount) {
jEndCount = 1;
}
for (int j = 0; j < jEndCount; j++) {
//for each tick to be displayed
if (this.smallLogFlag) {
//small log values in use
tickVal = Math.pow(10, i) + (Math.pow(10, i) * j);
if (j == 0) {
//first tick of group; create label text
if (this.log10TickLabelsFlag) {
//if flag then
tickLabel = "10^" + i; //create "log10"-type label
}
else { //not "log10"-type label
if (this.expTickLabelsFlag) {
//if flag then
tickLabel = "1e" + i; //create "1e#"-type label
}
else { //not "1e#"-type label
if (i >= 0) { // if positive exponent then
// make integer
NumberFormat format
= getNumberFormatOverride();
if (format != null) {
tickLabel = format.format(tickVal);
}
else {
tickLabel = Long.toString((long)
Math.rint(tickVal));
}
}
else {
//negative exponent; create fractional value
//set exact number of fractional digits to
// be shown:
this.numberFormatterObj
.setMaximumFractionDigits(-i);
//create tick label:
tickLabel = this.numberFormatterObj.format(
tickVal);
}
}
}
}
else { //not first tick to be displayed
tickLabel = ""; //no tick label
}
}
else { //not small log values in use; allow for values <= 0
if (zeroTickFlag) { //if did zero tick last iter then
--j;
} //decrement to do 1.0 tick now
tickVal = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
: -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
if (j == 0) { //first tick of group
if (!zeroTickFlag) { // did not do zero tick last
// iteration
if (i > iBegCount && i < iEndCount
&& Math.abs(tickVal - 1.0) < 0.0001) {
// not first or last tick on graph and value
// is 1.0
tickVal = 0.0; //change value to 0.0
zeroTickFlag = true; //indicate zero tick
tickLabel = "0"; //create label for tick
}
else {
//first or last tick on graph or value is 1.0
//create label for tick:
if (this.log10TickLabelsFlag) {
//create "log10"-type label
tickLabel = (((i < 0) ? "-" : "")
+ "10^" + Math.abs(i));
}
else {
if (this.expTickLabelsFlag) {
//create "1e#"-type label
tickLabel = (((i < 0) ? "-" : "")
+ "1e" + Math.abs(i));
}
else {
NumberFormat format
= getNumberFormatOverride();
if (format != null) {
tickLabel = format.format(tickVal);
}
else {
tickLabel = Long.toString(
(long) Math.rint(tickVal));
}
}
}
}
}
else { // did zero tick last iteration
tickLabel = ""; //no label
zeroTickFlag = false; //clear flag
}
}
else { // not first tick of group
tickLabel = ""; //no label
zeroTickFlag = false; //make sure flag cleared
}
}
if (tickVal > upperBoundVal) {
return ticks; //if past highest data value then exit method
}
if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
//tick value not below lowest data value
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = -Math.PI / 2.0;
}
else {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
//create tick object and add to list:
ticks.add(new NumberTick(new Double(tickVal), tickLabel,
anchor, rotationAnchor, angle));
}
}
}
return ticks;
}
/**
* Converts the given value to a tick label string.
*
* @param val the value to convert.
* @param forceFmtFlag true to force the number-formatter object
* to be used.
*
* @return The tick label string.
*/
protected String makeTickLabel(double val, boolean forceFmtFlag) {
if (this.expTickLabelsFlag || forceFmtFlag) {
//using exponents or force-formatter flag is set
// (convert 'E' to lower-case 'e'):
return this.numberFormatterObj.format(val).toLowerCase();
}
return getTickUnit().valueToString(val);
}
/**
* Converts the given value to a tick label string.
* @param val the value to convert.
*
* @return The tick label string.
*/
protected String makeTickLabel(double val) {
return makeTickLabel(val, false);
}
}
| lgpl-3.0 |
AlgorithmX2/Chisels-and-Bits | src/main/java/mod/chiselsandbits/chiseledblock/properties/UnlistedBlockStateID.java | 526 | package mod.chiselsandbits.chiseledblock.properties;
import net.minecraftforge.common.property.IUnlistedProperty;
public final class UnlistedBlockStateID implements IUnlistedProperty<Integer>
{
@Override
public String getName()
{
return "b";
}
@Override
public boolean isValid(
final Integer value )
{
return value != 0;
}
@Override
public Class<Integer> getType()
{
return Integer.class;
}
@Override
public String valueToString(
final Integer value )
{
return Integer.toString( value );
}
} | lgpl-3.0 |
ennerf/mvn-repo-sources | lcm-java/src/main/java/lcm/spy/Spy.java | 15859 | package lcm.spy;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
import lcm.util.*;
import java.lang.reflect.*;
import lcm.lcm.*;
/** Spy main class. **/
public class Spy
{
JFrame jf;
LCM lcm;
JDesktopPane jdp;
LCMTypeDatabase handlers;
HashMap<String, ChannelData> channelMap = new HashMap<String, ChannelData>();
ArrayList<ChannelData> channelList = new ArrayList<ChannelData>();
ChannelTableModel _channelTableModel = new ChannelTableModel();
TableSorter channelTableModel = new TableSorter(_channelTableModel);
JTable channelTable = new JTable(channelTableModel);
ArrayList<SpyPlugin> plugins = new ArrayList<SpyPlugin>();
JButton clearButton = new JButton("Clear");
public Spy(String lcmurl) throws IOException
{
jf = new JFrame("LCM Spy");
jdp = new JDesktopPane();
jdp.setBackground(new Color(0, 0, 160));
jf.setLayout(new BorderLayout());
jf.add(jdp, BorderLayout.CENTER);
jf.setSize(1024, 768);
jf.setVisible(true);
// sortedChannelTableModel.addMouseListenerToHeaderInTable(channelTable);
channelTableModel.setTableHeader(channelTable.getTableHeader());
channelTableModel.setSortingStatus(0, TableSorter.ASCENDING);
handlers = new LCMTypeDatabase();
TableColumnModel tcm = channelTable.getColumnModel();
tcm.getColumn(0).setMinWidth(140);
tcm.getColumn(1).setMinWidth(140);
tcm.getColumn(2).setMaxWidth(100);
tcm.getColumn(3).setMaxWidth(100);
tcm.getColumn(4).setMaxWidth(100);
tcm.getColumn(5).setMaxWidth(100);
tcm.getColumn(6).setMaxWidth(100);
JInternalFrame jif = new JInternalFrame("Channels", true);
jif.setLayout(new BorderLayout());
jif.add(channelTable.getTableHeader(), BorderLayout.PAGE_START);
// XXX weird bug, if clearButton is added after JScrollPane, we get an error.
jif.add(clearButton, BorderLayout.SOUTH);
jif.add(new JScrollPane(channelTable), BorderLayout.CENTER);
jif.setSize(800,600);
jif.setVisible(true);
jdp.add(jif);
if(null == lcmurl)
lcm = new LCM();
else
lcm = new LCM(lcmurl);
lcm.subscribeAll(new MySubscriber());
new HzThread().start();
clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
channelMap.clear();
channelList.clear();
channelTableModel.fireTableDataChanged();
}
});
channelTable.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int mods=e.getModifiersEx();
if (e.getButton()==3)
{
showPopupMenu(e);
}
else if (e.getClickCount() == 2)
{
Point p = e.getPoint();
int row = rowAtPoint(p);
ChannelData cd = channelList.get(row);
boolean got_one = false;
for (SpyPlugin plugin : plugins)
{
if (!got_one && plugin.canHandle(cd.fingerprint)) {
plugin.getAction(jdp, cd).actionPerformed(null);
got_one = true;
}
}
if (!got_one)
createViewer(channelList.get(row));
}
}
});
jf.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.out.println("Spy quitting");
System.exit(0);
}
});
ClassDiscoverer.findClasses(new PluginClassVisitor());
System.out.println("Found "+plugins.size()+" plugins");
for (SpyPlugin plugin : plugins) {
System.out.println(" "+plugin);
}
}
class PluginClassVisitor implements ClassDiscoverer.ClassVisitor
{
public void classFound(String jar, Class cls)
{
Class interfaces[] = cls.getInterfaces();
for (Class iface : interfaces) {
if (iface.equals(SpyPlugin.class)) {
try {
Constructor c = cls.getConstructor(new Class[0]);
SpyPlugin plugin = (SpyPlugin) c.newInstance(new Object[0]);
plugins.add(plugin);
} catch (Exception ex) {
System.out.println("ex: "+ex);
}
}
}
}
}
void createViewer(ChannelData cd)
{
if (cd.viewerFrame != null && !cd.viewerFrame.isVisible())
{
cd.viewerFrame.dispose();
cd.viewer = null;
}
if (cd.viewer == null) {
cd.viewerFrame = new JInternalFrame(cd.name, true, true);
cd.viewer = new ObjectPanel(cd.name);
cd.viewer.setObject(cd.last);
// cd.viewer = new ObjectViewer(cd.name, cd.cls, null);
cd.viewerFrame.setLayout(new BorderLayout());
cd.viewerFrame.add(new JScrollPane(cd.viewer), BorderLayout.CENTER);
jdp.add(cd.viewerFrame);
cd.viewerFrame.setSize(500,400);
cd.viewerFrame.setVisible(true);
} else {
cd.viewerFrame.setVisible(true);
cd.viewerFrame.moveToFront();
}
}
static final long utime_now()
{
return System.nanoTime()/1000;
}
class ChannelTableModel extends AbstractTableModel
{
public int getColumnCount()
{
return 8;
}
public int getRowCount()
{
return channelList.size();
}
public Object getValueAt(int row, int col)
{
ChannelData cd = channelList.get(row);
if (cd == null)
return "";
switch (col)
{
case 0:
return cd.name;
case 1:
if (cd.cls == null)
return String.format("?? %016x", cd.fingerprint);
String s = cd.cls.getName();
return s.substring(s.lastIndexOf('.')+1);
case 2:
return ""+cd.nreceived;
case 3:
return String.format("%6.2f", cd.hz);
case 4:
return String.format("%6.2f ms",1000.0/cd.hz); // cd.max_interval/1000.0);
case 5:
return String.format("%6.2f ms",(cd.max_interval - cd.min_interval)/1000.0);
case 6:
return String.format("%6.2f KB/s", (cd.bandwidth/1024.0));
case 7:
return ""+cd.nerrors;
}
return "???";
}
public String getColumnName(int col)
{
switch (col)
{
case 0:
return "Channel";
case 1:
return "Type";
case 2:
return "Num Msgs";
case 3:
return "Hz";
case 4:
return "1/Hz";
case 5:
return "Jitter";
case 6:
return "Bandwidth";
case 7:
return "Undecodable";
}
return "???";
}
}
class MySubscriber implements LCMSubscriber
{
public void messageReceived(LCM lcm, String channel, LCMDataInputStream dins)
{
Object o = null;
ChannelData cd = channelMap.get(channel);
int msg_size = 0;
try {
msg_size = dins.available();
long fingerprint = (msg_size >=8) ? dins.readLong() : -1;
dins.reset();
Class cls = handlers.getClassByFingerprint(fingerprint);
if (cd == null) {
cd = new ChannelData();
cd.name = channel;
cd.cls = cls;
cd.fingerprint = fingerprint;
cd.row = channelList.size();
synchronized(channelList) {
channelMap.put(channel, cd);
channelList.add(cd);
_channelTableModel.fireTableDataChanged();
}
} else {
if (cls != null && cd.cls != null && !cd.cls.equals(cls)) {
System.out.println("WARNING: Class changed for channel "+channel);
cd.nerrors++;
}
}
long utime = utime_now();
long interval = utime - cd.last_utime;
cd.hz_min_interval = Math.min(cd.hz_min_interval, interval);
cd.hz_max_interval = Math.max(cd.hz_max_interval, interval);
cd.hz_bytes += msg_size;
cd.last_utime = utime;
cd.nreceived++;
o = cd.cls.getConstructor(DataInput.class).newInstance(dins);
cd.last = o;
if (cd.viewer != null)
cd.viewer.setObject(o);
} catch (NullPointerException ex) {
cd.nerrors++;
} catch (IOException ex) {
cd.nerrors++;
System.out.println("Spy.messageReceived ex: "+ex);
} catch (NoSuchMethodException ex) {
cd.nerrors++;
System.out.println("Spy.messageReceived ex: "+ex);
} catch (InstantiationException ex) {
cd.nerrors++;
System.out.println("Spy.messageReceived ex: "+ex);
} catch (IllegalAccessException ex) {
cd.nerrors++;
System.out.println("Spy.messageReceived ex: "+ex);
} catch (InvocationTargetException ex) {
cd.nerrors++;
// these are almost always spurious
//System.out.println("ex: "+ex+"..."+ex.getTargetException());
}
}
}
class HzThread extends Thread
{
public HzThread()
{
setDaemon(true);
}
public void run()
{
while (true)
{
long utime = utime_now();
synchronized(channelList)
{
for (ChannelData cd : channelList)
{
long diff_recv = cd.nreceived - cd.hz_last_nreceived;
cd.hz_last_nreceived = cd.nreceived;
long dutime = utime - cd.hz_last_utime;
cd.hz_last_utime = utime;
cd.hz = diff_recv / (dutime/1000000.0);
cd.min_interval = cd.hz_min_interval;
cd.max_interval = cd.hz_max_interval;
cd.hz_min_interval = 9999;
cd.hz_max_interval = 0;
cd.bandwidth = cd.hz_bytes / (dutime/1000000.0);
cd.hz_bytes = 0;
}
}
int selrow = channelTable.getSelectedRow();
channelTableModel.fireTableDataChanged();
if (selrow >= 0)
channelTable.setRowSelectionInterval(selrow, selrow);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class DefaultViewer extends AbstractAction
{
ChannelData cd;
public DefaultViewer(ChannelData cd)
{
super("Structure Viewer...");
this.cd = cd;
}
public void actionPerformed(ActionEvent e)
{
createViewer(cd);
}
}
int rowAtPoint(Point p)
{
int physicalRow = channelTable.rowAtPoint(p);
return channelTableModel.modelIndex(physicalRow);
}
public void showPopupMenu(MouseEvent e)
{
Point p = e.getPoint();
int row = rowAtPoint(p);
ChannelData cd = channelList.get(row);
JPopupMenu jm = new JPopupMenu("Viewers");
int prow = channelTable.rowAtPoint(p);
channelTable.setRowSelectionInterval(prow, prow);
jm.add(new DefaultViewer(cd));
if (cd.cls != null)
{
for (SpyPlugin plugin : plugins)
{
if (plugin.canHandle(cd.fingerprint))
jm.add(plugin.getAction(jdp, cd));
}
}
jm.show(channelTable, e.getX(), e.getY());
}
public static void usage()
{
System.err.println("usage: lcm-spy [options]");
System.err.println("");
System.err.println("lcm-spy is the Lightweight Communications and Marshalling traffic ");
System.err.println("inspection utility. It is a graphical tool for viewing messages received on ");
System.err.println("an LCM network, and is analagous to tools like Ethereal/Wireshark and tcpdump");
System.err.println("in that it is able to inspect all LCM messages received and provide information");
System.err.println("and statistics on the channels used.");
System.err.println("");
System.err.println("When given appropriate LCM type definitions, lcm-spy is able to");
System.err.println("automatically detect and decode messages, and can display the individual fields");
System.err.println("of recognized messages. lcm-spy is limited to displaying statistics for");
System.err.println("unrecognized messages.");
System.err.println("");
System.err.println("Options:");
System.err.println(" -l, --lcm-url=URL Use the specified LCM URL");
System.err.println(" -h, --help Shows this help text and exits");
System.err.println("");
System.exit(1);
}
public static void main(String args[])
{
// check if the JRE is supplied by gcj, and warn the user if it is.
if(System.getProperty("java.vendor").indexOf("Free Software Foundation") >= 0) {
System.err.println("WARNING: Detected gcj. lcm-spy is not known to work well with gcj.");
System.err.println(" The Sun JRE is recommended.");
}
String lcmurl = null;
for(int optind=0; optind<args.length; optind++) {
String c = args[optind];
if(c.equals("-h") || c.equals("--help")) {
usage();
} else if(c.equals("-l") || c.equals("--lcm-url") || c.startsWith("--lcm-url=")) {
String optarg = null;
if(c.startsWith("--lcm-url=")) {
optarg=c.substring(10);
} else if(optind < args.length) {
optind++;
optarg = args[optind];
}
if(null == optarg) {
usage();
} else {
lcmurl = optarg;
}
} else {
usage();
}
}
try {
new Spy(lcmurl);
} catch (IOException ex) {
System.out.println(ex);
}
}
}
| lgpl-3.0 |
nivertius/perfectable-incubation | visuable/src/main/java/org/perfectable/visuable/richtext/RichText.java | 858 | package org.perfectable.visuable.richtext;
import java.io.Serializable;
import java.net.URI;
@FunctionalInterface
public interface RichText extends Serializable {
long serialVersionUID = 6850761820189924926L;
void render(RichTextRenderer painter);
static RichText plain(String text) {
return PlainRichText.of(text);
}
static RichText lineBreak() {
return LineBreakRichText.INSTANCE;
}
default RichText asLink(URI target) {
return LinkRichText.of(this, target);
}
default RichText asStrong() {
return StrongRichText.of(this);
}
default RichText asEmphasis() {
return EmphasisRichText.of(this);
}
default RichText asCode() {
return CodeRichText.of(this);
}
default RichText join(RichText other) {
return CompositeRichText.of(this, other);
}
default RichText joinPlain(String plain) {
return join(plain(plain));
}
}
| lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-process-monitor/src/test/java/org/sonar/process/monitor/StreamGobblerTest.java | 1728 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.process.monitor;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import java.io.InputStream;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
public class StreamGobblerTest {
@Test
public void forward_stream_to_log() {
InputStream stream = IOUtils.toInputStream("one\nsecond log\nthird log\n");
Logger logger = mock(Logger.class);
StreamGobbler gobbler = new StreamGobbler(stream, "WEB", logger);
verifyZeroInteractions(logger);
gobbler.start();
StreamGobbler.waitUntilFinish(gobbler);
verify(logger).info("one");
verify(logger).info("second log");
verify(logger).info("third log");
verifyNoMoreInteractions(logger);
}
}
| lgpl-3.0 |
oakes/Nightweb | common/java/core/net/i2p/data/Payload.java | 4452 | package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* with no warranty of any kind, either expressed or implied.
* It probably won't make your computer catch on fire, or eat
* your children, but it might. Use at your own risk.
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Defines the actual payload of a message being delivered, including the
* standard encryption wrapping, as defined by the I2P data structure spec.
*
* This is used mostly in I2CP, where we used to do end-to-end encryption.
* Since we don't any more, you probably just want to use the
* get/set EncryptedData methods.
*
* @author jrandom
*/
public class Payload extends DataStructureImpl {
//private final static Log _log = new Log(Payload.class);
private byte[] _encryptedData;
private byte[] _unencryptedData;
public Payload() {
}
/**
* Retrieve the unencrypted body of the message.
*
* Deprecated.
* Unless you are doing encryption, use getEncryptedData() instead.
*
* @return body of the message, or null if the message has either not been
* decrypted yet or if the hash is not correct
*/
public byte[] getUnencryptedData() {
return _unencryptedData;
}
/**
* Populate the message body with data. This does not automatically encrypt
* yet.
*
* Deprecated.
* Unless you are doing encryption, use setEncryptedData() instead.
*/
public void setUnencryptedData(byte[] data) {
_unencryptedData = data;
}
/** the real data */
public byte[] getEncryptedData() {
return _encryptedData;
}
/** the real data */
public void setEncryptedData(byte[] data) {
_encryptedData = data;
}
public int getSize() {
if (_unencryptedData != null)
return _unencryptedData.length;
else if (_encryptedData != null)
return _encryptedData.length;
else
return 0;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
int size = (int) DataHelper.readLong(in, 4);
if (size < 0) throw new DataFormatException("payload size out of range (" + size + ")");
_encryptedData = new byte[size];
int read = read(in, _encryptedData);
if (read != size) throw new DataFormatException("Incorrect number of bytes read in the payload structure");
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("read payload: " + read + " bytes");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_encryptedData == null) throw new DataFormatException("Not yet encrypted. Please set the encrypted data");
DataHelper.writeLong(out, 4, _encryptedData.length);
out.write(_encryptedData);
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("wrote payload: " + _encryptedData.length);
}
/**
* @return the written length (NOT the new offset)
*/
public int writeBytes(byte target[], int offset) {
if (_encryptedData == null) throw new IllegalStateException("Not yet encrypted. Please set the encrypted data");
DataHelper.toLong(target, offset, 4, _encryptedData.length);
offset += 4;
System.arraycopy(_encryptedData, 0, target, offset, _encryptedData.length);
return 4 + _encryptedData.length;
}
@Override
public boolean equals(Object object) {
if (object == this) return true;
if ((object == null) || !(object instanceof Payload)) return false;
Payload p = (Payload) object;
return DataHelper.eq(_unencryptedData, p.getUnencryptedData())
&& DataHelper.eq(_encryptedData, p.getEncryptedData());
}
@Override
public int hashCode() {
return DataHelper.hashCode(_encryptedData != null ? _encryptedData : _unencryptedData);
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(32);
buf.append("[Payload: ");
if (_encryptedData != null)
buf.append(_encryptedData.length).append(" bytes");
else
buf.append("null");
buf.append("]");
return buf.toString();
}
}
| unlicense |
sdgdsffdsfff/dream | mash-service/src/main/java/com/izpzp/mash/util/FreeMarkerResolver.java | 1162 | /*
* Copyright (C), 2002-2013, izpzp
* FileName: FreeMarkerResolver.java
* Author: 12070644@cnsuning.com
* Date: 2014-3-10 上午00:00:00
*/
package com.izpzp.mash.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import freemarker.template.Template;
/**
* FreeMarkerResolver
*
*/
@Component
public class FreeMarkerResolver {
/**
* freemarker配置
*/
@Autowired
FreeMarkerConfigurer freemarkerConfig;
/**
* 将模板解析成页面
*/
public String resolve(String templateName, Object map) {
String htmlText = null;
try {
Template tpl = freemarkerConfig.getConfiguration().getTemplate(templateName, "UTF-8");
htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
} catch (Exception e) {
htmlText = "";
// TODO
}
return htmlText;
}
}
| unlicense |
0x0all/codelibrary | java/src/PerfectMatchingCount.java | 2272 | import java.util.*;
public class PerfectMatchingCount {
static class Vertex {
List<Vertex> adj = new ArrayList<>();
int id, max;
}
public static int numberOfPerfectMatchings(Vertex[] vertices) {
int n = vertices.length;
for (int i = 0; i < n; i++)
vertices[i].id = i;
for (Vertex u : vertices)
for (Vertex v : u.adj)
u.max = Math.max(u.max, v.id);
int[] v2i = null;
int[] i2v = null;
int active = 0;
int[] ways = { 1 };
for (int k = 0; k < n; k++) {
int[] nv2i = new int[k + 1];
int[] ni2v = new int[k + 1];
Arrays.fill(nv2i, -1);
int nactive = 0;
for (int i = 0; i <= k; i++) {
if (vertices[i].max > k) {
nv2i[i] = nactive;
ni2v[nactive] = i;
++nactive;
}
}
int[] nways = new int[1 << nactive];
loop: for (int mask = 0; mask < 1 << active; mask++) {
if (ways[mask] > 0) {
boolean need = false;
int nmask = 0;
for (int i = 0; i < active; i++) {
if ((mask & 1 << i) != 0) {
int ni = nv2i[i2v[i]];
if (ni < 0) {
if (need)
continue loop;
need = true;
} else {
nmask |= 1 << ni;
}
}
}
if (need) {
nways[nmask] += ways[mask];
} else {
if (nv2i[k] >= 0) {
nways[nmask | 1 << nv2i[k]] += ways[mask];
}
for (Vertex v : vertices[k].adj) {
if (v.id < k && (mask & 1 << v2i[v.id]) != 0) {
nways[nmask ^ 1 << nv2i[v.id]] += ways[mask];
}
}
}
}
}
v2i = nv2i;
i2v = ni2v;
active = nactive;
ways = nways;
}
return ways[0];
}
static Vertex[] convert(boolean[][] g) {
List<Vertex> list = new ArrayList<>();
for (int i = 0; i < g.length; i++)
list.add(new Vertex());
for (int i = 0; i < g.length; i++)
for (int j = 0; j < g.length; j++)
if (g[i][j])
list.get(i).adj.add(list.get(j));
return list.toArray(new Vertex[0]);
}
// Usage example
public static void main(String[] args) {
boolean[][] g = new boolean[4][4];
for (int i = 0; i < g.length; i++) {
Arrays.fill(g[i], true);
}
System.out.println(3 == numberOfPerfectMatchings(convert(g)));
g[0][2] = g[2][0] = false;
g[1][3] = g[3][1] = false;
System.out.println(2 == numberOfPerfectMatchings(convert(g)));
}
}
| unlicense |
SixArmDonkey/aerodrome-for-jet | src/main/java/com/buffalokiwi/aerodrome/jet/JetException.java | 4052 | /**
* This file is part of the Aerodrome package, and is subject to the
* terms and conditions defined in file 'LICENSE', which is part
* of this source code package.
*
* Copyright (c) 2016 All Rights Reserved, John T. Quinn III,
* <johnquinn3@gmail.com>
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*/
package com.buffalokiwi.aerodrome.jet;
import com.buffalokiwi.api.APIException;
import com.buffalokiwi.api.IAPIResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
/**
* An exception for the Jet API
* @author John Quinn
*/
public class JetException extends APIException
{
/**
* Some error messages
*/
private final List<String> messages;
private final IAPIResponse response;
/**
* Creates a new instance of <code>JetException</code> without detail message.
*/
public JetException() {
response = null;
messages = Collections.unmodifiableList( new ArrayList<String>());
}
/**
* Constructs an instance of <code>JetException</code> with the specified
* detail message.
*
* @param msg the detail message.
*/
public JetException(String msg) {
super(msg);
response = null;
messages = Collections.unmodifiableList( new ArrayList<String>());
}
public JetException( List<String> messages )
{
this( messages, null );
}
public JetException( List<String> messages, Exception previous, IAPIResponse response )
{
super( "Jet API Error Response", previous );
if ( messages != null )
this.messages = Collections.unmodifiableList( messages );
else
this.messages = null;
this.response = response;
}
public JetException( List<String> messages, Exception previous )
{
super( "Jet API Error Response", previous );
if ( messages != null )
this.messages = Collections.unmodifiableList( messages );
else
this.messages = null;
response = null;
}
/**
* An api exception with a previous exception
* @param message the detail message
* @param previous The previous exception
*/
public JetException(String message, Exception previous )
{
super( message, previous );
messages = null;
response = null;
}
/**
* An api exception with a previous exception
* @param message the detail message
* @param previous The previous exception
*/
public JetException(String message, Exception previous, IAPIResponse response )
{
super( message, previous );
messages = null;
this.response = response;
}
public IAPIResponse getResponse()
{
return response;
}
/**
* Returns the detail message string of this throwable.
*
* @return the detail message string of this {@code Throwable} instance
* (which may be {@code null}).
*/
@Override
public String getMessage()
{
final StringBuilder s = new StringBuilder();
s.append( super.getMessage());
s.append( implodeMessages( "\n " ));
return s.toString();
}
/**
* Retrieve the API Error messages
* @return error messages
*/
public List<String> getMessages()
{
if ( messages == null )
return new ArrayList<>();
return messages;
}
public String implodeMessages( final String delim )
{
final StringBuilder s = new StringBuilder();
for ( final String s1 : getMessages())
{
s.append( s1 );
s.append( delim );
}
return s.toString();
}
/**
* Print this exception to the log
* @param log Log to print to
*/
@Override
public void printToLog( final Log log )
{
super.printToLog( log );
if ( messages == null )
return;
for ( final String m : messages )
{
log.error( m );
}
}
}
| apache-2.0 |
keizer619/siddhi | modules/siddhi-core/src/main/java/org/wso2/siddhi/core/util/Scheduler.java | 6412 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.
* 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.wso2.siddhi.core.util;
import org.apache.log4j.Logger;
import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.stream.StreamEvent;
import org.wso2.siddhi.core.event.stream.StreamEventPool;
import org.wso2.siddhi.core.event.stream.converter.ConversionStreamEventChunk;
import org.wso2.siddhi.core.event.stream.converter.StreamEventConverter;
import org.wso2.siddhi.core.query.input.stream.single.SingleThreadEntryValveProcessor;
import org.wso2.siddhi.core.util.snapshot.Snapshotable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created on 12/3/14.
*/
public class Scheduler implements Snapshotable {
private static final Logger log = Logger.getLogger(Scheduler.class);
private final BlockingQueue<Long> toNotifyQueue = new LinkedBlockingQueue<Long>();
private ScheduledExecutorService scheduledExecutorService;
private EventCaller eventCaller;
private volatile boolean running = false;
private StreamEventPool streamEventPool;
private ComplexEventChunk<StreamEvent> streamEventChunk;
private ExecutionPlanContext executionPlanContext;
private String elementId;
public Scheduler(ScheduledExecutorService scheduledExecutorService, Schedulable singleThreadEntryValve) {
this.scheduledExecutorService = scheduledExecutorService;
eventCaller = new EventCaller(singleThreadEntryValve);
}
public void notifyAt(long time) {
try {
toNotifyQueue.put(time);
if (!running && toNotifyQueue.size() == 1) {
synchronized (toNotifyQueue) {
if (!running) {
running = true;
long timeDiff = time - System.currentTimeMillis(); //todo fix
if (timeDiff > 0) {
scheduledExecutorService.schedule(eventCaller, timeDiff, TimeUnit.MILLISECONDS);
} else {
scheduledExecutorService.schedule(eventCaller, 0, TimeUnit.MILLISECONDS);
}
}
}
}
} catch (InterruptedException e) {
log.error("Error when adding time:" + time + " to toNotifyQueue at Scheduler", e);
}
}
public void setStreamEventPool(StreamEventPool streamEventPool) {
this.streamEventPool = streamEventPool;
streamEventChunk = new ConversionStreamEventChunk((StreamEventConverter) null, streamEventPool);
}
public void init(ExecutionPlanContext executionPlanContext) {
this.executionPlanContext = executionPlanContext;
if (elementId == null) {
elementId = executionPlanContext.getElementIdGenerator().createNewId();
}
executionPlanContext.getSnapshotService().addSnapshotable(this);
}
@Override
public Object[] currentState() {
return new Object[]{toNotifyQueue};
}
@Override
public void restoreState(Object[] state) {
BlockingQueue<Long> restoreToNotifyQueue = (BlockingQueue<Long>) state[0];
for (Long time : restoreToNotifyQueue) {
notifyAt(time);
}
}
@Override
public String getElementId() {
return elementId;
}
public Scheduler clone(String key, SingleThreadEntryValveProcessor singleThreadEntryValveProcessor) {
Scheduler scheduler = new Scheduler(scheduledExecutorService, singleThreadEntryValveProcessor);
scheduler.elementId = elementId + "-" + key;
scheduler.init(executionPlanContext);
return scheduler;
}
private class EventCaller implements Runnable {
private Schedulable singleThreadEntryValve;
public EventCaller(Schedulable singleThreadEntryValve) {
this.singleThreadEntryValve = singleThreadEntryValve;
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p/>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
Long toNotifyTime = toNotifyQueue.peek();
long currentTime = System.currentTimeMillis();
while (toNotifyTime != null && toNotifyTime - currentTime <= 0) {
toNotifyQueue.poll();
StreamEvent timerEvent = streamEventPool.borrowEvent();
timerEvent.setType(StreamEvent.Type.TIMER);
timerEvent.setTimestamp(currentTime);
streamEventChunk.add(timerEvent);
singleThreadEntryValve.process(streamEventChunk);
streamEventChunk.clear();
toNotifyTime = toNotifyQueue.peek();
currentTime = System.currentTimeMillis();
}
if (toNotifyTime != null) {
scheduledExecutorService.schedule(eventCaller, toNotifyTime - currentTime, TimeUnit.MILLISECONDS);
} else {
synchronized (toNotifyQueue) {
running = false;
if (toNotifyQueue.peek() != null) {
running = true;
scheduledExecutorService.schedule(eventCaller, 0, TimeUnit.MILLISECONDS);
}
}
}
}
}
}
| apache-2.0 |
tdyas/pants | tests/java/org/pantsbuild/tools/junit/impl/XmlReportTest.java | 17051 | // Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.pantsbuild.tools.junit.impl;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.pantsbuild.tools.junit.lib.ConsoleRunnerTestBase;
import org.pantsbuild.tools.junit.lib.FailingTestRunner;
import org.pantsbuild.tools.junit.lib.XmlReportAllIgnoredTest;
import org.pantsbuild.tools.junit.lib.XmlReportAllPassingTest;
import org.pantsbuild.tools.junit.lib.XmlReportAssumeSetupTest;
import org.pantsbuild.tools.junit.lib.XmlReportAssumeTest;
import org.pantsbuild.tools.junit.lib.XmlReportFailInSetupTest;
import org.pantsbuild.tools.junit.lib.XmlReportFailingParameterizedTest;
import org.pantsbuild.tools.junit.lib.XmlReportFailingTestRunnerTest;
import org.pantsbuild.tools.junit.lib.XmlReportFirstTestIngoredTest;
import org.pantsbuild.tools.junit.lib.XmlReportIgnoredTestSuiteTest;
import org.pantsbuild.tools.junit.lib.XmlReportMockitoStubbingTest;
import org.pantsbuild.tools.junit.lib.XmlReportTestSuite;
import org.pantsbuild.tools.junit.lib.MockScalaTest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test the XML report output.
*/
public class XmlReportTest extends ConsoleRunnerTestBase {
/**
* <P>This test is Parameterized to run with different combinations of
* -default-concurrency and -use-experimental-runner flags.
* </P>
* <P>
* See {@link ConsoleRunnerTestBase#invokeConsoleRunner(String)}
* </P>
*/
public XmlReportTest(TestParameters parameters) {
super(parameters);
}
@Test
public void testXmlReportAll() throws Exception {
String testClassName = org.pantsbuild.tools.junit.lib.XmlReportTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, true);
assertNotNull(testSuite);
assertEquals(4, testSuite.getTests());
assertEquals(1, testSuite.getFailures());
assertEquals(1, testSuite.getErrors());
assertEquals(1, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
assertEquals("Test output\n", testSuite.getOut());
assertEquals("", testSuite.getErr());
List<AntJunitXmlReportListener.TestCase> testCases = testSuite.getTestCases();
assertEquals(4, testCases.size());
sortTestCasesByName(testCases);
AntJunitXmlReportListener.TestCase errorTestCase = testCases.get(0);
assertEquals(testClassName, errorTestCase.getClassname());
assertEquals("testXmlErrors", errorTestCase.getName());
assertTrue(Float.parseFloat(errorTestCase.getTime()) > 0);
assertNull(errorTestCase.getFailure());
assertEquals("testXmlErrors exception", errorTestCase.getError().getMessage());
assertEquals("java.lang.Exception", errorTestCase.getError().getType());
assertThat(errorTestCase.getError().getStacktrace(),
containsString(testClassName + ".testXmlErrors("));
AntJunitXmlReportListener.TestCase failureTestCase = testCases.get(1);
assertEquals(testClassName, failureTestCase.getClassname());
assertEquals("testXmlFails", failureTestCase.getName());
assertTrue(Float.parseFloat(failureTestCase.getTime()) > 0);
assertNull(failureTestCase.getError());
assertEquals("java.lang.AssertionError", failureTestCase.getFailure().getType());
assertThat(failureTestCase.getFailure().getStacktrace(),
containsString(testClassName + ".testXmlFails("));
AntJunitXmlReportListener.TestCase passingTestCase = testCases.get(2);
assertEquals(testClassName, passingTestCase.getClassname());
assertEquals("testXmlPasses", passingTestCase.getName());
assertTrue(Float.parseFloat(passingTestCase.getTime()) > 0);
assertNull(passingTestCase.getFailure());
assertNull(passingTestCase.getError());
AntJunitXmlReportListener.TestCase ignoredTestCase = testCases.get(3);
assertEquals(testClassName, ignoredTestCase.getClassname());
assertEquals("testXmlSkipped", ignoredTestCase.getName());
assertEquals("0", ignoredTestCase.getTime());
assertNull(ignoredTestCase.getFailure());
assertNull(ignoredTestCase.getError());
}
@Test
public void testXmlReportAllIgnored() throws Exception {
String testClassName = XmlReportAllIgnoredTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, false);
assertNotNull(testSuite);
assertEquals(2, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(2, testSuite.getSkipped());
assertEquals("0", testSuite.getTime());
assertEquals(testClassName, testSuite.getName());
}
@Test
public void testXmlReportMockitoUnnecessaryStubbing() throws Exception {
String testClassName = XmlReportMockitoStubbingTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, true);
assertNotNull(testSuite);
assertEquals(1, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(1, testSuite.getErrors());
assertEquals(0, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
List<AntJunitXmlReportListener.TestCase> testCases = testSuite.getTestCases();
assertEquals(2, testCases.size());
sortTestCasesByName(testCases);
AntJunitXmlReportListener.TestCase errorTestCase = testCases.get(1);
assertEquals(testClassName, errorTestCase.getClassname());
assertEquals("unnecessary Mockito stubbings", errorTestCase.getName());
assertEquals("0", errorTestCase.getTime());
assertNull(errorTestCase.getFailure());
assertThat(errorTestCase.getError().getMessage(),
containsString("Unnecessary stubbings detected in test class:"));
assertEquals("org.mockito.exceptions.misusing.UnnecessaryStubbingException",
errorTestCase.getError().getType());
assertThat(errorTestCase.getError().getStacktrace(), containsString(testClassName));
}
@Test
public void testXmlReportFirstTestIgnored() throws Exception {
String testClassName = XmlReportFirstTestIngoredTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, false);
assertNotNull(testSuite);
assertEquals(2, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(1, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
}
@Test
public void testXmlReportAssume() throws Exception {
String testClassName = XmlReportAssumeTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, true);
assertNotNull(testSuite);
assertEquals(3, testSuite.getTests());
assertEquals(1, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(1, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
}
@Test
public void testXmlReportAssumeInSetup() throws Exception {
String testClassName = XmlReportAssumeSetupTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, false);
assertNotNull(testSuite);
assertEquals(2, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(2, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
}
@Test
public void testXmlReportAllPassing() throws Exception {
String testClassName = XmlReportAllPassingTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, false);
assertNotNull(testSuite);
assertEquals(2, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(0, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
}
@Test
public void testXmlReportXmlElements() throws Exception {
String testClassName = XmlReportAllPassingTest.class.getCanonicalName();
String xmlOutput = FileUtils.readFileToString(
runTestAndReturnXmlFile(testClassName, false), Charsets.UTF_8);
assertThat(xmlOutput, containsString("<testsuite"));
assertThat(xmlOutput, containsString("<properties>"));
assertThat(xmlOutput, containsString("<testcase"));
assertThat(xmlOutput, containsString("<system-out>"));
assertThat(xmlOutput, containsString("<system-err>"));
assertThat(xmlOutput, not(containsString("startNs")));
assertThat(xmlOutput, not(containsString("testClass")));
}
@Test
public void testXmlReportFailInSetup() throws Exception {
String testClassName = XmlReportFailInSetupTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, true);
assertNotNull(testSuite);
assertEquals(2, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(2, testSuite.getErrors());
assertEquals(0, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
}
@Test
public void testXmlReportIgnoredTestSuite() throws Exception {
String testClassName = XmlReportIgnoredTestSuiteTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, false);
assertNotNull(testSuite);
assertEquals(1, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(1, testSuite.getSkipped());
assertEquals("0", testSuite.getTime());
assertEquals(testClassName, testSuite.getName());
List<AntJunitXmlReportListener.TestCase> testCases = testSuite.getTestCases();
assertEquals(1, testCases.size());
AntJunitXmlReportListener.TestCase testCase = testCases.get(0);
assertEquals(testClassName, testCase.getClassname());
assertEquals(testClassName, testCase.getName());
assertEquals("0", testCase.getTime());
assertNull(testCase.getError());
assertNull(testCase.getFailure());
}
@Test
public void testXmlReportTestSuite() throws Exception {
String testClassName = XmlReportTestSuite.class.getCanonicalName();
File testXmlFile = runTestAndReturnXmlFile(testClassName, true);
// With a test suite we get back TEST-*.xml files for the test classes
// in the suite, not for the test suite class itself
testXmlFile = new File(testXmlFile.getParent(),
"TEST-" + org.pantsbuild.tools.junit.lib.XmlReportTest.class.getCanonicalName() + ".xml");
AntJunitXmlReportListener.TestSuite testSuite = parseTestXml(testXmlFile);
assertNotNull(testSuite);
assertEquals(4, testSuite.getTests());
assertEquals(1, testSuite.getFailures());
assertEquals(1, testSuite.getErrors());
assertEquals(1, testSuite.getSkipped());
testXmlFile = new File(testXmlFile.getParent(),
"TEST-" + XmlReportAllPassingTest.class.getCanonicalName() + ".xml");
testSuite = parseTestXml(testXmlFile);
assertNotNull(testSuite);
assertEquals(2, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(0, testSuite.getSkipped());
}
@Test
public void testXmlReportFailingParameterizedTest() throws Exception {
String testClassName = XmlReportFailingParameterizedTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, true);
assertNotNull(testSuite);
assertEquals(4, testSuite.getTests());
assertEquals(1, testSuite.getFailures());
assertEquals(2, testSuite.getErrors());
assertEquals(0, testSuite.getSkipped());
assertTrue(Float.parseFloat(testSuite.getTime()) > 0);
assertEquals(testClassName, testSuite.getName());
List<AntJunitXmlReportListener.TestCase> testCases = testSuite.getTestCases();
assertEquals(4, testCases.size());
}
@Test
public void testXmlErrorInTestRunnerInitialization() throws Exception {
String testClassName = XmlReportFailingTestRunnerTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, true);
assertNotNull(testSuite);
assertEquals(1, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(1, testSuite.getErrors());
assertEquals(0, testSuite.getSkipped());
assertEquals("0", testSuite.getTime());
assertEquals(testClassName, testSuite.getName());
List<AntJunitXmlReportListener.TestCase> testCases = testSuite.getTestCases();
assertEquals(1, testCases.size());
AntJunitXmlReportListener.TestCase testCase = testCases.get(0);
assertEquals(testClassName, testCase.getClassname());
assertEquals(testClassName, testCase.getName());
assertEquals("0", testCase.getTime());
assertNull(testCase.getFailure());
assertThat(testCase.getError().getMessage(), containsString("failed in getTestRules"));
assertEquals("java.lang.RuntimeException", testCase.getError().getType());
assertThat(testCase.getError().getStacktrace(),
containsString(FailingTestRunner.class.getCanonicalName() + ".getTestRules("));
}
@Test
public void testXmlReportOnScalaSuite() throws Exception {
String testClassName = MockScalaTest.class.getCanonicalName();
AntJunitXmlReportListener.TestSuite testSuite = runTestAndParseXml(testClassName, false);
assertNotNull(testSuite);
assertEquals(1, testSuite.getTests());
assertEquals(0, testSuite.getFailures());
assertEquals(0, testSuite.getErrors());
assertEquals(0, testSuite.getSkipped());
assertEquals(testClassName, testSuite.getName());
List<AntJunitXmlReportListener.TestCase> testCases = testSuite.getTestCases();
assertEquals(1, testCases.size());
AntJunitXmlReportListener.TestCase testCase = testCases.get(0);
assertEquals(testClassName, testCase.getClassname());
assertNull(testCase.getFailure());
assertNull(testCase.getError());
}
protected File runTestAndReturnXmlFile(String testClassName, boolean shouldFail)
throws IOException, JAXBException {
String outdirPath = temporary.newFolder("testOutputDir").getAbsolutePath();
String args = Joiner.on(" ").join(testClassName, "-xmlreport", "-outdir", outdirPath);
// run through asArgsArray so that we always tack on parameterized test arguments
if (shouldFail) {
try {
invokeConsoleRunner(args);
fail("The ConsoleRunner should throw an exception when running these tests");
} catch (RuntimeException ex) {
// Expected
ex.printStackTrace();
}
} else {
invokeConsoleRunner(args);
}
return new File(outdirPath, "TEST-" + testClassName + ".xml");
}
protected AntJunitXmlReportListener.TestSuite runTestAndParseXml(
String testClassName, boolean shouldFail) throws IOException, JAXBException {
return parseTestXml(runTestAndReturnXmlFile(testClassName, shouldFail));
}
protected AntJunitXmlReportListener.TestSuite parseTestXml(File testXmlFile)
throws IOException, JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(AntJunitXmlReportListener.TestSuite.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (AntJunitXmlReportListener.TestSuite) jaxbUnmarshaller.unmarshal(testXmlFile);
}
protected void sortTestCasesByName(List<AntJunitXmlReportListener.TestCase> testCases) {
Collections.sort(testCases, new Comparator<AntJunitXmlReportListener.TestCase>() {
@Override public int compare(AntJunitXmlReportListener.TestCase tc1,
AntJunitXmlReportListener.TestCase tc2) {
return tc1.getName().compareTo(tc2.getName());
}
});
}
}
| apache-2.0 |
IllusionRom-deprecated/android_platform_tools_idea | platform/vcs-log/graph/src/com/intellij/vcs/log/graph/Graph.java | 400 | package com.intellij.vcs.log.graph;
import com.intellij.vcs.log.graph.elements.Node;
import com.intellij.vcs.log.graph.elements.NodeRow;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author erokhins
*/
public interface Graph {
@NotNull
List<NodeRow> getNodeRows();
@Nullable
Node getCommitNodeInRow(int rowIndex);
}
| apache-2.0 |
MichaelNedzelsky/intellij-community | java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java | 15282 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.source.resolve.graphInference.constraints;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* User: anna
*/
public class PsiMethodReferenceCompatibilityConstraint implements ConstraintFormula {
private static final Logger LOG = Logger.getInstance("#" + PsiMethodReferenceCompatibilityConstraint.class.getName());
private final PsiMethodReferenceExpression myExpression;
private PsiType myT;
public PsiMethodReferenceCompatibilityConstraint(PsiMethodReferenceExpression expression, PsiType t) {
myExpression = expression;
myT = t;
}
@Override
public boolean reduce(InferenceSession session, List<ConstraintFormula> constraints) {
if (!LambdaUtil.isFunctionalType(myT)) {
session.registerIncompatibleErrorMessage(myT.getPresentableText() + " is not a functional interface");
return false;
}
final PsiType groundTargetType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(myT);
final PsiClassType.ClassResolveResult classResolveResult = PsiUtil.resolveGenericsClassInType(groundTargetType);
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(classResolveResult);
if (interfaceMethod == null) {
session.registerIncompatibleErrorMessage("No valid function type can be found for " + myT.getPresentableText());
return false;
}
final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, classResolveResult);
final MethodSignature signature = interfaceMethod.getSignature(substitutor);
final PsiParameter[] targetParameters = interfaceMethod.getParameterList().getParameters();
final PsiType interfaceMethodReturnType = interfaceMethod.getReturnType();
final PsiType returnType = substitutor.substitute(interfaceMethodReturnType);
final PsiType[] typeParameters = myExpression.getTypeParameters();
final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(myExpression);
if (myExpression.isExact()) {
final PsiMember applicableMember = myExpression.getPotentiallyApplicableMember();
LOG.assertTrue(applicableMember != null);
final PsiClass applicableMemberContainingClass = applicableMember.getContainingClass();
final PsiClass containingClass = qualifierResolveResult.getContainingClass();
PsiSubstitutor psiSubstitutor = getSubstitutor(signature, qualifierResolveResult, applicableMember, applicableMemberContainingClass);
PsiType applicableMethodReturnType = applicableMember instanceof PsiMethod ? ((PsiMethod)applicableMember).getReturnType() : null;
int idx = 0;
for (PsiTypeParameter param : ((PsiTypeParameterListOwner)applicableMember).getTypeParameters()) {
if (idx < typeParameters.length) {
psiSubstitutor = psiSubstitutor.put(param, typeParameters[idx++]);
}
}
final PsiParameter[] parameters = applicableMember instanceof PsiMethod ? ((PsiMethod)applicableMember).getParameterList().getParameters() : PsiParameter.EMPTY_ARRAY;
if (targetParameters.length == parameters.length + 1) {
final PsiType qualifierType = PsiMethodReferenceUtil.getQualifierType(myExpression);
final PsiClass qualifierClass = PsiUtil.resolveClassInType(qualifierType);
if (qualifierClass != null) {
final PsiType pType = signature.getParameterTypes()[0];
constraints.add(new StrictSubtypingConstraint(session.substituteWithInferenceVariables(qualifierType), pType));
}
for (int i = 1; i < targetParameters.length; i++) {
constraints.add(new TypeCompatibilityConstraint(session.substituteWithInferenceVariables(psiSubstitutor.substitute(parameters[i - 1].getType())),
signature.getParameterTypes()[i]));
}
}
else if (targetParameters.length == parameters.length) {
for (int i = 0; i < targetParameters.length; i++) {
constraints.add(new TypeCompatibilityConstraint(session.substituteWithInferenceVariables(psiSubstitutor.substitute(parameters[i].getType())),
signature.getParameterTypes()[i]));
}
}
else {
session.registerIncompatibleErrorMessage("Incompatible parameter types in method reference expression");
return false;
}
if (!PsiType.VOID.equals(returnType) && returnType != null) {
if (PsiType.VOID.equals(applicableMethodReturnType)) {
session.registerIncompatibleErrorMessage("Incompatible types: expected not void but compile-time declaration for the method reference has void return type");
return false;
}
if (applicableMethodReturnType != null) {
constraints.add(new TypeCompatibilityConstraint(returnType,
session.substituteWithInferenceVariables(psiSubstitutor.substitute(applicableMethodReturnType))));
}
else if (applicableMember instanceof PsiClass || applicableMember instanceof PsiMethod && ((PsiMethod)applicableMember).isConstructor()) {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(applicableMember.getProject());
if (containingClass != null) {
final PsiType classType = session.substituteWithInferenceVariables(elementFactory.createType(containingClass, psiSubstitutor));
constraints.add(new TypeCompatibilityConstraint(returnType, classType));
}
}
}
return true;
}
//------ non exact method references --------------------
for (PsiType paramType : signature.getParameterTypes()) {
if (!session.isProperType(paramType)) {
//session.registerIncompatibleErrorMessage("Parameter type in not yet inferred: " + type.getPresentableText());
return false;
}
}
final Map<PsiElement, PsiType> map = LambdaUtil.getFunctionalTypeMap();
final PsiType added = map.put(myExpression, session.startWithFreshVars(groundTargetType));
final JavaResolveResult resolve;
try {
resolve = myExpression.advancedResolve(true);
}
finally {
if (added == null) {
map.remove(myExpression);
}
}
final PsiElement element = resolve.getElement();
if (element == null) {
session.registerIncompatibleErrorMessage("No compile-time declaration for the method reference is found");
return false;
}
if (PsiType.VOID.equals(returnType) || returnType == null) {
return true;
}
if (element instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)element;
final PsiType referencedMethodReturnType;
final PsiClass containingClass = method.getContainingClass();
LOG.assertTrue(containingClass != null, method);
PsiSubstitutor psiSubstitutor = getSubstitutor(signature, qualifierResolveResult, method, containingClass);
if (method.isConstructor()) {
referencedMethodReturnType = JavaPsiFacade.getElementFactory(method.getProject()).createType(containingClass, PsiSubstitutor.EMPTY);
}
else {
referencedMethodReturnType = method.getReturnType();
}
LOG.assertTrue(referencedMethodReturnType != null, method);
//if i) the method reference elides NonWildTypeArguments,
// ii) the compile-time declaration is a generic method, and
// iii) the return type of the compile-time declaration mentions at least one of the method's type parameters;
if (typeParameters.length == 0 && method.getTypeParameters().length > 0) {
final PsiClass interfaceClass = classResolveResult.getElement();
LOG.assertTrue(interfaceClass != null);
if (PsiPolyExpressionUtil.mentionsTypeParameters(referencedMethodReturnType,
ContainerUtil.newHashSet(method.getTypeParameters()))) {
session.registerSiteSubstitutor(psiSubstitutor);
session.initBounds(myExpression, method.getTypeParameters());
//the constraint reduces to the bound set B3 which would be used to determine the method reference's invocation type
//when targeting the return type of the function type, as defined in 18.5.2.
session.collectApplicabilityConstraints(myExpression, ((MethodCandidateInfo)resolve), groundTargetType);
session.registerReturnTypeConstraints(psiSubstitutor.substitute(referencedMethodReturnType), returnType);
return true;
}
}
if (PsiType.VOID.equals(referencedMethodReturnType)) {
session.registerIncompatibleErrorMessage("Incompatible types: expected not void but compile-time declaration for the method reference has void return type");
return false;
}
int idx = 0;
for (PsiTypeParameter param : method.getTypeParameters()) {
if (idx < typeParameters.length) {
psiSubstitutor = psiSubstitutor.put(param, typeParameters[idx++]);
}
}
if (myExpression.isConstructor() && PsiUtil.isRawSubstitutor(containingClass, qualifierResolveResult.getSubstitutor())) {
session.initBounds(myExpression, containingClass.getTypeParameters());
}
final PsiType capturedReturnType = PsiImplUtil.normalizeWildcardTypeByPosition(psiSubstitutor.substitute(referencedMethodReturnType), myExpression);
constraints.add(new TypeCompatibilityConstraint(returnType, session.substituteWithInferenceVariables(capturedReturnType)));
}
return true;
}
private PsiSubstitutor getSubstitutor(MethodSignature signature,
PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult,
PsiMember member,
@Nullable PsiClass containingClass) {
final PsiClass qContainingClass = qualifierResolveResult.getContainingClass();
PsiSubstitutor psiSubstitutor = qualifierResolveResult.getSubstitutor();
if (qContainingClass != null && containingClass != null) {
// 15.13.1 If the ReferenceType is a raw type, and there exists a parameterization of this type, T, that is a supertype of P1,
// the type to search is the result of capture conversion (5.1.10) applied to T;
// otherwise, the type to search is the same as the type of the first search. Again, the type arguments, if any, are given by the method reference.
if ( PsiUtil.isRawSubstitutor(qContainingClass, psiSubstitutor)) {
if (member instanceof PsiMethod && PsiMethodReferenceUtil.isSecondSearchPossible(signature.getParameterTypes(), qualifierResolveResult, myExpression)) {
final PsiType pType = PsiImplUtil.normalizeWildcardTypeByPosition(signature.getParameterTypes()[0], myExpression);
psiSubstitutor = getParameterizedTypeSubstitutor(qContainingClass, pType);
}
else if (member instanceof PsiMethod && ((PsiMethod)member).isConstructor() || member instanceof PsiClass) {
//15.13.1
//If ClassType is a raw type, but is not a non-static member type of a raw type,
//the candidate notional member methods are those specified in §15.9.3 for a class instance creation expression that uses <>
//to elide the type arguments to a class.
final PsiResolveHelper helper = JavaPsiFacade.getInstance(myExpression.getProject()).getResolveHelper();
final PsiType[] paramTypes =
member instanceof PsiMethod ? ((PsiMethod)member).getSignature(PsiSubstitutor.EMPTY).getParameterTypes() : PsiType.EMPTY_ARRAY;
LOG.assertTrue(paramTypes.length == signature.getParameterTypes().length, "expr: " + myExpression + "; " +
paramTypes.length + "; " +
Arrays.toString(signature.getParameterTypes()));
psiSubstitutor = helper.inferTypeArguments(qContainingClass.getTypeParameters(),
paramTypes,
signature.getParameterTypes(),
PsiUtil.getLanguageLevel(myExpression));
}
else {
psiSubstitutor = PsiSubstitutor.EMPTY;
}
}
if (qContainingClass.isInheritor(containingClass, true)) {
psiSubstitutor = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, psiSubstitutor);
LOG.assertTrue(psiSubstitutor != null);
}
}
return psiSubstitutor;
}
public static PsiSubstitutor getParameterizedTypeSubstitutor(PsiClass qContainingClass, PsiType pType) {
if (pType instanceof PsiIntersectionType) {
for (PsiType type : ((PsiIntersectionType)pType).getConjuncts()) {
PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(type);
if (InheritanceUtil.isInheritorOrSelf(resolveResult.getElement(), qContainingClass, true)) {
return getParameterizedTypeSubstitutor(qContainingClass, type);
}
}
}
PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(pType);
PsiClass paramClass = resolveResult.getElement();
LOG.assertTrue(paramClass != null);
PsiSubstitutor psiSubstitutor = TypeConversionUtil.getClassSubstitutor(qContainingClass, paramClass, resolveResult.getSubstitutor());
LOG.assertTrue(psiSubstitutor != null);
return psiSubstitutor;
}
@Override
public void apply(PsiSubstitutor substitutor, boolean cache) {
myT = substitutor.substitute(myT);
}
@Override
public String toString() {
return myExpression.getText() + " -> " + myT.getPresentableText();
}
}
| apache-2.0 |
oneliang/third-party-lib | proguard/proguard/evaluation/value/SpecificLongValue.java | 6546 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2014 Eric Lafortune (eric@graphics.cornell.edu)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.evaluation.value;
/**
* This LongValue represents a specific long value.
*
* @author Eric Lafortune
*/
abstract class SpecificLongValue extends LongValue
{
// Implementations of unary methods of LongValue.
public LongValue negate()
{
return new NegatedLongValue(this);
}
public IntegerValue convertToInteger()
{
return new ConvertedIntegerValue(this);
}
public FloatValue convertToFloat()
{
return new ConvertedFloatValue(this);
}
public DoubleValue convertToDouble()
{
return new ConvertedDoubleValue(this);
}
// Implementations of binary methods of LongValue.
public LongValue generalize(LongValue other)
{
return other.generalize(this);
}
public LongValue add(LongValue other)
{
return other.add(this);
}
public LongValue subtract(LongValue other)
{
return other.subtractFrom(this);
}
public LongValue subtractFrom(LongValue other)
{
return other.subtract(this);
}
public LongValue multiply(LongValue other)
{
return other.multiply(this);
}
public LongValue divide(LongValue other)
throws ArithmeticException
{
return other.divideOf(this);
}
public LongValue divideOf(LongValue other)
throws ArithmeticException
{
return other.divide(this);
}
public LongValue remainder(LongValue other)
throws ArithmeticException
{
return other.remainderOf(this);
}
public LongValue remainderOf(LongValue other)
throws ArithmeticException
{
return other.remainder(this);
}
public LongValue shiftLeft(IntegerValue other)
{
return other.shiftLeftOf(this);
}
public LongValue shiftRight(IntegerValue other)
{
return other.shiftRightOf(this);
}
public LongValue unsignedShiftRight(IntegerValue other)
{
return other.unsignedShiftRightOf(this);
}
public LongValue and(LongValue other)
{
return other.and(this);
}
public LongValue or(LongValue other)
{
return other.or(this);
}
public LongValue xor(LongValue other)
{
return other.xor(this);
}
public IntegerValue compare(LongValue other)
{
return other.compareReverse(this);
}
// Implementations of binary LongValue methods with SpecificLongValue
// arguments.
public LongValue generalize(SpecificLongValue other)
{
return this.equals(other) ? this : ValueFactory.LONG_VALUE;
}
public LongValue add(SpecificLongValue other)
{
return new CompositeLongValue(this, CompositeLongValue.ADD, other);
}
public LongValue subtract(SpecificLongValue other)
{
return this.equals(other) ?
ParticularValueFactory.LONG_VALUE_0 :
new CompositeLongValue(this, CompositeLongValue.SUBTRACT, other);
}
public LongValue subtractFrom(SpecificLongValue other)
{
return this.equals(other) ?
ParticularValueFactory.LONG_VALUE_0 :
new CompositeLongValue(other, CompositeLongValue.SUBTRACT, this);
}
public LongValue multiply(SpecificLongValue other)
{
return new CompositeLongValue(this, CompositeLongValue.MULTIPLY, other);
}
public LongValue divide(SpecificLongValue other)
throws ArithmeticException
{
return new CompositeLongValue(this, CompositeLongValue.DIVIDE, other);
}
public LongValue divideOf(SpecificLongValue other)
throws ArithmeticException
{
return new CompositeLongValue(other, CompositeLongValue.DIVIDE, this);
}
public LongValue remainder(SpecificLongValue other)
throws ArithmeticException
{
return new CompositeLongValue(this, CompositeLongValue.REMAINDER, other);
}
public LongValue remainderOf(SpecificLongValue other)
throws ArithmeticException
{
return new CompositeLongValue(other, CompositeLongValue.REMAINDER, this);
}
public LongValue shiftLeft(SpecificLongValue other)
{
return new CompositeLongValue(this, CompositeLongValue.SHIFT_LEFT, other);
}
public LongValue shiftRight(SpecificLongValue other)
{
return new CompositeLongValue(this, CompositeLongValue.SHIFT_RIGHT, other);
}
public LongValue unsignedShiftRight(SpecificLongValue other)
{
return new CompositeLongValue(this, CompositeLongValue.UNSIGNED_SHIFT_RIGHT, other);
}
public LongValue and(SpecificLongValue other)
{
return this.equals(other) ?
this :
new CompositeLongValue(other, CompositeLongValue.AND, this);
}
public LongValue or(SpecificLongValue other)
{
return this.equals(other) ?
this :
new CompositeLongValue(other, CompositeLongValue.OR, this);
}
public LongValue xor(SpecificLongValue other)
{
return this.equals(other) ?
ParticularValueFactory.LONG_VALUE_0 :
new CompositeLongValue(other, CompositeLongValue.XOR, this);
}
public IntegerValue compare(SpecificLongValue other)
{
return new ComparisonValue(this, other);
}
// Implementations for Value.
public boolean isSpecific()
{
return true;
}
// Implementations for Object.
public boolean equals(Object object)
{
return object != null &&
this.getClass() == object.getClass();
}
public int hashCode()
{
return this.getClass().hashCode();
}
}
| apache-2.0 |
CloudSlang/cs-actions | cs-office-365/src/main/java/io/cloudslang/content/office365/entities/GetAttachmentsInputs.java | 3141 | /*
* (c) Copyright 2019 Micro Focus, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available 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 io.cloudslang.content.office365.entities;
import org.jetbrains.annotations.NotNull;
import static org.apache.commons.lang3.StringUtils.EMPTY;
public class GetAttachmentsInputs {
private final String messageId;
private final String attachmentId;
private final String filePath;
private final Office365CommonInputs commonInputs;
@java.beans.ConstructorProperties({"messageId", "attachmentId", "filePath", "commonInputs"})
public GetAttachmentsInputs(String messageId, String attachmentId, String filePath, Office365CommonInputs commonInputs) {
this.messageId = messageId;
this.attachmentId = attachmentId;
this.filePath = filePath;
this.commonInputs = commonInputs;
}
@NotNull
public static GetAttachmentsInputsBuilder builder() {
return new GetAttachmentsInputsBuilder();
}
@NotNull
public String getMessageId() {
return messageId;
}
@NotNull
public String getAttachmentId() {
return attachmentId;
}
@NotNull
public String getoFilePath() {
return this.filePath;
}
@NotNull
public Office365CommonInputs getCommonInputs() {
return this.commonInputs;
}
public static class GetAttachmentsInputsBuilder {
private String messageId = EMPTY;
private String attachmentId = EMPTY;
private String filePath = EMPTY;
private Office365CommonInputs commonInputs;
GetAttachmentsInputsBuilder() {
}
@NotNull
public GetAttachmentsInputs.GetAttachmentsInputsBuilder messageId(@NotNull final String messageId) {
this.messageId = messageId;
return this;
}
@NotNull
public GetAttachmentsInputs.GetAttachmentsInputsBuilder attachmentId(@NotNull final String attachmentId) {
this.attachmentId = attachmentId;
return this;
}
@NotNull
public GetAttachmentsInputs.GetAttachmentsInputsBuilder filePath(@NotNull final String filePath) {
this.filePath = filePath;
return this;
}
@NotNull
public GetAttachmentsInputs.GetAttachmentsInputsBuilder commonInputs(@NotNull final Office365CommonInputs commonInputs) {
this.commonInputs = commonInputs;
return this;
}
public GetAttachmentsInputs build() {
return new GetAttachmentsInputs(messageId, attachmentId, filePath, commonInputs);
}
}
}
| apache-2.0 |
Xylus/pinpoint | web/src/main/java/com/navercorp/pinpoint/web/service/DotExtractor.java | 3617 | /*
* Copyright 2019 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.service;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.web.scatter.ScatterData;
import com.navercorp.pinpoint.web.vo.*;
import com.navercorp.pinpoint.web.vo.scatter.ApplicationScatterScanResult;
import com.navercorp.pinpoint.web.vo.scatter.Dot;
import com.navercorp.pinpoint.web.vo.scatter.ScatterScanResult;
import com.navercorp.pinpoint.common.profiler.util.TransactionId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @author emeroad
* @author HyunGil Jeong
*/
public class DotExtractor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final Map<Application, List<Dot>> dotMap = new HashMap<>(128);
public DotExtractor() {
}
public void addDot(Application application, Dot dot) {
Objects.requireNonNull(application, "application");
Objects.requireNonNull(dot, "dot");
final List<Dot> dotList = getDotList(application);
dotList.add(dot);
logger.trace("Application:{} Dot:{}", application, dot);
}
public Dot newDot(SpanBo span) {
Objects.requireNonNull(span, "span");
final TransactionId transactionId = span.getTransactionId();
return new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId());
}
private List<Dot> getDotList(Application spanApplication) {
List<Dot> dotList = this.dotMap.computeIfAbsent(spanApplication, k -> new ArrayList<>());
return dotList;
}
public List<ApplicationScatterScanResult> getApplicationScatterScanResult(long from, long to) {
List<ApplicationScatterScanResult> applicationScatterScanResult = new ArrayList<>();
for (Map.Entry<Application, List<Dot>> entry : this.dotMap.entrySet()) {
List<Dot> dotList = entry.getValue();
Application application = entry.getKey();
ScatterScanResult scatterScanResult = new ScatterScanResult(from, to, dotList);
applicationScatterScanResult.add(new ApplicationScatterScanResult(application, scatterScanResult));
}
return applicationScatterScanResult;
}
public Map<Application, ScatterData> getApplicationScatterData(long from, long to, int xGroupUnitMillis, int yGroupUnitMillis) {
Map<Application, ScatterData> applicationScatterDataMap = new HashMap<>();
for (Map.Entry<Application, List<Dot>> entry : this.dotMap.entrySet()) {
Application application = entry.getKey();
List<Dot> dotList = entry.getValue();
ScatterData scatterData = new ScatterData(from, to, xGroupUnitMillis, yGroupUnitMillis);
scatterData.addDot(dotList);
applicationScatterDataMap.put(application, scatterData);
}
return applicationScatterDataMap;
}
}
| apache-2.0 |
GaryWKeim/ehcache3 | clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java | 31815 | /*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.clustered.client.internal.store;
import com.google.common.base.Objects;
import org.assertj.core.api.ThrowableAssert;
import org.ehcache.Cache;
import org.ehcache.clustered.client.TestTimeSource;
import org.ehcache.clustered.client.config.ClusteredResourcePool;
import org.ehcache.clustered.client.config.ClusteringServiceConfiguration;
import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder;
import org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory;
import org.ehcache.clustered.client.internal.UnitTestConnectionService;
import org.ehcache.clustered.client.internal.store.ServerStoreProxy.ServerCallback;
import org.ehcache.clustered.client.internal.store.operations.EternalChainResolver;
import org.ehcache.clustered.common.internal.store.operations.codecs.OperationsCodec;
import org.ehcache.clustered.common.ServerSideConfiguration;
import org.ehcache.clustered.common.internal.ServerStoreConfiguration;
import org.ehcache.config.EvictionAdvisor;
import org.ehcache.config.ResourcePools;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.core.Ehcache;
import org.ehcache.core.spi.store.Store;
import org.ehcache.core.statistics.DefaultStatisticsService;
import org.ehcache.expiry.ExpiryPolicy;
import org.ehcache.impl.store.DefaultStoreEventDispatcher;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.ehcache.spi.resilience.StoreAccessException;
import org.ehcache.core.spi.time.TimeSource;
import org.ehcache.core.statistics.StoreOperationOutcomes;
import org.ehcache.impl.store.HashUtils;
import org.ehcache.impl.serialization.LongSerializer;
import org.ehcache.impl.serialization.StringSerializer;
import org.ehcache.spi.serialization.Serializer;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.terracotta.connection.Connection;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.ehcache.clustered.util.StatisticsTestUtils.validateStat;
import static org.ehcache.clustered.util.StatisticsTestUtils.validateStats;
import static org.ehcache.core.spi.store.Store.ValueHolder.NO_EXPIRE;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.CombinableMatcher.either;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
public class ClusteredStoreTest {
private static final String CACHE_IDENTIFIER = "testCache";
private static final URI CLUSTER_URI = URI.create("terracotta://localhost");
private ClusteredStore<Long, String> store;
private final Store.Configuration<Long, String> config = new Store.Configuration<Long, String>() {
@Override
public Class<Long> getKeyType() {
return Long.class;
}
@Override
public Class<String> getValueType() {
return String.class;
}
@Override
public EvictionAdvisor<? super Long, ? super String> getEvictionAdvisor() {
return null;
}
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public ExpiryPolicy<? super Long, ? super String> getExpiry() {
return null;
}
@Override
public ResourcePools getResourcePools() {
return null;
}
@Override
public Serializer<Long> getKeySerializer() {
return null;
}
@Override
public Serializer<String> getValueSerializer() {
return null;
}
@Override
public int getDispatcherConcurrency() {
return 0;
}
@Override
public CacheLoaderWriter<? super Long, String> getCacheLoaderWriter() {
return null;
}
};
@Before
public void setup() throws Exception {
UnitTestConnectionService.add(
CLUSTER_URI,
new UnitTestConnectionService.PassthroughServerBuilder().resource("defaultResource", 8, MemoryUnit.MB).build()
);
Connection connection = new UnitTestConnectionService().connect(CLUSTER_URI, new Properties());
ClusterTierManagerClientEntityFactory entityFactory = new ClusterTierManagerClientEntityFactory(connection, Runnable::run);
ServerSideConfiguration serverConfig =
new ServerSideConfiguration("defaultResource", Collections.emptyMap());
entityFactory.create("TestCacheManager", serverConfig);
ClusteredResourcePool resourcePool = ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB);
ServerStoreConfiguration serverStoreConfiguration = new ServerStoreConfiguration(resourcePool.getPoolAllocation(),
Long.class.getName(), String.class.getName(), LongSerializer.class.getName(), StringSerializer.class.getName(), null, false);
ClusterTierClientEntity clientEntity = entityFactory.fetchOrCreateClusteredStoreEntity("TestCacheManager", CACHE_IDENTIFIER, serverStoreConfiguration, ClusteringServiceConfiguration.ClientMode.AUTO_CREATE, false);
clientEntity.validate(serverStoreConfiguration);
ServerStoreProxy serverStoreProxy = new CommonServerStoreProxy(CACHE_IDENTIFIER, clientEntity, mock(ServerCallback.class));
TestTimeSource testTimeSource = new TestTimeSource();
OperationsCodec<Long, String> codec = new OperationsCodec<>(new LongSerializer(), new StringSerializer());
EternalChainResolver<Long, String> resolver = new EternalChainResolver<>(codec);
store = new ClusteredStore<>(config, codec, resolver, serverStoreProxy, testTimeSource, new DefaultStoreEventDispatcher<>(8), new DefaultStatisticsService());
}
@After
public void tearDown() throws Exception {
UnitTestConnectionService.remove(CLUSTER_URI);
}
private void assertTimeoutOccurred(ThrowableAssert.ThrowingCallable throwingCallable) {
assertThatExceptionOfType(StoreAccessException.class)
.isThrownBy(throwingCallable)
.withCauseInstanceOf(TimeoutException.class);
}
@Test
public void testPut() throws Exception {
assertThat(store.put(1L, "one"), is(Store.PutStatus.PUT));
validateStats(store, EnumSet.of(StoreOperationOutcomes.PutOutcome.PUT));
assertThat(store.put(1L, "another one"), is(Store.PutStatus.PUT));
assertThat(store.put(1L, "yet another one"), is(Store.PutStatus.PUT));
validateStat(store, StoreOperationOutcomes.PutOutcome.PUT, 3);
}
@Test
@SuppressWarnings("unchecked")
public void testPutTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
doThrow(TimeoutException.class).when(proxy).append(anyLong(), isNull());
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, null, proxy, timeSource, null, new DefaultStatisticsService());
assertTimeoutOccurred(() -> store.put(1L, "one"));
}
@Test
public void testGet() throws Exception {
assertThat(store.get(1L), nullValue());
validateStats(store, EnumSet.of(StoreOperationOutcomes.GetOutcome.MISS));
store.put(1L, "one");
assertThat(store.get(1L).get(), is("one"));
validateStats(store, EnumSet.of(StoreOperationOutcomes.GetOutcome.MISS, StoreOperationOutcomes.GetOutcome.HIT));
}
@Test(expected = StoreAccessException.class)
public void testGetThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
when(serverStoreProxy.get(anyLong())).thenThrow(new RuntimeException());
TestTimeSource testTimeSource = mock(TestTimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
store.get(1L);
}
@Test
@SuppressWarnings("unchecked")
public void testGetTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
long longKey = HashUtils.intHashToLong(new Long(1L).hashCode());
when(proxy.get(longKey)).thenThrow(TimeoutException.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config,null, null, proxy, null, null, new DefaultStatisticsService());
assertThat(store.get(1L), nullValue());
validateStats(store, EnumSet.of(StoreOperationOutcomes.GetOutcome.TIMEOUT));
}
@Test
public void testContainsKey() throws Exception {
assertThat(store.containsKey(1L), is(false));
store.put(1L, "one");
assertThat(store.containsKey(1L), is(true));
validateStat(store, StoreOperationOutcomes.GetOutcome.HIT, 0);
validateStat(store, StoreOperationOutcomes.GetOutcome.MISS, 0);
}
@Test(expected = StoreAccessException.class)
public void testContainsKeyThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
when(serverStoreProxy.get(anyLong())).thenThrow(new RuntimeException());
TestTimeSource testTimeSource = mock(TestTimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
store.containsKey(1L);
}
@Test
public void testRemove() throws Exception {
assertThat(store.remove(1L), is(false));
validateStats(store, EnumSet.of(StoreOperationOutcomes.RemoveOutcome.MISS));
store.put(1L, "one");
assertThat(store.remove(1L), is(true));
assertThat(store.containsKey(1L), is(false));
validateStats(store, EnumSet.of(StoreOperationOutcomes.RemoveOutcome.MISS, StoreOperationOutcomes.RemoveOutcome.REMOVED));
}
@Test
public void testRemoveThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
RuntimeException theException = new RuntimeException();
when(serverStoreProxy.getAndAppend(anyLong(), any())).thenThrow(theException);
TestTimeSource testTimeSource = new TestTimeSource();
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
assertThatExceptionOfType(StoreAccessException.class)
.isThrownBy(() -> store.remove(1L))
.withCause(theException);
}
@Test
@SuppressWarnings("unchecked")
public void testRemoveTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, null, proxy, timeSource, null, new DefaultStatisticsService());
assertTimeoutOccurred(() -> store.remove(1L));
}
@Test
public void testClear() throws Exception {
assertThat(store.containsKey(1L), is(false));
store.clear();
assertThat(store.containsKey(1L), is(false));
store.put(1L, "one");
store.put(2L, "two");
store.put(3L, "three");
assertThat(store.containsKey(1L), is(true));
store.clear();
assertThat(store.containsKey(1L), is(false));
assertThat(store.containsKey(2L), is(false));
assertThat(store.containsKey(3L), is(false));
}
@Test(expected = StoreAccessException.class)
public void testClearThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
doThrow(new RuntimeException()).when(serverStoreProxy).clear();
TestTimeSource testTimeSource = mock(TestTimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
store.clear();
}
@Test
public void testClearTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
doThrow(TimeoutException.class).when(proxy).clear();
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, null, proxy, timeSource, null, new DefaultStatisticsService());
assertTimeoutOccurred(() -> store.clear());
}
@Test
public void testPutIfAbsent() throws Exception {
assertThat(store.putIfAbsent(1L, "one", b -> {}), nullValue());
validateStats(store, EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.PUT));
assertThat(store.putIfAbsent(1L, "another one", b -> {}).get(), is("one"));
validateStats(store, EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.PUT, StoreOperationOutcomes.PutIfAbsentOutcome.HIT));
}
@Test(expected = StoreAccessException.class)
public void testPutIfAbsentThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
when(serverStoreProxy.getAndAppend(anyLong(), any())).thenThrow(new RuntimeException());
TestTimeSource testTimeSource = mock(TestTimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
store.putIfAbsent(1L, "one", b -> {});
}
@Test
@SuppressWarnings("unchecked")
public void testPutIfAbsentTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, null, proxy, timeSource, null, new DefaultStatisticsService());
assertTimeoutOccurred(() -> store.putIfAbsent(1L, "one", b -> {}));
}
@Test
public void testConditionalRemove() throws Exception {
assertThat(store.remove(1L, "one"), is(Store.RemoveStatus.KEY_MISSING));
validateStats(store, EnumSet.of(StoreOperationOutcomes.ConditionalRemoveOutcome.MISS));
store.put(1L, "one");
assertThat(store.remove(1L, "one"), is(Store.RemoveStatus.REMOVED));
validateStats(store, EnumSet.of(StoreOperationOutcomes.ConditionalRemoveOutcome.MISS, StoreOperationOutcomes.ConditionalRemoveOutcome.REMOVED));
store.put(1L, "another one");
assertThat(store.remove(1L, "one"), is(Store.RemoveStatus.KEY_PRESENT));
validateStat(store, StoreOperationOutcomes.ConditionalRemoveOutcome.MISS, 2);
}
@Test(expected = StoreAccessException.class)
public void testConditionalRemoveThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
when(serverStoreProxy.getAndAppend(anyLong(), any())).thenThrow(new RuntimeException());
TestTimeSource testTimeSource = mock(TestTimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
store.remove(1L, "one");
}
@Test
@SuppressWarnings("unchecked")
public void testConditionalRemoveTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, null, proxy, timeSource, null, new DefaultStatisticsService());
assertTimeoutOccurred(() -> store.remove(1L, "one"));
}
@Test
public void testReplace() throws Exception {
assertThat(store.replace(1L, "one"), nullValue());
validateStats(store, EnumSet.of(StoreOperationOutcomes.ReplaceOutcome.MISS));
store.put(1L, "one");
assertThat(store.replace(1L, "another one").get(), is("one"));
validateStats(store, EnumSet.of(StoreOperationOutcomes.ReplaceOutcome.MISS, StoreOperationOutcomes.ReplaceOutcome.REPLACED));
}
@Test(expected = StoreAccessException.class)
public void testReplaceThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
when(serverStoreProxy.getAndAppend(anyLong(), any())).thenThrow(new RuntimeException());
TestTimeSource testTimeSource = mock(TestTimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
store.replace(1L, "one");
}
@Test
@SuppressWarnings("unchecked")
public void testReplaceTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, null, proxy, timeSource, null, new DefaultStatisticsService());
assertTimeoutOccurred(() -> store.replace(1L, "one"));
}
@Test
public void testConditionalReplace() throws Exception {
assertThat(store.replace(1L, "one" , "another one"), is(Store.ReplaceStatus.MISS_NOT_PRESENT));
validateStats(store, EnumSet.of(StoreOperationOutcomes.ConditionalReplaceOutcome.MISS));
store.put(1L, "some other one");
assertThat(store.replace(1L, "one" , "another one"), is(Store.ReplaceStatus.MISS_PRESENT));
validateStat(store, StoreOperationOutcomes.ConditionalReplaceOutcome.MISS, 2);
validateStat(store, StoreOperationOutcomes.ConditionalReplaceOutcome.REPLACED, 0);
assertThat(store.replace(1L, "some other one" , "another one"), is(Store.ReplaceStatus.HIT));
validateStat(store, StoreOperationOutcomes.ConditionalReplaceOutcome.REPLACED, 1);
validateStat(store, StoreOperationOutcomes.ConditionalReplaceOutcome.MISS, 2);
}
@Test(expected = StoreAccessException.class)
public void testConditionalReplaceThrowsOnlySAE() throws Exception {
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> chainResolver = mock(EternalChainResolver.class);
ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class);
when(serverStoreProxy.getAndAppend(anyLong(), any())).thenThrow(new RuntimeException());
TestTimeSource testTimeSource = mock(TestTimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, chainResolver, serverStoreProxy, testTimeSource, null, new DefaultStatisticsService());
store.replace(1L, "one", "another one");
}
@Test
@SuppressWarnings("unchecked")
public void testConditionalReplaceTimeout() throws Exception {
ServerStoreProxy proxy = mock(ServerStoreProxy.class);
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, null, proxy, timeSource, null, new DefaultStatisticsService());
assertTimeoutOccurred(() -> store.replace(1L, "one", "another one"));
}
@Test
public void testBulkComputePutAll() throws Exception {
store.put(1L, "another one");
Map<Long, String> map = new HashMap<>();
map.put(1L, "one");
map.put(2L, "two");
Ehcache.PutAllFunction<Long, String> putAllFunction = new Ehcache.PutAllFunction<>(null, map, null);
Map<Long, Store.ValueHolder<String>> valueHolderMap = store.bulkCompute(new HashSet<>(Arrays.asList(1L, 2L)), putAllFunction);
assertThat(valueHolderMap.get(1L).get(), is(map.get(1L)));
assertThat(store.get(1L).get(), is(map.get(1L)));
assertThat(valueHolderMap.get(2L).get(), is(map.get(2L)));
assertThat(store.get(2L).get(), is(map.get(2L)));
assertThat(putAllFunction.getActualPutCount().get(), is(2));
validateStats(store, EnumSet.of(StoreOperationOutcomes.PutOutcome.PUT)); //outcome of the initial store put
}
@Test
public void testBulkComputeRemoveAll() throws Exception {
store.put(1L, "one");
store.put(2L, "two");
store.put(3L, "three");
Ehcache.RemoveAllFunction<Long, String> removeAllFunction = new Ehcache.RemoveAllFunction<>();
Map<Long, Store.ValueHolder<String>> valueHolderMap = store.bulkCompute(new HashSet<>(Arrays.asList(1L, 2L, 4L)), removeAllFunction);
assertThat(valueHolderMap.get(1L), nullValue());
assertThat(store.get(1L), nullValue());
assertThat(valueHolderMap.get(2L), nullValue());
assertThat(store.get(2L), nullValue());
assertThat(valueHolderMap.get(4L), nullValue());
assertThat(store.get(4L), nullValue());
validateStats(store, EnumSet.noneOf(StoreOperationOutcomes.RemoveOutcome.class));
}
@Test(expected = UnsupportedOperationException.class)
public void testBulkComputeThrowsForGenericFunction() throws Exception {
@SuppressWarnings("unchecked")
Function<Iterable<? extends Map.Entry<? extends Long, ? extends String>>, Iterable<? extends Map.Entry<? extends Long, ? extends String>>> remappingFunction
= mock(Function.class);
store.bulkCompute(new HashSet<>(Arrays.asList(1L, 2L)), remappingFunction);
}
@Test
public void testBulkComputeIfAbsentGetAll() throws Exception {
store.put(1L, "one");
store.put(2L, "two");
Ehcache.GetAllFunction<Long, String> getAllAllFunction = new Ehcache.GetAllFunction<>();
Map<Long, Store.ValueHolder<String>> valueHolderMap = store.bulkComputeIfAbsent(new HashSet<>(Arrays.asList(1L, 2L)), getAllAllFunction);
assertThat(valueHolderMap.get(1L).get(), is("one"));
assertThat(store.get(1L).get(), is("one"));
assertThat(valueHolderMap.get(2L).get(), is("two"));
assertThat(store.get(2L).get(), is("two"));
}
@Test(expected = UnsupportedOperationException.class)
public void testBulkComputeIfAbsentThrowsForGenericFunction() throws Exception {
@SuppressWarnings("unchecked")
Function<Iterable<? extends Long>, Iterable<? extends Map.Entry<? extends Long, ? extends String>>> mappingFunction
= mock(Function.class);
store.bulkComputeIfAbsent(new HashSet<>(Arrays.asList(1L, 2L)), mappingFunction);
}
@Test
public void testExpirationIsSentToHigherTiers() throws Exception {
@SuppressWarnings("unchecked")
Store.ValueHolder<String> valueHolder = mock(Store.ValueHolder.class, withSettings().defaultAnswer(RETURNS_MOCKS));
when(valueHolder.get()).thenReturn("bar");
when(valueHolder.expirationTime()).thenReturn(1000L);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> resolver = mock(EternalChainResolver.class);
when(resolver.resolve(any(ServerStoreProxy.ChainEntry.class), anyLong(), anyLong())).thenReturn(valueHolder);
ServerStoreProxy proxy = mock(ServerStoreProxy.class, withSettings().defaultAnswer(RETURNS_MOCKS));
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, resolver, proxy, timeSource, null, new DefaultStatisticsService());
Store.ValueHolder<?> vh = store.get(1L);
long expirationTime = vh.expirationTime();
assertThat(expirationTime, is(1000L));
}
@Test
public void testNoExpireIsSentToHigherTiers() throws Exception {
@SuppressWarnings("unchecked")
Store.ValueHolder<String> valueHolder = mock(Store.ValueHolder.class, withSettings().defaultAnswer(RETURNS_MOCKS));
when(valueHolder.get()).thenReturn("bar");
when(valueHolder.expirationTime()).thenReturn(NO_EXPIRE);
@SuppressWarnings("unchecked")
EternalChainResolver<Long, String> resolver = mock(EternalChainResolver.class);
when(resolver.resolve(any(ServerStoreProxy.ChainEntry.class), anyLong(), anyLong())).thenReturn(valueHolder);
ServerStoreProxy proxy = mock(ServerStoreProxy.class, withSettings().defaultAnswer(RETURNS_MOCKS));
@SuppressWarnings("unchecked")
OperationsCodec<Long, String> codec = mock(OperationsCodec.class);
TimeSource timeSource = mock(TimeSource.class);
ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, resolver, proxy, timeSource, null, new DefaultStatisticsService());
Store.ValueHolder<?> vh = store.get(1L);
long expirationTime = vh.expirationTime();
assertThat(expirationTime, is(NO_EXPIRE));
}
@Test
public void testEmptyChainIteratorIsEmpty() throws StoreAccessException {
Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();
assertThat(iterator.hasNext(), is(false));
try {
iterator.next();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
//expected
}
}
@Test
public void testSingleChainSingleValue() throws StoreAccessException {
store.put(1L, "foo");
Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), isEntry(1L, "foo"));
assertThat(iterator.hasNext(), is(false));
try {
iterator.next();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
//expected
}
}
@Test
public void testSingleChainMultipleValues() throws StoreAccessException {
assertThat(Long.hashCode(1L), is(Long.hashCode(~1L)));
store.put(1L, "foo");
store.put(~1L, "bar");
Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();
Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryOne = isEntry(1L, "foo");
Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryTwo = isEntry(~1L, "bar");
assertThat(iterator.hasNext(), is(true));
Cache.Entry<Long, Store.ValueHolder<String>> next = iterator.next();
assertThat(next, either(entryOne).or(entryTwo));
if (entryOne.matches(next)) {
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), is(entryTwo));
assertThat(iterator.hasNext(), is(false));
} else {
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), is(entryOne));
assertThat(iterator.hasNext(), is(false));
}
try {
iterator.next();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
//expected
}
}
@Test
public void testSingleChainRequiresResolution() throws StoreAccessException {
store.put(~1L, "bar");
store.put(1L, "foo");
store.remove(~1L);
Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), isEntry(1L, "foo"));
assertThat(iterator.hasNext(), is(false));
try {
iterator.next();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
//expected
}
}
@Test
public void testMultipleChains() throws StoreAccessException {
store.put(1L, "foo");
store.put(2L, "bar");
Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();
Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryOne = isEntry(1L, "foo");
Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryTwo = isEntry(2L, "bar");
assertThat(iterator.hasNext(), is(true));
Cache.Entry<Long, Store.ValueHolder<String>> next = iterator.next();
assertThat(next, either(entryOne).or(entryTwo));
if (entryOne.matches(next)) {
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), is(entryTwo));
assertThat(iterator.hasNext(), is(false));
} else {
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), is(entryOne));
assertThat(iterator.hasNext(), is(false));
}
try {
iterator.next();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
//expected
}
}
private <K, V> Matcher<Cache.Entry<K, Store.ValueHolder<V>>> isEntry(K key, V value) {
return new TypeSafeMatcher<Cache.Entry<K, Store.ValueHolder<V>>>() {
@Override
public void describeTo(Description description) {
description.appendText(" the cache entry { ").appendValue(key).appendText(": ").appendValue(value).appendText(" }");
}
@Override
protected boolean matchesSafely(Cache.Entry<K, Store.ValueHolder<V>> item) {
return Objects.equal(key, item.getKey()) && Objects.equal(value, item.getValue().get());
}
};
}
}
| apache-2.0 |
swift-lang/swift-k | cogkit/modules/abstraction-common/src/org/globus/cog/abstraction/interfaces/OutputListener.java | 1453 | /*
* Swift Parallel Scripting Language (http://swift-lang.org)
* Code from Java CoG Kit Project (see notice below) with modifications.
*
* Copyright 2005-2014 University of Chicago
*
* 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.
*/
// ----------------------------------------------------------------------
// This code is developed as part of the Java CoG Kit project
// The terms of the license can be found at http://www.cogkit.org/license
// This message may not be removed or altered.
// ----------------------------------------------------------------------
package org.globus.cog.abstraction.interfaces;
import org.globus.cog.abstraction.impl.common.task.OutputEvent;
/**
* This interface represents a listener that gets notified every time the
* the contents of {@link org.globus.cog.abstraction.interfaces.Task#getStdOutput()} changes.
*/
public interface OutputListener {
public void outputChanged(OutputEvent event);
}
| apache-2.0 |
a1vanov/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheStartStopLoadTest.java | 4316 | /*
* 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.ignite.internal.processors.cache;
import java.util.Date;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
/**
* Test for dynamic cache start.
*/
@SuppressWarnings("unchecked")
public class IgniteCacheStartStopLoadTest extends GridCommonAbstractTest {
/** */
private static final long DURATION = 60_000L;
/** */
private static final int CACHE_COUNT = 1;
/** */
private static final String[] CACHE_NAMES = new String[CACHE_COUNT];
/** */
static {
for (int i = 0; i < CACHE_NAMES.length; i++)
CACHE_NAMES[i] = "cache_" + i;
}
/** */
private WeakHashMap<Object, Boolean> weakMap;
/** {@inheritDoc} */
@Override protected long getTestTimeout() {
return DURATION + 20_000L;
}
/**
* @return Number of nodes for this test.
*/
public int nodeCount() {
return 4;
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
return super.getConfiguration(igniteInstanceName);
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGridsMultiThreaded(nodeCount());
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
}
/**
* @throws Exception If failed.
*/
public void testMemoryLeaks() throws Exception {
final Ignite ignite = ignite(0);
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < DURATION) {
final AtomicInteger idx = new AtomicInteger();
GridTestUtils.runMultiThreaded(new Callable<Object>() {
@Override public Object call() throws Exception {
CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
ccfg.setName(CACHE_NAMES[idx.getAndIncrement()]);
ignite.createCache(ccfg);
return null;
}
}, CACHE_COUNT, "cache-starter");
for (String cacheName : CACHE_NAMES)
assert ignite(0).cache(cacheName) != null;
if (weakMap == null) {
weakMap = new WeakHashMap<>();
IgniteCache<Object, Object> cache = ignite(0).cache(CACHE_NAMES[0]);
Object obj = new Date();
cache.put(1, obj);
weakMap.put(((IgniteCacheProxy)cache).delegate(), Boolean.TRUE);
weakMap.put(obj, Boolean.TRUE);
}
idx.set(0);
GridTestUtils.runMultiThreaded(new Callable<Object>() {
@Override public Object call() throws Exception {
ignite.destroyCache(CACHE_NAMES[idx.getAndIncrement()]);
return null;
}
}, CACHE_COUNT, "cache-starter");
System.out.println("Start-Stop Ok !!!");
}
GridTestUtils.runGC();
assert weakMap.isEmpty() : weakMap;
}
} | apache-2.0 |
marbon87/spring-cloud-config | spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/FileMonitorConfigurationTest.java | 5575 | /*
* Copyright 2015-2019 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.config.monitor;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.config.server.environment.AbstractScmEnvironmentRepository;
import org.springframework.cloud.config.server.environment.JGitEnvironmentProperties;
import org.springframework.cloud.config.server.environment.JGitEnvironmentRepository;
import org.springframework.cloud.config.server.environment.NativeEnvironmentProperties;
import org.springframework.cloud.config.server.environment.NativeEnvironmentRepository;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Gilles Robert
* @author Stefan Pfeiffer
*
*/
public class FileMonitorConfigurationTest {
private static final String SAMPLE_PATH = "resources/pathsamples";
private static final String SAMPLE_FILE_URL = "file:///test";
private FileMonitorConfiguration fileMonitorConfiguration = new FileMonitorConfiguration();
private List<AbstractScmEnvironmentRepository> repositories = new ArrayList<>();
@Before
public void setup() {
fileMonitorConfiguration.setResourceLoader(new FileSystemResourceLoader());
}
@After
public void tearDown() {
fileMonitorConfiguration.stop();
}
@Test
public void testStart_whenRepositoriesAreNull() {
// given
// when
fileMonitorConfiguration.start();
// then
Set<Path> directory = getDirectory();
assertThat(directory).isNull();
}
@Test
public void testStart_withNativeEnvironmentRepository() {
// given
NativeEnvironmentRepository repository = createNativeEnvironmentRepository();
ReflectionTestUtils.setField(fileMonitorConfiguration, "nativeEnvironmentRepository", repository);
// when
fileMonitorConfiguration.start();
// then
assertOnDirectory(1);
}
@Test
public void testStart_withOneScmRepository() {
// given
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_PATH);
addScmRepository(repository);
// when
fileMonitorConfiguration.start();
// then
assertOnDirectory(1);
}
@Test
public void testStart_withTwoScmRepositories() {
// given
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_PATH);
AbstractScmEnvironmentRepository secondRepository = createScmEnvironmentRepository("anotherPath");
addScmRepository(repository);
addScmRepository(secondRepository);
// when
fileMonitorConfiguration.start();
// then
assertOnDirectory(2);
}
@Test
public void testStart_withOneFileUrlScmRepository() {
// given
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_FILE_URL);
addScmRepository(repository);
// when
fileMonitorConfiguration.start();
// then
assertOnDirectory(1);
}
@Test
public void testStart_withTwoMixedPathAndFileUrlScmRepositories() {
// given
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_PATH);
AbstractScmEnvironmentRepository secondRepository = createScmEnvironmentRepository(SAMPLE_FILE_URL);
addScmRepository(repository);
addScmRepository(secondRepository);
// when
fileMonitorConfiguration.start();
// then
assertOnDirectory(2);
}
private void addScmRepository(AbstractScmEnvironmentRepository... repository) {
repositories.addAll(Arrays.asList(repository));
ReflectionTestUtils.setField(fileMonitorConfiguration, "scmRepositories", repositories);
}
private NativeEnvironmentRepository createNativeEnvironmentRepository() {
ConfigurableEnvironment environment = createConfigurableEnvironment();
NativeEnvironmentProperties properties = new NativeEnvironmentProperties();
properties.setSearchLocations(new String[] { "classpath:pathsamples" });
return new NativeEnvironmentRepository(environment, properties);
}
private AbstractScmEnvironmentRepository createScmEnvironmentRepository(String uri) {
ConfigurableEnvironment environment = createConfigurableEnvironment();
JGitEnvironmentProperties properties = new JGitEnvironmentProperties();
properties.setUri(uri);
return new JGitEnvironmentRepository(environment, properties);
}
private void assertOnDirectory(int expectedDirectorySize) {
Set<Path> directory = getDirectory();
assertThat(directory).isNotNull();
assertThat(directory).hasSize(expectedDirectorySize);
}
private ConfigurableEnvironment createConfigurableEnvironment() {
return new MockEnvironment();
}
@SuppressWarnings("unchecked")
private Set<Path> getDirectory() {
return (Set<Path>) ReflectionTestUtils.getField(fileMonitorConfiguration, "directory");
}
}
| apache-2.0 |
Zhangsongsong/GraduationPro | 毕业设计/code/android/YYFramework/src/com/hyphenate/easeui/ui/EaseBaseActivity.java | 2572 | /**
* Copyright (C) 2016 Hyphenate Inc. 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.
* 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.hyphenate.easeui.ui;
import org.ql.activity.customtitle.FragmentActActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.hyphenate.easeui.controller.EaseUI;
@SuppressLint({"NewApi", "Registered"})
public class EaseBaseActivity extends FragmentActActivity {
protected InputMethodManager inputMethodManager;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
//http://stackoverflow.com/questions/4341600/how-to-prevent-multiple-instances-of-an-activity-when-it-is-launched-with-differ/
// should be in launcher activity, but all app use this can avoid the problem
if(!isTaskRoot()){
Intent intent = getIntent();
String action = intent.getAction();
if(intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)){
finish();
return;
}
}
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
// cancel the notification
EaseUI.getInstance().getNotifier().reset();
}
protected void hideSoftKeyboard() {
if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
if (getCurrentFocus() != null)
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* back
*
* @param view
*/
public void back(View view) {
finish();
}
}
| apache-2.0 |
mvp4g/mvp4g-examples | examples/Mvp4gModules/src/com/mvp4g/example/client/main/view/InfoReceiverView.java | 1112 | package com.mvp4g.example.client.main.view;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.mvp4g.example.client.main.presenter.InfoReceiverPresenter.IInfoReceiverView;
public class InfoReceiverView extends DecoratedPopupPanel implements IInfoReceiverView {
private static int position = 0;
private Anchor close = new Anchor( "Close" );
private Label info = new Label();
public InfoReceiverView() {
FlowPanel fp = new FlowPanel();
fp.add( close );
fp.add( info );
setWidget( fp );
setPopupPosition( position, position );
position += 20;
}
@Override
public void setInfo( String[] info ) {
StringBuilder builder = new StringBuilder( info.length * 20 );
builder.append( "Info: " );
for ( String s : info ) {
builder.append( s ).append( "," );
}
this.info.setText( builder.toString() );
}
@Override
public HasClickHandlers getClose() {
return close;
}
}
| apache-2.0 |
CesarPantoja/jena | jena-core/src/main/java/org/apache/jena/vocabulary/RDF.java | 4855 | /*
* 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.jena.vocabulary;
import org.apache.jena.datatypes.RDFDatatype ;
import org.apache.jena.datatypes.xsd.impl.RDFLangString ;
import org.apache.jena.datatypes.xsd.impl.RDFhtml ;
import org.apache.jena.datatypes.xsd.impl.XMLLiteralType ;
import org.apache.jena.graph.Node ;
import org.apache.jena.rdf.model.Property ;
import org.apache.jena.rdf.model.Resource ;
import org.apache.jena.rdf.model.ResourceFactory ;
/**
The standard RDF vocabulary.
*/
public class RDF{
/**
* The namespace of the vocabulary as a string
*/
public static final String uri ="http://www.w3.org/1999/02/22-rdf-syntax-ns#";
/** returns the URI for this schema
@return the URI for this schema
*/
public static String getURI()
{ return uri; }
protected static final Resource resource( String local )
{ return ResourceFactory.createResource( uri + local ); }
protected static final Property property( String local )
{ return ResourceFactory.createProperty( uri, local ); }
public static Property li( int i )
{ return property( "_" + i ); }
public static final Resource Alt = resource( "Alt" );
public static final Resource Bag = resource( "Bag" );
public static final Resource Property = resource( "Property" );
public static final Resource Seq = resource( "Seq" );
public static final Resource Statement = resource( "Statement" );
public static final Resource List = resource( "List" );
public static final Resource nil = resource( "nil" );
public static final Property first = property( "first" );
public static final Property rest = property( "rest" );
public static final Property subject = property( "subject" );
public static final Property predicate = property( "predicate" );
public static final Property object = property( "object" );
public static final Property type = property( "type" );
public static final Property value = property( "value" );
// RDF 1.1 - the datatypes of language strings
public static final Resource langString = ResourceFactory.createResource(RDFLangString.rdfLangString.getURI()) ;
// RDF 1.1 - rdf:HTML
public static final Resource HTML = ResourceFactory.createResource(RDFhtml.rdfHTML.getURI()) ;
// rdf:XMLLiteral
public static final Resource xmlLiteral = ResourceFactory.createResource(XMLLiteralType.theXMLLiteralType.getURI()) ;
public static final RDFDatatype dtRDFHTML = RDFhtml.rdfHTML;
public static final RDFDatatype dtLangString = RDFLangString.rdfLangString;
public static final RDFDatatype dtXMLLiteral = XMLLiteralType.theXMLLiteralType;
/**
The same items of vocabulary, but at the Node level, parked inside a
nested class so that there's a simple way to refer to them.
*/
@SuppressWarnings("hiding")
public static final class Nodes
{
public static final Node Alt = RDF.Alt.asNode();
public static final Node Bag = RDF.Bag.asNode();
public static final Node Property = RDF.Property.asNode();
public static final Node Seq = RDF.Seq.asNode();
public static final Node Statement = RDF.Statement.asNode();
public static final Node List = RDF.List.asNode();
public static final Node nil = RDF.nil.asNode();
public static final Node first = RDF.first.asNode();
public static final Node rest = RDF.rest.asNode();
public static final Node subject = RDF.subject.asNode();
public static final Node predicate = RDF.predicate.asNode();
public static final Node object = RDF.object.asNode();
public static final Node type = RDF.type.asNode();
public static final Node value = RDF.value.asNode();
public static final Node langString = RDF.langString.asNode();
public static final Node HTML = RDF.HTML.asNode();
public static final Node xmlLiteral = RDF.xmlLiteral.asNode();
}
}
| apache-2.0 |
dusenberrymw/systemml | src/main/java/org/apache/sysml/runtime/instructions/mr/CombineUnaryInstruction.java | 2274 | /*
* 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.sysml.runtime.instructions.mr;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.instructions.InstructionUtils;
import org.apache.sysml.runtime.matrix.data.MatrixValue;
import org.apache.sysml.runtime.matrix.mapred.CachedValueMap;
import org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue;
import org.apache.sysml.runtime.matrix.operators.Operator;
public class CombineUnaryInstruction extends UnaryMRInstructionBase {
private CombineUnaryInstruction(Operator op, byte in, byte out, String istr) {
super(MRType.CombineUnary, op, in, out);
instString = istr;
}
public static CombineUnaryInstruction parseInstruction ( String str ) throws DMLRuntimeException {
InstructionUtils.checkNumFields ( str, 2 );
String[] parts = InstructionUtils.getInstructionParts ( str );
byte in, out;
String opcode = parts[0];
in = Byte.parseByte(parts[1]);
out = Byte.parseByte(parts[2]);
if ( opcode.equalsIgnoreCase("combineunary") ) {
return new CombineUnaryInstruction(null, in, out, str);
}else
return null;
}
@Override
public void processInstruction(Class<? extends MatrixValue> valueClass,
CachedValueMap cachedValues, IndexedMatrixValue tempValue,
IndexedMatrixValue zeroInput, int blockRowFactor, int blockColFactor)
throws DMLRuntimeException {
throw new DMLRuntimeException("CombineInstruction.processInstruction should never be called!");
}
}
| apache-2.0 |
frapu78/processeditor | src/com/inubit/research/gui/plugins/AnimationDemoPlugin.java | 8064 | /**
*
* Process Editor - inubit Workbench Plugin Package
*
* (C) 2009, 2010 inubit AG
* (C) 2014 the authors
*
*/
package com.inubit.research.gui.plugins;
import com.inubit.research.animation.AnimationFacade.Type;
import com.inubit.research.gui.Workbench;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import net.frapu.code.visualization.ProcessEditor;
import net.frapu.code.visualization.bpmn.SequenceFlow;
import net.frapu.code.visualization.bpmn.Task;
import net.frapu.code.visualization.bpmn.TextAnnotation;
/**
*
* @author fpu
*/
public class AnimationDemoPlugin extends WorkbenchPlugin implements Runnable {
private Task f_task1;
private Task f_task2;
private Task f_task3;
private SequenceFlow f_edge;
private TextAnnotation f_text;
private ProcessEditor f_pe;
private Workbench wb;
public AnimationDemoPlugin(Workbench workbench) {
wb = workbench;
}
@Override
public Component getMenuEntry() {
JMenuItem menu = new JMenuItem("Animation demo");
menu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread(new AnimationDemoPlugin(wb));
t.start();
}
});
return menu;
}
/**
* showing edge transition
* @throws InterruptedException
*/
private void scenario6() throws InterruptedException {
showText("It works with edges, too", 6000);
f_pe.getAnimator().addProcessObject(f_task1, 1000, 0);
f_pe.getAnimator().addProcessObject(f_task2, 1000, 0);
f_pe.getAnimator().addProcessObject(f_edge, 1000, 0);
SequenceFlow _newEdge = new SequenceFlow(f_task1, f_task2);
_newEdge.addRoutingPoint(1, new Point(100, 350));
_newEdge.addRoutingPoint(2, new Point(500, 350));
f_pe.getAnimator().animateEdge(f_edge, _newEdge, 3000, 2000);
_newEdge = new SequenceFlow(f_task1, f_task2); //creating a new container
_newEdge.addRoutingPoint(1, new Point(200, 150));
f_pe.getAnimator().animateEdge(f_edge, _newEdge, 3000, 6000);
_newEdge = new SequenceFlow(f_task1, f_task2);//creating a new container
_newEdge.addRoutingPoint(1, new Point(180, 20));
_newEdge.addRoutingPoint(2, new Point(250, 200));
_newEdge.addRoutingPoint(2, new Point(400, 300));
f_pe.getAnimator().animateEdge(f_edge, _newEdge, 3000, 10000);
f_pe.getAnimator().removeProcessObject(f_task1, 1000, 14000);
f_pe.getAnimator().removeProcessObject(f_task2, 1000, 14000);
f_pe.getAnimator().removeProcessObject(f_edge, 1000, 14000);
Thread.sleep(15500);
restoreObjects();
}
/**
* @throws InterruptedException
*
*/
private void scenario5() throws InterruptedException {
showText("... and even interrupt each other", 6000);
f_pe.getAnimator().addProcessNode(f_task1, 1000, 0, Type.TYPE_FADE_IN);
f_pe.getAnimator().animateNode(f_task1, f_task2, 3000, 2000);
f_pe.getAnimator().animateNode(f_task1, f_task3, 3000, 3500); //starts in the middle of the first
f_pe.getAnimator().removeProcessObject(f_task1, 1000, 7000);
Thread.sleep(7500);
restoreObjects();
}
/**
* node animations can be combined!
* @throws InterruptedException
*/
private void scenario4() throws InterruptedException {
showText("Animations can be combined...", 6000);
f_pe.getAnimator().addProcessNode(f_task1, 1000, 0, Type.TYPE_FADE_IN);
f_pe.getAnimator().animateNode(f_task1, f_task2, 3000, 2000);
f_pe.getAnimator().animateNode(f_task1, f_task3, 3000, 5500);
f_pe.getAnimator().removeProcessObject(f_task1, 1000, 9000);
Thread.sleep(9500);
restoreObjects();
}
private void restoreObjects() {
f_task1 = new Task(100, 100, "Tester");
f_task1.setAlpha(1.0f);
f_task2 = new Task(500, 100, "Tester234");
f_task2.setAlpha(1.0f);
f_task2.setBackground(Color.RED);
f_task3 = new Task(100, 200, "Tester234");
f_task3.setAlpha(1.0f);
f_edge = new SequenceFlow(f_task1, f_task2);
}
/**
* changing to different nodes simultaneously
* @throws InterruptedException
*/
private void scenario3() throws InterruptedException {
showText("Several nodes at the same time", 6000);
//order is important here!
//addProcessNode sets the alpha of f_task2 to 0.0
//so f_task2 should not be used as a container after adding it, that
//has to be done before!!!!
f_pe.getAnimator().addProcessNode(f_task1, 1000, 0, Type.TYPE_FADE_IN);
f_pe.getAnimator().animateNode(f_task1, f_task2, 3000, 2000);
f_pe.getAnimator().addProcessNode(f_task2, 1000, 0, Type.TYPE_FADE_IN);
f_pe.getAnimator().animateNode(f_task2, f_task3, 3000, 2500);
f_pe.getAnimator().removeProcessObject(f_task1, 1000, 7000);
f_pe.getAnimator().removeProcessObject(f_task2, 1000, 7000);
Thread.sleep(8000);
restoreObjects();
}
/**
*changing the properties of a node
* @throws InterruptedException
*/
private void scenario2() throws InterruptedException {
showText("Their properties can be changed", 6000);
f_pe.getAnimator().addProcessNode(f_task1, 1000, 0, Type.TYPE_FADE_IN);
f_task2.setSize(200, 80);
f_task2.setAlpha(0.5f);
f_pe.getAnimator().animateNode(f_task1, f_task2, 3000, 2000);
f_pe.getAnimator().removeProcessObject(f_task1, 1000, 6000);
Thread.sleep(7500);
restoreObjects();
}
/**
* fading in and out
* @throws InterruptedException
*/
private void scenario1() throws InterruptedException {
showText("Objects can be faded in and out", 6000);
//fading in
f_pe.getAnimator().addProcessNode(f_task1, 3000, 1000, Type.TYPE_FADE_IN);
//fading out with larger delay
f_pe.getAnimator().removeProcessObject(f_task1, 3000, 5000);
Thread.sleep(8500); //Thats how long everything will take
}
/**
* @param string
* @param i
*/
private void showText(String string, int time) {
if (time < 1000) {
time = 1000;
}
System.out.println("Show text: " + string);
f_text.setText(string);
// Set back to visible!
f_text.setAlpha(1.0f);
f_pe.getAnimator().addProcessObject(f_text, 1000, 0);
f_pe.getAnimator().removeProcessObject(f_text, 1000, time - 1000);
}
public void run() {
try {
f_pe = wb.getSelectedProcessEditor();
//enabling animations
f_pe.setAnimationEnabled(true);
f_text = new TextAnnotation();
f_text.setPos(300, 20);
f_text.setSize(400, 30);
//setting up our test objects
restoreObjects();
// fading
scenario1();
//state transition
scenario2();
//double state transition
scenario3();
//compound state transition
//scenario4();
//interrupted compound state transition
//scenario5();
//edge transition
//scenario6();
//barchart animation
//scenario7();
//piechart animation
//scenario8();
showText("That's it!", 6000);
Thread.sleep(4000);
showText("Copyright inubit AG 2010", 3000);
} catch (Exception ex) {
}
}
}
| apache-2.0 |
huihoo/olat | olat7.8/src/test/java/org/olat/test/load/OpenAllCoursesTest.java | 2363 | package org.olat.test.load;
import org.olat.test.util.selenium.BaseSeleneseTestCase;
import org.olat.test.util.selenium.olatapi.OLATWorkflowHelper;
import org.olat.test.util.selenium.olatapi.course.run.CourseRun;
import org.olat.test.util.selenium.olatapi.lr.LearningResources;
import org.olat.test.util.setup.SetupType;
import org.olat.test.util.setup.context.Context;
/**
* Performance test; it measures the time needed to open course, click few times (numOfIterations) in course, close course, and repeat for all courses.
*
* @author Lavinia Dumitrescu
*
*/
public class OpenAllCoursesTest extends BaseSeleneseTestCase {
private final int numOfIterations = 5;
public void testVisitAllCourses() throws Exception {
Context context = Context.setupContext(getFullName(), SetupType.TWO_NODE_CLUSTER);
OLATWorkflowHelper workflow = context.getOLATWorkflowHelper(context.getStandardAdminOlatLoginInfos(1));
LearningResources learningResources = workflow.getLearningResources();
// go to courses and open each course on each table page, then close the course
boolean selectNextPage = false;
int courseIndex = 1;
int pageLength = 20;
while (courseIndex <= pageLength) {
CourseRun courseRun = learningResources.showCourseContent(selectNextPage, courseIndex);
if (courseRun != null) {
visitCourse(courseRun);
courseIndex++;
selectNextPage = false;
} else if (courseRun == null && !learningResources.hasMorePages()) {
break;
}
if (courseIndex == 21 && learningResources.hasMorePages()) {
courseIndex = 1;
selectNextPage = true;
}
}
}
/**
* Select first numOfIterations elements in this course.
*
* @param courseRun
*/
public void visitCourse(CourseRun courseRun) throws InterruptedException {
System.out.println("visit course");
// select node in course
for (int i = 1; i <= numOfIterations; i++) {
boolean elemFound = courseRun.selectCourseElement(i);
if (!elemFound) {
break;
}
}
Thread.sleep(3000);
courseRun.closeAny();
System.out.println("closed course");
}
}
| apache-2.0 |
justinedelson/spring-security | taglibs/src/main/java/org/springframework/security/taglibs/authz/LegacyAuthorizeTag.java | 7515 | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.util.ExpressionEvaluationUtils;
/**
* An implementation of {@link javax.servlet.jsp.tagext.Tag} that allows it's body through if some authorizations
* are granted to the request's principal.
*
* @author Francois Beausoleil
*/
public class LegacyAuthorizeTag extends TagSupport {
//~ Instance fields ================================================================================================
private String ifAllGranted = "";
private String ifAnyGranted = "";
private String ifNotGranted = "";
//~ Methods ========================================================================================================
private Set<String> authoritiesToRoles(Collection<GrantedAuthority> c) {
Set<String> target = new HashSet<String>();
for (GrantedAuthority authority : c) {
if (null == authority.getAuthority()) {
throw new IllegalArgumentException(
"Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process "
+ authority.toString());
}
target.add(authority.getAuthority());
}
return target;
}
public int doStartTag() throws JspException {
if (((null == ifAllGranted) || "".equals(ifAllGranted)) && ((null == ifAnyGranted) || "".equals(ifAnyGranted))
&& ((null == ifNotGranted) || "".equals(ifNotGranted))) {
return Tag.SKIP_BODY;
}
final Collection<GrantedAuthority> granted = getPrincipalAuthorities();
final String evaledIfNotGranted = ExpressionEvaluationUtils.evaluateString("ifNotGranted", ifNotGranted,
pageContext);
if ((null != evaledIfNotGranted) && !"".equals(evaledIfNotGranted)) {
Set<GrantedAuthority> grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfNotGranted));
if (!grantedCopy.isEmpty()) {
return Tag.SKIP_BODY;
}
}
final String evaledIfAllGranted = ExpressionEvaluationUtils.evaluateString("ifAllGranted", ifAllGranted,
pageContext);
if ((null != evaledIfAllGranted) && !"".equals(evaledIfAllGranted)) {
if (!granted.containsAll(parseAuthoritiesString(evaledIfAllGranted))) {
return Tag.SKIP_BODY;
}
}
final String evaledIfAnyGranted = ExpressionEvaluationUtils.evaluateString("ifAnyGranted", ifAnyGranted,
pageContext);
if ((null != evaledIfAnyGranted) && !"".equals(evaledIfAnyGranted)) {
Set<GrantedAuthority> grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfAnyGranted));
if (grantedCopy.isEmpty()) {
return Tag.SKIP_BODY;
}
}
return Tag.EVAL_BODY_INCLUDE;
}
public String getIfAllGranted() {
return ifAllGranted;
}
public String getIfAnyGranted() {
return ifAnyGranted;
}
public String getIfNotGranted() {
return ifNotGranted;
}
private Collection<GrantedAuthority> getPrincipalAuthorities() {
Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
if (null == currentUser) {
return Collections.emptyList();
}
return currentUser.getAuthorities();
}
private Set<GrantedAuthority> parseAuthoritiesString(String authorizationsString) {
final Set<GrantedAuthority> requiredAuthorities = new HashSet<GrantedAuthority>();
requiredAuthorities.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList(authorizationsString));
return requiredAuthorities;
}
/**
* Find the common authorities between the current authentication's {@link GrantedAuthority} and the ones
* that have been specified in the tag's ifAny, ifNot or ifAllGranted attributes.<p>We need to manually
* iterate over both collections, because the granted authorities might not implement {@link
* Object#equals(Object)} and {@link Object#hashCode()} in the same way as {@link GrantedAuthorityImpl}, thereby
* invalidating {@link Collection#retainAll(java.util.Collection)} results.</p>
* <p>
* <strong>CAVEAT</strong>: This method <strong>will not</strong> work if the granted authorities
* returns a <code>null</code> string as the return value of {@link GrantedAuthority#getAuthority()}.
* </p>
*
* @param granted The authorities granted by the authentication. May be any implementation of {@link
* GrantedAuthority} that does <strong>not</strong> return <code>null</code> from {@link
* GrantedAuthority#getAuthority()}.
* @param required A {@link Set} of {@link GrantedAuthorityImpl}s that have been built using ifAny, ifAll or
* ifNotGranted.
*
* @return A set containing only the common authorities between <var>granted</var> and <var>required</var>.
*
*/
private Set<GrantedAuthority> retainAll(final Collection<GrantedAuthority> granted, final Set<GrantedAuthority> required) {
Set<String> grantedRoles = authoritiesToRoles(granted);
Set<String> requiredRoles = authoritiesToRoles(required);
grantedRoles.retainAll(requiredRoles);
return rolesToAuthorities(grantedRoles, granted);
}
private Set<GrantedAuthority> rolesToAuthorities(Set<String> grantedRoles, Collection<GrantedAuthority> granted) {
Set<GrantedAuthority> target = new HashSet<GrantedAuthority>();
for (String role : grantedRoles) {
for (GrantedAuthority authority : granted) {
if (authority.getAuthority().equals(role)) {
target.add(authority);
break;
}
}
}
return target;
}
public void setIfAllGranted(String ifAllGranted) throws JspException {
this.ifAllGranted = ifAllGranted;
}
public void setIfAnyGranted(String ifAnyGranted) throws JspException {
this.ifAnyGranted = ifAnyGranted;
}
public void setIfNotGranted(String ifNotGranted) throws JspException {
this.ifNotGranted = ifNotGranted;
}
}
| apache-2.0 |
AlbinTheander/MeQanTT | mqtt-library/src/test/java/org/meqantt/message/PingRespMessageTest.java | 1274 | /*******************************************************************************
* Copyright 2011 Albin Theander
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.meqantt.message;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.meqantt.message.PingRespMessage;
import org.meqantt.message.Message.Header;
public class PingRespMessageTest {
@Test
public void isDeserializedCorrectly() throws IOException {
Header header = new Header((byte) 0xD0);
InputStream in = new ByteArrayInputStream(new byte[] {0});
PingRespMessage msg = new PingRespMessage(header);
msg.read(in);
}
}
| apache-2.0 |
rmetzger/flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/StreamExecutionEnvironmentTest.java | 17023 | /*
* 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.flink.streaming.api;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.typeutils.GenericTypeInfo;
import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
import org.apache.flink.streaming.api.functions.source.FromElementsFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.source.StatefulSequenceSource;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator;
import org.apache.flink.streaming.api.operators.StreamOperator;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;
import org.apache.flink.util.SplittableIterator;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** Tests for {@link StreamExecutionEnvironment}. */
public class StreamExecutionEnvironmentTest {
@Test
public void fromElementsWithBaseTypeTest1() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.fromElements(ParentClass.class, new SubClass(1, "Java"), new ParentClass(1, "hello"));
}
@Test(expected = IllegalArgumentException.class)
public void fromElementsWithBaseTypeTest2() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.fromElements(SubClass.class, new SubClass(1, "Java"), new ParentClass(1, "hello"));
}
@Test
public void testFromElementsDeducedType() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<String> source = env.fromElements("a", "b");
FromElementsFunction<String> elementsFunction =
(FromElementsFunction<String>) getFunctionFromDataSource(source);
assertEquals(
BasicTypeInfo.STRING_TYPE_INFO.createSerializer(env.getConfig()),
elementsFunction.getSerializer());
}
@Test
public void testFromElementsPostConstructionType() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<String> source = env.fromElements("a", "b");
TypeInformation<String> customType = new GenericTypeInfo<>(String.class);
source.returns(customType);
FromElementsFunction<String> elementsFunction =
(FromElementsFunction<String>) getFunctionFromDataSource(source);
assertNotEquals(
BasicTypeInfo.STRING_TYPE_INFO.createSerializer(env.getConfig()),
elementsFunction.getSerializer());
assertEquals(
customType.createSerializer(env.getConfig()), elementsFunction.getSerializer());
}
@Test
@SuppressWarnings("unchecked")
public void testFromCollectionParallelism() {
try {
TypeInformation<Integer> typeInfo = BasicTypeInfo.INT_TYPE_INFO;
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<Integer> dataStream1 =
env.fromCollection(new DummySplittableIterator<Integer>(), typeInfo);
try {
dataStream1.setParallelism(4);
fail("should throw an exception");
} catch (IllegalArgumentException e) {
// expected
}
dataStream1.addSink(new DiscardingSink<Integer>());
DataStreamSource<Integer> dataStream2 =
env.fromParallelCollection(new DummySplittableIterator<Integer>(), typeInfo)
.setParallelism(4);
dataStream2.addSink(new DiscardingSink<Integer>());
final StreamGraph streamGraph = env.getStreamGraph();
streamGraph.getStreamingPlanAsJSON();
assertEquals(
"Parallelism of collection source must be 1.",
1,
streamGraph.getStreamNode(dataStream1.getId()).getParallelism());
assertEquals(
"Parallelism of parallel collection source must be 4.",
4,
streamGraph.getStreamNode(dataStream2.getId()).getParallelism());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testSources() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
SourceFunction<Integer> srcFun =
new SourceFunction<Integer>() {
private static final long serialVersionUID = 1L;
@Override
public void run(SourceContext<Integer> ctx) throws Exception {}
@Override
public void cancel() {}
};
DataStreamSource<Integer> src1 = env.addSource(srcFun);
src1.addSink(new DiscardingSink<Integer>());
assertEquals(srcFun, getFunctionFromDataSource(src1));
List<Long> list = Arrays.asList(0L, 1L, 2L);
DataStreamSource<Long> src2 = env.generateSequence(0, 2);
assertTrue(getFunctionFromDataSource(src2) instanceof StatefulSequenceSource);
DataStreamSource<Long> src3 = env.fromElements(0L, 1L, 2L);
assertTrue(getFunctionFromDataSource(src3) instanceof FromElementsFunction);
DataStreamSource<Long> src4 = env.fromCollection(list);
assertTrue(getFunctionFromDataSource(src4) instanceof FromElementsFunction);
}
/** Verifies that the API method doesn't throw and creates a source of the expected type. */
@Test
public void testFromSequence() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<Long> src = env.fromSequence(0, 2);
assertEquals(BasicTypeInfo.LONG_TYPE_INFO, src.getType());
}
@Test
public void testParallelismBounds() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
SourceFunction<Integer> srcFun =
new SourceFunction<Integer>() {
private static final long serialVersionUID = 1L;
@Override
public void run(SourceContext<Integer> ctx) throws Exception {}
@Override
public void cancel() {}
};
SingleOutputStreamOperator<Object> operator =
env.addSource(srcFun)
.flatMap(
new FlatMapFunction<Integer, Object>() {
private static final long serialVersionUID = 1L;
@Override
public void flatMap(Integer value, Collector<Object> out)
throws Exception {}
});
// default value for max parallelism
Assert.assertEquals(-1, operator.getTransformation().getMaxParallelism());
// bounds for parallelism 1
try {
operator.setParallelism(0);
Assert.fail();
} catch (IllegalArgumentException expected) {
}
// bounds for parallelism 2
operator.setParallelism(1);
Assert.assertEquals(1, operator.getParallelism());
// bounds for parallelism 3
operator.setParallelism(1 << 15);
Assert.assertEquals(1 << 15, operator.getParallelism());
// default value after generating
env.getStreamGraph(StreamExecutionEnvironment.DEFAULT_JOB_NAME, false).getJobGraph();
Assert.assertEquals(-1, operator.getTransformation().getMaxParallelism());
// configured value after generating
env.setMaxParallelism(42);
env.getStreamGraph(StreamExecutionEnvironment.DEFAULT_JOB_NAME, false).getJobGraph();
Assert.assertEquals(42, operator.getTransformation().getMaxParallelism());
// bounds configured parallelism 1
try {
env.setMaxParallelism(0);
Assert.fail();
} catch (IllegalArgumentException expected) {
}
// bounds configured parallelism 2
try {
env.setMaxParallelism(1 + (1 << 15));
Assert.fail();
} catch (IllegalArgumentException expected) {
}
// bounds for max parallelism 1
try {
operator.setMaxParallelism(0);
Assert.fail();
} catch (IllegalArgumentException expected) {
}
// bounds for max parallelism 2
try {
operator.setMaxParallelism(1 + (1 << 15));
Assert.fail();
} catch (IllegalArgumentException expected) {
}
// bounds for max parallelism 3
operator.setMaxParallelism(1);
Assert.assertEquals(1, operator.getTransformation().getMaxParallelism());
// bounds for max parallelism 4
operator.setMaxParallelism(1 << 15);
Assert.assertEquals(1 << 15, operator.getTransformation().getMaxParallelism());
// override config
env.getStreamGraph(StreamExecutionEnvironment.DEFAULT_JOB_NAME, false).getJobGraph();
Assert.assertEquals(1 << 15, operator.getTransformation().getMaxParallelism());
}
@Test
public void testGetStreamGraph() {
try {
TypeInformation<Integer> typeInfo = BasicTypeInfo.INT_TYPE_INFO;
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<Integer> dataStream1 =
env.fromCollection(new DummySplittableIterator<Integer>(), typeInfo);
dataStream1.addSink(new DiscardingSink<Integer>());
assertEquals(2, env.getStreamGraph().getStreamNodes().size());
DataStreamSource<Integer> dataStream2 =
env.fromCollection(new DummySplittableIterator<Integer>(), typeInfo);
dataStream2.addSink(new DiscardingSink<Integer>());
assertEquals(2, env.getStreamGraph().getStreamNodes().size());
DataStreamSource<Integer> dataStream3 =
env.fromCollection(new DummySplittableIterator<Integer>(), typeInfo);
dataStream3.addSink(new DiscardingSink<Integer>());
// Does not clear the transformations.
env.getExecutionPlan();
DataStreamSource<Integer> dataStream4 =
env.fromCollection(new DummySplittableIterator<Integer>(), typeInfo);
dataStream4.addSink(new DiscardingSink<Integer>());
assertEquals(4, env.getStreamGraph("TestJob").getStreamNodes().size());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testDefaultJobName() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
testJobName(StreamExecutionEnvironment.DEFAULT_JOB_NAME, env);
}
@Test
public void testUserDefinedJobName() {
String jobName = "MyTestJob";
Configuration config = new Configuration();
config.set(PipelineOptions.NAME, jobName);
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(config);
testJobName(jobName, env);
}
@Test
public void testUserDefinedJobNameWithConfigure() {
String jobName = "MyTestJob";
Configuration config = new Configuration();
config.set(PipelineOptions.NAME, jobName);
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.configure(config, this.getClass().getClassLoader());
testJobName(jobName, env);
}
private void testJobName(String expectedJobName, StreamExecutionEnvironment env) {
env.fromElements(1, 2, 3).print();
StreamGraph streamGraph = env.getStreamGraph();
assertEquals(expectedJobName, streamGraph.getJobName());
}
@Test
public void testAddSourceWithUserDefinedTypeInfo() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<Row> source1 =
env.addSource(new RowSourceFunction(), Types.ROW(Types.STRING));
// the source type information should be the user defined type
assertEquals(Types.ROW(Types.STRING), source1.getType());
DataStreamSource<Row> source2 = env.addSource(new RowSourceFunction());
// the source type information should be derived from RowSourceFunction#getProducedType
assertEquals(new GenericTypeInfo<>(Row.class), source2.getType());
}
/////////////////////////////////////////////////////////////
// Utilities
/////////////////////////////////////////////////////////////
private static StreamOperator<?> getOperatorFromDataStream(DataStream<?> dataStream) {
StreamExecutionEnvironment env = dataStream.getExecutionEnvironment();
StreamGraph streamGraph = env.getStreamGraph();
return streamGraph.getStreamNode(dataStream.getId()).getOperator();
}
@SuppressWarnings("unchecked")
private static <T> SourceFunction<T> getFunctionFromDataSource(
DataStreamSource<T> dataStreamSource) {
dataStreamSource.addSink(new DiscardingSink<T>());
AbstractUdfStreamOperator<?, ?> operator =
(AbstractUdfStreamOperator<?, ?>) getOperatorFromDataStream(dataStreamSource);
return (SourceFunction<T>) operator.getUserFunction();
}
private static class DummySplittableIterator<T> extends SplittableIterator<T> {
private static final long serialVersionUID = 1312752876092210499L;
@SuppressWarnings("unchecked")
@Override
public Iterator<T>[] split(int numPartitions) {
return (Iterator<T>[]) new Iterator<?>[0];
}
@Override
public int getMaximumNumberOfSplits() {
return 0;
}
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private static class ParentClass {
int num;
String string;
public ParentClass(int num, String string) {
this.num = num;
this.string = string;
}
}
private static class SubClass extends ParentClass {
public SubClass(int num, String string) {
super(num, string);
}
}
private static class RowSourceFunction
implements SourceFunction<Row>, ResultTypeQueryable<Row> {
private static final long serialVersionUID = 5216362688122691404L;
@Override
public TypeInformation<Row> getProducedType() {
return TypeInformation.of(Row.class);
}
@Override
public void run(SourceContext<Row> ctx) throws Exception {}
@Override
public void cancel() {}
}
}
| apache-2.0 |
daverix/zxing | android/src/com/google/zxing/client/android/encode/ContactEncoder.java | 3507 | /*
* Copyright (C) 2011 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.encode;
import android.telephony.PhoneNumberUtils;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
/**
* Implementations encode according to some scheme for encoding contact information, like VCard or
* MECARD.
*
* @author Sean Owen
*/
abstract class ContactEncoder {
/**
* @return first, the best effort encoding of all data in the appropriate format; second, a
* display-appropriate version of the contact information
*/
abstract String[] encode(List<String> names,
String organization,
List<String> addresses,
List<String> phones,
List<String> phoneTypes,
List<String> emails,
List<String> urls,
String note);
/**
* @return null if s is null or empty, or result of s.trim() otherwise
*/
static String trim(String s) {
if (s == null) {
return null;
}
String result = s.trim();
return result.isEmpty() ? null : result;
}
static void append(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
String value,
Formatter fieldFormatter,
char terminator) {
String trimmed = trim(value);
if (trimmed != null) {
newContents.append(prefix).append(fieldFormatter.format(trimmed, 0)).append(terminator);
newDisplayContents.append(trimmed).append('\n');
}
}
static void appendUpToUnique(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
List<String> values,
int max,
Formatter displayFormatter,
Formatter fieldFormatter,
char terminator) {
if (values == null) {
return;
}
int count = 0;
Collection<String> uniques = new HashSet<>(2);
for (int i = 0; i < values.size(); i++) {
String value = values.get(i);
String trimmed = trim(value);
if (trimmed != null && !trimmed.isEmpty() && !uniques.contains(trimmed)) {
newContents.append(prefix).append(fieldFormatter.format(trimmed, i)).append(terminator);
CharSequence display = displayFormatter == null ? trimmed : displayFormatter.format(trimmed, i);
newDisplayContents.append(display).append('\n');
if (++count == max) {
break;
}
uniques.add(trimmed);
}
}
}
static String formatPhone(String phoneData) {
// Just collect the call to a deprecated method in one place
return PhoneNumberUtils.formatNumber(phoneData);
}
}
| apache-2.0 |
KurtStam/fabric8-devops | git-collector/src/test/java/io/fabric8/collector/git/SearchDTOTest.java | 2484 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.collector.git;
import io.fabric8.collector.elasticsearch.SearchDTO;
import io.fabric8.collector.git.elasticsearch.Searches;
import io.fabric8.utils.cxf.JsonHelper;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
*/
public class SearchDTOTest {
@Test
public void testFirstMatchMaxValue() throws Exception {
String namespace = "default";
String app = "kubeflix";
String branch = "master";
boolean ascending = false;
SearchDTO search = Searches.createMinMaxGitCommitSearch(namespace, app, branch, ascending);
String json = JsonHelper.toJson(search);
System.out.println("Have created JSON: " + json);
assertEquals("{\n" +
" \"filter\" : {\n" +
" \"bool\" : {\n" +
" \"must\" : [ {\n" +
" \"term\" : {\n" +
" \"namespace\" : \"default\"\n" +
" }\n" +
" }, {\n" +
" \"term\" : {\n" +
" \"app\" : \"kubeflix\"\n" +
" }\n" +
" }, {\n" +
" \"term\" : {\n" +
" \"branch\" : \"master\"\n" +
" }\n" +
" } ]\n" +
" }\n" +
" },\n" +
" \"sort\" : [ {\n" +
" \"commit_time\" : {\n" +
" \"order\" : \"desc\"\n" +
" }\n" +
" } ],\n" +
" \"size\" : 1\n" +
"}", json);
}
}
| apache-2.0 |
CC4401-TeraCity/TeraCity | engine/src/main/java/org/terasology/logic/players/PlayerFactory.java | 2605 | /*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.logic.players;
import org.terasology.entitySystem.entity.EntityBuilder;
import org.terasology.entitySystem.entity.EntityManager;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.logic.characters.CharacterComponent;
import org.terasology.logic.inventory.InventoryUtils;
import org.terasology.logic.location.LocationComponent;
import org.terasology.logic.players.event.SelectedItemChangedEvent;
import org.terasology.math.geom.Vector3f;
import org.terasology.network.ClientComponent;
import org.terasology.network.ColorComponent;
import org.terasology.rendering.logic.MeshComponent;
/**
* @author Immortius
*/
public class PlayerFactory {
private EntityManager entityManager;
public PlayerFactory(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityRef newInstance(Vector3f spawnPosition, EntityRef controller) {
EntityBuilder builder = entityManager.newBuilder("engine:player");
builder.getComponent(LocationComponent.class).setWorldPosition(spawnPosition);
builder.setOwner(controller);
EntityRef transferSlot = entityManager.create("engine:transferSlot");
ClientComponent clientComp = controller.getComponent(ClientComponent.class);
if (clientComp != null) {
ColorComponent colorComp = clientComp.clientInfo.getComponent(ColorComponent.class);
MeshComponent meshComp = builder.getComponent(MeshComponent.class);
meshComp.color = colorComp.color;
}
CharacterComponent playerComponent = builder.getComponent(CharacterComponent.class);
playerComponent.spawnPosition.set(spawnPosition);
playerComponent.movingItem = transferSlot;
playerComponent.controller = controller;
EntityRef player = builder.build();
player.send(new SelectedItemChangedEvent(EntityRef.NULL, InventoryUtils.getItemAt(player, 0)));
return player;
}
}
| apache-2.0 |
treason258/TreBundle | lib_TreCore/src/main/java/com/mjiayou/trecore/util/ViewUtil.java | 7440 | package com.mjiayou.trecore.util;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mjiayou.trecore.R;
import com.mjiayou.trecore.bean.entity.TCRect;
import com.mjiayou.trecore.common.Caches;
import com.mjiayou.trecorelib.util.LogUtil;
/**
* Created by treason on 15/11/15.
*/
public class ViewUtil {
public static final String TAG = "ViewUtil";
public static final int NONE_SIZE = Integer.MIN_VALUE;
/**
* OnGetViewWidthAndHeightListener
*/
public interface OnGetViewWidthAndHeightListener {
void onGet(int width, int height);
}
/**
* 重新设置view的宽高大小
*/
public static void resize(View view, int width, int height) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
// LogUtil.i(TAG, "width -> " + width + ";height -> " + height);
}
/**
* 重新设置Banner的宽高 HomeFragment、VideoRecommendFragment、EquipRecommendFragment
*/
public static void resizeBanner(Context context, View view) {
// 设置图片展示宽高-585*287/640
// float edge = context.getResources().getDimension(R.dimen.item_home_card_margin_right) +
// context.getResources().getDimension(R.dimen.item_home_card_margin_left) +
// context.getResources().getDimension(R.dimen.item_home_image_padding) * 2;
float edge = 0;
int width = Caches.get().getScreenWidth();
int height = (int) ((width - edge) * 287.0f / 585.0f);
resize(view, width, height);
}
public static void resizeHomeNew(Context context, View view) {
float edge = context.getResources().getDimension(R.dimen.tc_margin_mini_2) * 2 +
context.getResources().getDimension(R.dimen.tc_margin_mini_2) * 3 * 2;
int width = (int) ((Caches.get().getScreenWidth() - edge) / 3);
int height = width;
resize(view, width, height);
}
public static void resizeHomeHot(Context context, View view) {
float edge = 0;
int width = (int) (Caches.get().getScreenWidth() - edge);
int height = width;
resize(view, width, height);
}
/**
* 获取无数据时的页面
*/
public static View getEmptyView(Context context, String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tc_layout_status_empty, null);
ImageView ivHint = (ImageView) view.findViewById(R.id.iv_hint);
TextView tvMessage = (TextView) view.findViewById(R.id.tv_message);
TextView tvButton = (TextView) view.findViewById(R.id.tv_button);
tvMessage.setText(text);
return view;
}
public static View getEmptyView(Context context) {
return getEmptyView(context, "暂无数据");
}
/**
* 设置空间的高度和宽度
*/
public static void setWidthAndHeight(View view, int width, int height) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
if (width != NONE_SIZE) {
layoutParams.width = width;
}
if (height != NONE_SIZE) {
layoutParams.height = height;
}
view.setLayoutParams(layoutParams);
}
public static void setWidthAndHeightOld(View view, int width, int height) {
ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginLayoutParams);
if (width != NONE_SIZE) {
layoutParams.width = width;
}
if (height != NONE_SIZE) {
layoutParams.height = height;
}
view.setLayoutParams(layoutParams);
}
/**
* 获取控件的高度和宽度,自己测量
*/
public static TCRect getWidthAndHeight(final View view) {
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
TCRect tcRect = new TCRect();
tcRect.setWidth(view.getMeasuredWidth());
tcRect.setHeight(view.getMeasuredHeight());
return tcRect;
}
public static void getWidthAndHeight(final View view, final OnGetViewWidthAndHeightListener onGetViewWidthAndHeightListener) {
final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
onGetViewWidthAndHeightListener.onGet(view.getMeasuredWidth(), view.getMeasuredHeight());
}
});
}
public static void getWidthAndHeightOld(final View view, final OnGetViewWidthAndHeightListener onGetViewWidthAndHeightListener) {
final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
view.getViewTreeObserver().removeOnPreDrawListener(this);
onGetViewWidthAndHeightListener.onGet(view.getMeasuredWidth(), view.getMeasuredHeight());
return true;
}
});
}
/**
* printMotionEvent
*/
public static void printMotionEvent(MotionEvent event, String viewStr, String method) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
LogUtil.i(TAG, viewStr + " | " + method + " | action ACTION_DOWN");
break;
case MotionEvent.ACTION_UP:
LogUtil.i(TAG, viewStr + " | " + method + " | action ACTION_UP");
break;
case MotionEvent.ACTION_MOVE:
LogUtil.i(TAG, viewStr + " | " + method + " | action ACTION_MOVE");
break;
case MotionEvent.ACTION_CANCEL:
LogUtil.i(TAG, viewStr + " | " + method + " | action ACTION_CANCEL");
break;
default:
LogUtil.i(TAG, viewStr + " | " + method + " | action " + event.getAction());
break;
}
}
/**
* printEvent
*/
public static void printEvent(String viewStr, String method) {
LogUtil.i(TAG, viewStr + " | " + method);
}
/**
* 设置显示或者隐藏
*/
public static void setVisibility(View view, boolean visible) {
if (view == null) {
LogUtil.i("view == null");
return;
}
view.setVisibility(visible ? View.VISIBLE : View.GONE);
}
/**
* 设置点击监听
*/
public static void setOnClickListener(View view, View.OnClickListener listener) {
if (view == null) {
LogUtil.i("view == null");
return;
}
view.setOnClickListener(listener);
}
}
| apache-2.0 |
yanzhijun/jclouds-aliyun | blobstore/src/main/java/org/jclouds/blobstore/KeyNotFoundException.java | 1554 | /*
* 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.jclouds.blobstore;
import org.jclouds.rest.ResourceNotFoundException;
/**
* Thrown when a blob cannot be located in the container.
*/
public class KeyNotFoundException extends ResourceNotFoundException {
private String container;
private String key;
public KeyNotFoundException() {
super();
}
public KeyNotFoundException(String container, String key, String message) {
super(String.format("%s not found in container %s: %s", key, container, message));
this.container = container;
this.key = key;
}
public KeyNotFoundException(Throwable from) {
super(from);
}
public String getContainer() {
return container;
}
public String getKey() {
return key;
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/DescribeEventSubscriptionsRequest.java | 13417 | /*
* Copyright 2010-2016 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.services.redshift.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p/>
*/
public class DescribeEventSubscriptionsRequest extends AmazonWebServiceRequest
implements Serializable, Cloneable {
/**
* <p>
* The name of the Amazon Redshift event notification subscription to be
* described.
* </p>
*/
private String subscriptionName;
/**
* <p>
* The maximum number of response records to return in each call. If the
* number of remaining response records exceeds the specified
* <code>MaxRecords</code> value, a value is returned in a
* <code>marker</code> field of the response. You can retrieve the next set
* of records by retrying the command with the returned marker value.
* </p>
* <p>
* Default: <code>100</code>
* </p>
* <p>
* Constraints: minimum 20, maximum 100.
* </p>
*/
private Integer maxRecords;
/**
* <p>
* An optional parameter that specifies the starting point to return a set
* of response records. When the results of a
* <a>DescribeEventSubscriptions</a> request exceed the value specified in
* <code>MaxRecords</code>, AWS returns a value in the <code>Marker</code>
* field of the response. You can retrieve the next set of response records
* by providing the returned marker value in the <code>Marker</code>
* parameter and retrying the request.
* </p>
*/
private String marker;
/**
* <p>
* The name of the Amazon Redshift event notification subscription to be
* described.
* </p>
*
* @param subscriptionName
* The name of the Amazon Redshift event notification subscription to
* be described.
*/
public void setSubscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
}
/**
* <p>
* The name of the Amazon Redshift event notification subscription to be
* described.
* </p>
*
* @return The name of the Amazon Redshift event notification subscription
* to be described.
*/
public String getSubscriptionName() {
return this.subscriptionName;
}
/**
* <p>
* The name of the Amazon Redshift event notification subscription to be
* described.
* </p>
*
* @param subscriptionName
* The name of the Amazon Redshift event notification subscription to
* be described.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeEventSubscriptionsRequest withSubscriptionName(
String subscriptionName) {
setSubscriptionName(subscriptionName);
return this;
}
/**
* <p>
* The maximum number of response records to return in each call. If the
* number of remaining response records exceeds the specified
* <code>MaxRecords</code> value, a value is returned in a
* <code>marker</code> field of the response. You can retrieve the next set
* of records by retrying the command with the returned marker value.
* </p>
* <p>
* Default: <code>100</code>
* </p>
* <p>
* Constraints: minimum 20, maximum 100.
* </p>
*
* @param maxRecords
* The maximum number of response records to return in each call. If
* the number of remaining response records exceeds the specified
* <code>MaxRecords</code> value, a value is returned in a
* <code>marker</code> field of the response. You can retrieve the
* next set of records by retrying the command with the returned
* marker value. </p>
* <p>
* Default: <code>100</code>
* </p>
* <p>
* Constraints: minimum 20, maximum 100.
*/
public void setMaxRecords(Integer maxRecords) {
this.maxRecords = maxRecords;
}
/**
* <p>
* The maximum number of response records to return in each call. If the
* number of remaining response records exceeds the specified
* <code>MaxRecords</code> value, a value is returned in a
* <code>marker</code> field of the response. You can retrieve the next set
* of records by retrying the command with the returned marker value.
* </p>
* <p>
* Default: <code>100</code>
* </p>
* <p>
* Constraints: minimum 20, maximum 100.
* </p>
*
* @return The maximum number of response records to return in each call. If
* the number of remaining response records exceeds the specified
* <code>MaxRecords</code> value, a value is returned in a
* <code>marker</code> field of the response. You can retrieve the
* next set of records by retrying the command with the returned
* marker value. </p>
* <p>
* Default: <code>100</code>
* </p>
* <p>
* Constraints: minimum 20, maximum 100.
*/
public Integer getMaxRecords() {
return this.maxRecords;
}
/**
* <p>
* The maximum number of response records to return in each call. If the
* number of remaining response records exceeds the specified
* <code>MaxRecords</code> value, a value is returned in a
* <code>marker</code> field of the response. You can retrieve the next set
* of records by retrying the command with the returned marker value.
* </p>
* <p>
* Default: <code>100</code>
* </p>
* <p>
* Constraints: minimum 20, maximum 100.
* </p>
*
* @param maxRecords
* The maximum number of response records to return in each call. If
* the number of remaining response records exceeds the specified
* <code>MaxRecords</code> value, a value is returned in a
* <code>marker</code> field of the response. You can retrieve the
* next set of records by retrying the command with the returned
* marker value. </p>
* <p>
* Default: <code>100</code>
* </p>
* <p>
* Constraints: minimum 20, maximum 100.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeEventSubscriptionsRequest withMaxRecords(Integer maxRecords) {
setMaxRecords(maxRecords);
return this;
}
/**
* <p>
* An optional parameter that specifies the starting point to return a set
* of response records. When the results of a
* <a>DescribeEventSubscriptions</a> request exceed the value specified in
* <code>MaxRecords</code>, AWS returns a value in the <code>Marker</code>
* field of the response. You can retrieve the next set of response records
* by providing the returned marker value in the <code>Marker</code>
* parameter and retrying the request.
* </p>
*
* @param marker
* An optional parameter that specifies the starting point to return
* a set of response records. When the results of a
* <a>DescribeEventSubscriptions</a> request exceed the value
* specified in <code>MaxRecords</code>, AWS returns a value in the
* <code>Marker</code> field of the response. You can retrieve the
* next set of response records by providing the returned marker
* value in the <code>Marker</code> parameter and retrying the
* request.
*/
public void setMarker(String marker) {
this.marker = marker;
}
/**
* <p>
* An optional parameter that specifies the starting point to return a set
* of response records. When the results of a
* <a>DescribeEventSubscriptions</a> request exceed the value specified in
* <code>MaxRecords</code>, AWS returns a value in the <code>Marker</code>
* field of the response. You can retrieve the next set of response records
* by providing the returned marker value in the <code>Marker</code>
* parameter and retrying the request.
* </p>
*
* @return An optional parameter that specifies the starting point to return
* a set of response records. When the results of a
* <a>DescribeEventSubscriptions</a> request exceed the value
* specified in <code>MaxRecords</code>, AWS returns a value in the
* <code>Marker</code> field of the response. You can retrieve the
* next set of response records by providing the returned marker
* value in the <code>Marker</code> parameter and retrying the
* request.
*/
public String getMarker() {
return this.marker;
}
/**
* <p>
* An optional parameter that specifies the starting point to return a set
* of response records. When the results of a
* <a>DescribeEventSubscriptions</a> request exceed the value specified in
* <code>MaxRecords</code>, AWS returns a value in the <code>Marker</code>
* field of the response. You can retrieve the next set of response records
* by providing the returned marker value in the <code>Marker</code>
* parameter and retrying the request.
* </p>
*
* @param marker
* An optional parameter that specifies the starting point to return
* a set of response records. When the results of a
* <a>DescribeEventSubscriptions</a> request exceed the value
* specified in <code>MaxRecords</code>, AWS returns a value in the
* <code>Marker</code> field of the response. You can retrieve the
* next set of response records by providing the returned marker
* value in the <code>Marker</code> parameter and retrying the
* request.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeEventSubscriptionsRequest withMarker(String marker) {
setMarker(marker);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSubscriptionName() != null)
sb.append("SubscriptionName: " + getSubscriptionName() + ",");
if (getMaxRecords() != null)
sb.append("MaxRecords: " + getMaxRecords() + ",");
if (getMarker() != null)
sb.append("Marker: " + getMarker());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeEventSubscriptionsRequest == false)
return false;
DescribeEventSubscriptionsRequest other = (DescribeEventSubscriptionsRequest) obj;
if (other.getSubscriptionName() == null
^ this.getSubscriptionName() == null)
return false;
if (other.getSubscriptionName() != null
&& other.getSubscriptionName().equals(
this.getSubscriptionName()) == false)
return false;
if (other.getMaxRecords() == null ^ this.getMaxRecords() == null)
return false;
if (other.getMaxRecords() != null
&& other.getMaxRecords().equals(this.getMaxRecords()) == false)
return false;
if (other.getMarker() == null ^ this.getMarker() == null)
return false;
if (other.getMarker() != null
&& other.getMarker().equals(this.getMarker()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getSubscriptionName() == null) ? 0 : getSubscriptionName()
.hashCode());
hashCode = prime * hashCode
+ ((getMaxRecords() == null) ? 0 : getMaxRecords().hashCode());
hashCode = prime * hashCode
+ ((getMarker() == null) ? 0 : getMarker().hashCode());
return hashCode;
}
@Override
public DescribeEventSubscriptionsRequest clone() {
return (DescribeEventSubscriptionsRequest) super.clone();
}
} | apache-2.0 |
kohsah/akomantoso-lib | src/main/java/org/akomantoso/schema/v3/csd13/Quantity.java | 1810 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.16 at 12:57:08 PM IST
//
package org.akomantoso.schema.v3.csd13;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13}inlinereqreq">
* <attribute name="normalized" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "quantity")
public class Quantity
extends Inlinereqreq
{
@XmlAttribute(name = "normalized")
protected String normalized;
/**
* Gets the value of the normalized property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNormalized() {
return normalized;
}
/**
* Sets the value of the normalized property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNormalized(String value) {
this.normalized = value;
}
}
| apache-2.0 |
marqh/def.scitools | src/main/java/com/epimorphics/registry/core/RegisterItem.java | 16894 | /******************************************************************
* File: RegisterItem.java
* Created by: Dave Reynolds
* Created on: 23 Jan 2013
*
* (c) Copyright 2013, Epimorphics Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************/
package com.epimorphics.registry.core;
import java.util.Calendar;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import com.epimorphics.rdfutil.RDFUtil;
import com.epimorphics.registry.store.StoreAPI;
import com.epimorphics.registry.vocab.RegistryVocab;
import com.epimorphics.server.webapi.WebApiException;
import com.epimorphics.vocabs.SKOS;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.sparql.util.Closure;
import com.hp.hpl.jena.util.ResourceUtils;
import com.hp.hpl.jena.vocabulary.DCTerms;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
/**
* Abstraction for creation and access to the details of a register item plus its entity.
*
* The entity, if present, should be kept in a separate graph so that it can be stored
* independently of the item without making any assumptions like CBD.
*
* @author <a href="mailto:dave@epimorphics.com">Dave Reynolds</a>
*/
public class RegisterItem extends Description {
Resource entity;
String notation;
String parentURI;
boolean entityAsGraph = false;
/** Properties that should not be changed once set */
public static final Property[] RIGID_PROPS = new Property[] {
RegistryVocab.register, RegistryVocab.notation,
RegistryVocab.itemClass, RegistryVocab.predecessor,
RegistryVocab.submitter, RDF.type,
DCTerms.dateSubmitted, OWL.versionInfo};
/** Properties that must be present so cannot be removed but may be updated */
public static final Property[] REQUIRED_PROPS = new Property[] {RegistryVocab.status, RDFS.label};
/** Properties that are set internally and should not be set by register/update payload */
public static final Property[] INTERNAL_PROPS = new Property[] {RegistryVocab.register, RegistryVocab.subregister, OWL.versionInfo};
/**
* Construct a new register item from a loaded description
*/
public RegisterItem(Resource root) {
super(root);
}
/**
* Construct a register item from a description
* @param root the item resource in a model that can be modified
* @param parentURI the URI of the target register in which the registration is taking place
*/
private RegisterItem(Resource root, String parentURI) {
super(root);
this.parentURI = parentURI;
}
/**
* Construct a register item from a description
* @param root the item resource in a model that can be modified
* @param parentURI the URI of the target register in which the registration is taking place
* @param notation the local name of the item within the parent register
*/
private RegisterItem(Resource root, String parentURI, String notation) {
super(root);
this.parentURI = parentURI;
this.notation = notation;
}
/**
* Record the address of an associated entity.
* Should be in a separate model to allowed to be saved on its own.
* Does NOT create reg:definition/reg:entity links.
*/
public void setEntity(Resource entity) {
this.entity = entity;
}
/**
* Flag that the entity should stored as a whole graph, not as a simple closure
*/
public void setAsGraph(boolean asGraph) {
this.entityAsGraph = asGraph;
}
/**
* Test if the entity should stored as a whole graph, not as a simple closure
*/
public boolean isGraph() {
return entityAsGraph;
}
public String getNotation() {
if (notation == null) {
determineLocation();
}
return notation;
}
/**
* Return the associated entity resource, if any. A RegisterItem can be created
* or retrieved without also setting the entity so this may return null in those cases.
*/
public Resource getEntity() {
return entity;
}
/**
* Return the entity specified by reg:definition/reg:entity.
* For a well-formed RegisterItem this should never return null, even
* if the entity itself hasn't been retrieved and attached to this wrapper object.
*/
public Resource getEntitySpec() {
Resource def = root.getPropertyResourceValue(RegistryVocab.definition);
if (def != null) {
return def.getPropertyResourceValue(RegistryVocab.entity);
} else {
return null;
}
}
public Status getStatus() {
return Status.forResource( root.getPropertyResourceValue(RegistryVocab.status) );
}
public String getRegisterURI() {
if (parentURI == null) {
Resource reg = root.getPropertyResourceValue(RegistryVocab.register);
if (reg != null) {
parentURI = reg.getURI();
}
}
return parentURI;
}
public boolean isRegister() {
return root.hasProperty(RegistryVocab.itemClass, RegistryVocab.Register);
}
public Register getAsRegister(StoreAPI store) {
return Description.descriptionFrom( store.getEntity(this), store ).asRegister();
}
/**
* Takes a register item resource from a request payload, determines and checks
* the intended URI for both it and the entity, fills in blanks on the register item,
* returns the constructed item representation.
*/
public static RegisterItem fromRIRequest(Resource ri, String parentURI, boolean isNewSubmission) {
return fromRIRequest(ri, parentURI, isNewSubmission, Calendar.getInstance());
}
public static RegisterItem fromRIRequest(Resource ri, String parentURI, boolean isNewSubmission, Calendar now) {
Model d = Closure.closure(ri, false);
Resource entity = findRequiredEntity(ri);
RegisterItem item = new RegisterItem( ri.inModel(d), parentURI );
item.relocate();
if (entity != null) {
entity = entity.inModel( Closure.closure(entity, false) );
// item.relocateEntity(entity);
item.setEntity(entity); // Don't relocate in this case, so that bNode reservations are preserved
item.updateForEntity(isNewSubmission, now);
}
return item;
}
/**
* Constructs a RegisterIem for an entity in a request payload that doesn't have
* any explict RegisterItem specification.
*/
public static RegisterItem fromEntityRequest(Resource e, String parentURI, boolean isNewSubmission) {
return fromEntityRequest(e, parentURI, isNewSubmission, Calendar.getInstance());
}
public static RegisterItem fromEntityRequest(Resource e, String parentURI, boolean isNewSubmission, Calendar now) {
String notation = notationFromEntity(e, parentURI);
String riURI = makeItemURI(parentURI, notation);
Resource ri = ModelFactory.createDefaultModel().createResource(riURI)
.addProperty(RDF.type, RegistryVocab.RegisterItem);
try {
int notationInt = Integer.parseInt(notation);
ri.addLiteral(RegistryVocab.notation, notationInt);
} catch (NumberFormatException ex) {
ri.addProperty(RegistryVocab.notation, notation);
}
RegisterItem item = new RegisterItem( ri, parentURI, notation );
Resource entity = e;
item.relocateEntity(entity);
item.updateForEntity(isNewSubmission, now);
return item;
}
/**
* Set the status of the item
*/
public Resource setStatus(String status) {
return setStatus( Status.forString(status, null) );
}
/**
* Set the status of the item, bypassing lifecycle checks
*/
public Resource forceStatus(String status) {
return forceStatus( Status.forString(status, null) );
}
/**
* Set the status of the item, by passing lifecycle check
*/
public Resource forceStatus(Status s) {
if (s != null) {
return setStatus( s.getResource() );
}
return null;
}
/**
* Set the status of the item
*/
public Resource setStatus(Status s) {
if (s != null) {
if (!getStatus().legalNextState(s)) {
return null;
}
return setStatus( s.getResource() );
}
return null;
}
private Resource setStatus(Resource status) {
root.removeAll(RegistryVocab.status);
root.addProperty(RegistryVocab.status, status);
return status;
}
/**
* If the entity is a bNode then skolemize it
*/
public void skolemize() {
if (entity != null && entity.isAnon()) {
String skolemURI = Registry.get().baseURI + "/.well-known/skolem/" + entity.getId();
ResourceUtils.renameResource(entity, skolemURI);
entity = entity.getModel().createResource( skolemURI );
}
}
/**
* Flatten versioning information for the register item and, if present, the entity
*/
public RegisterItem flatten() {
doFlatten(root);
if (entity != null) {
doFlatten(entity);
}
return this;
}
// ----------- internal helpers for sorting out the different notation cases ---------------------------
private void relocate() {
String uri = makeItemURI(parentURI, getNotation());
if ( ! uri.equals(root.getURI()) ) {
ResourceUtils.renameResource(root, uri);
}
root = root.getModel().createResource(uri);
}
private void relocateEntity(Resource srcEntity) {
String uri = entityURI(srcEntity);
if ( ! uri.equals(srcEntity.getURI()) ) {
ResourceUtils.renameResource(srcEntity, uri);
entity = srcEntity.getModel().createResource(uri);
} else {
entity = srcEntity;
}
}
/**
* Update a register item to reflect the current state of the entity
*/
public void updateForEntity(boolean isNewSubmission, Calendar time) {
if (isNewSubmission) {
root.removeAll(DCTerms.dateSubmitted);
root.addProperty(DCTerms.dateSubmitted, root.getModel().createTypedLiteral(time));
} else {
root.removeAll(DCTerms.modified);
root.addProperty(DCTerms.modified, root.getModel().createTypedLiteral(time));
}
if ( !root.hasProperty(RegistryVocab.status) && isNewSubmission) {
root.addProperty(RegistryVocab.status, RegistryVocab.statusSubmitted);
}
if (!root.hasProperty(RegistryVocab.notation)) {
root.addProperty(RegistryVocab.notation, notation);
}
root.removeAll(RDFS.label)
.removeAll(DCTerms.description)
.removeAll(RegistryVocab.itemClass);
if (entity.hasProperty(SKOS.prefLabel)) {
RDFUtil.copyProperty(entity, root, SKOS.prefLabel, RDFS.label);
} else if (entity.hasProperty(SKOS.altLabel)) {
RDFUtil.copyProperty(entity, root, SKOS.altLabel, RDFS.label);
} else {
RDFUtil.copyProperty(entity, root, RDFS.label);
}
RDFUtil.copyProperty(entity, root, DCTerms.description);
for (Statement s : entity.listProperties(RDF.type).toList()) {
root.addProperty(RegistryVocab.itemClass, s.getObject());
}
// Omit entity reference link itself, this will be created per-version when added to store
}
public String getEntityRefURI() {
return root.getURI() + "#entityref";
}
private void determineLocation() {
notation = getExplicitNotation(root);
// Presumably a item under construction from a web request
if (notation == null && root.isURIResource()) {
String uri = root.getURI();
if (parentURI != null && uri.startsWith(parentURI)) {
notation = validateNotation( uri.substring(parentURI.length() + 1) );
} else {
// Register Item has explicit URI which is not relative to the target parent register
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
}
if (notation == null) {
notation = UUID.randomUUID().toString();
} else if ( ! LEGAL_NOTATION.matcher(notation).matches() ) {
throw new WebApiException(Response.Status.BAD_REQUEST, "Proposed notation for item is not a legal pchar or starts with '_' - " + notation);
}
}
// static final Pattern LEGAL_NOTATION = Pattern.compile("^[a-zA-Z0-9][\\w\\.\\-~%@=!&'()*+,;=]*$");
static final Pattern LEGAL_NOTATION = Pattern.compile("^[a-zA-Z0-9\\.\\-~%@=!&'()*+,;=][\\w\\.\\-~%@=!&'()*+,;=]*$");
private static String getExplicitNotation(Resource root) {
if (root.hasProperty(RegistryVocab.notation)) {
String location = RDFUtil.getStringValue(root, RegistryVocab.notation);
if (location.startsWith("_")) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
return location;
}
return null;
}
private static String validateNotation(String notation) {
if (notation.startsWith("_")) {
return notation.substring(1);
} else {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
public static String notationFromEntity(Resource entity, String parentURI) {
String uri = entity.getURI();
String notation = null;
if (entity.isAnon()) {
notation = UUID.randomUUID().toString();
} else if (uri.startsWith(parentURI)) {
notation = uri.substring(parentURI.length() + 1);
} else {
// Absolute URI, just use it and create anotation for the item
notation = UUID.randomUUID().toString();
}
if ( ! LEGAL_NOTATION.matcher(notation).matches() ) {
throw new WebApiException(Response.Status.BAD_REQUEST, "Proposed notation for item is not a legal pchar or starts with '_' - " + notation);
}
return notation;
}
private String entityURI(Resource entity) {
String uri = entity.getURI();
if (entity.isAnon()) {
uri = makeEntityURI();
} else if (uri.startsWith(parentURI)) {
String eNotation = uri.substring(parentURI.length() + 1);
if (!eNotation.equals(notation)) {
throw new WebApiException(Response.Status.BAD_REQUEST, "Entity path doesn't match its notation");
}
uri = makeEntityURI();
}
return uri;
}
private String makeEntityURI() {
return makeEntityURI(parentURI, notation);
}
private static String makeEntityURI(String parentURI, String notation) {
return baseParentURI(parentURI) + "/" + notation;
}
private static String makeItemURI(String parentURI, String notation) {
return baseParentURI(parentURI) + "/_" + notation;
}
private static String baseParentURI(String parentURI){
if (parentURI.endsWith("/")) {
return parentURI.substring(0, parentURI.length() - 1);
} else {
return parentURI;
}
}
private static Resource findRequiredEntity(Resource ri) {
Resource definition = ri.getPropertyResourceValue(RegistryVocab.definition);
if (definition != null) {
Resource entity = definition.getPropertyResourceValue(RegistryVocab.entity);
return entity;
}
return null;
}
@Override
public String toString() {
return String.format("RegisterItem %s (entity=%s)", root, entity);
}
}
| apache-2.0 |
withletters/jodconverter | src/main/java/org/artofsolving/jodconverter/office/OfficeManager.java | 880 | //
// JODConverter - Java OpenDocument Converter
// Copyright 2004-2012 Mirko Nasato and contributors
//
// JODConverter is Open Source software, you can redistribute it and/or
// modify it under either (at your option) of the following licenses
//
// 1. The GNU Lesser General Public License v3 (or later)
// -> http://www.gnu.org/licenses/lgpl-3.0.txt
// 2. The Apache License, Version 2.0
// -> http://www.apache.org/licenses/LICENSE-2.0.txt
//
package org.artofsolving.jodconverter.office;
/**
* An OfficeManager knows how to execute {@link OfficeTask}s.
* <p>
* An OfficeManager implementation will typically manage one or more
* {@link OfficeConnection}s.
*/
public interface OfficeManager {
void execute(OfficeTask task) throws OfficeException;
void start() throws OfficeException;
void stop() throws OfficeException;
boolean isRunning();
}
| apache-2.0 |
00wendi00/MyProject | W_myeclipse/binary/com.sun.java.jdk.win32.x86_1.6.0.013/demo/plugin/jfc/SampleTree/src/DynamicTreeNode.java | 6890 | /*
* @(#)DynamicTreeNode.java 1.13 05/11/17
*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* @(#)DynamicTreeNode.java 1.13 05/11/17
*/
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.util.Random;
/**
* DynamicTreeNode illustrates one of the possible ways in which dynamic
* loading can be used in tree. The basic premise behind this is that
* getChildCount() will be messaged from JTreeModel before any children
* are asked for. So, the first time getChildCount() is issued the
* children are loaded.<p>
* It should be noted that isLeaf will also be messaged from the model.
* The default behavior of TreeNode is to message getChildCount to
* determine this. As such, isLeaf is subclassed to always return false.<p>
* There are others ways this could be accomplished as well. Instead of
* subclassing TreeNode you could subclass JTreeModel and do the same
* thing in getChildCount(). Or, if you aren't using TreeNode you could
* write your own TreeModel implementation.
* Another solution would be to listen for TreeNodeExpansion events and
* the first time a node has been expanded post the appropriate insertion
* events. I would not recommend this approach though, the other two
* are much simpler and cleaner (and are faster from the perspective of
* how tree deals with it).
*
* NOTE: getAllowsChildren() can be messaged before getChildCount().
* For this example the nodes always allow children, so it isn't
* a problem, but if you do support true leaf nodes you may want
* to check for loading in getAllowsChildren too.
*
* @version 1.13 11/17/05
* @author Scott Violet
*/
public class DynamicTreeNode extends DefaultMutableTreeNode
{
// Class stuff.
/** Number of names. */
static protected float nameCount;
/** Names to use for children. */
static protected String[] names;
/** Potential fonts used to draw with. */
static protected Font[] fonts;
/** Used to generate the names. */
static protected Random nameGen;
/** Number of children to create for each node. */
static protected final int DefaultChildrenCount = 7;
static {
String[] fontNames;
try {
fontNames = Toolkit.getDefaultToolkit().getFontList();
} catch (Exception e) {
fontNames = null;
}
if(fontNames == null || fontNames.length == 0) {
names = new String[] {"Mark Andrews", "Tom Ball", "Alan Chung",
"Rob Davis", "Jeff Dinkins",
"Amy Fowler", "James Gosling",
"David Karlton", "Dave Kloba",
"Dave Moore", "Hans Muller",
"Rick Levenson", "Tim Prinzing",
"Chester Rose", "Ray Ryan",
"Georges Saab", "Scott Violet",
"Kathy Walrath", "Arnaud Weber" };
}
else {
/* Create the Fonts, creating fonts is slow, much better to
do it once. */
int fontSize = 12;
names = fontNames;
fonts = new Font[names.length];
for(int counter = 0, maxCounter = names.length;
counter < maxCounter; counter++) {
try {
fonts[counter] = new Font(fontNames[counter], 0, fontSize);
}
catch (Exception e) {
fonts[counter] = null;
}
fontSize = ((fontSize + 2 - 12) % 12) + 12;
}
}
nameCount = (float)names.length;
nameGen = new Random(System.currentTimeMillis());
}
/** Have the children of this node been loaded yet? */
protected boolean hasLoaded;
/**
* Constructs a new DynamicTreeNode instance with o as the user
* object.
*/
public DynamicTreeNode(Object o) {
super(o);
}
public boolean isLeaf() {
return false;
}
/**
* If hasLoaded is false, meaning the children have not yet been
* loaded, loadChildren is messaged and super is messaged for
* the return value.
*/
public int getChildCount() {
if(!hasLoaded) {
loadChildren();
}
return super.getChildCount();
}
/**
* Messaged the first time getChildCount is messaged. Creates
* children with random names from names.
*/
protected void loadChildren() {
DynamicTreeNode newNode;
Font font;
int randomIndex;
SampleData data;
for(int counter = 0; counter < DynamicTreeNode.DefaultChildrenCount;
counter++) {
randomIndex = (int)(nameGen.nextFloat() * nameCount);
if(fonts != null)
font = fonts[randomIndex];
else
font = null;
if(counter % 2 == 0)
data = new SampleData(font, Color.red, names[randomIndex]);
else
data = new SampleData(font, Color.blue, names[randomIndex]);
newNode = new DynamicTreeNode(data);
/* Don't use add() here, add calls insert(newNode, getChildCount())
so if you want to use add, just be sure to set hasLoaded = true
first. */
insert(newNode, counter);
}
/* This node has now been loaded, mark it so. */
hasLoaded = true;
}
}
| apache-2.0 |
DimitrisAndreou/flexigraph | test/gr/forth/ics/graph/algo/BiconnectivityTest.java | 2298 | package gr.forth.ics.graph.algo;
import gr.forth.ics.graph.Edge;
import gr.forth.ics.graph.Graph;
import gr.forth.ics.graph.Node;
import gr.forth.ics.graph.PrimaryGraph;
import junit.framework.*;
public class BiconnectivityTest extends TestCase {
public BiconnectivityTest(String testName) {
super(testName);
}
private Graph g;
private Node[] n;
private Edge e12;
private Edge e23;
private Edge e13;
private Edge e34;
private Edge e45;
private Edge e46;
private Edge e56;
protected void setUp() {
g = new PrimaryGraph();
n = g.newNodes("1", "2", "3", "4", "5", "6");
e12 = g.newEdge(n[0], n[1]);
e13 = g.newEdge(n[0], n[2]);
e23 = g.newEdge(n[1], n[2]);
e34 = g.newEdge(n[2], n[3]);
e45 = g.newEdge(n[3], n[4]);
e46 = g.newEdge(n[3], n[5]);
e56 = g.newEdge(n[4], n[5]);
}
public static Test suite() {
TestSuite suite = new TestSuite(BiconnectivityTest.class);
return suite;
}
public void testCutNodes() {
Biconnectivity bicon = Biconnectivity.execute(g);
assertFalse(bicon.isCutNode(n[0]));
assertFalse(bicon.isCutNode(n[1]));
assertFalse(bicon.isCutNode(n[4]));
assertFalse(bicon.isCutNode(n[5]));
assertTrue(bicon.isCutNode(n[2]));
assertTrue(bicon.isCutNode(n[3]));
}
public void testEdgeComponents() {
Biconnectivity bicon = Biconnectivity.execute(g);
assertEquals(bicon.componentOf(e12), bicon.componentOf(e13));
assertEquals(bicon.componentOf(e13), bicon.componentOf(e23));
assertEquals(bicon.componentOf(e45), bicon.componentOf(e46));
assertEquals(bicon.componentOf(e46), bicon.componentOf(e56));
assertNotSame(bicon.componentOf(e23), bicon.componentOf(e34));
assertNotSame(bicon.componentOf(e34), bicon.componentOf(e45));
assertNotSame(bicon.componentOf(e23), bicon.componentOf(e45));
}
public void testEmpty() {
g = new PrimaryGraph();
Biconnectivity bicon = Biconnectivity.execute(g);
Edge e = g.newEdge(g.newNode(), g.newNode());
assertNull(bicon.componentOf(e));
}
}
| apache-2.0 |
spring-social/spring-social-google | src/main/java/org/springframework/social/google/api/calendar/DisplayMode.java | 1366 | /**
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.google.api.calendar;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.social.google.api.calendar.impl.DisplayModeDeserializer;
import org.springframework.social.google.api.impl.ApiEnumSerializer;
/**
* Enumeration representing a gadget's display mode.
*
* @author Martin Wink
*/
@JsonSerialize(using = ApiEnumSerializer.class)
@JsonDeserialize(using = DisplayModeDeserializer.class)
public enum DisplayMode {
/**
* "icon" - The gadget displays next to the event's title in the calendar view.
*/
ICON,
/**
* "chip" - The gadget displays when the event is clicked.
*/
CHIP
}
| apache-2.0 |
romankagan/DDBWorkbench | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/VoidCompatibility.java | 640 | public class Main {
interface I<T> {
void m(T t);
}
static void foo() {}
{
String s = "";
I<Object> arr1 = <error descr="Incompatible return type String in lambda expression">(t) -> s</error>;
I<Object> arr2 = (t) -> s.toString();
I<Integer> i1 = <error descr="Incompatible return type int in lambda expression">i -> i * 2</error>;
I<Integer> i2 = <error descr="Incompatible return type int in lambda expression">i -> 2 * i</error>;
I<Integer> i3 = <error descr="Incompatible return type void in lambda expression">i -> true ? foo() : foo()</error>;
}
}
| apache-2.0 |
ChinmaySKulkarni/hbase | hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAsyncRegionLocator.java | 6264 | /**
* 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.hadoop.hbase.client;
import static org.apache.hadoop.hbase.HConstants.EMPTY_START_ROW;
import static org.apache.hadoop.hbase.HConstants.HBASE_CLIENT_META_OPERATION_TIMEOUT;
import static org.apache.hadoop.hbase.coprocessor.CoprocessorHost.REGION_COPROCESSOR_CONF_KEY;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.RegionObserver;
import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category({ MediumTests.class, ClientTests.class })
public class TestAsyncRegionLocator {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestAsyncRegionLocator.class);
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static TableName TABLE_NAME = TableName.valueOf("async");
private static byte[] FAMILY = Bytes.toBytes("cf");
private static AsyncConnectionImpl CONN;
private static AsyncRegionLocator LOCATOR;
private static volatile long SLEEP_MS = 0L;
public static class SleepRegionObserver implements RegionCoprocessor, RegionObserver {
@Override
public Optional<RegionObserver> getRegionObserver() {
return Optional.of(this);
}
@Override
public void preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> e, Scan scan)
throws IOException {
if (SLEEP_MS > 0) {
Threads.sleepWithoutInterrupt(SLEEP_MS);
}
}
}
@BeforeClass
public static void setUp() throws Exception {
Configuration conf = TEST_UTIL.getConfiguration();
conf.set(REGION_COPROCESSOR_CONF_KEY, SleepRegionObserver.class.getName());
conf.setLong(HBASE_CLIENT_META_OPERATION_TIMEOUT, 2000);
TEST_UTIL.startMiniCluster(1);
TEST_UTIL.createTable(TABLE_NAME, FAMILY);
TEST_UTIL.waitTableAvailable(TABLE_NAME);
AsyncRegistry registry = AsyncRegistryFactory.getRegistry(TEST_UTIL.getConfiguration());
CONN = new AsyncConnectionImpl(TEST_UTIL.getConfiguration(), registry,
registry.getClusterId().get(), null, User.getCurrent());
LOCATOR = CONN.getLocator();
}
@AfterClass
public static void tearDown() throws Exception {
IOUtils.closeQuietly(CONN);
TEST_UTIL.shutdownMiniCluster();
}
@After
public void tearDownAfterTest() {
LOCATOR.clearCache();
}
@Test
public void testTimeout() throws InterruptedException, ExecutionException {
SLEEP_MS = 1000;
long startNs = System.nanoTime();
try {
LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
TimeUnit.MILLISECONDS.toNanos(500)).get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(TimeoutIOException.class));
}
long costMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
assertTrue(costMs >= 500);
assertTrue(costMs < 1000);
// wait for the background task finish
Thread.sleep(2000);
// Now the location should be in cache, so we will not visit meta again.
HRegionLocation loc = LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW,
RegionLocateType.CURRENT, TimeUnit.MILLISECONDS.toNanos(500)).get();
assertEquals(loc.getServerName(),
TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName());
}
@Test
public void testNoCompletionException() {
// make sure that we do not get CompletionException
SLEEP_MS = 0;
AtomicReference<Throwable> errorHolder = new AtomicReference<>();
try {
LOCATOR.getRegionLocation(TableName.valueOf("NotExist"), EMPTY_START_ROW,
RegionLocateType.CURRENT, TimeUnit.SECONDS.toNanos(1))
.whenComplete((r, e) -> errorHolder.set(e)).join();
fail();
} catch (CompletionException e) {
// join will return a CompletionException, which is OK
assertThat(e.getCause(), instanceOf(TableNotFoundException.class));
}
// but we need to make sure that we do not get a CompletionException in the callback
assertThat(errorHolder.get(), instanceOf(TableNotFoundException.class));
}
}
| apache-2.0 |
finmath/finmath-lib | src/main/java8/net/finmath/montecarlo/assetderivativevaluation/products/BermudanOption.java | 10352 | /*
* (c) Copyright Christian P. Fries, Germany. Contact: email@christian-fries.de.
*
* Created on 23.01.2004
*/
package net.finmath.montecarlo.assetderivativevaluation.products;
import java.util.ArrayList;
import java.util.Arrays;
import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.RandomVariableFromDoubleArray;
import net.finmath.montecarlo.assetderivativevaluation.AssetModelMonteCarloSimulationModel;
import net.finmath.montecarlo.conditionalexpectation.MonteCarloConditionalExpectationRegression;
import net.finmath.optimizer.GoldenSectionSearch;
import net.finmath.stochastic.ConditionalExpectationEstimator;
import net.finmath.stochastic.RandomVariable;
import net.finmath.stochastic.Scalar;
/**
* This class implements the valuation of a Bermudan option paying
* <br>
* <i> N(i) * (S(T(i)) - K(i)) </i> at <i>T(i)</i>,
* <br>
* when exercised in T(i), where N(i) is the notional, S is the underlying, K(i) is the strike
* and T(i) the exercise date.
*
* The code "demos" the two prominent methods for the valuation of Bermudan (American) products:
* <ul>
* <li>
* The valuation may be performed using an estimation of the conditional expectation to determine the
* exercise criteria. Apart from a possible foresight bias induced by the Monte-Carlo errors, this give a lower bound
* for the Bermudan value.
* <li>
* The valuation may be performed using the dual method based on a minimization problem, which gives an upper bound.
* </ul>
*
*
* @author Christian Fries
* @version 1.4
*/
public class BermudanOption extends AbstractAssetMonteCarloProduct {
public enum ExerciseMethod {
ESTIMATE_COND_EXPECTATION,
UPPER_BOUND_METHOD
}
private final double[] exerciseDates;
private final double[] notionals;
private final double[] strikes;
private final int orderOfRegressionPolynomial = 4;
private final boolean intrinsicValueAsBasisFunction = false;
private final ExerciseMethod exerciseMethod;
private RandomVariable lastValuationExerciseTime;
/**
* Create a Bermudan option paying
* N(i) * (S(T(i)) - K(i)) at T(i),
* when exercised in T(i), where N(i) is the notional, S is the underlying, K(i) is the strike
* and T(i) the exercise date.
*
* @param exerciseDates The exercise dates (T(i)), given as doubles.
* @param notionals The notionals (N(i)) for each exercise date.
* @param strikes The strikes (K(i)) for each exercise date.
* @param exerciseMethod The exercise method to be used for the estimation of the exercise boundary.
*/
public BermudanOption(
final double[] exerciseDates,
final double[] notionals,
final double[] strikes,
final ExerciseMethod exerciseMethod) {
super();
this.exerciseDates = exerciseDates;
this.notionals = notionals;
this.strikes = strikes;
this.exerciseMethod = exerciseMethod;
}
/**
* Create a Bermudan option paying
* N(i) * (S(T(i)) - K(i)) at T(i),
* when exercised in T(i), where N(i) is the notional, S is the underlying, K(i) is the strike
* and T(i) the exercise date.
*
* The product will use ExerciseMethod.ESTIMATE_COND_EXPECTATION.
*
* @param exerciseDates The exercise dates (T(i)), given as doubles.
* @param notionals The notionals (N(i)) for each exercise date.
* @param strikes The strikes (K(i)) for each exercise date.
*/
public BermudanOption(
final double[] exerciseDates,
final double[] notionals,
final double[] strikes) {
this(exerciseDates, notionals, strikes, ExerciseMethod.ESTIMATE_COND_EXPECTATION);
}
/**
* This method returns the value random variable of the product within the specified model,
* evaluated at a given evalutationTime.
* Cash-flows prior evaluationTime are not considered.
*
* @param evaluationTime The time on which this products value should be observed.
* @param model The model used to price the product.
* @return The random variable representing the value of the product discounted to evaluation time.
* @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
*
*/
@Override
public RandomVariable getValue(final double evaluationTime, final AssetModelMonteCarloSimulationModel model) throws CalculationException {
if(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) {
// Find optimal lambda
final GoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0);
while(!optimizer.isDone()) {
final double lambda = optimizer.getNextPoint();
final double value = this.getValues(evaluationTime, model, lambda).getAverage();
optimizer.setValue(value);
}
return getValues(evaluationTime, model, optimizer.getBestPoint());
}
else {
return getValues(evaluationTime, model, 0.0);
}
}
private RandomVariable getValues(final double evaluationTime, final AssetModelMonteCarloSimulationModel model, final double lambda) throws CalculationException {
/*
* We are going backward in time (note that this bears the risk of an foresight bias).
* We store the value of the option, if not exercised in a vector. Is is not allowed to used the specific entry in this vector
* in the exercise decision (perfect foresight). Instead some exercise strategy / estimate has to be used.
*/
// Initialize our value random variable: the value of the option if we never exercise is zero
RandomVariable value = model.getRandomVariableForConstant(0.0);
RandomVariable exerciseTime = model.getRandomVariableForConstant(exerciseDates[exerciseDates.length-1]+1);
for(int exerciseDateIndex=exerciseDates.length-1; exerciseDateIndex>=0; exerciseDateIndex--)
{
final double exerciseDate = exerciseDates[exerciseDateIndex];
final double notional = notionals[exerciseDateIndex];
final double strike = strikes[exerciseDateIndex];
// Get some model values upon exercise date
final RandomVariable underlyingAtExercise = model.getAssetValue(exerciseDate,0);
final RandomVariable numeraireAtPayment = model.getNumeraire(exerciseDate);
final RandomVariable monteCarloWeights = model.getMonteCarloWeights(exerciseDate);
// Value received if exercised at current time
final RandomVariable valueOfPaymentsIfExercised = underlyingAtExercise.sub(strike).mult(notional).div(numeraireAtPayment).mult(monteCarloWeights);
/*
* Calculate the exercise criteria (exercise if the following exerciseCriteria is negative)
*/
RandomVariable exerciseValue = null;
RandomVariable exerciseCriteria = null;
switch(exerciseMethod) {
case ESTIMATE_COND_EXPECTATION:
// Create a conditional expectation estimator with some basis functions (predictor variables) for conditional expectation estimation.
ArrayList<RandomVariable> basisFunctions;
if(intrinsicValueAsBasisFunction) {
basisFunctions = getRegressionBasisFunctions(underlyingAtExercise.sub(strike).floor(0.0));
} else {
basisFunctions = getRegressionBasisFunctions(underlyingAtExercise);
}
final ConditionalExpectationEstimator condExpEstimator = new MonteCarloConditionalExpectationRegression(basisFunctions.toArray(new RandomVariable[0]));
// Calculate conditional expectation on numeraire relative quantity.
final RandomVariable valueIfNotExcercisedEstimated = value.getConditionalExpectation(condExpEstimator);
exerciseValue = valueOfPaymentsIfExercised;
exerciseCriteria = valueIfNotExcercisedEstimated.sub(exerciseValue);
break;
case UPPER_BOUND_METHOD:
RandomVariable martingale = model.getAssetValue(exerciseDates[exerciseDateIndex], 0).div(model.getNumeraire(exerciseDates[exerciseDateIndex]));
// Construct a martingale with initial value being zero.
martingale = martingale.sub(martingale.getAverage()).mult(lambda);
// Initialize value as 0-M, if we are on the last exercise date.
if(exerciseDateIndex==exerciseDates.length-1) {
value = value.sub(martingale);
}
exerciseValue = valueOfPaymentsIfExercised.sub(martingale);
exerciseCriteria = value.sub(exerciseValue);
break;
default:
throw new IllegalArgumentException("Unknown exerciseMethod " + exerciseMethod + ".");
}
// If trigger is positive keep value, otherwise take underlying
value = exerciseCriteria.choose(value, exerciseValue);
exerciseTime = exerciseCriteria.choose(exerciseTime, new Scalar(exerciseDate));
}
lastValuationExerciseTime = exerciseTime;
// Note that values is a relative price - no numeraire division is required
final RandomVariable numeraireAtEvalTime = model.getNumeraire(evaluationTime);
final RandomVariable monteCarloWeightsAtEvalTime = model.getMonteCarloWeights(evaluationTime);
value = value.mult(numeraireAtEvalTime).div(monteCarloWeightsAtEvalTime);
return value;
}
public RandomVariable getLastValuationExerciseTime() {
return lastValuationExerciseTime;
}
public double[] getExerciseDates() {
return exerciseDates;
}
public double[] getNotionals() {
return notionals;
}
public double[] getStrikes() {
return strikes;
}
private ArrayList<RandomVariable> getRegressionBasisFunctions(RandomVariable underlying) {
final ArrayList<RandomVariable> basisFunctions = new ArrayList<>();
underlying = new RandomVariableFromDoubleArray(0.0, underlying.getRealizations());
// Create basis functions - here: 1, S, S^2, S^3, S^4
for(int powerOfRegressionMonomial=0; powerOfRegressionMonomial<=orderOfRegressionPolynomial; powerOfRegressionMonomial++) {
basisFunctions.add(underlying.pow(powerOfRegressionMonomial));
}
return basisFunctions;
}
private ArrayList<RandomVariable> getRegressionBasisFunctionsBinning(RandomVariable underlying) {
final ArrayList<RandomVariable> basisFunctions = new ArrayList<>();
underlying = new RandomVariableFromDoubleArray(0.0, underlying.getRealizations());
final int numberOfBins = 20;
final double[] values = underlying.getRealizations();
Arrays.sort(values);
for(int i = 0; i<numberOfBins; i++) {
final double binLeft = values[(int)((double)i/(double)numberOfBins*values.length)];
final RandomVariable basisFunction = underlying.sub(binLeft).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0));
basisFunctions.add(basisFunction);
}
return basisFunctions;
}
}
| apache-2.0 |
vincentpoon/hbase | hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestRegionObserverForAddingMutationsFromCoprocessors.java | 10739 | /**
* 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.hadoop.hbase.coprocessor;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress;
import org.apache.hadoop.hbase.shaded.com.google.common.collect.Lists;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.wal.WALEdit;
import org.apache.hadoop.hbase.wal.WALKey;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@Category(MediumTests.class)
public class TestRegionObserverForAddingMutationsFromCoprocessors {
private static final Log LOG
= LogFactory.getLog(TestRegionObserverForAddingMutationsFromCoprocessors.class);
private static HBaseTestingUtility util;
private static final byte[] dummy = Bytes.toBytes("dummy");
private static final byte[] row1 = Bytes.toBytes("r1");
private static final byte[] row2 = Bytes.toBytes("r2");
private static final byte[] row3 = Bytes.toBytes("r3");
private static final byte[] test = Bytes.toBytes("test");
@Rule
public TestName name = new TestName();
private TableName tableName;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Configuration conf = HBaseConfiguration.create();
conf.set(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY, TestWALObserver.class.getName());
util = new HBaseTestingUtility(conf);
util.startMiniCluster();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
util.shutdownMiniCluster();
}
@Before
public void setUp() throws Exception {
tableName = TableName.valueOf(name.getMethodName());
}
private void createTable(String coprocessor) throws IOException {
HTableDescriptor htd = new HTableDescriptor(tableName)
.addFamily(new HColumnDescriptor(dummy))
.addFamily(new HColumnDescriptor(test))
.addCoprocessor(coprocessor);
util.getAdmin().createTable(htd);
}
/**
* Test various multiput operations.
* @throws Exception
*/
@Test
public void testMulti() throws Exception {
createTable(TestMultiMutationCoprocessor.class.getName());
try (Table t = util.getConnection().getTable(tableName)) {
t.put(new Put(row1).addColumn(test, dummy, dummy));
assertRowCount(t, 3);
}
}
/**
* Tests that added mutations from coprocessors end up in the WAL.
*/
@Test
public void testCPMutationsAreWrittenToWALEdit() throws Exception {
createTable(TestMultiMutationCoprocessor.class.getName());
try (Table t = util.getConnection().getTable(tableName)) {
t.put(new Put(row1).addColumn(test, dummy, dummy));
assertRowCount(t, 3);
}
assertNotNull(TestWALObserver.savedEdit);
assertEquals(4, TestWALObserver.savedEdit.getCells().size());
}
private static void assertRowCount(Table t, int expected) throws IOException {
try (ResultScanner scanner = t.getScanner(new Scan())) {
int i = 0;
for (Result r: scanner) {
LOG.info(r.toString());
i++;
}
assertEquals(expected, i);
}
}
@Test
public void testDeleteCell() throws Exception {
createTable(TestDeleteCellCoprocessor.class.getName());
try (Table t = util.getConnection().getTable(tableName)) {
t.put(Lists.newArrayList(
new Put(row1).addColumn(test, dummy, dummy),
new Put(row2).addColumn(test, dummy, dummy),
new Put(row3).addColumn(test, dummy, dummy)
));
assertRowCount(t, 3);
t.delete(new Delete(test).addColumn(test, dummy)); // delete non-existing row
assertRowCount(t, 1);
}
}
@Test
public void testDeleteFamily() throws Exception {
createTable(TestDeleteFamilyCoprocessor.class.getName());
try (Table t = util.getConnection().getTable(tableName)) {
t.put(Lists.newArrayList(
new Put(row1).addColumn(test, dummy, dummy),
new Put(row2).addColumn(test, dummy, dummy),
new Put(row3).addColumn(test, dummy, dummy)
));
assertRowCount(t, 3);
t.delete(new Delete(test).addFamily(test)); // delete non-existing row
assertRowCount(t, 1);
}
}
@Test
public void testDeleteRow() throws Exception {
createTable(TestDeleteRowCoprocessor.class.getName());
try (Table t = util.getConnection().getTable(tableName)) {
t.put(Lists.newArrayList(
new Put(row1).addColumn(test, dummy, dummy),
new Put(row2).addColumn(test, dummy, dummy),
new Put(row3).addColumn(test, dummy, dummy)
));
assertRowCount(t, 3);
t.delete(new Delete(test).addColumn(test, dummy)); // delete non-existing row
assertRowCount(t, 1);
}
}
public static class TestMultiMutationCoprocessor implements RegionCoprocessor, RegionObserver {
@Override
public Optional<RegionObserver> getRegionObserver() {
return Optional.of(this);
}
@Override
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
Mutation mut = miniBatchOp.getOperation(0);
List<Cell> cells = mut.getFamilyCellMap().get(test);
Put[] puts = new Put[] {
new Put(row1).addColumn(test, dummy, cells.get(0).getTimestamp(),
Bytes.toBytes("cpdummy")),
new Put(row2).addColumn(test, dummy, cells.get(0).getTimestamp(), dummy),
new Put(row3).addColumn(test, dummy, cells.get(0).getTimestamp(), dummy),
};
LOG.info("Putting:" + puts);
miniBatchOp.addOperationsFromCP(0, puts);
}
}
public static class TestDeleteCellCoprocessor implements RegionCoprocessor, RegionObserver {
@Override
public Optional<RegionObserver> getRegionObserver() {
return Optional.of(this);
}
@Override
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
Mutation mut = miniBatchOp.getOperation(0);
if (mut instanceof Delete) {
List<Cell> cells = mut.getFamilyCellMap().get(test);
Delete[] deletes = new Delete[] {
// delete only 2 rows
new Delete(row1).addColumns(test, dummy, cells.get(0).getTimestamp()),
new Delete(row2).addColumns(test, dummy, cells.get(0).getTimestamp()),
};
LOG.info("Deleting:" + Arrays.toString(deletes));
miniBatchOp.addOperationsFromCP(0, deletes);
}
}
}
public static class TestDeleteFamilyCoprocessor implements RegionCoprocessor, RegionObserver {
@Override
public Optional<RegionObserver> getRegionObserver() {
return Optional.of(this);
}
@Override
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
Mutation mut = miniBatchOp.getOperation(0);
if (mut instanceof Delete) {
List<Cell> cells = mut.getFamilyCellMap().get(test);
Delete[] deletes = new Delete[] {
// delete only 2 rows
new Delete(row1).addFamily(test, cells.get(0).getTimestamp()),
new Delete(row2).addFamily(test, cells.get(0).getTimestamp()),
};
LOG.info("Deleting:" + Arrays.toString(deletes));
miniBatchOp.addOperationsFromCP(0, deletes);
}
}
}
public static class TestDeleteRowCoprocessor implements RegionCoprocessor, RegionObserver {
@Override
public Optional<RegionObserver> getRegionObserver() {
return Optional.of(this);
}
@Override
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
Mutation mut = miniBatchOp.getOperation(0);
if (mut instanceof Delete) {
List<Cell> cells = mut.getFamilyCellMap().get(test);
Delete[] deletes = new Delete[] {
// delete only 2 rows
new Delete(row1, cells.get(0).getTimestamp()),
new Delete(row2, cells.get(0).getTimestamp()),
};
LOG.info("Deleting:" + Arrays.toString(deletes));
miniBatchOp.addOperationsFromCP(0, deletes);
}
}
}
public static class TestWALObserver implements WALCoprocessor, WALObserver {
static WALEdit savedEdit = null;
@Override
public Optional<WALObserver> getWALObserver() {
return Optional.of(this);
}
@Override
public void postWALWrite(ObserverContext<? extends WALCoprocessorEnvironment> ctx,
RegionInfo info, WALKey logKey, WALEdit logEdit) throws IOException {
if (info.getTable().equals(TableName.valueOf("testCPMutationsAreWrittenToWALEdit"))) {
savedEdit = logEdit;
}
}
}
}
| apache-2.0 |
wanliyang10010/Shop | src/cn/xaut/shop/service/impl/ShopApplyServiceImpl.java | 2186 | package cn.xaut.shop.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.xaut.common.paging.domain.Page;
import cn.xaut.shop.dao.ShopApplyDao;
import cn.xaut.shop.dao.ShopDao;
import cn.xaut.shop.pojo.Shop;
import cn.xaut.shop.pojo.ShopApply;
import cn.xaut.shop.pojo.UserInfo;
import cn.xaut.shop.service.ShopApplyService;
@Service
@Transactional
public class ShopApplyServiceImpl extends BaseServiceRImpl<ShopApply,Integer> implements
ShopApplyService {
private ShopApplyDao shopApplyDao = null;
public void setShopApplyDao(ShopApplyDao shopApplyDao) {
this.shopApplyDao = shopApplyDao;
}
@Autowired
private ShopDao shopDao=null;
public boolean isApply(int userid){
return shopApplyDao.isApply(userid);
}
@Override
public ShopApply getCheckShopName(ShopApply shopApply) {
return shopApplyDao.getCheckShopName(shopApply);
}
@Override
public Page<ShopApply> getAllCheckList(Page<ShopApply> page,String fromdate, String todate,int id)
{
return shopApplyDao.getAllCheckList(page, fromdate,todate,id);
}
@Override
public List<ShopApply> getMyAlterList(int userid,String fromdate, String todate,
String state) {
return shopApplyDao.getMyAlterList(userid,fromdate,todate,state);
}
@Override
public List<ShopApply> getMyViewList(int userid,String fromdate, String todate) {
return shopApplyDao.getMyViewList(userid,fromdate,todate);
}
@Override
public Page<ShopApply> getMyViewList(Page<ShopApply> page,String fromdate, String todate,UserInfo user,int id)
{
return shopApplyDao.getMyViewList(page, fromdate,todate,user,id);
}
@Override
public Page<ShopApply> getAllCheckListNoDate(Page<ShopApply> page, int id) {
return shopApplyDao.getAllCheckListNoDate(page, id);
}
@Override
public List<ShopApply> getMyViewListNoDate(int userid) {
return shopApplyDao.getMyViewListNoDate(userid);
}
public void updateAndSave(ShopApply shopApply,Shop shop){
shopApplyDao.update(shopApply);// 更新店铺申请表
shopDao.save(shop);// 添加店铺表
}
}
| apache-2.0 |
gkathir15/unisannio-reboot | app/src/main/java/solutions/alterego/android/unisannio/di/RetrieversModule.java | 956 | package solutions.alterego.android.unisannio.di;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import solutions.alterego.android.unisannio.ateneo.AteneoRetriever;
import solutions.alterego.android.unisannio.giurisprudenza.GiurisprudenzaRetriever;
import solutions.alterego.android.unisannio.scienze.ScienzeRetriever;
import solutions.alterego.android.unisannio.sea.SeaRetriever;
@Module
public class RetrieversModule {
@Provides
@Singleton
AteneoRetriever provideAteneoRetriever() {
return new AteneoRetriever();
}
@Provides
@Singleton
GiurisprudenzaRetriever provideGiurisprudenzaRetriever() {
return new GiurisprudenzaRetriever();
}
@Provides
@Singleton
SeaRetriever provideSeaRetriever() {
return new SeaRetriever();
}
@Provides
@Singleton
ScienzeRetriever provideScienzeRetriever() {
return new ScienzeRetriever();
}
} | apache-2.0 |
corochoone/elasticsearch | src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreTests.java | 23902 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.snapshots;
import com.carrotsearch.randomizedtesting.LifecycleScope;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.delete.DeleteSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotStatus;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.store.support.AbstractIndexStore;
import org.elasticsearch.snapshots.mockstore.MockRepositoryModule;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.test.store.MockDirectoryHelper;
import org.elasticsearch.threadpool.ThreadPool;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static com.google.common.collect.Lists.newArrayList;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope;
import static org.elasticsearch.test.ElasticsearchIntegrationTest.Scope;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
import static org.hamcrest.Matchers.*;
/**
*/
@ClusterScope(scope = Scope.TEST, numDataNodes = 0)
public class DedicatedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
@Test
public void restorePersistentSettingsTest() throws Exception {
logger.info("--> start node");
internalCluster().startNode(settingsBuilder().put("gateway.type", "local"));
Client client = client();
// Add dummy persistent setting
logger.info("--> set test persistent setting");
String settingValue = "test-" + randomInt();
client.admin().cluster().prepareUpdateSettings().setPersistentSettings(ImmutableSettings.settingsBuilder().put(ThreadPool.THREADPOOL_GROUP + "dummy.value", settingValue)).execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().get(ThreadPool.THREADPOOL_GROUP + "dummy.value"), equalTo(settingValue));
logger.info("--> create repository");
PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
.setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDir())).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
logger.info("--> start snapshot");
CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).execute().actionGet();
assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(0));
assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
logger.info("--> clean the test persistent setting");
client.admin().cluster().prepareUpdateSettings().setPersistentSettings(ImmutableSettings.settingsBuilder().put(ThreadPool.THREADPOOL_GROUP + "dummy.value", "")).execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().get(ThreadPool.THREADPOOL_GROUP + "dummy.value"), equalTo(""));
logger.info("--> restore snapshot");
client.admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap").setRestoreGlobalState(true).setWaitForCompletion(true).execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().get(ThreadPool.THREADPOOL_GROUP + "dummy.value"), equalTo(settingValue));
}
@Test
public void snapshotDuringNodeShutdownTest() throws Exception {
logger.info("--> start 2 nodes");
Client client = client();
assertAcked(prepareCreate("test-idx", 2, settingsBuilder().put("number_of_shards", 2).put("number_of_replicas", 0).put(MockDirectoryHelper.RANDOM_NO_DELETE_OPEN_FILE, false)));
ensureGreen();
logger.info("--> indexing some data");
for (int i = 0; i < 100; i++) {
index("test-idx", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client.prepareCount("test-idx").get().getCount(), equalTo(100L));
logger.info("--> create repository");
logger.info("--> creating repository");
PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
.setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
ImmutableSettings.settingsBuilder()
.put("location", newTempDir(LifecycleScope.TEST))
.put("random", randomAsciiOfLength(10))
.put("wait_after_unblock", 200)
).get();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
// Pick one node and block it
String blockedNode = blockNodeWithIndex("test-idx");
logger.info("--> snapshot");
client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
logger.info("--> waiting for block to kick in");
waitForBlock(blockedNode, "test-repo", TimeValue.timeValueSeconds(60));
logger.info("--> execution was blocked on node [{}], shutting it down", blockedNode);
unblockNode(blockedNode);
logger.info("--> stopping node", blockedNode);
stopNode(blockedNode);
logger.info("--> waiting for completion");
SnapshotInfo snapshotInfo = waitForCompletion("test-repo", "test-snap", TimeValue.timeValueSeconds(60));
logger.info("Number of failed shards [{}]", snapshotInfo.shardFailures().size());
logger.info("--> done");
}
@Test
public void snapshotWithStuckNodeTest() throws Exception {
logger.info("--> start 2 nodes");
ArrayList<String> nodes = newArrayList();
nodes.add(internalCluster().startNode());
nodes.add(internalCluster().startNode());
Client client = client();
assertAcked(prepareCreate("test-idx", 2, settingsBuilder().put("number_of_shards", 2).put("number_of_replicas", 0).put(MockDirectoryHelper.RANDOM_NO_DELETE_OPEN_FILE, false)));
ensureGreen();
logger.info("--> indexing some data");
for (int i = 0; i < 100; i++) {
index("test-idx", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client.prepareCount("test-idx").get().getCount(), equalTo(100L));
logger.info("--> creating repository");
PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
.setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
ImmutableSettings.settingsBuilder()
.put("location", newTempDir(LifecycleScope.TEST))
.put("random", randomAsciiOfLength(10))
.put("wait_after_unblock", 200)
).get();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
// Pick one node and block it
String blockedNode = blockNodeWithIndex("test-idx");
// Remove it from the list of available nodes
nodes.remove(blockedNode);
logger.info("--> snapshot");
client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
logger.info("--> waiting for block to kick in");
waitForBlock(blockedNode, "test-repo", TimeValue.timeValueSeconds(60));
logger.info("--> execution was blocked on node [{}], aborting snapshot", blockedNode);
ListenableActionFuture<DeleteSnapshotResponse> deleteSnapshotResponseFuture = internalCluster().client(nodes.get(0)).admin().cluster().prepareDeleteSnapshot("test-repo", "test-snap").execute();
// Make sure that abort makes some progress
Thread.sleep(100);
unblockNode(blockedNode);
logger.info("--> stopping node", blockedNode);
stopNode(blockedNode);
try {
DeleteSnapshotResponse deleteSnapshotResponse = deleteSnapshotResponseFuture.actionGet();
assertThat(deleteSnapshotResponse.isAcknowledged(), equalTo(true));
} catch (SnapshotMissingException ex) {
// When master node is closed during this test, it sometime manages to delete the snapshot files before
// completely stopping. In this case the retried delete snapshot operation on the new master can fail
// with SnapshotMissingException
}
logger.info("--> making sure that snapshot no longer exists");
assertThrows(client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute(), SnapshotMissingException.class);
logger.info("--> done");
}
@Test
@TestLogging("snapshots:TRACE")
public void restoreIndexWithMissingShards() throws Exception {
logger.info("--> start 2 nodes");
internalCluster().startNode(settingsBuilder().put("gateway.type", "local"));
internalCluster().startNode(settingsBuilder().put("gateway.type", "local"));
cluster().wipeIndices("_all");
assertAcked(prepareCreate("test-idx-1", 2, settingsBuilder().put("number_of_shards", 6)
.put("number_of_replicas", 0)
.put(MockDirectoryHelper.RANDOM_NO_DELETE_OPEN_FILE, false)));
ensureGreen();
logger.info("--> indexing some data into test-idx-1");
for (int i = 0; i < 100; i++) {
index("test-idx-1", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client().prepareCount("test-idx-1").get().getCount(), equalTo(100L));
logger.info("--> shutdown one of the nodes");
internalCluster().stopRandomDataNode();
assertThat(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForNodes("<2").execute().actionGet().isTimedOut(), equalTo(false));
assertAcked(prepareCreate("test-idx-2", 1, settingsBuilder().put("number_of_shards", 6)
.put("number_of_replicas", 0)
.put(MockDirectoryHelper.RANDOM_NO_DELETE_OPEN_FILE, false)));
ensureGreen("test-idx-2");
logger.info("--> indexing some data into test-idx-2");
for (int i = 0; i < 100; i++) {
index("test-idx-2", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client().prepareCount("test-idx-2").get().getCount(), equalTo(100L));
logger.info("--> create repository");
logger.info("--> creating repository");
PutRepositoryResponse putRepositoryResponse = client().admin().cluster().preparePutRepository("test-repo")
.setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDir())).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
logger.info("--> start snapshot with default settings - should fail");
CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1").setWaitForCompletion(true).execute().actionGet();
assertThat(createSnapshotResponse.getSnapshotInfo().state(), equalTo(SnapshotState.FAILED));
if (randomBoolean()) {
logger.info("checking snapshot completion using status");
client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-2").setWaitForCompletion(false).setPartial(true).execute().actionGet();
awaitBusy(new Predicate<Object>() {
@Override
public boolean apply(Object o) {
SnapshotsStatusResponse snapshotsStatusResponse = client().admin().cluster().prepareSnapshotStatus("test-repo").setSnapshots("test-snap-2").get();
ImmutableList<SnapshotStatus> snapshotStatuses = snapshotsStatusResponse.getSnapshots();
if(snapshotStatuses.size() == 1) {
logger.trace("current snapshot status [{}]", snapshotStatuses.get(0));
return snapshotStatuses.get(0).getState().completed();
}
return false;
}
});
SnapshotsStatusResponse snapshotsStatusResponse = client().admin().cluster().prepareSnapshotStatus("test-repo").setSnapshots("test-snap-2").get();
ImmutableList<SnapshotStatus> snapshotStatuses = snapshotsStatusResponse.getSnapshots();
assertThat(snapshotStatuses.size(), equalTo(1));
SnapshotStatus snapshotStatus = snapshotStatuses.get(0);
logger.info("State: [{}], Reason: [{}]", createSnapshotResponse.getSnapshotInfo().state(), createSnapshotResponse.getSnapshotInfo().reason());
assertThat(snapshotStatus.getShardsStats().getTotalShards(), equalTo(12));
assertThat(snapshotStatus.getShardsStats().getDoneShards(), lessThan(12));
assertThat(snapshotStatus.getShardsStats().getDoneShards(), greaterThan(6));
} else {
logger.info("checking snapshot completion using wait_for_completion flag");
createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-2").setWaitForCompletion(true).setPartial(true).execute().actionGet();
logger.info("State: [{}], Reason: [{}]", createSnapshotResponse.getSnapshotInfo().state(), createSnapshotResponse.getSnapshotInfo().reason());
assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(12));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), lessThan(12));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(6));
}
assertThat(client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap-2").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.PARTIAL));
assertAcked(client().admin().indices().prepareClose("test-idx-1", "test-idx-2").execute().actionGet());
logger.info("--> restore incomplete snapshot - should fail");
assertThrows(client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false).setWaitForCompletion(true).execute(), SnapshotRestoreException.class);
logger.info("--> restore snapshot for the index that was snapshotted completely");
RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false).setIndices("test-idx-2").setWaitForCompletion(true).execute().actionGet();
assertThat(restoreSnapshotResponse.getRestoreInfo(), notNullValue());
assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), equalTo(6));
assertThat(restoreSnapshotResponse.getRestoreInfo().successfulShards(), equalTo(6));
assertThat(restoreSnapshotResponse.getRestoreInfo().failedShards(), equalTo(0));
ensureGreen("test-idx-2");
assertThat(client().prepareCount("test-idx-2").get().getCount(), equalTo(100L));
}
@Test
@TestLogging("snapshots:TRACE,repositories:TRACE")
@Ignore
public void chaosSnapshotTest() throws Exception {
final List<String> indices = new CopyOnWriteArrayList<>();
Settings settings = settingsBuilder().put("action.write_consistency", "one").build();
int initialNodes = between(1, 3);
logger.info("--> start {} nodes", initialNodes);
for (int i = 0; i < initialNodes; i++) {
internalCluster().startNode(settings);
}
logger.info("--> creating repository");
assertAcked(client().admin().cluster().preparePutRepository("test-repo")
.setType("fs").setSettings(ImmutableSettings.settingsBuilder()
.put("location", newTempDir(LifecycleScope.SUITE))
.put("compress", randomBoolean())
.put("chunk_size", randomIntBetween(100, 1000))));
int initialIndices = between(1, 3);
logger.info("--> create {} indices", initialIndices);
for (int i = 0; i < initialIndices; i++) {
createTestIndex("test-" + i);
indices.add("test-" + i);
}
int asyncNodes = between(0, 5);
logger.info("--> start {} additional nodes asynchronously", asyncNodes);
ListenableFuture<List<String>> asyncNodesFuture = internalCluster().startNodesAsync(asyncNodes, settings);
int asyncIndices = between(0, 10);
logger.info("--> create {} additional indices asynchronously", asyncIndices);
Thread[] asyncIndexThreads = new Thread[asyncIndices];
for (int i = 0; i < asyncIndices; i++) {
final int cur = i;
asyncIndexThreads[i] = new Thread(new Runnable() {
@Override
public void run() {
createTestIndex("test-async-" + cur);
indices.add("test-async-" + cur);
}
});
asyncIndexThreads[i].start();
}
logger.info("--> snapshot");
ListenableActionFuture<CreateSnapshotResponse> snapshotResponseFuture = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).setIndices("test-*").setPartial(true).execute();
long start = System.currentTimeMillis();
// Produce chaos for 30 sec or until snapshot is done whatever comes first
int randomIndices = 0;
while (System.currentTimeMillis() - start < 30000 && !snapshotIsDone("test-repo", "test-snap")) {
Thread.sleep(100);
int chaosType = randomInt(10);
if (chaosType < 4) {
// Randomly delete an index
if (indices.size() > 0) {
String index = indices.remove(randomInt(indices.size() - 1));
logger.info("--> deleting random index [{}]", index);
internalCluster().wipeIndices(index);
}
} else if (chaosType < 6) {
// Randomly shutdown a node
if (cluster().size() > 1) {
logger.info("--> shutting down random node");
internalCluster().stopRandomDataNode();
}
} else if (chaosType < 8) {
// Randomly create an index
String index = "test-rand-" + randomIndices;
logger.info("--> creating random index [{}]", index);
createTestIndex(index);
randomIndices++;
} else {
// Take a break
logger.info("--> noop");
}
}
logger.info("--> waiting for async indices creation to finish");
for (int i = 0; i < asyncIndices; i++) {
asyncIndexThreads[i].join();
}
logger.info("--> update index settings to back to normal");
assertAcked(client().admin().indices().prepareUpdateSettings("test-*").setSettings(ImmutableSettings.builder()
.put(AbstractIndexStore.INDEX_STORE_THROTTLE_TYPE, "node")
));
// Make sure that snapshot finished - doesn't matter if it failed or succeeded
try {
CreateSnapshotResponse snapshotResponse = snapshotResponseFuture.get();
SnapshotInfo snapshotInfo = snapshotResponse.getSnapshotInfo();
assertNotNull(snapshotInfo);
logger.info("--> snapshot is done with state [{}], total shards [{}], successful shards [{}]", snapshotInfo.state(), snapshotInfo.totalShards(), snapshotInfo.successfulShards());
} catch (Exception ex) {
logger.info("--> snapshot didn't start properly", ex);
}
asyncNodesFuture.get();
logger.info("--> done");
}
private boolean snapshotIsDone(String repository, String snapshot) {
try {
SnapshotsStatusResponse snapshotsStatusResponse = client().admin().cluster().prepareSnapshotStatus(repository).setSnapshots(snapshot).get();
if (snapshotsStatusResponse.getSnapshots().isEmpty()) {
return false;
}
for (SnapshotStatus snapshotStatus : snapshotsStatusResponse.getSnapshots()) {
if (snapshotStatus.getState().completed()) {
return true;
}
}
return false;
} catch (SnapshotMissingException ex) {
return false;
}
}
private void createTestIndex(String name) {
assertAcked(prepareCreate(name, 0, settingsBuilder().put("number_of_shards", between(1, 6))
.put("number_of_replicas", between(1, 6))
.put(MockDirectoryHelper.RANDOM_NO_DELETE_OPEN_FILE, false)));
ensureYellow(name);
logger.info("--> indexing some data into {}", name);
for (int i = 0; i < between(10, 500); i++) {
index(name, "doc", Integer.toString(i), "foo", "bar" + i);
}
assertAcked(client().admin().indices().prepareUpdateSettings(name).setSettings(ImmutableSettings.builder()
.put(AbstractIndexStore.INDEX_STORE_THROTTLE_TYPE, "all")
.put(AbstractIndexStore.INDEX_STORE_THROTTLE_MAX_BYTES_PER_SEC, between(100, 50000))
));
}
}
| apache-2.0 |
liveontologies/elk-reasoner | elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/saturation/properties/inferences/ObjectPropertyInferenceConclusionVisitor.java | 1877 | package org.semanticweb.elk.reasoner.saturation.properties.inferences;
/*-
* #%L
* ELK Reasoner Core
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2011 - 2017 Department of Computer Science, University of Oxford
* %%
* 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.
* #L%
*/
import org.semanticweb.elk.reasoner.saturation.conclusions.model.ObjectPropertyConclusion;
public class ObjectPropertyInferenceConclusionVisitor<O>
implements ObjectPropertyInference.Visitor<O> {
private final ObjectPropertyConclusion.Factory conclusionFactory_;
private final ObjectPropertyConclusion.Visitor<O> conclusionVisitor_;
public ObjectPropertyInferenceConclusionVisitor(
ObjectPropertyConclusion.Factory conclusionFactory,
ObjectPropertyConclusion.Visitor<O> conclusionVisitor) {
this.conclusionFactory_ = conclusionFactory;
this.conclusionVisitor_ = conclusionVisitor;
}
@Override
public O visit(PropertyRangeInherited inference) {
return conclusionVisitor_
.visit(inference.getConclusion(conclusionFactory_));
}
@Override
public O visit(SubPropertyChainExpandedSubObjectPropertyOf inference) {
return conclusionVisitor_
.visit(inference.getConclusion(conclusionFactory_));
}
@Override
public O visit(SubPropertyChainTautology inference) {
return conclusionVisitor_
.visit(inference.getConclusion(conclusionFactory_));
}
}
| apache-2.0 |
shopping24/querqy | querqy-for-lucene/querqy-solr/src/test/java/querqy/solr/UserQueryWithSimilarityOnTest.java | 1668 | package querqy.solr;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.params.DisMaxParams;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.QueryParsing;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@SolrTestCaseJ4.SuppressSSL
public class UserQueryWithSimilarityOnTest extends SolrTestCaseJ4 {
public void index() {
assertU(adoc("id", "1", "f1", "a"));
assertU(adoc("id", "2", "f1", "a"));
assertU(adoc("id", "5", "f1", "a"));
assertU(adoc("id", "6", "f2", "y"));
assertU(adoc("id", "3", "f2", "a"));
assertU(adoc("id", "4", "f3", "k a"));
assertU(commit());
}
@BeforeClass
public static void beforeTests() throws Exception {
initCore("solrconfig.xml", "schema.xml");
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
clearIndex();
index();
}
@Test
public void testThatDfAndDfAreUsedForRanking() {
String q = "a";
SolrQueryRequest req = req("q", q,
DisMaxParams.QF, "f1 f2 f3",
QueryParsing.OP, "OR",
DisMaxParams.TIE, "0.0",
"defType", "querqy",
"uq.similarityScore", "on",
"debugQuery", "true"
);
assertQ("Ranking",
req,
"//doc[1]/str[@name='id'][contains(.,'3')]",
"//doc[2]/str[@name='id'][contains(.,'4')]",
"//lst[@name='explain']/str[@name='3'][contains(.,'idf, computed as')]"
);
req.close();
}
}
| apache-2.0 |
apache/bookkeeper | microbenchmarks/src/main/java/org/apache/bookkeeper/proto/ProtocolBenchmark.java | 7952 | /*
* 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.bookkeeper.proto;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.protobuf.ByteString;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.util.ReferenceCountUtil;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.bookkeeper.proto.BookieProtoEncoding.EnDecoder;
import org.apache.bookkeeper.proto.BookieProtoEncoding.RequestEnDeCoderPreV3;
import org.apache.bookkeeper.proto.BookieProtoEncoding.RequestEnDecoderV3;
import org.apache.bookkeeper.proto.BookkeeperProtocol.AddRequest;
import org.apache.bookkeeper.proto.BookkeeperProtocol.BKPacketHeader;
import org.apache.bookkeeper.proto.BookkeeperProtocol.OperationType;
import org.apache.bookkeeper.proto.BookkeeperProtocol.ProtocolVersion;
import org.apache.bookkeeper.proto.BookkeeperProtocol.Request;
import org.apache.bookkeeper.util.ByteBufList;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.slf4j.MDC;
/**
* Benchmarking serialization and deserialization.
*/
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class ProtocolBenchmark {
@Param({"10", "100", "1000", "10000"})
int size;
byte[] masterKey;
ByteBuf entry;
long ledgerId;
long entryId;
short flags;
EnDecoder reqEnDeV2;
EnDecoder reqEnDeV3;
@Setup
public void prepare() {
this.masterKey = "test-benchmark-key".getBytes(UTF_8);
Random r = new Random(System.currentTimeMillis());
byte[] data = new byte[this.size];
r.nextBytes(data);
this.entry = Unpooled.wrappedBuffer(data);
this.ledgerId = r.nextLong();
this.entryId = r.nextLong();
this.flags = 1;
// prepare the encoder
this.reqEnDeV2 = new RequestEnDeCoderPreV3(null);
this.reqEnDeV3 = new RequestEnDecoderV3(null);
}
@Benchmark
public void testAddEntryV2() throws Exception {
ByteBufList list = ByteBufList.get(entry.retainedSlice());
BookieProtocol.AddRequest req = BookieProtocol.AddRequest.create(
BookieProtocol.CURRENT_PROTOCOL_VERSION,
ledgerId,
entryId,
flags,
masterKey,
list);
Object res = this.reqEnDeV2.encode(req, ByteBufAllocator.DEFAULT);
ReferenceCountUtil.release(res);
ReferenceCountUtil.release(list);
}
@Benchmark
public void testAddEntryV3() throws Exception {
// Build the request and calculate the total size to be included in the packet.
BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder()
.setVersion(ProtocolVersion.VERSION_THREE)
.setOperation(OperationType.ADD_ENTRY)
.setTxnId(0L);
ByteBuf toSend = entry.slice();
byte[] toSendArray = new byte[toSend.readableBytes()];
toSend.getBytes(toSend.readerIndex(), toSendArray);
AddRequest.Builder addBuilder = AddRequest.newBuilder()
.setLedgerId(ledgerId)
.setEntryId(entryId)
.setMasterKey(ByteString.copyFrom(masterKey))
.setBody(ByteString.copyFrom(toSendArray))
.setFlag(AddRequest.Flag.RECOVERY_ADD);
Request request = Request.newBuilder()
.setHeader(headerBuilder)
.setAddRequest(addBuilder)
.build();
Object res = this.reqEnDeV3.encode(request, ByteBufAllocator.DEFAULT);
ReferenceCountUtil.release(res);
}
@Benchmark
public void testAddEntryV3WithMdc() throws Exception {
MDC.put("parent_id", "LetsPutSomeLongParentRequestIdHere");
MDC.put("request_id", "LetsPutSomeLongRequestIdHere");
// Build the request and calculate the total size to be included in the packet.
BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder()
.setVersion(ProtocolVersion.VERSION_THREE)
.setOperation(OperationType.ADD_ENTRY)
.setTxnId(0L);
ByteBuf toSend = entry.slice();
byte[] toSendArray = new byte[toSend.readableBytes()];
toSend.getBytes(toSend.readerIndex(), toSendArray);
AddRequest.Builder addBuilder = AddRequest.newBuilder()
.setLedgerId(ledgerId)
.setEntryId(entryId)
.setMasterKey(ByteString.copyFrom(masterKey))
.setBody(ByteString.copyFrom(toSendArray))
.setFlag(AddRequest.Flag.RECOVERY_ADD);
Request request = PerChannelBookieClient.appendRequestContext(Request.newBuilder())
.setHeader(headerBuilder)
.setAddRequest(addBuilder)
.build();
Object res = this.reqEnDeV3.encode(request, ByteBufAllocator.DEFAULT);
ReferenceCountUtil.release(res);
MDC.clear();
}
static Request.Builder appendRequestContextNoMdc(Request.Builder builder) {
final BookkeeperProtocol.ContextPair context1 = BookkeeperProtocol.ContextPair.newBuilder()
.setKey("parent_id")
.setValue("LetsPutSomeLongParentRequestIdHere")
.build();
builder.addRequestContext(context1);
final BookkeeperProtocol.ContextPair context2 = BookkeeperProtocol.ContextPair.newBuilder()
.setKey("request_id")
.setValue("LetsPutSomeLongRequestIdHere")
.build();
builder.addRequestContext(context2);
return builder;
}
@Benchmark
public void testAddEntryV3WithExtraContextDataNoMdc() throws Exception {
// Build the request and calculate the total size to be included in the packet.
BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder()
.setVersion(ProtocolVersion.VERSION_THREE)
.setOperation(OperationType.ADD_ENTRY)
.setTxnId(0L);
ByteBuf toSend = entry.slice();
byte[] toSendArray = new byte[toSend.readableBytes()];
toSend.getBytes(toSend.readerIndex(), toSendArray);
AddRequest.Builder addBuilder = AddRequest.newBuilder()
.setLedgerId(ledgerId)
.setEntryId(entryId)
.setMasterKey(ByteString.copyFrom(masterKey))
.setBody(ByteString.copyFrom(toSendArray))
.setFlag(AddRequest.Flag.RECOVERY_ADD);
Request request = appendRequestContextNoMdc(Request.newBuilder())
.setHeader(headerBuilder)
.setAddRequest(addBuilder)
.build();
Object res = this.reqEnDeV3.encode(request, ByteBufAllocator.DEFAULT);
ReferenceCountUtil.release(res);
}
}
| apache-2.0 |
FlxRobin/presto | presto-main/src/main/java/com/facebook/presto/sql/planner/plan/WindowNode.java | 4051 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.plan;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.spi.block.SortOrder;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.tree.FunctionCall;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import javax.annotation.concurrent.Immutable;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.concat;
@Immutable
public class WindowNode
extends PlanNode
{
private final PlanNode source;
private final List<Symbol> partitionBy;
private final List<Symbol> orderBy;
private final Map<Symbol, SortOrder> orderings;
private final Map<Symbol, FunctionCall> windowFunctions;
private final Map<Symbol, Signature> functionHandles;
@JsonCreator
public WindowNode(
@JsonProperty("id") PlanNodeId id,
@JsonProperty("source") PlanNode source,
@JsonProperty("partitionBy") List<Symbol> partitionBy,
@JsonProperty("orderBy") List<Symbol> orderBy,
@JsonProperty("orderings") Map<Symbol, SortOrder> orderings,
@JsonProperty("windowFunctions") Map<Symbol, FunctionCall> windowFunctions,
@JsonProperty("signatures") Map<Symbol, Signature> signatures)
{
super(id);
checkNotNull(source, "source is null");
checkNotNull(partitionBy, "partitionBy is null");
checkNotNull(orderBy, "orderBy is null");
checkArgument(orderings.size() == orderBy.size(), "orderBy and orderings sizes don't match");
checkNotNull(windowFunctions, "windowFunctions is null");
checkNotNull(signatures, "signatures is null");
checkArgument(windowFunctions.keySet().equals(signatures.keySet()), "windowFunctions does not match signatures");
this.source = source;
this.partitionBy = ImmutableList.copyOf(partitionBy);
this.orderBy = ImmutableList.copyOf(orderBy);
this.orderings = ImmutableMap.copyOf(orderings);
this.windowFunctions = ImmutableMap.copyOf(windowFunctions);
this.functionHandles = ImmutableMap.copyOf(signatures);
}
@Override
public List<PlanNode> getSources()
{
return ImmutableList.of(source);
}
@Override
public List<Symbol> getOutputSymbols()
{
return ImmutableList.copyOf(concat(source.getOutputSymbols(), windowFunctions.keySet()));
}
@JsonProperty
public PlanNode getSource()
{
return source;
}
@JsonProperty
public List<Symbol> getPartitionBy()
{
return partitionBy;
}
@JsonProperty
public List<Symbol> getOrderBy()
{
return orderBy;
}
@JsonProperty
public Map<Symbol, SortOrder> getOrderings()
{
return orderings;
}
@JsonProperty
public Map<Symbol, FunctionCall> getWindowFunctions()
{
return windowFunctions;
}
@JsonProperty
public Map<Symbol, Signature> getSignatures()
{
return functionHandles;
}
@Override
public <C, R> R accept(PlanVisitor<C, R> visitor, C context)
{
return visitor.visitWindow(this, context);
}
}
| apache-2.0 |
Jasig/NotificationPortlet | notification-portlet-webapp/src/main/java/org/jasig/portlet/notice/util/NotificationResponseFlattener.java | 3639 | /*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portlet.notice.util;
import org.jasig.portlet.notice.*;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* {@link INotificationService} beans return {@link NotificationResponse} objects, which are tree
* structures wherein notices are grouped by category. Most APIs and clients probably prefer
* notices in a list (often sorted). This utility provides a standard way to flatten a
* <code>NotificationResponse</code>.
*/
@Component
public class NotificationResponseFlattener {
public List<NotificationEntry> flatten(NotificationResponse response) {
// We will be modifying the entries to add the category since it will not be represented in the uncategorized list, so create a
// copy of the data if it is not already cloned.
final NotificationResponse clone = response.cloneIfNotCloned();
// Combine all categories into one list and create a category list. The category list will include categories that have no elements so
// it can be used for a consistent filtering interface if the data source provides a full list. (This is helpful for an interface such as
// student jobs where you always want the user to see a consistent list of all the categories for a category filter).
List<NotificationEntry> rslt = new ArrayList<>();
final Set<String> categoryList = new HashSet<>();
for (final NotificationCategory notificationCategory : clone.getCategories()) {
categoryList.add(notificationCategory.getTitle());
addAndCategorizeEntries(rslt, notificationCategory);
}
return rslt;
}
/*
* Implementation
*/
/**
* Add all entries from the notification category to the <code>allEntries</code> list after adding an attribute 'category' that contains
* the category. That allows UIs that want the convenience of an uncategorized list, such as dataTables, to obtain the data in a simple
* format that requires no additional processing but maintains the knowledge of the category of the entries.
*
* @param allEntries List of all entries
* @param notificationCategory <code>NotificationCategory</code> to add its entries to the <code>allEntries</code> list
*/
private void addAndCategorizeEntries(List<NotificationEntry> allEntries, NotificationCategory notificationCategory) {
for (NotificationEntry entry : notificationCategory.getEntries()) {
List<NotificationAttribute> attrs = new ArrayList<>(entry.getAttributes());
attrs.add(new NotificationAttribute("category", notificationCategory.getTitle()));
entry.setAttributes(attrs);
allEntries.add(entry);
}
}
}
| apache-2.0 |
ryoenji/libgdx | extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/Collision.java | 9158 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.10
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
public class Collision implements CollisionConstants {
/** Temporary Vector3 instance, used by native methods that return a Vector3 instance */
public final static Vector3 staticVector3 = new Vector3();
/** Pool of Vector3, used by native (callback) method for the arguments */
public final static com.badlogic.gdx.utils.Pool<Vector3> poolVector3 = new com.badlogic.gdx.utils.Pool<Vector3>() {
@Override
protected Vector3 newObject() {
return new Vector3();
}
};
/** Temporary Quaternion instance, used by native methods that return a Quaternion instance */
public final static Quaternion staticQuaternion = new Quaternion();
/** Pool of Quaternion, used by native (callback) method for the arguments */
public final static com.badlogic.gdx.utils.Pool<Quaternion> poolQuaternion = new com.badlogic.gdx.utils.Pool<Quaternion>() {
@Override
protected Quaternion newObject() {
return new Quaternion();
}
};
/** Temporary Matrix3 instance, used by native methods that return a Matrix3 instance */
public final static Matrix3 staticMatrix3 = new Matrix3();
/** Pool of Matrix3, used by native (callback) method for the arguments */
public final static com.badlogic.gdx.utils.Pool<Matrix3> poolMatrix3 = new com.badlogic.gdx.utils.Pool<Matrix3>() {
@Override
protected Matrix3 newObject() {
return new Matrix3();
}
};
/** Temporary Matrix4 instance, used by native methods that return a Matrix4 instance */
public final static Matrix4 staticMatrix4 = new Matrix4();
/** Pool of Matrix4, used by native (callback) method for the arguments */
public final static com.badlogic.gdx.utils.Pool<Matrix4> poolMatrix4 = new com.badlogic.gdx.utils.Pool<Matrix4>() {
@Override
protected Matrix4 newObject() {
return new Matrix4();
}
};
public static boolean Intersect(btDbvtAabbMm a, btDbvtAabbMm b) {
return CollisionJNI.Intersect__SWIG_0(btDbvtAabbMm.getCPtr(a), a, btDbvtAabbMm.getCPtr(b), b);
}
public static boolean Intersect(btDbvtAabbMm a, Vector3 b) {
return CollisionJNI.Intersect__SWIG_1(btDbvtAabbMm.getCPtr(a), a, b);
}
public static float Proximity(btDbvtAabbMm a, btDbvtAabbMm b) {
return CollisionJNI.Proximity(btDbvtAabbMm.getCPtr(a), a, btDbvtAabbMm.getCPtr(b), b);
}
public static int Select(btDbvtAabbMm o, btDbvtAabbMm a, btDbvtAabbMm b) {
return CollisionJNI.Select(btDbvtAabbMm.getCPtr(o), o, btDbvtAabbMm.getCPtr(a), a, btDbvtAabbMm.getCPtr(b), b);
}
public static void Merge(btDbvtAabbMm a, btDbvtAabbMm b, btDbvtAabbMm r) {
CollisionJNI.Merge(btDbvtAabbMm.getCPtr(a), a, btDbvtAabbMm.getCPtr(b), b, btDbvtAabbMm.getCPtr(r), r);
}
public static boolean NotEqual(btDbvtAabbMm a, btDbvtAabbMm b) {
return CollisionJNI.NotEqual(btDbvtAabbMm.getCPtr(a), a, btDbvtAabbMm.getCPtr(b), b);
}
public static void setGOverlappingPairs(int value) {
CollisionJNI.gOverlappingPairs_set(value);
}
public static int getGOverlappingPairs() {
return CollisionJNI.gOverlappingPairs_get();
}
public static void setGRemovePairs(int value) {
CollisionJNI.gRemovePairs_set(value);
}
public static int getGRemovePairs() {
return CollisionJNI.gRemovePairs_get();
}
public static void setGAddedPairs(int value) {
CollisionJNI.gAddedPairs_set(value);
}
public static int getGAddedPairs() {
return CollisionJNI.gAddedPairs_get();
}
public static void setGFindPairs(int value) {
CollisionJNI.gFindPairs_set(value);
}
public static int getGFindPairs() {
return CollisionJNI.gFindPairs_get();
}
public static int getBT_NULL_PAIR() {
return CollisionJNI.BT_NULL_PAIR_get();
}
public static boolean gdxCheckFilter(int filter, int flag) {
return CollisionJNI.gdxCheckFilter__SWIG_0(filter, flag);
}
public static boolean gdxCheckFilter(btCollisionObject colObj0, btCollisionObject colObj1) {
return CollisionJNI.gdxCheckFilter__SWIG_1(btCollisionObject.getCPtr(colObj0), colObj0, btCollisionObject.getCPtr(colObj1), colObj1);
}
public static void setGCompoundCompoundChildShapePairCallback(SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool value) {
CollisionJNI.gCompoundCompoundChildShapePairCallback_set(SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool.getCPtr(value));
}
public static SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool getGCompoundCompoundChildShapePairCallback() {
long cPtr = CollisionJNI.gCompoundCompoundChildShapePairCallback_get();
return (cPtr == 0) ? null : new SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool(cPtr, false);
}
public static void setGContactAddedCallback(SWIGTYPE_p_f_r_btManifoldPoint_p_q_const__btCollisionObjectWrapper_int_int_p_q_const__btCollisionObjectWrapper_int_int__bool value) {
CollisionJNI.gContactAddedCallback_set(SWIGTYPE_p_f_r_btManifoldPoint_p_q_const__btCollisionObjectWrapper_int_int_p_q_const__btCollisionObjectWrapper_int_int__bool.getCPtr(value));
}
public static SWIGTYPE_p_f_r_btManifoldPoint_p_q_const__btCollisionObjectWrapper_int_int_p_q_const__btCollisionObjectWrapper_int_int__bool getGContactAddedCallback() {
long cPtr = CollisionJNI.gContactAddedCallback_get();
return (cPtr == 0) ? null : new SWIGTYPE_p_f_r_btManifoldPoint_p_q_const__btCollisionObjectWrapper_int_int_p_q_const__btCollisionObjectWrapper_int_int__bool(cPtr, false);
}
public static int getBT_SIMPLE_NULL_PAIR() {
return CollisionJNI.BT_SIMPLE_NULL_PAIR_get();
}
public static void setGOverlappingSimplePairs(int value) {
CollisionJNI.gOverlappingSimplePairs_set(value);
}
public static int getGOverlappingSimplePairs() {
return CollisionJNI.gOverlappingSimplePairs_get();
}
public static void setGRemoveSimplePairs(int value) {
CollisionJNI.gRemoveSimplePairs_set(value);
}
public static int getGRemoveSimplePairs() {
return CollisionJNI.gRemoveSimplePairs_get();
}
public static void setGAddedSimplePairs(int value) {
CollisionJNI.gAddedSimplePairs_set(value);
}
public static int getGAddedSimplePairs() {
return CollisionJNI.gAddedSimplePairs_get();
}
public static void setGFindSimplePairs(int value) {
CollisionJNI.gFindSimplePairs_set(value);
}
public static int getGFindSimplePairs() {
return CollisionJNI.gFindSimplePairs_get();
}
public static void btGenerateInternalEdgeInfo(btBvhTriangleMeshShape trimeshShape, btTriangleInfoMap triangleInfoMap) {
CollisionJNI.btGenerateInternalEdgeInfo(btBvhTriangleMeshShape.getCPtr(trimeshShape), trimeshShape, btTriangleInfoMap.getCPtr(triangleInfoMap), triangleInfoMap);
}
public static void btAdjustInternalEdgeContacts(btManifoldPoint cp, btCollisionObjectWrapper trimeshColObj0Wrap, btCollisionObjectWrapper otherColObj1Wrap, int partId0, int index0, int normalAdjustFlags) {
CollisionJNI.btAdjustInternalEdgeContacts__SWIG_0(btManifoldPoint.getCPtr(cp), cp, btCollisionObjectWrapper.getCPtr(trimeshColObj0Wrap), trimeshColObj0Wrap, btCollisionObjectWrapper.getCPtr(otherColObj1Wrap), otherColObj1Wrap, partId0, index0, normalAdjustFlags);
}
public static void btAdjustInternalEdgeContacts(btManifoldPoint cp, btCollisionObjectWrapper trimeshColObj0Wrap, btCollisionObjectWrapper otherColObj1Wrap, int partId0, int index0) {
CollisionJNI.btAdjustInternalEdgeContacts__SWIG_1(btManifoldPoint.getCPtr(cp), cp, btCollisionObjectWrapper.getCPtr(trimeshColObj0Wrap), trimeshColObj0Wrap, btCollisionObjectWrapper.getCPtr(otherColObj1Wrap), otherColObj1Wrap, partId0, index0);
}
public static void setGCompoundChildShapePairCallback(SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool value) {
CollisionJNI.gCompoundChildShapePairCallback_set(SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool.getCPtr(value));
}
public static SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool getGCompoundChildShapePairCallback() {
long cPtr = CollisionJNI.gCompoundChildShapePairCallback_get();
return (cPtr == 0) ? null : new SWIGTYPE_p_f_p_q_const__btCollisionShape_p_q_const__btCollisionShape__bool(cPtr, false);
}
public static void setGContactBreakingThreshold(float value) {
CollisionJNI.gContactBreakingThreshold_set(value);
}
public static float getGContactBreakingThreshold() {
return CollisionJNI.gContactBreakingThreshold_get();
}
}
| apache-2.0 |
retomerz/intellij-community | platform/lang-impl/src/com/intellij/ui/ColorLineMarkerProvider.java | 4191 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.daemon.*;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ElementColorProvider;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.util.Function;
import com.intellij.util.FunctionUtil;
import com.intellij.util.ui.ColorIcon;
import com.intellij.util.ui.TwoColorsIcon;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public final class ColorLineMarkerProvider implements LineMarkerProvider {
private final ElementColorProvider[] myExtensions = ElementColorProvider.EP_NAME.getExtensions();
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) {
for (ElementColorProvider colorProvider : myExtensions) {
final Color color = colorProvider.getColorFrom(element);
if (color != null) {
MyInfo info = new MyInfo(element, color, colorProvider);
NavigateAction.setNavigateAction(info, "Choose color", null);
return info;
}
}
return null;
}
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> elements, @NotNull Collection<LineMarkerInfo> result) {
}
private static class MyInfo extends MergeableLineMarkerInfo<PsiElement> {
private final Color myColor;
public MyInfo(@NotNull final PsiElement element, final Color color, final ElementColorProvider colorProvider) {
super(element,
element.getTextRange(),
new ColorIcon(12, color),
Pass.UPDATE_ALL,
FunctionUtil.<Object, String>nullConstant(),
new GutterIconNavigationHandler<PsiElement>() {
@Override
public void navigate(MouseEvent e, PsiElement elt) {
if (!elt.isWritable()) return;
final Editor editor = PsiUtilBase.findEditor(element);
assert editor != null;
final Color c = ColorChooser.chooseColor(editor.getComponent(), "Choose Color", color, true);
if (c != null) {
AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(ColorLineMarkerProvider.class);
try {
colorProvider.setColorTo(element, c);
}
finally {
token.finish();
}
}
}
},
GutterIconRenderer.Alignment.LEFT);
myColor = color;
}
@Override
public boolean canMergeWith(@NotNull MergeableLineMarkerInfo<?> info) {
return info instanceof MyInfo;
}
@Override
public Icon getCommonIcon(@NotNull List<MergeableLineMarkerInfo> infos) {
if (infos.size() == 2 && infos.get(0) instanceof MyInfo && infos.get(1) instanceof MyInfo) {
return new TwoColorsIcon(12, ((MyInfo)infos.get(0)).myColor, ((MyInfo)infos.get(1)).myColor);
}
return AllIcons.Gutter.Colors;
}
@NotNull
@Override
public Function<? super PsiElement, String> getCommonTooltip(@NotNull List<MergeableLineMarkerInfo> infos) {
return FunctionUtil.nullConstant();
}
}
}
| apache-2.0 |
Minoli/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.core/src/main/java/org/wso2/carbon/apimgt/core/api/APIManager.java | 12762 | /*
*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.core.api;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.APIMgtDAOException;
import org.wso2.carbon.apimgt.core.models.API;
import org.wso2.carbon.apimgt.core.models.Application;
import org.wso2.carbon.apimgt.core.models.DedicatedGateway;
import org.wso2.carbon.apimgt.core.models.DocumentContent;
import org.wso2.carbon.apimgt.core.models.DocumentInfo;
import org.wso2.carbon.apimgt.core.models.Label;
import org.wso2.carbon.apimgt.core.models.Subscription;
import org.wso2.carbon.apimgt.core.workflow.Workflow;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
/**
* This interface mainly used to have the common methods to publisher and store
*/
public interface APIManager {
/**
* Returns details of an API
*
* @param uuid UUID of the API's registry artifact
* @return An API object related to the given artifact id or null
* @throws APIManagementException if failed get API from String
*/
API getAPIbyUUID(String uuid) throws APIManagementException;
/**
* Retrieves the last updated time of an API
*
* @param apiId UUID of API
* @return Last updated time of API given its uuid
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfAPI(String apiId) throws APIManagementException;
/**
* Retrieves the last updated time of the swagger definition of an API
*
* @param apiId UUID of API
* @return Last updated time of swagger definition of the API given its uuid
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfSwaggerDefinition(String apiId) throws APIManagementException;
/**
* Checks if a given API exists
*
* @param apiId UUID of the API
* @return boolean result
* @throws APIManagementException If failed to check ia API exist.
*/
boolean isAPIExists(String apiId) throws APIManagementException;
/**
* Checks whether the given API context is already registered in the system
*
* @param context A String representing an API context
* @return true if the context already exists and false otherwise
* @throws APIManagementException if failed to check the context availability
*/
boolean isContextExist(String context) throws APIManagementException;
/**
* Checks whether the given API name is already registered in the system
*
* @param apiName A String representing an API name
* @return true if the api name already exists and false otherwise
* @throws APIManagementException if failed to check the context availability
*/
boolean isApiNameExist(String apiName) throws APIManagementException;
/**
* Returns a set of API versions for the given provider and API name
*
* @param providerName name of the provider (common)
* @param apiName name of the api
* @return Set of version strings (possibly empty)
* @throws APIManagementException if failed to get version for api
*/
Set<String> getAPIVersions(String providerName, String apiName) throws APIManagementException;
/**
* Returns the swagger v2.0 definition as a string
*
* @param api id of the String
* @return swagger string
* @throws APIManagementException If failed to get swagger v2.0 definition
*/
String getApiSwaggerDefinition(String api) throws APIManagementException;
/**
* Returns a paginated list of documentation attached to a particular API
*
* @param apiId UUID of API
* @param offset The number of results from the beginning that is to be ignored
* @param limit The maximum number of results to be returned after the offset
* @return {@code List<DocumentInfo>} Document meta data list
* @throws APIManagementException if it failed to fetch Documentations
*/
List<DocumentInfo> getAllDocumentation(String apiId, int offset, int limit)
throws APIManagementException;
/**
* Get a summary of documentation by doc Id
*
* @param docId Document ID
* @return {@code DocumentInfo} Documentation meta data
* @throws APIManagementException if it failed to fetch Documentation
*/
DocumentInfo getDocumentationSummary(String docId) throws APIManagementException;
/**
* This method used to get the content of a documentation
*
* @param docId Document ID
* @return {@code DocumentContent} Input stream for document content
* @throws APIManagementException if the requested documentation content is not available
*/
DocumentContent getDocumentationContent(String docId) throws APIManagementException;
/**
* Returns the corresponding application given the uuid
*
* @param uuid uuid of the Application
* @param userId Name of the User.
* @return it will return Application corresponds to the uuid provided.
* @throws APIManagementException If failed to get application.
*/
Application getApplication(String uuid, String userId) throws APIManagementException;
/**
* Retrieves the last updated time of the subscription
*
* @param subscriptionId UUID of the subscription
* @return Last updated time of the resource
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfSubscription(String subscriptionId) throws APIManagementException;
/**
* Returns the subscriptions for api
* @param apiId UUID of the api
* @return List of subscription for the API.
* @throws APIManagementException If failed to retrieve subscriptions.
*/
List<Subscription> getSubscriptionsByAPI(String apiId) throws APIManagementException;
/**
* Return {@code Subscription} of subscription id
*
* @param subId Subscription ID
* @return Returns the subscription object
* @throws APIManagementException If failed to get subscription from UUID.
*/
Subscription getSubscriptionByUUID(String subId) throws APIManagementException;
/**
* Save the thumbnail icon for api
*
* @param apiId apiId of api
* @param inputStream inputStream of image
* @param dataType Data Type of image
* @throws APIManagementException If failed to save the thumbnail.
*/
void saveThumbnailImage(String apiId, InputStream inputStream, String dataType) throws APIManagementException;
/**
* Get the thumbnail icon for api
*
* @param apiId apiId of api
* @return thumbnail as a stream
* @throws APIManagementException If failed to retrieve the thumbnail.
*/
InputStream getThumbnailImage(String apiId) throws APIManagementException;
/**
*
* @param apiId UUID of API
* @return Last updated time of gateway configuration of the API given its uuid
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfGatewayConfig(String apiId) throws APIManagementException;
/**
* Retrieves the last updated time of a document of an API
*
* @param documentId UUID of document
* @return Last updated time of document given its uuid
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfDocument(String documentId) throws APIManagementException;
/**
* Retrieves the last updated time of the content of a document of an API
*
* @param apiId UUID of API
* @param documentId UUID of document
* @return Last updated time of document's content
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfDocumentContent(String apiId, String documentId) throws APIManagementException;
/**
* Retrieves the last updated time of the thumbnail image of an API
*
* @param apiId UUID of API
* @return Last updated time of document's content
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfAPIThumbnailImage(String apiId) throws APIManagementException;
/**
* Retrieves the last updated time of a throttling policy given its policy level and policy name
*
* @param policyLevel level of throttling policy
* @param policyName name of throttling policy
* @return last updated time
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel policyLevel, String policyName)
throws APIManagementException;
/**
* Retrieves the last updated time of the application
*
* @param applicationId UUID of the application
* @return Last updated time of the resource
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfApplication(String applicationId) throws APIManagementException;
/**
* Retrieves the last updated time of the comment
*
* @param commentId UUID of the comment
* @return Last updated time of the comment
* @throws APIManagementException if API Manager core level exception occurred
*/
String getLastUpdatedTimeOfComment(String commentId) throws APIManagementException;
/**
* Retrieve workflow for the given workflow reference ID
* @param workflowRefId External workflow reference Id
* @return Workflow workflow entry
* @throws APIManagementException if API Manager core level exception occurred
*/
Workflow retrieveWorkflow(String workflowRefId) throws APIManagementException;
/**
* Complete workflow task
* @param workflowExecutor executor related to the workflow task
* @param workflow workflow object
* @return WorkflowResponse WorkflowResponse of the executor
* @throws APIManagementException if API Manager core level exception occurred
*/
WorkflowResponse completeWorkflow(WorkflowExecutor workflowExecutor, Workflow workflow)
throws APIManagementException;
/**
* Retrieves Label information of the given label.
*
* @param labelID Label ID of the gateway
* @return {@code Label} Label information
* @throws APIManagementException if API Manager core level exception occurred
*/
Label getLabelByID(String labelID) throws APIManagementException;
/**
* Checks whether an WSDL archive exists for an API.
*
* @param apiId UUID of API
* @return true if an WSDL archive exists for an API
* @throws APIMgtDAOException If an error occurs while accessing data layer
*/
boolean isWSDLArchiveExists(String apiId) throws APIMgtDAOException;
/**
* Checks whether an WSDL exists for an API.
*
* @param apiId UUID of API
* @return true if an WSDL exists for an API
* @throws APIMgtDAOException If an error occurs while accessing data layer
*/
boolean isWSDLExists(String apiId) throws APIMgtDAOException;
/**
* Update DedicatedGateway of API
*
* @param dedicatedGateway updated DedicatedGatewayObject
* @throws APIManagementException If a core level exception occurs
*/
void updateDedicatedGateway(DedicatedGateway dedicatedGateway) throws APIManagementException;
/**
* Get Dedicated Gateway of API
*
* @param apiId of the API related to the Container Based Gateway
* @return Dedicated Gateway Object
* @throws APIManagementException if API Manager core level exception occurred
*
*/
DedicatedGateway getDedicatedGateway(String apiId) throws APIManagementException;
}
| apache-2.0 |
basepom/duplicate-finder-maven-plugin | src/main/java/org/basepom/mojo/duplicatefinder/artifact/MavenCoordinates.java | 7765 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.basepom.mojo.duplicatefinder.artifact;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.OverConstrainedVersionException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Dependency;
public class MavenCoordinates
{
private final String artifactId;
private final String groupId;
private final Optional<? extends ArtifactVersion> version;
private final Optional<VersionRange> versionRange;
private final String type;
private final Optional<String> classifier;
public MavenCoordinates(final Dependency dependency) throws InvalidVersionSpecificationException
{
checkNotNull(dependency, "dependency is null");
this.artifactId = checkNotNull(dependency.getArtifactId(), "artifactId for dependency '%s' is null", dependency);
this.groupId = checkNotNull(dependency.getGroupId(), "groupId for dependency '%s' is null", dependency);
final String version = dependency.getVersion();
this.version = version == null ? Optional.<ArtifactVersion>absent() : Optional.of(new DefaultArtifactVersion(version));
if (this.version.isPresent()) {
this.versionRange = Optional.of(VersionRange.createFromVersionSpec(version));
}
else {
this.versionRange = Optional.absent();
}
final String type = dependency.getType();
final String classifier = dependency.getClassifier();
if ("test-jar".equals(type)) {
this.classifier = Optional.of(MoreObjects.firstNonNull(classifier, "tests"));
this.type = "jar";
}
else {
this.type = MoreObjects.firstNonNull(type, "jar");
this.classifier = Optional.fromNullable(classifier);
}
}
public MavenCoordinates(final Artifact artifact) throws OverConstrainedVersionException
{
checkNotNull(artifact, "artifact is null");
this.artifactId = checkNotNull(artifact.getArtifactId(), "artifactId for artifact '%s' is null", artifact);
this.groupId = checkNotNull(artifact.getGroupId(), "groupId for artifact '%s' is null", artifact);
this.versionRange = Optional.fromNullable(artifact.getVersionRange());
if (this.versionRange.isPresent()) {
this.version = Optional.fromNullable(artifact.getSelectedVersion());
}
else {
final String version = artifact.getBaseVersion();
this.version = version == null ? Optional.<ArtifactVersion>absent() : Optional.of(new DefaultArtifactVersion(version));
}
final String type = artifact.getType();
final String classifier = artifact.getClassifier();
if ("test-jar".equals(type)) {
this.classifier = Optional.of(MoreObjects.firstNonNull(classifier, "tests"));
this.type = "jar";
}
else {
this.type = MoreObjects.firstNonNull(type, "jar");
this.classifier = Optional.fromNullable(classifier);
}
}
public String getArtifactId()
{
return artifactId;
}
public String getGroupId()
{
return groupId;
}
public Optional<? extends ArtifactVersion> getVersion()
{
return version;
}
public Optional<VersionRange> getVersionRange()
{
return versionRange;
}
public String getType()
{
return type;
}
public Optional<String> getClassifier()
{
return classifier;
}
public boolean matches(final Artifact artifact) throws OverConstrainedVersionException
{
return matches(new MavenCoordinates(artifact));
}
public boolean matches(final MavenCoordinates other)
{
if (!(Objects.equals(getGroupId(), other.getGroupId())
&& Objects.equals(getArtifactId(), other.getArtifactId())
&& Objects.equals(getType(), other.getType()))) {
return false;
}
// If a classifier is present, try to match the other classifier,
// otherwise, if no classifier is present, it matches all classifiers from the other MavenCoordinates.
if (getClassifier().isPresent()) {
if (!Objects.equals(getClassifier().get(), other.getClassifier().orNull())) {
return false;
}
}
// no version range and no version present, so any other version matches
if (!getVersionRange().isPresent() && !getVersion().isPresent()) {
return true;
}
// starting here, either a version or a version range is present
// other has no version. So there can be no match
if (!other.getVersion().isPresent()) {
return false;
}
// version range local and version in other
if (getVersionRange().isPresent()) {
// is there a recommended version?
final ArtifactVersion recommendedVersion = getVersionRange().get().getRecommendedVersion();
if (recommendedVersion != null) {
// Yes, then it must be matched.
return Objects.equals(recommendedVersion, other.getVersion().orNull());
}
// No, see if the other version is in the range
if (getVersionRange().get().containsVersion(other.getVersion().get())) {
return true;
}
}
// exact version match.
return Objects.equals(getVersion().orNull(), other.getVersion().orNull());
}
@Override
public int hashCode()
{
return Objects.hash(groupId, artifactId, classifier, type);
}
@Override
public boolean equals(final Object other)
{
if (other == null || other.getClass() != this.getClass()) {
return false;
}
if (other == this) {
return true;
}
MavenCoordinates that = (MavenCoordinates) other;
return Objects.equals(this.groupId, that.groupId)
&& Objects.equals(this.artifactId, that.artifactId)
&& Objects.equals(this.classifier, that.classifier)
&& Objects.equals(this.type, that.type);
}
@Override
public String toString()
{
final ImmutableList.Builder<String> builder = ImmutableList.builder();
builder.add(getGroupId());
builder.add(getArtifactId());
if (getVersion().isPresent()) {
builder.add(getVersion().get().toString());
}
else {
builder.add("<any>");
}
builder.add(getType());
builder.add(getClassifier().or("<any>"));
return Joiner.on(':').join(builder.build());
}
}
| apache-2.0 |
betfair/cougar | cougar-test/cougar-test-utils/src/main/java/com/betfair/testing/utils/cougar/misc/AbstractAggregatedMetaData.java | 2201 | /*
* Copyright 2013, The Sporting Exchange Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.betfair.testing.utils.cougar.misc;
import java.util.ArrayList;
import java.util.List;
/**
* Aggregates all Step Meta Data (eg a list of bets with parameters) into this object.
*
*/
public abstract class AbstractAggregatedMetaData {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractAggregatedMetaData other = (AbstractAggregatedMetaData) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
return true;
}
private List<StepMetaData> data = new ArrayList<StepMetaData>();
public void addMetaData(StepMetaData metaData) {
data.add(metaData);
}
public StepMetaData getMetaDataAtIndex(int x) {
return data.get(x);
}
public StepMetaData getMetaDataForKey(String key) throws RuntimeException {
for (StepMetaData metaData : data) {
if (metaData.getId().equals(key)) {
return metaData;
}
}
throw new RuntimeException("Unable to find meta data for key:" + key);
}
public List<StepMetaData> getData() {
return data;
}
public boolean isEmpty() {
return data.isEmpty();
}
public List<StepMetaData> getValues() {
return data;
}
public int size() {
return data.size();
}
public void setData(List<StepMetaData> data) {
this.data = data;
}
}
| apache-2.0 |
vthangathurai/SOA-Runtime | integration-tests/ProtoBufFindItemService/src/main/java/com/ebay/marketplace/search/v1/services/SellerLogoFieldValue.java | 2391 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-792
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.04.07 at 12:06:52 PM GMT+05:30
//
package com.ebay.marketplace.search.v1.services;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* This type contains aggregated information about
* seller logo.
*
*
* <p>Java class for SellerLogoFieldValue complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SellerLogoFieldValue">
* <complexContent>
* <extension base="{http://www.ebay.com/marketplace/search/v1/services}FieldValueBase">
* <sequence>
* <element name="imageUrl" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="imageType" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SellerLogoFieldValue", propOrder = {
"imageUrl",
"imageType"
})
public class SellerLogoFieldValue
extends FieldValueBase
{
@XmlElement(required = true)
protected String imageUrl;
protected int imageType;
/**
* Gets the value of the imageUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getImageUrl() {
return imageUrl;
}
/**
* Sets the value of the imageUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setImageUrl(String value) {
this.imageUrl = value;
}
/**
* Gets the value of the imageType property.
*
*/
public int getImageType() {
return imageType;
}
/**
* Sets the value of the imageType property.
*
*/
public void setImageType(int value) {
this.imageType = value;
}
}
| apache-2.0 |
EvilMcJerkface/kudu | java/kudu-client/src/test/java/org/apache/kudu/client/TestAuthnTokenReacquire.java | 5720 | // 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.kudu.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import static org.apache.kudu.util.ClientTestUtil.countRowsInScan;
import static org.apache.kudu.util.ClientTestUtil.createBasicSchemaInsert;
import static org.apache.kudu.util.ClientTestUtil.getBasicCreateTableOptions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
/**
* This test contains scenarios to verify that client re-acquires authn token upon expiration
* of the current one and automatically retries the call.
*/
public class TestAuthnTokenReacquire extends BaseKuduTest {
private static final String TABLE_NAME = "TestAuthnTokenReacquire-table";
private static final int TOKEN_TTL_SEC = 1;
private static final int OP_TIMEOUT_MS = 60 * TOKEN_TTL_SEC * 1000;
@Override
protected MiniKuduCluster.MiniKuduClusterBuilder getMiniClusterBuilder() {
// Inject additional INVALID_AUTHENTICATION_TOKEN responses from both the master and tablet
// servers, even for not-yet-expired tokens.
return super.getMiniClusterBuilder()
.enableKerberos()
.addMasterFlag(String.format("--authn_token_validity_seconds=%d", TOKEN_TTL_SEC))
.addMasterFlag("--rpc_inject_invalid_authn_token_ratio=0.5")
.addTserverFlag("--rpc_inject_invalid_authn_token_ratio=0.5");
}
private void dropConnections() {
for (Connection c : client.getConnectionListCopy()) {
c.disconnect();
}
}
private void dropConnectionsAndExpireToken() throws InterruptedException {
// Drop all connections from the client to Kudu servers.
dropConnections();
// Wait for authn token expiration.
Thread.sleep(TOKEN_TTL_SEC * 1000);
}
@Test
public void testBasicMasterOperations() throws Exception {
// To ratchet up the intensity a bit, run the scenario by several concurrent threads.
List<Thread> threads = new ArrayList<>();
final Map<Integer, Throwable> exceptions =
Collections.synchronizedMap(new HashMap<Integer, Throwable>());
for (int i = 0; i < 8; ++i) {
final int threadIdx = i;
Thread thread = new Thread(new Runnable() {
@Override
@SuppressWarnings("AssertionFailureIgnored")
public void run() {
final String tableName = "TestAuthnTokenReacquire-table-" + threadIdx;
try {
ListTabletServersResponse response = syncClient.listTabletServers();
assertNotNull(response);
dropConnectionsAndExpireToken();
ListTablesResponse tableList = syncClient.getTablesList(tableName);
assertNotNull(tableList);
assertTrue(tableList.getTablesList().isEmpty());
dropConnectionsAndExpireToken();
syncClient.createTable(tableName, basicSchema, getBasicCreateTableOptions());
dropConnectionsAndExpireToken();
KuduTable table = syncClient.openTable(tableName);
assertEquals(basicSchema.getColumnCount(), table.getSchema().getColumnCount());
dropConnectionsAndExpireToken();
syncClient.deleteTable(tableName);
assertFalse(syncClient.tableExists(tableName));
} catch (Throwable e) {
//noinspection ThrowableResultOfMethodCallIgnored
exceptions.put(threadIdx, e);
}
}
});
thread.run();
threads.add(thread);
}
for (Thread thread : threads) {
thread.join();
}
if (!exceptions.isEmpty()) {
for (Map.Entry<Integer, Throwable> e : exceptions.entrySet()) {
LOG.error("exception in thread {}: {}", e.getKey(), e.getValue());
}
fail("test failed: unexpected errors");
}
}
@Test
public void testBasicWorkflow() throws Exception {
KuduTable table = syncClient.createTable(TABLE_NAME, basicSchema,
getBasicCreateTableOptions());
dropConnectionsAndExpireToken();
KuduSession session = syncClient.newSession();
session.setTimeoutMillis(OP_TIMEOUT_MS);
session.apply(createBasicSchemaInsert(table, 1));
session.flush();
RowErrorsAndOverflowStatus errors = session.getPendingErrors();
assertFalse(errors.isOverflowed());
assertEquals(0, session.countPendingErrors());
dropConnectionsAndExpireToken();
KuduTable scanTable = syncClient.openTable(TABLE_NAME);
AsyncKuduScanner scanner = new AsyncKuduScanner.AsyncKuduScannerBuilder(client, scanTable)
.scanRequestTimeout(OP_TIMEOUT_MS)
.build();
assertEquals(1, countRowsInScan(scanner));
dropConnectionsAndExpireToken();
syncClient.deleteTable(TABLE_NAME);
assertFalse(syncClient.tableExists(TABLE_NAME));
}
}
| apache-2.0 |
sopel39/presto | presto-main/src/main/java/io/prestosql/sql/planner/optimizations/joins/JoinGraph.java | 12292 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.planner.optimizations.joins;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.iterative.GroupReference;
import io.prestosql.sql.planner.iterative.Lookup;
import io.prestosql.sql.planner.plan.FilterNode;
import io.prestosql.sql.planner.plan.JoinNode;
import io.prestosql.sql.planner.plan.PlanNode;
import io.prestosql.sql.planner.plan.PlanNodeId;
import io.prestosql.sql.planner.plan.PlanVisitor;
import io.prestosql.sql.planner.plan.ProjectNode;
import io.prestosql.sql.tree.Expression;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
/**
* JoinGraph represents sequence of Joins, where nodes in the graph
* are PlanNodes that are being joined and edges are all equality join
* conditions between pair of nodes.
*/
public class JoinGraph
{
private final Optional<Map<Symbol, Expression>> assignments;
private final List<Expression> filters;
private final List<PlanNode> nodes; // nodes in order of their appearance in tree plan (left, right, parent)
private final Multimap<PlanNodeId, Edge> edges;
private final PlanNodeId rootId;
/**
* Builds all (distinct) {@link JoinGraph}-es whole plan tree.
*/
public static List<JoinGraph> buildFrom(PlanNode plan)
{
return buildFrom(plan, Lookup.noLookup());
}
/**
* Builds {@link JoinGraph} containing {@code plan} node.
*/
public static JoinGraph buildShallowFrom(PlanNode plan, Lookup lookup)
{
JoinGraph graph = plan.accept(new Builder(true, lookup), new Context());
return graph;
}
private static List<JoinGraph> buildFrom(PlanNode plan, Lookup lookup)
{
Context context = new Context();
JoinGraph graph = plan.accept(new Builder(false, lookup), context);
if (graph.size() > 1) {
context.addSubGraph(graph);
}
return context.getGraphs();
}
public JoinGraph(PlanNode node)
{
this(ImmutableList.of(node), ImmutableMultimap.of(), node.getId(), ImmutableList.of(), Optional.empty());
}
public JoinGraph(
List<PlanNode> nodes,
Multimap<PlanNodeId, Edge> edges,
PlanNodeId rootId,
List<Expression> filters,
Optional<Map<Symbol, Expression>> assignments)
{
this.nodes = nodes;
this.edges = edges;
this.rootId = rootId;
this.filters = filters;
this.assignments = assignments;
}
public JoinGraph withAssignments(Map<Symbol, Expression> assignments)
{
return new JoinGraph(nodes, edges, rootId, filters, Optional.of(assignments));
}
public Optional<Map<Symbol, Expression>> getAssignments()
{
return assignments;
}
public JoinGraph withFilter(Expression expression)
{
ImmutableList.Builder<Expression> filters = ImmutableList.builder();
filters.addAll(this.filters);
filters.add(expression);
return new JoinGraph(nodes, edges, rootId, filters.build(), assignments);
}
public List<Expression> getFilters()
{
return filters;
}
public PlanNodeId getRootId()
{
return rootId;
}
public JoinGraph withRootId(PlanNodeId rootId)
{
return new JoinGraph(nodes, edges, rootId, filters, assignments);
}
public boolean isEmpty()
{
return nodes.isEmpty();
}
public int size()
{
return nodes.size();
}
public PlanNode getNode(int index)
{
return nodes.get(index);
}
public List<PlanNode> getNodes()
{
return nodes;
}
public Collection<Edge> getEdges(PlanNode node)
{
return ImmutableList.copyOf(edges.get(node.getId()));
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
for (PlanNode nodeFrom : nodes) {
builder.append(nodeFrom.getId())
.append(" = ")
.append(nodeFrom.toString())
.append("\n");
}
for (PlanNode nodeFrom : nodes) {
builder.append(nodeFrom.getId())
.append(":");
for (Edge nodeTo : edges.get(nodeFrom.getId())) {
builder.append(" ").append(nodeTo.getTargetNode().getId());
}
builder.append("\n");
}
return builder.toString();
}
private JoinGraph joinWith(JoinGraph other, List<JoinNode.EquiJoinClause> joinClauses, Context context, PlanNodeId newRoot)
{
for (PlanNode node : other.nodes) {
checkState(!edges.containsKey(node.getId()), format("Node [%s] appeared in two JoinGraphs", node));
}
List<PlanNode> nodes = ImmutableList.<PlanNode>builder()
.addAll(this.nodes)
.addAll(other.nodes)
.build();
ImmutableMultimap.Builder<PlanNodeId, Edge> edges = ImmutableMultimap.<PlanNodeId, Edge>builder()
.putAll(this.edges)
.putAll(other.edges);
List<Expression> joinedFilters = ImmutableList.<Expression>builder()
.addAll(this.filters)
.addAll(other.filters)
.build();
for (JoinNode.EquiJoinClause edge : joinClauses) {
Symbol leftSymbol = edge.getLeft();
Symbol rightSymbol = edge.getRight();
checkState(context.containsSymbol(leftSymbol));
checkState(context.containsSymbol(rightSymbol));
PlanNode left = context.getSymbolSource(leftSymbol);
PlanNode right = context.getSymbolSource(rightSymbol);
edges.put(left.getId(), new Edge(right, leftSymbol, rightSymbol));
edges.put(right.getId(), new Edge(left, rightSymbol, leftSymbol));
}
return new JoinGraph(nodes, edges.build(), newRoot, joinedFilters, Optional.empty());
}
private static class Builder
extends PlanVisitor<JoinGraph, Context>
{
// TODO When io.prestosql.sql.planner.optimizations.EliminateCrossJoins is removed, remove 'shallow' flag
private final boolean shallow;
private final Lookup lookup;
private Builder(boolean shallow, Lookup lookup)
{
this.shallow = shallow;
this.lookup = requireNonNull(lookup, "lookup cannot be null");
}
@Override
protected JoinGraph visitPlan(PlanNode node, Context context)
{
if (!shallow) {
for (PlanNode child : node.getSources()) {
JoinGraph graph = child.accept(this, context);
if (graph.size() < 2) {
continue;
}
context.addSubGraph(graph.withRootId(child.getId()));
}
}
for (Symbol symbol : node.getOutputSymbols()) {
context.setSymbolSource(symbol, node);
}
return new JoinGraph(node);
}
@Override
public JoinGraph visitFilter(FilterNode node, Context context)
{
JoinGraph graph = node.getSource().accept(this, context);
return graph.withFilter(node.getPredicate());
}
@Override
public JoinGraph visitJoin(JoinNode node, Context context)
{
//TODO: add support for non inner joins
if (node.getType() != INNER) {
return visitPlan(node, context);
}
JoinGraph left = node.getLeft().accept(this, context);
JoinGraph right = node.getRight().accept(this, context);
JoinGraph graph = left.joinWith(right, node.getCriteria(), context, node.getId());
if (node.getFilter().isPresent()) {
return graph.withFilter(node.getFilter().get());
}
return graph;
}
@Override
public JoinGraph visitProject(ProjectNode node, Context context)
{
if (node.isIdentity()) {
JoinGraph graph = node.getSource().accept(this, context);
return graph.withAssignments(node.getAssignments().getMap());
}
return visitPlan(node, context);
}
@Override
public JoinGraph visitGroupReference(GroupReference node, Context context)
{
PlanNode dereferenced = lookup.resolve(node);
JoinGraph graph = dereferenced.accept(this, context);
if (isTrivialGraph(graph)) {
return replacementGraph(dereferenced, node, context);
}
return graph;
}
private boolean isTrivialGraph(JoinGraph graph)
{
return graph.nodes.size() < 2 && graph.edges.isEmpty() && graph.filters.isEmpty() && !graph.assignments.isPresent();
}
private JoinGraph replacementGraph(PlanNode oldNode, PlanNode newNode, Context context)
{
// TODO optimize when idea is generally approved
List<Symbol> symbols = context.symbolSources.entrySet().stream()
.filter(entry -> entry.getValue() == oldNode)
.map(Map.Entry::getKey)
.collect(toImmutableList());
symbols.forEach(symbol -> context.symbolSources.put(symbol, newNode));
return new JoinGraph(newNode);
}
}
public static class Edge
{
private final PlanNode targetNode;
private final Symbol sourceSymbol;
private final Symbol targetSymbol;
public Edge(PlanNode targetNode, Symbol sourceSymbol, Symbol targetSymbol)
{
this.targetNode = requireNonNull(targetNode, "targetNode is null");
this.sourceSymbol = requireNonNull(sourceSymbol, "sourceSymbol is null");
this.targetSymbol = requireNonNull(targetSymbol, "targetSymbol is null");
}
public PlanNode getTargetNode()
{
return targetNode;
}
public Symbol getSourceSymbol()
{
return sourceSymbol;
}
public Symbol getTargetSymbol()
{
return targetSymbol;
}
}
private static class Context
{
private final Map<Symbol, PlanNode> symbolSources = new HashMap<>();
// TODO When io.prestosql.sql.planner.optimizations.EliminateCrossJoins is removed, remove 'joinGraphs'
private final List<JoinGraph> joinGraphs = new ArrayList<>();
public void setSymbolSource(Symbol symbol, PlanNode node)
{
symbolSources.put(symbol, node);
}
public void addSubGraph(JoinGraph graph)
{
joinGraphs.add(graph);
}
public boolean containsSymbol(Symbol symbol)
{
return symbolSources.containsKey(symbol);
}
public PlanNode getSymbolSource(Symbol symbol)
{
checkState(containsSymbol(symbol));
return symbolSources.get(symbol);
}
public List<JoinGraph> getGraphs()
{
return joinGraphs;
}
}
}
| apache-2.0 |
eSDK/esdk_cloud_fc_native_java | source/src/main/java/com/huawei/esdk/fusioncompute/local/model/site/SiteBasicInfo.java | 1778 | package com.huawei.esdk.fusioncompute.local.model.site;
/**
*
* 站点基本信息。
* <p>
* @since eSDK Cloud V100R003C50
*/
public class SiteBasicInfo
{
/**
* 站点标识
*/
private String urn;
/**
* 站点uri
*/
private String uri;
/**
* 名称
*/
private String name;
/**
* 站点IP
*/
private String ip;
/**
* 是否是域控制器
*/
private Boolean isDC;
/**
* 是否是当前站点
*/
private Boolean isSelf;
/**
* vrm状态:<br>
* joining, 加入域中<br>
* exiting, 退出域中<br>
* normal,正常<br>
* fault, 故障<br>
*/
private String status;
public String getUrn()
{
return urn;
}
public void setUrn(String urn)
{
this.urn = urn;
}
public String getUri()
{
return uri;
}
public void setUri(String uri)
{
this.uri = uri;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getIp()
{
return ip;
}
public void setIp(String ip)
{
this.ip = ip;
}
public Boolean getIsDC()
{
return isDC;
}
public void setIsDC(Boolean isDC)
{
this.isDC = isDC;
}
public Boolean getIsSelf()
{
return isSelf;
}
public void setIsSelf(Boolean isSelf)
{
this.isSelf = isSelf;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
}
| apache-2.0 |
shefansxyh/eap | eap/eap.comps.vcode/src/main/java/eap/comps/vcode/VcodeManager.java | 2189 | package eap.comps.vcode;
import java.awt.image.BufferedImage;
import javax.servlet.http.HttpSession;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import eap.EapContext;
import eap.Env;
import eap.util.PropertiesUtil;
import eap.util.StringUtil;
/**
* <p> Title: </p>
* <p> Description: </p>
* @作者 chiknin@gmail.com
* @创建时间
* @版本 1.00
* @修改记录
* <pre>
* 版本 修改人 修改时间 修改内容描述
* ----------------------------------------
*
* ----------------------------------------
* </pre>
*/
public class VcodeManager {
public static final String SESSION_VCODE_KEY = "__vcode";
private static DefaultKaptcha vcodeProducer;
public static String createText() {
return getVcodeProducer().createText();
}
public static BufferedImage createImage() {
return getVcodeProducer().createImage(createText());
}
public static BufferedImage createImage(String text) {
return getVcodeProducer().createImage(text);
}
public static BufferedImage createImage(String text, HttpSession session) {
BufferedImage img = getVcodeProducer().createImage(text);
session.setAttribute(SESSION_VCODE_KEY, text);
return img;
}
public static boolean isValid(String text, HttpSession session) {
if (StringUtil.isBlank(text)) {
return false;
}
return text.equalsIgnoreCase((String)session.getAttribute(SESSION_VCODE_KEY));
}
public static boolean pass(String text, HttpSession session) {
boolean result = isValid(text, session);
if (result) {
session.removeAttribute(SESSION_VCODE_KEY);
}
return result;
}
private static Producer getVcodeProducer() {
if (vcodeProducer == null) {
Env env = EapContext.getEnv();
vcodeProducer = new DefaultKaptcha();
vcodeProducer.setConfig(new Config(PropertiesUtil.from(env.filterForPrefix("vcode.config."))));
}
return vcodeProducer;
}
public static void main(String[] args) {
String text = createText();
System.out.println(text);
}
}
| apache-2.0 |
keshin/RTran | rtran-api/src/main/java/com/ebay/rtran/api/IProjectCtx.java | 717 | /*
* Copyright (c) 2016 eBay Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ebay.rtran.api;
import java.io.File;
public interface IProjectCtx {
File rootDir();
}
| apache-2.0 |
b-slim/hive | serde/src/java/org/apache/hadoop/hive/serde2/binarysortable/fast/BinarySortableDeserializeRead.java | 22889 | /*
* 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.hadoop.hive.serde2.binarysortable.fast;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.UnionTypeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.serde2.binarysortable.BinarySortableSerDe;
import org.apache.hadoop.hive.serde2.binarysortable.InputByteBuffer;
import org.apache.hadoop.hive.serde2.fast.DeserializeRead;
import org.apache.hadoop.hive.serde2.io.TimestampWritableV2;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
/*
* Directly deserialize with the caller reading field-by-field the LazyBinary serialization format.
*
* The caller is responsible for calling the read method for the right type of each field
* (after calling readNextField).
*
* Reading some fields require a results object to receive value information. A separate
* results object is created by the caller at initialization per different field even for the same
* type.
*
* Some type values are by reference to either bytes in the deserialization buffer or to
* other type specific buffers. So, those references are only valid until the next time set is
* called.
*/
public final class BinarySortableDeserializeRead extends DeserializeRead {
public static final Logger LOG = LoggerFactory.getLogger(BinarySortableDeserializeRead.class.getName());
// The sort order (ascending/descending) for each field. Set to true when descending (invert).
private boolean[] columnSortOrderIsDesc;
byte[] columnNullMarker;
byte[] columnNotNullMarker;
private int start;
private int end;
private int fieldStart;
private int bytesStart;
private int internalBufferLen;
private byte[] internalBuffer;
private byte[] tempTimestampBytes;
private byte[] tempDecimalBuffer;
private InputByteBuffer inputByteBuffer = new InputByteBuffer();
private Field root;
private Deque<Field> stack;
private class Field {
Field[] children;
Category category;
PrimitiveObjectInspector.PrimitiveCategory primitiveCategory;
TypeInfo typeInfo;
int index;
int count;
int start;
int tag;
}
/*
* Use this constructor when only ascending sort order is used.
*/
public BinarySortableDeserializeRead(TypeInfo[] typeInfos, boolean useExternalBuffer) {
this(typeInfos, useExternalBuffer, null, null, null);
}
public BinarySortableDeserializeRead(TypeInfo[] typeInfos, boolean useExternalBuffer,
boolean[] columnSortOrderIsDesc, byte[] columnNullMarker, byte[] columnNotNullMarker) {
super(typeInfos, useExternalBuffer);
final int count = typeInfos.length;
root = new Field();
root.category = Category.STRUCT;
root.children = createFields(typeInfos);
root.count = count;
stack = new ArrayDeque<>();
if (columnSortOrderIsDesc != null) {
this.columnSortOrderIsDesc = columnSortOrderIsDesc;
} else {
this.columnSortOrderIsDesc = new boolean[count];
Arrays.fill(this.columnSortOrderIsDesc, false);
}
if (columnNullMarker != null) {
this.columnNullMarker = columnNullMarker;
this.columnNotNullMarker = columnNotNullMarker;
} else {
this.columnNullMarker = new byte[count];
this.columnNotNullMarker = new byte[count];
for (int i = 0; i < count; i++) {
if (this.columnSortOrderIsDesc[i]) {
// Descending
// Null last (default for descending order)
this.columnNullMarker[i] = BinarySortableSerDe.ZERO;
this.columnNotNullMarker[i] = BinarySortableSerDe.ONE;
} else {
// Ascending
// Null first (default for ascending order)
this.columnNullMarker[i] = BinarySortableSerDe.ZERO;
this.columnNotNullMarker[i] = BinarySortableSerDe.ONE;
}
}
}
inputByteBuffer = new InputByteBuffer();
internalBufferLen = -1;
}
// Not public since we must have column information.
private BinarySortableDeserializeRead() {
super();
}
/*
* Set the range of bytes to be deserialized.
*/
@Override
public void set(byte[] bytes, int offset, int length) {
start = offset;
end = offset + length;
inputByteBuffer.reset(bytes, start, end);
root.index = -1;
stack.clear();
stack.push(root);
clearIndex(root);
}
private void clearIndex(Field field) {
field.index = -1;
if (field.children == null) {
return;
}
for (Field child : field.children) {
clearIndex(child);
}
}
/*
* Get detailed read position information to help diagnose exceptions.
*/
public String getDetailedReadPositionString() {
StringBuilder sb = new StringBuilder(64);
sb.append("Reading inputByteBuffer of length ");
sb.append(inputByteBuffer.getEnd());
sb.append(" at start offset ");
sb.append(start);
sb.append(" for length ");
sb.append(end - start);
sb.append(" to read ");
sb.append(root.count);
sb.append(" fields with types ");
sb.append(Arrays.toString(typeInfos));
sb.append(". ");
if (root.index == -1) {
sb.append("Before first field?");
} else {
sb.append("Read field #");
sb.append(root.index);
sb.append(" at field start position ");
sb.append(fieldStart);
sb.append(" current read offset ");
sb.append(inputByteBuffer.tell());
}
sb.append(" column sort order ");
sb.append(Arrays.toString(columnSortOrderIsDesc));
// UNDONE: Convert byte 0 or 1 to character.
sb.append(" column null marker ");
sb.append(Arrays.toString(columnNullMarker));
sb.append(" column non null marker ");
sb.append(Arrays.toString(columnNotNullMarker));
return sb.toString();
}
/*
* Reads the the next field.
*
* Afterwards, reading is positioned to the next field.
*
* @return Return true when the field was not null and data is put in the appropriate
* current* member.
* Otherwise, false when the field is null.
*
*/
@Override
public boolean readNextField() throws IOException {
return readComplexField();
}
private boolean readPrimitive(Field field) throws IOException {
final int fieldIndex = root.index;
field.start = inputByteBuffer.tell();
/*
* We have a field and are positioned to it. Read it.
*/
switch (field.primitiveCategory) {
case BOOLEAN:
currentBoolean = (inputByteBuffer.read(columnSortOrderIsDesc[fieldIndex]) == 2);
return true;
case BYTE:
currentByte = (byte) (inputByteBuffer.read(columnSortOrderIsDesc[fieldIndex]) ^ 0x80);
return true;
case SHORT:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
int v = inputByteBuffer.read(invert) ^ 0x80;
v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
currentShort = (short) v;
}
return true;
case INT:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
int v = inputByteBuffer.read(invert) ^ 0x80;
for (int i = 0; i < 3; i++) {
v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
}
currentInt = v;
}
return true;
case LONG:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
long v = inputByteBuffer.read(invert) ^ 0x80;
for (int i = 0; i < 7; i++) {
v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
}
currentLong = v;
}
return true;
case DATE:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
int v = inputByteBuffer.read(invert) ^ 0x80;
for (int i = 0; i < 3; i++) {
v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
}
currentDateWritable.set(v);
}
return true;
case TIMESTAMP:
{
if (tempTimestampBytes == null) {
tempTimestampBytes = new byte[TimestampWritableV2.BINARY_SORTABLE_LENGTH];
}
final boolean invert = columnSortOrderIsDesc[fieldIndex];
for (int i = 0; i < tempTimestampBytes.length; i++) {
tempTimestampBytes[i] = inputByteBuffer.read(invert);
}
currentTimestampWritable.setBinarySortable(tempTimestampBytes, 0);
}
return true;
case FLOAT:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
int v = 0;
for (int i = 0; i < 4; i++) {
v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
}
if ((v & (1 << 31)) == 0) {
// negative number, flip all bits
v = ~v;
} else {
// positive number, flip the first bit
v = v ^ (1 << 31);
}
currentFloat = Float.intBitsToFloat(v);
}
return true;
case DOUBLE:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
long v = 0;
for (int i = 0; i < 8; i++) {
v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
}
if ((v & (1L << 63)) == 0) {
// negative number, flip all bits
v = ~v;
} else {
// positive number, flip the first bit
v = v ^ (1L << 63);
}
currentDouble = Double.longBitsToDouble(v);
}
return true;
case BINARY:
case STRING:
case CHAR:
case VARCHAR:
{
/*
* This code is a modified version of BinarySortableSerDe.deserializeText that lets us
* detect if we can return a reference to the bytes directly.
*/
// Get the actual length first
bytesStart = inputByteBuffer.tell();
final boolean invert = columnSortOrderIsDesc[fieldIndex];
int length = 0;
do {
byte b = inputByteBuffer.read(invert);
if (b == 0) {
// end of string
break;
}
if (b == 1) {
// the last char is an escape char. read the actual char
inputByteBuffer.read(invert);
}
length++;
} while (true);
if (length == 0 ||
(!invert && length == inputByteBuffer.tell() - bytesStart - 1)) {
// No inversion or escaping happened, so we are can reference directly.
currentExternalBufferNeeded = false;
currentBytes = inputByteBuffer.getData();
currentBytesStart = bytesStart;
currentBytesLength = length;
} else {
// We are now positioned at the end of this field's bytes.
if (useExternalBuffer) {
// If we decided not to reposition and re-read the buffer to copy it with
// copyToExternalBuffer, we we will still be correctly positioned for the next field.
currentExternalBufferNeeded = true;
currentExternalBufferNeededLen = length;
} else {
// The copyToBuffer will reposition and re-read the input buffer.
currentExternalBufferNeeded = false;
if (internalBufferLen < length) {
internalBufferLen = length;
internalBuffer = new byte[internalBufferLen];
}
copyToBuffer(internalBuffer, 0, length);
currentBytes = internalBuffer;
currentBytesStart = 0;
currentBytesLength = length;
}
}
}
return true;
case INTERVAL_YEAR_MONTH:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
int v = inputByteBuffer.read(invert) ^ 0x80;
for (int i = 0; i < 3; i++) {
v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
}
currentHiveIntervalYearMonthWritable.set(v);
}
return true;
case INTERVAL_DAY_TIME:
{
final boolean invert = columnSortOrderIsDesc[fieldIndex];
long totalSecs = inputByteBuffer.read(invert) ^ 0x80;
for (int i = 0; i < 7; i++) {
totalSecs = (totalSecs << 8) + (inputByteBuffer.read(invert) & 0xff);
}
int nanos = inputByteBuffer.read(invert) ^ 0x80;
for (int i = 0; i < 3; i++) {
nanos = (nanos << 8) + (inputByteBuffer.read(invert) & 0xff);
}
currentHiveIntervalDayTimeWritable.set(totalSecs, nanos);
}
return true;
case DECIMAL:
{
// Since enforcing precision and scale can cause a HiveDecimal to become NULL,
// we must read it, enforce it here, and either return NULL or buffer the result.
final boolean invert = columnSortOrderIsDesc[fieldIndex];
int b = inputByteBuffer.read(invert) - 1;
if (!(b == 1 || b == -1 || b == 0)) {
throw new IOException("Unexpected byte value " + (int)b + " in binary sortable format data (invert " + invert + ")");
}
final boolean positive = b != -1;
int factor = inputByteBuffer.read(invert) ^ 0x80;
for (int i = 0; i < 3; i++) {
factor = (factor << 8) + (inputByteBuffer.read(invert) & 0xff);
}
if (!positive) {
factor = -factor;
}
final int decimalStart = inputByteBuffer.tell();
int length = 0;
do {
b = inputByteBuffer.read(positive ? invert : !invert);
if (b == 1) {
throw new IOException("Expected -1 and found byte value " + (int)b + " in binary sortable format data (invert " + invert + ")");
}
if (b == 0) {
// end of digits
break;
}
length++;
} while (true);
// CONSIDER: Allocate a larger initial size.
if(tempDecimalBuffer == null || tempDecimalBuffer.length < length) {
tempDecimalBuffer = new byte[length];
}
inputByteBuffer.seek(decimalStart);
for (int i = 0; i < length; ++i) {
tempDecimalBuffer[i] = inputByteBuffer.read(positive ? invert : !invert);
}
// read the null byte again
inputByteBuffer.read(positive ? invert : !invert);
// Set the value of the writable from the decimal digits that were written with no dot.
final int scale = length - factor;
currentHiveDecimalWritable.setFromDigitsOnlyBytesWithScale(
!positive, tempDecimalBuffer, 0, length, scale);
boolean decimalIsNull = !currentHiveDecimalWritable.isSet();
if (!decimalIsNull) {
// We have a decimal. After we enforce precision and scale, will it become a NULL?
final DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) field.typeInfo;
final int enforcePrecision = decimalTypeInfo.getPrecision();
final int enforceScale = decimalTypeInfo.getScale();
decimalIsNull =
!currentHiveDecimalWritable.mutateEnforcePrecisionScale(
enforcePrecision, enforceScale);
}
if (decimalIsNull) {
return false;
}
}
return true;
default:
throw new RuntimeException("Unexpected primitive type category " + field.primitiveCategory);
}
}
/*
* Reads through an undesired field.
*
* No data values are valid after this call.
* Designed for skipping columns that are not included.
*/
public void skipNextField() throws IOException {
final Field current = stack.peek();
current.index++;
if (root.index >= root.count) {
return;
}
if (inputByteBuffer.isEof()) {
// Also, reading beyond our byte range produces NULL.
return;
}
if (current.category == Category.UNION && current.index == 0) {
current.tag = inputByteBuffer.read();
currentInt = current.tag;
return;
}
final Field child = getChild(current);
if (isNull()) {
return;
}
if (child.category == Category.PRIMITIVE) {
readPrimitive(child);
} else {
stack.push(child);
switch (child.category) {
case LIST:
case MAP:
while (isNextComplexMultiValue()) {
skipNextField();
}
break;
case STRUCT:
for (int i = 0; i < child.count; i++) {
skipNextField();
}
finishComplexVariableFieldsType();
break;
case UNION:
readComplexField();
skipNextField();
finishComplexVariableFieldsType();
break;
}
}
}
@Override
public void copyToExternalBuffer(byte[] externalBuffer, int externalBufferStart) throws IOException {
copyToBuffer(externalBuffer, externalBufferStart, currentExternalBufferNeededLen);
}
private void copyToBuffer(byte[] buffer, int bufferStart, int bufferLength) throws IOException {
final boolean invert = columnSortOrderIsDesc[root.index];
inputByteBuffer.seek(bytesStart);
// 3. Copy the data.
for (int i = 0; i < bufferLength; i++) {
byte b = inputByteBuffer.read(invert);
if (b == 1) {
// The last char is an escape char, read the actual char.
// The serialization format escape \0 to \1, and \1 to \2,
// to make sure the string is null-terminated.
b = (byte) (inputByteBuffer.read(invert) - 1);
}
buffer[bufferStart + i] = b;
}
// 4. Read the null terminator.
byte b = inputByteBuffer.read(invert);
if (b != 0) {
throw new RuntimeException("Expected 0 terminating byte");
}
}
/*
* Call this method may be called after all the all fields have been read to check
* for unread fields.
*
* Note that when optimizing reading to stop reading unneeded include columns, worrying
* about whether all data is consumed is not appropriate (often we aren't reading it all by
* design).
*
* Since LazySimpleDeserializeRead parses the line through the last desired column it does
* support this function.
*/
public boolean isEndOfInputReached() {
return inputByteBuffer.isEof();
}
private Field[] createFields(TypeInfo[] typeInfos) {
final Field[] children = new Field[typeInfos.length];
for (int i = 0; i < typeInfos.length; i++) {
children[i] = createField(typeInfos[i]);
}
return children;
}
private Field createField(TypeInfo typeInfo) {
final Field field = new Field();
final Category category = typeInfo.getCategory();
field.category = category;
field.typeInfo = typeInfo;
switch (category) {
case PRIMITIVE:
field.primitiveCategory = ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory();
break;
case LIST:
field.children = new Field[1];
field.children[0] = createField(((ListTypeInfo) typeInfo).getListElementTypeInfo());
break;
case MAP:
field.children = new Field[2];
field.children[0] = createField(((MapTypeInfo) typeInfo).getMapKeyTypeInfo());
field.children[1] = createField(((MapTypeInfo) typeInfo).getMapValueTypeInfo());
break;
case STRUCT:
StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;
List<TypeInfo> fieldTypeInfos = structTypeInfo.getAllStructFieldTypeInfos();
field.count = fieldTypeInfos.size();
field.children = createFields(fieldTypeInfos.toArray(new TypeInfo[fieldTypeInfos.size()]));
break;
case UNION:
UnionTypeInfo unionTypeInfo = (UnionTypeInfo) typeInfo;
List<TypeInfo> objectTypeInfos = unionTypeInfo.getAllUnionObjectTypeInfos();
field.count = 2;
field.children = createFields(objectTypeInfos.toArray(new TypeInfo[objectTypeInfos.size()]));
break;
default:
throw new RuntimeException();
}
return field;
}
private Field getChild(Field field) {
switch (field.category) {
case LIST:
return field.children[0];
case MAP:
return field.children[field.index % 2];
case STRUCT:
return field.children[field.index];
case UNION:
return field.children[field.tag];
default:
throw new RuntimeException();
}
}
private boolean isNull() throws IOException {
return inputByteBuffer.read(columnSortOrderIsDesc[root.index]) ==
columnNullMarker[root.index];
}
@Override
public boolean readComplexField() throws IOException {
final Field current = stack.peek();
current.index++;
if (root.index >= root.count) {
return false;
}
if (inputByteBuffer.isEof()) {
// Also, reading beyond our byte range produces NULL.
return false;
}
if (current.category == Category.UNION) {
if (current.index == 0) {
current.tag = inputByteBuffer.read(columnSortOrderIsDesc[root.index]);
currentInt = current.tag;
return true;
}
}
final Field child = getChild(current);
boolean isNull = isNull();
if (isNull) {
return false;
}
if (child.category == Category.PRIMITIVE) {
isNull = !readPrimitive(child);
} else {
stack.push(child);
}
return !isNull;
}
@Override
public boolean isNextComplexMultiValue() throws IOException {
final byte isNullByte = inputByteBuffer.read(columnSortOrderIsDesc[root.index]);
final boolean isEnded;
switch (isNullByte) {
case 0:
isEnded = true;
break;
case 1:
isEnded = false;
break;
default:
throw new RuntimeException();
}
if (isEnded) {
stack.pop();
stack.peek();
}
return !isEnded;
}
@Override
public void finishComplexVariableFieldsType() {
stack.pop();
if (stack.peek() == null) {
throw new RuntimeException();
}
stack.peek();
}
}
| apache-2.0 |
mohanaraosv/commons-net | src/main/java/examples/unix/rshell.java | 3310 | /*
* 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 examples.unix;
import java.io.IOException;
import org.apache.commons.net.bsd.RCommandClient;
import examples.util.IOUtil;
/***
* This is an example program demonstrating how to use the RCommandClient
* class. This program connects to an rshell daemon and requests that the
* given command be executed on the server. It then reads input from stdin
* (this will be line buffered on most systems, so don't expect character
* at a time interactivity), passing it to the remote process and writes
* the process stdout and stderr to local stdout.
* <p>
* On Unix systems you will not be able to use the rshell capability
* unless the process runs as root since only root can bind port addresses
* lower than 1024.
* <p>
* Example: java rshell myhost localusername remoteusername "ps -aux"
* <p>
* Usage: rshell <hostname> <localuser> <remoteuser> <command>
***/
// This class requires the IOUtil support class!
public final class rshell
{
public static void main(String[] args)
{
String server, localuser, remoteuser, command;
RCommandClient client;
if (args.length != 4)
{
System.err.println(
"Usage: rshell <hostname> <localuser> <remoteuser> <command>");
System.exit(1);
return ; // so compiler can do proper flow control analysis
}
client = new RCommandClient();
server = args[0];
localuser = args[1];
remoteuser = args[2];
command = args[3];
try
{
client.connect(server);
}
catch (IOException e)
{
System.err.println("Could not connect to server.");
e.printStackTrace();
System.exit(1);
}
try
{
client.rcommand(localuser, remoteuser, command);
}
catch (IOException e)
{
try
{
client.disconnect();
}
catch (IOException f)
{/* ignored */}
e.printStackTrace();
System.err.println("Could not execute command.");
System.exit(1);
}
IOUtil.readWrite(client.getInputStream(), client.getOutputStream(),
System.in, System.out);
try
{
client.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
}
| apache-2.0 |
Forexware/quickfixj | src/main/java/quickfix/field/DeskOrderHandlingInst.java | 2463 | /*******************************************************************************
* Copyright (c) quickfixengine.org All rights reserved.
*
* This file is part of the QuickFIX FIX Engine
*
* This file may be distributed under the terms of the quickfixengine.org
* license as defined by quickfixengine.org and appearing in the file
* LICENSE included in the packaging of this file.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
* THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* See http://www.quickfixengine.org/LICENSE for licensing information.
*
* Contact ask@quickfixengine.org if any conditions of this licensing
* are not clear to you.
******************************************************************************/
package quickfix.field;
import quickfix.StringField;
public class DeskOrderHandlingInst extends StringField
{
static final long serialVersionUID = 20050617;
public static final int FIELD = 1035;
public static final String ADD_ON_ORDER = "ADD";
public static final String ALL_OR_NONE = "AON";
public static final String CASH_NOT_HELD = "CNH";
public static final String DIRECTED_ORDER = "DIR";
public static final String EXCHANGE_FOR_PHYSICAL_TRANSACTION = "E.W";
public static final String FILL_OR_KILL = "FOK";
public static final String IMBALANCE_ONLY = "IO";
public static final String IMMEDIATE_OR_CANCEL = "IOC";
public static final String LIMIT_ON_OPEN = "LOO";
public static final String LIMIT_ON_CLOSE = "LOC";
public static final String MARKET_AT_OPEN = "MAO";
public static final String MARKET_AT_CLOSE = "MAC";
public static final String MARKET_ON_OPEN = "MOO";
public static final String MARKET_ON_CLOSE = "MOC";
public static final String MINIMUM_QUANTITY = "MQT";
public static final String NOT_HELD = "NH";
public static final String OVER_THE_DAY = "OVD";
public static final String PEGGED = "PEG";
public static final String RESERVE_SIZE_ORDER = "RSV";
public static final String STOP_STOCK_TRANSACTION = "S.W";
public static final String SCALE = "SCL";
public static final String TIME_ORDER = "TMO";
public static final String TRAILING_STOP = "TS";
public static final String WORK = "WRK";
public DeskOrderHandlingInst()
{
super(1035);
}
public DeskOrderHandlingInst(String data)
{
super(1035, data);
}
}
| apache-2.0 |
davebarnes97/geode | geode-dunit/src/main/java/org/apache/geode/cache/query/dunit/TestObject.java | 2531 | /*
* 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.geode.cache.query.dunit;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.geode.DataSerializable;
import org.apache.geode.DataSerializer;
public class TestObject implements DataSerializable {
protected String _ticker;
protected int _price;
public int id;
public int important;
public int selection;
public int select;
public TestObject() {}
public TestObject(int id, String ticker) {
this.id = id;
this._ticker = ticker;
this._price = id;
this.important = id;
this.selection = id;
this.select = id;
}
public int getId() {
return this.id;
}
public String getTicker() {
return this._ticker;
}
public int getPrice() {
return this._price;
}
@Override
public void toData(DataOutput out) throws IOException {
out.writeInt(this.id);
DataSerializer.writeString(this._ticker, out);
out.writeInt(this._price);
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
this.id = in.readInt();
this._ticker = DataSerializer.readString(in);
this._price = in.readInt();
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("TestObject [").append("id=").append(this.id).append("; ticker=")
.append(this._ticker).append("; price=").append(this._price).append("]");
return buffer.toString();
}
@Override
public boolean equals(Object o) {
TestObject other = (TestObject) o;
if ((id == other.id) && (_ticker.equals(other._ticker))) {
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
return this.id;
}
}
| apache-2.0 |
pkcool/qalingo-engine | apis/api-core/api-core-solr/src/main/java/org/hoteia/qalingo/core/solr/service/CatalogCategorySolrService.java | 8932 | /**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - contact@hoteia.com
*
*/
package org.hoteia.qalingo.core.solr.service;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.hoteia.qalingo.core.domain.CatalogCategoryMaster;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.hoteia.qalingo.core.solr.bean.CatalogCategorySolr;
import org.hoteia.qalingo.core.solr.bean.SolrFields;
import org.hoteia.qalingo.core.solr.bean.SolrParam;
import org.hoteia.qalingo.core.solr.response.CatalogCategoryResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("catalogCategorySolrService")
@Transactional
public class CatalogCategorySolrService extends AbstractSolrService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
public SolrServer catalogCategorySolrServer;
public void addOrUpdateCatalogCategory(final CatalogCategoryMaster catalogCategoryMaster, final MarketArea marketArea) throws SolrServerException, IOException {
if (catalogCategoryMaster.getId() == null) {
throw new IllegalArgumentException("Id cannot be blank or null.");
}
if (logger.isDebugEnabled()) {
logger.debug("Indexing category " + catalogCategoryMaster.getId() + " : " + catalogCategoryMaster.getCode() + " : " + catalogCategoryMaster.getName());
}
CatalogCategorySolr categorySolr = new CatalogCategorySolr();
categorySolr.setId(catalogCategoryMaster.getId());
categorySolr.setCode(catalogCategoryMaster.getCode());
categorySolr.setDateCreate(catalogCategoryMaster.getDateCreate());
categorySolr.setDateUpdate(catalogCategoryMaster.getDateUpdate());
categorySolr.setName(catalogCategoryMaster.getName());
catalogCategorySolrServer.addBean(categorySolr);
catalogCategorySolrServer.commit();
logger.debug("Fields has been added sucessfully ");
}
public void removeCatalogCategory(final CatalogCategorySolr categorySolr) throws SolrServerException, IOException {
if (categorySolr.getId() == null) {
throw new IllegalArgumentException("Id cannot be blank or null.");
}
if (logger.isDebugEnabled()) {
logger.debug("Remove Index category " + categorySolr.getId() + " : " + categorySolr.getName());
}
catalogCategorySolrServer.deleteById(categorySolr.getId().toString());
catalogCategorySolrServer.commit();
}
public CatalogCategoryResponseBean searchCatalogCategory(final String searchQuery, final List<String> facetFields, final SolrParam solrParam) throws SolrServerException, IOException {
SolrQuery solrQuery = new SolrQuery();
if(solrParam != null){
if(solrParam.get("rows") != null){
solrQuery.setParam("rows", (String)solrParam.get("rows"));
} else {
solrQuery.setParam("rows", getMaxResult());
}
if(solrParam.get("solrFields") != null){
SolrFields solrFields = (SolrFields) solrParam.get("solrFields");
for (Iterator<String> iterator = solrFields.keySet().iterator(); iterator.hasNext();) {
String field = (String) iterator.next();
solrQuery.addSortField(field, solrFields.get(field));
}
}
}
if (StringUtils.isEmpty(searchQuery)) {
throw new IllegalArgumentException("SearchQuery field can not be Empty or Blank!");
}
solrQuery.setQuery(searchQuery);
if(facetFields != null && !facetFields.isEmpty()){
solrQuery.setFacet(true);
solrQuery.setFacetMinCount(1);
for(String facetField : facetFields){
solrQuery.addFacetField(facetField);
}
}
logger.debug("QueryRequest solrQuery: " + solrQuery);
SolrRequest request = new QueryRequest(solrQuery, METHOD.POST);
QueryResponse response = new QueryResponse(catalogCategorySolrServer.request(request), catalogCategorySolrServer);
logger.debug("QueryResponse Obj: " + response.toString());
List<CatalogCategorySolr> solrList = response.getBeans(CatalogCategorySolr.class);
CatalogCategoryResponseBean catalogCategoryResponseBean = new CatalogCategoryResponseBean();
catalogCategoryResponseBean.setCatalogCategorySolrList(solrList);
if(facetFields != null && !facetFields.isEmpty()){
List<FacetField> solrFacetFieldList = response.getFacetFields();
catalogCategoryResponseBean.setCatalogCategorySolrFacetFieldList(solrFacetFieldList);
}
return catalogCategoryResponseBean;
}
@Deprecated
public CatalogCategoryResponseBean searchCatalogCategory(String searchBy,String searchText, List<String> facetFields) throws SolrServerException, IOException {
SolrQuery solrQuery = new SolrQuery();
solrQuery.setParam("rows", getMaxResult());
if (StringUtils.isEmpty(searchBy)) {
throw new IllegalArgumentException("SearchBy field can not be Empty or Blank!");
}
if (StringUtils.isEmpty(searchText)) {
solrQuery.setQuery(searchBy + ":*");
} else {
solrQuery.setQuery(searchBy + ":" + searchText + "*");
}
if(facetFields != null && !facetFields.isEmpty()){
solrQuery.setFacet(true);
solrQuery.setFacetMinCount(1);
for(String facetField : facetFields){
solrQuery.addFacetField(facetField);
}
}
logger.debug("QueryRequest solrQuery: " + solrQuery);
SolrRequest request = new QueryRequest(solrQuery, METHOD.POST);
QueryResponse response = new QueryResponse(catalogCategorySolrServer.request(request), catalogCategorySolrServer);
logger.debug("QueryResponse Obj: " + response.toString());
List<CatalogCategorySolr> solrList = response.getBeans(CatalogCategorySolr.class);
CatalogCategoryResponseBean catalogCategoryResponseBean = new CatalogCategoryResponseBean();
catalogCategoryResponseBean.setCatalogCategorySolrList(solrList);
if(facetFields != null && !facetFields.isEmpty()){
List<FacetField> solrFacetFieldList = response.getFacetFields();
catalogCategoryResponseBean.setCatalogCategorySolrFacetFieldList(solrFacetFieldList);
}
return catalogCategoryResponseBean;
}
public CatalogCategoryResponseBean searchCatalogCategory() throws SolrServerException, IOException {
SolrQuery solrQuery = new SolrQuery();
solrQuery.setParam("rows", getMaxResult());
solrQuery.setQuery("*");
solrQuery.setFacet(true);
solrQuery.setFacetMinCount(1);
solrQuery.addFacetField("code");
logger.debug("QueryRequest solrQuery: " + solrQuery);
SolrRequest request = new QueryRequest(solrQuery, METHOD.POST);
QueryResponse response = new QueryResponse(catalogCategorySolrServer.request(request), catalogCategorySolrServer);
logger.debug("QueryResponse Obj: " + response.toString());
List<CatalogCategorySolr> solrList = response.getBeans(CatalogCategorySolr.class);
List<FacetField> solrFacetFieldList = response.getFacetFields();
CatalogCategoryResponseBean catalogCategoryResponseBean = new CatalogCategoryResponseBean();
catalogCategoryResponseBean.setCatalogCategorySolrList(solrList);
catalogCategoryResponseBean.setCatalogCategorySolrFacetFieldList(solrFacetFieldList);
return catalogCategoryResponseBean;
}
} | apache-2.0 |
SciGaP/DEPRECATED-Cipres-Airavata-POC | saminda/cipres-airavata/sdk/src/main/java/org/ngbw/sdk/core/transformation/BaseTransformer.java | 3085 | /*
* BaseTransformer.java
*/
package org.ngbw.sdk.core.transformation;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Set;
import org.ngbw.sdk.api.core.CoreRegistry;
import org.ngbw.sdk.api.core.GenericDataRecordCollection;
import org.ngbw.sdk.api.core.SourceDocumentTransformer;
import org.ngbw.sdk.core.shared.SourceDocumentType;
import org.ngbw.sdk.core.configuration.ServiceFactory;
import org.ngbw.sdk.core.shared.GenericDataRecordCollectionImpl;
import org.ngbw.sdk.core.shared.IndexedDataRecord;
import org.ngbw.sdk.core.types.RecordFieldType;
import org.ngbw.sdk.core.types.RecordType;
import org.ngbw.sdk.database.DataRecord;
import org.ngbw.sdk.database.RecordField;
import org.ngbw.sdk.database.SourceDocument;
/**
*
* @author Roland H. Niedner
*
*/
public abstract class BaseTransformer implements SourceDocumentTransformer {
protected ServiceFactory serviceFactory;
protected SourceDocument srcDocument;
protected RecordType targetType;
protected BaseTransformer(ServiceFactory serviceFactory, SourceDocument srcDocument, RecordType targetType) throws IOException, SQLException {
if (srcDocument == null)
throw new NullPointerException("SourceDocument is null!");
this.serviceFactory = serviceFactory;
this.srcDocument = srcDocument;
this.targetType = targetType;
transform(srcDocument);
}
public SourceDocumentType getSourceType() {
return srcDocument.getType();
}
public RecordType getTargetType() {
return targetType;
}
public abstract GenericDataRecordCollection<IndexedDataRecord> getDataRecordCollection() throws ParseException;
public abstract SourceDocument getTransformedSourceDocument(DataRecord dataRecord);
protected abstract void transform(SourceDocument srcDocument) throws IOException, SQLException;
protected GenericDataRecordCollection<IndexedDataRecord> newDataRecordCollection() {
CoreRegistry coreRegistry = serviceFactory.getCoreRegistry();
if (targetType == null)
throw new NullPointerException("RecordType cannot be NULL!");
Set<RecordFieldType> fields = coreRegistry.getRecordFields(targetType);
return new GenericDataRecordCollectionImpl<IndexedDataRecord>(targetType, fields);
}
protected IndexedDataRecord newDataRecord(int index) {
CoreRegistry coreRegistry = serviceFactory.getCoreRegistry();
if (targetType == null)
throw new NullPointerException("RecordType cannot be NULL!");
Set<RecordFieldType> fields = coreRegistry.getRecordFields(targetType);
return new IndexedDataRecord(targetType, fields, index);
}
protected IndexedDataRecord newDataRecord(int index, DataRecord record) {
if (targetType == null)
throw new NullPointerException("RecordType cannot be NULL!");
Set<RecordFieldType> fields = serviceFactory.getCoreRegistry().getRecordFields(targetType);
IndexedDataRecord newRecord = new IndexedDataRecord(targetType, fields, index);
for (RecordField field : record.getFields())
newRecord.getField(field.getFieldType()).setValue(field.getValue());
return newRecord;
}
}
| apache-2.0 |
DuncanDoyle/jbpm | jbpm-persistence/jbpm-persistence-jpa/src/main/java/org/jbpm/persistence/processinstance/JPAProcessInstanceManager.java | 11946 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.persistence.processinstance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.drools.core.common.InternalKnowledgeRuntime;
import org.drools.persistence.api.TransactionManager;
import org.drools.persistence.api.TransactionManagerHelper;
import org.jbpm.persistence.api.ProcessPersistenceContext;
import org.jbpm.persistence.api.ProcessPersistenceContextManager;
import org.jbpm.persistence.correlation.CorrelationKeyInfo;
import org.jbpm.persistence.correlation.CorrelationPropertyInfo;
import org.jbpm.process.instance.InternalProcessRuntime;
import org.jbpm.process.instance.ProcessInstanceManager;
import org.jbpm.process.instance.impl.ProcessInstanceImpl;
import org.jbpm.process.instance.timer.TimerManager;
import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.jbpm.workflow.instance.node.StateBasedNodeInstance;
import org.jbpm.workflow.instance.node.TimerNodeInstance;
import org.kie.api.definition.process.Process;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkflowProcessInstance;
import org.kie.internal.process.CorrelationKey;
import org.kie.internal.runtime.manager.InternalRuntimeManager;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
/**
* This is an implementation of the {@link ProcessInstanceManager} that uses JPA.
* </p>
* What's important to remember here is that we have a jbpm-console which has 1 static (stateful) knowledge session
* which is used by multiple threads: each request sent to the jbpm-console is picked up in it's own thread.
* </p>
* This means that multiple threads can be using the same instance of this class.
*/
public class JPAProcessInstanceManager
implements
ProcessInstanceManager {
private InternalKnowledgeRuntime kruntime;
// In a scenario in which 1000's of processes are running daily,
// lazy initialization is more costly than eager initialization
// Added volatile so that if something happens, we can figure out what
private volatile transient Map<Long, ProcessInstance> processInstances = new ConcurrentHashMap<Long, ProcessInstance>();
public void setKnowledgeRuntime(InternalKnowledgeRuntime kruntime) {
this.kruntime = kruntime;
}
public void addProcessInstance(ProcessInstance processInstance, CorrelationKey correlationKey) {
ProcessInstanceInfo processInstanceInfo = new ProcessInstanceInfo( processInstance, this.kruntime.getEnvironment() );
ProcessPersistenceContext context
= ((ProcessPersistenceContextManager) this.kruntime.getEnvironment()
.get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER ))
.getProcessPersistenceContext();
processInstanceInfo = (ProcessInstanceInfo) context.persist( processInstanceInfo );
((org.jbpm.process.instance.ProcessInstance) processInstance).setId( processInstanceInfo.getId() );
processInstanceInfo.updateLastReadDate();
// generate correlation key if not given which is same as process instance id to keep uniqueness
if (correlationKey == null) {
correlationKey = new CorrelationKeyInfo();
((CorrelationKeyInfo)correlationKey).addProperty(new CorrelationPropertyInfo(null, processInstanceInfo.getId().toString()));
((org.jbpm.process.instance.ProcessInstance) processInstance).getMetaData().put("CorrelationKey", correlationKey);
}
CorrelationKeyInfo correlationKeyInfo = (CorrelationKeyInfo) correlationKey;
correlationKeyInfo.setProcessInstanceId(processInstanceInfo.getId());
context.persist(correlationKeyInfo);
internalAddProcessInstance(processInstance);
}
public void internalAddProcessInstance(ProcessInstance processInstance) {
if( ((ConcurrentHashMap<Long, ProcessInstance>) processInstances)
.putIfAbsent(processInstance.getId(), processInstance)
!= null ) {
throw new ConcurrentModificationException(
"Duplicate process instance [" + processInstance.getProcessId() + "/" + processInstance.getId() + "]"
+ " added to process instance manager." );
}
}
public ProcessInstance getProcessInstance(long id) {
return getProcessInstance(id, false);
}
public ProcessInstance getProcessInstance(long id, boolean readOnly) {
InternalRuntimeManager manager = (InternalRuntimeManager) kruntime.getEnvironment().get(EnvironmentName.RUNTIME_MANAGER);
if (manager != null) {
manager.validate((KieSession) kruntime, ProcessInstanceIdContext.get(id));
}
TransactionManager txm = (TransactionManager) this.kruntime.getEnvironment().get( EnvironmentName.TRANSACTION_MANAGER );
org.jbpm.process.instance.ProcessInstance processInstance = null;
processInstance = (org.jbpm.process.instance.ProcessInstance) this.processInstances.get(id);
if (processInstance != null) {
if (((WorkflowProcessInstanceImpl) processInstance).isPersisted() && !readOnly) {
ProcessPersistenceContextManager ppcm
= (ProcessPersistenceContextManager) this.kruntime.getEnvironment().get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER );
ppcm.beginCommandScopedEntityManager();
ProcessPersistenceContext context = ppcm.getProcessPersistenceContext();
ProcessInstanceInfo processInstanceInfo = (ProcessInstanceInfo) context.findProcessInstanceInfo( id );
if ( processInstanceInfo == null ) {
return null;
}
TransactionManagerHelper.addToUpdatableSet(txm, processInstanceInfo);
processInstanceInfo.updateLastReadDate();
}
return processInstance;
}
// Make sure that the cmd scoped entity manager has started
ProcessPersistenceContextManager ppcm
= (ProcessPersistenceContextManager) this.kruntime.getEnvironment().get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER );
ppcm.beginCommandScopedEntityManager();
ProcessPersistenceContext context = ppcm.getProcessPersistenceContext();
ProcessInstanceInfo processInstanceInfo = (ProcessInstanceInfo) context.findProcessInstanceInfo( id );
if ( processInstanceInfo == null ) {
return null;
}
processInstance = (org.jbpm.process.instance.ProcessInstance)
processInstanceInfo.getProcessInstance(kruntime, this.kruntime.getEnvironment(), readOnly);
if (!readOnly) {
processInstanceInfo.updateLastReadDate();
TransactionManagerHelper.addToUpdatableSet(txm, processInstanceInfo);
}
if (((ProcessInstanceImpl) processInstance).getProcessXml() == null) {
Process process = kruntime.getKieBase().getProcess( processInstance.getProcessId() );
if ( process == null ) {
throw new IllegalArgumentException( "Could not find process " + processInstance.getProcessId() );
}
processInstance.setProcess( process );
}
if ( processInstance.getKnowledgeRuntime() == null ) {
Long parentProcessInstanceId = (Long) ((ProcessInstanceImpl) processInstance).getMetaData().get("ParentProcessInstanceId");
if (parentProcessInstanceId != null) {
kruntime.getProcessInstance(parentProcessInstanceId);
}
processInstance.setKnowledgeRuntime( kruntime );
((ProcessInstanceImpl) processInstance).reconnect();
if (readOnly) {
internalRemoveProcessInstance(processInstance);
}
}
return processInstance;
}
public Collection<ProcessInstance> getProcessInstances() {
return Collections.unmodifiableCollection(processInstances.values());
}
public void removeProcessInstance(ProcessInstance processInstance) {
ProcessPersistenceContext context = ((ProcessPersistenceContextManager) this.kruntime.getEnvironment().get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )).getProcessPersistenceContext();
ProcessInstanceInfo processInstanceInfo = (ProcessInstanceInfo) context.findProcessInstanceInfo( processInstance.getId() );
if ( processInstanceInfo != null ) {
context.remove( processInstanceInfo );
}
internalRemoveProcessInstance(processInstance);
}
public void internalRemoveProcessInstance(ProcessInstance processInstance) {
processInstances.remove( processInstance.getId() );
}
public void clearProcessInstances() {
for (ProcessInstance processInstance: new ArrayList<ProcessInstance>(processInstances.values())) {
((ProcessInstanceImpl) processInstance).disconnect();
}
}
public void clearProcessInstancesState() {
try {
// at this point only timers are considered as state that needs to be cleared
TimerManager timerManager = ((InternalProcessRuntime)kruntime.getProcessRuntime()).getTimerManager();
for (ProcessInstance processInstance: new ArrayList<ProcessInstance>(processInstances.values())) {
WorkflowProcessInstance pi = ((WorkflowProcessInstance) processInstance);
for (org.kie.api.runtime.process.NodeInstance nodeInstance : pi.getNodeInstances()) {
if (nodeInstance instanceof TimerNodeInstance){
if (((TimerNodeInstance)nodeInstance).getTimerInstance() != null) {
timerManager.cancelTimer(((TimerNodeInstance)nodeInstance).getTimerInstance().getId());
}
} else if (nodeInstance instanceof StateBasedNodeInstance) {
List<Long> timerIds = ((StateBasedNodeInstance) nodeInstance).getTimerInstances();
if (timerIds != null) {
for (Long id: timerIds) {
timerManager.cancelTimer(id);
}
}
}
}
}
} catch (Exception e) {
// catch everything here to make sure it will not break any following
// logic to allow complete clean up
}
}
@Override
public ProcessInstance getProcessInstance(CorrelationKey correlationKey) {
ProcessPersistenceContext context = ((ProcessPersistenceContextManager) this.kruntime.getEnvironment()
.get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER ))
.getProcessPersistenceContext();
Long processInstanceId = context.getProcessInstanceByCorrelationKey(correlationKey);
if (processInstanceId == null) {
return null;
}
return getProcessInstance(processInstanceId);
}
}
| apache-2.0 |
lburgazzoli/spring-boot | spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/NoteRepository.java | 772 | /*
* Copyright 2012-2019 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.jpa.repository;
import java.util.List;
import sample.jpa.domain.Note;
public interface NoteRepository {
List<Note> findAll();
}
| apache-2.0 |
ManfredTremmel/mt-bean-validators | src/main/java/de/knightsoftnet/validators/shared/NotEmptyAfterStrip.java | 2658 | /*
* 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 de.knightsoftnet.validators.shared;
import de.knightsoftnet.validators.shared.impl.NotEmptyAfterStripValidator;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* The annotated element must not be null or empty after strip. There is one parameter option:
* <ul>
* <li>characters which should be striped (option <code>stripcharacters</code>, default " 0")</li>
* </ul>
*
* @author Manfred Tremmel
*
*/
@Documented
@Constraint(validatedBy = NotEmptyAfterStripValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotEmptyAfterStrip {
/**
* localized message.
*
* @return localized validation message
*/
String message() default "{javax.validation.constraints.NotEmpty.message}";
/**
* groups to use.
*
* @return array of validation groups
*/
Class<?>[] groups() default {};
/**
* payload whatever.
*
* @return payload class
*/
Class<? extends Payload>[] payload() default {};
/**
* characters which should be striped.
*
* @return characters to strip
*/
String stripcharacters() default " 0";
/**
* Defines several {@code @NotEmptyAfterStrip} annotations on the same element.
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
/**
* NotEmptyAfterStrip value.
*
* @return value
*/
NotEmptyAfterStrip[] value();
}
}
| apache-2.0 |
taochaoqiang/druid | server/src/main/java/io/druid/server/coordinator/CoordinatorDynamicConfig.java | 16609 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.server.coordinator;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableSet;
import io.druid.java.util.common.IAE;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* This class is for users to change their configurations while their Druid cluster is running.
* These configurations are designed to allow only simple values rather than complicated JSON objects.
*
* @see io.druid.common.config.JacksonConfigManager
* @see io.druid.common.config.ConfigManager
*/
public class CoordinatorDynamicConfig
{
public static final String CONFIG_KEY = "coordinator.config";
private final long millisToWaitBeforeDeleting;
private final long mergeBytesLimit;
private final int mergeSegmentsLimit;
private final int maxSegmentsToMove;
private final int replicantLifetime;
private final int replicationThrottleLimit;
private final int balancerComputeThreads;
private final boolean emitBalancingStats;
private final boolean killAllDataSources;
private final Set<String> killDataSourceWhitelist;
// The pending segments of the dataSources in this list are not killed.
private final Set<String> killPendingSegmentsSkipList;
/**
* The maximum number of segments that could be queued for loading to any given server.
* Default values is 0 with the meaning of "unbounded" (any number of
* segments could be added to the loading queue for any server).
* See {@link LoadQueuePeon}, {@link io.druid.server.coordinator.rules.LoadRule#run}
*/
private final int maxSegmentsInNodeLoadingQueue;
@JsonCreator
public CoordinatorDynamicConfig(
@JsonProperty("millisToWaitBeforeDeleting") long millisToWaitBeforeDeleting,
@JsonProperty("mergeBytesLimit") long mergeBytesLimit,
@JsonProperty("mergeSegmentsLimit") int mergeSegmentsLimit,
@JsonProperty("maxSegmentsToMove") int maxSegmentsToMove,
@JsonProperty("replicantLifetime") int replicantLifetime,
@JsonProperty("replicationThrottleLimit") int replicationThrottleLimit,
@JsonProperty("balancerComputeThreads") int balancerComputeThreads,
@JsonProperty("emitBalancingStats") boolean emitBalancingStats,
// Type is Object here so that we can support both string and list as
// coordinator console can not send array of strings in the update request.
// See https://github.com/druid-io/druid/issues/3055
@JsonProperty("killDataSourceWhitelist") Object killDataSourceWhitelist,
@JsonProperty("killAllDataSources") boolean killAllDataSources,
@JsonProperty("killPendingSegmentsSkipList") Object killPendingSegmentsSkipList,
@JsonProperty("maxSegmentsInNodeLoadingQueue") int maxSegmentsInNodeLoadingQueue
)
{
this.millisToWaitBeforeDeleting = millisToWaitBeforeDeleting;
this.mergeBytesLimit = mergeBytesLimit;
this.mergeSegmentsLimit = mergeSegmentsLimit;
this.maxSegmentsToMove = maxSegmentsToMove;
this.replicantLifetime = replicantLifetime;
this.replicationThrottleLimit = replicationThrottleLimit;
this.balancerComputeThreads = Math.max(balancerComputeThreads, 1);
this.emitBalancingStats = emitBalancingStats;
this.killAllDataSources = killAllDataSources;
this.killDataSourceWhitelist = parseJsonStringOrArray(killDataSourceWhitelist);
this.killPendingSegmentsSkipList = parseJsonStringOrArray(killPendingSegmentsSkipList);
this.maxSegmentsInNodeLoadingQueue = maxSegmentsInNodeLoadingQueue;
if (this.killAllDataSources && !this.killDataSourceWhitelist.isEmpty()) {
throw new IAE("can't have killAllDataSources and non-empty killDataSourceWhitelist");
}
}
private static Set<String> parseJsonStringOrArray(Object jsonStringOrArray)
{
if (jsonStringOrArray instanceof String) {
String[] list = ((String) jsonStringOrArray).split(",");
Set<String> result = new HashSet<>();
for (String item : list) {
String trimmed = item.trim();
if (!trimmed.isEmpty()) {
result.add(trimmed);
}
}
return result;
} else if (jsonStringOrArray instanceof Collection) {
return ImmutableSet.copyOf(((Collection) jsonStringOrArray));
} else {
return ImmutableSet.of();
}
}
@JsonProperty
public long getMillisToWaitBeforeDeleting()
{
return millisToWaitBeforeDeleting;
}
@JsonProperty
public long getMergeBytesLimit()
{
return mergeBytesLimit;
}
@JsonProperty
public boolean emitBalancingStats()
{
return emitBalancingStats;
}
@JsonProperty
public int getMergeSegmentsLimit()
{
return mergeSegmentsLimit;
}
@JsonProperty
public int getMaxSegmentsToMove()
{
return maxSegmentsToMove;
}
@JsonProperty
public int getReplicantLifetime()
{
return replicantLifetime;
}
@JsonProperty
public int getReplicationThrottleLimit()
{
return replicationThrottleLimit;
}
@JsonProperty
public int getBalancerComputeThreads()
{
return balancerComputeThreads;
}
@JsonProperty
public Set<String> getKillDataSourceWhitelist()
{
return killDataSourceWhitelist;
}
@JsonProperty
public boolean isKillAllDataSources()
{
return killAllDataSources;
}
@JsonProperty
public Set<String> getKillPendingSegmentsSkipList()
{
return killPendingSegmentsSkipList;
}
@JsonProperty
public int getMaxSegmentsInNodeLoadingQueue()
{
return maxSegmentsInNodeLoadingQueue;
}
@Override
public String toString()
{
return "CoordinatorDynamicConfig{" +
"millisToWaitBeforeDeleting=" + millisToWaitBeforeDeleting +
", mergeBytesLimit=" + mergeBytesLimit +
", mergeSegmentsLimit=" + mergeSegmentsLimit +
", maxSegmentsToMove=" + maxSegmentsToMove +
", replicantLifetime=" + replicantLifetime +
", replicationThrottleLimit=" + replicationThrottleLimit +
", balancerComputeThreads=" + balancerComputeThreads +
", emitBalancingStats=" + emitBalancingStats +
", killDataSourceWhitelist=" + killDataSourceWhitelist +
", killAllDataSources=" + killAllDataSources +
", killPendingSegmentsSkipList=" + killPendingSegmentsSkipList +
", maxSegmentsInNodeLoadingQueue=" + maxSegmentsInNodeLoadingQueue +
'}';
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CoordinatorDynamicConfig that = (CoordinatorDynamicConfig) o;
if (millisToWaitBeforeDeleting != that.millisToWaitBeforeDeleting) {
return false;
}
if (mergeBytesLimit != that.mergeBytesLimit) {
return false;
}
if (mergeSegmentsLimit != that.mergeSegmentsLimit) {
return false;
}
if (maxSegmentsToMove != that.maxSegmentsToMove) {
return false;
}
if (replicantLifetime != that.replicantLifetime) {
return false;
}
if (replicationThrottleLimit != that.replicationThrottleLimit) {
return false;
}
if (balancerComputeThreads != that.balancerComputeThreads) {
return false;
}
if (emitBalancingStats != that.emitBalancingStats) {
return false;
}
if (killAllDataSources != that.killAllDataSources) {
return false;
}
if (maxSegmentsInNodeLoadingQueue != that.maxSegmentsInNodeLoadingQueue) {
return false;
}
if (!Objects.equals(killDataSourceWhitelist, that.killDataSourceWhitelist)) {
return false;
}
return Objects.equals(killPendingSegmentsSkipList, that.killPendingSegmentsSkipList);
}
@Override
public int hashCode()
{
return Objects.hash(
millisToWaitBeforeDeleting,
mergeBytesLimit,
mergeSegmentsLimit,
maxSegmentsToMove,
replicantLifetime,
replicationThrottleLimit,
balancerComputeThreads,
emitBalancingStats,
killAllDataSources,
maxSegmentsInNodeLoadingQueue,
killDataSourceWhitelist,
killPendingSegmentsSkipList
);
}
public static Builder builder()
{
return new Builder();
}
public static class Builder
{
private static final long DEFAULT_MILLIS_TO_WAIT_BEFORE_DELETING = TimeUnit.MINUTES.toMillis(15);
private static final long DEFAULT_MERGE_BYTES_LIMIT = 524288000L;
private static final int DEFAULT_MERGE_SEGMENTS_LIMIT = 100;
private static final int DEFAULT_MAX_SEGMENTS_TO_MOVE = 5;
private static final int DEFAULT_REPLICANT_LIFETIME = 15;
private static final int DEFAULT_REPLICATION_THROTTLE_LIMIT = 10;
private static final int DEFAULT_BALANCER_COMPUTE_THREADS = 1;
private static final boolean DEFAULT_EMIT_BALANCING_STATS = false;
private static final boolean DEFAULT_KILL_ALL_DATA_SOURCES = false;
private static final int DEFAULT_MAX_SEGMENTS_IN_NODE_LOADING_QUEUE = 0;
private Long millisToWaitBeforeDeleting;
private Long mergeBytesLimit;
private Integer mergeSegmentsLimit;
private Integer maxSegmentsToMove;
private Integer replicantLifetime;
private Integer replicationThrottleLimit;
private Boolean emitBalancingStats;
private Integer balancerComputeThreads;
private Object killDataSourceWhitelist;
private Boolean killAllDataSources;
private Object killPendingSegmentsSkipList;
private Integer maxSegmentsInNodeLoadingQueue;
public Builder()
{
}
@JsonCreator
public Builder(
@JsonProperty("millisToWaitBeforeDeleting") @Nullable Long millisToWaitBeforeDeleting,
@JsonProperty("mergeBytesLimit") @Nullable Long mergeBytesLimit,
@JsonProperty("mergeSegmentsLimit") @Nullable Integer mergeSegmentsLimit,
@JsonProperty("maxSegmentsToMove") @Nullable Integer maxSegmentsToMove,
@JsonProperty("replicantLifetime") @Nullable Integer replicantLifetime,
@JsonProperty("replicationThrottleLimit") @Nullable Integer replicationThrottleLimit,
@JsonProperty("balancerComputeThreads") @Nullable Integer balancerComputeThreads,
@JsonProperty("emitBalancingStats") @Nullable Boolean emitBalancingStats,
@JsonProperty("killDataSourceWhitelist") @Nullable Object killDataSourceWhitelist,
@JsonProperty("killAllDataSources") @Nullable Boolean killAllDataSources,
@JsonProperty("killPendingSegmentsSkipList") @Nullable Object killPendingSegmentsSkipList,
@JsonProperty("maxSegmentsInNodeLoadingQueue") @Nullable Integer maxSegmentsInNodeLoadingQueue
)
{
this.millisToWaitBeforeDeleting = millisToWaitBeforeDeleting;
this.mergeBytesLimit = mergeBytesLimit;
this.mergeSegmentsLimit = mergeSegmentsLimit;
this.maxSegmentsToMove = maxSegmentsToMove;
this.replicantLifetime = replicantLifetime;
this.replicationThrottleLimit = replicationThrottleLimit;
this.balancerComputeThreads = balancerComputeThreads;
this.emitBalancingStats = emitBalancingStats;
this.killAllDataSources = killAllDataSources;
this.killDataSourceWhitelist = killDataSourceWhitelist;
this.killPendingSegmentsSkipList = killPendingSegmentsSkipList;
this.maxSegmentsInNodeLoadingQueue = maxSegmentsInNodeLoadingQueue;
}
public Builder withMillisToWaitBeforeDeleting(long millisToWaitBeforeDeleting)
{
this.millisToWaitBeforeDeleting = millisToWaitBeforeDeleting;
return this;
}
public Builder withMergeBytesLimit(long mergeBytesLimit)
{
this.mergeBytesLimit = mergeBytesLimit;
return this;
}
public Builder withMergeSegmentsLimit(int mergeSegmentsLimit)
{
this.mergeSegmentsLimit = mergeSegmentsLimit;
return this;
}
public Builder withMaxSegmentsToMove(int maxSegmentsToMove)
{
this.maxSegmentsToMove = maxSegmentsToMove;
return this;
}
public Builder withReplicantLifetime(int replicantLifetime)
{
this.replicantLifetime = replicantLifetime;
return this;
}
public Builder withReplicationThrottleLimit(int replicationThrottleLimit)
{
this.replicationThrottleLimit = replicationThrottleLimit;
return this;
}
public Builder withBalancerComputeThreads(int balancerComputeThreads)
{
this.balancerComputeThreads = balancerComputeThreads;
return this;
}
public Builder withEmitBalancingStats(boolean emitBalancingStats)
{
this.emitBalancingStats = emitBalancingStats;
return this;
}
public Builder withKillDataSourceWhitelist(Set<String> killDataSourceWhitelist)
{
this.killDataSourceWhitelist = killDataSourceWhitelist;
return this;
}
public Builder withKillAllDataSources(boolean killAllDataSources)
{
this.killAllDataSources = killAllDataSources;
return this;
}
public Builder withMaxSegmentsInNodeLoadingQueue(int maxSegmentsInNodeLoadingQueue)
{
this.maxSegmentsInNodeLoadingQueue = maxSegmentsInNodeLoadingQueue;
return this;
}
public CoordinatorDynamicConfig build()
{
return new CoordinatorDynamicConfig(
millisToWaitBeforeDeleting == null ? DEFAULT_MILLIS_TO_WAIT_BEFORE_DELETING : millisToWaitBeforeDeleting,
mergeBytesLimit == null ? DEFAULT_MERGE_BYTES_LIMIT : mergeBytesLimit,
mergeSegmentsLimit == null ? DEFAULT_MERGE_SEGMENTS_LIMIT : mergeSegmentsLimit,
maxSegmentsToMove == null ? DEFAULT_MAX_SEGMENTS_TO_MOVE : maxSegmentsToMove,
replicantLifetime == null ? DEFAULT_REPLICANT_LIFETIME : replicantLifetime,
replicationThrottleLimit == null ? DEFAULT_REPLICATION_THROTTLE_LIMIT : replicationThrottleLimit,
balancerComputeThreads == null ? DEFAULT_BALANCER_COMPUTE_THREADS : balancerComputeThreads,
emitBalancingStats == null ? DEFAULT_EMIT_BALANCING_STATS : emitBalancingStats,
killDataSourceWhitelist,
killAllDataSources == null ? DEFAULT_KILL_ALL_DATA_SOURCES : killAllDataSources,
killPendingSegmentsSkipList,
maxSegmentsInNodeLoadingQueue == null ? DEFAULT_MAX_SEGMENTS_IN_NODE_LOADING_QUEUE : maxSegmentsInNodeLoadingQueue
);
}
public CoordinatorDynamicConfig build(CoordinatorDynamicConfig defaults)
{
return new CoordinatorDynamicConfig(
millisToWaitBeforeDeleting == null ? defaults.getMillisToWaitBeforeDeleting() : millisToWaitBeforeDeleting,
mergeBytesLimit == null ? defaults.getMergeBytesLimit() : mergeBytesLimit,
mergeSegmentsLimit == null ? defaults.getMergeSegmentsLimit() : mergeSegmentsLimit,
maxSegmentsToMove == null ? defaults.getMaxSegmentsToMove() : maxSegmentsToMove,
replicantLifetime == null ? defaults.getReplicantLifetime() : replicantLifetime,
replicationThrottleLimit == null ? defaults.getReplicationThrottleLimit() : replicationThrottleLimit,
balancerComputeThreads == null ? defaults.getBalancerComputeThreads() : balancerComputeThreads,
emitBalancingStats == null ? defaults.emitBalancingStats() : emitBalancingStats,
killDataSourceWhitelist == null ? defaults.getKillDataSourceWhitelist() : killDataSourceWhitelist,
killAllDataSources == null ? defaults.isKillAllDataSources() : killAllDataSources,
killPendingSegmentsSkipList == null ? defaults.getKillPendingSegmentsSkipList() : killPendingSegmentsSkipList,
maxSegmentsInNodeLoadingQueue == null ? defaults.getMaxSegmentsInNodeLoadingQueue() : maxSegmentsInNodeLoadingQueue
);
}
}
}
| apache-2.0 |
godfreyhe/flink | flink-connectors/flink-connector-aws-kinesis-data-streams/src/test/java/org/apache/flink/connector/kinesis/table/KinesisDynamicTableSinkFactoryTest.java | 15806 | /*
* 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.flink.connector.kinesis.table;
import org.apache.flink.api.connector.sink2.Sink;
import org.apache.flink.connector.kinesis.sink.KinesisDataStreamsSink;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.Column;
import org.apache.flink.table.catalog.ResolvedSchema;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.connector.sink.SinkV2Provider;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.factories.TableOptionsBuilder;
import org.apache.flink.table.factories.TestFormatFactory;
import org.apache.flink.table.runtime.connector.sink.SinkRuntimeProviderContext;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.util.TestLogger;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.FLUSH_BUFFER_SIZE;
import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.FLUSH_BUFFER_TIMEOUT;
import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.MAX_BATCH_SIZE;
import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.MAX_BUFFERED_REQUESTS;
import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.MAX_IN_FLIGHT_REQUESTS;
import static org.apache.flink.connector.kinesis.table.KinesisConnectorOptions.SINK_FAIL_ON_ERROR;
import static org.apache.flink.table.factories.utils.FactoryMocks.createTableSink;
/** Test for {@link KinesisDynamicSink} created by {@link KinesisDynamicTableSinkFactory}. */
public class KinesisDynamicTableSinkFactoryTest extends TestLogger {
private static final String STREAM_NAME = "myStream";
@Test
public void testGoodTableSinkForPartitionedTable() {
ResolvedSchema sinkSchema = defaultSinkSchema();
DataType physicalDataType = sinkSchema.toPhysicalRowDataType();
Map<String, String> sinkOptions = defaultTableOptions().build();
List<String> sinkPartitionKeys = Arrays.asList("name", "curr_id");
// Construct actual DynamicTableSink using FactoryUtil
KinesisDynamicSink actualSink =
(KinesisDynamicSink) createTableSink(sinkSchema, sinkPartitionKeys, sinkOptions);
// Construct expected DynamicTableSink using factory under test
KinesisDynamicSink expectedSink =
(KinesisDynamicSink)
new KinesisDynamicSink.KinesisDynamicTableSinkBuilder()
.setConsumedDataType(physicalDataType)
.setStream(STREAM_NAME)
.setKinesisClientProperties(defaultProducerProperties())
.setEncodingFormat(new TestFormatFactory.EncodingFormatMock(","))
.setPartitioner(
new RowDataFieldsKinesisPartitionKeyGenerator(
(RowType) physicalDataType.getLogicalType(),
sinkPartitionKeys))
.build();
// verify that the constructed DynamicTableSink is as expected
Assertions.assertThat(actualSink).isEqualTo(expectedSink);
// verify the produced sink
DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider =
actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false));
Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink();
Assertions.assertThat(sinkFunction).isInstanceOf(KinesisDataStreamsSink.class);
}
@Test
public void testGoodTableSinkCopyForPartitionedTable() {
ResolvedSchema sinkSchema = defaultSinkSchema();
DataType physicalDataType = sinkSchema.toPhysicalRowDataType();
Map<String, String> sinkOptions = defaultTableOptions().build();
List<String> sinkPartitionKeys = Arrays.asList("name", "curr_id");
// Construct actual DynamicTableSink using FactoryUtil
KinesisDynamicSink actualSink =
(KinesisDynamicSink) createTableSink(sinkSchema, sinkPartitionKeys, sinkOptions);
// Construct expected DynamicTableSink using factory under test
KinesisDynamicSink expectedSink =
(KinesisDynamicSink)
new KinesisDynamicSink.KinesisDynamicTableSinkBuilder()
.setConsumedDataType(physicalDataType)
.setStream(STREAM_NAME)
.setKinesisClientProperties(defaultProducerProperties())
.setEncodingFormat(new TestFormatFactory.EncodingFormatMock(","))
.setPartitioner(
new RowDataFieldsKinesisPartitionKeyGenerator(
(RowType) physicalDataType.getLogicalType(),
sinkPartitionKeys))
.build();
Assertions.assertThat(actualSink).isEqualTo(expectedSink.copy());
Assertions.assertThat(expectedSink).isNotSameAs(expectedSink.copy());
}
@Test
public void testGoodTableSinkForNonPartitionedTable() {
ResolvedSchema sinkSchema = defaultSinkSchema();
Map<String, String> sinkOptions = defaultTableOptions().build();
// Construct actual DynamicTableSink using FactoryUtil
KinesisDynamicSink actualSink =
(KinesisDynamicSink) createTableSink(sinkSchema, sinkOptions);
// Construct expected DynamicTableSink using factory under test
KinesisDynamicSink expectedSink =
(KinesisDynamicSink)
new KinesisDynamicSink.KinesisDynamicTableSinkBuilder()
.setConsumedDataType(sinkSchema.toPhysicalRowDataType())
.setStream(STREAM_NAME)
.setKinesisClientProperties(defaultProducerProperties())
.setEncodingFormat(new TestFormatFactory.EncodingFormatMock(","))
.setPartitioner(new RandomKinesisPartitionKeyGenerator<>())
.build();
Assertions.assertThat(actualSink).isEqualTo(expectedSink);
// verify the produced sink
DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider =
actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false));
Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink();
Assertions.assertThat(sinkFunction).isInstanceOf(KinesisDataStreamsSink.class);
}
@Test
public void testGoodTableSinkForNonPartitionedTableWithSinkOptions() {
ResolvedSchema sinkSchema = defaultSinkSchema();
Map<String, String> sinkOptions = defaultTableOptionsWithSinkOptions().build();
// Construct actual DynamicTableSink using FactoryUtil
KinesisDynamicSink actualSink =
(KinesisDynamicSink) createTableSink(sinkSchema, sinkOptions);
// Construct expected DynamicTableSink using factory under test
KinesisDynamicSink expectedSink =
(KinesisDynamicSink)
getDefaultSinkBuilder()
.setConsumedDataType(sinkSchema.toPhysicalRowDataType())
.setStream(STREAM_NAME)
.setKinesisClientProperties(defaultProducerProperties())
.setEncodingFormat(new TestFormatFactory.EncodingFormatMock(","))
.setPartitioner(new RandomKinesisPartitionKeyGenerator<>())
.build();
Assertions.assertThat(actualSink).isEqualTo(expectedSink);
// verify the produced sink
DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider =
actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false));
Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink();
Assertions.assertThat(sinkFunction).isInstanceOf(KinesisDataStreamsSink.class);
}
@Test
public void testGoodTableSinkForNonPartitionedTableWithProducerOptions() {
ResolvedSchema sinkSchema = defaultSinkSchema();
Map<String, String> sinkOptions = defaultTableOptionsWithDeprecatedOptions().build();
// Construct actual DynamicTableSink using FactoryUtil
KinesisDynamicSink actualSink =
(KinesisDynamicSink) createTableSink(sinkSchema, sinkOptions);
// Construct expected DynamicTableSink using factory under test
KinesisDynamicSink expectedSink =
(KinesisDynamicSink)
new KinesisDynamicSink.KinesisDynamicTableSinkBuilder()
.setFailOnError(true)
.setMaxBatchSize(100)
.setMaxInFlightRequests(100)
.setMaxTimeInBufferMS(1000)
.setConsumedDataType(sinkSchema.toPhysicalRowDataType())
.setStream(STREAM_NAME)
.setKinesisClientProperties(defaultProducerProperties())
.setEncodingFormat(new TestFormatFactory.EncodingFormatMock(","))
.setPartitioner(new RandomKinesisPartitionKeyGenerator<>())
.build();
// verify that the constructed DynamicTableSink is as expected
Assertions.assertThat(actualSink).isEqualTo(expectedSink);
// verify the produced sink
DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider =
actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false));
Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink();
Assertions.assertThat(sinkFunction).isInstanceOf(KinesisDataStreamsSink.class);
}
@Test
public void testBadTableSinkForCustomPartitionerForPartitionedTable() {
ResolvedSchema sinkSchema = defaultSinkSchema();
Map<String, String> sinkOptions =
defaultTableOptions()
.withTableOption(KinesisConnectorOptions.SINK_PARTITIONER, "random")
.build();
Assertions.assertThatExceptionOfType(ValidationException.class)
.isThrownBy(
() ->
createTableSink(
sinkSchema, Arrays.asList("name", "curr_id"), sinkOptions))
.havingCause()
.withMessageContaining(
String.format(
"Cannot set %s option for a table defined with a PARTITIONED BY clause",
KinesisConnectorOptions.SINK_PARTITIONER.key()));
}
@Test
public void testBadTableSinkForNonExistingPartitionerClass() {
ResolvedSchema sinkSchema = defaultSinkSchema();
Map<String, String> sinkOptions =
defaultTableOptions()
.withTableOption(KinesisConnectorOptions.SINK_PARTITIONER, "abc")
.build();
Assertions.assertThatExceptionOfType(ValidationException.class)
.isThrownBy(() -> createTableSink(sinkSchema, sinkOptions))
.havingCause()
.withMessageContaining("Could not find and instantiate partitioner class 'abc'");
}
private ResolvedSchema defaultSinkSchema() {
return ResolvedSchema.of(
Column.physical("name", DataTypes.STRING()),
Column.physical("curr_id", DataTypes.BIGINT()),
Column.physical("time", DataTypes.TIMESTAMP(3)));
}
private TableOptionsBuilder defaultTableOptionsWithSinkOptions() {
return defaultTableOptions()
.withTableOption(SINK_FAIL_ON_ERROR.key(), "true")
.withTableOption(MAX_BATCH_SIZE.key(), "100")
.withTableOption(MAX_IN_FLIGHT_REQUESTS.key(), "100")
.withTableOption(MAX_BUFFERED_REQUESTS.key(), "100")
.withTableOption(FLUSH_BUFFER_SIZE.key(), "1000")
.withTableOption(FLUSH_BUFFER_TIMEOUT.key(), "1000");
}
private TableOptionsBuilder defaultTableOptionsWithDeprecatedOptions() {
return defaultTableOptions()
.withTableOption("sink.producer.record-max-buffered-time", "1000")
.withTableOption("sink.producer.collection-max-size", "100")
.withTableOption("sink.producer.collection-max-count", "100")
.withTableOption("sink.producer.fail-on-error", "true");
}
private TableOptionsBuilder defaultTableOptions() {
String connector = KinesisDynamicTableSinkFactory.IDENTIFIER;
String format = TestFormatFactory.IDENTIFIER;
return new TableOptionsBuilder(connector, format)
// default table options
.withTableOption(KinesisConnectorOptions.STREAM, STREAM_NAME)
.withTableOption("aws.region", "us-west-2")
.withTableOption("aws.credentials.provider", "BASIC")
.withTableOption("aws.credentials.basic.accesskeyid", "ververicka")
.withTableOption(
"aws.credentials.basic.secretkey",
"SuperSecretSecretSquirrel") // default format options
.withFormatOption(TestFormatFactory.DELIMITER, ",")
.withFormatOption(TestFormatFactory.FAIL_ON_MISSING, "true");
}
private KinesisDynamicSink.KinesisDynamicTableSinkBuilder getDefaultSinkBuilder() {
return new KinesisDynamicSink.KinesisDynamicTableSinkBuilder()
.setFailOnError(true)
.setMaxBatchSize(100)
.setMaxInFlightRequests(100)
.setMaxBufferSizeInBytes(1000)
.setMaxBufferedRequests(100)
.setMaxTimeInBufferMS(1000);
}
private Properties defaultProducerProperties() {
return new Properties() {
{
setProperty("aws.region", "us-west-2");
setProperty("aws.credentials.provider", "BASIC");
setProperty("aws.credentials.provider.basic.accesskeyid", "ververicka");
setProperty(
"aws.credentials.provider.basic.secretkey", "SuperSecretSecretSquirrel");
}
};
}
}
| apache-2.0 |
jbeecham/ovirt-engine | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/view/tab/disk/SubTabDiskPermissionView.java | 1646 | package org.ovirt.engine.ui.webadmin.section.main.view.tab.disk;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.permissions;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.system.ClientStorage;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicommonweb.models.disks.DiskListModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.disk.SubTabDiskPermissionPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.tab.AbstractSubTabPermissionsView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
public class SubTabDiskPermissionView extends AbstractSubTabPermissionsView<Disk, DiskListModel>
implements SubTabDiskPermissionPresenter.ViewDef {
interface ViewIdHandler extends ElementIdHandler<SubTabDiskPermissionView> {
ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
}
@Inject
public SubTabDiskPermissionView(SearchableDetailModelProvider<permissions, DiskListModel, PermissionListModel> modelProvider,
EventBus eventBus,
ClientStorage clientStorage, ApplicationConstants constants) {
super(modelProvider, eventBus, clientStorage, constants);
}
@Override
protected void generateIds() {
ViewIdHandler.idHandler.generateAndSetIds(this);
}
}
| apache-2.0 |
flaminc/olingo-odata4 | samples/tutorials/p11_batch/src/main/java/myservice/mynamespace/service/DemoBatchProcessor.java | 8323 | /*
* 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 myservice.mynamespace.service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.batch.BatchFacade;
import org.apache.olingo.server.api.deserializer.batch.BatchOptions;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import org.apache.olingo.server.api.processor.BatchProcessor;
import myservice.mynamespace.data.Storage;
/**
* --abc123
Content-Type: application/http
Content-Transfer-Encoding: binary
GET Products HTTP/1.1
Content-Type: application/json
--abc123
Content-Type: multipart/mixed;boundary=changeset_abc
--changeset_abc
Content-Type: application/http
Content-Transfer-Encoding:binary
Content-Id: abc1234
POST Products HTTP/1.1
Content-Type: application/json
{"Name": "Test", "Description": "This is a test product"}
--changeset_abc
Content-Type: application/http
Content-Transfer-Encoding:binary
Content-ID: 2
PATCH $abc1234 HTTP/1.1
Content-Type: application/json
Accept: application/json
{"Name": "Bäääääm"}
--changeset_abc--
--abc123
Content-Type: application/http
Content-Transfer-Encoding: binary
GET Products HTTP/1.1
Content-Type: application/json
--abc123--
*
*/
public class DemoBatchProcessor implements BatchProcessor {
private OData odata;
private Storage storage;
public DemoBatchProcessor(final Storage storage) {
this.storage = storage;
}
@Override
public void init(final OData odata, final ServiceMetadata serviceMetadata) {
this.odata = odata;
}
@Override
public void processBatch(final BatchFacade facade, final ODataRequest request, final ODataResponse response)
throws ODataApplicationException, ODataLibraryException {
// 1. Extract the boundary
final String boundary = facade.extractBoundaryFromContentType(request.getHeader(HttpHeader.CONTENT_TYPE));
// 2. Prepare the batch options
final BatchOptions options = BatchOptions.with().rawBaseUri(request.getRawBaseUri())
.rawServiceResolutionUri(request.getRawServiceResolutionUri())
.build();
// 3. Deserialize the batch request
final List<BatchRequestPart> requestParts = odata.createFixedFormatDeserializer()
.parseBatchRequest(request.getBody(), boundary, options);
// 4. Execute the batch request parts
final List<ODataResponsePart> responseParts = new ArrayList<ODataResponsePart>();
for (final BatchRequestPart part : requestParts) {
responseParts.add(facade.handleBatchRequest(part));
}
// 5. Serialize the response content
final InputStream responseContent = odata.createFixedFormatSerializer().batchResponse(responseParts, boundary);
// 6. Create a new boundary for the response
final String responseBoundary = "batch_" + UUID.randomUUID().toString();
// 7. Setup response
response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED + ";boundary=" + responseBoundary);
response.setContent(responseContent);
response.setStatusCode(HttpStatusCode.ACCEPTED.getStatusCode());
}
@Override
public ODataResponsePart processChangeSet(final BatchFacade facade, final List<ODataRequest> requests)
throws ODataApplicationException, ODataLibraryException {
/*
* OData Version 4.0 Part 1: Protocol Plus Errata 02
* 11.7.4 Responding to a Batch Request
*
* All operations in a change set represent a single change unit so a service MUST successfully process and
* apply all the requests in the change set or else apply none of them. It is up to the service implementation
* to define rollback semantics to undo any requests within a change set that may have been applied before
* another request in that same change set failed and thereby apply this all-or-nothing requirement.
* The service MAY execute the requests within a change set in any order and MAY return the responses to the
* individual requests in any order. The service MUST include the Content-ID header in each response with the
* same value that the client specified in the corresponding request, so clients can correlate requests
* and responses.
*
* To keep things simple, we dispatch the requests within the change set to the other processor interfaces.
*/
final List<ODataResponse> responses = new ArrayList<ODataResponse>();
try {
storage.beginTransaction();
for(final ODataRequest request : requests) {
// Actual request dispatching to the other processor interfaces.
final ODataResponse response = facade.handleODataRequest(request);
// Determine if an error occurred while executing the request.
// Exceptions thrown by the processors get caught and result in a proper OData response.
final int statusCode = response.getStatusCode();
if(statusCode < 400) {
// The request has been executed successfully. Return the response as a part of the change set
responses.add(response);
} else {
// Something went wrong. Undo all previous requests in this Change Set
storage.rollbackTranscation();
/*
* In addition the response must be provided as follows:
*
* OData Version 4.0 Part 1: Protocol Plus Errata 02
* 11.7.4 Responding to a Batch Request
*
* When a request within a change set fails, the change set response is not represented using
* the multipart/mixed media type. Instead, a single response, using the application/http media type
* and a Content-Transfer-Encoding header with a value of binary, is returned that applies to all requests
* in the change set and MUST be formatted according to the Error Handling defined
* for the particular response format.
*
* This can be simply done by passing the response of the failed ODataRequest to a new instance of
* ODataResponsePart and setting the second parameter "isChangeSet" to false.
*/
return new ODataResponsePart(response, false);
}
}
// Everything went well, so commit the changes.
storage.commitTransaction();
return new ODataResponsePart(responses, true);
} catch(ODataApplicationException e) {
// See below
storage.rollbackTranscation();
throw e;
} catch(ODataLibraryException e) {
// The request is malformed or the processor implementation is not correct.
// Throwing an exception will stop the whole batch request not only the change set!
storage.rollbackTranscation();
throw e;
}
}
}
| apache-2.0 |
Gadreel/divconq | divconq.core/src/main/java/divconq/json3/io/IOContext.java | 9282 | package divconq.json3.io;
import divconq.json3.JsonEncoding;
import divconq.json3.util.BufferRecycler;
import divconq.json3.util.TextBuffer;
/**
* To limit number of configuration and state objects to pass, all
* contextual objects that need to be passed by the factory to
* readers and writers are combined under this object. One instance
* is created for each reader and writer.
*<p>
* NOTE: non-final since 2.4, to allow sub-classing.
*/
public class IOContext
{
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
/**
* Reference to the source object, which can be used for displaying
* location information
*/
protected final Object _sourceRef;
/**
* Encoding used by the underlying stream, if known.
*/
protected JsonEncoding _encoding;
/**
* Flag that indicates whether underlying input/output source/target
* object is fully managed by the owner of this context (parser or
* generator). If true, it is, and is to be closed by parser/generator;
* if false, calling application has to do closing (unless auto-closing
* feature is enabled for the parser/generator in question; in which
* case it acts like the owner).
*/
protected final boolean _managedResource;
/*
/**********************************************************
/* Buffer handling, recycling
/**********************************************************
*/
/**
* Recycler used for actual allocation/deallocation/reuse
*/
protected final BufferRecycler _bufferRecycler;
/**
* Reference to the allocated I/O buffer for low-level input reading,
* if any allocated.
*/
protected byte[] _readIOBuffer = null;
/**
* Reference to the allocated I/O buffer used for low-level
* encoding-related buffering.
*/
protected byte[] _writeEncodingBuffer = null;
/**
* Reference to the buffer allocated for temporary use with
* base64 encoding or decoding.
*/
protected byte[] _base64Buffer = null;
/**
* Reference to the buffer allocated for tokenization purposes,
* in which character input is read, and from which it can be
* further returned.
*/
protected char[] _tokenCBuffer = null;
/**
* Reference to the buffer allocated for buffering it for
* output, before being encoded: generally this means concatenating
* output, then encoding when buffer fills up.
*/
protected char[] _concatCBuffer = null;
/**
* Reference temporary buffer Parser instances need if calling
* app decides it wants to access name via 'getTextCharacters' method.
* Regular text buffer can not be used as it may contain textual
* representation of the value token.
*/
protected char[] _nameCopyBuffer = null;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public IOContext(BufferRecycler br, Object sourceRef, boolean managedResource)
{
_bufferRecycler = br;
_sourceRef = sourceRef;
_managedResource = managedResource;
}
public void setEncoding(JsonEncoding enc) {
_encoding = enc;
}
/*
/**********************************************************
/* Public API, accessors
/**********************************************************
*/
public Object getSourceReference() { return _sourceRef; }
public JsonEncoding getEncoding() { return _encoding; }
public boolean isResourceManaged() { return _managedResource; }
/*
/**********************************************************
/* Public API, buffer management
/**********************************************************
*/
public TextBuffer constructTextBuffer() {
return new TextBuffer(_bufferRecycler);
}
/*
*<p>
* Note: the method can only be called once during its life cycle.
* This is to protect against accidental sharing.
*/
public byte[] allocReadIOBuffer() {
_verifyAlloc(_readIOBuffer);
return (_readIOBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_READ_IO_BUFFER));
}
/*
* @since 2.4
*/
public byte[] allocReadIOBuffer(int minSize) {
_verifyAlloc(_readIOBuffer);
return (_readIOBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_READ_IO_BUFFER, minSize));
}
public byte[] allocWriteEncodingBuffer() {
_verifyAlloc(_writeEncodingBuffer);
return (_writeEncodingBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_WRITE_ENCODING_BUFFER));
}
/*
* @since 2.4
*/
public byte[] allocWriteEncodingBuffer(int minSize) {
_verifyAlloc(_writeEncodingBuffer);
return (_writeEncodingBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_WRITE_ENCODING_BUFFER, minSize));
}
/*
* @since 2.1
*/
public byte[] allocBase64Buffer() {
_verifyAlloc(_base64Buffer);
return (_base64Buffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_BASE64_CODEC_BUFFER));
}
public char[] allocTokenBuffer() {
_verifyAlloc(_tokenCBuffer);
return (_tokenCBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_TOKEN_BUFFER));
}
/*
* @since 2.4
*/
public char[] allocTokenBuffer(int minSize) {
_verifyAlloc(_tokenCBuffer);
return (_tokenCBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_TOKEN_BUFFER, minSize));
}
public char[] allocConcatBuffer() {
_verifyAlloc(_concatCBuffer);
return (_concatCBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_CONCAT_BUFFER));
}
public char[] allocNameCopyBuffer(int minSize) {
_verifyAlloc(_nameCopyBuffer);
return (_nameCopyBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_NAME_COPY_BUFFER, minSize));
}
/*
* Method to call when all the processing buffers can be safely
* recycled.
*/
public void releaseReadIOBuffer(byte[] buf) {
if (buf != null) {
/* Let's do sanity checks to ensure once-and-only-once release,
* as well as avoiding trying to release buffers not owned
*/
_verifyRelease(buf, _readIOBuffer);
_readIOBuffer = null;
_bufferRecycler.releaseByteBuffer(BufferRecycler.BYTE_READ_IO_BUFFER, buf);
}
}
public void releaseWriteEncodingBuffer(byte[] buf) {
if (buf != null) {
/* Let's do sanity checks to ensure once-and-only-once release,
* as well as avoiding trying to release buffers not owned
*/
_verifyRelease(buf, _writeEncodingBuffer);
_writeEncodingBuffer = null;
_bufferRecycler.releaseByteBuffer(BufferRecycler.BYTE_WRITE_ENCODING_BUFFER, buf);
}
}
public void releaseBase64Buffer(byte[] buf) {
if (buf != null) { // sanity checks, release once-and-only-once, must be one owned
_verifyRelease(buf, _base64Buffer);
_base64Buffer = null;
_bufferRecycler.releaseByteBuffer(BufferRecycler.BYTE_BASE64_CODEC_BUFFER, buf);
}
}
public void releaseTokenBuffer(char[] buf) {
if (buf != null) {
_verifyRelease(buf, _tokenCBuffer);
_tokenCBuffer = null;
_bufferRecycler.releaseCharBuffer(BufferRecycler.CHAR_TOKEN_BUFFER, buf);
}
}
public void releaseConcatBuffer(char[] buf) {
if (buf != null) {
// 14-Jan-2014, tatu: Let's actually allow upgrade of the original buffer.
_verifyRelease(buf, _concatCBuffer);
_concatCBuffer = null;
_bufferRecycler.releaseCharBuffer(BufferRecycler.CHAR_CONCAT_BUFFER, buf);
}
}
public void releaseNameCopyBuffer(char[] buf) {
if (buf != null) {
// 14-Jan-2014, tatu: Let's actually allow upgrade of the original buffer.
_verifyRelease(buf, _nameCopyBuffer);
_nameCopyBuffer = null;
_bufferRecycler.releaseCharBuffer(BufferRecycler.CHAR_NAME_COPY_BUFFER, buf);
}
}
/*
/**********************************************************
/* Internal helpers
/**********************************************************
*/
protected final void _verifyAlloc(Object buffer) {
if (buffer != null) { throw new IllegalStateException("Trying to call same allocXxx() method second time"); }
}
protected final void _verifyRelease(byte[] toRelease, byte[] src) {
if ((toRelease != src) && (toRelease.length <= src.length)) { throw wrongBuf(); }
}
protected final void _verifyRelease(char[] toRelease, char[] src) {
if ((toRelease != src) && (toRelease.length <= src.length)) { throw wrongBuf(); }
}
private IllegalArgumentException wrongBuf() { return new IllegalArgumentException("Trying to release buffer not owned by the context"); }
}
| apache-2.0 |
mdogan/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/util/executor/TimeoutRunnable.java | 873 | /*
* Copyright (c) 2008-2020, Hazelcast, Inc. 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.
* 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.hazelcast.internal.util.executor;
import java.util.concurrent.TimeUnit;
/**
* Interface for runnable with timeout value
*/
public interface TimeoutRunnable extends Runnable {
long getTimeout();
TimeUnit getTimeUnit();
}
| apache-2.0 |