answer stringlengths 17 10.2M |
|---|
package org.mskcc.portal.servlet;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;
import org.owasp.validator.html.PolicyException;
import org.apache.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.ArrayList;
/**
* Generates Plots via RServe.
*
* @author Anders Jacobsen, Ethan Cerami.
*/
public class PlotServlet extends HttpServlet {
private static Logger logger = Logger.getLogger(PlotServlet.class);
public static final String SKIN = "skin";
public static final String SKIN_COL_GROUP = "skin_col_gp";
public static final String SKIN_NORMALS = "skin_normals";
public static final int PLOT_WIDTH = 600;
public static final int PLOT_HEIGHT = 600;
private static final String UNDEFINED = "undefined";
private static ServletXssUtil servletXssUtil;
/**
* Initializes the servlet.
*
* @throws ServletException Serlvet Init Error.
*/
public void init() throws ServletException {
super.init();
try {
servletXssUtil = ServletXssUtil.getInstance();
} catch (PolicyException e) {
throw new ServletException (e);
}
}
/**
* Processes GET Request.
*
* @param req Http Servlet Request.
* @param res http Servlet Response.
* @throws ServletException Servlet Error.
* @throws IOException IO Error.
*/
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
try {
// Get All Parameters Safely
Pattern p = Pattern.compile(",");
// TODO: Later: ACCESS CONTROL: change to cancer study, etc.
String cancerTypeId = servletXssUtil.getCleanInput(req, QueryBuilder.CANCER_STUDY_ID);
String[] genesList = p.split(servletXssUtil.getCleanInput(req, QueryBuilder.GENE_LIST));
String[] geneticProfilesList = p.split
(servletXssUtil.getCleanInput(req, QueryBuilder.GENETIC_PROFILE_IDS));
String skin = servletXssUtil.getCleanInput(req, SKIN);
String caseSetId = servletXssUtil.getCleanInput(req, QueryBuilder.CASE_SET_ID);
String caseIds = servletXssUtil.getCleanInput(req, QueryBuilder.CASE_IDS);
String format = servletXssUtil.getCleanInput(req, QueryBuilder.FORMAT);
String skinColGroup = servletXssUtil.getCleanInput(req, SKIN_COL_GROUP);
String skinNormals = servletXssUtil.getCleanInput(req, SKIN_NORMALS);
if (format == null || !format.equals("pdf")) {
format = "png"; // default is png
}
// Split Gene List
String genes = "";
for (String s : genesList) {
genes += "'" + s + "',";
}
genes = genes.substring(0, genes.length() - 1);
String geneticProfiles = "";
for (String s : geneticProfilesList) {
geneticProfiles += "'" + s + "',";
}
geneticProfiles = geneticProfiles.substring(0, geneticProfiles.length() - 1);
RConnection c = new RConnection();
if (format.equals("pdf")) {
res.setContentType("application/pdf");
} else {
res.setContentType("image/png");
}
String tmpfile = "tmp" + String.valueOf(System.currentTimeMillis() + "." + format);
// Must use Cairo Library, so that we can generate Images without GUI
StringBuffer plot = new StringBuffer("library(cgdsr);\n");
plot.append("library(Cairo);\n");
if (format.equals("png")) {
plot.append("Cairo(width=" + PLOT_WIDTH + ", height="
+ PLOT_HEIGHT + ", file='" + tmpfile + "', type='" + format + "', units=\"px\")\n");
} else {
plot.append("pdf(width=6, height=6, file='" + tmpfile + "')\n");
}
String currentUrl = req.getRequestURL().toString();
String localHost = "127.0.0.1";
logger.debug("Current URL is: " + currentUrl);
// locate host name to replace
int startOfHostname = currentUrl.indexOf("
int endOfHostname = currentUrl.indexOf(":", startOfHostname);
// port not included in url
if (endOfHostname == -1) {
endOfHostname = currentUrl.indexOf("/", startOfHostname);
// we need to append port number
localHost += ":38080";
}
String hostname = currentUrl.substring(startOfHostname, endOfHostname);
String cgdsUrl = currentUrl.replaceAll("plot.(do|pdf)", "");
cgdsUrl = cgdsUrl.replace(hostname, localHost);
logger.debug("Web API URL is: " + cgdsUrl);
plot.append ("c = CGDS('" + cgdsUrl + "',TRUE);\n");
if (caseSetId != null && !caseSetId.equals("-1")) {
plot.append (String.format("plot(c, '%s', c(%s), c(%s), '%s', skin='%s' ",
cancerTypeId, genes, geneticProfiles, caseSetId, skin));
} else {
ArrayList <String> caseList = new ArrayList<String>();
for (String currentCase : caseIds.split("[\\s,]+")) {
currentCase = currentCase.trim();
if (currentCase.length() > 0) {
caseList.add(currentCase);
}
}
StringBuffer caseBuffer = new StringBuffer();
for (int i=0; i<caseList.size(); i++) {
caseBuffer.append ("\"" + caseList.get(i) + "\"");
if (i < caseList.size() -1) {
caseBuffer.append (",");
}
}
plot.append (String.format("plot(c, '%s', c(%s), c(%s), cases=c(%s), skin='%s' ",
cancerTypeId, genes, geneticProfiles, caseBuffer.toString(), skin));
}
if (skinColGroup != null && !skinColGroup.equals(UNDEFINED)) {
plot.append (", skin.col.gp=c(");
if (skinColGroup.contains(",")) {
String colGroups [] = skinColGroup.split(",");
for (int i=0; i<colGroups.length; i++) {
plot.append ("'" + colGroups[i] +"'");
if (i < colGroups.length -1) {
plot.append (",");
}
}
}
else {
plot.append ("'" + skinColGroup + "'");
}
plot.append (")");
}
if (skinNormals != null) {
plot.append (", skin.normals='" + skinNormals + "'");
}
plot.append (");\n");
plot.append ("dev.off();\n");
logger.debug("Call to R Follows:");
logger.debug(plot.toString());
// open device
c.parseAndEval(plot.toString());
// There is no I/O API in REngine because it's actually more efficient to use R for this
// we limit the file size to 1MB which should be sufficient and we delete the file as well
REXP xp = c.parseAndEval("r=readBin('" + tmpfile
+ "','raw',1024*1024); unlink('" + tmpfile + "'); r;");
// now this is pretty boring AWT stuff - create an image from the data and display it ...
byte[] imageBytes = xp.asBytes();
res.setContentLength(imageBytes.length);
res.getOutputStream().write(imageBytes);
c.close();
} catch (Exception e) {
// In the event of an exception, redirect to the Plot NA Image.
logger.error(e);
res.sendRedirect("images/plots_na.png");
}
}
} |
package won.protocol.agreement;
import org.apache.jena.query.Dataset;
import org.apache.jena.rdf.model.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import won.protocol.util.DynamicDatasetToDatasetBySparqlGSPOSelectFunction;
import java.net.URI;
import java.util.List;
import java.util.Set;
/**
* @deprecated replaced by {@Link won.protocol.agreement.AgreementProtocolState}
*/
@Deprecated
public class AgreementProtocol {
private static final Logger logger = LoggerFactory.getLogger(AgreementProtocol.class);
private static DynamicDatasetToDatasetBySparqlGSPOSelectFunction cutAfterMessageFunction;
/**
* Calculates all agreements present in the specified conversation dataset.
*/
public static Dataset getAgreements(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
public static AgreementProtocolUris getHighlevelProtocolUris(Dataset connectionDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
public static Model getAgreement(Dataset conversationDataset, URI agreementURI) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Calculates all open proposals present in the specified conversation dataset.
* Returns the envelope graph of the proposal with the contents of the proposed
* message inside.
* @param conversationDataset
* @return
*/
public static Dataset getProposals(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
public static Model getProposal(Dataset conversationDataset, String proposalUri) {
throw new UnsupportedOperationException("not yet implemented");
}
public static Set<URI> getProposalUris(Dataset conversationDataset){
throw new UnsupportedOperationException("not yet implemented");
}
public static Set<URI> getAgreementUris(Dataset conversationDataset){
throw new UnsupportedOperationException("not yet implemented");
}
public static Set<URI> getCancelledAgreementUris(Dataset conversationDataset){
throw new UnsupportedOperationException("not yet implemented");
}
public static Set<URI> getAgreementsProposedToBeCancelledUris(Dataset conversationDataset){
throw new UnsupportedOperationException("not yet implemented");
}
public static Set<URI> getRejectedProposalUris(Dataset conversationDataset){
throw new UnsupportedOperationException("not yet implemented");
}
/** reveiw and rewrite the JavaDoc descriptions below **/
/**
* Calculates all open proposals to cancel present in the specified conversation dataset.
* returns envelope graph of the proposaltocancel with the contents of the target agreement to
* cancel inside.
* @param conversationDataset
* @return
*/
public static Dataset getProposalsToCancel(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?openprop agr:proposes ?openclause .
* ?openprop == unaccepted propsal
* ?openclause == proposed clause that is unaccepted
* @param conversationDataset
* @return
*/
public static Model getPendingProposes(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?openprop agr:proposesToCancel ?acc .
* ?openprop == unaccepted proposal to cancel
* ?acc == agreement proposed for cancellation
* @param conversationDataset
* @return
*/
public static Model getPendingProposesToCancel(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?prop agr:proposes ?clause .
* ?prop == accepted proposal in an agreement
* ?clause == accepted clause in an agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptedProposes(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?acc agr:accepts ?prop .
* ?prop == accepted proposal in an agreement
* ?acc == agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptsProposes(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?cancelProp2 agr:proposesToCancel ?acc .
* ?cancelProp2 == accepted proposal to cancel
* ?acc == agreement proposed for cancellation
* @param conversationDataset
* @return
*/
public static Model getAcceptedProposesToCancel(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?cancelAcc2 agr:accepts ?cancelProp2 .
* ?cancelProp2 . == accepted proposal to cancel
* ?cancelAcc2 == cancallation agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptsProposesToCancel(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?prop agr:proposes ?clause .
* ?prop == accepted proposal in agreement that was cancelled
* ?clause == accepted clause in an agreement that was cancelled
* @param conversationDataset
* @return
*/
public static Model getProposesInCancelledAgreement(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?acc agr:accepts ?prop .
* ?acc == agreement that was cancelled
* ?prop == accepted proposal in agreement that was cancelled
* @param conversationDataset
* @return
*/
public static Model getAcceptsInCancelledAgreement(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Returns ?retractingMsg mod:retracts ?retractedMsg .
* ?retractingMsg == message containing mod:retracts
* ?retractedMsg == message that was retracted
* @param conversationDataset
* @return
*/
public static Model getAcceptedRetracts(Dataset conversationDataset) {
throw new UnsupportedOperationException("not yet implemented");
}
public static List<URI> getRetractedAgreements(Dataset input, URI acceptsMessageURI) {
throw new UnsupportedOperationException("not yet implemented");
}
public static Set<URI> getRetractedUris(Dataset input){
throw new UnsupportedOperationException("not yet implemented");
}
public static Dataset cutOffAfterMessage(Dataset input, URI acceptsMessageURI) {
throw new UnsupportedOperationException("not yet implemented");
}
public static List<URI> getAcceptMessages(Dataset input) {
throw new UnsupportedOperationException("not yet implemented");
}
public static List<URI> getProposalSingleAgreement(Dataset actual, URI acceptsMessageURI) {
throw new UnsupportedOperationException("not yet implemented");
}
} |
package org.elasticsearch.xpack.sql.plan.logical.command.sys;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer;
import org.elasticsearch.xpack.sql.analysis.index.EsIndex;
import org.elasticsearch.xpack.sql.analysis.index.IndexResolution;
import org.elasticsearch.xpack.sql.analysis.index.IndexResolver;
import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry;
import org.elasticsearch.xpack.sql.parser.SqlParser;
import org.elasticsearch.xpack.sql.plan.logical.command.Command;
import org.elasticsearch.xpack.sql.session.SqlSession;
import org.elasticsearch.xpack.sql.type.DataType;
import org.elasticsearch.xpack.sql.type.TypesTests;
import java.sql.JDBCType;
import java.util.List;
import java.util.TimeZone;
import static java.util.Arrays.asList;
import static org.elasticsearch.action.ActionListener.wrap;
import static org.mockito.Mockito.mock;
public class SysTypesTests extends ESTestCase {
private final SqlParser parser = new SqlParser();
private Tuple<Command, SqlSession> sql(String sql) {
EsIndex test = new EsIndex("test", TypesTests.loadMapping("mapping-multi-field-with-nested.json", true));
Analyzer analyzer = new Analyzer(new FunctionRegistry(), IndexResolution.valid(test), TimeZone.getTimeZone("UTC"), null);
Command cmd = (Command) analyzer.analyze(parser.createStatement(sql), true);
IndexResolver resolver = mock(IndexResolver.class);
SqlSession session = new SqlSession(null, null, null, resolver, null, null, null, null);
return new Tuple<>(cmd, session);
}
public void testSysTypes() throws Exception {
Command cmd = sql("SYS TYPES").v1();
List<String> names = asList("BYTE", "LONG", "BINARY", "NULL", "INTEGER", "SHORT", "HALF_FLOAT", "SCALED_FLOAT", "FLOAT", "DOUBLE",
"KEYWORD", "TEXT", "IP", "BOOLEAN", "DATE",
"INTERVAL_YEAR", "INTERVAL_MONTH", "INTERVAL_DAY", "INTERVAL_HOUR", "INTERVAL_MINUTE", "INTERVAL_SECOND",
"INTERVAL_YEAR_TO_MONTH", "INTERVAL_DAY_TO_HOUR", "INTERVAL_DAY_TO_MINUTE", "INTERVAL_DAY_TO_SECOND",
"INTERVAL_HOUR_TO_MINUTE", "INTERVAL_HOUR_TO_SECOND", "INTERVAL_MINUTE_TO_SECOND",
"UNSUPPORTED", "OBJECT", "NESTED");
cmd.execute(null, wrap(r -> {
assertEquals(19, r.columnCount());
assertEquals(DataType.values().length, r.size());
assertFalse(r.schema().types().contains(DataType.NULL));
// test numeric as signed
assertFalse(r.column(9, Boolean.class));
// make sure precision is returned as boolean (not int)
assertFalse(r.column(10, Boolean.class));
// no auto-increment
assertFalse(r.column(11, Boolean.class));
for (int i = 0; i < r.size(); i++) {
assertEquals(names.get(i), r.column(0));
r.advanceRow();
}
}, ex -> fail(ex.getMessage())));
}
public void testSysTypesDefaultFiltering() throws Exception {
Command cmd = sql("SYS TYPES 0").v1();
cmd.execute(null, wrap(r -> {
assertEquals(DataType.values().length, r.size());
}, ex -> fail(ex.getMessage())));
}
public void testSysTypesPositiveFiltering() throws Exception {
// boolean = 16
Command cmd = sql("SYS TYPES " + JDBCType.BOOLEAN.getVendorTypeNumber()).v1();
cmd.execute(null, wrap(r -> {
assertEquals(1, r.size());
assertEquals("BOOLEAN", r.column(0));
}, ex -> fail(ex.getMessage())));
}
public void testSysTypesNegativeFiltering() throws Exception {
Command cmd = sql("SYS TYPES " + JDBCType.TINYINT.getVendorTypeNumber()).v1();
cmd.execute(null, wrap(r -> {
assertEquals(1, r.size());
assertEquals("BYTE", r.column(0));
}, ex -> fail(ex.getMessage())));
}
public void testSysTypesMultipleMatches() throws Exception {
Command cmd = sql("SYS TYPES " + JDBCType.VARCHAR.getVendorTypeNumber()).v1();
cmd.execute(null, wrap(r -> {
assertEquals(3, r.size());
assertEquals("KEYWORD", r.column(0));
assertTrue(r.advanceRow());
assertEquals("TEXT", r.column(0));
assertTrue(r.advanceRow());
assertEquals("IP", r.column(0));
}, ex -> fail(ex.getMessage())));
}
} |
package com.xamoom.android.xamoomsdk.Storage.TableContracts;
import android.provider.BaseColumns;
public class OfflineEnduserContract {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "OfflineEnduser.db";
public static final String TEXT_TYPE = " TEXT";
public static final String INTEGER_TYPE = " INTEGER";
public static final String REAL_TYPE = " REAL";
public static final String UNIQUE = " UNIQUE";
public static final String COMMA_SEP = ",";
private OfflineEnduserContract() {}
/**
* System
*/
public static class SystemEntry implements BaseColumns {
public static final String TABLE_NAME = "System";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_NAME = "name";
public static final String COLUMN_NAME_URL = "url";
public static final String CREATE_TABLE =
"CREATE TABLE " + SystemEntry.TABLE_NAME + " (" +
SystemEntry._ID + " INTEGER PRIMARY KEY," +
SystemEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + UNIQUE + COMMA_SEP +
SystemEntry.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP +
SystemEntry.COLUMN_NAME_URL + TEXT_TYPE + " )";
public static final String[] PROJECTION = {
SystemEntry._ID,
SystemEntry.COLUMN_NAME_JSON_ID,
SystemEntry.COLUMN_NAME_NAME,
SystemEntry.COLUMN_NAME_URL
};
}
/**
* Style
*/
public static class StyleEntry implements BaseColumns {
public static final String TABLE_NAME = "Style";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_SYSTEM_RELATION = "system";
public static final String COLUMN_NAME_BACKGROUND_COLOR = "background_color";
public static final String COLUMN_NAME_HIGHLIGHT_COLOR = "highlight_color";
public static final String COLUMN_NAME_FOREGROUND_COLOR = "foreground_color";
public static final String COLUMN_NAME_CHROME_HEADER_COLOR = "chrome_header_color";
public static final String COLUMN_NAME_MAP_PIN = "map_pin";
public static final String COLUMN_NAME_ICON = "icon";
public static final String CREATE_TABLE =
"CREATE TABLE " + StyleEntry.TABLE_NAME + " (" +
StyleEntry._ID + " INTEGER PRIMARY KEY," +
StyleEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + UNIQUE + COMMA_SEP +
StyleEntry.COLUMN_NAME_SYSTEM_RELATION + INTEGER_TYPE + COMMA_SEP +
StyleEntry.COLUMN_NAME_BACKGROUND_COLOR + TEXT_TYPE + COMMA_SEP +
StyleEntry.COLUMN_NAME_HIGHLIGHT_COLOR + TEXT_TYPE + COMMA_SEP +
StyleEntry.COLUMN_NAME_FOREGROUND_COLOR + TEXT_TYPE + COMMA_SEP +
StyleEntry.COLUMN_NAME_CHROME_HEADER_COLOR + TEXT_TYPE + COMMA_SEP +
StyleEntry.COLUMN_NAME_MAP_PIN + TEXT_TYPE + COMMA_SEP +
StyleEntry.COLUMN_NAME_ICON + TEXT_TYPE + " )";
public static final String[] PROJECTION = {
StyleEntry._ID,
StyleEntry.COLUMN_NAME_JSON_ID,
StyleEntry.COLUMN_NAME_SYSTEM_RELATION,
StyleEntry.COLUMN_NAME_BACKGROUND_COLOR,
StyleEntry.COLUMN_NAME_HIGHLIGHT_COLOR,
StyleEntry.COLUMN_NAME_FOREGROUND_COLOR,
StyleEntry.COLUMN_NAME_CHROME_HEADER_COLOR,
StyleEntry.COLUMN_NAME_MAP_PIN,
StyleEntry.COLUMN_NAME_ICON,
};
}
/**
* Settings
*/
public static class SettingEntry implements BaseColumns {
public static final String TABLE_NAME = "Settings";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_SYSTEM_RELATION = "system";
public static final String COLUMN_NAME_PLAYSTORE_ID = "playstore_id";
public static final String COLUMN_NAME_APPSTORE_ID = "appstore_id";
public static final String CREATE_TABLE =
"CREATE TABLE " + SettingEntry.TABLE_NAME + " (" +
SettingEntry._ID + " INTEGER PRIMARY KEY," +
SettingEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + UNIQUE + COMMA_SEP +
SettingEntry.COLUMN_NAME_SYSTEM_RELATION + INTEGER_TYPE + COMMA_SEP +
SettingEntry.COLUMN_NAME_PLAYSTORE_ID + TEXT_TYPE + COMMA_SEP +
SettingEntry.COLUMN_NAME_APPSTORE_ID + TEXT_TYPE + " )";
public static final String[] PROJECTION = {
SettingEntry._ID,
SettingEntry.COLUMN_NAME_JSON_ID,
SettingEntry.COLUMN_NAME_SYSTEM_RELATION,
SettingEntry.COLUMN_NAME_PLAYSTORE_ID,
SettingEntry.COLUMN_NAME_APPSTORE_ID
};
}
/**
* Spot
*/
public static class SpotEntry implements BaseColumns {
public static final String TABLE_NAME = "Spot";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_RELATION_SYSTEM = "system";
public static final String COLUMN_NAME_RELATION_CONTENT = "content";
public static final String COLUMN_NAME_NAME = "name";
public static final String COLUMN_NAME_DESCRIPTION = "description";
public static final String COLUMN_NAME_PUBLIC_IMAGE_URL = "publicImageUrl";
public static final String COLUMN_NAME_LOCATION_LAT = "locationLat";
public static final String COLUMN_NAME_LOCATION_LON = "locationLon";
public static final String COLUMN_NAME_TAGS = "tags";
public static final String COLUMN_NAME_CATEGORY = "category";
public static final String CREATE_TABLE =
"CREATE TABLE " + SpotEntry.TABLE_NAME + " (" +
SpotEntry._ID + " INTEGER PRIMARY KEY," +
SpotEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + UNIQUE + COMMA_SEP +
SpotEntry.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_DESCRIPTION + TEXT_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_PUBLIC_IMAGE_URL + TEXT_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_LOCATION_LAT + REAL_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_LOCATION_LON + REAL_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_TAGS + TEXT_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_CATEGORY + INTEGER_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_RELATION_SYSTEM + INTEGER_TYPE + COMMA_SEP +
SpotEntry.COLUMN_NAME_RELATION_CONTENT + INTEGER_TYPE + " )";
public static final String[] PROJECTION = {
_ID,
COLUMN_NAME_JSON_ID,
COLUMN_NAME_NAME,
COLUMN_NAME_DESCRIPTION,
COLUMN_NAME_PUBLIC_IMAGE_URL,
COLUMN_NAME_LOCATION_LAT,
COLUMN_NAME_LOCATION_LON,
COLUMN_NAME_TAGS,
COLUMN_NAME_CATEGORY,
COLUMN_NAME_RELATION_SYSTEM,
COLUMN_NAME_RELATION_CONTENT
};
}
/**
* Marker
*/
public static class MarkerEntry implements BaseColumns {
public static final String TABLE_NAME = "Marker";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_SPOT_RELATION = "spotRelation";
public static final String COLUMN_NAME_QR = "qr";
public static final String COLUMN_NAME_NFC = "nfc";
public static final String COLUMN_NAME_BEACON_UUID = "beaconUUID";
public static final String COLUMN_NAME_BEACON_MAJOR = "beaconMajor";
public static final String COLUMN_NAME_BEACON_MINOR = "beaconMinor";
public static final String COLUMN_NAME_EDDYSTONE_URL = "eddystoneUrl";
public static final String CREATE_TABLE =
"CREATE TABLE " + MarkerEntry.TABLE_NAME + " (" +
MarkerEntry._ID + " INTEGER PRIMARY KEY," +
MarkerEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + UNIQUE + COMMA_SEP +
MarkerEntry.COLUMN_NAME_SPOT_RELATION + INTEGER_TYPE + COMMA_SEP +
MarkerEntry.COLUMN_NAME_QR + TEXT_TYPE + COMMA_SEP +
MarkerEntry.COLUMN_NAME_NFC + TEXT_TYPE + COMMA_SEP +
MarkerEntry.COLUMN_NAME_BEACON_UUID + TEXT_TYPE + COMMA_SEP +
MarkerEntry.COLUMN_NAME_BEACON_MAJOR + TEXT_TYPE + COMMA_SEP +
MarkerEntry.COLUMN_NAME_BEACON_MINOR + TEXT_TYPE + COMMA_SEP +
MarkerEntry.COLUMN_NAME_EDDYSTONE_URL + TEXT_TYPE + " )";
public static final String[] PROJECTION = {
MarkerEntry._ID,
MarkerEntry.COLUMN_NAME_JSON_ID,
MarkerEntry.COLUMN_NAME_SPOT_RELATION,
MarkerEntry.COLUMN_NAME_QR,
MarkerEntry.COLUMN_NAME_NFC,
MarkerEntry.COLUMN_NAME_BEACON_UUID,
MarkerEntry.COLUMN_NAME_BEACON_MAJOR,
MarkerEntry.COLUMN_NAME_BEACON_MINOR,
MarkerEntry.COLUMN_NAME_EDDYSTONE_URL
};
}
/**
* Menu
*/
public static class MenuEntry implements BaseColumns {
public static final String TABLE_NAME = "Menu";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_SYSTEM_RELATION = "system";
public static final String CREATE_TABLE =
"CREATE TABLE " + MenuEntry.TABLE_NAME + " (" +
MenuEntry._ID + " INTEGER PRIMARY KEY," +
MenuEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + COMMA_SEP +
MenuEntry.COLUMN_NAME_SYSTEM_RELATION + INTEGER_TYPE + " )";
public static final String[] PROJECTION = {
MenuEntry._ID,
MenuEntry.COLUMN_NAME_JSON_ID,
MenuEntry.COLUMN_NAME_SYSTEM_RELATION
};
}
/**
* Content
*/
public static class ContentEntry implements BaseColumns {
public static final String TABLE_NAME = "Content";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_SYSTEM_RELATION = "systemRelation";
public static final String COLUMN_NAME_MENU_RELATION = "menuRelation";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_DESCRIPTION = "description";
public static final String COLUMN_NAME_LANGUAGE = "language";
public static final String COLUMN_NAME_CATEGORY = "category";
public static final String COLUMN_NAME_TAGS = "tags";
public static final String COLUMN_NAME_PUBLIC_IMAGE_URL = "imageUrl";
public static final String CREATE_TABLE =
"CREATE TABLE " + ContentEntry.TABLE_NAME + " (" +
ContentEntry._ID + " INTEGER PRIMARY KEY," +
ContentEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + UNIQUE + COMMA_SEP +
ContentEntry.COLUMN_NAME_SYSTEM_RELATION + INTEGER_TYPE + COMMA_SEP +
ContentEntry.COLUMN_NAME_MENU_RELATION + INTEGER_TYPE + COMMA_SEP +
ContentEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
ContentEntry.COLUMN_NAME_DESCRIPTION + TEXT_TYPE + COMMA_SEP +
ContentEntry.COLUMN_NAME_LANGUAGE + TEXT_TYPE + COMMA_SEP +
ContentEntry.COLUMN_NAME_CATEGORY + INTEGER_TYPE + COMMA_SEP +
ContentEntry.COLUMN_NAME_TAGS + TEXT_TYPE + COMMA_SEP +
ContentEntry.COLUMN_NAME_PUBLIC_IMAGE_URL + TEXT_TYPE + " )";
public static final String[] PROJECTION = {
ContentEntry._ID,
ContentEntry.COLUMN_NAME_JSON_ID,
ContentEntry.COLUMN_NAME_SYSTEM_RELATION,
ContentEntry.COLUMN_NAME_TITLE,
ContentEntry.COLUMN_NAME_DESCRIPTION,
ContentEntry.COLUMN_NAME_LANGUAGE,
ContentEntry.COLUMN_NAME_CATEGORY,
ContentEntry.COLUMN_NAME_TAGS,
ContentEntry.COLUMN_NAME_PUBLIC_IMAGE_URL
};
}
/**
* ContentBlock
*/
public static class ContentBlockEntry implements BaseColumns {
public static final String TABLE_NAME = "ContentBlock";
public static final String COLUMN_NAME_JSON_ID = "json_id";
public static final String COLUMN_NAME_CONTENT_RELATION = "contentRelation";
public static final String COLUMN_NAME_BLOCK_TYPE = "blockType";
public static final String COLUMN_NAME_PUBLIC_STATUS = "publicStatus";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_TEXT = "text";
public static final String COLUMN_NAME_ARTISTS = "artists";
public static final String COLUMN_NAME_FILE_ID = "fileId";
public static final String COLUMN_NAME_SOUNDCLOUD_URL = "soundcloudUrl";
public static final String COLUMN_NAME_LINK_TYPE = "linkType";
public static final String COLUMN_NAME_LINK_URL = "linkUrl";
public static final String COLUMN_NAME_CONTENT_ID = "contentId";
public static final String COLUMN_NAME_DOWNLOAD_TYPE = "downloadType";
public static final String COLUMN_NAME_SPOT_MAP_TAGS = "spotMapTags";
public static final String COLUMN_NAME_SCALE_X = "scaleX";
public static final String COLUMN_NAME_VIDEO_URL = "videoUrl";
public static final String COLUMN_NAME_SHOW_CONTENT_ON_SPOTMAP = "showContentOnSpotmap";
public static final String COLUMN_NAME_ALT_TEXT = "altText";
public static final String CREATE_TABLE =
"CREATE TABLE " + ContentBlockEntry.TABLE_NAME + " (" +
ContentBlockEntry._ID + " INTEGER PRIMARY KEY," +
ContentBlockEntry.COLUMN_NAME_JSON_ID + TEXT_TYPE + UNIQUE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_CONTENT_RELATION + INTEGER_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_BLOCK_TYPE + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_PUBLIC_STATUS + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_TEXT + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_ARTISTS + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_FILE_ID + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_SOUNDCLOUD_URL + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_LINK_TYPE + INTEGER_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_LINK_URL + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_CONTENT_ID + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_DOWNLOAD_TYPE + INTEGER_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_SPOT_MAP_TAGS + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_SCALE_X + REAL_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_VIDEO_URL + TEXT_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_SHOW_CONTENT_ON_SPOTMAP + INTEGER_TYPE + COMMA_SEP +
ContentBlockEntry.COLUMN_NAME_ALT_TEXT + TEXT_TYPE + " )";
public static final String[] PROJECTION = {
ContentBlockEntry._ID,
ContentBlockEntry.COLUMN_NAME_JSON_ID,
ContentBlockEntry.COLUMN_NAME_BLOCK_TYPE,
ContentBlockEntry.COLUMN_NAME_PUBLIC_STATUS,
ContentBlockEntry.COLUMN_NAME_TITLE,
ContentBlockEntry.COLUMN_NAME_TEXT,
ContentBlockEntry.COLUMN_NAME_ARTISTS,
ContentBlockEntry.COLUMN_NAME_FILE_ID,
ContentBlockEntry.COLUMN_NAME_SOUNDCLOUD_URL,
ContentBlockEntry.COLUMN_NAME_LINK_TYPE,
ContentBlockEntry.COLUMN_NAME_LINK_URL,
ContentBlockEntry.COLUMN_NAME_CONTENT_ID,
ContentBlockEntry.COLUMN_NAME_DOWNLOAD_TYPE,
ContentBlockEntry.COLUMN_NAME_SPOT_MAP_TAGS,
ContentBlockEntry.COLUMN_NAME_SCALE_X,
ContentBlockEntry.COLUMN_NAME_VIDEO_URL,
ContentBlockEntry.COLUMN_NAME_SHOW_CONTENT_ON_SPOTMAP,
ContentBlockEntry.COLUMN_NAME_ALT_TEXT };
}
} |
package org.opendaylight.yangtools.yang.stmt;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.isA;
import static org.junit.Assert.assertThrows;
import com.google.common.base.Throwables;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.SubstatementIndexingException;
import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
public class YangParserNegativeTest {
@SuppressWarnings("checkstyle:regexpSinglelineJava")
private final PrintStream stdout = System.out;
private final ByteArrayOutputStream output = new ByteArrayOutputStream();
private String testLog;
@Before
public void setUp() {
System.setOut(new PrintStream(output, true, StandardCharsets.UTF_8));
}
@After
public void cleanUp() {
System.setOut(stdout);
}
@Test
public void testInvalidImport() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/testfile1.yang"));
final Throwable rootCause = Throwables.getRootCause(ex);
assertThat(rootCause, isA(InferenceException.class));
assertThat(rootCause.getMessage(), startsWith("Imported module"));
assertThat(rootCause.getMessage(), containsString("was not found."));
}
@Test
public void testTypeNotFound() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/testfile2.yang"));
final Throwable rootCause = Throwables.getRootCause(ex);
assertThat(rootCause, isA(InferenceException.class));
assertThat(rootCause.getMessage(),
startsWith("Type [(urn:simple.types.data.demo?revision=2013-02-27)int-ext] was not found."));
}
@Test
public void testInvalidAugmentTarget() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(),
"/negative-scenario/testfile0.yang", "/negative-scenario/testfile3.yang"));
final Throwable rootCause = Throwables.getRootCause(ex);
assertThat(rootCause, isA(InferenceException.class));
assertThat(rootCause.getMessage(), startsWith(
"Augment target 'Absolute{qnames=[(urn:simple.container.demo)unknown]}' not found"));
}
@Test
public void testInvalidRefine() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/testfile4.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(SourceException.class));
assertThat(cause.getMessage(), containsString("Error in module 'test4' in the refine of uses "
+ "'Descendant{qnames=[(urn:simple.container.demo)node]}': can not perform refine of 'PRESENCE' for"
+ " the target 'LEAF_LIST'."));
}
@Test
public void testInvalidLength() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/testfile5.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(SourceException.class));
assertThat(cause.getMessage(), containsString("Invalid length constraint [4..10]"));
}
@Test
public void testInvalidRange() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/testfile6.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(SourceException.class));
assertThat(cause.getMessage(), startsWith("Invalid range constraint: [[5..20]]"));
}
@Test
public void testDuplicateContainer() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/duplicity/container.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(SourceException.class));
assertThat(cause.getMessage(), containsString("Error in module 'container': cannot add "
+ "'(urn:simple.container.demo)foo'. Node name collision: '(urn:simple.container.demo)foo' already "
+ "declared"));
}
@Test
public void testDuplicateContainerList() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/duplicity/container-list.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(SourceException.class));
assertThat(cause.getMessage(), containsString("Error in module 'container-list': cannot add "
+ "'(urn:simple.container.demo)foo'. Node name collision: '(urn:simple.container.demo)foo' already "
+ "declared"));
}
@Test
public void testDuplicateContainerLeaf() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/duplicity/container-leaf.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(SourceException.class));
assertThat(cause.getMessage(), containsString("Error in module 'container-leaf': cannot add "
+ "'(urn:simple.container.demo)foo'. Node name collision: '(urn:simple.container.demo)foo' already "
+ "declared"));
}
@Test
public void testDuplicateTypedef() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/duplicity/typedef.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(SourceException.class));
assertThat(cause.getMessage(), startsWith(
"Duplicate name for typedef (urn:simple.container.demo)int-ext [at"));
}
@Test
public void testDuplicityInAugmentTarget1() throws IOException, ReactorException, YangSyntaxErrorException {
TestUtils.loadModuleResources(getClass(),
"/negative-scenario/duplicity/augment0.yang", "/negative-scenario/duplicity/augment1.yang");
testLog = output.toString();
assertThat(testLog, containsString(
"An augment cannot add node named 'id' because this name is already used in target"));
}
@Test
public void testDuplicityInAugmentTarget2() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(),
"/negative-scenario/duplicity/augment0.yang", "/negative-scenario/duplicity/augment2.yang"));
final Throwable rootCause = Throwables.getRootCause(ex);
assertThat(rootCause, isA(SubstatementIndexingException.class));
assertThat(rootCause.getMessage(), containsString("Cannot add schema tree child with name "
+ "(urn:simple.augment2.demo?revision=2014-06-02)delta, a conflicting child already exists"));
}
@Test
public void testMandatoryInAugment() throws IOException, ReactorException, YangSyntaxErrorException {
TestUtils.loadModuleResources(getClass(),
"/negative-scenario/testfile8.yang",
"/negative-scenario/testfile7.yang");
testLog = output.toString();
assertThat(testLog, containsString(
"An augment cannot add node 'linkleaf' because it is mandatory and in module different than target"));
}
@Test
public void testInvalidListKeyDefinition() {
final SomeModifiersUnresolvedException ex = assertThrows(SomeModifiersUnresolvedException.class,
() -> TestUtils.loadModuleResources(getClass(), "/negative-scenario/invalid-list-key-def.yang"));
final Throwable cause = ex.getCause();
assertThat(cause, isA(InferenceException.class));
assertThat(cause.getMessage(), startsWith(
"Key 'rib-id' misses node 'rib-id' in list '(invalid:list:key:def)application-map'"));
}
} |
package com.esri.runtime.android.materialbasemaps.ui;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Outline;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import com.esri.android.map.LocationDisplayManager;
import com.esri.android.map.MapView;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.LinearUnit;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.geometry.Unit;
import com.esri.core.portal.Portal;
import com.esri.core.portal.WebMap;
import com.esri.runtime.android.materialbasemaps.R;
import com.esri.runtime.android.materialbasemaps.util.TaskExecutor;
import java.util.concurrent.Callable;
/**
* Activity for Map and floating action bar button.
*/
public class MapActivity extends Activity{
final private String portalUrl = "http:
MapView mMapView;
// GPS location tracking
private boolean mIsLocationTracking;
private Point mLocation = null;
// The circle area specified by search_radius and input lat/lon serves
// searching purpose.
// It is also used to construct the extent which map zooms to after the first
// GPS fix is retrieved.
private final static double SEARCH_RADIUS = 10;
private static final String KEY_IS_LOCATION_TRACKING = "IsLocationTracking";
RelativeLayout relativeMapLayout;
ImageButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
// layout to add MapView to
relativeMapLayout = (RelativeLayout) findViewById(R.id.relative);
// receive portal id and title of the basemap to add to the map
Intent intent = getIntent();
String itemId = intent.getExtras().getString("portalId");
String title = intent.getExtras().getString("title");
// adds back button to action bar
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(title);
// load the basemap on a background thread
loadWebMapIntoMapView(itemId, portalUrl);
fab = (ImageButton) findViewById(R.id.fab);
// floating action bar settings
ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
outline.setOval(0, 0, size, size);
}
};
fab.setOutlineProvider(viewOutlineProvider);
}
public void onClick(View view){
// Toggle location tracking on or off
if (mIsLocationTracking) {
mMapView.getLocationDisplayManager().stop();
mIsLocationTracking = false;
fab.setImageResource(R.mipmap.ic_action_location_off);
} else {
startLocationTracking();
fab.setImageResource(R.mipmap.ic_action_location_found);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// inflate action bar menu
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(intent, 0);
return super.onOptionsItemSelected(item);
}
/**
* Creates a new WebMap on a background thread based on the portal item id of the basemap
* to be used. Goes back to UI thread to use the WebMap as a new MapView to display in
* the ViewGroup layout. Centers and zooms to default Palm Springs location.
*
* @param portalItemId represents the basemap to be used as a new webmap
* @param portalUrl represents the portal url to look up the portalItemId
*/
private void loadWebMapIntoMapView(final String portalItemId, final String portalUrl){
TaskExecutor.getInstance().getThreadPool().submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
Portal portal = new Portal(portalUrl, null);
// load a webmap instance from portal item
final WebMap webmap = WebMap.newInstance(portalItemId, portal);
if(webmap != null){
runOnUiThread(new Runnable() {
@Override
public void run() {
// udpate the MapView with the basemap
mMapView = new MapView(getApplicationContext(), webmap, null, null);
// Layout Parameters for MapView
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
mMapView.setLayoutParams(lp);
// add MapView to layout
relativeMapLayout.addView(mMapView);
// enable wrap around date line
mMapView.enableWrapAround(true);
// attribute esri
mMapView.setEsriLogoVisible(true);
mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
@Override
public void onStatusChanged(Object source, STATUS status) {
if(mMapView == source && status == STATUS.INITIALIZED){
// zoom in into Palm Springs
mMapView.centerAndZoom(33.829547, -116.515882, 14);
}
}
});
}
});
}
return null;
}
});
}
/**
* Starts tracking GPS location.
*/
void startLocationTracking() {
LocationDisplayManager locDispMgr = mMapView.getLocationDisplayManager();
locDispMgr.setAutoPanMode(LocationDisplayManager.AutoPanMode.OFF);
locDispMgr.setAllowNetworkLocation(true);
locDispMgr.setLocationListener(new LocationListener() {
boolean locationChanged = false;
// Zooms to the current location when first GPS fix arrives
@Override
public void onLocationChanged(Location loc) {
Point wgspoint = new Point(loc.getLongitude(), loc.getLatitude());
mLocation = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326),
mMapView.getSpatialReference());
if (!locationChanged) {
locationChanged = true;
Unit mapUnit = mMapView.getSpatialReference().getUnit();
double zoomWidth = Unit.convertUnits(SEARCH_RADIUS, Unit.create(LinearUnit.Code.MILE_US), mapUnit);
Envelope zoomExtent = new Envelope(mLocation, zoomWidth, zoomWidth);
mMapView.setExtent(zoomExtent);
}
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
});
locDispMgr.start();
mIsLocationTracking = true;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_IS_LOCATION_TRACKING, mIsLocationTracking);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
} |
package org.mamkschools.mhs.fbla_mobileapp_2016.lib;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public final class Constants {
//API URL
public static final String API_BASE_URL = "https://aakatz3.aakportfolio.com:9084/fbla2016/api/";
//Output debug info
public static boolean DEBUG_MODE = true;
//Show static demos in case of server problems
public static boolean DEMO_MODE = false;
//Authcode needs to be saved and loaded
public static String AUTHCODE = null;
//Authcode expiration time, to kick user back to login. We need a "renew" function to extend time
public static long AUTHCODE_EXP;
//Variable to see if prefs restored yet
public static boolean PREFS_RESTORED = false;
private Constants(){
//Do nothing constructor, exists to defeat instantiation.
}
public static void restorePrefs(Context ctx){
PREFS_RESTORED = true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
DEBUG_MODE = prefs.getBoolean("DEBUG_MODE", true);
DEMO_MODE = prefs.getBoolean("DEMO_MODE", false);
AUTHCODE = prefs.getString("AUTHCODE", null);
AUTHCODE_EXP = prefs.getLong("AUTHCODE_EXP", -1);
}
@SuppressLint("CommitPrefEdits")
public static void savePrefs(Context ctx){
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("DEBUG_MODE", DEBUG_MODE);
editor.putBoolean("DEMO_MODE", DEMO_MODE);
editor.putString("AUTHCODE", AUTHCODE);
editor.putLong("AUTHCODE_EXP", AUTHCODE_EXP);
// Commit the edits! Do not change to "apply" or will not be done because app will close!
editor.commit();
}
} |
package de.sb.messenger.persistence;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.validation.constraints.Size;
@Entity
@Table(name = "Message")
@DiscriminatorValue(value = "Message")
@PrimaryKeyJoinColumn(name="identity")
public class Message extends BaseEntity {
@Column(name = "author")
private Person author;
@ManyToOne
@Column(name = "subject")
private BaseEntity subject;
@Column(name = "body")
@Size(min = 1, max = 4093)
private String body;
public Message(Person author, BaseEntity subject, String body) {
this.author = author;
this.subject = subject;
this.body = body;
}
protected Message() {
this.author = null;
this.subject = null;
this.body = null;
}
public Person getAuthor() {
return author;
}
public BaseEntity getSubject() {
return subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public BaseEntity getSubjectReference() {
return this.subject;
}
} |
package de.st_ddt.crazyspawner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;
import de.st_ddt.crazyplugin.CrazyPlugin;
import de.st_ddt.crazyspawner.commands.CommandCreatureSpawner;
import de.st_ddt.crazyspawner.commands.CommandKill;
import de.st_ddt.crazyspawner.commands.CommandSpawn;
import de.st_ddt.crazyspawner.commands.CommandTheEndAutoRespawn;
import de.st_ddt.crazyspawner.data.CustomCreature;
import de.st_ddt.crazyspawner.data.CustomCreature_1_4_5;
import de.st_ddt.crazyspawner.data.CustomCreature_1_4_6;
import de.st_ddt.crazyspawner.data.CustomCreature_1_5;
import de.st_ddt.crazyspawner.listener.PlayerListener;
import de.st_ddt.crazyspawner.tasks.SpawnTask;
import de.st_ddt.crazyutil.ChatHelper;
import de.st_ddt.crazyutil.ExtendedCreatureType;
import de.st_ddt.crazyutil.VersionComparator;
import de.st_ddt.crazyutil.paramitrisable.CreatureParamitrisable;
import de.st_ddt.crazyutil.paramitrisable.EnumParamitrisable;
import de.st_ddt.crazyutil.paramitrisable.ExtendedCreatureParamitrisable;
import de.st_ddt.crazyutil.source.Localized;
import de.st_ddt.crazyutil.source.LocalizedVariable;
@LocalizedVariable(variables = { "CRAZYPLUGIN" }, values = { "CRAZYSPAWNER" })
public class CrazySpawner extends CrazyPlugin
{
private static CrazySpawner plugin;
private final Set<CustomCreature> creatures = new LinkedHashSet<CustomCreature>();
private final Set<SpawnTask> tasks = new TreeSet<SpawnTask>();
private final Map<Player, EntityType> creatureSelection = new HashMap<Player, EntityType>();
private boolean v146OrLater;
private boolean v15OrLater;
public static CrazySpawner getPlugin()
{
return plugin;
}
public void registerHooks()
{
final PluginManager pm = Bukkit.getPluginManager();
pm.registerEvents(new PlayerListener(this, creatureSelection), this);
}
private void registerCommands()
{
getCommand("crazyspawn").setExecutor(new CommandSpawn(this));
getCommand("crazykill").setExecutor(new CommandKill(this));
getCommand("crazycreaturespawner").setExecutor(new CommandCreatureSpawner(this, creatureSelection));
getCommand("crazytheendautorespawn").setExecutor(new CommandTheEndAutoRespawn(this));
}
@Override
public void onLoad()
{
plugin = this;
super.onLoad();
}
@Override
@Localized("CRAZYSPAWNER.CREATURES.AVAILABLE $Count$")
public void onEnable()
{
final String mcVersion = ChatHelper.getMinecraftVersion();
v15OrLater = (VersionComparator.compareVersions(mcVersion, "1.5") >= 0);
v146OrLater = (VersionComparator.compareVersions(mcVersion, "1.4.6") >= 0);
registerEnderCrystalType();
super.onEnable();
if (isUpdated)
if (VersionComparator.compareVersions(previousVersion, "3.7") == -1)
{
final ConfigurationSection config = getConfig();
// ExampleCreature
CustomCreature_1_4_5.dummySave(config, "example.Creature.");
// ExampleType
config.set("example.EntityType", CreatureParamitrisable.CREATURE_NAMES);
// ExampleColor
config.set("example.DyeColor", EnumParamitrisable.getEnumNames(DyeColor.values()).toArray());
// ExampleItem
config.set("example.Item.type", "Material");
config.set("example.Item.damage", "short (0 (full) - 528 (broken, upper limit may differ (mostly below)))");
config.set("example.Item.amount", "int (1-64)");
config.set("example.Item.meta.==", "ItemMeta");
config.set("example.Item.meta.meta-type", "UNSPECIFIC");
config.set("example.Item.meta.display-name", "String");
config.set("example.Item.meta.lore", new String[] { "Line1", "Line2", "..." });
config.set("example.Item.meta.enchants.ENCHANTMENT1", "int (1-255)");
config.set("example.Item.meta.enchants.ENCHANTMENT2", "int (1-255)");
config.set("example.Item.meta.enchants.ENCHANTMENTx", "int (1-255)");
// DefaultCreatures
// - Spider_Skeleton
final CustomCreature spiderSkeleton = new CustomCreature_1_4_5("Spider_Skeleton", EntityType.SPIDER, "SKELETON");
creatures.add(spiderSkeleton);
ExtendedCreatureParamitrisable.registerExtendedEntityType(spiderSkeleton);
// - Diamont_Zombie
final CustomCreature diamondZombie = new CustomCreature_1_4_5("Diamont_Zombie", EntityType.ZOMBIE, new ItemStack(Material.DIAMOND_BOOTS), 0.01F, new ItemStack(Material.DIAMOND_LEGGINGS), 0.01F, new ItemStack(Material.DIAMOND_CHESTPLATE), 0.01F, new ItemStack(Material.DIAMOND_HELMET), 0.01F, new ItemStack(Material.DIAMOND_SWORD), 0.01F);
creatures.add(diamondZombie);
ExtendedCreatureParamitrisable.registerExtendedEntityType(diamondZombie);
// - Healthy_Diamont_Zombie
final ItemStack chestplate = new ItemStack(Material.DIAMOND_CHESTPLATE);
chestplate.setAmount(1);
chestplate.setDurability((short) 3);
chestplate.addUnsafeEnchantment(Enchantment.PROTECTION_EXPLOSIONS, 5);
chestplate.addUnsafeEnchantment(Enchantment.PROTECTION_FIRE, 5);
chestplate.addUnsafeEnchantment(Enchantment.DURABILITY, 10);
if (v146OrLater)
chestplate.addUnsafeEnchantment(Enchantment.THORNS, 3);
final ItemMeta meta = chestplate.getItemMeta();
meta.setDisplayName("Holy Chestplate of the Goddes");
final List<String> lore = new ArrayList<String>();
lore.add("Blessed by the goddess kiss");
lore.add("Manufactured by the best dwarfs known");
meta.setLore(lore);
chestplate.setItemMeta(meta);
final CustomCreature healthyDiamondZombie;
if (v15OrLater)
healthyDiamondZombie = new CustomCreature_1_5("Healthy_Diamont_Zombie", "Diamond_Zombie", true, EntityType.ZOMBIE, 100, new ItemStack(Material.DIAMOND_BOOTS), 1F, new ItemStack(Material.DIAMOND_LEGGINGS), 1F, chestplate, 1F, new ItemStack(Material.DIAMOND_HELMET), 1F, new ItemStack(Material.DIAMOND_SWORD), 1F);
else if (v146OrLater)
healthyDiamondZombie = new CustomCreature_1_4_6("Healthy_Diamont_Zombie", EntityType.ZOMBIE, 100, new ItemStack(Material.DIAMOND_BOOTS), 1F, new ItemStack(Material.DIAMOND_LEGGINGS), 1F, chestplate, 1F, new ItemStack(Material.DIAMOND_HELMET), 1F, new ItemStack(Material.DIAMOND_SWORD), 1F);
else
healthyDiamondZombie = new CustomCreature_1_4_5("Healthy_Diamont_Zombie", EntityType.ZOMBIE, new ItemStack(Material.DIAMOND_BOOTS), 1F, new ItemStack(Material.DIAMOND_LEGGINGS), 1F, chestplate, 1F, new ItemStack(Material.DIAMOND_HELMET), 1F, new ItemStack(Material.DIAMOND_SWORD), 1F);
creatures.add(healthyDiamondZombie);
ExtendedCreatureParamitrisable.registerExtendedEntityType(healthyDiamondZombie);
// - Giant
final CustomCreature giant = new CustomCreature_1_4_5("Giant", EntityType.GIANT);
creatures.add(giant);
ExtendedCreatureParamitrisable.registerExtendedEntityType(giant);
// - Healthy_Giant
if (v146OrLater)
{
final CustomCreature healthyGiant = new CustomCreature_1_4_6("Healthy_Giant", EntityType.GIANT, 200);
creatures.add(healthyGiant);
ExtendedCreatureParamitrisable.registerExtendedEntityType(healthyGiant);
}
// - Spider_Diamont_Zombie
final CustomCreature spiderDiamondZombie = new CustomCreature_1_4_5("Spider_Diamont_Zombie", EntityType.SPIDER, diamondZombie);
creatures.add(spiderDiamondZombie);
ExtendedCreatureParamitrisable.registerExtendedEntityType(spiderDiamondZombie);
saveConfiguration();
}
registerHooks();
registerCommands();
sendLocaleMessage("CREATURES.AVAILABLE", Bukkit.getConsoleSender(), ExtendedCreatureParamitrisable.CREATURE_TYPES.size());
}
private void registerEnderCrystalType()
{
ExtendedCreatureParamitrisable.registerExtendedEntityType(new ExtendedCreatureType()
{
@Override
public String getName()
{
return "ENDER_CRYSTAL";
}
@Override
public EntityType getType()
{
return EntityType.ENDER_CRYSTAL;
}
@Override
public Entity spawn(final Location location)
{
if (location.getChunk().isLoaded())
{
location.setX(Math.floor(location.getX()) + 0.5);
location.setY(Math.floor(location.getY()));
location.setZ(Math.floor(location.getZ()) + 0.5);
location.setYaw(0);
location.setPitch(0);
location.clone().add(0, 1, 0).getBlock().setType(Material.FIRE);
location.getBlock().setType(Material.BEDROCK);
return location.getWorld().spawnEntity(location, EntityType.ENDER_CRYSTAL);
}
else
return null;
}
@Override
public Collection<? extends Entity> getEntities(final World world)
{
return world.getEntitiesByClass(EntityType.ENDER_CRYSTAL.getEntityClass());
}
@Override
public String toString()
{
return getName();
}
}, "DRAGON_CRYSTAL", "HEAL_CRYSTAL", "ENDERCRYSTAL");
}
@Override
@Localized("CRAZYSPAWNER.CREATURES.LOADED $Count$")
public void loadConfiguration()
{
final ConfigurationSection config = getConfig();
creatures.clear();
final ConfigurationSection creatureConfig = config.getConfigurationSection("creatures");
if (creatureConfig != null)
for (final String key : creatureConfig.getKeys(false))
try
{
final CustomCreature creature;
if (v15OrLater)
creature = new CustomCreature_1_5(creatureConfig.getConfigurationSection(key));
else if (v146OrLater)
creature = new CustomCreature_1_4_6(creatureConfig.getConfigurationSection(key));
else
creature = new CustomCreature_1_4_5(creatureConfig.getConfigurationSection(key));
creatures.add(creature);
ExtendedCreatureParamitrisable.registerExtendedEntityType(creature);
}
catch (final IllegalArgumentException e)
{
System.err.println("Could not load creature " + key);
System.err.println(e.getMessage());
}
sendLocaleMessage("CREATURES.LOADED", Bukkit.getConsoleSender(), creatures.size());
for (final SpawnTask task : tasks)
task.cancel();
tasks.clear();
final ConfigurationSection taskConfig = config.getConfigurationSection("tasks");
if (taskConfig != null)
for (final String key : taskConfig.getKeys(false))
try
{
tasks.add(new SpawnTask(plugin, taskConfig.getConfigurationSection(key)));
}
catch (final IllegalArgumentException e)
{
e.printStackTrace();
}
for (final SpawnTask task : tasks)
task.start(100);
}
@Override
public void saveConfiguration()
{
final ConfigurationSection config = getConfig();
config.set("creatures", null);
for (final CustomCreature creature : creatures)
creature.save(config, "creatures." + creature.getName() + ".");
config.set("tasks", null);
int i = 0;
for (final SpawnTask task : tasks)
task.save(config, "tasks.t" + i++ + ".");
super.saveConfiguration();
}
public void addSpawnTask(final SpawnTask task)
{
tasks.add(task);
saveConfiguration();
}
public void removeSpawnTask(final SpawnTask task)
{
tasks.remove(task);
saveConfiguration();
}
} |
package org.anyline.entity;
import com.fasterxml.jackson.databind.JsonNode;
import org.anyline.util.*;
import org.anyline.util.regular.Regular;
import org.anyline.util.regular.RegularUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import org.anyline.entity.KeyAdapter.KEY_CASE;
public class DataSet implements Collection<DataRow>, Serializable {
private static final long serialVersionUID = 6443551515441660101L;
protected static final Logger log = LoggerFactory.getLogger(DataSet.class);
private boolean result = true;
private Exception exception = null;
private String message = null;
private PageNavi navi = null;
private List<String> head = null;
private List<DataRow> rows = null;
private List<String> primaryKeys = null;
private String datalink = null;
private String dataSource = null; // (||XMLSQL)
private String schema = null;
private String table = null;
private long createTime = 0;
private long expires = -1; //() expires
private boolean isFromCache = false;
private boolean isAsc = false;
private boolean isDesc = false;
private Map<String, Object> queryParams = new HashMap<String, Object>();
/**
*
*
* @param key key
* @return DataSet
* crateIndex("ID");
* crateIndex("ID:ASC");
*/
public DataSet creatIndex(String key) {
return this;
}
public DataSet() {
rows = new ArrayList<DataRow>();
createTime = System.currentTimeMillis();
}
public DataSet(List<Map<String, Object>> list) {
rows = new ArrayList<DataRow>();
if (null == list)
return;
for (Map<String, Object> map : list) {
DataRow row = new DataRow(map);
rows.add(row);
}
}
public static DataSet build(Collection<?> list, String ... fields) {
return parse(list, fields);
}
/**
* listDataSet
* @param list list
* @param fields list
* fields (/key) "ID","CODE","NAME"
* DataRowkey row.put("0","100").put("1","A01").put("2","");
* list,nullDataRow
*
* list
* fileds DataRowkey "USER_ID:id","USER_NM:name"
*
* @return DataSet
*/
public static DataSet parse(Collection<?> list, String ... fields) {
DataSet set = new DataSet();
if (null != list) {
for (Object obj : list) {
DataRow row = null;
if(obj instanceof Collection){
row = DataRow.parseList((Collection)obj, fields);
}else {
row = DataRow.parse(obj, fields);
}
set.add(row);
}
}
return set;
}
public static DataSet parseJson(KEY_CASE keyCase, String json) {
if (null != json) {
try {
return parseJson(keyCase, BeanUtil.JSON_MAPPER.readTree(json));
} catch (Exception e) {
}
}
return null;
}
public static DataSet parseJson(String json) {
return parseJson(KEY_CASE.CONFIG, json);
}
public static DataSet parseJson(KEY_CASE keyCase, JsonNode json) {
DataSet set = new DataSet();
if (null != json) {
if (json.isArray()) {
Iterator<JsonNode> items = json.iterator();
while (items.hasNext()) {
JsonNode item = items.next();
set.add(DataRow.parseJson(keyCase, item));
}
}
}
return set;
}
public static DataSet parseJson(JsonNode json) {
return parseJson(KEY_CASE.CONFIG, json);
}
public DataSet Camel(){
for(DataRow row:rows){
row.Camel();
}
return this;
}
public DataSet camel(){
for(DataRow row:rows){
row.camel();
}
return this;
}
public DataSet setIsNew(boolean bol) {
for (DataRow row : rows) {
row.setIsNew(bol);
}
return this;
}
/**
* key
*
* @param keys keys
* @return DataSet
*/
public DataSet remove(String... keys) {
for (DataRow row : rows) {
for (String key : keys) {
row.remove(key);
}
}
return this;
}
public DataSet trim(){
for(DataRow row:rows){
row.trim();
}
return this;
}
/**
*
*
* @param applyItem DataRow true
* @param pks pks
* @return DataSet
*/
public DataSet addPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
addPrimaryKey(applyItem, list);
}
return this;
}
public DataSet addPrimaryKey(String... pks) {
return addPrimaryKey(true, pks);
}
public DataSet addPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
if (null == pks) {
return this;
}
for (String pk : pks) {
if (BasicUtil.isEmpty(pk)) {
continue;
}
pk = key(pk);
if (!primaryKeys.contains(pk)) {
primaryKeys.add(pk);
}
}
if (applyItem) {
for (DataRow row : rows) {
row.setPrimaryKey(false, primaryKeys);
}
}
return this;
}
public DataSet addPrimaryKey(Collection<String> pks) {
return addPrimaryKey(true, pks);
}
/**
*
*
* @param applyItem applyItem
* @param pks pks
* @return DataSet
*/
public DataSet setPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
setPrimaryKey(applyItem, list);
}
return this;
}
public DataSet setPrimaryKey(String... pks) {
return setPrimaryKey(true, pks);
}
public DataSet setPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == pks) {
return this;
}
this.primaryKeys = new ArrayList<>();
addPrimaryKey(applyItem, pks);
return this;
}
public DataSet setPrimaryKey(Collection<String> pks) {
return setPrimaryKey(true, pks);
}
public DataSet set(int index, DataRow item) {
rows.set(index, item);
return this;
}
/**
*
*
* @return boolean
*/
public boolean hasPrimaryKeys() {
if (null != primaryKeys && primaryKeys.size() > 0) {
return true;
} else {
return false;
}
}
/**
*
*
* @return List
*/
public List<String> getPrimaryKeys() {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
return primaryKeys;
}
/**
*
*
* @param col col
* @return DataSet
*/
public DataSet addHead(String col) {
if (null == head) {
head = new ArrayList<>();
}
if ("ROW_NUMBER".equals(col)) {
return this;
}
if (head.contains(col)) {
return this;
}
head.add(col);
return this;
}
/**
*
*
* @return List
*/
public List<String> getHead() {
return head;
}
public int indexOf(Object obj) {
return rows.indexOf(obj);
}
/**
* beginend,DataSet
*
* @param begin
* @param end
* @return DataSet
*/
public DataSet truncates(int begin, int end) {
if (!rows.isEmpty()) {
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
rows = rows.subList(begin, end);
}
return this;
}
/**
* begin
*
* @param begin
* @return DataSet
*/
public DataSet truncates(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return truncates(begin, end);
} else {
return truncates(begin, rows.size() - 1);
}
}
/**
* beginDataRow
*
* @param begin
* @return DataRow
*/
public DataRow truncate(int begin) {
return truncate(begin, rows.size() - 1);
}
/**
* beginendDataRow
*
* @param begin
* @param end
* @return DataRow
*/
public DataRow truncate(int begin, int end) {
truncates(begin, end);
if (rows.size() > 0) {
return rows.get(0);
} else {
return null;
}
}
/**
* begin
*
* @param begin
* n,,
* @return DataSet
*/
public DataSet cuts(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return cuts(begin, end);
} else {
return cuts(begin, rows.size() - 1);
}
}
/**
* beginend,DataSetset
*
* @param begin
* @param end
* @return DataSet
*/
public DataSet cuts(int begin, int end) {
DataSet result = new DataSet();
if (rows.isEmpty()) {
return result;
}
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
for (int i = begin; i <= end; i++) {
result.add(rows.get(i));
}
return result;
}
/**
* begin,DataRow
*
* @param begin
* @return DataSet
*/
public DataRow cut(int begin) {
return cut(begin, rows.size() - 1);
}
/**
* beginend,DataRow,DataSetset
*
* @param begin
* @param end
* @return DataSet
*/
public DataRow cut(int begin, int end) {
DataSet result = cuts(begin, end);
if (result.size() > 0) {
return result.getRow(0);
}
return null;
}
/**
*
*
* @return int
*/
public int size() {
int result = 0;
if (null != rows)
result = rows.size();
return result;
}
public int getSize() {
return size();
}
/**
*
*
* @return boolean
*/
public boolean isException() {
return null != exception;
}
public boolean isFromCache() {
return isFromCache;
}
public DataSet setIsFromCache(boolean bol) {
this.isFromCache = bol;
return this;
}
/**
*
*
* @return boolean
*/
public boolean isEmpty() {
boolean result = true;
if (null == rows) {
result = true;
} else if (rows instanceof Collection) {
result = ((Collection<?>) rows).isEmpty();
}
return result;
}
/**
*
*
* @param index index
* @return DataRow
*/
public DataRow getRow(int index) {
DataRow row = null;
if (null != rows && index < rows.size()) {
row = rows.get(index);
}
if (null != row) {
row.setContainer(this);
}
return row;
}
public boolean exists(String ... params){
DataRow row = getRow(0, params);
return row != null;
}
public DataRow getRow(String... params) {
return getRow(0, params);
}
public DataRow getRow(DataRow params) {
return getRow(0, params);
}
public DataRow getRow(List<String> params) {
String[] kvs = BeanUtil.list2array(params);
return getRow(0, kvs);
}
public DataRow getRow(int begin, String... params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
public DataRow getRow(int begin, DataRow params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
/**
* keys
*
* @param keys keys
* @return DataSet
*/
public DataSet distinct(String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
DataRow row = rows.get(i);
//result
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public DataSet distinct(List<String> keys) {
DataSet result = new DataSet();
if (null != rows) {
for (DataRow row:rows) {
//result
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public Object clone() {
DataSet set = new DataSet();
List<DataRow> rows = new ArrayList<DataRow>();
for (DataRow row : this.rows) {
rows.add((DataRow) row.clone());
}
set.setRows(rows);
set.cloneProperty(this);
return set;
}
private DataSet cloneProperty(DataSet from) {
return cloneProperty(from, this);
}
public static DataSet cloneProperty(DataSet from, DataSet to) {
if (null != from && null != to) {
to.exception = from.exception;
to.message = from.message;
to.navi = from.navi;
to.head = from.head;
to.primaryKeys = from.primaryKeys;
to.dataSource = from.dataSource;
to.datalink = from.datalink;
to.schema = from.schema;
to.table = from.table;
}
return to;
}
/**
* keynumber
* @param keys keys
* @return DataRow
*/
public DataSet convertNumber(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertNumber(keys);
}
}
return this;
}
public DataSet convertString(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertString(keys);
}
}
return this;
}
public DataSet skip(boolean skip){
for(DataRow row:rows){
row.skip = skip;
}
return this;
}
/**
*
* String 11.0, convertNumber
* @param params key1,value1,key2:value2,key3,value3
* "NM:zh%","AGE:>20","NM","%zh%"
* @param begin begin
* @param qty 0
* @return DataSet
*/
public DataSet getRows(int begin, int qty, String... params) {
DataSet set = new DataSet();
Map<String, String> kvs = new HashMap<String, String>();
int len = params.length;
int i = 0;
String srcFlagTag = "srcFlag"; //{} kvskey+tag ,TIME:{10:10}
while (i < len) {
String p1 = params[i];
if (BasicUtil.isEmpty(p1)) {
i++;
continue;
} else if (p1.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(p1);
kvs.put(ks[0], ks[1]);
i++;
continue;
} else {
if (i + 1 < len) {
String p2 = params[i + 1];
if (BasicUtil.isEmpty(p2) || !p2.contains(":")) {
kvs.put(p1, p2);
i += 2;
continue;
} else if (p2.startsWith("${") && p2.endsWith("}")) {
p2 = p2.substring(1, p2.length() - 1);
kvs.put(p1, p2);
kvs.put(p1 + srcFlagTag, "true");
i += 2;
continue;
} else {
String ks[] = BeanUtil.parseKeyValue(p2);
kvs.put(ks[0], ks[1]);
i += 2;
continue;
}
}
}
i++;
}
return getRows(begin, qty, kvs);
}
public DataSet getRows(int begin, int qty, DataRow kvs) {
Map<String,String> map = new HashMap<String,String>();
for(String k:kvs.keySet()){
map.put(k, kvs.getString(k));
}
return getRows(begin, qty, map);
}
public DataSet getRows(int begin, int qty, Map<String, String> kvs) {
DataSet set = new DataSet();
String srcFlagTag = "srcFlag"; //{} kvskey+tag
BigDecimal d1;
BigDecimal d2;
for (DataRow row:rows) {
if(row.skip){
continue;
}
boolean chk = true;
for (String k : kvs.keySet()) {
boolean srcFlag = false;
if (k.endsWith(srcFlagTag)) {
continue;
} else {
String srcFlagValue = kvs.get(k + srcFlagTag);
if (BasicUtil.isNotEmpty(srcFlagValue)) {
srcFlag = true;
}
}
String v = kvs.get(k);
Object value = row.get(k);
if(!row.containsKey(k) && null == value){
//key
chk = false;
break;
}
if (null == v) {
if (null != value) {
chk = false;
break;
}else{
continue;
}
} else {
if (null == value) {
chk = false;
break;
}
//SQL.COMPARE_TYPE
int compare = 10;
if (v.startsWith("=")) {
compare = 10;
v = v.substring(1);
} else if (v.startsWith(">")) {
compare = 20;
v = v.substring(1);
} else if (v.startsWith(">=")) {
compare = 21;
v = v.substring(2);
} else if (v.startsWith("<")) {
compare = 30;
v = v.substring(1);
} else if (v.startsWith("<=")) {
compare = 31;
v = v.substring(2);
} else if (v.startsWith("%") && v.endsWith("%")) {
compare = 50;
v = v.substring(1, v.length() - 1);
} else if (v.endsWith("%")) {
compare = 51;
v = v.substring(0, v.length() - 1);
} else if (v.startsWith("%")) {
compare = 52;
v = v.substring(1);
}
if(compare <= 31 && value instanceof Number) {
try {
d1 = new BigDecimal(value.toString());
d2 = new BigDecimal(v);
int cr = d1.compareTo(d2);
if (compare == 10) {
if (cr != 0) {
chk = false;
break;
}
} else if (compare == 20) {
if (cr <= 0) {
chk = false;
break;
}
} else if (compare == 21) {
if (cr < 0) {
chk = false;
break;
}
} else if (compare == 30) {
if (cr >= 0) {
chk = false;
break;
}
} else if (compare == 31) {
if (cr > 0) {
chk = false;
break;
}
}
}catch (NumberFormatException e){
chk = false;
break;
}
}
String str = value + "";
str = str.toLowerCase();
v = v.toLowerCase();
if (srcFlag) {
v = "${" + v + "}";
}
if (compare == 10) {
if (!v.equals(str)) {
chk = false;
break;
}
} else if (compare == 50) {
if (!str.contains(v)) {
chk = false;
break;
}
} else if (compare == 51) {
if (!str.startsWith(v)) {
chk = false;
break;
}
} else if (compare == 52) {
if (!str.endsWith(v)) {
chk = false;
break;
}
}
}
}//end for kvs
if (chk) {
set.add(row);
if (qty > 0 && set.size() >= qty) {
break;
}
}
}//end for rows
set.cloneProperty(this);
return set;
}
public DataSet getRows(int begin, String... params) {
return getRows(begin, -1, params);
}
public DataSet getRows(String... params) {
return getRows(0, params);
}
public DataSet getRows(DataSet set, String key) {
String kvs[] = new String[set.size()];
int i = 0;
for (DataRow row : set) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
kvs[i++] = key + ":" + value;
}
}
return getRows(kvs);
}
public DataSet getRows(DataRow row, String... keys) {
List<String> list = new ArrayList<>();
int i = 0;
for (String key : keys) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
list.add(key + ":" + value);
}
}
String[] kvs = BeanUtil.list2array(list);
return getRows(kvs);
}
/**
*
*
* @param format format
* @param cols cols
* @return DataSet
*/
public DataSet formatNumber(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatNumber(format, cols);
}
return this;
}
public DataSet numberFormat(String target, String key, String format){
for(DataRow row: rows){
numberFormat(target, key, format);
}
return this;
}
public DataSet numberFormat(String key, String format){
return numberFormat(key, key, format);
}
/**
*
*
* @param format format
* @param cols cols
* @return DataSet
*/
public DataSet formatDate(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatDate(format, cols);
}
return this;
}
public DataSet dateFormat(String target, String key, String format){
for(DataRow row: rows){
row.dateFormat(target, key, format);
}
return this;
}
public DataSet dateParse(String target, String key, String format){
for(DataRow row: rows){
row.dateParse(target, key, format);
}
return this;
}
public DataSet dateParse(String target, String key){
for(DataRow row: rows){
row.dateParse(target, key);
}
return this;
}
public DataSet dateParse(String key){
for(DataRow row: rows){
row.dateParse(key, key);
}
return this;
}
public DataSet dateFormat(String key, String format){
return dateFormat(key, key, format);
}
/**
*
*
* @param begin begin
* @param end end
* @param key key
* @param value value
* @return DataSet
*/
public DataSet filter(int begin, int end, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
int size = size();
if (begin < 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
tmpValue = getString(i, key, "");
if ((null == value && null == tmpValue)
|| (null != value && value.equals(tmpValue))) {
set.add(getRow(i));
}
}
set.cloneProperty(this);
return set;
}
public DataSet getRows(int fr, int to) {
DataSet set = new DataSet();
int size = this.size();
if (fr < 0) {
fr = 0;
}
for (int i = fr; i < size && i <= to; i++) {
set.addRow(getRow(i));
}
return set;
}
/**
*
* @param begin
* @param end
* @param key key
* @return BigDecimal
*/
public BigDecimal sum(int begin, int end, String key) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (begin <= 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(getDecimal(i, key, 0));
}
}
return result;
}
public BigDecimal sum(String key) {
BigDecimal result = BigDecimal.ZERO;
result = sum(0, size() - 1, key);
return result;
}
/**
*
* @param result
* @param fixs fixs
* @param keys keys
* @return DataRow
*/
public DataRow sums(DataRow result, List<String> fixs, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
List<String> list = BeanUtil.merge(fixs, keys);
for (String key : list) {
result.put(key, sum(key));
}
}
return result;
}
public DataRow sums(DataRow result, String[] fixs, String... keys) {
return sums(result, BeanUtil.array2list(fixs, keys));
}
public DataRow sums(String ... keys) {
List<String> list = BeanUtil.array2list(keys);
if(list.size() ==0 && size() >0){
list = getRow(0).numberKeys();
}
return sums(new DataRow(), list);
}
/**
*
*
* @param result
* @param fixs fixs
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, List<String> fixs, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
List<String> list = BeanUtil.merge(fixs, keys);
for (String key : list) {
result.put(key, avg(key));
}
}
return result;
}
public DataRow avgs(DataRow result, String[] fixs, String... keys) {
return avgs(result, BeanUtil.array2list(fixs, keys));
}
public DataRow avgs(String ... keys) {
List<String> list = BeanUtil.array2list(keys);
if(list.size() ==0 && size() >0){
list = getRow(0).numberKeys();
}
return avgs(new DataRow(), list);
}
/**
*
* @param result
* @param scale scale
* @param round round
* @param fixs fixs
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, int scale, int round, List<String> fixs, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
List<String> list = BeanUtil.merge(fixs, keys);
for (String key : keys) {
result.put(key, avg(key, scale, round));
}
}
return result;
}
public DataRow avgs(DataRow result, int scale, int round, String[] fixs, String... keys) {
return avgs(result, scale, round, BeanUtil.array2list(fixs, keys));
}
public DataRow avgs(int scale, int round, String ... keys) {
List<String> list = BeanUtil.array2list(keys);
if(list.size() ==0 && size() >0){
list = getRow(0).numberKeys();
}
return avgs(new DataRow(), scale, round, list);
}
/**
*
*
* @param top
* @param key key
* @return BigDecimal
*/
public BigDecimal maxDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) > 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal maxDecimal(String key) {
return maxDecimal(size(), key);
}
public int maxInt(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int maxInt(String key) {
return maxInt(size(), key);
}
public double maxDouble(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double maxDouble(String key) {
return maxDouble(size(), key);
}
public double maxFloat(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.floatValue();
}
public double maxFloat(String key) {
return maxFloat(size(), key);
}
// public BigDecimal max(int top, String key){
// BigDecimal result = maxDecimal(top, key);
// return result;
// public BigDecimal max(String key){
// return maxDecimal(size(), key);
/**
*
*
* @param top
* @param key key
* @return BigDecimal
*/
public BigDecimal minDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) < 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal minDecimal(String key) {
return minDecimal(size(), key);
}
public int minInt(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int minInt(String key) {
return minInt(size(), key);
}
public double minDouble(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double minDouble(String key) {
return minDouble(size(), key);
}
public double minFloat(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.floatValue();
}
public double minFloat(String key) {
return minFloat(size(), key);
}
// public BigDecimal min(int top, String key){
// BigDecimal result = minDecimal(top, key);
// return result;
// public BigDecimal min(String key){
// return minDecimal(size(), key);
/**
* keyvalue
*
* @param key key
* @return DataRow
*/
public DataRow max(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(size - 1);
} else if (isDesc) {
row = getRow(0);
} else {
asc(key);
row = getRow(size - 1);
}
return row;
}
public DataRow min(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(0);
} else if (isDesc) {
row = getRow(size - 1);
} else {
asc(key);
row = getRow(0);
}
return row;
}
/**
*
*
* @param top
* @param key key
* @param scale scale
* @param round round
* @return BigDecimal
*/
public BigDecimal avg(int top, String key, int scale, int round) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (size > top) {
size = top;
}
int count = 0;
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(tmp);
}
count++;
}
if (count > 0) {
result = result.divide(new BigDecimal(count), scale, round);
}
return result;
}
public BigDecimal avg(String key, int scale, int round) {
BigDecimal result = avg(size(), key, scale ,round);
return result;
}
public BigDecimal avg(String key) {
BigDecimal result = avg(size(), key, 2, BigDecimal.ROUND_HALF_UP);
return result;
}
public DataSet addRow(DataRow row) {
if (null != row) {
rows.add(row);
}
return this;
}
public DataSet addRow(int idx, DataRow row) {
if (null != row) {
rows.add(idx, row);
}
return this;
}
/**
* key connector
*
* @param key key
* @param connector connector
* @return String v1,v2,v3
*/
public String concat(String key, String connector) {
return BasicUtil.concat(getStrings(key), connector);
}
public String concatNvl(String key, String connector) {
return BasicUtil.concat(getNvlStrings(key), connector);
}
/**
* key connector(null)
*
* @param key key
* @param connector connector
* @return String v1,v2,v3
*/
public String concatWithoutNull(String key, String connector) {
return BasicUtil.concat(getStringsWithoutNull(key), connector);
}
/**
* key connector()
*
* @param key key
* @param connector connector
* @return String v1,v2,v3
*/
public String concatWithoutEmpty(String key, String connector) {
return BasicUtil.concat(getStringsWithoutEmpty(key), connector);
}
public String concatNvl(String key) {
return BasicUtil.concat(getNvlStrings(key), ",");
}
public String concatWithoutNull(String key) {
return BasicUtil.concat(getStringsWithoutNull(key), ",");
}
public String concatWithoutEmpty(String key) {
return BasicUtil.concat(getStringsWithoutEmpty(key), ",");
}
public String concat(String key) {
return BasicUtil.concat(getStrings(key), ",");
}
/**
*
*
* @param key key
* @return List
*/
public List<Object> fetchValues(String key) {
List<Object> result = new ArrayList<Object>();
for (int i = 0; i < size(); i++) {
result.add(get(i, key));
}
return result;
}
/**
*
*
* @param key key
* @return List
*/
public List<String> fetchDistinctValue(String key) {
List<String> result = new ArrayList<>();
for (int i = 0; i < size(); i++) {
String value = getString(i, key, "");
if (result.contains(value)) {
continue;
}
result.add(value);
}
return result;
}
public List<String> fetchDistinctValues(String key) {
return fetchDistinctValue(key);
}
/**
*
*
* @param link link
* @return String
*/
public String displayNavi(String link) {
String result = "";
if (null != navi) {
result = navi.getHtml();
}
return result;
}
public String navi(String link) {
return displayNavi(link);
}
public String displayNavi() {
return displayNavi(null);
}
public String navi() {
return displayNavi(null);
}
public DataSet put(int idx, String key, Object value) {
DataRow row = getRow(idx);
if (null != row) {
row.put(key, value);
}
return this;
}
public DataSet removes(String... keys) {
for (DataRow row : rows) {
row.removes(keys);
}
return this;
}
/**
* String
*
* @param index index
* @param key key
* @return String
* @throws Exception Exception
*/
public String getString(int index, String key) throws Exception {
return getRow(index).getString(key);
}
public String getString(int index, String key, String def) {
try {
return getString(index, key);
} catch (Exception e) {
return def;
}
}
public String getString(String key) throws Exception {
return getString(0, key);
}
public String getString(String key, String def) {
return getString(0, key, def);
}
public Object get(int index, String key) {
DataRow row = getRow(index);
if (null != row) {
return row.get(key);
}
return null;
}
public List<Object> gets(String key) {
List<Object> list = new ArrayList<Object>();
for (DataRow row : rows) {
list.add(row.getString(key));
}
return list;
}
public List<DataSet> getSets(String key) {
List<DataSet> list = new ArrayList<DataSet>();
for (DataRow row : rows) {
DataSet set = row.getSet(key);
if (null != set) {
list.add(set);
}
}
return list;
}
public List<String> getStrings(String key) {
List<String> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getString(key));
}
return result;
}
public List<String> getStrings(String key, String ... defs) {
List<String> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getStringNvl(key, defs));
}
return result;
}
public List<Integer> getInts(String key) throws Exception {
List<Integer> result = new ArrayList<Integer>();
for (DataRow row : rows) {
result.add(row.getInt(key));
}
return result;
}
public List<Integer> getInts(String key, int def) {
List<Integer> result = new ArrayList<Integer>();
for (DataRow row : rows) {
result.add(row.getInt(key, def));
}
return result;
}
public List<Long> getLongs(String key) throws Exception {
List<Long> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getLong(key));
}
return result;
}
public List<Long> getLongs(String key, Long def) {
List<Long> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getLong(key, def));
}
return result;
}
public List<Double> getDoubles(String key) throws Exception {
List<Double> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getDouble(key));
}
return result;
}
public List<Double> getDoubles(String key, Double def) {
List<Double> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getDouble(key, def));
}
return result;
}
public List<Object> getObjects(String key) {
List<Object> result = new ArrayList<Object>();
for (DataRow row : rows) {
result.add(row.get(key));
}
return result;
}
public List<String> getDistinctStrings(String key) {
return fetchDistinctValue(key);
}
public List<String> getNvlStrings(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
} else {
result.add("");
}
}
return result;
}
public List<String> getStringsWithoutEmpty(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (BasicUtil.isNotEmpty(val)) {
result.add(val.toString());
}
}
return result;
}
public List<String> getStringsWithoutNull(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
}
}
return result;
}
public BigDecimal getDecimal(int idx, String key) throws Exception {
return getRow(idx).getDecimal(key);
}
public BigDecimal getDecimal(int idx, String key, double def) {
return getDecimal(idx, key, new BigDecimal(def));
}
public BigDecimal getDecimal(int idx, String key, BigDecimal def) {
try {
BigDecimal val = getDecimal(idx, key);
if (null == val) {
return def;
}
return val;
} catch (Exception e) {
return def;
}
}
/**
* DataSet DataSet,()
* @param keys keys
* @return DataSet
*/
public DataSet extract(String ... keys){
return extract(BeanUtil.array2list(keys));
}
public DataSet extract(String[] fixs, String ... keys){
return extract(BeanUtil.array2list(fixs, keys));
}
public DataSet extract(List<String> fixs, String ... keys){
DataSet result = new DataSet();
List<String> list = BeanUtil.merge(fixs, keys);
for(DataRow row:rows){
DataRow item = row.extract(list);
result.add(item);
}
result.navi = this.navi;
return result;
}
/**
* html()
*
* @param index index
* @param key key
* @return String
* @throws Exception Exception
*/
public String getHtmlString(int index, String key) throws Exception {
return getString(index, key);
}
public String getHtmlString(int index, String key, String def) {
return getString(index, key, def);
}
public String getHtmlString(String key) throws Exception {
return getHtmlString(0, key);
}
/**
* escape String
*
* @param index index
* @param key key
* @return String
* @throws Exception Exception
*/
public String getEscapeString(int index, String key) throws Exception {
return EscapeUtil.escape(getString(index, key)).toString();
}
public String getEscapeString(int index, String key, String def) {
try {
return getEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.escape(def).toString();
}
}
public String getDoubleEscapeString(int index, String key) throws Exception {
return EscapeUtil.doubleEscape(getString(index, key));
}
public String getDoubleEscapeString(int index, String key, String def) {
try {
return getDoubleEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.doubleEscape(def);
}
}
public String getEscapeString(String key) throws Exception {
return getEscapeString(0, key);
}
public String getDoubleEscapeString(String key) throws Exception {
return getDoubleEscapeString(0, key);
}
/**
* int
*
* @param index index
* @param key key
* @return int
* @throws Exception Exception
*/
public int getInt(int index, String key) throws Exception {
return getRow(index).getInt(key);
}
public int getInt(int index, String key, int def) {
try {
return getInt(index, key);
} catch (Exception e) {
return def;
}
}
public int getInt(String key) throws Exception {
return getInt(0, key);
}
public int getInt(String key, int def) {
return getInt(0, key, def);
}
/**
* double
*
* @param index index
* @param key key
* @return double
* @throws Exception Exception
*/
public double getDouble(int index, String key) throws Exception {
return getRow(index).getDouble(key);
}
public double getDouble(int index, String key, double def) {
try {
return getDouble(index, key);
} catch (Exception e) {
return def;
}
}
public double getDouble(String key) throws Exception {
return getDouble(0, key);
}
public double getDouble(String key, double def) {
return getDouble(0, key, def);
}
/**
* key +value,key0puttarget
* targetkey
* @param target key
* @param key key
* @param value value
* @return this
*/
public DataSet add(String target, String key, int value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, double value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, short value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, float value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String key, int value){
return add(key, key, value);
}
public DataSet add(String key, double value){
return add(key, key, value);
}
public DataSet add(String key, short value){
return add(key, key, value);
}
public DataSet add(String key, float value){
return add(key, key, value);
}
public DataSet add(String key, BigDecimal value){
return add(key, key, value);
}
public DataSet subtract(String target, String key, int value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, double value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, short value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, float value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String key, int value){
return subtract(key, key, value);
}
public DataSet subtract(String key, double value){
return subtract(key, key, value);
}
public DataSet subtract(String key, short value){
return subtract(key, key, value);
}
public DataSet subtract(String key, float value){
return subtract(key, key, value);
}
public DataSet subtract(String key, BigDecimal value){
return subtract(key, key, value);
}
public DataSet multiply(String target, String key, int value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, double value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, short value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, float value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String key, int value){
return multiply(key,key,value);
}
public DataSet multiply(String key, double value){
return multiply(key,key,value);
}
public DataSet multiply(String key, short value){
return multiply(key,key,value);
}
public DataSet multiply(String key, float value){
return multiply(key,key,value);
}
public DataSet multiply(String key, BigDecimal value){
return multiply(key,key,value);
}
public DataSet divide(String target, String key, int value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, double value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, short value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, float value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, BigDecimal value, int mode){
for(DataRow row:rows){
row.divide(target, key, value, mode);
}
return this;
}
public DataSet divide(String key, int value){
return divide(key,key, value);
}
public DataSet divide(String key, double value){
return divide(key,key, value);
}
public DataSet divide(String key, short value){
return divide(key,key, value);
}
public DataSet divide(String key, float value){
return divide(key,key, value);
}
public DataSet divide(String key, BigDecimal value, int mode){
return divide(key,key, value, mode);
}
public DataSet round(String target, String key, int scale, int mode){
for (DataRow row:rows){
row.round(target, key, scale, mode);
}
return this;
}
/**
*
* @param key
* @param scale
* @param mode BigDecimal
* ROUND_UP 1 :2.36 2.4
* ROUND_DOWN (1,). :2.36 2.3
* ROUND_CEILING BigDecimal , ROUND_UP , ROUND_DOWN ROUND_UP ROUND_DOWN
* ROUND_FLOOR BigDecimal , ROUND_DOWN , ROUND_UP ROUND_CEILING
* ROUND_HALF_UP
* ROUND_HALF_DOWN
* ROUND_HALF_EVEN , ROUND_HALF_UP , ROUND_HALF_DOWN :1.15 1.1,1.25 1.2
* ROUND_UNNECESSARY , , ArithmeticException
* @return DataSet
*/
public DataSet round(String key, int scale, int mode){
return round(key, key, scale, mode);
}
/**
* DataSetsize
* @param page
* @return list
*/
public List<DataSet> split(int page){
List<DataSet> list = new ArrayList<>();
int size = this.size();
int vol = (size-1) / page + 1;
for(int i=0; i<page; i++){
int fr = i*vol;
int to = (i+1)*vol-1;
if(i == page-1){
to = size-1;
}
DataSet set = this.cuts(fr, to);
list.add(set);
}
return list;
}
/**
* rows json toJSON
* map.put("type", "list");
* map.put("result", result);
* map.put("message", message);
* map.put("rows", rows);
* map.put("success", result);
* map.put("navi", navi);
*/
public String toString() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", "list");
map.put("result", result);
map.put("message", message);
map.put("rows", rows);
map.put("success", result);
if(null != navi){
Map<String,Object> navi_ = new HashMap<String,Object>();
navi_.put("page", navi.getCurPage());
navi_.put("pages", navi.getTotalPage());
navi_.put("rows", navi.getTotalRow());
navi_.put("vol", navi.getPageRows());
map.put("navi", navi_);
}
return BeanUtil.map2json(map);
}
/**
* rows json toString
*
* @return String
*/
public String toJson() {
return BeanUtil.object2json(this);
}
public String getJson() {
return toJSON();
}
public String toJSON() {
return toJson();
}
/**
* map
*
* @param key ID,{ID}_{NM}
* @return Map
*/
public Map<String, DataRow> toMap(String key) {
Map<String, DataRow> maps = new HashMap<String, DataRow>();
for (DataRow row : rows) {
maps.put(row.getString(key), row);
}
return maps;
}
/**
*
*
* @param idx idx
* @return Object
*/
public Object getChildren(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getChildren();
}
return null;
}
public Object getChildren() {
return getChildren(0);
}
public DataSet setChildren(int idx, Object children) {
DataRow row = getRow(idx);
if (null != row) {
row.setChildren(children);
}
return this;
}
public DataSet setChildren(Object children) {
setChildren(0, children);
return this;
}
/**
*
*
* @param idx idx
* @return Object
*/
public Object getParent(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getParent();
}
return null;
}
public Object getParent() {
return getParent(0);
}
public DataSet setParent(int idx, Object parent) {
DataRow row = getRow(idx);
if (null != row) {
row.setParent(parent);
}
return this;
}
public DataSet setParent(Object parent) {
setParent(0, parent);
return this;
}
/**
*
*
* @param <T> T
* @param index index
* @param clazz clazz
* @return T
*/
public <T> T entity(int index, Class<T> clazz) {
DataRow row = getRow(index);
if (null != row) {
return row.entity(clazz);
}
return null;
}
/**
*
*
* @param <T> T
* @param clazz clazz
* @return List
*/
public <T> List<T> entity(Class<T> clazz) {
List<T> list = new ArrayList<T>();
if (null != rows) {
for (DataRow row : rows) {
list.add(row.entity(clazz));
}
}
return list;
}
public <T> T entity(Class<T> clazz, int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.entity(clazz);
}
return null;
}
public DataSet setDataSource(String dataSource) {
if (null == dataSource) {
return this;
}
this.dataSource = dataSource;
if (dataSource.contains(".") && !dataSource.contains(":")) {
schema = dataSource.substring(0, dataSource.indexOf("."));
table = dataSource.substring(dataSource.indexOf(".") + 1);
}
for (DataRow row : rows) {
if (BasicUtil.isEmpty(row.getDataSource())) {
row.setDataSource(dataSource);
}
}
return this;
}
/**
*
* @param set DataSet
* @param fixs fixs
* @param keys keys
* @return DataSet
*/
public DataSet union(DataSet set, List<String> fixs, String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
List<String> list = BeanUtil.merge(fixs, keys);
if (list.size() == 0) {
list.add(ConfigTable.getString("DEFAULT_PRIMARY_KEY"));
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
if (! result.contains(item, list)) {
result.add(item);
}
}
return result;
}
public DataSet union(DataSet set, String[] fixs, String... keys) {
return union(set, BeanUtil.array2list(fixs, keys));
}
public DataSet union(DataSet set, String... keys) {
return union(set, BeanUtil.array2list(keys));
}
/**
*
*
* @param set set
* @return DataSet
*/
public DataSet unionAll(DataSet set) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
result.add(item);
}
return result;
}
/**
*
*
* @param row row
* @param fixs fixs
* @param keys keys
* @return boolean
*/
public boolean contains(DataRow row, List<String> fixs, String... keys) {
if (null == rows || rows.size() == 0 || null == row) {
return false;
}
List<String> list = BeanUtil.merge(fixs, keys);
if (list.size() == 0) {
list.add(ConfigTable.getString("DEFAULT_PRIMARY_KEY", "ID"));
}
String params[] = packParam(row, list);
return exists(params);
}
public boolean contains(DataRow row, String[] fixs, String... keys) {
return contains(row, BeanUtil.array2list(fixs, keys));
}
public boolean contains(DataRow row, String... keys) {
return contains(row, BeanUtil.array2list(keys));
}
public String[] packParam(DataRow row, List<String> fixs, String... keys) {
if (null == row) {
return null;
}
List<String> list = BeanUtil.merge(fixs, keys);
if(list.size()==0){
return null;
}
String params[] = new String[list.size() * 2];
int idx = 0;
for (String key : list) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
public String[] packParam(DataRow row, String[] fixs, String... keys) {
return packParam(row, BeanUtil.array2list(fixs, keys));
}
public String[] packParam(DataRow row, String... keys) {
return packParam(row, BeanUtil.array2list(keys));
}
/**
* kvs
* ["ID","1","CODE","A01"]
* @param row DataRow
* @param keys ID,CODE
* @return kvs
*/
public String[] packParam(DataRow row, List<String> keys) {
if (null == keys || null == row) {
return null;
}
String params[] = new String[keys.size() * 2];
int idx = 0;
for (String key : keys) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
/**
* itemskey
* dispatch("children",items, "DEPAT_CD")
* dispatchs("children",items, "CD:BASE_CD")
*
* @param field "ITEMS"
* @param unique ()
* @param recursion
* @param items items
* @param fixs fixs
* @param keys ID:DEPT_IDID
* @return DataSet
*/
public DataSet dispatchs(String field, boolean unique, boolean recursion, DataSet items, List<String> fixs, String... keys) {
if (null == items) {
return this;
}
List<String> list = BeanUtil.merge(fixs, keys);
if(list.size() == 0){
throw new RuntimeException("");
}
if (BasicUtil.isEmpty(field)) {
field = "ITEMS";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] kvs = packParam(row, reverseKey(list));
DataSet set = items.getRows(kvs);
if (recursion) {
set.dispatchs(field, unique, recursion, items, list);
}
if(unique) {
set.skip(true);
}
row.put(field, set);
}
}
items.skip(false);
return this;
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, DataSet items, String[] fixs, String... keys) {
return dispatchs(field, unique, recursion, items, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs(field, unique, recursion, items, BeanUtil.array2list(keys));
}
public DataSet dispatchs(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs("ITEMS", unique, recursion, items, keys);
}
public DataSet dispatchs(boolean unique, boolean recursion, DataSet items, List<String> fixs, String... keys) {
return dispatchs("ITEMS", unique, recursion, items, BeanUtil.merge(fixs, keys));
}
public DataSet dispatchs(boolean unique, boolean recursion, DataSet items, String[] fixs, String... keys) {
return dispatchs("ITEMS", unique, recursion, items, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatchs(String field, DataSet items, String... keys) {
return dispatchs(field,false, false, items, keys);
}
public DataSet dispatchs(String field, DataSet items, String[] fixs, String... keys) {
return dispatchs(field,false, false, items, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatchs(String field, DataSet items, List<String> fixs, String... keys) {
return dispatchs(field,false, false, items, BeanUtil.merge(fixs, keys));
}
public DataSet dispatchs(DataSet items, String... keys) {
return dispatchs("ITEMS", items, keys);
}
public DataSet dispatchs(DataSet items, List<String> fixs, String... keys) {
return dispatchs("ITEMS", items, BeanUtil.merge(fixs, keys));
}
public DataSet dispatchs(DataSet items, String[] fixs, String... keys) {
return dispatchs("ITEMS", items, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatchs(boolean unique, boolean recursion, String... keys) {
return dispatchs("ITEMS", unique, recursion, this, keys);
}
public DataSet dispatchs(boolean unique, boolean recursion, List<String> fixs, String... keys) {
return dispatchs("ITEMS", unique, recursion, this, BeanUtil.merge(fixs, keys));
}
public DataSet dispatchs(boolean unique, boolean recursion, String[] fixs, String... keys) {
return dispatchs("ITEMS", unique, recursion, this, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, this, keys);
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, List<String> fixs, String... keys) {
return dispatchs(field, unique, recursion, this, BeanUtil.merge(fixs, keys));
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, String[] fixs, String... keys) {
return dispatchs(field, unique, recursion, this, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatch(String field, boolean unique, boolean recursion, DataSet items, List<String> fixs, String... keys) {
if (null == items) {
return this;
}
List<String> list = BeanUtil.merge(fixs, keys);
if(list.size() == 0){
throw new RuntimeException("");
}
if (BasicUtil.isEmpty(field)) {
field = "ITEMS";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] params = packParam(row, reverseKey(list));
DataRow result = items.getRow(params);
if(unique){
result.skip = true;
}
row.put(field, result);
}
}
items.skip(false);
return this;
}
public DataSet dispatch(String field, boolean unique, boolean recursion, DataSet items, String[] fixs, String... keys) {
return dispatchs(field, unique, recursion, items, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatch(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs(field, unique, recursion, items, BeanUtil.array2list(keys));
}
public DataSet dispatch(String field, DataSet items, String... keys) {
return dispatch(field, false, false, items, keys);
}
public DataSet dispatch(String field, DataSet items, String[] fixs, String... keys) {
return dispatch(field, false, false, items, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatch(String field, DataSet items, List<String> fixs, String... keys) {
return dispatch(field, false, false, items, BeanUtil.merge(fixs, keys));
}
public DataSet dispatch(DataSet items, String... keys) {
return dispatch("ITEM", items, BeanUtil.array2list(keys));
}
public DataSet dispatch(DataSet items, String[] fixs, String... keys) {
return dispatch("ITEM", items, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatch(DataSet items, List<String> fixs, String... keys) {
return dispatch("ITEM", items, BeanUtil.merge(fixs, keys));
}
public DataSet dispatch(boolean unique, boolean recursion, String... keys) {
return dispatch("ITEM", unique, recursion, this, keys);
}
public DataSet dispatch(boolean unique, boolean recursion, String[] fixs, String... keys) {
return dispatch("ITEM", unique, recursion, this, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatch(boolean unique, boolean recursion, List<String> fixs, String... keys) {
return dispatch("ITEM", unique, recursion, this, BeanUtil.merge(fixs, keys));
}
public DataSet dispatch(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, this, keys);
}
public DataSet dispatch(String field, boolean unique, boolean recursion, String[] fixs, String... keys) {
return dispatch(field, unique, recursion, this, BeanUtil.array2list(fixs, keys));
}
public DataSet dispatch(String field, boolean unique, boolean recursion, List<String> fixs, String... keys) {
return dispatch(field, unique, recursion, this, BeanUtil.merge(fixs, keys));
}
/**
* dispatchs
* @param field "ITEMS"
* @param unique ()
* @param recursion
* @param items items
* @param keys ID:DEPT_IDID
* @return DataSet
*/
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs( unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(String field, DataSet items, String... keys) {
return dispatchs(field, items, keys);
}
@Deprecated
public DataSet dispatchItems(DataSet items, String... keys) {
return dispatchs(items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, String... keys) {
return dispatchs( unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatch(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItem(String field, DataSet items, String... keys) {
return dispatch(field, items, keys);
}
@Deprecated
public DataSet dispatchItem(DataSet items, String... keys) {
return dispatch(items, keys);
}
@Deprecated
public DataSet dispatchItem(boolean unique, boolean recursion, String... keys) {
return dispatch(unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, keys);
}
/**
* keys,,
*
* @param items
* @param fixs
* @param keys
* @return DataSet
*/
public DataSet join(DataSet items, List<String> fixs, String... keys) {
List<String> list = BeanUtil.merge(fixs, keys);
if (null == items || list.size() == 0) {
return this;
}
for (DataRow row : rows) {
String[] params = packParam(row, reverseKey(list));
DataRow result = items.getRow(params);
if (null != result) {
row.copy(result, result.keys());
}
}
return this;
}
public DataSet join(DataSet items, String[] fixs, String... keys) {
return join(items, BeanUtil.array2list(fixs, keys));
}
public DataSet join(DataSet items, String... keys) {
return join(items, BeanUtil.array2list(keys));
}
public DataSet toLowerKey() {
for (DataRow row : rows) {
row.toLowerKey();
}
return this;
}
public DataSet toUpperKey() {
for (DataRow row : rows) {
row.toUpperKey();
}
return this;
}
/**
* keys
*
* @param fixs keys
* @param keys keys
* @return DataSet
*/
public DataSet group(String[] fixs, String... keys) {
DataSet result = distinct(BeanUtil.merge(fixs, keys));
result.dispatchs(true,false, this, keys);
return result;
}
public DataSet group(List<String> fixs, String... keys) {
DataSet result = distinct(BeanUtil.merge(fixs, keys));
result.dispatchs(true,false, this, keys);
return result;
}
public DataSet group(String... keys) {
DataSet result = distinct(keys);
result.dispatchs(true,false, this, keys);
return result;
}
public Object agg(String type, String key){
Aggregation agg = Aggregation.valueOf(type);
Object result = null;
switch (agg){
case COUNT:
result = this.size();
break;
case SUM:
result = sum(key);
break;
case AVG:
result = avg(key);
break;
case MAX:
result = max(key);
break;
case MAX_DECIMAL:
result = maxDecimal(key);
break;
case MAX_DOUBLE:
result = maxDouble(key);
break;
case MAX_FLOAT:
result = maxFloat(key);
break;
case MAX_INT:
result = maxInt(key);
break;
case MIN:
result = min(key);
break;
case MIN_DECIMAL:
result = minDecimal(key);
break;
case MIN_DOUBLE:
result = minDouble(key);
break;
case MIN_FLOAT:
result = minFloat(key);
break;
case MIN_INT:
result = minInt(key);
break;
case STDEV:
result = stdev(key);
break;
case STDEVP:
result = stdevp(key);
break;
case STDEVA:
result = stdeva(key);
break;
case STDEVPA:
result = stdevpa(key);
break;
case VAR:
result = var(key);
break;
case VARA:
result = vara(key);
break;
case VARP:
result = varp(key);
break;
case VARPA:
result = varpa(key);
break;
}
return result;
}
public BigDecimal stdev(String key){
return null;
}
public BigDecimal stdeva(String key){
return null;
}
public BigDecimal stdevp(String key){
return null;
}
public BigDecimal stdevpa(String key){
return null;
}
public BigDecimal var(String key){
return null;
}
public BigDecimal vara(String key){
return null;
}
public BigDecimal varp(String key){
return null;
}
public BigDecimal varpa(String key){
return null;
}
public DataSet or(DataSet set, String... keys) {
return this.union(set, keys);
}
public DataSet getRows(Map<String, String> kvs) {
return getRows(0, -1, kvs);
}
/**
*
*
* @param distinct keys
* @param sets
* @param keys
* @return DataSet
*/
public static DataSet intersection(boolean distinct, List<DataSet> sets, String... keys) {
DataSet result = null;
if (null != sets && sets.size() > 0) {
for (DataSet set : sets) {
if (null == result) {
result = set;
} else {
result = result.intersection(distinct, set, keys);
}
}
}
if (null == result) {
result = new DataSet();
}
return result;
}
public static DataSet intersection(List<DataSet> sets, String... keys) {
return intersection(false, sets, keys);
}
/**
*
*
* @param distinct keys(keys)
* @param set set
* @param keys keys,"ID:USER_ID",IDDataSet,USER_IDDataSet
* @return DataSet
*/
public DataSet intersection(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
if (null == set) {
return result;
}
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (set.contains(row, kv)) {
if(!result.contains(row, kv)){//result
result.add((DataRow) row.clone());
}else {
if(!distinct){//resultdistinct
result.add((DataRow) row.clone());
}
}
}
}
return result;
}
public DataSet intersection(DataSet set, String... keys) {
return intersection(false, set, keys);
}
public DataSet and(boolean distinct, DataSet set, String... keys) {
return intersection(distinct, set, keys);
}
public DataSet and(DataSet set, String... keys) {
return intersection(false, set, keys);
}
/**
*
* this,set
* this set
*
* @param distinct keys
* @param set set
* @param keys keys
* @return DataSet
*/
public DataSet complement(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet complement(DataSet set, String... keys) {
return complement(false, set, keys);
}
/**
*
* setrow,DataSet
* this set
*
* @param distinct keys
* @param set set
* @param keys CD,"CD:WORK_CD"
* @return DataSet
*/
public DataSet difference(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet difference(DataSet set, String... keys) {
return difference(false, set, keys);
}
/**
* kv-vk
*
* @param keys kv
* @return String[]
*/
private String[] reverseKey(String[] keys) {
return reverseKey(BeanUtil.array2list(keys));
}
private String[] reverseKey(List<String> keys) {
if (null == keys) {
return new String[0];
}
int size = keys.size();
String result[] = new String[size];
for (int i = 0; i < size; i++) {
String key = keys.get(i);
if (BasicUtil.isNotEmpty(key) && key.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(key);
key = ks[1] + ":" + ks[0];
}
result[i] = key;
}
return result;
}
/**
* ,keys,
*
* @param keys keys
* @return DataSet
*/
public DataSet removeEmptyRow(String... keys) {
int size = this.size();
for (int i = size - 1; i >= 0; i
DataRow row = getRow(i);
if (null == keys || keys.length == 0) {
if (row.isEmpty()) {
this.remove(row);
}
} else {
boolean isEmpty = true;
for (String key : keys) {
if (row.isNotEmpty(key)) {
isEmpty = false;
break;
}
}
if (isEmpty) {
this.remove(row);
}
}
}
return this;
}
public DataSet changeKey(String key, String target, boolean remove) {
for(DataRow row:rows){
row.changeKey(key, target, remove);
}
return this;
}
public DataSet changeKey(String key, String target) {
return changeKey(key, target, true);
}
/**
* rowscolumns
*
* @param columns ,
* @return DataSet
*/
public DataSet removeColumn(String... columns) {
if (null != columns) {
for (String column : columns) {
for (DataRow row : rows) {
row.remove(column);
}
}
}
return this;
}
/**
* rows(null|'')
*
* @param columns ,
* @return DataSet
*/
public DataSet removeEmptyColumn(String... columns) {
for (DataRow row : rows) {
row.removeEmpty(columns);
}
return this;
}
/**
* NULL > ""
*
* @return DataSet
*/
public DataSet nvl() {
for (DataRow row : rows) {
row.nvl();
}
return this;
}
public boolean add(DataRow e) {
return rows.add((DataRow) e);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public boolean addAll(Collection c) {
return rows.addAll(c);
}
public void clear() {
rows.clear();
}
public boolean contains(Object o) {
return rows.contains(o);
}
public boolean containsAll(Collection<?> c) {
return rows.containsAll(c);
}
public Iterator<DataRow> iterator() {
return rows.iterator();
}
public boolean remove(Object o) {
return rows.remove(o);
}
public boolean removeAll(Collection<?> c) {
return rows.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return rows.retainAll(c);
}
public Object[] toArray() {
return rows.toArray();
}
@SuppressWarnings("unchecked")
public Object[] toArray(Object[] a) {
return rows.toArray(a);
}
public String getSchema() {
return schema;
}
public DataSet setSchema(String schema) {
this.schema = schema;
return this;
}
public String getTable() {
return table;
}
public DataSet setTable(String table) {
if (null != table && table.contains(".")) {
String[] tbs = table.split("\\.");
this.table = tbs[1];
this.schema = tbs[0];
} else {
this.table = table;
}
return this;
}
/**
*
*
* true
*
* @param millisecond () millisecond ()
* @return boolean
*/
public boolean isExpire(int millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire(long millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire() {
if (getExpires() == -1) {
return false;
}
if (System.currentTimeMillis() - createTime > getExpires()) {
return true;
}
return false;
}
public long getCreateTime() {
return createTime;
}
public List<DataRow> getRows() {
return rows;
}
/**
* ()
*
* @return long
*/
public long getExpires() {
return expires;
}
public DataSet setExpires(long millisecond) {
this.expires = millisecond;
return this;
}
public DataSet setExpires(int millisecond) {
this.expires = millisecond;
return this;
}
public boolean isResult() {
return result;
}
public boolean isSuccess() {
return result;
}
public DataSet setResult(boolean result) {
this.result = result;
return this;
}
public Exception getException() {
return exception;
}
public DataSet setException(Exception exception) {
this.exception = exception;
return this;
}
public String getMessage() {
return message;
}
public DataSet setMessage(String message) {
this.message = message;
return this;
}
public PageNavi getNavi() {
return navi;
}
public DataSet setNavi(PageNavi navi) {
this.navi = navi;
return this;
}
public DataSet setRows(List<DataRow> rows) {
this.rows = rows;
return this;
}
public String getDataSource() {
String ds = table;
if (BasicUtil.isNotEmpty(ds) && BasicUtil.isNotEmpty(schema)) {
ds = schema + "." + ds;
}
if (BasicUtil.isEmpty(ds)) {
ds = dataSource;
}
return ds;
}
public DataSet order(final String... keys) {
return asc(keys);
}
public DataSet put(String key, Object value, boolean pk, boolean override) {
for (DataRow row : rows) {
row.put(key, value, pk, override);
}
return this;
}
public DataSet put(String key, Object value, boolean pk) {
for (DataRow row : rows) {
row.put(key, value, pk);
}
return this;
}
public DataSet put(String key, Object value) {
for (DataRow row : rows) {
row.put(key, value);
}
return this;
}
/**
*
* (, , , , , )
* @param pks key(,)
* @param classKeys key(,)
* @param valueKeys key(,),keyvalue
* @return
* key
* [
* {:01,:,2010--:100},
* {:01,:,2010--:A},
* {:01,:,2010--:100}
* ]
* valueKey[
* {:01,:,2010-:100},
* {:01,:,2010-:90}
* ]
* valuekey [
* {:01,:,2010-:{:100,:A}},
* {:01,:,2010-:{:100,:A}}
* ]
*/
public DataSet pivot(List<String> pks, List<String> classKeys, List<String> valueKeys) {
DataSet result = distinct(pks);
DataSet classValues = distinct(classKeys); //[{:2010,:},{:2010,:},{:2011,:}]
for (DataRow row : result) {
for (DataRow classValue : classValues) {
DataRow params = new DataRow();
params.copy(row, pks).copy(classValue);
DataRow valueRow = getRow(params);
if(null != valueRow){
valueRow.skip = true;
}
String finalKey = concatValue(classValue,"-");//2010-
if(null != valueKeys && valueKeys.size() > 0){
if(valueKeys.size() == 1){
if (null != valueRow) {
row.put(finalKey, valueRow.get(valueKeys.get(0)));
} else {
row.put(finalKey, null);
}
}else {
for (String valueKey : valueKeys) {
//{2010--:100;2010--:A}
if (null != valueRow) {
row.put(finalKey + "-" + valueKey, valueRow.get(valueKey));
} else {
row.put(finalKey + "-" + valueKey, null);
}
}
}
}else{
if (null != valueRow){
row.put(finalKey, valueRow);
}else{
row.put(finalKey, null);
}
}
}
}
skip(false);
return result;
}
public DataSet pivot(String[] pks, String[] classKeys, String[] valueKeys) {
return pivot(BeanUtil.array2list(pks),BeanUtil.array2list(classKeys),BeanUtil.array2list(valueKeys));
}
/**
*
* @param pk key()key,(,)
* @param classKey key()key,(,)
* @param valueKey key()key,(,)
* @return
* (,,)
* [{:,:100,:90,:80},{:,:100,:90,:80}]
*/
public DataSet pivot(String pk, String classKey, String valueKey) {
List<String> pks = BeanUtil.array2list(pk.trim().split(","));
List<String> classKeys = BeanUtil.array2list(classKey.trim().split(","));
List<String> valueKeys = BeanUtil.array2list(valueKey.trim().split(","));
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(String pk, String classKey) {
List<String> pks = BeanUtil.array2list(pk.trim().split(","));
List<String> classKeys = BeanUtil.array2list(classKey.trim().split(","));
List<String> valueKeys = new ArrayList<>();
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(List<String> pks, List<String> classKeys, String ... valueKeys) {
List<String> list = new ArrayList<>();
if(null != valueKeys){
for(String item:valueKeys){
list.add(item);
}
}
return pivot(pks, classKeys, valueKeys);
}
private String concatValue(DataRow row, String split){
StringBuilder builder = new StringBuilder();
List<String> keys = row.keys();
for(String key:keys){
if(builder.length() > 0){
builder.append(split);
}
builder.append(row.getString(key));
}
return builder.toString();
}
private String[] kvs(DataRow row){
List<String> keys = row.keys();
int size = keys.size();
String[] kvs = new String[size*2];
for(int i=0; i<size; i++){
String k = keys.get(i);
String v = row.getStringNvl(k);
kvs[i*2] = k;
kvs[i*2+1] = v;
}
return kvs;
}
/**
*
*
* @param keys keys
* @return DataSet
*/
public DataSet asc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return -1;
} else {
if (null == v2) {
return 1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal num1 = new BigDecimal(v1.toString());
BigDecimal num2 = new BigDecimal(v2.toString());
result = num1.compareTo(num2);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date1.compareTo(date2);
} else {
result = v1.toString().compareTo(v2.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = true;
isDesc = false;
return this;
}
public DataSet desc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return 1;
} else {
if (null == v2) {
return -1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal val1 = new BigDecimal(v1.toString());
BigDecimal val2 = new BigDecimal(v2.toString());
result = val2.compareTo(val1);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date2.compareTo(date1);
} else {
result = v2.toString().compareTo(v1.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = false;
isDesc = true;
return this;
}
public DataSet addAllUpdateColumns() {
for (DataRow row : rows) {
row.addAllUpdateColumns();
}
return this;
}
public DataSet clearUpdateColumns() {
for (DataRow row : rows) {
row.clearUpdateColumns();
}
return this;
}
public DataSet removeNull(String... keys) {
for (DataRow row : rows) {
row.removeNull(keys);
}
return this;
}
private static String key(String key) {
if (null != key && ConfigTable.IS_UPPER_KEY) {
key = key.toUpperCase();
}
return key;
}
/**
* NULL
*
* @param value value
* @return DataSet
*/
public DataSet replaceNull(String value) {
for (DataRow row : rows) {
row.replaceNull(value);
}
return this;
}
/**
*
*
* @param value value
* @return DataSet
*/
public DataSet replaceEmpty(String value) {
for (DataRow row : rows) {
row.replaceEmpty(value);
}
return this;
}
/**
* NULL
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet replaceNull(String key, String value) {
for (DataRow row : rows) {
row.replaceNull(key, value);
}
return this;
}
/**
*
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet replaceEmpty(String key, String value) {
for (DataRow row : rows) {
row.replaceEmpty(key, value);
}
return this;
}
public DataSet replace(String key, String oldChar, String newChar) {
if (null == key || null == oldChar || null == newChar) {
return this;
}
for (DataRow row : rows) {
row.replace(key, oldChar, newChar);
}
return this;
}
public DataSet replace(String oldChar, String newChar) {
for (DataRow row : rows) {
row.replace(oldChar, newChar);
}
return this;
}
/**
*
* @return DataRow
*/
public DataRow random() {
DataRow row = null;
int size = size();
if (size > 0) {
row = getRow(BasicUtil.getRandomNumber(0, size - 1));
}
return row;
}
/**
* qty
* @param qty
* @return DataSet
*/
public DataSet randoms(int qty) {
DataSet set = new DataSet();
int size = size();
if (qty < 0) {
qty = 0;
}
if (qty > size) {
qty = size;
}
for (int i = 0; i < qty; i++) {
while (true) {
int idx = BasicUtil.getRandomNumber(0, size - 1);
DataRow row = set.getRow(idx);
if (!set.contains(row)) {
set.add(row);
break;
}
}
}
set.cloneProperty(this);
return set;
}
/**
* ognl DataRow.key
* @param key key
* @param formula ognl
* @param values
* @param strategy 0: 1:
* @param exception
* @return DataSet
*/
public DataSet ognl(String key, String formula, Object values, int strategy, boolean exception) throws Exception{
if(strategy == 0){
for(DataRow row:rows){
try {
row.ognl(key, formula, values);
}catch (Exception e){
if(exception){
throw e;
}
}
}
}else{
List<Object> results = new ArrayList<>();
for(DataRow row:rows){
try {
results.add(row.ognl(formula, values));
}catch (Exception e){
results.add(null);
if(exception){
throw e;
}
}
}
int size = results.size();
for(int i=0; i<size; i++){
Object result = results.get(i);
if(null != result){
rows.get(i).put(key,result);
}
}
}
return this;
}
public DataSet ognl(String key, String formula, int strategy, boolean exception) throws Exception{
return ognl(key, formula, null, strategy, exception);
}
public DataSet ognl(String key, String formula) throws Exception{
return ognl(key, formula, null, 0, false);
}
/**
* minmax
* @param min min
* @param max max
* @return DataSet
*/
public DataSet randoms(int min, int max) {
int qty = BasicUtil.getRandomNumber(min, max);
return randoms(qty);
}
public DataSet unique(String... keys) {
return distinct(keys);
}
/**
*
* @param key key
* @param regex
* @param mode
* @return DataSet
*/
public DataSet regex(String key, String regex, Regular.MATCH_MODE mode) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : this) {
tmpValue = row.getString(key);
if (RegularUtil.match(tmpValue, regex, mode)) {
set.add(row);
}
}
set.cloneProperty(this);
return set;
}
public DataSet regex(String key, String regex) {
return regex(key, regex, Regular.MATCH_MODE.MATCH);
}
public boolean checkRequired(String... keys) {
for (DataRow row : rows) {
if (!row.checkRequired(keys)) {
return false;
}
}
return true;
}
public Map<String, Object> getQueryParams() {
return queryParams;
}
public DataSet setQueryParams(Map<String, Object> params) {
this.queryParams = params;
return this;
}
public Object getQueryParam(String key) {
return queryParams.get(key);
}
public DataSet addQueryParam(String key, Object param) {
queryParams.put(key, param);
return this;
}
public String getDatalink() {
return datalink;
}
public void setDatalink(String datalink) {
this.datalink = datalink;
}
public class Select implements Serializable {
private static final long serialVersionUID = 1L;
private boolean ignoreCase = true;
/**
* NULL true equal notEqual like contains nullnullfalse
* NULLfalse
* true equal notEqual
*/
private boolean ignoreNull = true;
public DataSet setIgnoreCase(boolean bol) {
this.ignoreCase = bol;
return DataSet.this;
}
public DataSet setIgnoreNull(boolean bol) {
this.ignoreNull = bol;
return DataSet.this;
}
/**
* key=value
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet equals(String key, String value) {
return equals(DataSet.this, key, value);
}
private DataSet equals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = tmpValue.equalsIgnoreCase(value);
} else {
chk = tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* key = value
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet notEquals(String key, String value) {
return notEquals(DataSet.this, key, value);
}
private DataSet notEquals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = !tmpValue.equalsIgnoreCase(value);
} else {
chk = !tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* keyvalue
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet contains(String key, String value) {
return contains(DataSet.this, key, value);
}
private DataSet contains(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == value) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
value = value.toLowerCase();
}
if (tmpValue.contains(value)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* keylike pattern,patternsql,%,_
*
* @param key
* @param pattern
* @return DataSet
*/
public DataSet like(String key, String pattern) {
return like(DataSet.this, key, pattern);
}
private DataSet like(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null != pattern) {
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
}
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet notLike(String key, String pattern) {
return notLike(DataSet.this, key, pattern);
}
private DataSet notLike(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null == pattern) {
return set;
}
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (!RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet startWith(String key, String prefix) {
return startWith(DataSet.this, key, prefix);
}
private DataSet startWith(DataSet src, String key, String prefix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == prefix) {
continue;
}
} else {
if (null == tmpValue && null == prefix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == prefix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
prefix = prefix.toLowerCase();
}
if (tmpValue.startsWith(prefix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet endWith(String key, String suffix) {
return endWith(DataSet.this, key, suffix);
}
private DataSet endWith(DataSet src, String key, String suffix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == suffix) {
continue;
}
} else {
if (null == tmpValue && null == suffix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == suffix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
suffix = suffix.toLowerCase();
}
if (tmpValue.endsWith(suffix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet in(String key, T... values) {
return in(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet in(String key, Collection<T> values) {
return in(DataSet.this, key, values);
}
private <T> DataSet in(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
for (DataRow row : src) {
if (BasicUtil.containsString(ignoreNull, ignoreCase, values, row.getString(key))) {
set.add(row);
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet notIn(String key, T... values) {
return notIn(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet notIn(String key, Collection<T> values) {
return notIn(DataSet.this, key, values);
}
private <T> DataSet notIn(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
if (null != values) {
String tmpValue = null;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull && null == tmpValue) {
continue;
}
if (!BasicUtil.containsString(ignoreNull, ignoreCase, values, tmpValue)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet isNull(String... keys) {
return isNull(DataSet.this, keys);
}
private DataSet isNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNull(set, key);
}
}
return set;
}
private DataSet isNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null == row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet isNotNull(String... keys) {
return isNotNull(DataSet.this, keys);
}
private DataSet isNotNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNotNull(set, key);
}
}
return set;
}
private DataSet isNotNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null != row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet notNull(String... keys) {
return isNotNull(keys);
}
/**
*
* @param keys keys
* @return DataSet
*/
public DataSet empty(String... keys) {
return empty(DataSet.this, keys);
}
private DataSet empty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = empty(set, key);
}
}
return set;
}
private DataSet empty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isEmpty(key)){
set.add(row);
}
}
return set;
}
public DataSet notEmpty(String... keys) {
return notEmpty(DataSet.this, keys);
}
private DataSet notEmpty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = notEmpty(set, key);
}
}
return set;
}
private DataSet notEmpty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isNotEmpty(key)){
set.add(row);
}
}
return set;
}
public <T> DataSet less(String key, T value) {
return less(DataSet.this, key, value);
}
private <T> DataSet less(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) < 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) < 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) < 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet lessEqual(String key, T value) {
return lessEqual(DataSet.this, key, value);
}
private <T> DataSet lessEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) <= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) <= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greater(String key, T value) {
return greater(DataSet.this, key, value);
}
private <T> DataSet greater(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) > 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) > 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) > 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greaterEqual(String key, T value) {
return greaterEqual(DataSet.this, key, value);
}
private <T> DataSet greaterEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) >= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) >= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet between(String key, T min, T max) {
return between(DataSet.this, key, min, max);
}
private <T> DataSet between(DataSet src, String key, T min, T max) {
DataSet set = greaterEqual(src, key, min);
set = lessEqual(set, key, max);
return set;
}
}
public Select select = new Select();
} |
package com.creatubbles.api.model.user;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.creatubbles.api.model.school.School;
import com.creatubbles.api.model.user.custom_style.CustomStyle;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.jasminb.jsonapi.annotations.Id;
import com.github.jasminb.jsonapi.annotations.Relationship;
import com.github.jasminb.jsonapi.annotations.Type;
import com.github.jasminb.jsonapi.models.EmptyRelationship;
import java.util.Date;
@Type("users")
public class User extends EmptyRelationship {
@Id
private String id;
private String username;
@JsonProperty("display_name")
private String displayName;
@JsonProperty("list_name")
private String listName;
private String name;
private Role role;
@JsonProperty("created_at")
private Date createdAt;
@JsonProperty("updated_at")
private Date updatedAt;
@JsonProperty("avatar_url")
private String avatarUrl;
private String age;
@JsonProperty("last_bubbled_at")
private Date lastBubbledAt;
@JsonProperty("last_commented_at")
private Date lastCommentedAt;
@JsonProperty("added_bubbles_count")
private Integer addedBubblesCount;
@JsonProperty("activities_count")
private Integer activitiesCount;
@JsonProperty("bubbles_count")
private Integer bubblesCount;
@JsonProperty("comments_count")
private Integer commentsCount;
@JsonProperty("creations_count")
private Integer creationsCount;
@JsonProperty("creators_count")
private Integer creatorsCount;
@JsonProperty("galleries_count")
private Integer galleriesCount;
@JsonProperty("managers_count")
private Integer managersCount;
@JsonProperty("short_url")
private String shortUrl;
@JsonProperty("country_code")
private String countryCode;
@JsonProperty("country_name")
private String countryName;
@JsonProperty("signed_up_as_instructor")
private boolean signedUpAsInstructor;
@JsonProperty("home_schooling")
private boolean homeSchooling;
@JsonProperty("what_do_you_teach")
private String whatDoYouTeach;
private String interests;
@Relationship("custom_style")
private CustomStyle customStyle;
@Relationship("school")
private School school;
@JsonProperty("followed_users_count")
private Integer followedUsersCount;
@JsonProperty("followers_count")
private Integer followersCount;
@JsonProperty("followed_hashtags_count")
private Integer followedHashtagsCount;
@JsonProperty("bubbles_on_creations_count")
private Integer bubblesOnCreationsCount = 0;
public static User withId(String id) {
return new User(id);
}
@JsonCreator
public User() {
}
private User(String id) {
this.id = id;
}
@NonNull
public String getId() {
return id;
}
@NonNull
public String getUsername() {
return username;
}
@NonNull
public String getDisplayName() {
return displayName;
}
@NonNull
public String getName() {
return name;
}
@NonNull
public Role getRole() {
return role;
}
@NonNull
public Date getCreatedAt() {
return createdAt;
}
@NonNull
public Date getUpdatedAt() {
return updatedAt;
}
@Nullable
public String getAvatarUrl() {
return avatarUrl;
}
@Nullable
public String getAge() {
return age;
}
@Nullable
public Date getLastBubbledAt() {
return lastBubbledAt;
}
@Nullable
public Date getLastCommentedAt() {
return lastCommentedAt;
}
@NonNull
public Integer getAddedBubblesCount() {
return addedBubblesCount;
}
/**
* @return number of activities on this user.
*/
@NonNull
public Integer getActivitiesCount() {
return activitiesCount;
}
/**
* @return number of bubbles this user received
*/
@NonNull
public Integer getBubblesCount() {
return bubblesCount;
}
/**
* @return number of comments this user received
*/
@NonNull
public Integer getCommentsCount() {
return commentsCount;
}
/**
* @return number of creations the user created
*/
@NonNull
public Integer getCreationsCount() {
return creationsCount;
}
/**
* @return number of creators
*/
@NonNull
public Integer getCreatorsCount() {
return creatorsCount;
}
/**
* @return number of galleries the user created
*/
@NonNull
public Integer getGalleriesCount() {
return galleriesCount;
}
/**
* @return number of managers for this user
*/
@NonNull
public Integer getManagersCount() {
return managersCount;
}
@NonNull
public String getShortUrl() {
return shortUrl;
}
@Nullable
public String getCountryCode() {
return countryCode;
}
@Nullable
public String getCountryName() {
return countryName;
}
public boolean getSignedUpAsInstructor() {
return signedUpAsInstructor;
}
public boolean getHomeSchooling() {
return homeSchooling;
}
@NonNull
public String getListName() {
return listName;
}
/**
* Method returns value set in user's profile in "What do you teach?" (Teachers only).
*
* @return value set in "What do you teach?" field
*/
@Nullable
public String getWhatDoYouTeach() {
return whatDoYouTeach;
}
/**
* Method returns value set in user's profile in "Interests" (Teachers only).
*
* @return value set in "Interests" field
*/
@Nullable
public String getInterests() {
return interests;
}
@Nullable
public School getSchool() {
return school;
}
@Nullable
public CustomStyle getCustomStyle() {
return customStyle;
}
public Integer getFollowedUsersCount() {
return followedUsersCount;
}
public Integer getFollowersCount() {
return followersCount;
}
public Integer getFollowedHashtagsCount() {
return followedHashtagsCount;
}
public Integer getBubblesOnCreationsCount() {
return bubblesOnCreationsCount;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", displayName='" + displayName + '\'' +
", listName='" + listName + '\'' +
", name='" + name + '\'' +
", role=" + role +
", createdAt=" + createdAt +
", updatedAt=" + updatedAt +
", avatarUrl='" + avatarUrl + '\'' +
", age='" + age + '\'' +
", lastBubbledAt=" + lastBubbledAt +
", lastCommentedAt=" + lastCommentedAt +
", addedBubblesCount=" + addedBubblesCount +
", activitiesCount=" + activitiesCount +
", bubblesCount=" + bubblesCount +
", commentsCount=" + commentsCount +
", creationsCount=" + creationsCount +
", creatorsCount=" + creatorsCount +
", galleriesCount=" + galleriesCount +
", managersCount=" + managersCount +
", shortUrl='" + shortUrl + '\'' +
", countryCode='" + countryCode + '\'' +
", countryName='" + countryName + '\'' +
", signedUpAsInstructor=" + signedUpAsInstructor +
", homeSchooling=" + homeSchooling +
", whatDoYouTeach='" + whatDoYouTeach + '\'' +
", interests='" + interests + '\'' +
", customStyle=" + customStyle +
", school=" + school +
", followedUsersCount=" + followedUsersCount +
", followersCount=" + followersCount +
", followedHashtagsCount=" + followedHashtagsCount +
", bubblesOnCreationsCount=" + bubblesOnCreationsCount +
'}';
}
} |
package org.spine3.type;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.collect.BiMap;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Any;
import com.google.protobuf.Api;
import com.google.protobuf.BoolValue;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.Duration;
import com.google.protobuf.Empty;
import com.google.protobuf.EnumValue;
import com.google.protobuf.Field;
import com.google.protobuf.FieldMask;
import com.google.protobuf.FloatValue;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.ListValue;
import com.google.protobuf.Method;
import com.google.protobuf.Mixin;
import com.google.protobuf.NullValue;
import com.google.protobuf.Option;
import com.google.protobuf.SourceContext;
import com.google.protobuf.StringValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Syntax;
import com.google.protobuf.Timestamp;
import com.google.protobuf.Type;
import com.google.protobuf.UInt32Value;
import com.google.protobuf.UInt64Value;
import com.google.protobuf.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spine3.Internal;
import org.spine3.type.error.UnknownTypeException;
import javax.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Maps.newHashMap;
import static org.spine3.io.IoUtil.loadAllProperties;
import static org.spine3.util.Exceptions.newIllegalArgumentException;
import static org.spine3.util.Exceptions.newIllegalStateException;
/**
* A map which contains all Protobuf types known to the application.
*
* @author Mikhail Mikhaylov
* @author Alexander Yevsyukov
* @author Alexander Litus
*/
@Internal
public class KnownTypes {
/**
* File, containing Protobuf messages' typeUrls and their appropriate class names.
*
* <p>Is generated by Gradle during build process.
*/
private static final String PROPS_FILE_PATH = "known_types.properties";
@SuppressWarnings("DuplicateStringLiteralInspection")
private static final String DESCRIPTOR_GETTER_NAME = "getDescriptor";
private static final char PACKAGE_SEPARATOR = '.';
/**
* A map from Protobuf type URL to Java class name.
*
* <p>For example, for a key {@code type.spine3.org/spine.base.EventId},
* there will be the value {@code org.spine3.base.EventId}.
*/
private static final BiMap<TypeUrl, ClassName> knownTypes = Builder.build();
/**
* A map from Protobuf type name to type URL.
*
* <p>For example, for a key {@code spine.base.EventId},
* there will be the value {@code type.spine3.org/spine.base.EventId}.
*
* @see TypeUrl
*/
private static final ImmutableMap<String, TypeUrl> typeUrls = buildTypeToUrlMap(knownTypes);
private KnownTypes() {
}
/**
* Retrieves Protobuf type URLs known to the application.
*/
public static ImmutableSet<TypeUrl> getTypeUrls() {
final Set<TypeUrl> result = knownTypes.keySet();
return ImmutableSet.copyOf(result);
}
/** Retrieves names of Java classes generated for Protobuf types known to the application. */
@VisibleForTesting
public static ImmutableSet<ClassName> getJavaClasses() {
final Set<ClassName> result = knownTypes.values();
return ImmutableSet.copyOf(result);
}
/**
* Retrieves a Java class name generated for the Protobuf type by its type url
* to be used to parse {@link com.google.protobuf.Message Message} from {@link Any}.
*
* @param typeUrl {@link Any} type url
* @return Java class name
* @throws UnknownTypeException if there is no such type known to the application
*/
public static ClassName getClassName(TypeUrl typeUrl) throws UnknownTypeException {
if (!knownTypes.containsKey(typeUrl)) {
throw new UnknownTypeException(typeUrl.getTypeName());
}
final ClassName result = knownTypes.get(typeUrl);
return result;
}
public static TypeUrl getTypeUrl(ClassName className) {
final TypeUrl result = knownTypes.inverse()
.get(className);
if (result == null) {
throw newIllegalStateException("No Protobuf type URL found for the Java class %s",
className);
}
return result;
}
/** Returns a Protobuf type URL by Protobuf type name. */
@Nullable
public static TypeUrl getTypeUrl(String typeName) {
final TypeUrl typeUrl = typeUrls.get(typeName);
return typeUrl;
}
/**
* Retrieves all the types that belong to the given package or it's subpackages.
*
* @param packageName protobuf-style package
* @return set of {@link TypeUrl TypeUrls} for types that belong to the given package
*/
public static Set<TypeUrl> getTypesFromPackage(final String packageName) {
final Collection<TypeUrl> knownTypeUrls = knownTypes.keySet();
final Collection<TypeUrl> resultCollection = Collections2.filter(
knownTypeUrls, new Predicate<TypeUrl>() {
@Override
public boolean apply(@Nullable TypeUrl input) {
if (input == null) {
return false;
}
final String typeName = input.getTypeName();
final boolean inPackage = typeName.startsWith(packageName)
&& typeName.charAt(packageName.length()) == PACKAGE_SEPARATOR;
return inPackage;
}
});
final Set<TypeUrl> resultSet = ImmutableSet.copyOf(resultCollection);
return resultSet;
}
public static Descriptors.Descriptor getDescriptorForType(String typeName) {
final TypeUrl typeUrl = getTypeUrl(typeName);
checkArgument(typeUrl != null, "Given type name is invalid");
final ClassName className = getClassName(typeUrl);
final Class<?> cls;
try {
cls = Class.forName(className.value());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
final Descriptors.Descriptor descriptor;
try {
final java.lang.reflect.Method descriptorGetter =
cls.getDeclaredMethod(DESCRIPTOR_GETTER_NAME);
descriptor = (Descriptors.Descriptor) descriptorGetter.invoke(null);
} catch (NoSuchMethodException
| IllegalAccessException
| InvocationTargetException e) {
throw newIllegalArgumentException(e, "Type %s is not a protobuf Message", typeName);
}
return descriptor;
}
private static ImmutableMap<String, TypeUrl> buildTypeToUrlMap(BiMap<TypeUrl,
ClassName> knownTypes) {
final ImmutableMap.Builder<String, TypeUrl> builder = ImmutableMap.builder();
for (TypeUrl typeUrl : knownTypes.keySet()) {
builder.put(typeUrl.getTypeName(), typeUrl);
}
return builder.build();
}
/** The helper class for building internal immutable typeUrl-to-JavaClass map. */
private static class Builder {
private final Map<TypeUrl, ClassName> resultMap = newHashMap();
private static ImmutableBiMap<TypeUrl, ClassName> build() {
final Builder builder = new Builder()
.addStandardProtobufTypes()
.loadNamesFromProperties();
final ImmutableBiMap<TypeUrl, ClassName> result =
ImmutableBiMap.copyOf(builder.resultMap);
return result;
}
private Builder loadNamesFromProperties() {
final Set<Properties> propertiesSet = loadAllProperties(PROPS_FILE_PATH);
for (Properties properties : propertiesSet) {
putProperties(properties);
}
return this;
}
private void putProperties(Properties properties) {
final Set<String> typeUrls = properties.stringPropertyNames();
for (String typeUrlStr : typeUrls) {
final TypeUrl typeUrl = TypeUrl.of(typeUrlStr);
final ClassName className = ClassName.of(properties.getProperty(typeUrlStr));
put(typeUrl, className);
}
}
/**
* Returns classes from the {@code com.google.protobuf} package that need to be present
* in the result map.
*
* <p>This method needs to be updated with introduction of new Google Protobuf types
* after they are used in the framework.
*/
@SuppressWarnings("OverlyLongMethod")
// OK as there are many types in Protobuf and we want to keep this code in one place.
private Builder addStandardProtobufTypes() {
// Types from `any.proto`.
put(Any.class);
// Types from `api.proto`
put(Api.class);
put(Method.class);
put(Mixin.class);
// Types from `descriptor.proto`
put(DescriptorProtos.FileDescriptorSet.class);
put(DescriptorProtos.FileDescriptorProto.class);
put(DescriptorProtos.DescriptorProto.class);
// Inner types of `DescriptorProto`
put(DescriptorProtos.DescriptorProto.ExtensionRange.class);
put(DescriptorProtos.DescriptorProto.ReservedRange.class);
put(DescriptorProtos.FieldDescriptorProto.class);
putEnum(DescriptorProtos.FieldDescriptorProto.Type.getDescriptor(),
DescriptorProtos.FieldDescriptorProto.Type.class);
putEnum(DescriptorProtos.FieldDescriptorProto.Label.getDescriptor(),
DescriptorProtos.FieldDescriptorProto.Label.class);
put(DescriptorProtos.OneofDescriptorProto.class);
put(DescriptorProtos.EnumDescriptorProto.class);
put(DescriptorProtos.EnumValueDescriptorProto.class);
put(DescriptorProtos.ServiceDescriptorProto.class);
put(DescriptorProtos.MethodDescriptorProto.class);
put(DescriptorProtos.FileOptions.class);
putEnum(DescriptorProtos.FileOptions.OptimizeMode.getDescriptor(),
DescriptorProtos.FileOptions.OptimizeMode.class);
put(DescriptorProtos.MessageOptions.class);
put(DescriptorProtos.FieldOptions.class);
putEnum(DescriptorProtos.FieldOptions.CType.getDescriptor(),
DescriptorProtos.FieldOptions.CType.class);
putEnum(DescriptorProtos.FieldOptions.JSType.getDescriptor(),
DescriptorProtos.FieldOptions.JSType.class);
put(DescriptorProtos.EnumOptions.class);
put(DescriptorProtos.EnumValueOptions.class);
put(DescriptorProtos.ServiceOptions.class);
put(DescriptorProtos.MethodOptions.class);
put(DescriptorProtos.UninterpretedOption.class);
put(DescriptorProtos.SourceCodeInfo.class);
// Inner types of `SourceCodeInfo`.
put(DescriptorProtos.SourceCodeInfo.Location.class);
put(DescriptorProtos.GeneratedCodeInfo.class);
// Inner types of `GeneratedCodeInfo`.
put(DescriptorProtos.GeneratedCodeInfo.Annotation.class);
// Types from `duration.proto`.
put(Duration.class);
// Types from `empty.proto`.
put(Empty.class);
// Types from `field_mask.proto`.
put(FieldMask.class);
// Types from `source_context.proto`.
put(SourceContext.class);
// Types from `struct.proto`.
put(Struct.class);
put(Value.class);
putEnum(NullValue.getDescriptor(), NullValue.class);
put(ListValue.class);
// Types from `timestamp.proto`.
put(Timestamp.class);
// Types from `type.proto`.
put(Type.class);
put(Field.class);
putEnum(Field.Kind.getDescriptor(), Field.Kind.class);
putEnum(Field.Cardinality.getDescriptor(), Field.Cardinality.class);
put(com.google.protobuf.Enum.class);
put(EnumValue.class);
put(Option.class);
putEnum(Syntax.getDescriptor(), Syntax.class);
// Types from `wrappers.proto`.
put(DoubleValue.class);
put(FloatValue.class);
put(Int64Value.class);
put(UInt64Value.class);
put(Int32Value.class);
put(UInt32Value.class);
put(BoolValue.class);
put(StringValue.class);
put(BytesValue.class);
return this;
}
private void put(Class<? extends GeneratedMessageV3> clazz) {
final TypeUrl typeUrl = TypeUrl.of(clazz);
final ClassName className = ClassName.of(clazz);
put(typeUrl, className);
}
private void putEnum(EnumDescriptor desc, Class<? extends EnumLite> enumClass) {
final TypeUrl typeUrl = TypeUrl.from(desc);
final ClassName className = ClassName.of(enumClass);
put(typeUrl, className);
}
private void put(TypeUrl typeUrl, ClassName className) {
if (resultMap.containsKey(typeUrl)) {
log().warn("Duplicate key in the {} map: {}. " +
"It may be caused by the " +
"`task.descriptorSetOptions.includeImports` option " +
"set to `true` in the `build.gradle`.", KnownTypes.class.getName(),
typeUrl);
return;
}
resultMap.put(typeUrl, className);
}
private static Logger log() {
return LogSingleton.INSTANCE.value;
}
private enum LogSingleton {
INSTANCE;
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private final Logger value = LoggerFactory.getLogger(KnownTypes.class);
}
}
} |
package org.jetel.graph;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import junit.framework.TestCase;
import junit.framework.TestResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.graph.runtime.IThreadManager;
import org.jetel.graph.runtime.SimpleThreadManager;
import org.jetel.graph.runtime.WatchDog;
import org.jetel.util.file.FileUtils;
public class ResetTest extends TestCase{
private final static String[] EXAMPLE_PATH = {
"../cloveretl.examples/SimpleExamples/",
"../cloveretl.examples/AdvancedExamples/",
"../cloveretl.examples/CTL1FunctionsTutorial/",
"../cloveretl.examples/CTL2FunctionsTutorial/",
"../cloveretl.examples/DataProfiling/",
"../cloveretl.examples/ExtExamples/",
"../cloveretl.test.scenarios/",
"../cloveretl.examples.commercial/",
"../cloveretl.examples/CompanyTransactionsTutorial/"
};
static Log logger = LogFactory.getLog(ResetTest.class);
private GraphRuntimeContext runtimeContext;
private final static String GRAPHS_DIR = "graph";
private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"};
private final static String LOG_FILE_NAME = "reset.log";
private FileWriter log_file = null;
/**
* We suppose that this test is running from cloveretl.engine directory.
* If not, this variable has to be change to point to the cloveretl.engine directory.
*/
private final static File current_directory = new File(".");
private final static String SCENARIOS_RELATIVE_PATH = "/../cloveretl.test.scenarios";
private Map<String, Exception> errors = new HashMap<String, Exception>();
@Override
protected void setUp() throws Exception {
super.setUp();
try {
log_file = new FileWriter(LOG_FILE_NAME);
} catch (Exception e) {
System.err.println("Log file cannot be created:");
e.printStackTrace();
}
EngineInitializer.initEngine( "..", null, null);
runtimeContext = new GraphRuntimeContext();
runtimeContext.addAdditionalProperty("PROJECT", ".");
runtimeContext.addAdditionalProperty("CONN_DIR", current_directory.getAbsolutePath() + SCENARIOS_RELATIVE_PATH + "/conn");
runtimeContext.setUseJMX(false);
errors.clear();
}
public void testAllExamples() throws MalformedURLException{
for (int i = 0; i < EXAMPLE_PATH.length; i++) {
File[] graphFile = (new File(EXAMPLE_PATH[i] + GRAPHS_DIR)).listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".grf")
&& !pathname.getName().startsWith("TPCH")// ok, performance tests - last very long
&& !pathname.getName().contains("Performance")// ok, performance tests - last very long
&& !pathname.getName().equals("graphJoinData.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("conversionNum2num.grf") // ok, should fail
&& !pathname.getName().equals("outPortWriting.grf") // ok, should fail
&& !pathname.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client
&& !pathname.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client
&& !pathname.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client
&& !pathname.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client
&& !pathname.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client
&& !pathname.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server
&& !pathname.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server
&& !pathname.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows
&& !pathname.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server
&& !pathname.getName().equals("graphSequenceChecker.grf") // ok, is to fail
&& !pathname.getName().equals("FixedData.grf") // ok, is to fail
&& !pathname.getName().equals("xpathReaderStates.grf") // ok, is to fail
&& !pathname.getName().equals("graphDataPolicy.grf"); // ok, is to fail
//TODO these graphs should work in the future:
// && !pathname.getName().startsWith("graphLdap") //LDAP server is not configured properly yet
// && !pathname.getName().equals("mountainsSybase.grf") //issue 2939
// && !pathname.getName().equals("graphJms.grf") //issue 3250
// && !pathname.getName().equals("graphGenerateData.grf") //issue 3220
// && !pathname.getName().equals("graphJavaExecute.grf") //issue 3220
// && !pathname.getName().equals("dateToday.grf") //issue 3220
// && !pathname.getName().equals("mathRandom.grf") //issue 3220
// && !pathname.getName().equals("mathRandom_boolean.grf") //issue 3220
// && !pathname.getName().equals("mathRandom_gaussian.grf") //issue 3220
// && !pathname.getName().equals("mathRandom_intWithRange.grf") //issue 3220
// && !pathname.getName().equals("mathRandom_intWithoutRange.grf") //issue 3220
// && !pathname.getName().equals("mathRandom_longWithoutRange.grf") //issue 3220
// && !pathname.getName().equals("graphCheckForeignKey.grf") //issue 3220
// && !pathname.getName().equals("graphDBExecuteMySql.grf") //issue 3220
// && !pathname.getName().equals("graphDBExecuteMsSql.grf") //issue 3220
// && !pathname.getName().equals("graphDBExecuteOracle.grf") //issue 3220
// && !pathname.getName().equals("graphDBExecutePostgre.grf") //issue 3220
// && !pathname.getName().equals("graphDBUnload.grf") //issue 3220
// && !pathname.getName().equals("graphDBUnload2.grf") //issue 3220
// && !pathname.getName().equals("graphDBLoad5.grf") //issue 3220
// && !pathname.getName().equals("graphDBUnloadUniversal.grf") //issue 3220
// && !pathname.getName().equals("bufferedEdge1.grf") //issue 3220
// && !pathname.getName().equals("bufferedEdge2.grf") //issue 3220
// && !pathname.getName().equals("incrementalReadingDB.grf") //issue 3220
// && !pathname.getName().equals("informix.grf") //issue 3220
// && !pathname.getName().equals("parallelReaderFunctionalTest.grf") //issue 3220
// && !pathname.getName().equals("sort.grf") //issue 3220
// && !pathname.getName().equals("transformations.grf") //issue 3220
// && !pathname.getName().equals("mountainsPgsql.grf") //issue 3220
// && !pathname.getName().equals("A12_XMLExtractTransactionsFamily.grf") //issue 3220
// && !pathname.getName().equals("graphXMLExtract.grf") //issue 3220
// && !pathname.getName().equals("graphXMLExtractXsd.grf") //issue 3220
// && !pathname.getName().equals("mountainsInformix.grf") //issue 2550
// && !pathname.getName().equals("graphRunGraph.grf")
// && !pathname.getName().equals("DBJoin.grf");//issue 3285
}
});
log("Testing graphs in " + EXAMPLE_PATH[i]);
Arrays.sort(graphFile);
runtimeContext.setContextURL(FileUtils.getFileURL(EXAMPLE_PATH[i]));
// absolute path in PROJECT parameter is required for graphs using Derby database
runtimeContext.addAdditionalProperty("PROJECT", new File(EXAMPLE_PATH[i]).getAbsolutePath());
for (int j = 0; j < graphFile.length; j++) {
if (!graphFile[j].getName().contains("Jms")) {//set LIB_DIR to jdbc drivers directory
runtimeContext.addAdditionalProperty("LIB_DIR", current_directory.getAbsolutePath() + SCENARIOS_RELATIVE_PATH + "/lib");
}
try {
testExample(graphFile[j]);
// } catch (AssertionFailedError e) {
// fail(graphFile[j] + ": " + e.getMessage());
} catch (Exception e) {
// if (e.getMessage() == null){
// e.printStackTrace();
// fail(graphFile[j] + ": " + e.getMessage());
errors.put(graphFile[j].getName(), e);
}
}
}
if (!errors.isEmpty()) {
for (Entry<String, Exception> error : errors.entrySet()) {
System.err.println(error.getKey() + ": ");
error.getValue().printStackTrace();
}
}
}
@Override
public void run(TestResult result) {
super.run(result);
if (!errors.isEmpty()) {
Exception e;
for (Entry<String, Exception> error : errors.entrySet()) {
e = new RuntimeException(error.getKey() + " failed.", error.getValue());
result.addError(this, e);
}
}
}
public void testExample(File file) throws Exception {
TransformationGraph graph = null;
Future<Result> futureResult = null;
log("Analyzing graph " + file.getName());
try {
graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(file), runtimeContext);
graph.setDebugMode(false);
} catch (Exception e) {
log("Error in graph loading: " + e.getMessage());
errors.put(file.getName(), e);
return;
}
try {
EngineInitializer.initGraph(graph);
} catch (ComponentNotReadyException e) {
log("Error in graph initialization: " + e.getMessage());
errors.put(file.getName(), e);
return;
}
for(int i = 0; i < 3; i++) {
try {
IThreadManager threadManager = new SimpleThreadManager();
WatchDog watchDog = new WatchDog(graph, runtimeContext);
futureResult = threadManager.executeWatchDog(watchDog);
} catch (Exception e) {
log("Error in graph execution: " + e.getMessage());
errors.put(file.getName(), e);
return;
}
Result result = Result.N_A;
try {
result = futureResult.get();
} catch (Exception e) {
log("Error during graph processing: " + e.getMessage());
errors.put(file.getName(), e);
return;
}
switch (result) {
case FINISHED_OK:
// everything O.K.
log("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
log("Execution of graph aborted !");
System.exit(result.code());
break;
default:
log("Execution of graph failed !");
// fail();
errors.put(file.getName(), new RuntimeException("Execution of graph failed !"));
return;
}
}
log("Transformation graph is freeing.\n");
graph.free();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
log_file.close();
for (int j = 0; j < EXAMPLE_PATH.length; j++) {
for (String outDir : OUT_DIRS) {
File outDirFile = new File(EXAMPLE_PATH[j] + outDir);
File[] file = outDirFile.listFiles();
for (int i = 0; i < file.length; i++) {
file[i].delete();
}
}
}
}
/**
* 1. param should be plugins location
* 2. param should be graph file location
* 3. param (optional) should be project directory, if not exist simpleExamples project is used
* @param args
* @throws MalformedURLException
* @throws IOException
*/
public static void main(String[] args) throws Exception {
EngineInitializer.initEngine(args[0], null, null);
GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
runtimeContext.setContextURL(FileUtils.getFileURL(
args.length > 2 ? args[2] : "../cloveretl.examples/SimpleExamples/"));
runtimeContext.setUseJMX(false);
TransformationGraph graph = null;
try {
graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream((args.length > 2 ? args[2] + "/" : "") + args[1]), runtimeContext);
} catch (Exception e) {
logger.error("Error in graph loading !", e);
System.exit(-1);
}
try {
EngineInitializer.initGraph(graph);
} catch (ComponentNotReadyException e) {
logger.error("Error in graph initialization !", e);
System.exit(-1);
}
for(int i = 0; i < 5; i++) {
Future<Result> futureResult = null;
try {
IThreadManager threadManager = new SimpleThreadManager();
WatchDog watchDog = new WatchDog(graph, runtimeContext);
futureResult = threadManager.executeWatchDog(watchDog);
} catch (Exception e) {
logger.error("Error in graph execution !", e);
System.exit(-1);
}
Result result = Result.N_A;
try {
result = futureResult.get();
} catch (Exception e) {
logger.error("Error during graph processing !", e);
System.exit(-1);
}
switch (result) {
case FINISHED_OK:
// everything O.K.
System.out.println("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
System.err.println("Execution of graph aborted !");
System.exit(result.code());
break;
default:
System.err.println("Execution of graph failed !");
System.exit(result.code());
}
// if (i < 4) {
// try {
// graph.reset();
// } catch (ComponentNotReadyException e) {
// System.err.println("Graph reseting failed !");
// e.printStackTrace();
// System.exit(-1);
}
System.out.println("Transformation graph is freeing.");
graph.free();
System.out.println("Graph executor is terminating.");
}
private void log(String message){
System.out.println(message);
if (log_file != null) {
try {
log_file.write(message);
log_file.flush();
} catch (IOException e) {
System.err.println("Can't write to log file");
e.printStackTrace();
}
}
}
} |
package org.jetel.graph;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Future;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.io.filefilter.AbstractFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.main.runGraph;
import org.jetel.test.CloverTestCase;
import org.jetel.util.file.FileUtils;
import org.jetel.util.string.StringUtils;
public class ResetTest extends CloverTestCase {
private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/";
private final static String[] EXAMPLE_PATH = {
"../cloveretl.examples/SimpleExamples/",
"../cloveretl.examples/AdvancedExamples/",
"../cloveretl.examples/CTL1FunctionsTutorial/",
"../cloveretl.examples/CTL2FunctionsTutorial/",
"../cloveretl.examples/DataProfiling/",
"../cloveretl.examples/DataSampling/",
"../cloveretl.examples/ExtExamples/",
"../cloveretl.examples/RealWorldExamples/",
"../cloveretl.examples.community/RealWorldExamples/",
"../cloveretl.examples/WebSiteExamples/",
"../cloveretl.examples.community/WebSiteExamples/",
"../cloveretl.test.scenarios/",
"../cloveretl.examples.commercial/CommercialExamples/",
"../cloveretl.examples.commercial/DataQualityExamples/",
"../cloveretl.examples/CompanyTransactionsTutorial/"
};
private final static String[] NEEDS_SCENARIOS_CONNECTION = {
"graphRevenues.grf",
"graphDBExecuteMsSql.grf",
"graphDBExecuteMySql.grf",
"graphDBExecuteOracle.grf",
"graphDBExecutePostgre.grf",
"graphDBExecuteSybase.grf",
"graphInfobrightDataWriterRemote.grf",
"graphLdapReaderWriter.grf"
};
private final static String[] NEEDS_SCENARIOS_LIB = {
"graphDBExecuteOracle.grf",
"graphDBExecuteSybase.grf",
"graphLdapReaderWriter.grf"
};
private final static String GRAPHS_DIR = "graph";
private final static String TRANS_DIR = "trans";
private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"};
private final String basePath;
private final File graphFile;
private final boolean batchMode;
private boolean cleanUp = true;
private static Log logger = LogFactory.getLog(ResetTest.class);
public static Test suite() {
final TestSuite suite = new TestSuite();
for (int i = 0; i < EXAMPLE_PATH.length; i++) {
logger.info("Testing graphs in " + EXAMPLE_PATH[i]);
final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR);
if(!graphsDir.exists()){
throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found");
}
IOFileFilter fileFilter = new AbstractFileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(".grf")
&& !file.getName().startsWith("TPCH")// ok, performance tests - last very long
&& !file.getName().contains("Performance")// ok, performance tests - last very long
&& !file.getName().equals("graphJoinData.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created
&& !file.getName().equals("conversionNum2num.grf") // ok, should fail
&& !file.getName().equals("outPortWriting.grf") // ok, should fail
&& !file.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client
&& !file.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client
&& !file.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client
&& !file.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client
&& !file.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client
&& !file.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server
&& !file.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server
&& !file.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows
&& !file.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server
&& !file.getName().equals("graphSequenceChecker.grf") // ok, is to fail
&& !file.getName().equals("FixedData.grf") // ok, is to fail
&& !file.getName().equals("xpathReaderStates.grf") // ok, is to fail
&& !file.getName().equals("graphDataPolicy.grf") // ok, is to fail
&& !file.getName().equals("conversionDecimal2integer.grf") // ok, is to fail
&& !file.getName().equals("conversionDecimal2long.grf") // ok, is to fail
&& !file.getName().equals("conversionDouble2integer.grf") // ok, is to fail
&& !file.getName().equals("conversionDouble2long.grf") // ok, is to fail
&& !file.getName().equals("conversionLong2integer.grf") // ok, is to fail
&& !file.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths
&& !file.getName().equals("mountainsInformix.grf") // see issue 2550
&& !file.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows
&& !file.getName().equals("XLSEncryptedFail.grf") // ok, is to fail
&& !file.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail
&& !file.getName().equals("XLSInvalidFile.grf") // ok, is to fail
&& !file.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail
&& !file.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardStrict.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail
&& !file.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts
&& !file.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts
&& !file.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail
&& !file.getName().equals("FailingGraph.grf") // ok, is to fail
&& !file.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts
&& !file.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail
&& !file.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail
&& !file.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail
&& !file.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines
&& !file.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved
&& !file.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate)
&& !file.getName().contains("firebird") // remove after CL-2170 solved
&& !file.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved
&& !file.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved
&& !file.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved
&& !file.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved
&& !file.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved
&& !file.getName().equals("manyRecords.grf") // remove after CL-1292 implemented
&& !file.getName().equals("packedDecimal.grf") // remove after CL-1811 solved
&& !file.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately
&& !file.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf
&& !file.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail
&& !file.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved
&& !file.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail
&& !file.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail
&& !file.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail
&& !file.getName().equals("LUTPersistent_wrong_metadata.grf") // ok, is to fail
&& !file.getName().equals("UDW_nonExistingDir_fail_CL-2478.grf") // ok, is to fail
&& !file.getName().equals("CTL_lookup_put_fail.grf") // ok, is to fail
&& !file.getName().equals("SystemExecute_printBatchFile.grf") // ok, is to fail
&& !file.getName().equals("JoinMergeIssue_FailWhenMasterUnsorted.grf") // ok, is to fail
&& !file.getName().equals("UDW_remoteZipPartitioning_fail_CL-2564.grf") // ok, is to fail
&& !file.getName().equals("checkConfigTest.grf") // ok, is to fail
&& !file.getName().equals("DebuggingGraph.grf") // ok, is to fail
&& !file.getName().equals("graphDebuggingGraph.grf") // ok, is to fail
&& !file.getName().equals("CLO-404-recordCountsInErrorMessage.grf") // ok, is to fail
&& !file.getName().matches("Locale_.*_default.grf") // server only
&& !file.getName().equals("CompanyChecks.grf") // an example that needs embedded derby
&& !file.getName().equals("DatabaseAccess.grf") // an example that needs embedded derby
&& !file.getName().equals("graphDatabaseAccess.grf") // an example that needs embedded derby
&& !file.getName().equals("XMLReader_no_output_port.grf") // ok, is to fail
&& !file.getName().startsWith("Proxy_") // allowed to run only on virt-cyan as proxy tests
&& !file.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server
&& !file.getName().equals("DenormalizerWithoutInputFile.grf") // probably subgraph not supposed to be executed separately
&& !file.getName().equals("SimpleSequence_longValue.grf") // needs the sequence to be reset on start
&& !file.getName().equals("BeanWriterReader_employees.grf") // remove after CL-2474 solved
&& !file.getName().equals("GraphParameters_secure.grf") // server test
&& !file.getName().equals("GraphParameters_secureOverriden.grf") // server test
&& !file.getName().equals("GraphParameters_secureOverriden_subGraph.grf") // subgraph of server test
&& !file.getName().equals("SSR_CloseOnError.grf") // subgraph of server test
&& !file.getName().equals("TypedProperties_CLO-1997.grf") // server test
&& !file.getName().equals("ParallelReader_HDFS.grf") // cluster test
&& !file.getName().equals("graphHTTPConnector.grf") // external service is unstable
&& !file.getName().equals("CLO-2214_pre_post_execute_race_condition.grf") // ok, is to fail
&& !file.getName().equals("EmptyGraph.grf") // ok, is to fail
&& !file.getName().equals("rpc-literal-service-test.grf") // remove after CLO-2396 solved
&& !file.getName().equals("informix.grf") // remove after CLO-2793 solved
&& !file.getName().equals("EmailReader_BadDataFormatException.grf"); // ok, is to fail
}
};
IOFileFilter dirFilter = new AbstractFileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() && file.getName().equals("hadoop");
}
};
@SuppressWarnings("unchecked")
Collection<File> filesCollection = org.apache.commons.io.FileUtils.listFiles(graphsDir, fileFilter, dirFilter);
File[] graphFiles = filesCollection.toArray(new File[0]);
Arrays.sort(graphFiles);
for(int j = 0; j < graphFiles.length; j++){
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false));
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false));
}
}
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
initEngine();
}
protected static String getTestName(String basePath, File graphFile, boolean batchMode) {
final StringBuilder ret = new StringBuilder();
final String n = graphFile.getName();
int lastDot = n.lastIndexOf('.');
if (lastDot == -1) {
ret.append(n);
} else {
ret.append(n.substring(0, lastDot));
}
if (batchMode) {
ret.append("-batch");
} else {
ret.append("-nobatch");
}
return ret.toString();
}
protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) {
super(getTestName(basePath, graphFile, batchMode));
this.basePath = basePath;
this.graphFile = graphFile;
this.batchMode = batchMode;
this.cleanUp = cleanup;
}
@Override
protected void runTest() throws Throwable {
final String baseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/');
logger.info("Project dir: " + baseAbsolutePath);
logger.info("Analyzing graph " + graphFile.getPath());
logger.info("Batch mode: " + batchMode);
final GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
runtimeContext.setUseJMX(false);
runtimeContext.setContextURL(FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath))); // context URL should be absolute
// absolute path in PROJECT parameter is required for graphs using Derby database
runtimeContext.addAdditionalProperty("PROJECT", baseAbsolutePath);
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) {
final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath();
runtimeContext.addAdditionalProperty("CONN_DIR", connDir);
logger.info("CONN_DIR set to " + connDir);
}
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory
final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath();
runtimeContext.addAdditionalProperty("LIB_DIR", libDir);
logger.info("LIB_DIR set to " + libDir);
}
// for scenarios graphs, add the TRANS dir to the classpath
if (basePath.contains("cloveretl.test.scenarios")) {
runtimeContext.setRuntimeClassPath(new URL[] {FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath) + TRANS_DIR + "/")});
runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath());
}
runtimeContext.setBatchMode(batchMode);
final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext);
try {
graph.setDebugMode(false);
EngineInitializer.initGraph(graph);
for (int i = 0; i < 3; i++) {
final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext);
Result result = Result.N_A;
result = futureResult.get();
switch (result) {
case FINISHED_OK:
// everything O.K.
logger.info("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
break;
default:
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
}
}
} catch (Throwable e) {
throw new IllegalStateException("Error executing grap " + graphFile, e);
} finally {
if (cleanUp) {
cleanupData();
}
logger.info("Transformation graph is freeing.\n");
graph.free();
}
}
private void cleanupData() {
for (String outDir : OUT_DIRS) {
File outDirFile = new File(basePath, outDir);
File[] file = outDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile();
}
});
for (int i = 0; i < file.length; i++) {
final boolean drt = file[i].delete();
if (drt) {
logger.info("Cleanup: deleted file " + file[i].getAbsolutePath());
} else {
logger.info("Cleanup: error delete file " + file[i].getAbsolutePath());
}
}
}
}
} |
package dr.evolution.tree;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dr.evolution.io.Importer;
import dr.evolution.io.NewickImporter;
import jebl.evolution.taxa.Taxon;
import jebl.evolution.graphs.Node;
import jebl.evolution.treemetrics.RootedTreeMetric;
import jebl.evolution.trees.RootedTree;
/**
* @author Sebastian Hoehna
* @version 1.0
*
*/
public class BranchScoreMetric implements RootedTreeMetric {
public BranchScoreMetric() {
taxonMap = null;
}
public BranchScoreMetric(List<Taxon> taxa) {
taxonMap = new HashMap<Taxon, Integer>();
for (int i = 0; i < taxa.size(); i++) {
taxonMap.put(taxa.get(i), i);
}
}
public double getMetric(RootedTree tree1, RootedTree tree2) {
if (!tree1.getTaxa().equals(tree2.getTaxa())) {
throw new IllegalArgumentException("Trees contain different taxa");
}
Map<Taxon, Integer> tm = taxonMap;
if (tm == null) {
List<Taxon> taxa = new ArrayList<Taxon>(tree1.getTaxa());
if (!tree2.getTaxa().equals(taxa))
tm = new HashMap<Taxon, Integer>();
for (int i = 0; i < taxa.size(); i++) {
tm.put(taxa.get(i), i);
}
}
List<Clade> clades1 = new ArrayList<Clade>();
getClades(tm, tree1, tree1.getRootNode(), clades1, null);
List<Clade> clades2 = new ArrayList<Clade>();
getClades(tm, tree2, tree2.getRootNode(), clades2, null);
return getDistance(clades1, clades2);
}
protected void getClades(Map<Taxon, Integer> taxonMap, RootedTree tree,
Node node, List<Clade> clades, BitSet bits) {
BitSet bits2 = new BitSet();
if (tree.isExternal(node)) {
int index = taxonMap.get(tree.getTaxon(node));
bits2.set(index);
} else {
for (Node child : tree.getChildren(node)) {
getClades(taxonMap, tree, child, clades, bits2);
}
clades.add(new Clade(bits2, tree.getHeight(node)));
}
if (bits != null) {
bits.or(bits2);
}
}
protected double getDistance(List<Clade> clades1, List<Clade> clades2) {
Collections.sort(clades1);
Collections.sort(clades2);
double distance = 0.0;
int indexClade2 = 0;
Clade clade2 = null;
Clade parent1, parent2 = null;
double height1, height2;
for (Clade clade1 : clades1) {
parent1 = findParent(clade1, clades1);
height1 = parent1.getHeight() - clade1.getHeight();
if (indexClade2 < clades2.size()) {
clade2 = clades2.get(indexClade2);
parent2 = findParent(clade2, clades2);
}
while (clade1.compareTo(clade2) > 0 && indexClade2 < clades2.size()) {
height2 = parent2.getHeight() - clade2.getHeight();
distance += height2 * height2;
indexClade2++;
if (indexClade2 < clades2.size()) {
clade2 = clades2.get(indexClade2);
parent2 = findParent(clade2, clades2);
}
}
if (clade1.compareTo(clade2) == 0) {
height2 = parent2.getHeight() - clade2.getHeight();
distance += (height1 - height2) * (height1 - height2);
indexClade2++;
} else {
distance += height1 * height1;
}
}
return Math.sqrt(distance);
}
private Clade findParent(Clade clade1, List<Clade> clades) {
Clade parent = null;
for (Clade clade2 : clades) {
if (isParent(clade2, clade1)) {
if (parent == null || parent.getSize() > clade2.getSize())
parent = clade2;
}
}
if (parent == null){
//the case that this clade is the whole tree
return clade1;
}
return parent;
}
private boolean isParent(Clade parent, Clade child) {
if (parent.getSize() <= child.getSize()) {
return false;
}
tmpBits.clear();
tmpBits.or(parent.getBits());
tmpBits.xor(child.getBits());
return tmpBits.cardinality() < parent.getSize();
}
BitSet tmpBits = new BitSet();
private final Map<Taxon, Integer> taxonMap;
public static void main(String[] args) {
try {
NewickImporter importer = new NewickImporter("((('C':0.03365591238,'A':0.7225157402):0.306488578,'B':0.4572411443):0.4673149632,('D':0.7966438427,'E':0.8063645191):0.7478901469)");
Tree treeOne = importer.importNextTree();
System.out.println("tree 1: " + treeOne);
importer = new NewickImporter("(('A':0.2333369483,'B':0.3468381313):0.5562255983,('C':0.8732210915,('D':0.9124725792,'E':0.1983703848):0.5252404297):0.2000638912)");
Tree treeTwo = importer.importNextTree();
System.out.println("tree 2: " + treeTwo + "\n");
double metric = (new BranchScoreMetric().getMetric(TreeUtils.asJeblTree(treeOne), TreeUtils.asJeblTree(treeTwo)));
System.out.println("rooted branch score metric = " + metric);
} catch(Importer.ImportException ie) {
System.err.println(ie);
} catch(IOException ioe) {
System.err.println(ioe);
}
}
} |
package dr.evomodelxml.tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.Date;
import dr.evolution.util.Taxon;
import dr.evolution.util.TimeScale;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Parameter;
import dr.inference.model.ParameterParser;
import dr.xml.*;
import java.util.logging.Logger;
/**
* @author Alexei Drummond
*/
public class TreeModelParser extends AbstractXMLObjectParser {
public static final String ROOT_HEIGHT = "rootHeight";
public static final String LEAF_HEIGHT = "leafHeight";
public static final String LEAF_TRAIT = "leafTrait";
public static final String NODE_HEIGHTS = "nodeHeights";
public static final String NODE_RATES = "nodeRates";
public static final String NODE_TRAITS = "nodeTraits";
public static final String MULTIVARIATE_TRAIT = "traitDimension";
public static final String INITIAL_VALUE = "initialValue";
public static final String ROOT_NODE = "rootNode";
public static final String INTERNAL_NODES = "internalNodes";
public static final String LEAF_NODES = "leafNodes";
public static final String FIRE_TREE_EVENTS = "fireTreeEvents";
public static final String TAXON = "taxon";
public static final String NAME = "name";
public TreeModelParser() {
rules = new XMLSyntaxRule[]{
new ElementRule(Tree.class),
new ElementRule(ROOT_HEIGHT, Parameter.class, "A parameter definition with id only (cannot be a reference!)", false),
new ElementRule(NODE_HEIGHTS,
new XMLSyntaxRule[]{
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root height is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node heights (minus the root) are included in the parameter"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 1, Integer.MAX_VALUE),
new ElementRule(LEAF_HEIGHT,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(TAXON, false, "The name of the taxon for the leaf"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE),
new ElementRule(NODE_TRAITS,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(NAME, false, "The name of the trait attribute in the taxa"),
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root trait is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node traits (minus the root) are included in the parameter"),
AttributeRule.newBooleanRule(LEAF_NODES, true, "If true the leaf node traits are included in the parameter"),
AttributeRule.newIntegerRule(MULTIVARIATE_TRAIT, true, "The number of dimensions (if multivariate)"),
AttributeRule.newDoubleRule(INITIAL_VALUE, true, "The initial value(s)"),
AttributeRule.newBooleanRule(FIRE_TREE_EVENTS, true, "Whether to fire tree events if the traits change"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE),
new ElementRule(NODE_RATES,
new XMLSyntaxRule[]{
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root rate is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node rate (minus the root) are included in the parameter"),
AttributeRule.newBooleanRule(LEAF_NODES, true, "If true the leaf node rate are included in the parameter"),
AttributeRule.newDoubleRule(INITIAL_VALUE, true, "The initial value(s)"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE),
new ElementRule(LEAF_TRAIT,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(TAXON, false, "The name of the taxon for the leaf"),
AttributeRule.newStringRule(NAME, false, "The name of the trait attribute in the taxa"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE)
};
}
public String getParserName() {
return TreeModel.TREE_MODEL;
}
/**
* @return a tree object based on the XML element it was passed.
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Tree tree = (Tree) xo.getChild(Tree.class);
TreeModel treeModel = new TreeModel(xo.getId(), tree);
Logger.getLogger("dr.evomodel").info("Creating the tree model, '" + xo.getId() + "'");
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof XMLObject) {
XMLObject cxo = (XMLObject) xo.getChild(i);
if (cxo.getName().equals(ROOT_HEIGHT)) {
ParameterParser.replaceParameter(cxo, treeModel.getRootHeightParameter());
} else if (cxo.getName().equals(LEAF_HEIGHT)) {
String taxonName;
if (cxo.hasAttribute(TAXON)) {
taxonName = cxo.getStringAttribute(TAXON);
} else {
throw new XMLParseException("taxa element missing from leafHeight element in treeModel element");
}
int index = treeModel.getTaxonIndex(taxonName);
if (index == -1) {
throw new XMLParseException("taxon " + taxonName + " not found for leafHeight element in treeModel element");
}
NodeRef node = treeModel.getExternalNode(index);
Parameter newParameter = treeModel.getLeafHeightParameter(node);
ParameterParser.replaceParameter(cxo, newParameter);
Taxon taxon = treeModel.getTaxon(index);
Date date = taxon.getDate();
if (date != null) {
double precision = date.getPrecision();
if (precision > 0.0) {
// taxon date not specified to exact value so add appropriate bounds
double upper = Taxon.getHeightFromDate(date);
double lower = Taxon.getHeightFromDate(date);
if (date.isBackwards()) {
upper += precision;
} else {
lower += precision;
}
// set the bounds for the given precision
newParameter.addBounds(new Parameter.DefaultBounds(upper, lower, 1));
// set the initial value to be mid-point
newParameter.setParameterValue(0, (upper + lower) / 2);
}
}
} else if (cxo.getName().equals(NODE_HEIGHTS)) {
boolean rootNode = cxo.getAttribute(ROOT_NODE, false);
boolean internalNodes = cxo.getAttribute(INTERNAL_NODES, false);
boolean leafNodes = cxo.getAttribute(LEAF_NODES, false);
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeHeights element");
}
ParameterParser.replaceParameter(cxo, treeModel.createNodeHeightsParameter(rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_RATES)) {
boolean rootNode = cxo.getAttribute(ROOT_NODE, false);
boolean internalNodes = cxo.getAttribute(INTERNAL_NODES, false);
boolean leafNodes = cxo.getAttribute(LEAF_NODES, false);
double[] initialValues = null;
if (cxo.hasAttribute(INITIAL_VALUE)) {
initialValues = cxo.getDoubleArrayAttribute(INITIAL_VALUE);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeRates element");
}
ParameterParser.replaceParameter(cxo, treeModel.createNodeRatesParameter(initialValues, rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_TRAITS)) {
boolean rootNode = cxo.getAttribute(ROOT_NODE, false);
boolean internalNodes = cxo.getAttribute(INTERNAL_NODES, false);
boolean leafNodes = cxo.getAttribute(LEAF_NODES, false);
boolean fireTreeEvents = cxo.getAttribute(FIRE_TREE_EVENTS, false);
String name = cxo.getAttribute(NAME, "trait");
int dim = cxo.getAttribute(MULTIVARIATE_TRAIT, 1);
double[] initialValues = null;
if (cxo.hasAttribute(INITIAL_VALUE)) {
initialValues = cxo.getDoubleArrayAttribute(INITIAL_VALUE);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeTraits element");
}
ParameterParser.replaceParameter(cxo, treeModel.createNodeTraitsParameter(name, dim, initialValues, rootNode, internalNodes, leafNodes, fireTreeEvents));
} else if (cxo.getName().equals(LEAF_TRAIT)) {
String name = cxo.getAttribute(NAME, "trait");
String taxonName;
if (cxo.hasAttribute(TAXON)) {
taxonName = cxo.getStringAttribute(TAXON);
} else {
throw new XMLParseException("taxa element missing from leafTrait element in treeModel element");
}
int index = treeModel.getTaxonIndex(taxonName);
if (index == -1) {
throw new XMLParseException("taxon '" + taxonName + "' not found for leafTrait element in treeModel element");
}
NodeRef node = treeModel.getExternalNode(index);
Parameter parameter = treeModel.getNodeTraitParameter(node, name);
if (parameter == null)
throw new XMLParseException("trait '" + name + "' not found for leafTrait (taxon, " + taxonName + ") element in treeModel element");
ParameterParser.replaceParameter(cxo, parameter);
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + cxo.getName());
}
} else if (xo.getChild(i) instanceof Tree) {
// do nothing - already handled
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + xo.getChildName(i) + " " + xo.getChild(i));
}
}
// AR this is doubling up the number of bounds on each node.
// treeModel.setupHeightBounds();
//System.err.println("done constructing treeModel");
Logger.getLogger("dr.evomodel").info(" initial tree topology = " + Tree.Utils.uniqueNewick(treeModel, treeModel.getRoot()));
Logger.getLogger("dr.evomodel").info(" tree height = " + treeModel.getNodeHeight(treeModel.getRoot()));
return treeModel;
} |
package com.facebook.flipper.plugins.network;
import android.text.TextUtils;
import android.util.Pair;
import com.facebook.flipper.core.FlipperArray;
import com.facebook.flipper.core.FlipperConnection;
import com.facebook.flipper.core.FlipperObject;
import com.facebook.flipper.core.FlipperReceiver;
import com.facebook.flipper.core.FlipperResponder;
import com.facebook.flipper.plugins.common.BufferingFlipperPlugin;
import com.facebook.flipper.plugins.network.NetworkReporter.RequestInfo;
import com.facebook.flipper.plugins.network.NetworkReporter.ResponseInfo;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
public class FlipperOkhttpInterceptor
implements Interceptor, BufferingFlipperPlugin.MockResponseConnectionListener {
// By default, limit body size (request or response) reporting to 100KB to avoid OOM
private static final long DEFAULT_MAX_BODY_BYTES = 100 * 1024;
private final long mMaxBodyBytes;
private final NetworkFlipperPlugin mPlugin;
private static class PartialRequestInfo extends Pair<String, String> {
PartialRequestInfo(String url, String method) {
super(url, method);
}
}
// pair of request url and method
private Map<PartialRequestInfo, ResponseInfo> mMockResponseMap = new HashMap<>(0);
private boolean mIsMockResponseSupported;
public FlipperOkhttpInterceptor(NetworkFlipperPlugin plugin) {
this(plugin, DEFAULT_MAX_BODY_BYTES, false);
}
/** If you want to change the number of bytes displayed for the body, use this constructor */
public FlipperOkhttpInterceptor(NetworkFlipperPlugin plugin, long maxBodyBytes) {
this(plugin, maxBodyBytes, false);
}
public FlipperOkhttpInterceptor(NetworkFlipperPlugin plugin, boolean isMockResponseSupported) {
this(plugin, DEFAULT_MAX_BODY_BYTES, isMockResponseSupported);
}
public FlipperOkhttpInterceptor(
NetworkFlipperPlugin plugin, long maxBodyBytes, boolean isMockResponseSupported) {
mPlugin = plugin;
mMaxBodyBytes = maxBodyBytes;
mIsMockResponseSupported = isMockResponseSupported;
if (isMockResponseSupported) {
mPlugin.setConnectionListener(this);
}
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
final Request request = chain.request();
final String identifier = UUID.randomUUID().toString();
mPlugin.reportRequest(convertRequest(request, identifier));
// Check if there is a mock response
final Response mockResponse = mIsMockResponseSupported ? getMockResponse(request) : null;
final Response response = mockResponse != null ? mockResponse : chain.proceed(request);
final ResponseBody body = response.body();
final ResponseInfo responseInfo = convertResponse(response, body, identifier);
responseInfo.isMock = mockResponse != null;
mPlugin.reportResponse(responseInfo);
return response;
}
private static byte[] bodyToByteArray(final Request request, final long maxBodyBytes)
throws IOException {
final Buffer buffer = new Buffer();
if (request.body() != null) {
request.body().writeTo(buffer);
}
return buffer.readByteArray(Math.min(buffer.size(), maxBodyBytes));
}
private RequestInfo convertRequest(Request request, String identifier) throws IOException {
final List<NetworkReporter.Header> headers = convertHeader(request.headers());
final RequestInfo info = new RequestInfo();
info.requestId = identifier;
info.timeStamp = System.currentTimeMillis();
info.headers = headers;
info.method = request.method();
info.uri = request.url().toString();
if (request.body() != null) {
info.body = bodyToByteArray(request, mMaxBodyBytes);
}
return info;
}
private ResponseInfo convertResponse(Response response, ResponseBody body, String identifier)
throws IOException {
final List<NetworkReporter.Header> headers = convertHeader(response.headers());
final ResponseInfo info = new ResponseInfo();
info.requestId = identifier;
info.timeStamp = response.receivedResponseAtMillis();
info.statusCode = response.code();
info.headers = headers;
Buffer buffer = null;
try {
final BufferedSource source = body.source();
source.request(mMaxBodyBytes);
buffer = source.buffer().clone();
info.body = buffer.readByteArray();
} finally {
if (buffer != null) {
buffer.close();
}
}
return info;
}
private static List<NetworkReporter.Header> convertHeader(Headers headers) {
final List<NetworkReporter.Header> list = new ArrayList<>(headers.size());
final Set<String> keys = headers.names();
for (final String key : keys) {
list.add(new NetworkReporter.Header(key, headers.get(key)));
}
return list;
}
private void registerMockResponse(PartialRequestInfo partialRequest, ResponseInfo response) {
if (!mMockResponseMap.containsKey(partialRequest)) {
mMockResponseMap.put(partialRequest, response);
}
}
@Nullable
private Response getMockResponse(Request request) {
final String url = request.url().toString();
final String method = request.method();
final PartialRequestInfo partialRequest = new PartialRequestInfo(url, method);
if (!mMockResponseMap.containsKey(partialRequest)) {
return null;
}
ResponseInfo mockResponse = mMockResponseMap.get(partialRequest);
if (mockResponse == null) {
return null;
}
final Response.Builder builder = new Response.Builder();
builder
.request(request)
.protocol(Protocol.HTTP_1_1)
.code(mockResponse.statusCode)
.message(mockResponse.statusReason)
.receivedResponseAtMillis(System.currentTimeMillis())
.body(ResponseBody.create(MediaType.parse("application/text"), mockResponse.body));
if (mockResponse.headers != null && !mockResponse.headers.isEmpty()) {
for (final NetworkReporter.Header header : mockResponse.headers) {
if (!TextUtils.isEmpty(header.name) && !TextUtils.isEmpty(header.value)) {
builder.header(header.name, header.value);
}
}
}
return builder.build();
}
@Nullable
private ResponseInfo convertFlipperObjectRouteToResponseInfo(FlipperObject route) {
final String data = route.getString("data");
final String requestUrl = route.getString("requestUrl");
final String method = route.getString("method");
FlipperArray headersArray = route.getArray("headers");
if (TextUtils.isEmpty(requestUrl) || TextUtils.isEmpty(method)) {
return null;
}
final ResponseInfo mockResponse = new ResponseInfo();
mockResponse.body = data.getBytes();
mockResponse.statusCode = HttpURLConnection.HTTP_OK;
mockResponse.statusReason = "OK";
if (headersArray != null) {
final List<NetworkReporter.Header> headers = new ArrayList<>();
for (int j = 0; j < headersArray.length(); j++) {
final FlipperObject header = headersArray.getObject(j);
headers.add(new NetworkReporter.Header(header.getString("key"), header.getString("value")));
}
mockResponse.headers = headers;
}
return mockResponse;
}
@Override
public void onConnect(FlipperConnection connection) {
connection.receive(
"mockResponses",
new FlipperReceiver() {
@Override
public void onReceive(FlipperObject params, FlipperResponder responder) throws Exception {
FlipperArray array = params.getArray("routes");
mMockResponseMap.clear();
for (int i = 0; i < array.length(); i++) {
final FlipperObject route = array.getObject(i);
final String requestUrl = route.getString("requestUrl");
final String method = route.getString("method");
ResponseInfo mockResponse = convertFlipperObjectRouteToResponseInfo(route);
if (mockResponse != null) {
registerMockResponse(new PartialRequestInfo(requestUrl, method), mockResponse);
}
}
responder.success();
}
});
}
@Override
public void onDisconnect() {
mMockResponseMap.clear();
}
} |
package org.intelehealth.ekalarogya.activities.searchPatientActivity;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import org.intelehealth.ekalarogya.R;
import org.intelehealth.ekalarogya.models.dto.PatientDTO;
import org.intelehealth.ekalarogya.utilities.DateAndTimeUtils;
import org.intelehealth.ekalarogya.activities.patientDetailActivity.PatientDetailActivity;
public class SearchPatientAdapter extends RecyclerView.Adapter<SearchPatientAdapter.Myholder> {
List<PatientDTO> patients;
Context context;
LayoutInflater layoutInflater;
public SearchPatientAdapter(List<PatientDTO> patients, Context context) {
this.patients = patients;
this.context = context;
}
@NonNull
@Override
public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View row = inflater.inflate(R.layout.list_item_search, parent, false);
return new Myholder(row);
}
@Override
public void onBindViewHolder(@NonNull SearchPatientAdapter.Myholder holder, int position) {
final PatientDTO patinet = patients.get(position);
if (patinet != null) {
//int age = DateAndTimeUtils.getAge(patinet.getDateofbirth(),context);
String age = DateAndTimeUtils.getAgeInYearMonth(patinet.getDateofbirth(), context);
//String dob = DateAndTimeUtils.SimpleDatetoLongDate(patinet.getDateofbirth());
String body = context.getString(R.string.identification_screen_prompt_age) + "" + age;
if (patinet.getOpenmrsId() != null)
holder.headTextView.setText(patinet.getFirstname() + " " + patinet.getLastname()
+ ", " + patinet.getOpenmrsId());
else
holder.headTextView.setText(patinet.getFirstname() + " " + patinet.getLastname());
holder.bodyTextView.setText(body);
}
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("search adapter", "patientuuid" + patinet.getUuid());
String patientStatus = "returning";
Intent intent = new Intent(context, PatientDetailActivity.class);
intent.putExtra("patientUuid", patinet.getUuid());
intent.putExtra("patientName", patinet.getFirstname() + "" + patinet.getLastname());
intent.putExtra("status", patientStatus);
intent.putExtra("tag", "search");
intent.putExtra("hasPrescription", "false");
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return patients.size();
}
class Myholder extends RecyclerView.ViewHolder {
LinearLayout linearLayout;
private TextView headTextView;
private TextView bodyTextView;
public Myholder(View itemView) {
super(itemView);
headTextView = itemView.findViewById(R.id.list_item_head);
bodyTextView = itemView.findViewById(R.id.list_item_body);
linearLayout = itemView.findViewById(R.id.searchlinear);
}
}
} |
package football;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import football.players.*;
import football.util.metrics.Metric;
import football.util.metrics.SortOrderMetric;
public class FantasyFootballCustomScoringHelper
{
//files to write results to
public static final String resultsDir = "results";
public static final String sectionDenoter = "********";
public static final String delimiter = "***********************************************************";
public static void main(String[] args)
{
if(args.length < 1) {
System.out.println("Error in main: Mode not specified");
usage();
System.exit(1);
}
String mode = args[0];
//quickly initialize group of players based on mode
Player[] players = null;
if(mode.equals("qb")) {
players = new Player[]{Players.SANCHEZ,Players.WEEDEN,Players.LEINART,Players.QUINN,
Players.KOLB,Players.PALMER,Players.BRADY,Players.PEYTON,Players.RODGERS};
} else if(mode.equals("rb")) {
players = new Player[]{Players.REDMAN,Players.HILLMAN,Players.MATHEWS,Players.JONESDREW,
Players.RBUSH,Players.RICE,Players.LYNCH,Players.FOSTER};
} else if(mode.equals("wr")) {
players = new Player[]{Players.BEDWARDS,Players.SHOLMES,Players.HDOUGLAS,Players.MANNINGHAM,
Players.AMENDOLA,Players.JJONES,Players.DBRYANT,Players.CJOHNSON};
} else if(mode.equals("def")) {
players = new Player[]{Players.OAKLAND,Players.NEWORLEANS,Players.JACKSONVILLE,
Players.CLEVELAND,Players.SEATTLE,Players.SANFRAN,Players.CHICAGO};
} else if(mode.equals("k")) {
players = new Player[]{Players.CUNDIFF,Players.FOLK,Players.CROSBY,Players.FORBATH,
Players.SCOBEE,Players.SUISHAM,Players.GOSTKOWSKI,Players.MBRYANT,Players.TUCKER};
} else {
System.out.println("Error in main: Invalid mode");
usage();
System.exit(1);
}
String filename = (mode.toUpperCase() + "results.txt");
List<Player> defaultPlayers = new ArrayList<Player>(Arrays.asList(players));
List<Player> customPlayers = runPlayers(defaultPlayers,args,filename);
}
//TODO: replace List<Player> with List<T extends Player>
//could pass in PrintStream instead of filename string to make switching to System.out. easy
public static List<Player> runPlayers(List<Player> defaultPlayers, String[] args, String filename) {
//sort players according to default scores
Collections.sort(defaultPlayers);
//make copy of players to preserve original order
List<Player> customPlayers = new ArrayList<Player>(defaultPlayers.size());
for(Player player : defaultPlayers) {
customPlayers.add(player.deepCopy());
}
//evaluate all players with custom rules
for(Player player : customPlayers) {
player.parseScoringCoeffsAndEvaluate(args);
}
//sort players according to custom scores
Collections.sort(customPlayers);
//write results to file
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(new File(resultsDir,filename),true)));
out.println(delimiter + "\n");
out.println(toSectionHeader("Custom scoring coefficients"));
out.println(customPlayers.get(0).categoriesToString()); //TODO: make this call static
printCoeffs(args,out);
out.println(toSectionHeader("Default scoring rules"));
printList(defaultPlayers,out);
out.println(toSectionHeader("Custom scoring rules"));
printList(customPlayers,out);
//calculate (dis)similarity btw customPlayers and defaultPlayers
Metric metric = new SortOrderMetric();
double dist = metric.distance(defaultPlayers,customPlayers);
out.println("Distance between default and custom is: " + dist);
out.println("\n" + delimiter + "\n\n\n");
out.close();
} catch(IOException e) {
System.out.println("Error in runPlayers: IO exception when writing to file " + filename);
}
return customPlayers;
}
private static void usage() {
String indent = "\t\t";
System.out.println("Usage: java ff <mode> <sc1> ... <scN>,\twhere");
System.out.println(indent + "mode := player position to simulate. Possible values are def, k, qb, rb, and wr.");
System.out.println(indent + "sc1 - scN := scoring coefficients representing all rules needed to score players at position given by mode. Necessary scoring coefficients per position are given below.");
/*System.out.println(indent + "def: " + DEF.categoriesToString());
System.out.println(indent + "k: " + K.categoriesToString());
System.out.println(indent + "qb: " + QB.categoriesToString());
System.out.println(indent + "rb: " + RB.categoriesToString());
System.out.println(indent + "wr: " + WR.categoriesToString());*/
}
//TODO: consider just using players.toString()
//write players list to printwriter stream
private static <E extends Player> void printList(List<E> players, PrintWriter out) {
for(E player : players) {
out.println(player.toString());
}
out.println("\n");
out.flush(); //for System.out casted to printwriter
}
//TODO: format this better for players with different stat types
//write coeffs array to printwriter stream
private static void printCoeffs(String[] args, PrintWriter out) {
int numCoeffs = args.length;
for(int i = 1; i < numCoeffs; i++) { //skip mode argument
out.printf("%-10s ",args[i]);
}
out.println("\n");
}
//surrounds sectionTitle on both sides by sectionDenoter to create section header
private static String toSectionHeader(String sectionTitle) {
return (sectionDenoter + " " + sectionTitle + " " + sectionDenoter);
}
} |
/*
Input: Email message
Output:
A) Bag of words, ordered by index in the vector
B) For each email, outputs a vector of
1. Length of email (bytes)
2. Length of email (words)
3. Number of '?'
4. Number of questioning words (like "Who Why How When Where")
5. Number of "formal" words. (like "Sir", "Yours sincerely")
6. Bag of words, listed in order of the bag of words given.
7. Number of replies this email has
Other things we can do:
Metadata features:
1. If replied to sender earlier
2. If sender sent email but user ignored.
3. Sender email address. Internal email, external, from .com?
4. Many people in CC? Blasted email
*/
package com.expee.ml.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class GetFeature {
private static final int MIN_THEME_PERCENT = 5;
private static final int MAX_THEME_PERCENT = 15;
private static final int MIN_COUNT = 200;
private static final int MINWORDLEN = 3;
private static final Set<String> QUESTION_SET = new HashSet<String>(Arrays.asList(
"Could", "Would", "Who", "When", "Where", "What",
"Why", "How", "Is", "Are", "Will", "May", "Might"));
private static final Set<String> FORMAL_SET = new HashSet<String>(Arrays.asList(
"Yours", "Sincerely", "Sir", "Regards", "Madam"));
private static final Set<String> MEETING_SET = new HashSet<String>(Arrays.asList(
"reminder", "meeting", "location", "date", "time"));
private static final Set<String> REPLY_SET = new HashSet<String>(Arrays.asList(
"reply", "rsvp", "respond", "response", "acknowledge", "email"));
private static final String[] TRIGGER_PHRASE_ARRAY = {
"follow up", "let me know", "let us know", "feel free", "help us", "get back"};
private static final Set<String> STOPWORDS_SET = new HashSet<String>(Arrays.asList(
"a", "able", "about", "above", "abst", "accordance", "according", "accordingly", "across", "act", "actually", "added", "adj", "affected", "affecting", "affects", "after", "afterwards", "again", "against", "ah", "all", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "an", "and", "announce", "another", "any", "anybody", "anyhow", "anymore", "anyone", "anything", "anyway", "anyways", "anywhere", "apparently", "approximately", "are", "aren", "arent", "arise", "around", "as", "aside", "ask", "asking", "at", "auth", "available", "away", "awfully", "b", "back", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "begin", "beginning", "beginnings", "begins", "behind", "being", "believe", "below", "beside", "besides", "between", "beyond", "biol", "both", "brief", "briefly", "but", "by", "c", "ca", "came", "can", "cannot", "cant", "cause", "causes", "certain", "certainly", "co", "com", "come", "comes", "contain", "containing", "contains", "could", "couldnt", "d", "date", "did", "didnt", "different", "do", "does", "doesnt", "doing", "done", "dont", "down", "downwards", "due", "during", "e", "each", "ed", "edu", "effect", "eg", "eight", "eighty", "either", "else", "elsewhere", "end", "ending", "enough", "especially", "et", "et-al", "etc", "even", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "except", "f", "far", "few", "ff", "fifth", "first", "five", "fix", "followed", "following", "follows", "for", "former", "formerly", "forth", "found", "four", "from", "further", "furthermore", "g", "gave", "get", "gets", "getting", "give", "given", "gives", "giving", "go", "goes", "gone", "got", "gotten", "h", "had", "happens", "hardly", "has", "hasnt", "have", "havent", "having", "he", "hed", "hence", "her", "here", "hereafter", "hereby", "herein", "heres", "hereupon", "hers", "herself", "hes", "hi", "hid", "him", "himself", "his", "hither", "home", "how", "howbeit", "however", "hundred", "i", "id", "ie", "if", "ill", "im", "immediate", "immediately", "importance", "important", "in", "inc", "indeed", "index", "information", "instead", "into", "invention", "inward", "is", "isnt", "it", "itd", "itll", "its", "itself", "ive", "j", "just", "k", "keep", "keeps", "kept", "kg", "km", "know", "known", "knows", "l", "largely", "last", "lately", "later", "latter", "latterly", "least", "less", "lest", "let", "lets", "like", "liked", "likely", "line", "little", "ll", "look", "looking", "looks", "ltd", "m", "made", "mainly", "make", "makes", "many", "may", "maybe", "me", "mean", "means", "meantime", "meanwhile", "merely", "mg", "might", "million", "miss", "ml", "more", "moreover", "most", "mostly", "mr", "mrs", "much", "mug", "must", "my", "myself", "n", "na", "name", "namely", "nay", "nd", "near", "nearly", "necessarily", "necessary", "need", "needs", "neither", "never", "nevertheless", "new", "next", "nine", "ninety", "no", "nobody", "non", "none", "nonetheless", "noone", "nor", "normally", "nos", "not", "noted", "nothing", "now", "nowhere", "o", "obtain", "obtained", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "omitted", "on", "once", "one", "ones", "only", "onto", "or", "ord", "other", "others", "otherwise", "ought", "our", "ours", "ourselves", "out", "outside", "over", "overall", "owing", "own", "p", "page", "pages", "part", "particular", "particularly", "past", "per", "perhaps", "placed", "please", "plus", "poorly", "possible", "possibly", "potentially", "pp", "predominantly", "present", "previously", "primarily", "probably", "promptly", "proud", "provides", "put", "q", "que", "quickly", "quite", "qv", "r", "ran", "rather", "rd", "re", "readily", "really", "recent", "recently", "ref", "refs", "regarding", "regardless", "regards", "related", "relatively", "research", "respectively", "resulted", "resulting", "results", "right", "run", "s", "said", "same", "saw", "say", "saying", "says", "sec", "section", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self", "selves", "sent", "seven", "several", "shall", "she", "shed", "shell", "shes", "should", "shouldnt", "show", "showed", "shown", "showns", "shows", "significant", "significantly", "similar", "similarly", "since", "six", "slightly", "so", "some", "somebody", "somehow", "someone", "somethan", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specifically", "specified", "specify", "specifying", "still", "stop", "strongly", "sub", "substantially", "successfully", "such", "sufficiently", "suggest", "sup", "sure","which","while","andor","making","within","turn","want","these","there","unless","week","their","long","amount","include","very","today","well","were","without","days","currently","full","they","them","then","includes","than","feel","dear","what","when","who","why","where","how","thanks","with","that","would","those","through"));
private static final Set<String> SPAM_SET = new HashSet<String>(Arrays.asList(
"free", "Ad", "$", "$$", "$$$", "gift", "mortgage", "save", "aging", "marketing", "credit", "refund", "sample", "trial", "ad", "viagra"));
public static void makeEmailSetFeatures(Set<Email> emails, String output, String testOutput) throws IOException {
PrintWriter writer = new PrintWriter(new File(output));
PrintWriter writerTest = new PrintWriter(new File(testOutput));
Map<String, Integer> wordEmailCount = new HashMap<String, Integer>();
for (Email email: emails) {
String text = email.getText();
if (text == null) continue;
String[] wordArray = text.split("\\s");
Set<String> wordSet = new HashSet<String>();
for (String word : wordArray) {
String strippedLowerWord = word.replaceAll("[^a-zA-Z]","").toLowerCase();
if (strippedLowerWord.length() > MINWORDLEN) {
wordSet.add(strippedLowerWord);
}
}
for (String word : wordSet) {
if (wordEmailCount.containsKey(word)) {
wordEmailCount.put(word, wordEmailCount.get(word)+1);
} else {
wordEmailCount.put(word, 1);
}
}
}
System.out.println("Done making count map for subjects");
String header = "";
header += "Byte Length,Word Length,Num Question,Num Question Words,Num Formal Words,";
header += "Num Paragraphs,Paragraph Density,Num Recipients,Is Sender Enron,";
header += "Num Meeting Words,Num Replyrelated words, Num Spam words, Num Trigger Phrases, NumXto, Number times recipient mentioned, ";
int minThemeCount = (emails.size() * MIN_THEME_PERCENT) / 100;
int maxThemeCount = (emails.size() * MAX_THEME_PERCENT) / 100;
List<String> themeList = new ArrayList<String>();
int idx = 0;
Map<String, Integer> themeMap = new HashMap<String, Integer>();
for (Entry<String, Integer> entry : wordEmailCount.entrySet()) {
if (entry.getValue() >= minThemeCount && entry.getValue() <= maxThemeCount) {
String word = entry.getKey();
if (!(STOPWORDS_SET.contains(word))) {
themeList.add(word);
header += (word + ",");
themeMap.put(word, idx);
idx++;
}
}
}
header += ("Has Reply, Num Replies, Word Length of Reply");
for (String word : themeList) {
header += (",(Reply theme) " + word);
}
writer.println(header);
writerTest.println(header);
for (Email email : emails) {
GetFeature.preprocessEmail(themeMap, email);
}
for (Email email : emails) {
GetFeature.printEmailFeatures(themeMap, writer, email, true);
}
writer.flush();
writer.close();
for (Email email : emails) {
GetFeature.printEmailFeatures(themeMap, writerTest, email, false);
}
writerTest.flush();
writerTest.close();
}
public static void preprocessEmail(
Map<String, Integer> themeMap, Email email) throws IOException {
int themeMapSize = themeMap.size();
int[] themes = email.getThemes();
themes = new int[themeMapSize];
for (int i = 0; i < themeMapSize; i++) {
themes[i] = 0;
}
String text = email.getText();
if (text != null) {
String[] textWordArray = text.split("\\s");
for (String word : textWordArray) {
String strippedLowerWord = word.replaceAll("[^a-zA-Z]","").toLowerCase();
if (themeMap.containsKey(strippedLowerWord)) {
themes[themeMap.get(strippedLowerWord)]++;
}
}
}
email.setThemes(themes);
int numWords = email.getText().split("\\s").length;
email.setWordCount(numWords);
}
public static boolean purge(long uid, boolean isTrain) {
if (isTrain) {
return (uid%20 == 0);
}
else {
return (uid%20 != 0);
}
}
public static void printEmailFeatures(
Map<String, Integer> themeMap, PrintWriter writer, Email email, boolean is_training) throws IOException {
if (purge(email.getuid(), is_training)) {
return;
}
String to = email.getTo();
int numRecipients = 1;
if (to != null) {
numRecipients = to.split("\\w@\\w").length - 1;
}
String xto = email.getXTo();
String[] xtoArray = xto.split("\\s+");
Set<String> toNamesSet = new HashSet<String>();
for (String s : xtoArray) {
if (s.length() > 1) {
toNamesSet.add(s.toLowerCase().replaceAll("[^a-zA-Z]", ""));
}
}
int numXto = toNamesSet.size();
int isEnron = 0;
String sender = email.getSender();
if (sender != null && sender.toLowerCase().contains("@enron")) {
isEnron = 1;
}
String msg = email.getText();
String[] paragraphArray = msg.split("\n\\w");
int numParagraphs = paragraphArray.length;
int paragraphDensity = 0;
for (String paragraph: paragraphArray) {
int numWordsInParagraph = paragraph.split("\\s").length;
paragraphDensity += numWordsInParagraph;
}
if (numParagraphs > 0) {
paragraphDensity /= numParagraphs;
}
String[] wordArray = msg.split("\\s");
int numWords = wordArray.length;
email.setWordCount(numWords);
int numQuestionMarks = 0;
for (int i = 0; i < msg.length(); i++) {
if (msg.charAt(i) == '?') {
numQuestionMarks++;
}
}
int numQuestionWords = 0;
int numFormalWords = 0;
int numMeetingWords = 0;
int numReplyWords = 0;
int numSpamWords = 0;
int numToNameWords = 0;
for (String word : wordArray) {
String strippedWord = word.replaceAll("[^\\w]","");
String strippedLowerWord = strippedWord.toLowerCase();
if (strippedLowerWord.length() == 0) continue;
// Preserve upper case to differentiate "Is...?" "Are you...?" from "...is..."
if (QUESTION_SET.contains(strippedWord)) {
numQuestionWords++;
}
// Preserve upper case to differentiate "Yours (truly)" from "(this is) yours"
if (FORMAL_SET.contains(strippedWord)) {
numFormalWords++;
}
if (MEETING_SET.contains(strippedLowerWord)) {
numMeetingWords++;
}
if (REPLY_SET.contains(strippedLowerWord)) {
numReplyWords++;
}
if (SPAM_SET.contains(strippedLowerWord)) {
numSpamWords++;
}
if (toNamesSet.contains(strippedLowerWord)) {
numToNameWords++;
}
}
String msglower = msg.toLowerCase();
int numPhrases = 0;
for (String phrase : TRIGGER_PHRASE_ARRAY) {
if (msglower.contains(phrase)) {
numPhrases++;
}
}
Set<Email> children = email.getChildren();
for (Iterator<Email> iterator = children.iterator(); iterator.hasNext();) {
Email emailc = iterator.next();
if ((purge(emailc.getuid(), is_training))) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
int numChildren = children.size();
int averageChildrenSize = 0;
if (numChildren > 0) {
for (Email child: children) {
int numWordsInChild = child.getWordCount();
averageChildrenSize += numWordsInChild;
}
averageChildrenSize /= numChildren;
}
// Now compute themes
int[] themes = email.getThemes();
int len = themes.length;
int[] childrenThemes = new int[themes.length];
if (numChildren > 0) {
for (Email child: children) {
int[] childThemes = child.getThemes();
for (int i = 0; i < childrenThemes.length; i++) {
childrenThemes[i] += childThemes[i];
}
}
}
//Message length (bytes)
writer.print(Math.log(msg.length()+1) + ",");
// Message length (words)
writer.print(Math.log(numWords+1) + ",");
// Number of question marks
writer.print(Math.log(numQuestionMarks+1) + ",");
// Number of formal words:
writer.print(Math.log(numFormalWords+1) + ",");
// Number of interrogative words
writer.print(Math.log(numQuestionWords+1) + ",");
// Number of paragraphs
writer.print(Math.log(numParagraphs+1) + ",");
// Paragraph density
writer.print(Math.log(paragraphDensity+1) + ",");
// Number of recipients
writer.print(Math.log(numRecipients+1) + ",");
// Is sender domain from enron.com?
writer.print(isEnron + ",");
// Meeting words (number)
writer.print(Math.log(numMeetingWords+1) + ",");
// Reply-related words
writer.print(Math.log(numReplyWords+1) + ",");
// Spam-related words
writer.print(Math.log(numSpamWords+1) + ",");
// Number of trigger phrases
writer.print(Math.log(numPhrases+1) + ",");
// Num X-To recipients
writer.print(Math.log(numXto+1) + ",");
// Number of words in email that match recipient list
writer.print(Math.log(numToNameWords+1) + ",");
// Bag of words for subject
for (int i = 0; i < themes.length; i++) {
writer.print((themes[i]>0) + ",");
}
//Did the email have a reply
writer.print((numChildren>0) + ",");
// Number of replies this email has
writer.print(numChildren + ",");
// Average children size
writer.print(averageChildrenSize);
// Children theme words. Average number of words per child.
if (numChildren > 0) {
for (int i = 0; i < childrenThemes.length; i++) {
writer.print("," + (childrenThemes[i]>0));
}
}
else {
for (int i = 0; i < childrenThemes.length; i++) {
writer.print("," + "NO_CHILD");
}
}
writer.println("");
}
} |
package fm.libre.droid;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
public class LibreDroid extends ListActivity {
private LibreServiceConnection libreServiceConn;
private String username;
private String password;
private ArrayList<String> stations;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
libreServiceConn = new LibreServiceConnection();
bindService(new Intent(this, LibreService.class), libreServiceConn, Context.BIND_AUTO_CREATE);
this.registerReceiver(new MediaButtonReceiver(), new IntentFilter(Intent.ACTION_MEDIA_BUTTON));
this.registerReceiver(new UIUpdateReceiver(), new IntentFilter("LibreDroidNewSong"));
setContentView(R.layout.main);
// Load settings
final SharedPreferences settings = getSharedPreferences("LibreDroid", MODE_PRIVATE);
username = settings.getString("Username", "");
password = settings.getString("Password", "");
final EditText usernameEntry = (EditText) findViewById(R.id.usernameEntry);
final EditText passwordEntry = (EditText) findViewById(R.id.passwordEntry);
usernameEntry.setText(username);
passwordEntry.setText(password);
final Button loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Editor editor = settings.edit();
editor.putString("Username", usernameEntry.getText().toString());
editor.putString("Password", passwordEntry.getText().toString());
editor.commit();
LibreDroid.this.login();
}
});
stations = new ArrayList<String>();
try {
BufferedReader stationReader = new BufferedReader(new InputStreamReader(openFileInput("libredroid-custom-stations.conf")));
String station;
while((station = stationReader.readLine()) != null) {
stations.add(station);
}
} catch (IOException ex) {
Log.d("libredroid", ex.getMessage());
}
// Add default stations if empty
String radioButtons[] = { "Folk", "Rock", "Metal", "Classical", "Pop",
"Punk", "Jazz", "Blues", "Rap", "Ambient", "Add A Custom Station..." };
stations.addAll(Arrays.asList(radioButtons));
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, stations));
Button tagStation = (Button) findViewById(R.id.tagStationButton);
tagStation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.nextPage();
}
});
Button loveStation = (Button) findViewById(R.id.loveStationButton);
loveStation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.libreServiceConn.service.tuneStation("user", username + "/loved");
LibreDroid.this.nextPage();
LibreDroid.this.nextPage();
LibreDroid.this.nextPage();
}
});
Button communityLoveStation = (Button) findViewById(R.id.communityStationButton);
communityLoveStation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.libreServiceConn.service.tuneStation("community", "loved");
LibreDroid.this.nextPage();
LibreDroid.this.nextPage();
LibreDroid.this.nextPage();
}
});
final ImageButton nextButton = (ImageButton) findViewById(R.id.nextButton);
nextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.libreServiceConn.service.next();
}
});
final ImageButton prevButton = (ImageButton) findViewById(R.id.prevButton);
prevButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.libreServiceConn.service.prev();
}
});
final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton);
playPauseButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.togglePause();
}
});
final ImageButton saveButton = (ImageButton) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.save();
}
});
final ImageButton loveButton = (ImageButton) findViewById(R.id.loveButton);
loveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.libreServiceConn.service.love();
}
});
final ImageButton banButton = (ImageButton) findViewById(R.id.banButton);
banButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.libreServiceConn.service.ban();
}
});
final Button addStationButton = (Button) findViewById(R.id.addStationButton);
addStationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LibreDroid.this.addStation();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
String selection = l.getItemAtPosition(pos).toString();
if(selection.equals("Add A Custom Station...")) {
LibreDroid.this.nextPage();
} else {
LibreDroid.this.libreServiceConn.service.tuneStation("globaltags", selection);
LibreDroid.this.nextPage();
LibreDroid.this.nextPage();
}
}
public void updateSong() {
Song song = libreServiceConn.service.getSong();
final TextView titleText = (TextView) findViewById(R.id.titleText);
final TextView artistText = (TextView) findViewById(R.id.artistText);
final TextView stationText = (TextView) findViewById(R.id.stationNameText);
final ImageView albumImage = (ImageView) findViewById(R.id.albumImage);
final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton);
playPauseButton.setImageResource(R.drawable.pause);
titleText.setText(song.title);
artistText.setText(song.artist);
stationText.setText(libreServiceConn.service.getStationName());
if (song.imageURL.length() > 0) {
new AlbumImageTask().execute(song.imageURL);
} else {
albumImage.setImageResource(R.drawable.album);
}
}
public void addStation() {
final EditText stationEntry = (EditText) findViewById(R.id.stationEntry);
stations.add(0, stationEntry.getText().toString());
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, stations));
this.prevPage();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
if (this.libreServiceConn.service.getCurrentPage() > 0) {
if(this.libreServiceConn.service.getCurrentPage() == 4) {
// Back three pages if we're on the player page to get back to the main menu
this.prevPage();
this.prevPage();
}
this.prevPage();
LibreDroid.this.libreServiceConn.service.stop();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public String httpGet(String url) throws URISyntaxException,
ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse res = client.execute(method);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
res.getEntity().writeTo(outstream);
return outstream.toString();
}
public String httpPost(String url, String... params)
throws URISyntaxException, ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URI(url);
HttpPost method = new HttpPost(uri);
List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i < params.length; i += 2) {
paramPairs.add(new BasicNameValuePair(params[i], params[i + 1]));
}
method.setEntity(new UrlEncodedFormEntity(paramPairs));
method.getParams().setBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false); // Disable
// expect-continue,
// caching
// server
// doesn't like
// this
HttpResponse res = client.execute(method);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
res.getEntity().writeTo(outstream);
return outstream.toString();
}
public void togglePause() {
final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton);
if (libreServiceConn.service.isPlaying()) {
playPauseButton.setImageResource(R.drawable.play);
} else {
playPauseButton.setImageResource(R.drawable.pause);
}
libreServiceConn.service.togglePause();
}
public void login() {
final EditText usernameEntry = (EditText) findViewById(R.id.usernameEntry);
final EditText passwordEntry = (EditText) findViewById(R.id.passwordEntry);
username = usernameEntry.getText().toString();
password = passwordEntry.getText().toString();
boolean loggedIn = libreServiceConn.service.login(username, password);
if (loggedIn) {
nextPage();
}
}
public void nextPage() {
final ViewAnimator view = (ViewAnimator) findViewById(R.id.viewAnimator);
view.showNext();
libreServiceConn.service.setCurrentPage(view.getDisplayedChild());
}
public void prevPage() {
final ViewAnimator view = (ViewAnimator) findViewById(R.id.viewAnimator);
view.showPrevious();
libreServiceConn.service.setCurrentPage(view.getDisplayedChild());
}
public void save() {
Song song = this.libreServiceConn.service.getSong();
Toast.makeText(LibreDroid.this,
"Downloading \"" + song.title + "\" to your SD card.",
Toast.LENGTH_LONG).show();
new DownloadTrackTask().execute(song);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem changeStation = menu.add(0, Menu.FIRST, 0, "Change Station")
.setIcon(R.drawable.back);
MenuItem quit = menu.add(0, 2, 0, "Quit").setIcon(R.drawable.quit);
changeStation.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final ViewAnimator view = (ViewAnimator) findViewById(R.id.viewAnimator);
if (view.getDisplayedChild() == 2) {
LibreDroid.this.libreServiceConn.service.stop();
LibreDroid.this.prevPage();
return true;
} else {
return false;
}
}
});
quit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
LibreDroid.this.libreServiceConn.service.stop();
LibreDroid.this.finish();
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
private class AlbumImageTask extends AsyncTask<String, String, Bitmap> {
protected Bitmap doInBackground(String... params) {
String url = params[0];
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
}
return bm;
}
protected void onPostExecute(Bitmap bm) {
final ImageView albumImage = (ImageView) findViewById(R.id.albumImage);
albumImage.setImageBitmap(bm);
}
}
private class DownloadTrackTask extends
AsyncTask<Song, String, List<Object>> implements
MediaScannerConnectionClient {
private MediaScannerConnection msc;
private String path;
@Override
protected List<Object> doInBackground(Song... params) {
Song song = params[0];
List<Object> res = new ArrayList<Object>();
try {
File root = Environment.getExternalStorageDirectory();
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
res.add(false);
res.add("Please ensure an SD card is inserted before attempting to download songs. " + Environment.getExternalStorageState());
return res;
}
File musicDir = new File(root, "Music");
if (!musicDir.exists()) {
musicDir.mkdir();
}
File f = new File(musicDir, song.artist + " - " + song.title + ".ogg");
this.path = f.getAbsolutePath();
FileOutputStream fo = new FileOutputStream(f);
URL aURL = new URL(song.location);
HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
conn.connect();
if (conn.getResponseCode() == 301 || conn.getResponseCode() == 302 || conn.getResponseCode() == 307) {
// Redirected
aURL = new URL(conn.getHeaderField("Location"));
conn = (HttpURLConnection) aURL.openConnection();
}
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(fo);
byte buf[] = new byte[1024];
int count = 0;
while ((count = bis.read(buf, 0, 1024)) != -1) {
bos.write(buf, 0, count);
}
bos.close();
fo.close();
bis.close();
is.close();
res.add(true);
res.add("Finished downloading \"" + song.title + "\"");
} catch (Exception ex) {
res.add(false);
res.add("Unable to download \"" + song.title + "\": "
+ ex.getMessage());
}
return res;
}
protected void onPostExecute(List<Object> result) {
Boolean res = (Boolean) result.get(0);
String msg = (String) result.get(1);
if (res.booleanValue() == true) {
// Update the media library so it knows about the new file
this.msc = new MediaScannerConnection(LibreDroid.this, this);
this.msc.connect();
}
Toast.makeText(LibreDroid.this, msg, Toast.LENGTH_LONG).show();
}
public void onMediaScannerConnected() {
this.msc.scanFile(this.path, null);
}
public void onScanCompleted(String path, Uri uri) {
}
}
private class UIUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
LibreDroid.this.runOnUiThread(new Runnable() {
public void run() {
LibreDroid.this.updateSong();
}
});
}
}
private class MediaButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
KeyEvent ev = (KeyEvent) intent.getExtras().get(
Intent.EXTRA_KEY_EVENT);
if (ev.getAction() == KeyEvent.ACTION_UP) {
// Only perform the action on keydown/multiple
return;
}
switch (ev.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_NEXT:
LibreDroid.this.libreServiceConn.service.next();
this.abortBroadcast();
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
LibreDroid.this.libreServiceConn.service.prev();
this.abortBroadcast();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
LibreDroid.this.togglePause();
this.abortBroadcast();
break;
}
}
}
private class LibreServiceConnection implements ServiceConnection {
public ILibreService service = null;
public void onServiceConnected(ComponentName name, IBinder service) {
this.service = (ILibreService) service;
LibreDroid.this.runOnUiThread(new Runnable() {
public void run() {
final ViewAnimator view = (ViewAnimator) LibreDroid.this.findViewById(R.id.viewAnimator);
view.setDisplayedChild(LibreServiceConnection.this.service.getCurrentPage());
if (LibreServiceConnection.this.service.getCurrentPage() == 2) {
LibreDroid.this.updateSong();
}
}
});
}
public void onServiceDisconnected(ComponentName name) {
}
}
} |
package gov.nih.nci.calab.dto.particle;
import gov.nih.nci.calab.domain.Keyword;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.function.Function;
import gov.nih.nci.calab.domain.nano.particle.Nanoparticle;
import gov.nih.nci.calab.dto.inventory.SampleBean;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* This class represents shared properties of nanoparticles to be shown in the
* view page.
*
* @author pansu
*
*/
public class ParticleBean extends SampleBean {
private String particleClassification;
private String[] functionTypes;
private String[] characterizations;
private String[] keywords;
private String[] visibilityGroups;
private String gridNode;
public ParticleBean(String id, String name) {
super(id, name);
}
public ParticleBean() {
}
public ParticleBean(String id, String name, String particleSource,
String particleType, String particleClassification,
String[] functionTypes, String[] characterizations,
String[] keywords) {
this(id, name);
setSampleType(particleType);
setSampleSource(particleSource);
this.particleClassification = particleClassification;
this.functionTypes = functionTypes;
this.characterizations = characterizations;
this.keywords = keywords;
}
public ParticleBean(Nanoparticle particle) {
this(particle.getId().toString(), particle.getName());
this.setSampleType(particle.getType());
this.setSampleSource(particle.getSource().getOrganizationName());
if (particle.getSource() != null) {
this.setSampleSource(particle.getSource().getOrganizationName());
} else {
this.setSampleSource("");
}
this.particleClassification = particle.getClassification();
Collection<Keyword> keywordCol = particle.getKeywordCollection();
// get a unique set of keywords
SortedSet<String> keywordSet = new TreeSet<String>();
for (Keyword keywordObj : keywordCol) {
keywordSet.add(keywordObj.getName());
}
keywords = keywordSet.toArray(new String[0]);
Collection<Characterization> characterizationCol = particle
.getCharacterizationCollection();
// get a unique list of characterization
Set<String> charcterizationSet = new HashSet<String>();
for (Characterization charObj : characterizationCol) {
charcterizationSet.add(charObj.getClassification() + ":"
+ charObj.getName());
}
characterizations = charcterizationSet.toArray(new String[0]);
Collection<Function> functionCol = particle.getFunctionCollection();
// get a unique list of function
Set<String> functionTypeSet = new HashSet<String>();
for (Function funcObj : functionCol) {
functionTypeSet.add(funcObj.getType());
}
functionTypes = functionTypeSet.toArray(new String[0]);
}
public ParticleBean(Nanoparticle particle, String gridNode) {
this(particle);
this.gridNode = gridNode;
}
public String[] getCharacterizations() {
return characterizations;
}
public void setCharacterizations(String[] characterizations) {
this.characterizations = characterizations;
}
public String[] getFunctionTypes() {
return functionTypes;
}
public void setFunctionTypes(String[] functionTypes) {
this.functionTypes = functionTypes;
}
public String[] getKeywords() {
return keywords;
}
public void setKeywords(String[] keywords) {
this.keywords = keywords;
}
public String getParticleClassification() {
return particleClassification;
}
public void setParticleClassification(String particleClassification) {
this.particleClassification = particleClassification;
}
public String[] getVisibilityGroups() {
return visibilityGroups;
}
public void setVisibilityGroups(String[] visibilityGroups) {
this.visibilityGroups = visibilityGroups;
}
public String getGridNode() {
return gridNode;
}
public void setGridNode(String gridNode) {
this.gridNode = gridNode;
}
} |
package gov.nih.nci.calab.ui.core;
/**
* This class initializes session data to prepopulate the drop-down lists required
* in different view pages.
*
* @author pansu
*/
/* CVS $Id: InitSessionAction.java,v 1.14 2006-04-17 21:23:18 thangars Exp $ */
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
import gov.nih.nci.calab.dto.security.SecurityBean;
import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean;
import gov.nih.nci.calab.service.administration.ManageAliquotService;
import gov.nih.nci.calab.service.administration.ManageSampleService;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.search.SearchSampleService;
import gov.nih.nci.calab.service.search.SearchWorkflowService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
public class InitSessionAction extends AbstractBaseAction {
private static Logger logger = Logger.getLogger(InitSessionAction.class);
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
ActionForward forward = null;
String forwardPage = null;
String urlPrefix = request.getContextPath();
try {
DynaActionForm theForm = (DynaActionForm) form;
forwardPage = (String) theForm.get("forwardPage");
// retrieve from sesssion first if available assuming these values
// are not likely to change within the same session. If changed, the
// session should be updated.
LookupService lookupService = new LookupService();
if (forwardPage.equals("useAliquot")) {
String runId = (String) request.getParameter("runId");
session.setAttribute("runId", runId);
setUseAliquotSession(session, lookupService);
} else if (forwardPage.equals("createSample")) {
setCreateSampleSession(session, lookupService);
} else if (forwardPage.equals("createAliquot")) {
setCreateAliquotSession(session, lookupService, urlPrefix);
} else if (forwardPage.equals("searchWorkflow")) {
setSearchWorkflowSession(session, lookupService);
} else if (forwardPage.equals("searchSample")) {
setSearchSampleSession(session, lookupService);
} else if (forwardPage.equals("createRun")) {
setCreateRunSession(session, lookupService);
}
// get user and date information
String creator = "";
if (session.getAttribute("user") != null) {
SecurityBean user = (SecurityBean) session.getAttribute("user");
creator = user.getLoginId();
}
String creationDate = StringUtils.convertDateToString(new Date(),
CalabConstants.DATE_FORMAT);
session.setAttribute("creator", creator);
session.setAttribute("creationDate", creationDate);
forward = mapping.findForward(forwardPage);
} catch (Exception e) {
ActionMessages errors = new ActionMessages();
ActionMessage error = new ActionMessage("error.initSession",
forwardPage);
errors.add("error", error);
saveMessages(request, errors);
logger.error(
"Caught exception loading initial drop-down lists data", e);
forward = mapping.getInputForward();
}
return forward;
}
public boolean loginRequired() {
return true;
}
/**
* Set up session attributes for use aliquot page
*
* @param session
* @param lookupService
*/
private void setUseAliquotSession(HttpSession session,
LookupService lookupService) throws Exception {
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List<AliquotBean> allAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", allAliquots);
}
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
// clear the new aliquot created flag
session.removeAttribute("newAliquotCreated");
// clear the new workflow created flag
session.removeAttribute("newWorkflowCreated");
}
/**
* Set up session attributes for create sample page
*
* @param session
* @param lookupService
*/
private void setCreateSampleSession(HttpSession session,
LookupService lookupService) {
ManageSampleService mangeSampleService = new ManageSampleService();
// if values don't exist in the database or if no new samples created.
// call the service
if (session.getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.setAttribute("allSampleTypes", sampleTypes);
}
if (session.getAttribute("allSampleSOPs") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSOPs = mangeSampleService.getAllSampleSOPs();
session.setAttribute("allSampleSOPs", sampleSOPs);
}
if (session.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
// clear the form in the session
if (session.getAttribute("createSampleForm") != null
|| session.getAttribute("newSampleCreated") != null) {
session.removeAttribute("createSampleForm");
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
/**
* Set up session attributes for create aliquot page
*
* @param session
* @param lookupService
*/
private void setCreateAliquotSession(HttpSession session,
LookupService lookupService, String urlPrefix) {
ManageAliquotService manageAliquotService = new ManageAliquotService();
if (session.getAttribute("allSamples") == null
|| session.getAttribute("newSampleCreated") != null) {
List samples = lookupService.getAllSamples();
session.setAttribute("allSamples", samples);
}
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", aliquots);
}
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotCreateMethods") == null) {
List methods = manageAliquotService
.getAliquotCreateMethods(urlPrefix);
session.setAttribute("aliquotCreateMethods", methods);
}
// clear the form in the session
if (session.getAttribute("createAliquotForm") != null) {
session.removeAttribute("createAliquotForm");
}
if (session.getAttribute("aliquotMatrix") != null) {
session.removeAttribute("aliquotMatrix");
}
// clear new aliquot created flag and new sample created flag
session.removeAttribute("newAliquotCreated");
session.removeAttribute("newSampleCreated");
}
/**
* Set up session attributes for search workflow page
*
* @param session
* @param lookupService
*/
private void setSearchWorkflowSession(HttpSession session,
LookupService lookupService) {
SearchWorkflowService searchWorkflowService = new SearchWorkflowService();
if (session.getAttribute("allUnmaskedAliquots") == null) {
List<AliquotBean> allAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", allAliquots);
}
if (session.getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.setAttribute("allAssayTypes", assayTypes);
}
if (session.getAttribute("allFileSubmitters") == null) {
List submitters = searchWorkflowService.getAllFileSubmitters();
session.setAttribute("allFileSubmitters", submitters);
}
}
/**
* Set up session attributes for search sample page
*
* @param session
* @param lookupService
*/
private void setSearchSampleSession(HttpSession session,
LookupService lookupService) {
SearchSampleService searchSampleService = new SearchSampleService();
if (session.getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.setAttribute("allSampleTypes", sampleTypes);
}
if (session.getAttribute("allSampleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSources = searchSampleService.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
if (session.getAttribute("allSourceSampleIds") == null
|| session.getAttribute("newSampleCreated") != null) {
List sourceSampleIds = searchSampleService.getAllSourceSampleIds();
session.setAttribute("allSourceSampleIds", sourceSampleIds);
}
if (session.getAttribute("allSampleSubmitters") == null
|| session.getAttribute("newSampleCreated") != null) {
List submitters = searchSampleService.getAllSampleSubmitters();
session.setAttribute("allSampleSubmitters", submitters);
}
if (session.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
// clear new aliquot created flag and new sample created flag
session.removeAttribute("newAliquotCreated");
session.removeAttribute("newSampleCreated");
// clear session attributes created during search sample
session.removeAttribute("samples");
session.removeAttribute("aliquots");
}
/**
* Set up session attributes for create Run
*
* @param session
* @param lookupService
*/
private void setCreateRunSession(HttpSession session,
LookupService lookupService) throws Exception {
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.setAttribute("allAssayTypes", assayTypes);
}
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
if (session.getAttribute("allAvailableAliquots") == null) {
List<AliquotBean> allAvailableAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allAvailableAliquots", allAvailableAliquots);
}
if (session.getAttribute("allAssignedAliquots") == null) {
List allAssignedAliquots = lookupService.getAllAssignedAliquots();
session.setAttribute("allAssignedAliquots", allAssignedAliquots);
}
if (session.getAttribute("allInFiles") == null) {
List allInFiles = lookupService.getAllInFiles();
session.setAttribute("allInFiles", allInFiles);
}
if (session.getAttribute("allOutFiles") == null) {
List allOutFiles = lookupService.getAllOutFiles();
session.setAttribute("allOutFiles", allOutFiles);
}
if (session.getAttribute("allAssayBeans") == null) {
List allAssayBeans = lookupService.getAllAssayBeans();
session.setAttribute("allAssayBeans", allAssayBeans);
}
// clear the new workflow created flag
session.removeAttribute("newWorkflowCreated");
}
} |
package gov.nih.nci.calab.ui.core;
/**
* This class initializes session and application scope data to prepopulate the drop-down lists required
* in different view pages.
*
* @author pansu
*/
/* CVS $Id: InitSessionAction.java,v 1.40 2006-05-08 15:11:58 pansu Exp $ */
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean;
import gov.nih.nci.calab.service.administration.ManageAliquotService;
import gov.nih.nci.calab.service.administration.ManageSampleService;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.search.SearchSampleService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.util.file.HttpFileUploadSessionData;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class InitSessionAction extends AbstractDispatchAction {
public ActionForward createRun(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "createRun");
setCreateRunSession(request);
return mapping.findForward("createRun");
}
public ActionForward createAssayRun(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "createAssayRun");
setCreateRunSession(request);
return mapping.findForward("createAssayRun");
}
private void setCreateRunSession(HttpServletRequest request)
throws Exception {
HttpSession session = request.getSession();
LookupService lookupService = new LookupService();
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getServletContext().getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.getServletContext().setAttribute("allAssayTypes",
assayTypes);
}
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService
.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", aliquots);
}
if (session.getAttribute("allAssignedAliquots") == null) {
List allAssignedAliquots = lookupService.getAllAssignedAliquots();
session.setAttribute("allAssignedAliquots", allAssignedAliquots);
}
if (session.getServletContext().getAttribute("allAssayBeans") == null) {
List allAssayBeans = lookupService.getAllAssayBeans();
session.getServletContext().setAttribute("allAssayBeans",
allAssayBeans);
}
if (session.getServletContext().getAttribute("allUserBeans") == null) {
List allUserBeans = lookupService.getAllUserBeans();
session.getServletContext().setAttribute("allUserBeans",
allUserBeans);
}
session.removeAttribute("newWorkflowCreated");
session.removeAttribute("newAliquotCreated");
}
public ActionForward useAliquot(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "useAliquot");
HttpSession session = request.getSession();
LookupService lookupService = new LookupService();
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List<AliquotBean> allAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", allAliquots);
}
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService
.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
// clear the new aliquote created flag
session.removeAttribute("newAliquotCreated");
// clear the new workflow created flag
session.removeAttribute("newWorkflowcreated");
return mapping.findForward("useAliquot");
}
public ActionForward createSample(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "createSample");
HttpSession session = request.getSession();
LookupService lookupService = new LookupService();
ManageSampleService mangeSampleService = new ManageSampleService();
// if values don't exist in the database or if no new samples created.
// call the service
if (session.getAttribute("allSampleContainerTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List containerTypes = lookupService.getAllSampleContainerTypes();
session.setAttribute("allSampleContainerTypes", containerTypes);
}
if (session.getServletContext().getAttribute("allSampleTypes") == null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.getServletContext().setAttribute("allSampleTypes",
sampleTypes);
}
if (session.getServletContext().getAttribute("allSampleSOPs") == null) {
List sampleSOPs = mangeSampleService.getAllSampleSOPs();
session.getServletContext().setAttribute("allSampleSOPs",
sampleSOPs);
}
if (session.getServletContext().getAttribute("sampleContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.getServletContext().setAttribute("sampleContainerInfo",
containerInfo);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
return mapping.findForward("createSample");
}
public ActionForward createAliquot(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "createAliquot");
HttpSession session = request.getSession();
LookupService lookupService = new LookupService();
ManageAliquotService manageAliquotService = new ManageAliquotService();
if (session.getAttribute("allSamples") == null
|| session.getAttribute("newSampleCreated") != null) {
List samples = lookupService.getAllSamples();
session.setAttribute("allSamples", samples);
}
if (session.getAttribute("allAliquotContainerTypes") == null
|| session.getAttribute("newAliquotCreated") != null) {
List containerTypes = lookupService.getAllAliquotContainerTypes();
session.setAttribute("allAliquotContainerTypes", containerTypes);
}
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", aliquots);
}
if (session.getServletContext().getAttribute("aliquotContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.getServletContext().setAttribute("aliquotContainerInfo",
containerInfo);
}
if (session.getServletContext().getAttribute("aliquotCreateMethods") == null) {
List methods = manageAliquotService.getAliquotCreateMethods();
session.getServletContext().setAttribute("aliquotCreateMethods",
methods);
}
// clear new aliquot created flag and new sample created flag
session.removeAttribute("newAliquotCreated");
session.removeAttribute("newSampleCreated");
return mapping.findForward("createAliquot");
}
public ActionForward searchWorkflow(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "searchWorkflow");
HttpSession session = request.getSession();
LookupService lookupService = new LookupService();
if (session.getServletContext().getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.getServletContext().setAttribute("allAssayTypes",
assayTypes);
}
if (session.getServletContext().getAttribute("allUserBeans") == null) {
List allUserBeans = lookupService.getAllUserBeans();
session.getServletContext().setAttribute("allUserBeans",
allUserBeans);
}
return mapping.findForward("searchWorkflow");
}
public ActionForward searchSample(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "searchSample");
HttpSession session = request.getSession();
LookupService lookupService = new LookupService();
SearchSampleService searchSampleService = new SearchSampleService();
if (session.getServletContext().getAttribute("allSampleTypes") == null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.getServletContext().setAttribute("allSampleTypes",
sampleTypes);
}
if (session.getAttribute("allSampleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSources = searchSampleService.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
if (session.getAttribute("allSourceSampleIds") == null
|| session.getAttribute("newSampleCreated") != null) {
List sourceSampleIds = searchSampleService.getAllSourceSampleIds();
session.setAttribute("allSourceSampleIds", sourceSampleIds);
}
if (session.getServletContext().getAttribute("allUserBeans") == null) {
List allUserBeans = lookupService.getAllUserBeans();
session.getServletContext().setAttribute("allUserBeans",
allUserBeans);
}
if (session.getServletContext().getAttribute("sampleContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.getServletContext().setAttribute("sampleContainerInfo",
containerInfo);
}
if (session.getServletContext().getAttribute("aliquotContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.getServletContext().setAttribute("aliquotContainerInfo",
containerInfo);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
return mapping.findForward("searchSample");
}
public ActionForward workflowMessage(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
clearSessionData(request, "workflowMessage");
setWorkflowMessageSession(request);
return mapping.findForward("workflowMessage");
}
public ActionForward fileUploadOption(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
clearSessionData(request, "fileUploadOption");
setWorkflowMessageSession(request);
return mapping.findForward("fileUploadOption");
}
public ActionForward fileDownload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "fileDownload");
setWorkflowMessageSession(request);
return mapping.findForward("fileDownload");
}
public ActionForward runFileMask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "runFileMask");
setWorkflowMessageSession(request);
return mapping.findForward("runFileMask");
}
public ActionForward uploadForward(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
clearSessionData(request, "uploadForward");
setWorkflowMessageSession(request);
HttpSession session = request.getSession();
// read HttpFileUploadSessionData from session
HttpFileUploadSessionData hFileUploadData = (HttpFileUploadSessionData) request
.getSession().getAttribute("httpFileUploadSessionData");
// based on the type=in/out/upload and runId to modify the
// forwardPage
String type = hFileUploadData.getFromType();
String runId = hFileUploadData.getRunId();
String inout = hFileUploadData.getInout();
String runName = hFileUploadData.getRun();
session.removeAttribute("httpFileUploadSessionData");
String urlPrefix = request.getContextPath();
if (type.equalsIgnoreCase("in") || type.equalsIgnoreCase("out")) {
// cannot forward to a page with the request parameter, so
// use response
response.sendRedirect(urlPrefix + "/workflowForward.do?type="
+ type + "&runName=" + runName + "&runId=" + runId
+ "&inout=" + inout);
} else if (type.equalsIgnoreCase("upload")) {
session.setAttribute("runId", runId);
String forwardPage = "fileUploadOption";
return mapping.findForward(forwardPage);
}
return null;
}
private void setWorkflowMessageSession(HttpServletRequest request)
throws Exception {
HttpSession session = request.getSession();
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService
.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
session.removeAttribute("newWorkflowCreated");
}
public boolean loginRequired() {
return true;
}
private void clearSessionData(HttpServletRequest request, String forwardPage) {
HttpSession session = request.getSession();
if (!forwardPage.equals("createAliquot")) {
// clear session attributes created during create aliquot
session.removeAttribute("allSamples");
session.removeAttribute("allAliquotContainerTypes");
}
session.removeAttribute("aliquotMatrix");
session.removeAttribute("createAliquotForm");
session.removeAttribute("createSampleForm");
//add a request parameter so the back button from search results don't clear the forms
if (request.getParameter("rememberSearch")==null) {
session.removeAttribute("searchSampleForm");
session.removeAttribute("searchWorkflowForm");
}
if (!forwardPage.equals("createSample")) {
// clear session attributes created during create sample
session.removeAttribute("allSampleContainerTypes");
}
if (!forwardPage.equals("searchSample")) {
// clear session attributes created during search sample
session.removeAttribute("samples");
session.removeAttribute("aliquots");
}
if (!forwardPage.equals("uploadForward")) {
// clear session attributes creatd during fileUpload
session.removeAttribute("httpFileUploadSessionData");
}
if (forwardPage.equals("createSample")
|| forwardPage.equals("createAliquot")
|| forwardPage.equals("searchSample")
|| forwardPage.equals("searchWorkflow")) {
// clear session attributes created during execute workflow pages
session.removeAttribute("workflow");
}
// get user and date information
String creator = "";
if (session.getAttribute("user") != null) {
UserBean user = (UserBean) session.getAttribute("user");
creator = user.getLoginId();
}
String creationDate = StringUtils.convertDateToString(new Date(),
CalabConstants.DATE_FORMAT);
session.setAttribute("creator", creator);
session.setAttribute("creationDate", creationDate);
}
} |
package com.hockeyhurd.hcorelib.api.client.gui;
import com.hockeyhurd.hcorelib.api.math.Color4f;
import com.hockeyhurd.hcorelib.api.math.Rect;
import com.hockeyhurd.hcorelib.api.math.Vector2;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
/**
* Gui helper class.
*
* @author hockeyhurd
* @version 5/25/2016.
*/
@SideOnly(Side.CLIENT)
public final class GuiHelper {
private static final Minecraft minecraft = Minecraft.getMinecraft();
private static final TextureManager textureManager = minecraft.getTextureManager();
public static final Color4f DEFAULT_COL = new Color4f(1.0f, 1.0f, 1.0f, 1.0f);
private GuiHelper() {
}
/**
* Binds resourece to texture manager.
*
* @param resourceLocation ResourceLocation.
* @return boolean result.
*/
public static boolean bindTexture(ResourceLocation resourceLocation) {
if (resourceLocation == null) return false;
textureManager.bindTexture(resourceLocation);
return true;
}
/**
* Handles commong initialization of GlStateManager.
*
* @see net.minecraft.client.renderer.GlStateManager
*
* @param resourceLocation ResourceLocation.
* @param r red.
* @param g green.
* @param b blue.
* @param a alpha.
*/
public static void preRenderInit(ResourceLocation resourceLocation, float r, float g, float b, float a) {
if (!bindTexture(resourceLocation)) return;
GlStateManager.color(r, g, b, a);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA,
GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
}
/**
* Handles commong initialization of GlStateManager.
*
* @see net.minecraft.client.renderer.GlStateManager
*
* @param resourceLocation ResourceLocation.
* @param color4f Color4f color.
*/
public static void preRenderInit(ResourceLocation resourceLocation, Color4f color4f) {
if (!bindTexture(resourceLocation) || color4f == null) return;
GlStateManager.color(color4f.getR(), color4f.getG(), color4f.getB(), color4f.getA());
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA,
GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
}
/**
* Attempts to draw model rectangle.
*
* @param xp x-position.
* @param yp y-position.
* @param minU float.
* @param minV float.
* @param width int.
* @param height int.
* @param maxU float.
* @param maxV float.
*/
public static void drawModelRect(int xp, int yp, float minU, float minV, int width, int height, float maxU, float maxV) {
Gui.drawModalRectWithCustomSizedTexture(xp, yp, minU, minV, width, height, maxU, maxV);
}
/**
* Attempts to draw model rectangle.
*
* @param vec Vector2i position.
* @param rect Rectangle to render.
*/
public static void drawModelRect(Vector2<Integer> vec, Rect<Integer> rect) {
// gui.drawTexturedModalRect(vec.x, vec.y, rect.min.x, rect.min.y, rect.max.x, rect.max.y);
Gui.drawModalRectWithCustomSizedTexture(vec.x, vec.y, (float) rect.min.x, (float) rect.min.y, rect.max.x, rect.max.y,
(float) rect.max.x, (float) rect.max.y);
}
/**
* Handles generic set-up of GlStateManager and renders model rectangle.
*
* @see net.minecraft.client.renderer.GlStateManager
*
* @param resourceLocation ResourceLocation.
* @param color4f Color4f color.
* @param xp x-position.
* @param yp y-position.
* @param minU float.
* @param minV float.
* @param maxU float.
* @param maxV float.
*/
public static void simpleRenderGui(ResourceLocation resourceLocation, Color4f color4f, int xp, int yp,
float minU, float minV, float maxU, float maxV) {
GL11.glPushMatrix();
preRenderInit(resourceLocation, color4f);
drawModelRect(xp, yp, minU, minV, (int) maxU, (int) maxV, maxU, maxV);
GL11.glPopMatrix();
}
/**
* Handles generic set-up of GlStateManager and renders model rectangle.
*
* @see net.minecraft.client.renderer.GlStateManager
*
* @param resourceLocation ResourceLocation.
* @param color4f Color4f color.
* @param vec Vector2i positon.
* @param rect Rectangle to render.
*/
public static void simpleRenderGui(ResourceLocation resourceLocation, Color4f color4f, Vector2<Integer> vec, Rect<Integer> rect) {
preRenderInit(resourceLocation, color4f);
drawModelRect(vec, rect);
}
/**
* Handles generic set-up of GlStateManager and renders model rectangle.
*
* @see net.minecraft.client.renderer.GlStateManager
*
* @param resourceLocation ResourceLocation.
* @param color4f Color4g color.
* @param xp int.
* @param yp int.
* @param minU float.
* @param minV float.
* @param width int.
* @param height int.
* @param maxU float.
* @param maxV float.
*/
public static void simpleRenderGui(ResourceLocation resourceLocation, Color4f color4f, int xp, int yp,
float minU, float minV, int width, int height, float maxU, float maxV) {
preRenderInit(resourceLocation, color4f);
drawModelRect(xp, yp, minU, minV, width, height, maxU, maxV);
}
} |
package ie.lero.evoting.test.data;
import java.util.ArrayList;
import election.tally.AbstractBallotCounting;
import election.tally.AbstractCountStatus;
import election.tally.Ballot;
import election.tally.BallotBox;
import election.tally.BallotCounting;
import election.tally.Candidate;
import election.tally.Constituency;
import election.tally.Decision;
public class TestDataGenerator {
// Singletons
private static final BallotCounting BALLOT_COUNTING = new BallotCounting();
private static final BallotBox BALLOT_BOX = new BallotBox();
// Dynamic Arrays
static ArrayList<Candidate> candidateList = new ArrayList<Candidate>();
public static AbstractBallotCounting getAbstractBallotCounting(int n) {
return BALLOT_COUNTING;
}
public static byte[] getByteArray() {
return new byte[0];
}
public static Constituency getConstituency(int n) {
return new Constituency();
}
public static Ballot getBallot(int preferenceID) {
int[] list = new int[1];
list[0] = preferenceID;
return new Ballot(list);
}
public static Candidate getCandidate(int n) {
while (candidateList.size() < n) {
candidateList.add(new Candidate());
}
return candidateList.get(n);
}
public static BallotBox getBallotBox(int n) {
// default
return BALLOT_BOX;
}
public static int[] getIntArray() {
return new int[0];
}
public static long[] getLongArray() {
return new long[0];
}
public static Decision getDecision(int n) {
final Decision decision = new Decision();
switch (n) {
case 1: decision.setDecisionType(Decision.DEEM_ELECTED);
case 2: decision.setDecisionType(Decision.EXCLUDE); break;
default: decision.setDecisionType(Decision.NO_DECISION);
}
decision.setCountNumber(n);
decision.setCandidate(getCandidate(n).getCandidateID());
return decision;
}
public static BallotCounting getBallotCounting(int n) {
// default
return BALLOT_COUNTING;
}
public static Object[] getIntArrayAsObject() {
final Object[] intArray = new Object[0];
return intArray;
}
public static AbstractCountStatus getAbstractCountStatus(int n) {
// default
return BALLOT_COUNTING.getCountStatus();
}
} |
package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.bll.memory.LiveSnapshotMemoryImageBuilder;
import org.ovirt.engine.core.bll.memory.MemoryImageBuilder;
import org.ovirt.engine.core.bll.memory.MemoryStorageHandler;
import org.ovirt.engine.core.bll.memory.MemoryUtils;
import org.ovirt.engine.core.bll.memory.NullableMemoryImageBuilder;
import org.ovirt.engine.core.bll.memory.StatelessSnapshotMemoryImageBuilder;
import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter;
import org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter;
import org.ovirt.engine.core.bll.quota.QuotaStorageDependent;
import org.ovirt.engine.core.bll.snapshots.SnapshotsManager;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.tasks.CommandCoordinatorUtil;
import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand;
import org.ovirt.engine.core.bll.validator.LiveSnapshotValidator;
import org.ovirt.engine.core.bll.validator.VmValidator;
import org.ovirt.engine.core.bll.validator.storage.CinderDisksValidator;
import org.ovirt.engine.core.bll.validator.storage.DiskImagesValidator;
import org.ovirt.engine.core.bll.validator.storage.MultipleStorageDomainsValidator;
import org.ovirt.engine.core.bll.validator.storage.StoragePoolValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.CreateAllSnapshotsFromVmParameters;
import org.ovirt.engine.core.common.action.ImagesActionsParametersBase;
import org.ovirt.engine.core.common.action.ImagesContainterParametersBase;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.RemoveMemoryVolumesParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.asynctasks.AsyncTaskCreationInfo;
import org.ovirt.engine.core.common.asynctasks.EntityInfo;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.storage.CinderDisk;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskStorageType;
import org.ovirt.engine.core.common.errors.EngineError;
import org.ovirt.engine.core.common.errors.EngineException;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.validation.group.CreateEntity;
import org.ovirt.engine.core.common.vdscommands.SnapshotVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsAndVmIDVDSParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.NotImplementedException;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
@NonTransactiveCommandAttribute(forceCompensation = true)
@DisableInPrepareMode
public class CreateAllSnapshotsFromVmCommand<T extends CreateAllSnapshotsFromVmParameters> extends VmCommand<T> implements QuotaStorageDependent, TaskHandlerCommand<CreateAllSnapshotsFromVmParameters> {
private List<DiskImage> cachedSelectedActiveDisks;
private List<DiskImage> cachedImagesDisks;
private Guid cachedStorageDomainId = Guid.Empty;
private String cachedSnapshotIsBeingTakenMessage;
private Guid newActiveSnapshotId = Guid.newGuid();
private MemoryImageBuilder memoryBuilder;
protected CreateAllSnapshotsFromVmCommand(Guid commandId) {
super(commandId);
}
public CreateAllSnapshotsFromVmCommand(T parameters) {
this(parameters, null);
}
@Override
protected LockProperties applyLockProperties(LockProperties lockProperties) {
return lockProperties.withScope(Scope.Command);
}
public CreateAllSnapshotsFromVmCommand(T parameters, CommandContext commandContext) {
super(parameters, commandContext);
parameters.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVmId()));
setSnapshotName(parameters.getDescription());
setStoragePoolId(getVm() != null ? getVm().getStoragePoolId() : null);
}
@Override
public Map<String, String> getJobMessageProperties() {
if (jobProperties == null) {
jobProperties = super.getJobMessageProperties();
jobProperties.put(VdcObjectType.Snapshot.name().toLowerCase(), getParameters().getDescription());
}
return jobProperties;
}
private List<DiskImage> getDiskImagesForVm() {
List<Disk> disks = DbFacade.getInstance().getDiskDao().getAllForVm(getVmId());
List<DiskImage> allDisks = new ArrayList<>(getDiskImages(disks));
allDisks.addAll(ImagesHandler.getCinderLeafImages(disks, true));
return allDisks;
}
private List<DiskImage> getDiskImages(List<Disk> disks) {
if (cachedImagesDisks == null) {
cachedImagesDisks = ImagesHandler.filterImageDisks(disks, true, true, true);
}
return cachedImagesDisks;
}
/**
* Filter all allowed snapshot disks.
* @return list of disks to be snapshot.
*/
protected List<DiskImage> getDisksList() {
if (cachedSelectedActiveDisks == null) {
List<DiskImage> imagesAndCinderForVm = getDiskImagesForVm();
// Get disks from the specified parameters or according to the VM
if (getParameters().getDisks() == null) {
cachedSelectedActiveDisks = imagesAndCinderForVm;
}
else {
// Get selected images from 'DiskImagesForVm' to ensure disks entities integrity
// (i.e. only images' IDs and Cinders' IDs are relevant).
cachedSelectedActiveDisks = ImagesHandler.imagesIntersection(imagesAndCinderForVm, getParameters().getDisks());
}
}
return cachedSelectedActiveDisks;
}
protected List<DiskImage> getDisksListForChecks() {
List<DiskImage> disksListForChecks = getDisksList();
if (getParameters().getDiskIdsToIgnoreInChecks().isEmpty()) {
return disksListForChecks;
}
List<DiskImage> toReturn = new LinkedList<>();
for (DiskImage diskImage : disksListForChecks) {
if (!getParameters().getDiskIdsToIgnoreInChecks().contains(diskImage.getId())) {
toReturn.add(diskImage);
}
}
return toReturn;
}
protected List<DiskImage> getSnappableVmDisks() {
List<Disk> disks = getDiskDao().getAllForVm(getVm().getId());
return ImagesHandler.filterImageDisks(disks, false, true, false);
}
private boolean validateStorage() {
List<DiskImage> vmDisksList = getSnappableVmDisks();
vmDisksList = ImagesHandler.getDisksDummiesForStorageAllocations(vmDisksList);
List<DiskImage> allDisks = new ArrayList<>(vmDisksList);
List<DiskImage> memoryDisksList = null;
if (getParameters().isSaveMemory()) {
memoryDisksList = MemoryUtils.createDiskDummies(getVm().getTotalMemorySizeInBytes(), MemoryUtils.META_DATA_SIZE_IN_BYTES);
if (Guid.Empty.equals(getStorageDomainIdForVmMemory(memoryDisksList))) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND);
}
allDisks.addAll(memoryDisksList);
}
MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(allDisks);
if (!validate(sdValidator.allDomainsExistAndActive())
|| !validate(sdValidator.allDomainsWithinThresholds())
|| !validateCinder()) {
return false;
}
if (memoryDisksList == null) { //no memory volumes
return validate(sdValidator.allDomainsHaveSpaceForNewDisks(vmDisksList));
}
return validate(sdValidator.allDomainsHaveSpaceForAllDisks(vmDisksList, memoryDisksList));
}
public boolean validateCinder() {
List<CinderDisk> cinderDisks = ImagesHandler.filterDisksBasedOnCinder(DbFacade.getInstance().getDiskDao().getAllForVm(getVmId()));
if (!cinderDisks.isEmpty()) {
CinderDisksValidator cinderDisksValidator = getCinderDisksValidator(cinderDisks);
return validate(cinderDisksValidator.validateCinderDiskSnapshotsLimits());
}
return true;
}
protected CinderDisksValidator getCinderDisksValidator(List<CinderDisk> cinderDisks) {
return new CinderDisksValidator(cinderDisks);
}
protected MemoryImageBuilder getMemoryImageBuilder() {
if (memoryBuilder == null) {
memoryBuilder = createMemoryImageBuilder();
}
return memoryBuilder;
}
private void incrementVmGeneration() {
getVmStaticDao().incrementDbGeneration(getVm().getId());
}
@Override
protected void executeVmCommand() {
getParameters().setSnapshotType(determineSnapshotType());
Guid createdSnapshotId = updateActiveSnapshotId();
setActionReturnValue(createdSnapshotId);
MemoryImageBuilder memoryImageBuilder = getMemoryImageBuilder();
freezeVm();
createSnapshotsForDisks();
addSnapshotToDB(createdSnapshotId, memoryImageBuilder);
fastForwardDisksToActiveSnapshot();
memoryImageBuilder.build();
// means that there are no asynchronous tasks to execute and that we can
// end the command synchronously
boolean pendingAsyncTasks = !getTaskIdList().isEmpty() ||
!CommandCoordinatorUtil.getChildCommandIds(getCommandId()).isEmpty();
if (!pendingAsyncTasks) {
getParameters().setTaskGroupSuccess(true);
incrementVmGeneration();
}
setSucceeded(true);
}
private Guid updateActiveSnapshotId() {
final Snapshot activeSnapshot = getSnapshotDao().get(getVmId(), SnapshotType.ACTIVE);
final Guid activeSnapshotId = activeSnapshot.getId();
TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
getCompensationContext().snapshotEntity(activeSnapshot);
getSnapshotDao().updateId(activeSnapshotId, newActiveSnapshotId);
activeSnapshot.setId(newActiveSnapshotId);
getCompensationContext().snapshotNewEntity(activeSnapshot);
getCompensationContext().stateChanged();
return null;
}
});
return activeSnapshotId;
}
public Guid getStorageDomainIdForVmMemory(List<DiskImage> memoryDisksList) {
if (cachedStorageDomainId.equals(Guid.Empty) && getVm() != null) {
StorageDomain storageDomain = MemoryStorageHandler.getInstance().findStorageDomainForMemory(
getVm().getStoragePoolId(), memoryDisksList, getDisksList(), getVm());
if (storageDomain != null) {
cachedStorageDomainId = storageDomain.getId();
}
}
return cachedStorageDomainId;
}
private MemoryImageBuilder createMemoryImageBuilder() {
if (!isMemorySnapshotSupported()) {
return new NullableMemoryImageBuilder();
}
if (getParameters().getSnapshotType() == SnapshotType.STATELESS) {
return new StatelessSnapshotMemoryImageBuilder(getVm());
}
if (getParameters().isSaveMemory() && isLiveSnapshotApplicable()) {
return new LiveSnapshotMemoryImageBuilder(getVm(), cachedStorageDomainId, getStoragePool(), this);
}
return new NullableMemoryImageBuilder();
}
private Snapshot addSnapshotToDB(Guid snapshotId, MemoryImageBuilder memoryImageBuilder) {
// Reset cachedSelectedActiveDisks so new Cinder volumes can be fetched when calling getDisksList.
cachedSelectedActiveDisks = null;
boolean taskExists = !getDisksList().isEmpty() || memoryImageBuilder.isCreateTasks();
return new SnapshotsManager().addSnapshot(snapshotId,
getParameters().getDescription(),
taskExists ? SnapshotStatus.LOCKED : SnapshotStatus.OK,
getParameters().getSnapshotType(),
getVm(),
true,
memoryImageBuilder.getVolumeStringRepresentation(),
getDisksList(),
getCompensationContext());
}
private void createSnapshotsForDisks() {
for (DiskImage disk : getDisksList()) {
if (disk.getDiskStorageType() == DiskStorageType.CINDER) {
ImagesContainterParametersBase params = buildChildCommandParameters(disk);
params.setQuotaId(disk.getQuotaId());
Future<VdcReturnValueBase> future = CommandCoordinatorUtil.executeAsyncCommand(
VdcActionType.CreateCinderSnapshot,
params,
cloneContextAndDetachFromParent());
try {
VdcReturnValueBase vdcReturnValueBase = future.get();
if (!vdcReturnValueBase.getSucceeded()) {
log.error("Error creating snapshot for Cinder disk '{}'", disk.getDiskAlias());
throw new EngineException(EngineError.CINDER_ERROR, "Failed to create snapshot!");
}
} catch (InterruptedException | ExecutionException e) {
log.error("Error creating snapshot for Cinder disk '{}': {}", disk.getDiskAlias(), e.getMessage());
throw new EngineException(EngineError.CINDER_ERROR, "Failed to create snapshot!");
}
continue;
}
VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction(
VdcActionType.CreateSnapshot,
buildCreateSnapshotParameters(disk),
ExecutionHandler.createDefaultContextForTasks(getContext()));
if (vdcReturnValue.getSucceeded()) {
getTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList());
} else {
throw new EngineException(vdcReturnValue.getFault().getError(),
"Failed to create snapshot!");
}
}
}
private ImagesContainterParametersBase buildChildCommandParameters(DiskImage cinderDisk) {
ImagesContainterParametersBase createParams = new ImagesContainterParametersBase(cinderDisk.getId());
createParams.setVmSnapshotId(newActiveSnapshotId);
createParams.setParentHasTasks(!cachedImagesDisks.isEmpty() || getMemoryImageBuilder().isCreateTasks());
createParams.setDescription(getParameters().getDescription());
return withRootCommandInfo(createParams, getActionType());
}
private void fastForwardDisksToActiveSnapshot() {
if (getParameters().getDisks() != null) {
// Remove disks included in snapshot
List<DiskImage> diskImagesToUpdate = ImagesHandler.imagesSubtract(getDiskImagesForVm(), getParameters().getDisks());
// Fast-forward non-included disks to active snapshot
for (DiskImage diskImage : diskImagesToUpdate) {
getImageDao().updateImageVmSnapshotId(diskImage.getImageId(), newActiveSnapshotId);
}
}
}
private ImagesActionsParametersBase buildCreateSnapshotParameters(DiskImage image) {
VdcActionType parentCommand = getParameters().getParentCommand() != VdcActionType.Unknown ?
getParameters().getParentCommand() : VdcActionType.CreateAllSnapshotsFromVm;
ImagesActionsParametersBase result = new ImagesActionsParametersBase(image.getImageId());
result.setDescription(getParameters().getDescription());
result.setSessionId(getParameters().getSessionId());
result.setQuotaId(image.getQuotaId());
result.setDiskProfileId(image.getDiskProfileId());
result.setVmSnapshotId(newActiveSnapshotId);
result.setEntityInfo(getParameters().getEntityInfo());
result.setParentCommand(parentCommand);
result.setParentParameters(getParametersForTask(parentCommand, getParameters()));
if (getParameters().getDiskIdsToIgnoreInChecks().contains(image.getId())) {
result.setLeaveLocked(true);
}
return result;
}
/**
* @return For internal execution, return the type from parameters, otherwise return {@link SnapshotType#REGULAR}.
*/
protected SnapshotType determineSnapshotType() {
return isInternalExecution() ? getParameters().getSnapshotType() : SnapshotType.REGULAR;
}
@Override
protected void endVmCommand() {
if (CommandCoordinatorUtil.getChildCommandIds(getCommandId()).size() > 1) {
log.info("There are still running CoCo tasks");
return;
}
Snapshot createdSnapshot = getSnapshotDao().get(getVmId(), getParameters().getSnapshotType(), SnapshotStatus.LOCKED);
// if the snapshot was not created in the DB
// the command should also be handled as a failure
boolean taskGroupSucceeded = createdSnapshot != null && getParameters().getTaskGroupSuccess();
boolean liveSnapshotRequired = isLiveSnapshotApplicable();
boolean liveSnapshotSucceeded = false;
if (taskGroupSucceeded) {
getSnapshotDao().updateStatus(createdSnapshot.getId(), SnapshotStatus.OK);
if (liveSnapshotRequired) {
liveSnapshotSucceeded = performLiveSnapshot(createdSnapshot);
} else {
// If the created snapshot contains memory, remove the memory volumes as
// they are not going to be in use since no live snapshot is created
if (getParameters().isSaveMemory() && createdSnapshot.containsMemory()) {
logMemorySavingFailed();
getSnapshotDao().removeMemoryFromSnapshot(createdSnapshot.getId());
removeMemoryVolumesOfSnapshot(createdSnapshot);
}
}
} else {
if (createdSnapshot != null) {
revertToActiveSnapshot(createdSnapshot.getId());
// If the removed snapshot contained memory, remove the memory volumes
// Note that the memory volumes might not have been created
if (getParameters().isSaveMemory() && createdSnapshot.containsMemory()) {
removeMemoryVolumesOfSnapshot(createdSnapshot);
}
} else {
log.warn("No snapshot was created for VM '{}' which is in LOCKED status", getVmId());
}
}
incrementVmGeneration();
thawVm();
endActionOnDisks();
setSucceeded(taskGroupSucceeded && (!liveSnapshotRequired || liveSnapshotSucceeded));
getReturnValue().setEndActionTryAgain(false);
}
private void logMemorySavingFailed() {
addCustomValue("SnapshotName", getSnapshotName());
addCustomValue("VmName", getVmName());
auditLogDirector.log(this, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_NO_MEMORY_FAILURE);
}
private void removeMemoryVolumesOfSnapshot(Snapshot snapshot) {
VdcReturnValueBase retVal = runInternalAction(
VdcActionType.RemoveMemoryVolumes,
new RemoveMemoryVolumesParameters(snapshot.getMemoryVolume(), getVmId()), cloneContextAndDetachFromParent());
if (!retVal.getSucceeded()) {
log.error("Failed to remove memory volumes of snapshot '{}' ({})",
snapshot.getDescription(), snapshot.getId());
}
}
protected boolean isLiveSnapshotApplicable() {
return getParameters().getParentCommand() != VdcActionType.RunVm && getVm() != null
&& (getVm().isRunning() || getVm().getStatus() == VMStatus.Paused) && getVm().getRunOnVds() != null;
}
@Override
protected List<VdcActionParametersBase> getParametersForChildCommand() {
List<VdcActionParametersBase> sortedList = getParameters().getImagesParameters();
Collections.sort(sortedList, new Comparator<VdcActionParametersBase>() {
@Override
public int compare(VdcActionParametersBase o1, VdcActionParametersBase o2) {
if (o1 instanceof ImagesActionsParametersBase && o2 instanceof ImagesActionsParametersBase) {
return ((ImagesActionsParametersBase) o1).getDestinationImageId()
.compareTo(((ImagesActionsParametersBase) o2).getDestinationImageId());
}
return 0;
}
});
return sortedList;
}
/**
* Perform live snapshot on the host that the VM is running on. If the snapshot fails, and the error is
* unrecoverable then the {@link CreateAllSnapshotsFromVmParameters#getTaskGroupSuccess()} will return false.
*
* @param snapshot
* Snapshot to revert to being active, in case of rollback.
*/
protected boolean performLiveSnapshot(final Snapshot snapshot) {
try {
TransactionSupport.executeInScope(TransactionScopeOption.Suppress, new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
runVdsCommand(VDSCommandType.Snapshot, buildLiveSnapshotParameters(snapshot));
return null;
}
});
} catch (EngineException e) {
handleVdsLiveSnapshotFailure(e);
return false;
}
return true;
}
private SnapshotVDSCommandParameters buildLiveSnapshotParameters(Snapshot snapshot) {
List<Disk> pluggedDisksForVm = getDiskDao().getAllForVm(getVm().getId(), true);
List<DiskImage> filteredPluggedDisksForVm = ImagesHandler.filterImageDisks(pluggedDisksForVm, false, true, true);
// 'filteredPluggedDisks' should contain only disks from 'getDisksList()' that are plugged to the VM.
List<DiskImage> filteredPluggedDisks = ImagesHandler.imagesIntersection(filteredPluggedDisksForVm, getDisksList());
SnapshotVDSCommandParameters parameters = new SnapshotVDSCommandParameters(
getVm().getRunOnVds(), getVm().getId(), filteredPluggedDisks);
if (isMemorySnapshotSupported()) {
parameters.setMemoryVolume(snapshot.getMemoryVolume());
}
parameters.setVmFrozen(shouldFreezeOrThawVm());
return parameters;
}
/**
* Check if Memory Snapshot is supported
* @return
*/
private boolean isMemorySnapshotSupported () {
return FeatureSupported.memorySnapshot(getVm().getVdsGroupCompatibilityVersion())
&& FeatureSupported.isMemorySnapshotSupportedByArchitecture(getVm().getClusterArch(), getVm().getVdsGroupCompatibilityVersion());
}
/**
* Freezing the VM is needed for live snapshot with Cinder disks.
*/
private void freezeVm() {
if (!shouldFreezeOrThawVm()) {
return;
}
VDSReturnValue returnValue;
try {
auditLogDirector.log(this, AuditLogType.FREEZE_VM_INITIATED);
returnValue = runVdsCommand(VDSCommandType.Freeze, new VdsAndVmIDVDSParametersBase(
getVds().getId(), getVmId()));
} catch (EngineException e) {
handleFreezeVmFailure(e);
return;
}
if (returnValue.getSucceeded()) {
auditLogDirector.log(this, AuditLogType.FREEZE_VM_SUCCESS);
} else {
handleFreezeVmFailure(new EngineException(EngineError.freezeErr));
}
}
/**
* VM thaw is needed if the VM was frozen.
*/
private void thawVm() {
if (!shouldFreezeOrThawVm()) {
return;
}
VDSReturnValue returnValue;
try {
returnValue = runVdsCommand(VDSCommandType.Thaw, new VdsAndVmIDVDSParametersBase(
getVds().getId(), getVmId()));
} catch (EngineException e) {
handleThawVmFailure(e);
return;
}
if (!returnValue.getSucceeded()) {
handleThawVmFailure(new EngineException(EngineError.thawErr));
}
}
private boolean shouldFreezeOrThawVm() {
return isLiveSnapshotApplicable() && isCinderDisksExist();
}
private boolean isCinderDisksExist() {
return !ImagesHandler.filterDisksBasedOnCinder(getDisksList()).isEmpty();
}
private void handleVmFailure(EngineException e, AuditLogType auditLogType, String warnMessage) {
log.warn(warnMessage, e.getMessage());
log.debug("Exception", e);
addCustomValue("SnapshotName", getSnapshotName());
addCustomValue("VmName", getVmName());
updateCallStackFromThrowable(e);
auditLogDirector.log(this, auditLogType);
}
private void handleVdsLiveSnapshotFailure(EngineException e) {
handleVmFailure(e, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE,
"Could not perform live snapshot due to error, VM will still be configured to the new created"
+ " snapshot: {}");
}
private void handleFreezeVmFailure(EngineException e) {
handleVmFailure(e, AuditLogType.FAILED_TO_FREEZE_VM,
"Could not freeze VM guest filesystems due to an error: {}");
}
private void handleThawVmFailure(EngineException e) {
handleVmFailure(e, AuditLogType.FAILED_TO_THAW_VM,
"Could not thaw VM guest filesystems due to an error: {}");
}
/**
* Return the given snapshot ID's snapshot to be the active snapshot. The snapshot with the given ID is removed
* in the process.
*
* @param createdSnapshotId
* The snapshot ID to return to being active.
*/
protected void revertToActiveSnapshot(Guid createdSnapshotId) {
if (createdSnapshotId != null) {
getSnapshotDao().remove(createdSnapshotId);
getSnapshotDao().updateId(getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE), createdSnapshotId);
}
setSucceeded(false);
}
@Override
public AuditLogType getAuditLogTypeValue() {
switch (getActionState()) {
case EXECUTE:
return getSucceeded() ? AuditLogType.USER_CREATE_SNAPSHOT : AuditLogType.USER_FAILED_CREATE_SNAPSHOT;
case END_SUCCESS:
return getSucceeded() ? AuditLogType.USER_CREATE_SNAPSHOT_FINISHED_SUCCESS
: AuditLogType.USER_CREATE_SNAPSHOT_FINISHED_FAILURE;
default:
return AuditLogType.USER_CREATE_SNAPSHOT_FINISHED_FAILURE;
}
}
@Override
protected boolean canDoAction() {
if (getVm() == null) {
addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND);
return false;
}
if (!canRunActionOnNonManagedVm()) {
return false;
}
if (!isSpecifiedDisksExist(getParameters().getDisks())) {
return false;
}
// Initialize validators.
VmValidator vmValidator = createVmValidator();
SnapshotsValidator snapshotValidator = createSnapshotValidator();
StoragePoolValidator spValidator = createStoragePoolValidator();
if (!(validateVM(vmValidator) && validate(spValidator.isUp())
&& validate(vmValidator.vmNotIlegal())
&& validate(vmValidator.vmNotLocked())
&& validate(snapshotValidator.vmNotDuringSnapshot(getVmId()))
&& validate(snapshotValidator.vmNotInPreview(getVmId()))
&& validate(vmValidator.vmNotDuringMigration())
&& validate(vmValidator.vmNotRunningStateless()))) {
return false;
}
List<DiskImage> disksList = getDisksListForChecks();
if (disksList.size() > 0) {
DiskImagesValidator diskImagesValidator = createDiskImageValidator(disksList);
if (!(validate(diskImagesValidator.diskImagesNotLocked())
&& validate(diskImagesValidator.diskImagesNotIllegal()))) {
return false;
}
}
return validateStorage();
}
protected StoragePoolValidator createStoragePoolValidator() {
return new StoragePoolValidator(getStoragePool());
}
protected SnapshotsValidator createSnapshotValidator() {
return new SnapshotsValidator();
}
protected DiskImagesValidator createDiskImageValidator(List<DiskImage> disksList) {
return new DiskImagesValidator(disksList);
}
protected VmValidator createVmValidator() {
return new VmValidator(getVm());
}
protected boolean validateVM(VmValidator vmValidator) {
LiveSnapshotValidator validator = new LiveSnapshotValidator(getStoragePool().getCompatibilityVersion(), getVds());
return (getVm().isDown() || validate(validator.canDoSnapshot())) &&
validate(vmValidator.vmNotSavingRestoring()) &&
validate(vmValidator.validateVmStatusUsingMatrix(VdcActionType.CreateAllSnapshotsFromVm));
}
private boolean isSpecifiedDisksExist(List<DiskImage> disks) {
if (disks == null || disks.isEmpty()) {
return true;
}
DiskImagesValidator diskImagesValidator = createDiskImageValidator(disks);
if (!validate(diskImagesValidator.diskImagesNotExist())) {
return false;
}
return true;
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(EngineMessage.VAR__ACTION__CREATE);
addCanDoActionMessage(EngineMessage.VAR__TYPE__SNAPSHOT);
}
@Override
protected VdcActionType getChildActionType() {
return VdcActionType.CreateSnapshot;
}
@Override
protected List<Class<?>> getValidationGroups() {
addValidationGroup(CreateEntity.class);
return super.getValidationGroups();
}
@Override
protected Map<String, Pair<String, String>> getExclusiveLocks() {
return getParameters().isNeedsLocking() ?
Collections.singletonMap(getVmId().toString(),
LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, getSnapshotIsBeingTakenForVmMessage()))
: null;
}
private String getSnapshotIsBeingTakenForVmMessage() {
if (cachedSnapshotIsBeingTakenMessage == null) {
StringBuilder builder = new StringBuilder(EngineMessage.ACTION_TYPE_FAILED_SNAPSHOT_IS_BEING_TAKEN_FOR_VM.name());
if (getVmName() != null) {
builder.append(String.format("$VmName %1$s", getVmName()));
}
cachedSnapshotIsBeingTakenMessage = builder.toString();
}
return cachedSnapshotIsBeingTakenMessage;
}
@Override
public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() {
List<QuotaConsumptionParameter> list = new ArrayList<>();
for (DiskImage disk : getDisksList()) {
list.add(new QuotaStorageConsumptionParameter(
disk.getQuotaId(),
null,
QuotaConsumptionParameter.QuotaAction.CONSUME,
disk.getStorageIds().get(0),
disk.getActualSize()));
}
return list;
}
/// TaskHandlerCommand implementation ///
public T getParameters() {
return super.getParameters();
}
public VdcActionType getActionType() {
return super.getActionType();
}
public VdcReturnValueBase getReturnValue() {
return super.getReturnValue();
}
public void preventRollback() {
throw new NotImplementedException();
}
public Guid createTask(Guid taskId,
AsyncTaskCreationInfo asyncTaskCreationInfo,
VdcActionType parentCommand,
VdcObjectType entityType,
Guid... entityIds) {
return super.createTask(taskId,
asyncTaskCreationInfo, parentCommand,
entityType, entityIds);
}
public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand) {
return super.createTask(taskId, asyncTaskCreationInfo, parentCommand);
}
public ArrayList<Guid> getTaskIdList() {
return super.getTaskIdList();
}
@Override
public void taskEndSuccessfully() {
// Not implemented
}
public Guid persistAsyncTaskPlaceHolder() {
return super.persistAsyncTaskPlaceHolder(getActionType());
}
public Guid persistAsyncTaskPlaceHolder(String taskKey) {
return super.persistAsyncTaskPlaceHolder(getActionType(), taskKey);
}
} |
package jade.tools.introspector.gui;
import java.awt.*;
import java.awt.event.*;
import java.net.InetAddress;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import jade.core.AID;
import jade.gui.AgentTreeModel;
import jade.gui.AgentTree;
import jade.domain.introspection.*;
import jade.tools.introspector.Introspector;
/**
This is the main window, containing the agent tree and a
JDesktopPane to whom internal debugging window are added.
@author Andrea Squeri, - Universita` di Parma
*/
public class IntrospectorGUI extends JFrame implements WindowListener {
private Introspector debugger;
private TreePanel panel;
private JDesktopPane desk;
private JSplitPane split;
private JScrollPane scroll;
private JMenuBar bar;
private JMenu menuFile;
private JMenu menuHelp;
private JMenuItem item;
private JMenuItem about;
public IntrospectorGUI(Introspector i) {
debugger = i;
panel = new TreePanel(this);
panel.treeAgent.register("FIPAAGENT", new TreeAgentPopupMenu(debugger), "images/runtree.gif");
panel.treeAgent.register("FIPACONTAINER", null, "images/TreeClosed.gif");
scroll = new JScrollPane();
desk = new JDesktopPane();
split = new JSplitPane();
bar = new JMenuBar();
menuFile = new JMenu();
item = new JMenuItem();
menuHelp = new JMenu();
about = new JMenuItem();
build();
}
public void build(){
String title = debugger.getAID().getName();
this.setTitle(title);
Font f = new Font("Monospaced", 0, 10);
split.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
split.setContinuousLayout(true);
getContentPane().add(split);
menuFile.setText("File");
item.setText("Exit");
menuFile.add(item);
bar.add(menuFile);
this.setJMenuBar(bar);
menuHelp.setText("Help");
about.setText("About");
menuHelp.add(about);
about.setName("about");
bar.add(menuHelp);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exit_actionPerformed(e);
}
});
about.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
about();
}
});
scroll.getViewport().add(desk);
split.add(panel, JSplitPane.LEFT);
split.add(scroll,JSplitPane.RIGHT);
split.setDividerLocation(250);
this.addWindowListener(this);
this.setSize(new Dimension(680, 435));
setVisible(true);
}
void exit_actionPerformed(ActionEvent e){
this.debugger.doDelete();
}
public JDesktopPane getDesktop(){
return desk;
}
// interface WindowListener
public void windowClosing(WindowEvent e){
this.exit_actionPerformed(null);
}
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void showError(String errMsg) {
JOptionPane.showMessageDialog(null, errMsg, "Error in " + debugger.getName(), JOptionPane.ERROR_MESSAGE);
}
public void about(){
AboutBox about = new AboutBox(this,"About Jade Introspector Agent", true);
about.showCorrect();
}
// Methods called by the Introspector agent.
public void messageSent(MainWindow f, SentMessage sm) {
MessagePanel mp = f.getMessagePanel();
SwingUtilities.invokeLater(new TableUpdater(mp, sm));
}
public void messagePosted(MainWindow f, PostedMessage pm) {
MessagePanel mp = f.getMessagePanel();
SwingUtilities.invokeLater(new TableUpdater(mp, pm));
}
public void messageReceived(MainWindow f, ReceivedMessage rm) {
MessagePanel mp = f.getMessagePanel();
SwingUtilities.invokeLater(new TableUpdater(mp, rm));
}
public void changedAgentState(MainWindow f, ChangedAgentState cas) {
StatePanel sp = f.getStatePanel();
SwingUtilities.invokeLater(new StateUpdater(sp, cas));
}
/*
public void messageEvent(MessageEvent e, MainWindow f){
MessagePanel mp=f.getMessagePanel();
EventQueue.invokeLater(new TableUpdater(e, mp));
}
public void stateEvent(StateEvent e,MainWindow f){
StatePanel sp=f.getStatePanel();
EventQueue.invokeLater(new StateUpdater(e,sp));
}
public void behaviourEvent(BehaviourEvent e,MainWindow f){
BehaviourPanel bp=f.getBehaviourPanel();
EventQueue.invokeLater(new TreeUpdater(e,bp));
}
//l'initEvent viene scomposto in tanti eventi
//minori.Questo lo rende + lento ma meno complesso
public void initEvent(InitEvent e,MainWindow f){
Iterator it=e.getAllBehaviours();
BehaviourPanel bp=f.getBehaviourPanel();
while(it.hasNext()){
BehaviourRapp b=(BehaviourRapp)it.next();
BehaviourEvent event=new BehaviourEvent(b,false,true);
EventQueue.invokeLater(new TreeUpdater(event,bp));
}
it=e.getAllinMessages();
MessagePanel mp=f.getMessagePanel();
while(it.hasNext()){
MessageRapp b=(MessageRapp)it.next();
MessageEvent event=new MessageEvent(b,true,true);
EventQueue.invokeLater(new TableUpdater(event,mp));
}
it=e.getAlloutMessages();
while(it.hasNext()){
MessageRapp b=(MessageRapp)it.next();
MessageEvent event=new MessageEvent(b,false,true);
EventQueue.invokeLater(new TableUpdater(event,mp));
}
StateEvent se=new StateEvent(e.getState());
StatePanel sp=f.getStatePanel();
EventQueue.invokeLater(new StateUpdater(se,sp));
}
*/
// Adds a new InternalFrame (MainWindow)
public void addWindow(MainWindow m) {
desk.add(m);
m.setVisible(true);
}
// Shuts down the desktop
public void disposeAsync() {
class disposeIt implements Runnable {
private Window toDispose;
public disposeIt(Window w) {
toDispose = w;
}
public void run() {
toDispose.dispose();
}
}
SwingUtilities.invokeLater(new disposeIt(this));
}
// Shuts down an InternalFrame
public void closeInternal(MainWindow m){
class DisposeItMain implements Runnable{
MainWindow wnd;
DisposeItMain(MainWindow l){
wnd=l;
}
public void run(){
wnd.dispose();
}
}
EventQueue.invokeLater(new DisposeItMain(m));
}
// Methods for AgentTree management
public void addAgent(final String containerName, final AID agentID) {
// Add an agent to the specified container
Runnable addIt = new Runnable() {
public void run() {
String agentName = agentID.getName();
AgentTree.Node node = panel.treeAgent.createNewNode(agentName, 1);
panel.treeAgent.addAgentNode((AgentTree.AgentNode)node, containerName, agentName, "agentAddress", "FIPAAGENT");
}
};
SwingUtilities.invokeLater(addIt);
}
public void removeAgent(final String containerName, final AID agentID) {
// Remove an agent from the specified container
Runnable removeIt = new Runnable() {
public void run() {
String agentName = agentID.getName();
panel.treeAgent.removeAgentNode(containerName, agentName);
}
};
SwingUtilities.invokeLater(removeIt);
}
public AgentTreeModel getModel() {
return panel.treeAgent.getModel();
}
public void addContainer(final String name, final InetAddress addr) {
Runnable addIt = new Runnable() {
public void run() {
MutableTreeNode node = panel.treeAgent.createNewNode(name, 0);
panel.treeAgent.addContainerNode((AgentTree.ContainerNode)node, "FIPACONTAINER", addr);
}
};
SwingUtilities.invokeLater(addIt);
}
public void removeContainer(final String name) {
// Remove a container from the tree model
Runnable removeIt = new Runnable() {
public void run() {
panel.treeAgent.removeContainerNode(name);
}
};
SwingUtilities.invokeLater(removeIt);
}
public Introspector getAgent(){
return debugger;
}
} |
package org.ovirt.engine.core.common.businessentities;
import java.util.ArrayList;
import java.util.Map;
import org.ovirt.engine.core.compat.Guid;
/**
* The VmDevice represents a managed or unmanaged VM device.<br>
* The VmDevice data consists of this entity which holds the immutable fields of the device.<br>
* Each device have a link to its VM id , an address and optional boot order and additional special device parameters. <br>
* This BE holds both managed (disk, network interface etc.) and unmanaged (sound, video etc.) devices.
*/
public class VmDevice extends IVdcQueryable implements BusinessEntity<VmDeviceId> {
/**
* Needed for java serialization/deserialization mechanism.
*/
private static final long serialVersionUID = 826297167224396854L;
/**
* Device id and Vm id pair as a compound key
*/
private VmDeviceId id;
/**
* The device name.
*/
private String device;
/**
* The device name.
*/
private String type;
/**
* The device address.
*/
private String address;
/**
* The device boot order (if applicable).
*/
private int bootOrder;
/**
* The device special parameters.
*/
private Map<String, Object> specParams = null;
/**
* The device managed/unmanaged flag
*/
private boolean isManaged = false;
/**
* The device plugged flag
*/
private Boolean isPlugged = false;
/**
* The device read-only flag
*/
private boolean isReadOnly = false;
/**
* The device alias.
*/
private String alias = "";
public VmDevice() {
}
public VmDevice(VmDeviceId id, String type, String device, String address,
int bootOrder,
Map<String, Object> specParams,
boolean isManaged,
Boolean isPlugged,
boolean isReadOnly,
String alias) {
super();
this.id = id;
this.type = type;
this.device = device;
this.address = address;
this.bootOrder = bootOrder;
this.specParams = specParams;
this.isManaged = isManaged;
this.isPlugged = isPlugged;
this.isReadOnly = isReadOnly;
this.alias = alias;
}
@Override
public Object getQueryableId() {
return getId();
}
@Override
public ArrayList<String> getChangeablePropertiesList() {
return null;
}
@Override
public VmDeviceId getId() {
return id;
}
@Override
public void setId(VmDeviceId id) {
this.id = id;
}
public Guid getDeviceId() {
return id.getDeviceId();
}
public void setDeviceId(Guid deviceId) {
id.setDeviceId(deviceId);
}
public Guid getVmId() {
return id.getVmId();
}
public void setVmId(Guid vmId) {
this.id.setVmId(vmId);
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getBootOrder() {
return bootOrder;
}
public void setBootOrder(int bootOrder) {
this.bootOrder = bootOrder;
}
public Map<String, Object> getSpecParams() {
return specParams;
}
public void setSpecParams(Map<String, Object> specParams) {
this.specParams = specParams;
}
public boolean getIsManaged() {
return isManaged;
}
public void setIsManaged(boolean isManaged) {
this.isManaged = isManaged;
}
public Boolean getIsPlugged() {
return isPlugged == null ? Boolean.FALSE : isPlugged;
}
public void setIsPlugged(Boolean isPlugged) {
this.isPlugged = isPlugged;
}
public boolean getIsReadOnly() {
return isReadOnly;
}
public void setIsReadOnly(boolean isReadOnly) {
this.isReadOnly = isReadOnly;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id.hashCode();
result = prime * result + device.hashCode();
result = prime * result + type.hashCode();
result = prime * result + address.hashCode();
result = prime * result + bootOrder;
result = prime * result
+ ((specParams == null) ? 0 : specParams.hashCode());
result = prime * result + (isManaged ? 1 : 0);
result = prime * result + (isPlugged ? 1 : 0);
result = prime * result + (isReadOnly ? 1 : 0);
result = prime * result + alias.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof VmDevice)) {
return false;
}
VmDevice other = (VmDevice) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (!device.equals(other.device)) {
return false;
}
if (!type.equals(other.type)) {
return false;
}
if (!address.equals(other.address)) {
return false;
}
if (bootOrder != other.bootOrder) {
return false;
}
if (specParams == null) {
if (other.specParams != null) {
return false;
}
} else if (!specParams.equals(other.specParams)) {
return false;
}
if (isManaged != other.isManaged) {
return false;
}
if (isPlugged != other.isPlugged) {
return false;
}
if (isReadOnly != other.isReadOnly) {
return false;
}
if (!alias.equals(other.alias)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("VmDevice {");
sb.append("vmId=");
sb.append(id.getVmId());
sb.append(", deviceId=");
sb.append(id.getDeviceId());
sb.append(", device=");
sb.append(getDevice());
sb.append(", type=");
sb.append(getType());
sb.append(", bootOrder=");
sb.append(getBootOrder());
sb.append(", specParams=");
sb.append(getSpecParams());
sb.append(", address=");
sb.append(getAddress());
sb.append(", managed=");
sb.append(getIsManaged());
sb.append(", plugged=");
sb.append(getIsPlugged());
sb.append(", readOnly=");
sb.append(getIsReadOnly());
sb.append(", alias=");
sb.append(getAlias());
sb.append("}");
return sb.toString();
}
} |
// $Id: AStarPathUtil.java,v 1.2 2003/05/16 00:49:44 mdb Exp $
package com.threerings.miso.util;
import java.awt.Point;
import java.util.*;
import com.samskivert.util.HashIntMap;
import com.threerings.media.util.MathUtil;
import com.threerings.miso.Log;
import com.threerings.miso.tile.BaseTile;
public class AStarPathUtil
{
/**
* Provides traversibility information when computing paths.
*/
public static interface TraversalPred
{
/**
* Requests to know if the specified traverser (which was provided
* in the call to {@link #getPath}) can traverse the specified
* tile coordinate.
*/
public boolean canTraverse (Object traverser, int x, int y);
}
/** The standard cost to move between nodes. */
public static final int ADJACENT_COST = 10;
/** The cost to move diagonally. */
public static final int DIAGONAL_COST = (int)Math.sqrt(
(ADJACENT_COST * ADJACENT_COST) * 2);
/**
* Return a list of <code>Point</code> objects representing a path
* from coordinates <code>(ax, by)</code> to <code>(bx, by)</code>,
* inclusive, determined by performing an A* search in the given
* scene's base tile layer. Assumes the starting and destination nodes
* are traversable by the specified traverser.
*
* @param tpred lets us know what tiles are traversible.
* @param trav the traverser to follow the path.
* @param longest the longest allowable path in tile traversals.
* @param ax the starting x-position in tile coordinates.
* @param ay the starting y-position in tile coordinates.
* @param bx the ending x-position in tile coordinates.
* @param by the ending y-position in tile coordinates.
*
* @return the list of points in the path.
*/
public static List getPath (TraversalPred tpred, Object trav,
int longest, int ax, int ay, int bx, int by)
{
Info info = new Info(tpred, trav, longest, bx, by);
// set up the starting node
Node s = info.getNode(ax, ay);
s.g = 0;
s.h = getDistanceEstimate(ax, ay, bx, by);
s.f = s.g + s.h;
// push starting node on the open list
info.open.add(s);
_considered = 1;
// while there are more nodes on the open list
while (info.open.size() > 0) {
// pop the best node so far from open
Node n = (Node)info.open.first();
info.open.remove(n);
// if node is a goal node
if (n.x == bx && n.y == by) {
// construct and return the acceptable path
return getNodePath(n);
}
// consider each successor of the node
considerStep(info, n, n.x - 1, n.y - 1, DIAGONAL_COST);
considerStep(info, n, n.x, n.y - 1, ADJACENT_COST);
considerStep(info, n, n.x + 1, n.y - 1, DIAGONAL_COST);
considerStep(info, n, n.x - 1, n.y, ADJACENT_COST);
considerStep(info, n, n.x + 1, n.y, ADJACENT_COST);
considerStep(info, n, n.x - 1, n.y + 1, DIAGONAL_COST);
considerStep(info, n, n.x, n.y + 1, ADJACENT_COST);
considerStep(info, n, n.x + 1, n.y + 1, DIAGONAL_COST);
// push the node on the closed list
info.closed.add(n);
}
// no path found
return null;
}
/**
* Returns the number of nodes considered in computing the most recent
* path.
*/
public static int getConsidered ()
{
return _considered;
}
/**
* Consider the step <code>(n.x, n.y)</code> to <code>(x, y)</code>
* for possible inclusion in the path.
*
* @param info the info object.
* @param n the originating node for the step.
* @param x the x-coordinate for the destination step.
* @param y the y-coordinate for the destination step.
*/
protected static void considerStep (
Info info, Node n, int x, int y, int cost)
{
// skip node if it's outside the map bounds or otherwise impassable
if (!info.isStepValid(n.x, n.y, x, y)) {
return;
}
// calculate the new cost for this node
int newg = n.g + cost;
// make sure the cost is reasonable
if (newg > info.maxcost) {
// Log.info("Rejected costly step.");
return;
}
// retrieve the node corresponding to this location
Node np = info.getNode(x, y);
// skip if it's already in the open or closed list or if its
// actual cost is less than the just-calculated cost
if ((info.open.contains(np) || info.closed.contains(np)) &&
np.g <= newg) {
return;
}
// remove the node from the open list since we're about to
// modify its score which determines its placement in the list
info.open.remove(np);
// update the node's information
np.parent = n;
np.g = newg;
np.h = getDistanceEstimate(np.x, np.y, info.destx, info.desty);
np.f = np.g + np.h;
// remove it from the closed list if it's present
info.closed.remove(np);
// add it to the open list for further consideration
info.open.add(np);
_considered++;
}
/**
* Return a list of <code>Point</code> objects detailing the path
* from the first node (the given node's ultimate parent) to the
* ending node (the given node itself.)
*
* @param n the ending node in the path.
*
* @return the list detailing the path.
*/
protected static List getNodePath (Node n)
{
Node cur = n;
ArrayList path = new ArrayList();
while (cur != null) {
// add to the head of the list since we're traversing from
// the end to the beginning
path.add(0, new Point(cur.x, cur.y));
// advance to the next node in the path
cur = cur.parent;
}
return path;
}
/**
* Return a heuristic estimate of the cost to get from <code>(ax,
* ay)</code> to <code>(bx, by)</code>.
*/
protected static int getDistanceEstimate (int ax, int ay, int bx, int by)
{
// we're doing all of our cost calculations based on geometric
// distance times ten
int xsq = bx - ax;
int ysq = by - ay;
return (int) (ADJACENT_COST * Math.sqrt(xsq * xsq + ysq * ysq));
}
/**
* A holding class to contain the wealth of information referenced
* while performing an A* search for a path through a tile array.
*/
protected static class Info
{
/** Knows whether or not tiles are traversable. */
public TraversalPred tpred;
/** The tile array dimensions. */
public int tilewid, tilehei;
/** The traverser moving along the path. */
public Object trav;
/** The set of open nodes being searched. */
public SortedSet open;
/** The set of closed nodes being searched. */
public ArrayList closed;
/** The destination coordinates in the tile array. */
public int destx, desty;
/** The maximum cost of any path that we'll consider. */
public int maxcost;
public Info (TraversalPred tpred, Object trav,
int longest, int destx, int desty)
{
// save off references
this.tpred = tpred;
this.trav = trav;
this.destx = destx;
this.desty = desty;
// compute our maximum path cost
this.maxcost = longest * ADJACENT_COST;
// construct the open and closed lists
open = new TreeSet();
closed = new ArrayList();
}
/**
* Returns whether moving from the given source to destination
* coordinates is a valid move.
*/
protected boolean isStepValid (int sx, int sy, int dx, int dy)
{
// not traversable if the destination itself fails test
if (!isTraversable(dx, dy)) {
return false;
}
// if the step is diagonal, make sure the corners don't impede
// our progress
if ((Math.abs(dx - sx) == 1) && (Math.abs(dy - sy) == 1)) {
return isTraversable(dx, sy) && isTraversable(sx, dy);
}
// non-diagonals are always traversable
return true;
}
/**
* Returns whether the given coordinate is valid and traversable.
*/
protected boolean isTraversable (int x, int y)
{
return tpred.canTraverse(trav, x, y);
}
/**
* Get or create the node for the specified point.
*/
public Node getNode (int x, int y)
{
// note: this _could_ break for unusual values of x and y.
// perhaps use a IntTuple as a key? Bleah.
int key = (x << 16) | (y & 0xffff);
Node node = (Node) _nodes.get(key);
if (node == null) {
node = new Node(x, y);
_nodes.put(key, node);
}
return node;
}
/** The nodes being considered in the path. */
protected HashIntMap _nodes = new HashIntMap();
}
/**
* A class that represents a single traversable node in the tile array
* along with its current A*-specific search information.
*/
protected static class Node implements Comparable
{
/** The node coordinates. */
public int x, y;
/** The actual cheapest cost of arriving here from the start. */
public int g;
/** The heuristic estimate of the cost to the goal from here. */
public int h;
/** The score assigned to this node. */
public int f;
/** The node from which we reached this node. */
public Node parent;
/** The node's monotonically-increasing unique identifier. */
public int id;
public Node (int x, int y)
{
this.x = x;
this.y = y;
id = _nextid++;
}
public int compareTo (Object o)
{
int bf = ((Node)o).f;
// since the set contract is fulfilled using the equality results
// returned here, and we'd like to allow multiple nodes with
// equivalent scores in our set, we explicitly define object
// equivalence as the result of object.equals(), else we use the
// unique node id since it will return a consistent ordering for
// the objects.
if (f == bf) {
return (this == o) ? 0 : (id - ((Node)o).id);
}
return f - bf;
}
/** The next unique node id. */
protected static int _nextid = 0;
}
/** The number of nodes considered in computing our path. */
protected static int _considered = 0;
} |
package org.openhab.action.twitter.internal;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.FileUtils;
import org.openhab.core.scriptengine.action.ActionDoc;
import org.openhab.core.scriptengine.action.ParamDoc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.DirectMessage;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.TwitterException;
/**
* This class provides static methods that can be used in automation rules for
* sending Tweets via Twitter.
*
* @author Ben Jones
* @author Thomas.Eichstaedt-Engelen
* @author Kai Kreuzer
* @since 1.3.0
*/
public class Twitter {
private static final Logger logger = LoggerFactory.getLogger(Twitter.class);
/** Flag to enable/disable the Twitter client (optional, defaults to 'false') */
static boolean isEnabled = false;
/** The maximum length of a Tweet or direct message */
private static final int CHARACTER_LIMIT = 280;
static twitter4j.Twitter client = null;
/**
* Check twitter prerequesites. Should be used at the beginning of all public methods
*
* @return <code>true</code> if all prerequisites are validated and
* <code>false</code> if any prerequisite is not validated.
*/
private static boolean checkPrerequesites() {
if (!TwitterActionService.isProperlyConfigured) {
logger.debug("Twitter client is not yet configured > execution aborted!");
return false;
}
if (!isEnabled) {
logger.debug("Twitter client is disabled > execution aborted!");
return false;
}
return true;
}
/**
* Internal method for sending a tweet, with or without image
*
* @param tweetTxt
* text string to be sent as a Tweet
* @param fileToAttach
* the file to attach. May be null if no attached file.
*
* @return <code>true</code>, if sending the tweet has been successful and
* <code>false</code> in all other cases.
*/
private static boolean sendTweet(final String tweetTxt, final File fileToAttach) {
// abbreviate the Tweet to meet the 140 character limit ...
String abbreviatedTweetTxt = StringUtils.abbreviate(tweetTxt, CHARACTER_LIMIT);
try {
// abbreviate the Tweet to meet the allowed character limit ...
tweetTxt = StringUtils.abbreviate(tweetTxt, CHARACTER_LIMIT);
// send the Tweet
StatusUpdate status = new StatusUpdate(abbreviatedTweetTxt);
if (fileToAttach != null && fileToAttach.isFile()) {
status.setMedia(fileToAttach);
}
Status updatedStatus = client.updateStatus(status);
logger.debug("Successfully sent Tweet '{}'", updatedStatus.getText());
return true;
} catch (TwitterException e) {
logger.error("Failed to send Tweet '" + abbreviatedTweetTxt + "' because of: " + e.getLocalizedMessage());
return false;
}
}
/**
* Sends a standard Tweet.
*
* @param tweetTxt
* text string to be sent as a Tweet
*
* @return <code>true</code>, if sending the tweet has been successful and
* <code>false</code> in all other cases.
*/
@ActionDoc(text = "Sends a standard Tweet", returns = "<code>true</code>, if sending the tweet has been successful and <code>false</code> in all other cases.")
public static boolean sendTweet(
@ParamDoc(name = "tweetTxt", text = "text string to be sent as a Tweet") String tweetTxt) {
if (!checkPrerequisites()) {
return false;
}
return sendTweet(tweetTxt, (File)null);
}
/**
* Sends a Tweet with an image
*
* @param tweetTxt
* text string to be sent as a Tweet
* @param tweetPicture
* the path of the picture that needs to be attached (either an url,
* either a path pointing to a local file)
*
* @return <code>true</code>, if sending the tweet has been successful and
* <code>false</code> in all other cases.
*/
@ActionDoc(text = "Sends a Tweet with an image", returns = "<code>true</code>, if sending the tweet has been successful and <code>false</code> in all other cases.")
public static boolean sendTweet(
@ParamDoc(name = "tweetTxt", text = "text string to be sent as a Tweet") String tweetTxt,
@ParamDoc(name = "tweetPicture", text = "the picture to attach") String tweetPicture) {
if (!checkPrerequisites()) {
return false;
}
// prepare the image attachment
File fileToAttach = null;
boolean deleteTemporaryFile = false;
if (StringUtils.startsWith(tweetPicture, "http:
// we have a remote url and need to download the remote file to a temporary location
String tDir = System.getProperty("java.io.tmpdir");
String path = tDir + File.separator + "openhab-twitter-remote_attached_file" + "."
+ FilenameUtils.getExtension(tweetPicture);
try {
URL url = new URL(tweetPicture);
fileToAttach = new File(path);
deleteTemporaryFile = true;
FileUtils.copyURLToFile(url, fileToAttach);
} catch (MalformedURLException e) {
logger.warn("Can't read file from '{}'", tweetPicture, e);
} catch (IOException e) {
logger.warn("Can't save file from '{}' to '{}'", tweetPicture, path, e);
}
} else {
fileToAttach = new File(tweetPicture);
}
if (fileToAttach != null && fileToAttach.isFile()) {
logger.debug("Image '{}' correctly found, will be included in tweet", tweetPicture);
} else {
logger.warn("Image '{}' not found, will only tweet text", tweetPicture);
}
// send the Tweet
boolean result = sendTweet(tweetTxt, fileToAttach);
// delete temp file (if needed)
if (deleteTemporaryFile) {
FileUtils.deleteQuietly(fileToAttach);
}
return result;
}
/**
* Sends a direct message via Twitter
*
* @param recipientId
* the receiver of this direct message
* @param messageTxt
* the direct message to send
*
* @return <code>true</code>, if sending the direct message has been successful
* and <code>false</code> in all other cases.
*/
@ActionDoc(text = "Sends a direct message via Twitter", returns = "<code>true</code>, if sending the direct message has been successful and <code>false</code> in all other cases.")
public static boolean sendDirectMessage(
@ParamDoc(name = "recipientId", text = "the receiver of this direct message") String recipientId,
@ParamDoc(name = "messageTxt", text = "the direct message to send") String messageTxt) {
if (! checkPrerequesites()) {
return false;
}
try {
// abbreviate the Tweet to meet the allowed character limit ...
messageTxt = StringUtils.abbreviate(messageTxt, CHARACTER_LIMIT);
// send the direct message
DirectMessage message = client.sendDirectMessage(recipientId, messageTxt);
logger.debug("Successfully sent direct message '{}' to @", message.getText(),
message.getRecipientScreenName());
return true;
} catch (TwitterException e) {
logger.error("Failed to send Tweet '" + messageTxt + "' because of: " + e.getLocalizedMessage());
return false;
}
}
} |
// $Id: GameManager.java,v 1.53 2002/11/02 01:20:59 shaper Exp $
package com.threerings.parlor.game;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import com.samskivert.util.StringUtil;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.dobj.AttributeChangeListener;
import com.threerings.presents.dobj.AttributeChangedEvent;
import com.threerings.presents.dobj.MessageEvent;
import com.threerings.crowd.chat.SpeakProvider;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.server.PlaceManager;
import com.threerings.crowd.server.CrowdServer;
import com.threerings.crowd.server.CrowdServer;
import com.threerings.crowd.server.PlaceManagerDelegate;
import com.threerings.parlor.Log;
import com.threerings.parlor.data.ParlorCodes;
import com.threerings.parlor.server.ParlorSender;
/**
* The game manager handles the server side management of a game. It
* manipulates the game state in accordance with the logic of the game
* flow and generally manages the whole game playing process.
*
* <p> The game manager extends the place manager because games are
* implicitly played in a location, the players of the game implicitly
* bodies in that location.
*/
public class GameManager extends PlaceManager
implements ParlorCodes, GameProvider, AttributeChangeListener
{
// documentation inherited
protected void didInit ()
{
super.didInit();
// save off a casted reference to our config
_gameconfig = (GameConfig)_config;
}
/**
* Adds the given player to the game at the first available player
* index. This should only be called before the game is started, and
* is most likely to be used to add players to party games.
*
* @param player the username of the player to add to this game.
* @return the player index at which the player was added, or
* <code>-1</code> if the player could not be added to the game.
*/
public int addPlayer (String player)
{
// determine the first available player index
int pidx = -1;
for (int ii = 0; ii < getPlayerSlots(); ii++) {
if (!_gameobj.isOccupiedPlayer(ii)) {
pidx = ii;
break;
}
}
// sanity-check the player index
if (pidx == -1) {
Log.warning("Couldn't find free player index for player " +
"[game=" + _gameobj.which() + ", player=" + player +
", players=" + StringUtil.toString(_gameobj.players) +
"].");
return -1;
}
// proceed with the rest of the adding business
return (!addPlayerAt(player, pidx)) ? -1 : pidx;
}
/**
* Adds the given player to the game at the specified player index.
* This should only be called before the game is started, and is most
* likely to be used to add players to party games.
*
* @param player the username of the player to add to this game.
* @param pidx the player index at which the player is to be added.
* @return true if the player was added successfully, false if not.
*/
public boolean addPlayerAt (String player, int pidx)
{
// make sure the specified player index is valid
if (pidx < 0 || pidx >= getPlayerSlots()) {
Log.warning("Attempt to add player at an invalid index " +
"[game=" + _gameobj.which() + ", player=" + player +
", pidx=" + pidx + "].");
return false;
}
// make sure the player index is available
if (_gameobj.players[pidx] != null) {
Log.warning("Attempt to add player at occupied index " +
"[game=" + _gameobj.which() + ", player=" + player +
", pidx=" + pidx + "].");
return false;
}
// make sure the player isn't already somehow a part of the game
// to avoid any potential badness that might ensue if we added
// them more than once
if (_gameobj.getPlayerIndex(player) != -1) {
Log.warning("Attempt to add player to game that they're already " +
"playing [game=" + _gameobj.which() +
", player=" + player + "].");
return false;
}
// get the player's body object
BodyObject bobj = CrowdServer.lookupBody(player);
if (bobj == null) {
Log.warning("Unable to get body object while adding player " +
"[game=" + _gameobj.which() +
", player=" + player + "].");
return false;
}
// fill in the player's information
_gameobj.setPlayersAt(player, pidx);
// increment the number of players in the game
_playerCount++;
// save off their oid
_playerOids[pidx] = bobj.getOid();
// let derived classes do what they like
playerWasAdded(player, pidx);
return true;
}
/**
* Called when a player was added to the game. Derived classes may
* override this method to perform any game-specific actions they
* desire, but should be sure to call
* <code>super.playerWasAdded()</code>.
*
* @param player the username of the player added to the game.
* @param pidx the player index of the player added to the game.
*/
protected void playerWasAdded (String player, int pidx)
{
}
/**
* Removes the given player from the game. This is most likely to be
* used to allow players involved in a party game to leave the game
* early-on if they realize they'd rather not play for some reason.
*
* @param player the username of the player to remove from this game.
* @return true if the player was successfully removed, false if not.
*/
public boolean removePlayer (String player)
{
// get the player's index in the player list
int pidx = _gameobj.getPlayerIndex(player);
// sanity-check the player index
if (pidx == -1) {
Log.warning("Attempt to remove non-player from players list " +
"[game=" + _gameobj.which() +
", player=" + player +
", players=" + StringUtil.toString(_gameobj.players) +
"].");
return false;
}
// remove the player from the players list
_gameobj.setPlayersAt(null, pidx);
// clear out the player's entry in the player oid list
_playerOids[pidx] = 0;
if (_AIs != null) {
// clear out the player's entry in the AI list
_AIs[pidx] = -1;
}
// decrement the number of players in the game
_playerCount
// let derived classes do what they like
playerWasRemoved(player, pidx);
return true;
}
/**
* Called when a player was removed from the game. Derived classes
* may override this method to perform any game-specific actions they
* desire, but should be sure to call
* <code>super.playerWasRemoved()</code>.
*
* @param player the username of the player removed from the game.
* @param pidx the player index of the player before they were removed
* from the game.
*/
protected void playerWasRemoved (String player, int pidx)
{
}
/**
* Sets the specified player as an AI with the specified skill. It is
* assumed that this will be set soon after the player names for all
* AIs present in the game. (It should be done before human players
* start trickling into the game.)
*
* @param pidx the player index of the AI.
* @param skill the skill level, from 0 to 100 inclusive.
*/
public void setAI (final int pidx, final byte skill)
{
if (_AIs == null) {
// create and initialize the AI skill level array
_AIs = new byte[getPlayerSlots()];
Arrays.fill(_AIs, (byte)-1);
// set up a delegate op for AI ticking
_tickAIOp = new TickAIDelegateOp();
}
// save off the AI's skill level
_AIs[pidx] = skill;
// let the delegates know that the player's been made an AI
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).setAI(pidx, skill);
}
});
}
/**
* Returns the name of the player with the specified index.
*/
public String getPlayerName (int index)
{
return _gameobj.players[index];
}
/**
* Returns the player index of the given user in the game, or
* <code>-1</code> if the player is not involved in the game.
*/
public int getPlayerIndex (String username)
{
return _gameobj.getPlayerIndex(username);
}
/**
* Returns the user object oid of the player with the specified index.
*/
public int getPlayerOid (int index)
{
return _playerOids[index];
}
/**
* Returns the number of players in the game.
*/
public int getPlayerCount ()
{
return _playerCount;
}
/**
* Returns the number of players allowed in this game.
*/
public int getPlayerSlots ()
{
return _gameconfig.players.length;
}
/**
* Returns whether the player at the specified player index is an AI.
*/
public boolean isAI (int pidx)
{
return (_AIs != null && _AIs[pidx] != -1);
}
/**
* Returns the unique round identifier for the current round.
*/
public int getRoundId ()
{
return _gameobj.roundId;
}
/**
* Sends a system message to the players in the game room.
*/
public void systemMessage (String msgbundle, String msg)
{
systemMessage(msgbundle, msg, false);
}
/**
* Sends a system message to the players in the game room.
*
* @param waitForStart if true, the message will not be sent until the
* game has started.
*/
public void systemMessage (
String msgbundle, String msg, boolean waitForStart)
{
if (waitForStart &&
((_gameobj == null) ||
(_gameobj.state == GameObject.AWAITING_PLAYERS))) {
// queue up the message.
if (_startmsgs == null) {
_startmsgs = new ArrayList();
}
_startmsgs.add(msgbundle);
_startmsgs.add(msg);
return;
}
// otherwise, just deliver the message
SpeakProvider.sendSystemSpeak(_gameobj, msgbundle, msg);
}
// documentation inherited
protected Class getPlaceObjectClass ()
{
return GameObject.class;
}
// documentation inherited
protected void didStartup ()
{
// obtain a casted reference to our game object
_gameobj = (GameObject)_plobj;
// stick the players into the game object
_gameobj.setPlayers(_gameconfig.players);
// save off the number of players so that we needn't repeatedly
// iterate through the player name array server-side unnecessarily
_playerCount = _gameobj.getPlayerCount();
// instantiate a player oid array which we'll fill in later
_playerOids = new int[getPlayerSlots()];
// create and fill in our game service object
GameMarshaller service = (GameMarshaller)
_invmgr.registerDispatcher(new GameDispatcher(this), false);
_gameobj.setGameService(service);
// give delegates a chance to do their thing
super.didStartup();
// let the players of this game know that we're ready to roll (if
// we have a specific set of players)
for (int ii = 0; ii < getPlayerSlots(); ii++) {
// skip non-existent players
if (!_gameobj.isOccupiedPlayer(ii)) {
continue;
}
BodyObject bobj = CrowdServer.lookupBody(_gameobj.players[ii]);
if (bobj == null) {
Log.warning("Unable to deliver game ready to non-existent " +
"player [game=" + _gameobj.which() +
", player=" + _gameobj.players[ii] + "].");
continue;
}
// deliver a game ready notification to the player
ParlorSender.gameIsReady(bobj, _gameobj.getOid());
}
}
// documentation inherited
protected void didShutdown ()
{
super.didShutdown();
// clear out our service registration
_invmgr.clearDispatcher(_gameobj.gameService);
}
// documentation inherited
protected void bodyLeft (int bodyOid)
{
super.bodyLeft(bodyOid);
// TODO: if this is a party game not yet in play and the creator
// left, choose a new creator if at least one player still remains
// deal with disappearing players
}
/**
* When a game room becomes empty, we cancel the game if it's still in
* progress and close down the game room.
*/
protected void placeBecameEmpty ()
{
// Log.info("Game room empty. Going away. " +
// "[game=" + _gameobj.which() + "].");
// cancel the game if it was in play
if (_gameobj.state == GameObject.IN_PLAY) {
_gameobj.setState(GameObject.CANCELLED);
}
// shut down the place (which will destroy the game object and
// clean up after everything)
shutdown();
}
/**
* Called when all players have arrived in the game room. By default,
* this starts up the game, but a manager may wish to override this
* and start the game according to different criterion.
*/
protected void playersAllHere ()
{
// start up the game if we're not a party game and if we haven't
// already done so
if (!_gameconfig.isPartyGame() &&
_gameobj.state == GameObject.AWAITING_PLAYERS) {
startGame();
}
}
/**
* This is called when the game is ready to start (all players
* involved have delivered their "am ready" notifications). It calls
* {@link #gameWillStart}, sets the necessary wheels in motion and
* then calls {@link #gameDidStart}. Derived classes should override
* one or both of the calldown functions (rather than this function)
* if they need to do things before or after the game starts.
*
* @return true if the game was started, false if it could not be
* started because it was already in play or because all players have
* not yet reported in.
*/
public boolean startGame ()
{
// complain if we're already started
if (_gameobj.state == GameObject.IN_PLAY) {
Log.warning("Requested to start an already in-play game " +
"[game=" + _gameobj + "].");
return false;
}
// make sure everyone has turned up
if (!allPlayersReady()) {
Log.warning("Requested to start a game that is still " +
"awaiting players [game=" + _gameobj.which() +
", pnames=" + StringUtil.toString(_gameobj.players) +
", poids=" + StringUtil.toString(_playerOids) + "].");
return false;
}
// let the derived class do its pre-start stuff
gameWillStart();
// transition the game to started
_gameobj.setState(GameObject.IN_PLAY);
// do post-start processing
gameDidStart();
return true;
}
/**
* Called when the game is about to start, but before the game start
* notification has been delivered to the players. Derived classes
* should override this if they need to perform some pre-start
* activities, but should be sure to call
* <code>super.gameWillStart()</code>.
*/
protected void gameWillStart ()
{
// increment the round identifier
_gameobj.setRoundId(_gameobj.roundId + 1);
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameWillStart();
}
});
}
/**
* Called after the game start notification was dispatched. Derived
* classes can override this to put whatever wheels they might need
* into motion now that the game is started (if anything other than
* transitioning the game to {@link GameObject#IN_PLAY} is necessary),
* but should be sure to call <code>super.gameDidStart()</code>.
*/
protected void gameDidStart ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameDidStart();
}
});
// inform the players of any pending messages.
if (_startmsgs != null) {
for (Iterator iter = _startmsgs.iterator(); iter.hasNext(); ) {
systemMessage((String) iter.next(), // bundle
(String) iter.next()); // message
}
_startmsgs = null;
}
// and register ourselves to receive AI ticks
if (_AIs != null) {
AIGameTicker.registerAIGame(this);
}
}
/**
* Called by the {@link AIGameTicker} if we're registered as an AI
* game.
*/
protected void tickAIs ()
{
for (int ii = 0; ii < _AIs.length; ii++) {
byte level = _AIs[ii];
if (level != -1) {
tickAI(ii, level);
}
}
}
/**
* Called by tickAIs to tick each AI in the game.
*/
protected void tickAI (int pidx, byte level)
{
_tickAIOp.setAI(pidx, level);
applyToDelegates(_tickAIOp);
}
/**
* Called when the game is known to be over. This will call some
* calldown functions to determine the winner of the game and then
* transition the game to the {@link GameObject#GAME_OVER} state.
*/
public void endGame ()
{
if (_gameobj.state != GameObject.IN_PLAY) {
Log.debug("Refusing to end game that was not in play " +
"[game=" + _gameobj.which() + "].");
return;
}
try {
_gameobj.startTransaction();
// let the derived class do its pre-end stuff
gameWillEnd();
// determine winners and set them in the game object
boolean[] winners = new boolean[getPlayerSlots()];
assignWinners(winners);
_gameobj.setWinners(winners);
// transition to the game over state
_gameobj.setState(GameObject.GAME_OVER);
} finally {
_gameobj.commitTransaction();
}
// wait until we hear the game state transition on the game object
// to invoke our game over code so that we can be sure that any
// final events dispatched on the game object prior to the call to
// endGame() have been dispatched
}
/**
* Assigns the final winning status for each player to their respect
* player index in the supplied array. This will be called by {@link
* #endGame} when the game is over. The default implementation marks
* no players as winners. Derived classes should override this method
* in order to customize the winning conditions.
*/
protected void assignWinners (boolean[] winners)
{
Arrays.fill(winners, false);
}
/**
* Called when the game is about to end, but before the game end
* notification has been delivered to the players. Derived classes
* should override this if they need to perform some pre-end
* activities, but should be sure to call
* <code>super.gameWillEnd()</code>.
*/
protected void gameWillEnd ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameWillEnd();
}
});
}
/**
* Called after the game has transitioned to the {@link
* GameObject#GAME_OVER} state. Derived classes should override this
* to perform any post-game activities, but should be sure to call
* <code>super.gameDidEnd()</code>.
*/
protected void gameDidEnd ()
{
// remove ourselves from the AI ticker, if applicable
if (_AIs != null) {
AIGameTicker.unregisterAIGame(this);
}
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameDidEnd();
}
});
// calculate ratings and all that...
}
/**
* Called when the game is to be reset to its starting state in
* preparation for a new game without actually ending the current
* game. It calls {@link #gameWillReset} and {@link #gameDidReset}.
* The standard game start processing ({@link #gameWillStart} and
* {@link #gameDidStart}) will also be called (in between the calls to
* will and did reset). Derived classes should override one or both of
* the calldown functions (rather than this function) if they need to
* do things before or after the game resets.
*/
public void resetGame ()
{
// let the derived class do its pre-reset stuff
gameWillReset();
// do the standard game start processing
gameWillStart();
_gameobj.setState(GameObject.IN_PLAY);
gameDidStart();
// let the derived class do its post-reset stuff
gameDidReset();
}
/**
* Called when the game is about to reset, but before the board has
* been re-initialized or any other clearing out of game data has
* taken place. Derived classes should override this if they need to
* perform some pre-reset activities.
*/
protected void gameWillReset ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameWillReset();
}
});
}
/**
* Called after the game has been reset. Derived classes can override
* this to put whatever wheels they might need into motion now that
* the game is reset, but should be sure to call
* <code>super.gameDidReset()</code>.
*/
protected void gameDidReset ()
{
// let our delegates do their business
applyToDelegates(new DelegateOp() {
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate)delegate).gameDidReset();
}
});
}
// documentation inherited from interface
public void playerReady (ClientObject caller)
{
BodyObject plobj = (BodyObject)caller;
// get the user's player index
int pidx = _gameobj.getPlayerIndex(plobj.username);
if (pidx == -1) {
// only complain if this is not a party game, since it's
// perfectly normal to receive a player ready notification
// from a user entering a party game in which they're not yet
// a participant
if (!_gameconfig.isPartyGame()) {
Log.warning("Received playerReady() from non-player? " +
"[caller=" + caller + "].");
}
return;
}
// make a note of this player's oid
_playerOids[pidx] = plobj.getOid();
// if everyone is now ready to go, get things underway
if (allPlayersReady()) {
playersAllHere();
}
}
/**
* Returns true if all (non-AI) players have delivered their {@link
* #playerReady} notifications, false if they have not.
*/
protected boolean allPlayersReady ()
{
for (int ii = 0; ii < getPlayerSlots(); ii++) {
if (_gameobj.isOccupiedPlayer(ii) &&
(_playerOids[ii] == 0) &&
(_AIs == null || _AIs[ii] == -1)) {
return false;
}
}
return true;
}
// documentation inherited from interface
public void startPartyGame (ClientObject caller)
{
// make sure this is a party game
if (!_gameconfig.isPartyGame()) {
Log.warning("Attempt to player-start a non-party game " +
"[game=" + _gameobj.which() +
", caller=" + caller + "].");
return;
}
// make sure the caller is the creating player
BodyObject plobj = (BodyObject)caller;
int pidx = _gameobj.getPlayerIndex(plobj.username);
if (pidx != _gameobj.creator) {
Log.warning("Attempt to start party game by non-creating player " +
"[game=" + _gameobj.which() +
", creator=" + getPlayerName(_gameobj.creator) +
", caller=" + caller + "].");
return;
}
// make sure the game is ready to go
if (!canStartPartyGame()) {
Log.warning("Attempt to start party game that can't yet begin " +
"[game=" + _gameobj.which() +
", caller=" + caller + "].");
return;
}
// start things up
startGame();
}
/**
* Returns whether this party game is all set to begin. The default
* implementation returns true. Derived classes that implement a
* party game should override this method to enforce any prerequisites
* (such as a minimum number of players) as appropriate.
*/
protected boolean canStartPartyGame ()
{
return true;
}
// documentation inherited
public void attributeChanged (AttributeChangedEvent event)
{
if (event.getName().equals(GameObject.STATE)) {
switch (event.getIntValue()) {
case GameObject.CANCELLED:
// fall through to GAME_OVER case
case GameObject.GAME_OVER:
// now we do our end of game processing
gameDidEnd();
break;
}
}
}
/**
* A helper operation to distribute AI ticks to our delegates.
*/
protected class TickAIDelegateOp implements DelegateOp
{
public void apply (PlaceManagerDelegate delegate) {
((GameManagerDelegate) delegate).tickAI(_pidx, _level);
}
public void setAI (int pidx, byte level)
{
_pidx = pidx;
_level = level;
}
protected int _pidx;
protected byte _level;
}
/** A reference to our game config. */
protected GameConfig _gameconfig;
/** A reference to our game object. */
protected GameObject _gameobj;
/** The number of players in the game. */
protected int _playerCount;
/** The oids of our player and AI body objects. */
protected int[] _playerOids;
/** If AIs are present, contains their skill levels, or -1 at human
* player indexes. */
protected byte[] _AIs;
/** If non-null, contains bundles and messages that should be sent as
* system messages once the game has started. */
protected ArrayList _startmsgs;
/** Our delegate operator to tick AIs. */
protected TickAIDelegateOp _tickAIOp;
} |
/**
*@author Biju Joseph
*/
package gov.nih.nci.cabig.caaers.dao.query;
import junit.framework.TestCase;
public class StudyHavingStudySiteQueryTest extends TestCase {
public void testQueryConstructor() throws Exception {
StudyHavingStudySiteQuery query = new StudyHavingStudySiteQuery();
assertEquals("wrong parsing for constructor", "select distinct s from Study s join s.studyOrganizations ss WHERE ss.class = 'SST'",
query.getQueryString());
}
public void testFilterByStudySiteName() throws Exception {
StudyHavingStudySiteQuery query = new StudyHavingStudySiteQuery();
query.filterByStudySiteName("a");
assertEquals(
"select distinct s from Study s join s.studyOrganizations ss WHERE ss.class = 'SST' AND lower(ss.organization.name) LIKE :organizationName",
query.getQueryString());
assertEquals("wrong number of parameters", query.getParameterMap().size(), 1);
assertTrue("missing paramenter name", query.getParameterMap().containsKey(
"organizationName"));
assertEquals("wrong parameter value", query.getParameterMap().get("organizationName"),
"%a%");
query.filterByStudyShortTile("b");
assertEquals(
"select distinct s from Study s join s.studyOrganizations ss WHERE ss.class = 'SST' AND lower(ss.organization.name) LIKE :organizationName AND lower(s.shortTitle) LIKE :shortTitle",
query.getQueryString());
assertEquals("wrong number of parameters", query.getParameterMap().size(), 2);
assertTrue("missing paramenter name", query.getParameterMap().containsKey("shortTitle"));
assertEquals("wrong parameter value", query.getParameterMap().get("shortTitle"), "%b%");
}
public void testFilterByIdentifier() throws Exception {
StudyHavingStudySiteQuery query = new StudyHavingStudySiteQuery();
query.filterByIdentifierValue("a");
assertEquals(
"select distinct s from Study s join s.studyOrganizations ss WHERE ss.class = 'SST' AND lower(s.identifiers.value) LIKE :identifier",
query.getQueryString());
assertEquals("wrong number of parameters", query.getParameterMap().size(), 1);
assertTrue("missing paramenter name", query.getParameterMap().containsKey("identifier"));
assertEquals("wrong parameter value", query.getParameterMap().get("identifier"), "%a%");
query = new StudyHavingStudySiteQuery();
query.filterByIdentifierValueExactMatch("a");
assertEquals(
"select distinct s from Study s join s.studyOrganizations ss WHERE ss.class = 'SST' AND lower(s.identifiers.value) LIKE :identifier",
query.getQueryString());
assertEquals("wrong number of parameters", query.getParameterMap().size(), 1);
assertTrue("missing paramenter name", query.getParameterMap().containsKey("identifier"));
assertEquals("wrong parameter value", query.getParameterMap().get("identifier"), "a");
}
} |
package org.jaxen.dom4j;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Branch;
import org.dom4j.CDATA;
import org.dom4j.Comment;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.Node;
import org.dom4j.ProcessingInstruction;
import org.dom4j.QName;
import org.dom4j.Text;
import org.dom4j.io.SAXReader;
import org.jaxen.DefaultNavigator;
import org.jaxen.FunctionCallException;
import org.jaxen.NamedAccessNavigator;
import org.jaxen.Navigator;
import org.jaxen.XPath;
import org.jaxen.JaxenConstants;
import org.jaxen.saxpath.SAXPathException;
import org.jaxen.util.SingleObjectIterator;
/**
* Interface for navigating around the DOM4J object model.
*
* <p>
* This class is not intended for direct usage, but is
* used by the Jaxen engine during evaluation.
* </p>
*
* @see XPath
*
* @author <a href="mailto:bob@werken.com">bob mcwhirter</a>
* @author Stephen Colebourne
*/
public class DocumentNavigator extends DefaultNavigator implements NamedAccessNavigator
{
private transient SAXReader reader;
/** Singleton implementation.
*/
private static class Singleton
{
/** Singleton instance.
*/
private static DocumentNavigator instance = new DocumentNavigator();
}
/** Retrieve the singleton instance of this <code>DocumentNavigator</code>.
*/
public static Navigator getInstance()
{
return Singleton.instance;
}
public boolean isElement(Object obj)
{
return obj instanceof Element;
}
public boolean isComment(Object obj)
{
return obj instanceof Comment;
}
public boolean isText(Object obj)
{
return ( obj instanceof Text
||
obj instanceof CDATA );
}
public boolean isAttribute(Object obj)
{
return obj instanceof Attribute;
}
public boolean isProcessingInstruction(Object obj)
{
return obj instanceof ProcessingInstruction;
}
public boolean isDocument(Object obj)
{
return obj instanceof Document;
}
public boolean isNamespace(Object obj)
{
return obj instanceof Namespace;
}
public String getElementName(Object obj)
{
Element elem = (Element) obj;
return elem.getName();
}
public String getElementNamespaceUri(Object obj)
{
Element elem = (Element) obj;
String uri = elem.getNamespaceURI();
if ( uri == null)
return "";
else
return uri;
}
public String getElementQName(Object obj)
{
Element elem = (Element) obj;
return elem.getQualifiedName();
}
public String getAttributeName(Object obj)
{
Attribute attr = (Attribute) obj;
return attr.getName();
}
public String getAttributeNamespaceUri(Object obj)
{
Attribute attr = (Attribute) obj;
String uri = attr.getNamespaceURI();
if ( uri == null)
return "";
else
return uri;
}
public String getAttributeQName(Object obj)
{
Attribute attr = (Attribute) obj;
return attr.getQualifiedName();
}
public Iterator getChildAxisIterator(Object contextNode)
{
Iterator result = null;
if ( contextNode instanceof Branch )
{
Branch node = (Branch) contextNode;
result = node.nodeIterator();
}
if (result != null) {
return result;
}
return JaxenConstants.EMPTY_ITERATOR;
}
/**
* Retrieves an <code>Iterator</code> over the child elements that
* match the supplied name.
*
* @param contextNode the origin context node
* @param localName the local name of the children to return, always present
* @param namespacePrefix the prefix of the namespace of the children to return
* @param namespaceURI the uri of the namespace of the children to return
* @return an Iterator that traverses the named children, or null if none
*/
public Iterator getChildAxisIterator(
Object contextNode, String localName, String namespacePrefix, String namespaceURI) {
if ( contextNode instanceof Element ) {
Element node = (Element) contextNode;
return node.elementIterator(QName.get(localName, namespacePrefix, namespaceURI));
}
if ( contextNode instanceof Document ) {
Document node = (Document) contextNode;
Element el = node.getRootElement();
if (el.getName().equals(localName) == false) {
return JaxenConstants.EMPTY_ITERATOR;
}
if (namespaceURI != null) {
if (namespaceURI.equals(el.getNamespaceURI()) == false) {
return JaxenConstants.EMPTY_ITERATOR;
}
}
return new SingleObjectIterator(el);
}
return JaxenConstants.EMPTY_ITERATOR;
}
public Iterator getParentAxisIterator(Object contextNode)
{
if ( contextNode instanceof Document )
{
return JaxenConstants.EMPTY_ITERATOR;
}
Node node = (Node) contextNode;
Object parent = node.getParent();
if ( parent == null )
{
parent = node.getDocument();
}
return new SingleObjectIterator( parent );
}
public Iterator getAttributeAxisIterator(Object contextNode)
{
if ( ! ( contextNode instanceof Element ) )
{
return JaxenConstants.EMPTY_ITERATOR;
}
Element elem = (Element) contextNode;
return elem.attributeIterator();
}
/**
* Retrieves an <code>Iterator</code> over the attribute elements that
* match the supplied name.
*
* @param contextNode the origin context node
* @param localName the local name of the attributes to return, always present
* @param namespacePrefix the prefix of the namespace of the attributes to return
* @param namespaceURI the URI of the namespace of the attributes to return
* @return an Iterator that traverses the named attributes, not null
*/
public Iterator getAttributeAxisIterator(
Object contextNode, String localName, String namespacePrefix, String namespaceURI) {
if ( contextNode instanceof Element ) {
Element node = (Element) contextNode;
Attribute attr = node.attribute(QName.get(localName, namespacePrefix, namespaceURI));
if (attr == null) {
return JaxenConstants.EMPTY_ITERATOR;
}
return new SingleObjectIterator(attr);
}
return JaxenConstants.EMPTY_ITERATOR;
}
public Iterator getNamespaceAxisIterator(Object contextNode)
{
if ( ! ( contextNode instanceof Element ) )
{
return JaxenConstants.EMPTY_ITERATOR;
}
Element element = (Element) contextNode;
List nsList = new ArrayList();
HashSet prefixes = new HashSet();
for ( Element context = element; context != null; context = context.getParent() ) {
List declaredNS = context.declaredNamespaces();
declaredNS.add(context.getNamespace());
for ( Iterator iter = context.attributes().iterator(); iter.hasNext(); )
{
Attribute attr = (Attribute) iter.next();
declaredNS.add(attr.getNamespace());
}
for ( Iterator iter = declaredNS.iterator(); iter.hasNext(); )
{
Namespace namespace = (Namespace) iter.next();
if (namespace != Namespace.NO_NAMESPACE)
{
String prefix = namespace.getPrefix();
if ( ! prefixes.contains( prefix ) ) {
prefixes.add( prefix );
nsList.add( namespace.asXPathResult( element ) );
}
}
}
}
nsList.add( Namespace.XML_NAMESPACE.asXPathResult( element ) );
return nsList.iterator();
}
public Object getDocumentNode(Object contextNode)
{
if ( contextNode instanceof Document )
{
return contextNode;
}
else if ( contextNode instanceof Node )
{
Node node = (Node) contextNode;
return node.getDocument();
}
return null;
}
/** Returns a parsed form of the given xpath string, which will be suitable
* for queries on DOM4J documents.
*/
public XPath parseXPath (String xpath) throws SAXPathException
{
return new Dom4jXPath(xpath);
}
public Object getParentNode(Object contextNode)
{
if ( contextNode instanceof Node )
{
Node node = (Node) contextNode;
Object answer = node.getParent();
if ( answer == null )
{
answer = node.getDocument();
if (answer == contextNode) {
return null;
}
}
return answer;
}
return null;
}
public String getTextStringValue(Object obj)
{
return getNodeStringValue( (Node) obj );
}
public String getElementStringValue(Object obj)
{
return getNodeStringValue( (Node) obj );
}
public String getAttributeStringValue(Object obj)
{
return getNodeStringValue( (Node) obj );
}
private String getNodeStringValue(Node node)
{
return node.getStringValue();
}
public String getNamespaceStringValue(Object obj)
{
Namespace ns = (Namespace) obj;
return ns.getURI();
}
public String getNamespacePrefix(Object obj)
{
Namespace ns = (Namespace) obj;
return ns.getPrefix();
}
public String getCommentStringValue(Object obj)
{
Comment cmt = (Comment) obj;
return cmt.getText();
}
public String translateNamespacePrefixToUri(String prefix, Object context)
{
Element element = null;
if ( context instanceof Element )
{
element = (Element) context;
}
else if ( context instanceof Node )
{
Node node = (Node) context;
element = node.getParent();
}
if ( element != null )
{
Namespace namespace = element.getNamespaceForPrefix( prefix );
if ( namespace != null )
{
return namespace.getURI();
}
}
return null;
}
public short getNodeType(Object node)
{
if ( node instanceof Node )
{
return ((Node) node).getNodeType();
}
return 0;
}
public Object getDocument(String uri) throws FunctionCallException
{
try
{
return getSAXReader().read( uri );
}
catch (DocumentException e)
{
throw new FunctionCallException("Failed to parse document for URI: " + uri, e);
}
}
public String getProcessingInstructionTarget(Object obj)
{
ProcessingInstruction pi = (ProcessingInstruction) obj;
return pi.getTarget();
}
public String getProcessingInstructionData(Object obj)
{
ProcessingInstruction pi = (ProcessingInstruction) obj;
return pi.getText();
}
// Properties
public SAXReader getSAXReader()
{
if ( reader == null )
{
reader = new SAXReader();
reader.setMergeAdjacentText( true );
}
return reader;
}
public void setSAXReader(SAXReader reader)
{
this.reader = reader;
}
} |
package org.jaxen.function;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
import java.util.List;
import java.util.Iterator;
/**
* <p><b>4.2</b> <code><i>string</i> concat(<i>string</i>,<i>string</i>,<i>string*</i>)</code>
*
* @author bob mcwhirter (bob@werken.com)
*/
public class ConcatFunction implements Function
{
public Object call(Context context,
List args) throws FunctionCallException
{
if ( args.size() >= 2 )
{
return evaluate( args,
context.getNavigator() );
}
throw new FunctionCallException("concat() requires at least two arguments");
}
public static String evaluate(List list,
Navigator nav)
{
StringBuffer result = new StringBuffer();
Iterator argIter = list.iterator();
while ( argIter.hasNext() )
{
result.append( StringFunction.evaluate( argIter.next(),
nav ) );
}
return result.toString();
}
} |
package org.jasig.cas.services.web;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.jasig.cas.services.DefaultServicesManagerImpl;
import org.jasig.cas.services.InMemoryServiceRegistryDaoImpl;
import org.jasig.cas.services.RegexRegisteredService;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.RegisteredServiceImpl;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.services.web.support.RegisteredServiceValidator;
import org.jasig.services.persondir.support.StubPersonAttributeDao;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
public class RegisteredServiceSimpleFormControllerTests extends TestCase {
private RegisteredServiceSimpleFormController controller;
private ServicesManager manager;
private StubPersonAttributeDao repository;
@Override
protected void setUp() throws Exception {
final Map<String, List<Object>> attributes = new HashMap<String, List<Object>>();
attributes.put("test", Arrays.asList(new Object[] {"test"}));
this.repository = new StubPersonAttributeDao();
this.repository.setBackingMap(attributes);
this.manager = new DefaultServicesManagerImpl(
new InMemoryServiceRegistryDaoImpl());
final RegisteredServiceValidator validator = new RegisteredServiceValidator();
validator.setServicesManager(this.manager);
this.controller = new RegisteredServiceSimpleFormController(
this.manager, this.repository);
this.controller.setCommandName("registeredService");
this.controller.setValidator(validator);
}
public void testAddRegisteredServiceNoValues() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
request.setMethod("POST");
final ModelAndView modelAndView = this.controller.handleRequest(
request, response);
final BindingResult result = (BindingResult) modelAndView
.getModel()
.get(
"org.springframework.validation.BindingResult.registeredService");
assertTrue(result.hasErrors());
}
public void testAddRegisteredServiceWithValues() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("description", "description");
request.addParameter("serviceId", "serviceId");
request.addParameter("name", "name");
request.addParameter("theme", "theme");
request.addParameter("allowedToProxy", "true");
request.addParameter("enabled", "true");
request.addParameter("ssoEnabled", "true");
request.addParameter("anonymousAccess", "false");
request.addParameter("evaluationOrder", "1");
request.setMethod("POST");
assertTrue(this.manager.getAllServices().isEmpty());
this.controller.handleRequest(
request, response);
final Collection<RegisteredService> services = this.manager.getAllServices();
assertEquals(1, services.size());
for(RegisteredService rs : this.manager.getAllServices()) {
assertTrue(rs instanceof RegisteredServiceImpl);
}
}
public void testEditRegisteredServiceWithValues() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
final RegisteredServiceImpl r = new RegisteredServiceImpl();
r.setId(1000);
r.setServiceId("test");
r.setDescription("description");
this.manager.save(r);
request.addParameter("description", "description");
request.addParameter("serviceId", "serviceId1");
request.addParameter("name", "name");
request.addParameter("theme", "theme");
request.addParameter("allowedToProxy", "true");
request.addParameter("enabled", "true");
request.addParameter("ssoEnabled", "true");
request.addParameter("anonymousAccess", "false");
request.addParameter("evaluationOrder", "2");
request.addParameter("id", "1000");
request.setMethod("POST");
this.controller.handleRequest(
request, response);
assertFalse(this.manager.getAllServices().isEmpty());
final RegisteredService r2 = this.manager.findServiceBy(1000);
assertEquals("serviceId1", r2.getServiceId());
}
// CAS-1071 test
public void testAddRegexRegisteredService() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("description", "description");
request.addParameter("serviceId", "^https:
request.addParameter("name", "name");
request.addParameter("theme", "theme");
request.addParameter("allowedToProxy", "true");
request.addParameter("enabled", "true");
request.addParameter("ssoEnabled", "true");
request.addParameter("anonymousAccess", "false");
request.addParameter("evaluationOrder", "1");
request.setMethod("POST");
assertTrue(this.manager.getAllServices().isEmpty());
this.controller.handleRequest(
request, response);
final Collection<RegisteredService> services = this.manager.getAllServices();
assertEquals(1, services.size());
for(RegisteredService rs : this.manager.getAllServices()) {
assertTrue(rs instanceof RegexRegisteredService);
}
}
// CAS-1071 test
public void testAddMultipleRegisteredServiceTypes() throws Exception {
final MockHttpServletRequest request1 = new MockHttpServletRequest();
final MockHttpServletResponse response1 = new MockHttpServletResponse();
request1.addParameter("description", "description");
request1.addParameter("serviceId", "serviceId");
request1.addParameter("name", "ant");
request1.addParameter("theme", "theme");
request1.addParameter("allowedToProxy", "true");
request1.addParameter("enabled", "true");
request1.addParameter("ssoEnabled", "true");
request1.addParameter("anonymousAccess", "false");
request1.addParameter("evaluationOrder", "1");
request1.setMethod("POST");
final MockHttpServletRequest request2 = new MockHttpServletRequest();
final MockHttpServletResponse response2 = new MockHttpServletResponse();
request2.addParameter("description", "description");
request2.addParameter("serviceId", "^https:
request2.addParameter("name", "regex");
request2.addParameter("theme", "theme");
request2.addParameter("allowedToProxy", "true");
request2.addParameter("enabled", "true");
request2.addParameter("ssoEnabled", "true");
request2.addParameter("anonymousAccess", "false");
request2.addParameter("evaluationOrder", "1");
request2.setMethod("POST");
assertTrue(this.manager.getAllServices().isEmpty());
this.controller.handleRequest(request1, response1);
this.controller.handleRequest(request2, response2);
final Collection<RegisteredService> services = this.manager.getAllServices();
assertEquals(2, services.size());
for(RegisteredService rs : this.manager.getAllServices()) {
if(rs.getName().equals("ant")) {
assertTrue(rs instanceof RegisteredServiceImpl);
}else if (rs.getName().equals("regex")) {
assertTrue(rs instanceof RegexRegisteredService);
}
}
}
} |
package org.jaxen.function;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
import org.jaxen.UnsupportedAxisException;
import org.jaxen.JaxenRuntimeException;
import java.text.NumberFormat;
import java.util.List;
import java.util.Iterator;
import java.util.Locale;
/**
* <p><b>4.2</b> <code><i>string</i> string(<i>object</i>)</code>
*
* @author bob mcwhirter (bob @ werken.com)
*/
public class StringFunction implements Function
{
private static NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
static {
format.setGroupingUsed(false);
format.setMaximumFractionDigits(32);
}
public Object call(Context context,
List args) throws FunctionCallException
{
int size = args.size();
if ( size == 0 )
{
return evaluate( context.getNodeSet(),
context.getNavigator() );
}
else if ( size == 1 )
{
return evaluate( args.get(0),
context.getNavigator() );
}
throw new FunctionCallException( "string() requires one argument." );
}
public static String evaluate(Object obj,
Navigator nav)
{
try
{
if (obj == null) {
return "";
}
// Workaround because XOM uses lists for Text nodes
// so we need to check for that first
if (nav != null && nav.isText(obj))
{
return nav.getTextStringValue(obj);
}
if (obj instanceof List)
{
List list = (List) obj;
if (list.isEmpty())
{
return "";
}
// do not recurse: only first list should unwrap
obj = list.get(0);
}
if (nav != null && (nav.isElement(obj) || nav.isDocument(obj)))
{
Iterator descendantAxisIterator = nav.getDescendantAxisIterator(obj);
StringBuffer sb = new StringBuffer();
while (descendantAxisIterator.hasNext())
{
Object descendant = descendantAxisIterator.next();
if (nav.isText(descendant))
{
sb.append(nav.getTextStringValue(descendant));
}
}
return sb.toString();
}
else if (nav != null && nav.isAttribute(obj))
{
return nav.getAttributeStringValue(obj);
}
else if (nav != null && nav.isText(obj))
{
return nav.getTextStringValue(obj);
}
else if (nav != null && nav.isProcessingInstruction(obj))
{
return nav.getProcessingInstructionData(obj);
}
else if (nav != null && nav.isComment(obj))
{
return nav.getCommentStringValue(obj);
}
else if (nav != null && nav.isNamespace(obj))
{
return nav.getNamespaceStringValue(obj);
}
else if (obj instanceof String)
{
return (String) obj;
}
else if (obj instanceof Boolean)
{
return stringValue(((Boolean) obj).booleanValue());
}
else if (obj instanceof Number)
{
return stringValue(((Number) obj).doubleValue());
}
return "";
}
catch (UnsupportedAxisException e)
{
throw new JaxenRuntimeException(e);
}
}
public static String stringValue(double value)
{
if (Double.isNaN(value)) return "NaN";
else if (Double.isInfinite(value)) {
if (value > 0) return "Infinity";
else return "-Infinity";
}
return format.format(value);
}
public static String stringValue(boolean value)
{
return value ? "true" : "false";
}
} |
package org.jasig.cas.services.web;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jasig.cas.services.DefaultServicesManagerImpl;
import org.jasig.cas.services.InMemoryServiceRegistryDaoImpl;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.RegisteredServiceImpl;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.services.web.support.RegisteredServiceValidator;
import org.jasig.services.persondir.support.StubPersonAttributeDao;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import junit.framework.TestCase;
public class RegisteredServiceSimpleFormControllerTests extends TestCase {
private RegisteredServiceSimpleFormController controller;
private ServicesManager manager;
private StubPersonAttributeDao repository;
@Override
protected void setUp() throws Exception {
final Map<String, List<Object>> attributes = new HashMap<String, List<Object>>();
attributes.put("test", Arrays.asList(new Object[] {"test"}));
this.repository = new StubPersonAttributeDao();
this.repository.setBackingMap(attributes);
this.manager = new DefaultServicesManagerImpl(
new InMemoryServiceRegistryDaoImpl());
final RegisteredServiceValidator validator = new RegisteredServiceValidator();
validator.setServicesManager(this.manager);
this.controller = new RegisteredServiceSimpleFormController(
this.manager, this.repository);
this.controller.setCommandClass(RegisteredServiceImpl.class);
this.controller.setCommandName("registeredService");
this.controller.setValidator(validator);
}
public void testAddRegisteredServiceNoValues() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
request.setMethod("POST");
final ModelAndView modelAndView = this.controller.handleRequest(
request, response);
final BindingResult result = (BindingResult) modelAndView
.getModel()
.get(
"org.springframework.validation.BindingResult.registeredService");
assertTrue(result.hasErrors());
}
public void testAddRegisteredServiceWithValues() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("description", "description");
request.addParameter("serviceId", "serviceId");
request.addParameter("name", "name");
request.addParameter("theme", "theme");
request.addParameter("allowedToProxy", "true");
request.addParameter("enabled", "true");
request.addParameter("ssoEnabled", "true");
request.addParameter("anonymousAccess", "false");
request.setMethod("POST");
assertTrue(this.manager.getAllServices().isEmpty());
this.controller.handleRequest(
request, response);
assertFalse(this.manager.getAllServices().isEmpty());
}
public void testEditRegisteredServiceWithValues() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
final RegisteredServiceImpl r = new RegisteredServiceImpl();
r.setId(1000);
r.setServiceId("test");
r.setDescription("description");
this.manager.save(r);
request.addParameter("description", "description");
request.addParameter("serviceId", "serviceId1");
request.addParameter("name", "name");
request.addParameter("theme", "theme");
request.addParameter("allowedToProxy", "true");
request.addParameter("enabled", "true");
request.addParameter("ssoEnabled", "true");
request.addParameter("anonymousAccess", "false");
request.addParameter("id", "1000");
request.setMethod("POST");
this.controller.handleRequest(
request, response);
assertFalse(this.manager.getAllServices().isEmpty());
final RegisteredService r2 = this.manager.findServiceBy(1000);
assertEquals("serviceId1", r2.getServiceId());
}
} |
package jtermios.linux;
import java.io.File;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import jtermios.FDSet;
import jtermios.JTermios;
import jtermios.Pollfd;
import jtermios.Termios;
import jtermios.TimeVal;
import jtermios.JTermios.JTermiosInterface;
import jtermios.linux.JTermiosImpl.Linux_C_lib.pollfd;
import jtermios.linux.JTermiosImpl.Linux_C_lib.serial_struct;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import static jtermios.JTermios.*;
import static jtermios.JTermios.JTermiosLogging.log;
public class JTermiosImpl implements jtermios.JTermios.JTermiosInterface {
private static String DEVICE_DIR_PATH = "/dev/";
static Linux_C_lib m_Clib = (Linux_C_lib) Native.loadLibrary("c", Linux_C_lib.class);
private final static int TIOCGSERIAL = 0x0000541E;
private final static int TIOCSSERIAL = 0x0000541F;
private final static int ASYNC_SPD_MASK = 0x00001030;
private final static int ASYNC_SPD_CUST = 0x00000030;
private final static int[] m_BaudRates = {
50, 0000001,
75, 0000002,
110, 0000003,
134, 0000004,
150, 0000005,
200, 0000006,
300, 0000007,
600, 0000010,
1200, 0000011,
1800, 0000012,
2400, 0000013,
4800, 0000014,
9600, 0000015,
19200, 0000016,
38400, 0000017,
57600, 0010001,
115200, 0010002,
230400, 0010003,
460800, 0010004,
500000, 0010005,
576000, 0010006,
921600, 0010007,
1000000, 0010010,
1152000, 0010011,
1500000, 0010012,
2000000, 0010013,
2500000, 0010014,
3000000, 0010015,
3500000, 0010016,
4000000, 0010017
};
public interface Linux_C_lib extends com.sun.jna.Library {
public IntByReference __error();
public int tcdrain(int fd);
public void cfmakeraw(termios termios);
public int fcntl(int fd, int cmd, int[] arg);
public int fcntl(int fd, int cmd, int arg);
public int ioctl(int fd, int cmd, int[] arg);
public int ioctl(int fd, int cmd, serial_struct arg);
public int open(String path, int flags);
public int close(int fd);
public int tcgetattr(int fd, termios termios);
public int tcsetattr(int fd, int cmd, termios termios);
public int cfsetispeed(termios termios, NativeLong i);
public int cfsetospeed(termios termios, NativeLong i);
public NativeLong cfgetispeed(termios termios);
public NativeLong cfgetospeed(termios termios);
public NativeLong write(int fd, ByteBuffer buffer, NativeLong count);
public NativeLong read(int fd, ByteBuffer buffer, NativeLong count);
public int select(int n, int[] read, int[] write, int[] error, TimeVal timeout);
public int poll(pollfd[] fds, int nfds, int timeout);
public int tcflush(int fd, int qs);
public void perror(String msg);
public int tcsendbreak(int fd, int duration);
static public class TimeVal extends Structure {
public NativeLong tv_sec;
public NativeLong tv_usec;
public TimeVal(jtermios.TimeVal timeout) {
tv_sec = new NativeLong(timeout.tv_sec);
tv_usec = new NativeLong(timeout.tv_usec);
}
}
static public class pollfd extends Structure {
public int fd;
public short events;
public short revents;
public pollfd(Pollfd pfd) {
fd = pfd.fd;
events = pfd.events;
revents = pfd.revents;
}
}
public static class serial_struct extends Structure {
public int type;
public int line;
public int port;
public int irq;
public int flags;
public int xmit_fifo_size;
public int custom_divisor;
public int baud_base;
public short close_delay;
public short io_type;
//public char io_type;
//public char reserved_char;
public int hub6;
public short closing_wait;
public short closing_wait2;
public Pointer iomem_base;
public short iomem_reg_shift;
public int port_high;
public NativeLong iomap_base;
};
static public class termios extends Structure {
public int c_iflag;
public int c_oflag;
public int c_cflag;
public int c_lflag;
public byte c_line;
public byte[] c_cc = new byte[32];
public int c_ispeed;
public int c_ospeed;
public termios() {
}
public termios(jtermios.Termios t) {
c_iflag = t.c_iflag;
c_oflag = t.c_oflag;
c_cflag = t.c_cflag;
c_lflag = t.c_lflag;
System.arraycopy(t.c_cc, 0, c_cc, 0, t.c_cc.length);
c_ispeed = t.c_ispeed;
c_ospeed = t.c_ospeed;
}
public void update(jtermios.Termios t) {
t.c_iflag = c_iflag;
t.c_oflag = c_oflag;
t.c_cflag = c_cflag;
t.c_lflag = c_lflag;
System.arraycopy(c_cc, 0, t.c_cc, 0, t.c_cc.length);
t.c_ispeed = c_ispeed;
t.c_ospeed = c_ospeed;
}
}
}
static private class FDSetImpl extends FDSet {
static final int FD_SET_SIZE = 1024;
static final int NFBBITS = 32;
int[] bits = new int[(FD_SET_SIZE + NFBBITS - 1) / NFBBITS];
public String toString() {
return String.format("%08X%08X", bits[0], bits[1]);
}
}
public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
//linux/serial.h stuff
FIONREAD = 0x541B; // Looked up manually
//fcntl.h stuff
O_RDWR = 0x00000002;
O_NONBLOCK = 0x00000800;
O_NOCTTY = 0x00000100;
O_NDELAY = 0x00000800;
F_GETFL = 0x00000003;
F_SETFL = 0x00000004;
//errno.h stuff
EAGAIN = 35;
EACCES = 22;
EEXIST = 17;
EINTR = 4;
EINVAL = 22;
EIO = 5;
EISDIR = 21;
ELOOP = 40;
EMFILE = 24;
ENAMETOOLONG = 36;
ENFILE = 23;
ENOENT = 2;
ENOSR = 63;
ENOSPC = 28;
ENOTDIR = 20;
ENXIO = 6;
EOVERFLOW = 75;
EROFS = 30;
ENOTSUP = 95;
//termios.h stuff
TIOCM_RNG = 0x00000080;
TIOCM_CAR = 0x00000040;
IGNBRK = 0x00000001;
BRKINT = 0x00000002;
PARMRK = 0x00000008;
INLCR = 0x00000040;
IGNCR = 0x00000080;
ICRNL = 0x00000100;
ECHONL = 0x00000040;
IEXTEN = 0x00008000;
CLOCAL = 0x00000800;
OPOST = 0x00000001;
VSTART = 0x00000008;
TCSANOW = 0x00000000;
VSTOP = 0x00000009;
VMIN = 0x00000006;
VTIME = 0x00000005;
VEOF = 0x00000004;
TIOCMGET = 0x00005415;
TIOCM_CTS = 0x00000020;
TIOCM_DSR = 0x00000100;
TIOCM_RI = 0x00000080;
TIOCM_CD = 0x00000040;
TIOCM_DTR = 0x00000002;
TIOCM_RTS = 0x00000004;
ICANON = 0x00000002;
ECHO = 0x00000008;
ECHOE = 0x00000010;
ISIG = 0x00000001;
TIOCMSET = 0x00005418;
IXON = 0x00000400;
IXOFF = 0x00001000;
IXANY = 0x00000800;
CRTSCTS = 0x80000000;
TCSADRAIN = 0x00000001;
INPCK = 0x00000010;
ISTRIP = 0x00000020;
CSIZE = 0x00000030;
TCIFLUSH = 0x00000000;
TCOFLUSH = 0x00000001;
TCIOFLUSH = 0x00000002;
CS5 = 0x00000000;
CS6 = 0x00000010;
CS7 = 0x00000020;
CS8 = 0x00000030;
CSTOPB = 0x00000040;
CREAD = 0x00000080;
PARENB = 0x00000100;
PARODD = 0x00000200;
B0 = 0;
B50 = 1;
B75 = 2;
B110 = 3;
B134 = 4;
B150 = 5;
B200 = 6;
B300 = 7;
B600 = 8;
B1200 = 8;
B1800 = 10;
B2400 = 11;
B4800 = 12;
B9600 = 13;
B19200 = 14;
B38400 = 15;
B57600 = 4097;
B115200 = 4098;
B230400 = 4099;
//poll.h stuff
POLLIN = 0x0001;
POLLPRI = 0x0002;
POLLOUT = 0x0004;
POLLERR = 0x0008;
POLLNVAL = 0x0020;
//select.h stuff
}
public int errno() {
return Native.getLastError();
}
public void cfmakeraw(Termios termios) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
m_Clib.cfmakeraw(t);
t.update(termios);
}
public int fcntl(int fd, int cmd, int[] arg) {
return m_Clib.fcntl(fd, cmd, arg);
}
public int fcntl(int fd, int cmd, int arg) {
return m_Clib.fcntl(fd, cmd, arg);
}
public int tcdrain(int fd) {
return m_Clib.tcdrain(fd);
}
public int cfgetispeed(Termios termios) {
return m_Clib.cfgetispeed(new Linux_C_lib.termios(termios)).intValue();
}
public int cfgetospeed(Termios termios) {
return m_Clib.cfgetospeed(new Linux_C_lib.termios(termios)).intValue();
}
public int cfsetispeed(Termios termios, int speed) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
int ret = m_Clib.cfsetispeed(t, new NativeLong(speed));
t.update(termios);
return ret;
}
public int cfsetospeed(Termios termios, int speed) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
int ret = m_Clib.cfsetospeed(t, new NativeLong(speed));
t.update(termios);
return ret;
}
public int open(String s, int t) {
if (s != null && !s.startsWith("/"))
s = DEVICE_DIR_PATH + s;
return m_Clib.open(s, t);
}
public int read(int fd, byte[] buffer, int len) {
return m_Clib.read(fd, ByteBuffer.wrap(buffer), new NativeLong(len)).intValue();
}
public int write(int fd, byte[] buffer, int len) {
return m_Clib.write(fd, ByteBuffer.wrap(buffer), new NativeLong(len)).intValue();
}
public int close(int fd) {
return m_Clib.close(fd);
}
public int tcflush(int fd, int b) {
return m_Clib.tcflush(fd, b);
}
public int tcgetattr(int fd, Termios termios) {
Linux_C_lib.termios t = new Linux_C_lib.termios();
int ret = m_Clib.tcgetattr(fd, t);
t.update(termios);
return ret;
}
public void perror(String msg) {
m_Clib.perror(msg);
}
public int tcsendbreak(int fd, int duration) {
// If duration is not zero, it sends zero-valued bits for duration*N seconds,
// where N is at least 0.25, and not more than 0.5.
return m_Clib.tcsendbreak(fd, duration / 250);
}
public int tcsetattr(int fd, int cmd, Termios termios) {
return m_Clib.tcsetattr(fd, cmd, new Linux_C_lib.termios(termios));
}
public void FD_CLR(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] &= ~(1 << (fd % FDSetImpl.NFBBITS));
}
public boolean FD_ISSET(int fd, FDSet set) {
if (set == null)
return false;
FDSetImpl p = (FDSetImpl) set;
return (p.bits[fd / FDSetImpl.NFBBITS] & (1 << (fd % FDSetImpl.NFBBITS))) != 0;
}
public void FD_SET(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] |= 1 << (fd % FDSetImpl.NFBBITS);
}
public void FD_ZERO(FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
java.util.Arrays.fill(p.bits, 0);
}
public int select(int nfds, FDSet rfds, FDSet wfds, FDSet efds, TimeVal timeout) {
Linux_C_lib.TimeVal tout = null;
if (timeout != null)
tout = new Linux_C_lib.TimeVal(timeout);
int[] r = rfds != null ? ((FDSetImpl) rfds).bits : null;
int[] w = wfds != null ? ((FDSetImpl) wfds).bits : null;
int[] e = efds != null ? ((FDSetImpl) efds).bits : null;
return m_Clib.select(nfds, r, w, e, tout);
}
public int poll(Pollfd fds[], int nfds, int timeout) {
pollfd[] pfds = new pollfd[fds.length];
for (int i = 0; i < nfds; i++)
pfds[i] = new pollfd(fds[i]);
int ret = m_Clib.poll(pfds, nfds, timeout);
for(int i = 0; i < nfds; i++)
fds[i].revents = pfds[i].revents;
return ret;
}
public FDSet newFDSet() {
return new FDSetImpl();
}
public int ioctl(int fd, int cmd, int[] data) {
return m_Clib.ioctl(fd, cmd, data);
}
// This ioctl is Linux specific, so keep it private for now
private int ioctl(int fd, int cmd, serial_struct data) {
// Do the logging here as this does not go through the JTermios which normally does the logging
log = log && log(5, "> ioctl(%d,%d,%s)\n", fd, cmd, data);
int ret = m_Clib.ioctl(fd, cmd, data);
log = log && log(3, "< tcsetattr(%d,%d,%s) => %d\n", fd, cmd, data, ret);
return ret;
}
public String getPortNamePattern() {
return "^tty.*";
}
public List<String> getPortList() {
File dir = new File(DEVICE_DIR_PATH);
if (!dir.isDirectory()) {
log = log && log(1, "device directory %s does not exist\n", DEVICE_DIR_PATH);
return null;
}
String[] devs = dir.list();
LinkedList<String> list = new LinkedList<String>();
Pattern p = JTermios.getPortNamePattern(this);
if (devs != null) {
for (int i = 0; i < devs.length; i++) {
String s = devs[i];
if (p.matcher(s).matches())
list.add(s);
}
}
return list;
}
public void shutDown() {
}
public int setspeed(int fd, Termios termios, int speed) {
int c = speed;
int r;
for (int i = 0; i < m_BaudRates.length; i += 2) {
if (m_BaudRates[i] == speed) {
// found the baudrate from the table
// in case custom divisor was in use, turn it off first
serial_struct ss = new serial_struct();
// not every driver supports TIOCGSERIAL, so if it fails, just ignore it
if ((r = ioctl(fd, TIOCGSERIAL, ss)) == 0) {
ss.flags &= ~ASYNC_SPD_MASK;
if ((r = ioctl(fd, TIOCSSERIAL, ss)) != 0)
return r;
}
// now set the speed with the constant from the table
c = m_BaudRates[i + 1];
if ((r = JTermios.cfsetispeed(termios, c)) != 0)
return r;
if ((r = JTermios.cfsetospeed(termios, c)) != 0)
return r;
if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0)
return r;
return 0;
}
}
// baudrate not defined in the table, try custom divisor approach
// configure port to use custom speed instead of 38400
serial_struct ss = new serial_struct();
if ((r = ioctl(fd, TIOCGSERIAL, ss)) != 0)
return r;
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (speed / 2)) / speed;
int closestSpeed = ss.baud_base / ss.custom_divisor;
if (closestSpeed < speed * 98 / 100 || closestSpeed > speed * 102 / 100) {
log = log && log(1, "best available baudrate %d not close enough to requested %d \n", closestSpeed, speed);
return -1;
}
if ((r = ioctl(fd, TIOCSSERIAL, ss)) != 0)
return r;
if ((r = JTermios.cfsetispeed(termios, B38400)) != 0)
return r;
if ((r = JTermios.cfsetospeed(termios, B38400)) != 0)
return r;
if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0)
return r;
return 0;
}
} |
package org.apache.commons.lang.time;
/**
* <p><code>StopWatch</code> provides a convenient API for timings.</p>
*
* <p>The methods do <b>not</b> protect against inappropriate calls. Thus you
* can call stop before start, resume before suspend or unsplit before split.
* The results are indeterminate in these cases.</p>
*
* <p>To start the watch, call {@link #start()}. At this point you can:</p>
* <ul>
* <li>{@link #split()} the watch to get the time whilst the watch continues in the
* background. {@link #unsplit()} will remove the effect of the split. At this point,
* these three options are available again.
* <li>{@link #suspend()} the watch to pause it. {@link #resume()} allows the watch
* to continue. Any time between the suspend and resume will not be counted in
* the total. At this point, these three options are available again.
* <li>{@link #stop()} the watch to complete the timing session.
* </ul>
* <p>It is intended that the output methods {@link #toString()} and {@link #getTime()}
* should only be called after stop, split or suspend, however a suitable result will
* be returned at other points.</p>
*
* @author Henri Yandell
* @author Stephen Colebourne
* @since 2.0
* @version $Id: StopWatch.java,v 1.3 2003/05/21 23:37:20 scolebourne Exp $
*/
public class StopWatch {
private static final int MILLIS_IN_HOUR = 60 * 60 * 1000;
private static final int MILLIS_IN_MINUTE = 60 * 1000;
/** The start time */
private long startTime = -1;
/** The stop time */
private long stopTime = -1;
/**
* <p>Constructor.</p>
*/
public StopWatch() {
}
/**
* <p>Start the stopwatch.</p>
*
* <p>This method starts a new timing session, clearing any previous values.</p>
*/
public void start() {
stopTime = -1;
startTime = System.currentTimeMillis();
}
/**
* <p>Stop the stopwatch.</p>
*
* <p>This method ends a new timing session, allowing the time to be retrieved.</p>
*/
public void stop() {
stopTime = System.currentTimeMillis();
}
/**
* <p>Reset the stopwatch.</p>
*
* <p>This method clears the internal values to allow the object to be reused.</p>
*/
public void reset() {
startTime = -1;
stopTime = -1;
}
/**
* <p>Split the time.</p>
*
* <p>This method sets the stop time of the watch to allow a time to be extracted.
* The start time is unaffected, enabling {@link #unsplit()} to contine the
* timing from the original start point.</p>
*/
public void split() {
stopTime = System.currentTimeMillis();
}
/**
* <p>Remove a split.</p>
*
* <p>This method clears the stop time. The start time is unaffected, enabling
* timing from the original start point to continue.</p>
*/
public void unsplit() {
stopTime = -1;
}
/**
* <p>Suspend the stopwatch for later resumption.</p>
*
* <p>This method suspends the watch until it is resumed. The watch will not include
* time between the suspend and resume calls in the total time.</p>
*/
public void suspend() {
stopTime = System.currentTimeMillis();
}
/**
* <p>Resume the stopwatch after a suspend.</p>
*
* <p>This method resumes the watch after it was suspended. The watch will not include
* time between the suspend and resume calls in the total time.</p>
*/
public void resume() {
startTime += (System.currentTimeMillis() - stopTime);
stopTime = -1;
}
/**
* <p>Get the time on the stopwatch.</p>
*
* <p>This is either the time between start and latest split, between start
* and stop, or the time between the start and the moment this method is called.</p>
*
* @return the time in milliseconds
*/
public long getTime() {
if (stopTime == -1) {
if (startTime == -1) {
return 0;
}
return (System.currentTimeMillis() - this.startTime);
}
return (this.stopTime - this.startTime);
}
/**
* <p>Gets a summary of the time that the stopwatch recorded as a string.</p>
*
* <p>The format used is ISO8601,
* <i>hours</i>:<i>minutes</i>:<i>seconds</i>.<i>milliseconds</i>.</p>
*
* @return the time as a String
*/
public String toString() {
return StopWatch.toString(getTime());
}
/**
* <p>Get the time gap as a string.</p>
*
* <p>The format used is ISO8601,
* <i>hours</i>:<i>minutes</i>:<i>seconds</i>.<i>milliseconds</i>.</p>
*
* @return the time as a String
*/
public static String toString(long time) {
int hours, minutes, seconds, milliseconds;
hours = (int) (time / MILLIS_IN_HOUR);
time = time - (hours * MILLIS_IN_HOUR);
minutes = (int) (time / MILLIS_IN_MINUTE);
time = time - (minutes * MILLIS_IN_MINUTE);
seconds = (int) (time / 1000);
time = time - (seconds * 1000);
milliseconds = (int) time;
StringBuffer buf = new StringBuffer(32);
buf.append(hours);
buf.append(':');
if (minutes < 10) {
buf.append('0');
}
buf.append(minutes);
buf.append(':');
if (seconds < 10) {
buf.append('0');
}
buf.append(seconds);
buf.append('.');
if (milliseconds < 10) {
buf.append("00");
} else if (milliseconds < 100) {
buf.append('0');
}
buf.append(milliseconds);
return buf.toString();
}
} |
package edacc.model;
import SevenZip.Compression.LZMA.Decoder;
import edacc.EDACCTaskView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.SwingUtilities;
/**
*
* @author simon
*/
public class DecompressedInputStream extends InputStream {
private long outSize;
private Decoder dec;
private InputStream input;
private int id;
private EDACCTaskView view;
long outPos = 0;
int bufPos = 0;
int curBufSize = 0;
final static int maxBufSize = 16 * 1024;
byte[] buf = new byte[maxBufSize * 2];
public DecompressedInputStream(Decoder dec, long outSize, InputStream input) {
this.dec = dec;
this.outSize = outSize;
this.input = input;
this.view = Tasks.getTaskView();
if (view != null) {
id = view.getSubTaskId();
view.setMessage(id, "Decompressing");
}
}
@Override
public synchronized void reset() throws IOException {
// this is a hack, possible error
// TODO: fix
bufPos = 0;
outPos = 0;
}
private void fillBuffer() throws IOException {
bufPos = 0;
long bytesToRead = maxBufSize;
if (outSize - outPos < bytesToRead) {
bytesToRead = outSize - outPos;
}
dec.Code(input, new OutputStream() {
@Override
public void write(byte[] b, int off, int len) throws IOException {
System.arraycopy(b, off, buf, bufPos, len);
bufPos += len;
}
@Override
public void write(int b) throws IOException {
buf[bufPos++] = (byte) b;
}
}, outSize, bytesToRead, null);
curBufSize = bufPos;
bufPos = 0;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (outPos >= outSize) {
if (view != null) {
view.subTaskFinished(id);
view = null;
}
return -1;
}
if (bufPos >= curBufSize) {
fillBuffer();
}
if (len > curBufSize - bufPos)
len = curBufSize - bufPos;
if (len > outSize - outPos)
len = (int) (outSize - outPos);
System.arraycopy(buf, bufPos, b, off, len);
bufPos += len;
outPos += len;
view.setProgress(id, outPos / (float) outSize * 100);
return len;
}
@Override
public int read() throws IOException {
if (outPos >= outSize) {
if (view != null) {
view.subTaskFinished(id);
view = null;
}
return -1;
}
if (bufPos >= curBufSize) {
fillBuffer();
}
outPos++;
if (outPos % (32 * 1024) == 0 && view != null) {
view.setProgress(id, outPos / (float) outSize * 100);
}
return buf[bufPos++];
}
@Override
public void close() throws IOException {
super.close();
if (view != null) {
view.subTaskFinished(id);
view = null;
}
}
} |
package org.concord.otrunk;
import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.concord.framework.otrunk.OTControllerRegistry;
import org.concord.framework.otrunk.OTControllerService;
import org.concord.framework.otrunk.OTID;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.OTPackage;
import org.concord.framework.otrunk.OTResourceSchema;
import org.concord.framework.otrunk.otcore.OTClass;
import org.concord.otrunk.asm.GeneratedClassLoader;
import org.concord.otrunk.datamodel.DataObjectUtil;
import org.concord.otrunk.datamodel.OTDataList;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.datamodel.OTDataObjectType;
import org.concord.otrunk.datamodel.OTDatabase;
import org.concord.otrunk.datamodel.OTExternalIDProvider;
import org.concord.otrunk.datamodel.OTTransientMapID;
import org.concord.otrunk.datamodel.OTUUID;
import org.concord.otrunk.otcore.impl.ReflectiveOTClassFactory;
import org.concord.otrunk.overlay.CompositeDatabase;
import org.concord.otrunk.view.OTConfig;
import org.concord.otrunk.xml.XMLDataObject;
public class OTObjectServiceImpl
implements OTObjectService, OTExternalIDProvider
{
public final static Logger logger =
Logger.getLogger(OTObjectServiceImpl.class.getCanonicalName());
protected OTrunkImpl otrunk;
protected OTDatabase creationDb;
protected OTDatabase mainDb;
protected ArrayList<OTObjectServiceListener> listeners =
new ArrayList<OTObjectServiceListener>();
public OTObjectServiceImpl(OTrunkImpl otrunk)
{
this.otrunk = otrunk;
}
public void setCreationDb(OTDatabase creationDb)
{
this.creationDb = creationDb;
}
public OTDatabase getCreationDb()
{
return creationDb;
}
public void setMainDb(OTDatabase mainDb)
{
this.mainDb = mainDb;
}
public OTDatabase getMainDb()
{
return mainDb;
}
public <T extends OTObject> T createObject(Class<T> objectClass)
throws Exception
{
OTObjectInternal otObjectImpl = createOTObjectInternal(objectClass);
T newObject = loadOTObject(otObjectImpl, objectClass);
return newObject;
}
protected OTObjectInternal createOTObjectInternal(
Class<? extends OTObject> objectClass)
throws Exception
{
String className = objectClass.getName();
OTClass otClass = OTrunkImpl.getOTClass(className);
if(otClass == null){
// Can't find existing otClass for this class try to make one
otClass = ReflectiveOTClassFactory.singleton.registerClass(objectClass);
if(otClass == null){
// Java class isn't a valid OTObject
throw new IllegalStateException("Invalid OTClass definition: " + className);
}
// This will add the properties for this new class plus any dependencies that
// were registered at the same time.
ReflectiveOTClassFactory.singleton.processAllNewlyRegisteredClasses();
}
OTDataObjectType type = new OTDataObjectType(objectClass.getName());
OTDataObject dataObject = createDataObject(type);
OTObjectInternal otObjectImpl =
new OTObjectInternal(dataObject, this, otClass);
return otObjectImpl;
}
public OTObject getOTObject(OTID childID) throws Exception
{
return getOTObject(childID, false);
}
@SuppressWarnings("unchecked")
public OTObject getOTObject(OTID childID, boolean reload) throws Exception
{
// sanity check
if(childID == null) {
throw new Exception("Null child id");
}
OTDataObject childDataObject = getOTDataObject(childID);
if(childDataObject == null) {
// we have a null internal object that means the child doesn't
// exist in our database/databases.
// This will happen with the aggregate views which display different overlays
// of the same object. Each overlay is going to come from a different objectService
// So if we can't find this object then we go out to OTrunk to see if it can find
// the object. The way that this happens needs to be more clear so the ramifcations
// are clear.
return otrunk.getOrphanOTObject(childID, this, reload);
}
// Look for our object to see it is already setup in the otrunk list of loaded objects
// it might be better to have each object service maintain its own list of loaded objects
OTObject otObject = otrunk.getLoadedObject(childDataObject.getGlobalId(), reload);
if(otObject != null) {
return otObject;
}
String otObjectClassStr = OTrunkImpl.getClassName(childDataObject);
if(otObjectClassStr == null) {
return null;
}
Class<? extends OTObject> otObjectClass =
(Class<? extends OTObject>) Class.forName(otObjectClassStr);
OTObjectInternal otObjectInternal =
new OTObjectInternal(childDataObject, this, OTrunkImpl.getOTClass(otObjectClassStr));
return loadOTObject(otObjectInternal, otObjectClass);
}
public OTID getOTID(String otidStr)
{
return otrunk.getOTID(otidStr);
}
public OTControllerService createControllerService() {
OTControllerRegistry registry =
otrunk.getService(OTControllerRegistry.class);
return new OTControllerServiceImpl(this, registry);
}
// This will work as long as all of the object classes are loaded by the same classloader
// if the OTClass classes are loaded by different classloaders there will probably have
// to be multiple GeneratedClassLoader
GeneratedClassLoader asmClassLoader = null;
private HashMap<String, String> preserveUUIDCallers = new HashMap<String, String>();
public GeneratedClassLoader getASMClassLoader()
{
if(asmClassLoader != null){
return asmClassLoader;
}
asmClassLoader = new GeneratedClassLoader(OTObjectServiceImpl.class.getClassLoader());
return asmClassLoader;
}
@SuppressWarnings("unchecked")
public <T extends OTObject> T loadOTObject(OTObjectInternal otObjectImpl, Class<T> otObjectClass)
throws Exception
{
T otObject = null;
if(otObjectClass.isInterface()) {
if(OTConfig.getBooleanProp(OTConfig.USE_ASM, false)){
Class<? extends AbstractOTObject> generatedClass =
getASMClassLoader().generateClass(otObjectClass, otObjectImpl.otClass());
OTObjectInternal internalObj = generatedClass.newInstance();
otObject = (T)internalObj;
internalObj.setup(otObjectImpl);
internalObj.setEventSource(internalObj);
} else {
OTBasicObjectHandler handler = new OTBasicObjectHandler(otObjectImpl, otrunk, otObjectClass);
try {
otObject = (T)Proxy.newProxyInstance(otObjectClass.getClassLoader(),
new Class[] { otObjectClass }, handler);
handler.setOTObject(otObject);
} catch (ClassCastException e){
throw new RuntimeException("The OTClass: " + otObjectClass +
" does not extend OTObject or OTObjectInterface", e);
}
}
} else if(AbstractOTObject.class.isAssignableFrom(otObjectClass)){
Class<? extends AbstractOTObject> generatedClass =
getASMClassLoader().generateClass(otObjectClass, otObjectImpl.otClass());
OTObjectInternal internalObj = generatedClass.newInstance();
otObject = (T)internalObj;
internalObj.setup(otObjectImpl);
internalObj.setEventSource(internalObj);
} else {
otObject = setResourcesFromSchema(otObjectImpl, otObjectClass);
}
notifyLoaded(otObject);
otObject.init();
otrunk.putLoadedObject(otObject, otObjectImpl.getGlobalId());
return otObject;
}
/**
* @param otObject
*/
protected void notifyLoaded(OTObject otObject)
{
for(int i=0; i < listeners.size(); i++) {
(listeners.get(i)).objectLoaded(otObject);
}
}
/**
* Track down the objects schema by looking at the type
* of class of the argument to setResources method
*
* @param dataObject
* @param otObject
*/
@SuppressWarnings("unchecked")
public <T extends OTObject> T setResourcesFromSchema(OTObjectInternal otObjectImpl, Class<T> otObjectClass)
{
Constructor<T> [] memberConstructors = otObjectClass.getConstructors();
Constructor<T> resourceConstructor = memberConstructors[0];
Class<?> [] params = resourceConstructor.getParameterTypes();
if(memberConstructors.length > 1) {
System.err.println("OTObjects should only have 1 constructor");
return null;
}
if(params == null | params.length == 0) {
try {
return otObjectClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
OTResourceSchemaHandler handler = null;
Object constructorParams [] = new Object [params.length];
int nextParam = 0;
if(params[0].isInterface() &&
OTResourceSchema.class.isAssignableFrom(params[0])){
Class<? extends OTResourceSchema> schemaClass = (Class<? extends OTResourceSchema>)params[0];
handler = new OTResourceSchemaHandler(otObjectImpl, otrunk,
schemaClass);
Class<?> [] interfaceList = new Class[] { schemaClass };
Object resources =
Proxy.newProxyInstance(schemaClass.getClassLoader(),
interfaceList, handler);
constructorParams[0] = resources;
nextParam++;
}
for(int i=nextParam; i<params.length; i++) {
// look for a service in the services list to can
// be used for this param
constructorParams[i] = otrunk.getService(params[i]);
if(constructorParams[i] == null) {
System.err.println("No service could be found to handle the\n" +
" requirement of: " + otObjectClass + "\n" +
" for: " + params[i]);
return null;
}
}
T otObject = null;
try {
otObject = resourceConstructor.newInstance(constructorParams);
// now we need to pass the otObject to the schema handler so it can
// set that as the source of OTChangeEvents
handler.setEventSource(otObject);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return otObject;
}
boolean managesObject(OTID id)
{
if(id instanceof OTTransientMapID) {
Object mapToken = ((OTTransientMapID)id).getMapToken();
if (creationDb.getDatabaseId() == null) {
System.err.println("Database with a null id!");
return false;
}
return creationDb.getDatabaseId().equals(mapToken);
}
// Check our mainDb to see if it contains the object
// FIXME there is an issue here about what the difference between the
// mainDb and the creationDb.
return mainDb.contains(id);
}
private OTDataObject createDataObject(OTDataObjectType type)
throws Exception
{
return creationDb.createDataObject(type);
}
/**
*
* @param dataParent
* @param childID
* @return
* @throws Exception
*/
OTDataObject getOTDataObject(OTID childID)
throws Exception
{
// sanity check
if(childID == null) {
throw new Exception("Null child Id");
}
OTDataObject childDataObject = mainDb.getOTDataObject(null, childID);
return childDataObject;
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTObjectService#copyObject(org.concord.framework.otrunk.OTObject, int)
*/
public OTObject copyObject(OTObject original, int maxDepth)
throws Exception
{
OTObjectList orphanObjectList = null;
OTDataObject rootDO = otrunk.getRootDataObject();
OTObject root = getOTObject(rootDO.getGlobalId());
if(root instanceof OTSystem) {
orphanObjectList = ((OTSystem)root).getLibrary();
}
return copyObject(original, orphanObjectList, maxDepth);
}
public OTObject copyObject(OTObject original, OTObjectList orphanObjectList,
int maxDepth)
throws Exception
{
// make a copy of the original objects data object
// it is easier to copy data objects than the actual objects
OTDataObject originalDataObject = getOTDataObject(original);
// Assume the object list is our object list impl
OTDataList orphanDataList =
((OTObjectListImpl)orphanObjectList).getDataList();
OTDataObject copyDataObject =
DataObjectUtil.copy(originalDataObject, creationDb,
orphanDataList, maxDepth, this, otrunk.getDataObjectFinder(), false);
return getOTObject(copyDataObject.getGlobalId());
}
public void copyInto(OTObject source, OTObject destination, int maxDepth, boolean onlyModifications) throws Exception {
OTObjectList orphanObjectList = null;
OTDataObject rootDO = otrunk.getRootDataObject();
OTObject root = getOTObject(rootDO.getGlobalId());
if(root instanceof OTSystem) {
orphanObjectList = ((OTSystem)root).getLibrary();
}
// make a copy of the original objects data object
// it is easier to copy data objects than the actual objects
OTDataObject sourceDO = getOTDataObject(source);
OTDataObject destDO = getOTDataObject(destination);
// Assume the object list is our object list impl
OTDataList orphanDataList = null;
if (orphanObjectList != null) {
orphanDataList = ((OTObjectListImpl)orphanObjectList).getDataList();
}
// OTDataObject copyDataObject = DataObjectUtil.copy(originalDataObject, creationDb, orphanDataList, maxDepth, this, otrunk.getDataObjectFinder());
ArrayList<OTObjectService> idProviders = new ArrayList<OTObjectService>();
idProviders.add(source.getOTObjectService());
idProviders.add(destination.getOTObjectService());
DataObjectUtil.copyInto(sourceDO, destDO, orphanDataList, maxDepth, this, otrunk.getDataObjectFinder(), onlyModifications);
}
public void addObjectServiceListener(OTObjectServiceListener listener)
{
if(listeners.contains(listener)) {
return;
}
listeners.add(listener);
}
public void removeObjectServiceListener(OTObjectServiceListener listener)
{
listeners.remove(listener);
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTObjectService#registerPackageClass(java.lang.Class)
*/
public void registerPackageClass(Class<? extends OTPackage> packageClass)
{
otrunk.registerPackageClass(packageClass);
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTObjectService#getOTrunkService(java.lang.Class)
*/
public <T> T getOTrunkService(Class<T> serviceInterface)
{
return otrunk.getService(serviceInterface);
}
public String getExternalID(OTObject object)
{
OTID globalId = object.getGlobalId();
return getExternalID(globalId);
}
public String getExternalID(OTID otid)
{
if(mainDb instanceof CompositeDatabase){
return ((CompositeDatabase)mainDb).resolveID(otid).toExternalForm();
}
if(otid instanceof OTTransientMapID){
throw new RuntimeException("Cannot get an external id for " + otid +
" using this object service with mainDb: " + mainDb);
}
return otid.toExternalForm();
}
static OTDataObject getOTDataObject(OTObject otObject)
{
if(otObject instanceof OTObjectInternal){
return ((OTObjectInternal)otObject).dataObject;
}
return OTInvocationHandler.getOTDataObject(otObject);
}
public URL getCodebase(OTObject otObject)
{
try {
OTDataObject dataObject = getOTDataObject(otObject);
return dataObject.getCodebase();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void preserveUUID(OTObject otObject)
{
OTID id = otObject.getGlobalId();
if(!(id instanceof OTUUID)){
logPreserveUUIDError("object does not have a UUID " + otObject);
return;
}
try {
OTDataObject dataObject = getOTDataObject(id);
if(!(dataObject instanceof XMLDataObject)){
logPreserveUUIDError("object is not backed by a XMLDatabase " + otObject);
return;
}
((XMLDataObject)dataObject).setPreserveUUID(true);
} catch (Exception e) {
e.printStackTrace();
}
}
private void logPreserveUUIDError(String string)
{
logger.warning(string);
Throwable throwable =
new IllegalArgumentException(string);
StackTraceElement stackTraceElement = throwable.getStackTrace()[2];
String callerStr = stackTraceElement.getClassName() + "." +
stackTraceElement.getMethodName();
Object value = preserveUUIDCallers.get(callerStr);
if(value != null){
return;
}
preserveUUIDCallers.put(callerStr, callerStr);
logger.log(Level.FINE, "first call from method which caused bad preserveUUID call",
throwable);
}
} |
// You are free to use it for your own good as long as it doesn't hurt anybody.
// For questions or suggestions please contact me at httpeter@gmail.com
package org.op.data.repository;
import java.io.Serializable;
import java.util.List;
import org.op.data.model.Activity;
import org.op.data.model.Contact;
import org.op.data.model.Subscription;
import org.op.data.model.SystemUser;
public class AdminRepository extends DefaultRepository implements Serializable
{
private static final long serialVersionUID = -7610678289904424970L;
public SystemUser getSystemUser(String username, String password, String uRole)
{
try
{
return (SystemUser) this.getEm().createQuery("select u from SystemUser u "
+ "where u.username = :uName "
+ "and :pWord = u.password "
+ "and u.userRole = :uRole")
.setParameter("uName", username)
.setParameter("pWord", password)
.setParameter("uRole", uRole)
.getSingleResult();
} catch (Exception e)
{
e.printStackTrace(System.out);
return null;
}
}
// Methods below should be changed so they fit the new datastructure
public List<Activity> getProjectActivities(long projectId, boolean isMasterActivity)
{
return this.getEm()
.createQuery("select a from Activity a "
+ "where a.project.id = :projectId")
.setParameter("projectId", projectId)
.setParameter("isMasterActivity", isMasterActivity)
.getResultList();
}
public List<Subscription> getContactSubscriptions(Contact c)
{
return this.getEm()
.createQuery("select s from Subscription s "
+ "where s.contact.id = :contactId")
.setParameter("contactId", c.getId())
.getResultList();
}
public boolean subscriptionRemoved(Subscription s)
{
try
{
this.getEm().getTransaction().begin();
s = this.getEm().merge(s);
this.getEm().remove(s);
this.getEm().getTransaction().commit();
this.getEm().clear();
return true;
} catch (Exception e)
{
e.printStackTrace(System.out);
this.getEm().getTransaction().rollback();
return false;
}
}
} |
package org.orbeon.oxf.xforms;
import org.orbeon.oxf.properties.Properties;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class XFormsProperties {
public static final String XFORMS_PROPERTY_PREFIX = "oxf.xforms.";
// Document properties
public static final String STATE_HANDLING_PROPERTY = "state-handling";
public static final String STATE_HANDLING_SERVER_VALUE = "server";
public static final String STATE_HANDLING_CLIENT_VALUE = "client";
public static final String STATE_HANDLING_SESSION_VALUE = "session"; // deprecated
public static final String NOSCRIPT_PROPERTY = "noscript";
public static final String AJAX_PORTLET_PROPERTY = "ajax-portlet";
public static final String READONLY_APPEARANCE_PROPERTY = "readonly-appearance";
public static final String READONLY_APPEARANCE_STATIC_VALUE = "static";
public static final String READONLY_APPEARANCE_DYNAMIC_VALUE = "dynamic";
public static final String ORDER_PROPERTY = "order";
public static final String DEFAULT_ORDER_PROPERTY = "label control help alert hint";
public static final String LABEL_ELEMENT_NAME_PROPERTY = "label-element";
public static final String HINT_ELEMENT_NAME_PROPERTY = "hint-element";
public static final String HELP_ELEMENT_NAME_PROPERTY = "help-element";
public static final String ALERT_ELEMENT_NAME_PROPERTY = "alert-element";
public static final String EXTERNAL_EVENTS_PROPERTY = "external-events";
private static final String READONLY_PROPERTY = "readonly";
private static final String OPTIMIZE_GET_ALL_PROPERTY = "optimize-get-all";
private static final String OPTIMIZE_LOCAL_SUBMISSION_PROPERTY = "optimize-local-submission";
// private static final String XFORMS_OPTIMIZE_LOCAL_INSTANCE_LOADS_PROPERTY = "optimize-local-instance-loads";
private static final String OPTIMIZE_RELEVANCE_PROPERTY = "optimize-relevance";
private static final String EXCEPTION_ON_INVALID_CLIENT_CONTROL_PROPERTY = "exception-invalid-client-control";
private static final String AJAX_SHOW_LOADING_ICON_PROPERTY = "ajax.show-loading-icon";
private static final String AJAX_SHOW_ERRORS_PROPERTY = "ajax.show-errors";
private static final String MINIMAL_RESOURCES_PROPERTY = "minimal-resources";
private static final String COMBINE_RESOURCES_PROPERTY = "combine-resources";
private static final String SKIP_SCHEMA_VALIDATION_PROPERTY = "skip-schema-validation";
private static final String TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX = "format.";
private static final String TYPE_INPUT_FORMAT_PROPERTY_PREFIX = "format.input.";
private static final String DATE_FORMAT_PROPERTY = "format.date";
private static final String DATETIME_FORMAT_PROPERTY = "format.dateTime";
private static final String TIME_FORMAT_PROPERTY = "format.time";
private static final String DECIMAL_FORMAT_PROPERTY = "format.decimal";
private static final String INTEGER_FORMAT_PROPERTY = "format.integer";
private static final String FLOAT_FORMAT_PROPERTY = "format.float";
private static final String DOUBLE_FORMAT_PROPERTY = "format.double";
private static final String DATE_FORMAT_INPUT_PROPERTY = "format.input.date";
private static final String TIME_FORMAT_INPUT_PROPERTY = "format.input.time";
private static final String DATEPICKER_PROPERTY = "datepicker";
private static final String XHTML_EDITOR_PROPERTY = "htmleditor";
private static final String SESSION_HEARTBEAT_PROPERTY = "session-heartbeat";
public static final String SESSION_HEARTBEAT_DELAY_PROPERTY = "session-heartbeat-delay";
public static final String FCK_EDITOR_BASE_PATH_PROPERTY = "fck-editor-base-path";
private static final String DELAY_BEFORE_INCREMENTAL_REQUEST_PROPERTY = "delay-before-incremental-request";
private static final String DELAY_BEFORE_FORCE_INCREMENTAL_REQUEST_PROPERTY = "delay-before-force-incremental-request";
private static final String DELAY_BEFORE_GECKO_COMMUNICATION_ERROR_PROPERTY = "delay-before-gecko-communication-error";
private static final String DELAY_BEFORE_CLOSE_MINIMAL_DIALOG_PROPERTY = "delay-before-close-minimal-dialog";
private static final String DELAY_BEFORE_AJAX_TIMEOUT_PROPERTY = "delay-before-ajax-timeout";
private static final String INTERNAL_SHORT_DELAY_PROPERTY = "internal-short-delay";
private static final String DELAY_BEFORE_DISPLAY_LOADING_PROPERTY = "delay-before-display-loading";
private static final String REQUEST_RETRIES_PROPERTY = "request-retries";
private static final String DEBUG_WINDOW_HEIGHT_PROPERTY = "debug-window-height";
private static final String DEBUG_WINDOW_WIDTH_PROPERTY = "debug-window-width";
private static final String LOADING_MIN_TOP_PADDING_PROPERTY = "loading-min-top-padding";
private static final String REVISIT_HANDLING_PROPERTY = "revisit-handling";
public static final String REVISIT_HANDLING_RESTORE_VALUE = "restore";
public static final String REVISIT_HANDLING_RELOAD_VALUE = "reload";
public static final String HELP_HANDLER_PROPERTY = "help-handler";
private static final String HELP_TOOLTIP_PROPERTY = "help-tooltip";
public static final String OFFLINE_SUPPORT_PROPERTY = "offline";
public static final String OFFLINE_REPEAT_COUNT_PROPERTY = "offline-repeat-count";
public static final String FORWARD_SUBMISSION_HEADERS = "forward-submission-headers";
private static final String COMPUTED_BINDS_PROPERTY = "computed-binds";
public static final String COMPUTED_BINDS_RECALCULATE_VALUE = "recalculate";
public static final String COMPUTED_BINDS_REVALIDATE_VALUE = "revalidate";
public static final String DISPATCH_INITIAL_EVENTS = "dispatch-initial-events";
public static final String NEW_XHTML_LAYOUT = "new-xhtml-layout";
private static final String ENCRYPT_ITEM_VALUES_PROPERTY = "encrypt-item-values";
public static class PropertyDefinition {
private String name;
private Object defaultValue;
private boolean isPropagateToClient;
public PropertyDefinition(String name, String defaultValue, boolean propagateToClient) {
this.name = name;
this.defaultValue = defaultValue;
isPropagateToClient = propagateToClient;
}
public PropertyDefinition(String name, boolean defaultValue, boolean propagateToClient) {
this.name = name;
this.defaultValue = new Boolean(defaultValue);
isPropagateToClient = propagateToClient;
}
public PropertyDefinition(String name, int defaultValue, boolean propagateToClient) {
this.name = name;
this.defaultValue = new Integer(defaultValue);
isPropagateToClient = propagateToClient;
}
public String getName() {
return name;
}
public Object getDefaultValue() {
return defaultValue;
}
public boolean isPropagateToClient() {
return isPropagateToClient;
}
public Object parseProperty(String value) {
if (getDefaultValue() instanceof Integer) {
return new Integer(value);
} else if (getDefaultValue() instanceof Boolean) {
return new Boolean(value);
} else {
return value;
}
}
}
private static final PropertyDefinition[] SUPPORTED_DOCUMENT_PROPERTIES_DEFAULTS = {
new PropertyDefinition(STATE_HANDLING_PROPERTY, STATE_HANDLING_SERVER_VALUE, false),
new PropertyDefinition(NOSCRIPT_PROPERTY, false, false),
new PropertyDefinition(AJAX_PORTLET_PROPERTY, false, false),
new PropertyDefinition(READONLY_PROPERTY, false, false),
new PropertyDefinition(READONLY_APPEARANCE_PROPERTY, READONLY_APPEARANCE_DYNAMIC_VALUE, false),
new PropertyDefinition(ORDER_PROPERTY, DEFAULT_ORDER_PROPERTY, false),
new PropertyDefinition(LABEL_ELEMENT_NAME_PROPERTY, "label", false),
new PropertyDefinition(HINT_ELEMENT_NAME_PROPERTY, "label", false),
new PropertyDefinition(HELP_ELEMENT_NAME_PROPERTY, "label", false),
new PropertyDefinition(ALERT_ELEMENT_NAME_PROPERTY, "label", false),
new PropertyDefinition(EXTERNAL_EVENTS_PROPERTY, "", false),
new PropertyDefinition(OPTIMIZE_GET_ALL_PROPERTY, true, false),
new PropertyDefinition(OPTIMIZE_LOCAL_SUBMISSION_PROPERTY, true, false),
new PropertyDefinition(OPTIMIZE_RELEVANCE_PROPERTY, false, false),
new PropertyDefinition(EXCEPTION_ON_INVALID_CLIENT_CONTROL_PROPERTY, false, false),
new PropertyDefinition(AJAX_SHOW_LOADING_ICON_PROPERTY, true, false),
new PropertyDefinition(AJAX_SHOW_ERRORS_PROPERTY, true, false),
new PropertyDefinition(MINIMAL_RESOURCES_PROPERTY, true, false),
new PropertyDefinition(COMBINE_RESOURCES_PROPERTY, true, false),
new PropertyDefinition(SKIP_SCHEMA_VALIDATION_PROPERTY, false, false),
new PropertyDefinition(COMPUTED_BINDS_PROPERTY, COMPUTED_BINDS_RECALCULATE_VALUE, false),
new PropertyDefinition(DISPATCH_INITIAL_EVENTS, true, false),
new PropertyDefinition(NEW_XHTML_LAYOUT, false, false),
new PropertyDefinition(DATE_FORMAT_PROPERTY, "if (. castable as xs:date) then format-date(xs:date(.), '[FNn] [MNn] [D], [Y] [ZN]', 'en', (), ()) else .", false),
new PropertyDefinition(DATETIME_FORMAT_PROPERTY, "if (. castable as xs:dateTime) then format-dateTime(xs:dateTime(.), '[FNn] [MNn] [D], [Y] [H01]:[m01]:[s01] [ZN]', 'en', (), ()) else .", false),
new PropertyDefinition(TIME_FORMAT_PROPERTY, "if (. castable as xs:time) then format-time(xs:time(.), '[H01]:[m01]:[s01] [ZN]', 'en', (), ()) else .", false),
new PropertyDefinition(DECIMAL_FORMAT_PROPERTY, "if (. castable as xs:decimal) then format-number(xs:decimal(.),'
new PropertyDefinition(INTEGER_FORMAT_PROPERTY, "if (. castable as xs:integer) then format-number(xs:integer(.),'
new PropertyDefinition(FLOAT_FORMAT_PROPERTY, "if (. castable as xs:float) then format-number(xs:float(.),'#,##0.000') else .", false),
new PropertyDefinition(DOUBLE_FORMAT_PROPERTY, "if (. castable as xs:double) then format-number(xs:double(.),'#,##0.000') else .", false),
new PropertyDefinition(ENCRYPT_ITEM_VALUES_PROPERTY, true, false),
new PropertyDefinition(OFFLINE_REPEAT_COUNT_PROPERTY, 4, false),
new PropertyDefinition(FORWARD_SUBMISSION_HEADERS, "Authorization", false),
// Properties to propagate to the client
new PropertyDefinition(SESSION_HEARTBEAT_PROPERTY, true, true),
new PropertyDefinition(SESSION_HEARTBEAT_DELAY_PROPERTY, 12 * 60 * 60 * 800, true), // dynamic; 80 % of 12 hours in ms
new PropertyDefinition(FCK_EDITOR_BASE_PATH_PROPERTY, "/ops/fckeditor/", true),// dynamic
new PropertyDefinition(DELAY_BEFORE_INCREMENTAL_REQUEST_PROPERTY, 500, true),
new PropertyDefinition(DELAY_BEFORE_FORCE_INCREMENTAL_REQUEST_PROPERTY, 2000, true),
new PropertyDefinition(DELAY_BEFORE_GECKO_COMMUNICATION_ERROR_PROPERTY, 5000, true),
new PropertyDefinition(DELAY_BEFORE_CLOSE_MINIMAL_DIALOG_PROPERTY, 5000, true),
new PropertyDefinition(DELAY_BEFORE_AJAX_TIMEOUT_PROPERTY, -1, true),
new PropertyDefinition(INTERNAL_SHORT_DELAY_PROPERTY, 10, true),
new PropertyDefinition(DELAY_BEFORE_DISPLAY_LOADING_PROPERTY, 500, true),
new PropertyDefinition(REQUEST_RETRIES_PROPERTY, 1, true),
new PropertyDefinition(DEBUG_WINDOW_HEIGHT_PROPERTY, 600, true),
new PropertyDefinition(DEBUG_WINDOW_WIDTH_PROPERTY, 300, true),
new PropertyDefinition(LOADING_MIN_TOP_PADDING_PROPERTY, 10, true),
new PropertyDefinition(REVISIT_HANDLING_PROPERTY, REVISIT_HANDLING_RESTORE_VALUE, true),
new PropertyDefinition(HELP_HANDLER_PROPERTY, false, true),// dynamic
new PropertyDefinition(HELP_TOOLTIP_PROPERTY, false, true),
new PropertyDefinition(OFFLINE_SUPPORT_PROPERTY, false, true),// dynamic
new PropertyDefinition(DATE_FORMAT_INPUT_PROPERTY, "[M]/[D]/[Y]", true),
new PropertyDefinition(TIME_FORMAT_INPUT_PROPERTY, "[h]:[m]:[s] [P]", true),
new PropertyDefinition(DATEPICKER_PROPERTY, "yui", true),
new PropertyDefinition(XHTML_EDITOR_PROPERTY, "yui", true)
};
private static final Map SUPPORTED_DOCUMENT_PROPERTIES;
static {
final Map tempMap = new HashMap();
for (int i = 0; i < SUPPORTED_DOCUMENT_PROPERTIES_DEFAULTS.length; i++) {
final PropertyDefinition propertyDefinition = SUPPORTED_DOCUMENT_PROPERTIES_DEFAULTS[i];
tempMap.put(propertyDefinition.name, propertyDefinition);
}
SUPPORTED_DOCUMENT_PROPERTIES = Collections.unmodifiableMap(tempMap);
}
// Global properties
private static final String PASSWORD_PROPERTY = XFORMS_PROPERTY_PREFIX + "password";
private static final String CACHE_DOCUMENT_PROPERTY = XFORMS_PROPERTY_PREFIX + "cache.document";
private static final boolean CACHE_DOCUMENT_DEFAULT = true;
private static final String STORE_APPLICATION_SIZE_PROPERTY = XFORMS_PROPERTY_PREFIX + "store.application.size";
private static final int STORE_APPLICATION_SIZE_DEFAULT = 20 * 1024 * 1024;
private static final String STORE_APPLICATION_USERNAME_PROPERTY = XFORMS_PROPERTY_PREFIX + "store.application.username";
private static final String STORE_APPLICATION_PASSWORD_PROPERTY = XFORMS_PROPERTY_PREFIX + "store.application.password";
private static final String STORE_APPLICATION_URI_PROPERTY = XFORMS_PROPERTY_PREFIX + "store.application.uri";
private static final String STORE_APPLICATION_COLLECTION_PROPERTY = XFORMS_PROPERTY_PREFIX + "store.application.collection";
private static final String STORE_APPLICATION_USERNAME_DEFAULT = "guest";
private static final String STORE_APPLICATION_PASSWORD_DEFAULT = "";
private static final String STORE_APPLICATION_URI_DEFAULT = "xmldb:exist:
private static final String STORE_APPLICATION_COLLECTION_DEFAULT = "/db/orbeon/xforms/cache/";
private static final String GZIP_STATE_PROPERTY = XFORMS_PROPERTY_PREFIX + "gzip-state"; // global but could possibly be per document
private static final boolean GZIP_STATE_DEFAULT = true;
private static final String HOST_LANGUAGE_AVTS_PROPERTY = XFORMS_PROPERTY_PREFIX + "host-language-avts"; // global but should be per document
private static final boolean HOST_LANGUAGE_AVTS_DEFAULT = false;
private static final String CACHE_COMBINED_RESOURCES_PROPERTY = XFORMS_PROPERTY_PREFIX + "cache-combined-resources"; // global but could possibly be per document
private static final boolean CACHE_COMBINED_RESOURCES_DEFAULT = false;
private static final String TEST_AJAX_PROPERTY = XFORMS_PROPERTY_PREFIX + "test.ajax";
private static final boolean TEST_AJAX_DEFAULT = false;
// The following global properties are deprecated in favor of the persistent application store
private static final String CACHE_SESSION_SIZE_PROPERTY = XFORMS_PROPERTY_PREFIX + "cache.session.size";
private static final int CACHE_SESSION_SIZE_DEFAULT = 1024 * 1024;
private static final String CACHE_APPLICATION_SIZE_PROPERTY = XFORMS_PROPERTY_PREFIX + "cache.application.size";
private static final int CACHE_APPLICATION_SIZE_DEFAULT = 1024 * 1024;
/**
* Return a PropertyDefinition given a property name.
*
* @param propertyName property name
* @return PropertyDefinition
*/
public static PropertyDefinition getPropertyDefinition(String propertyName) {
return (XFormsProperties.PropertyDefinition) SUPPORTED_DOCUMENT_PROPERTIES.get(propertyName);
}
/**
* Return an iterator over property definition entries.
*
* @return Iterator<Entry<String,PropertyDefinition>> mapping a property name to a definition
*/
public static Iterator getPropertyDefinitionEntryIterator() {
return SUPPORTED_DOCUMENT_PROPERTIES.entrySet().iterator();
}
public static Object parseProperty(String propertyName, String propertyValue) {
final PropertyDefinition propertyDefinition = getPropertyDefinition(propertyName);
return propertyDefinition.parseProperty(propertyValue);
}
public static String getXFormsPassword() {
return Properties.instance().getPropertySet().getString(PASSWORD_PROPERTY);
}
public static boolean isCacheDocument() {
return Properties.instance().getPropertySet().getBoolean
(CACHE_DOCUMENT_PROPERTY, CACHE_DOCUMENT_DEFAULT).booleanValue();
}
public static int getSessionStoreSize() {
return Properties.instance().getPropertySet().getInteger
(CACHE_SESSION_SIZE_PROPERTY, CACHE_SESSION_SIZE_DEFAULT).intValue();
}
public static int getApplicationStateStoreSize() {
return Properties.instance().getPropertySet().getInteger
(STORE_APPLICATION_SIZE_PROPERTY, STORE_APPLICATION_SIZE_DEFAULT).intValue();
}
public static int getApplicationCacheSize() {
return Properties.instance().getPropertySet().getInteger
(CACHE_APPLICATION_SIZE_PROPERTY, CACHE_APPLICATION_SIZE_DEFAULT).intValue();
}
public static boolean isGZIPState() {
return Properties.instance().getPropertySet().getBoolean
(GZIP_STATE_PROPERTY, GZIP_STATE_DEFAULT).booleanValue();
}
public static boolean isAjaxTest() {
return Properties.instance().getPropertySet().getBoolean
(TEST_AJAX_PROPERTY, TEST_AJAX_DEFAULT).booleanValue();
}
public static String getStoreUsername() {
return Properties.instance().getPropertySet().getString
(STORE_APPLICATION_USERNAME_PROPERTY, STORE_APPLICATION_USERNAME_DEFAULT);
}
public static String getStorePassword() {
return Properties.instance().getPropertySet().getString
(STORE_APPLICATION_PASSWORD_PROPERTY, STORE_APPLICATION_PASSWORD_DEFAULT);
}
public static String getStoreURI() {
return Properties.instance().getPropertySet().getStringOrURIAsString
(STORE_APPLICATION_URI_PROPERTY, STORE_APPLICATION_URI_DEFAULT);
}
public static String getStoreCollection() {
return Properties.instance().getPropertySet().getString
(STORE_APPLICATION_COLLECTION_PROPERTY, STORE_APPLICATION_COLLECTION_DEFAULT);
}
public static boolean isHostLanguageAVTs() {
return Properties.instance().getPropertySet().getBoolean
(HOST_LANGUAGE_AVTS_PROPERTY, HOST_LANGUAGE_AVTS_DEFAULT).booleanValue();
}
public static boolean isCacheCombinedResources() {
return Properties.instance().getPropertySet().getBoolean
(CACHE_COMBINED_RESOURCES_PROPERTY, CACHE_COMBINED_RESOURCES_DEFAULT).booleanValue();
}
public static String getStateHandling(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, STATE_HANDLING_PROPERTY);
}
public static boolean isClientStateHandling(XFormsContainingDocument containingDocument) {
return getStateHandling(containingDocument).equals(STATE_HANDLING_CLIENT_VALUE);
}
public static boolean isLegacySessionStateHandling(XFormsContainingDocument containingDocument) {
return getStateHandling(containingDocument).equals(STATE_HANDLING_SESSION_VALUE);
}
public static boolean isNoscript(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, NOSCRIPT_PROPERTY);
}
public static boolean isAjaxPortlet(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, AJAX_PORTLET_PROPERTY);
}
public static boolean isOptimizeGetAllSubmission(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, OPTIMIZE_GET_ALL_PROPERTY);
}
public static boolean isOptimizeLocalSubmission(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, OPTIMIZE_LOCAL_SUBMISSION_PROPERTY);
}
public static boolean isExceptionOnInvalidClientControlId(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, EXCEPTION_ON_INVALID_CLIENT_CONTROL_PROPERTY);
}
public static boolean isAjaxShowLoadingIcon(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, AJAX_SHOW_LOADING_ICON_PROPERTY);
}
public static boolean isAjaxShowErrors(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, AJAX_SHOW_ERRORS_PROPERTY);
}
public static boolean isMinimalResources(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, MINIMAL_RESOURCES_PROPERTY);
}
public static boolean isCombinedResources(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, COMBINE_RESOURCES_PROPERTY);
}
public static boolean isOptimizeRelevance(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, OPTIMIZE_RELEVANCE_PROPERTY);
}
public static boolean isSkipSchemaValidation(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, SKIP_SCHEMA_VALIDATION_PROPERTY);
}
public static String getComputedBinds(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, COMPUTED_BINDS_PROPERTY);
}
public static boolean isDispatchInitialEvents(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, DISPATCH_INITIAL_EVENTS);
}
public static boolean isNewXHTMLLayout(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, NEW_XHTML_LAYOUT);
}
public static boolean isReadonly(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, READONLY_PROPERTY);
}
public static String getReadonlyAppearance(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, READONLY_APPEARANCE_PROPERTY);
}
public static String getOrder(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, ORDER_PROPERTY);
}
public static String getLabelElementName(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, LABEL_ELEMENT_NAME_PROPERTY);
}
public static String getHintElementName(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, HINT_ELEMENT_NAME_PROPERTY);
}
public static String getHelpElementName(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, HELP_ELEMENT_NAME_PROPERTY);
}
public static String getAlertElementName(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, ALERT_ELEMENT_NAME_PROPERTY);
}
public static boolean isStaticReadonlyAppearance(XFormsContainingDocument containingDocument) {
return getReadonlyAppearance(containingDocument).equals(XFormsProperties.READONLY_APPEARANCE_STATIC_VALUE);
}
public static String getTypeOutputFormat(XFormsContainingDocument containingDocument, String typeName) {
return getStringProperty(containingDocument, TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + typeName);
}
public static String getTypeInputFormat(XFormsContainingDocument containingDocument, String typeName) {
return getStringProperty(containingDocument, TYPE_INPUT_FORMAT_PROPERTY_PREFIX + typeName);
}
public static boolean isSessionHeartbeat(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, SESSION_HEARTBEAT_PROPERTY);
}
public static boolean isEncryptItemValues(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, ENCRYPT_ITEM_VALUES_PROPERTY);
}
public static boolean isOfflineMode(XFormsContainingDocument containingDocument) {
return getBooleanProperty(containingDocument, OFFLINE_SUPPORT_PROPERTY);
}
public static int getOfflineRepeatCount(XFormsContainingDocument containingDocument) {
return getIntegerProperty(containingDocument, OFFLINE_REPEAT_COUNT_PROPERTY);
}
public static String getForwardSubmissionHeaders(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, FORWARD_SUBMISSION_HEADERS);
}
public static String getDatePicker(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, DATEPICKER_PROPERTY);
}
public static String getHTMLEditor(XFormsContainingDocument containingDocument) {
return getStringProperty(containingDocument, XHTML_EDITOR_PROPERTY);
}
public static Object getProperty(XFormsContainingDocument containingDocument, String propertyName) {
return containingDocument.getStaticState().getProperty(propertyName);
}
private static boolean getBooleanProperty(XFormsContainingDocument containingDocument, String propertyName) {
return containingDocument.getStaticState().getBooleanProperty(propertyName);
}
private static String getStringProperty(XFormsContainingDocument containingDocument, String propertyName) {
return containingDocument.getStaticState().getStringProperty(propertyName);
}
private static int getIntegerProperty(XFormsContainingDocument containingDocument, String propertyName) {
return containingDocument.getStaticState().getIntegerProperty(propertyName);
}
} |
package org.quartz.impl.calendar;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.StringTokenizer;
import java.util.TimeZone;
/**
* This implementation of the Calendar excludes (or includes - see below) a
* specified time range each day. For example, you could use this calendar to
* exclude business hours (8AM - 5PM) every day. Each <CODE>DailyCalendar</CODE>
* only allows a single time range to be specified, and that time range may not
* cross daily boundaries (i.e. you cannot specify a time range from 8PM - 5AM).
* If the property <CODE>invertTimeRange</CODE> is <CODE>false</CODE> (default),
* the time range defines a range of times in which triggers are not allowed to
* fire. If <CODE>invertTimeRange</CODE> is <CODE>true</CODE>, the time range
* is inverted – that is, all times <I>outside</I> the defined time range
* are excluded.
* <P>
* Note when using <CODE>DailyCalendar</CODE>, it behaves on the same principals
* as, for example, {@link org.quartz.impl.calendar.WeeklyCalendar
* WeeklyCalendar}. <CODE>WeeklyCalendar</CODE> defines a set of days that are
* excluded <I>every week</I>. Likewise, <CODE>DailyCalendar</CODE> defines a
* set of times that are excluded <I>every day</I>.
*
* @author Mike Funk, Aaron Craven
*/
public class DailyCalendar extends BaseCalendar {
static final long serialVersionUID = -7561220099904944039L;
private static final String invalidHourOfDay = "Invalid hour of day: ";
private static final String invalidMinute = "Invalid minute: ";
private static final String invalidSecond = "Invalid second: ";
private static final String invalidMillis = "Invalid millis: ";
private static final String invalidTimeRange = "Invalid time range: ";
private static final String separator = " - ";
private static final long oneMillis = 1;
private static final String colon = ":";
/** @deprecated The use of <code>name</code> is no longer supported. */
private String name;
private int rangeStartingHourOfDay;
private int rangeStartingMinute;
private int rangeStartingSecond;
private int rangeStartingMillis;
private int rangeEndingHourOfDay;
private int rangeEndingMinute;
private int rangeEndingSecond;
private int rangeEndingMillis;
private boolean invertTimeRange = false;
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified strings and no <CODE>baseCalendar</CODE>.
* <CODE>rangeStartingTime</CODE> and <CODE>rangeEndingTime</CODE>
* must be in the format "HH:MM[:SS[:mmm]]" where:
* <UL><LI>HH is the hour of the specified time. The hour should be
* specified using military (24-hour) time and must be in the range
* 0 to 23.</LI>
* <LI>MM is the minute of the specified time and must be in the range
* 0 to 59.</LI>
* <LI>SS is the second of the specified time and must be in the range
* 0 to 59.</LI>
* <LI>mmm is the millisecond of the specified time and must be in the
* range 0 to 999.</LI>
* <LI>items enclosed in brackets ('[', ']') are optional.</LI>
* <LI>The time range starting time must be before the time range ending
* time. Note this means that a time range may not cross daily
* boundaries (10PM - 2AM)</LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>
* </p>
*
* @param rangeStartingTime a String representing the starting time for the
* time range
* @param rangeEndingTime a String representing the ending time for the
* the time range
*/
public DailyCalendar(String rangeStartingTime,
String rangeEndingTime) {
super();
setTimeRange(rangeStartingTime, rangeEndingTime);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified strings and the specified <CODE>baseCalendar</CODE>.
* <CODE>rangeStartingTime</CODE> and <CODE>rangeEndingTime</CODE>
* must be in the format "HH:MM[:SS[:mmm]]" where:
* <UL><LI>HH is the hour of the specified time. The hour should be
* specified using military (24-hour) time and must be in the range
* 0 to 23.</LI>
* <LI>MM is the minute of the specified time and must be in the range
* 0 to 59.</LI>
* <LI>SS is the second of the specified time and must be in the range
* 0 to 59.</LI>
* <LI>mmm is the millisecond of the specified time and must be in the
* range 0 to 999.</LI>
* <LI>items enclosed in brackets ('[', ']') are optional.</LI>
* <LI>The time range starting time must be before the time range ending
* time. Note this means that a time range may not cross daily
* boundaries (10PM - 2AM)</LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>
* </p>
*
* @param baseCalendar the base calendar for this calendar instance
* – see {@link BaseCalendar} for more
* information on base calendar functionality
* @param rangeStartingTime a String representing the starting time for the
* time range
* @param rangeEndingTime a String representing the ending time for the
* time range
*/
public DailyCalendar(org.quartz.Calendar baseCalendar,
String rangeStartingTime,
String rangeEndingTime) {
super(baseCalendar);
setTimeRange(rangeStartingTime, rangeEndingTime);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified values and no <CODE>baseCalendar</CODE>. Values are subject to
* the following validations:
* <UL><LI>Hours must be in the range 0-23 and are expressed using military
* (24-hour) time.</LI>
* <LI>Minutes must be in the range 0-59</LI>
* <LI>Seconds must be in the range 0-59</LI>
* <LI>Milliseconds must be in the range 0-999</LI>
* <LI>The time range starting time must be before the time range ending
* time. Note this means that a time range may not cross daily
* boundaries (10PM - 2AM)</LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>
* </p>
*
* @param rangeStartingHourOfDay the hour of the start of the time range
* @param rangeStartingMinute the minute of the start of the time range
* @param rangeStartingSecond the second of the start of the time range
* @param rangeStartingMillis the millisecond of the start of the time
* range
* @param rangeEndingHourOfDay the hour of the end of the time range
* @param rangeEndingMinute the minute of the end of the time range
* @param rangeEndingSecond the second of the end of the time range
* @param rangeEndingMillis the millisecond of the start of the time
* range
*/
public DailyCalendar(int rangeStartingHourOfDay,
int rangeStartingMinute,
int rangeStartingSecond,
int rangeStartingMillis,
int rangeEndingHourOfDay,
int rangeEndingMinute,
int rangeEndingSecond,
int rangeEndingMillis) {
super();
setTimeRange(rangeStartingHourOfDay,
rangeStartingMinute,
rangeStartingSecond,
rangeStartingMillis,
rangeEndingHourOfDay,
rangeEndingMinute,
rangeEndingSecond,
rangeEndingMillis);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified values and the specified <CODE>baseCalendar</CODE>. Values are
* subject to the following validations:
* <UL><LI>Hours must be in the range 0-23 and are expressed using military
* (24-hour) time.</LI>
* <LI>Minutes must be in the range 0-59</LI>
* <LI>Seconds must be in the range 0-59</LI>
* <LI>Milliseconds must be in the range 0-999</LI>
* <LI>The time range starting time must be before the time range ending
* time. Note this means that a time range may not cross daily
* boundaries (10PM - 2AM)</LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>
* </p>
*
* @param baseCalendar the base calendar for this calendar
* instance – see
* {@link BaseCalendar} for more
* information on base calendar
* functionality
* @param rangeStartingHourOfDay the hour of the start of the time range
* @param rangeStartingMinute the minute of the start of the time range
* @param rangeStartingSecond the second of the start of the time range
* @param rangeStartingMillis the millisecond of the start of the time
* range
* @param rangeEndingHourOfDay the hour of the end of the time range
* @param rangeEndingMinute the minute of the end of the time range
* @param rangeEndingSecond the second of the end of the time range
* @param rangeEndingMillis the millisecond of the start of the time
* range
*/
public DailyCalendar(org.quartz.Calendar baseCalendar,
int rangeStartingHourOfDay,
int rangeStartingMinute,
int rangeStartingSecond,
int rangeStartingMillis,
int rangeEndingHourOfDay,
int rangeEndingMinute,
int rangeEndingSecond,
int rangeEndingMillis) {
super(baseCalendar);
setTimeRange(rangeStartingHourOfDay,
rangeStartingMinute,
rangeStartingSecond,
rangeStartingMillis,
rangeEndingHourOfDay,
rangeEndingMinute,
rangeEndingSecond,
rangeEndingMillis);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified <CODE>java.util.Calendar</CODE>s and no
* <CODE>baseCalendar</CODE>. The Calendars are subject to the following
* considerations:
* <UL><LI>Only the time-of-day fields of the specified Calendars will be
* used (the date fields will be ignored)</LI>
* <LI>The starting time must be before the ending time of the defined
* time range. Note this means that a time range may not cross
* daily boundaries (10PM - 2AM). <I>(because only time fields are
* are used, it is possible for two Calendars to represent a valid
* time range and
* <CODE>rangeStartingCalendar.after(rangeEndingCalendar) ==
* true</CODE>)</I></LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>
* </p>
*
* @param rangeStartingCalendar a java.util.Calendar representing the
* starting time for the time range
* @param rangeEndingCalendar a java.util.Calendar representing the ending
* time for the time range
*/
public DailyCalendar(
Calendar rangeStartingCalendar,
Calendar rangeEndingCalendar) {
super();
setTimeRange(rangeStartingCalendar, rangeEndingCalendar);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified <CODE>java.util.Calendar</CODE>s and the specified
* <CODE>baseCalendar</CODE>. The Calendars are subject to the following
* considerations:
* <UL><LI>Only the time-of-day fields of the specified Calendars will be
* used (the date fields will be ignored)</LI>
* <LI>The starting time must be before the ending time of the defined
* time range. Note this means that a time range may not cross
* daily boundaries (10PM - 2AM). <I>(because only time fields are
* are used, it is possible for two Calendars to represent a valid
* time range and
* <CODE>rangeStartingCalendar.after(rangeEndingCalendar) ==
* true</CODE>)</I></LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>
* </p>
*
* @param baseCalendar the base calendar for this calendar instance
* – see {@link BaseCalendar} for more
* information on base calendar functionality
* @param rangeStartingCalendar a java.util.Calendar representing the
* starting time for the time range
* @param rangeEndingCalendar a java.util.Calendar representing the ending
* time for the time range
*/
public DailyCalendar(org.quartz.Calendar baseCalendar,
Calendar rangeStartingCalendar,
Calendar rangeEndingCalendar) {
super(baseCalendar);
setTimeRange(rangeStartingCalendar, rangeEndingCalendar);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified values and no <CODE>baseCalendar</CODE>. The values are
* subject to the following considerations:
* <UL><LI>Only the time-of-day portion of the specified values will be
* used</LI>
* <LI>The starting time must be before the ending time of the defined
* time range. Note this means that a time range may not cross
* daily boundaries (10PM - 2AM). <I>(because only time value are
* are used, it is possible for the two values to represent a valid
* time range and <CODE>rangeStartingTime >
* rangeEndingTime</CODE>)</I></LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>.
* You should use <code>{@link #DailyCalendar(String, TimeZone, long, long)}</code>
* if you don't want the given <code>rangeStartingTimeInMillis</code> and
* <code>rangeEndingTimeInMillis</code> to be evaluated in the default
* time zone.
* </p>
*
* @param rangeStartingTimeInMillis a long representing the starting time
* for the time range
* @param rangeEndingTimeInMillis a long representing the ending time for
* the time range
*/
public DailyCalendar(long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
super();
setTimeRange(rangeStartingTimeInMillis,
rangeEndingTimeInMillis);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified values and the specified <CODE>baseCalendar</CODE>. The values
* are subject to the following considerations:
* <UL><LI>Only the time-of-day portion of the specified values will be
* used</LI>
* <LI>The starting time must be before the ending time of the defined
* time range. Note this means that a time range may not cross
* daily boundaries (10PM - 2AM). <I>(because only time value are
* are used, it is possible for the two values to represent a valid
* time range and <CODE>rangeStartingTime >
* rangeEndingTime</CODE>)</I></LI>
* </UL>
*
* <p>
* <b>Note:</b> This <CODE>DailyCalendar</CODE> will use the
* <code>{@link TimeZone#getDefault()}</code> time zone unless an explicit
* time zone is set via <code>{@link BaseCalendar#setTimeZone(TimeZone)}</code>.
* You should use <code>{@link #DailyCalendar(String, Calendar, TimeZone, long, long)}</code>
* if you don't want the given <code>rangeStartingTimeInMillis</code> and
* <code>rangeEndingTimeInMillis</code> to be evaluated in the default
* time zone.
* </p>
*
* @param baseCalendar the base calendar for this calendar
* instance – see {@link
* BaseCalendar} for more information on
* base calendar functionality
* @param rangeStartingTimeInMillis a long representing the starting time
* for the time range
* @param rangeEndingTimeInMillis a long representing the ending time for
* the time range
*/
public DailyCalendar(org.quartz.Calendar baseCalendar,
long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
super(baseCalendar);
setTimeRange(rangeStartingTimeInMillis,
rangeEndingTimeInMillis);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified values and no <CODE>baseCalendar</CODE>. The values are
* subject to the following considerations:
* <UL><LI>Only the time-of-day portion of the specified values will be
* used</LI>
* <LI>The starting time must be before the ending time of the defined
* time range. Note this means that a time range may not cross
* daily boundaries (10PM - 2AM). <I>(because only time value are
* are used, it is possible for the two values to represent a valid
* time range and <CODE>rangeStartingTime >
* rangeEndingTime</CODE>)</I></LI>
* </UL>
*
* @param timeZone the time zone for of the
* <code>DailyCalendar</code> which will
* also be used to resolve the given
* start/end times.
* @param rangeStartingTimeInMillis a long representing the starting time
* for the time range
* @param rangeEndingTimeInMillis a long representing the ending time for
* the time range
*/
public DailyCalendar(TimeZone timeZone,
long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
super(timeZone);
setTimeRange(rangeStartingTimeInMillis,
rangeEndingTimeInMillis);
}
/**
* Create a <CODE>DailyCalendar</CODE> with a time range defined by the
* specified values and the specified <CODE>baseCalendar</CODE>. The values
* are subject to the following considerations:
* <UL><LI>Only the time-of-day portion of the specified values will be
* used</LI>
* <LI>The starting time must be before the ending time of the defined
* time range. Note this means that a time range may not cross
* daily boundaries (10PM - 2AM). <I>(because only time value are
* are used, it is possible for the two values to represent a valid
* time range and <CODE>rangeStartingTime >
* rangeEndingTime</CODE>)</I></LI>
* </UL>
*
* @param baseCalendar the base calendar for this calendar
* instance – see {@link
* BaseCalendar} for more information on
* base calendar functionality
* @param timeZone the time zone for of the
* <code>DailyCalendar</code> which will
* also be used to resolve the given
* start/end times.
* @param rangeStartingTimeInMillis a long representing the starting time
* for the time range
* @param rangeEndingTimeInMillis a long representing the ending time for
* the time range
*/
public DailyCalendar(org.quartz.Calendar baseCalendar,
TimeZone timeZone,
long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
super(baseCalendar, timeZone);
setTimeRange(rangeStartingTimeInMillis,
rangeEndingTimeInMillis);
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(String, String)
*/
public DailyCalendar(String name,
String rangeStartingTime,
String rangeEndingTime) {
this(rangeStartingTime, rangeEndingTime);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(org.quartz.Calendar, String, String)
*/
public DailyCalendar(String name,
org.quartz.Calendar baseCalendar,
String rangeStartingTime,
String rangeEndingTime) {
this(baseCalendar, rangeStartingTime, rangeEndingTime);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(int, int, int, int, int, int, int, int)
*/
public DailyCalendar(String name,
int rangeStartingHourOfDay,
int rangeStartingMinute,
int rangeStartingSecond,
int rangeStartingMillis,
int rangeEndingHourOfDay,
int rangeEndingMinute,
int rangeEndingSecond,
int rangeEndingMillis) {
this(rangeStartingHourOfDay,
rangeStartingMinute,
rangeStartingSecond,
rangeStartingMillis,
rangeEndingHourOfDay,
rangeEndingMinute,
rangeEndingSecond,
rangeEndingMillis);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(org.quartz.Calendar, int, int, int, int, int, int, int, int)
*/
public DailyCalendar(String name,
org.quartz.Calendar baseCalendar,
int rangeStartingHourOfDay,
int rangeStartingMinute,
int rangeStartingSecond,
int rangeStartingMillis,
int rangeEndingHourOfDay,
int rangeEndingMinute,
int rangeEndingSecond,
int rangeEndingMillis) {
this(baseCalendar,
rangeStartingHourOfDay,
rangeStartingMinute,
rangeStartingSecond,
rangeStartingMillis,
rangeEndingHourOfDay,
rangeEndingMinute,
rangeEndingSecond,
rangeEndingMillis);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(Calendar, Calendar)
*/
public DailyCalendar(String name,
Calendar rangeStartingCalendar,
Calendar rangeEndingCalendar) {
this(rangeStartingCalendar, rangeEndingCalendar);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(org.quartz.Calendar, Calendar, Calendar)
*/
public DailyCalendar(String name,
org.quartz.Calendar baseCalendar,
Calendar rangeStartingCalendar,
Calendar rangeEndingCalendar) {
this(baseCalendar, rangeStartingCalendar, rangeEndingCalendar);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(long, long)
*/
public DailyCalendar(String name,
long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
this(rangeStartingTimeInMillis, rangeEndingTimeInMillis);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(org.quartz.Calendar, long, long)
*/
public DailyCalendar(String name,
org.quartz.Calendar baseCalendar,
long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
this(baseCalendar, rangeStartingTimeInMillis, rangeEndingTimeInMillis);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(TimeZone, long, long)
*/
public DailyCalendar(String name,
TimeZone timeZone,
long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
this(timeZone,
rangeStartingTimeInMillis,
rangeEndingTimeInMillis);
this.name = name;
}
/**
* @deprecated The use of <code>name</code> is no longer supported.
*
* @see DailyCalendar#DailyCalendar(org.quartz.Calendar, TimeZone, long, long)
*/
public DailyCalendar(String name,
org.quartz.Calendar baseCalendar,
TimeZone timeZone,
long rangeStartingTimeInMillis,
long rangeEndingTimeInMillis) {
this(baseCalendar,
timeZone,
rangeStartingTimeInMillis,
rangeEndingTimeInMillis);
this.name = name;
}
/**
* Returns the name of the <CODE>DailyCalendar</CODE>
*
* @return the name of the <CODE>DailyCalendar</CODE>
*
* @deprecated The use of <code>name</code> is no longer supported.
*/
public String getName() {
return name;
}
/**
* Determines whether the given time (in milliseconds) is 'included' by the
* <CODE>BaseCalendar</CODE>
*
* @param timeInMillis the date/time to test
* @return a boolean indicating whether the specified time is 'included' by
* the <CODE>BaseCalendar</CODE>
*/
public boolean isTimeIncluded(long timeInMillis) {
if ((getBaseCalendar() != null) &&
(getBaseCalendar().isTimeIncluded(timeInMillis) == false)) {
return false;
}
long startOfDayInMillis = getStartOfDayJavaCalendar(timeInMillis).getTime().getTime();
long endOfDayInMillis = getEndOfDayJavaCalendar(timeInMillis).getTime().getTime();
long timeRangeStartingTimeInMillis =
getTimeRangeStartingTimeInMillis(timeInMillis);
long timeRangeEndingTimeInMillis =
getTimeRangeEndingTimeInMillis(timeInMillis);
if (!invertTimeRange) {
return
((timeInMillis > startOfDayInMillis &&
timeInMillis < timeRangeStartingTimeInMillis) ||
(timeInMillis > timeRangeEndingTimeInMillis &&
timeInMillis < endOfDayInMillis));
} else {
return ((timeInMillis >= timeRangeStartingTimeInMillis) &&
(timeInMillis <= timeRangeEndingTimeInMillis));
}
}
/**
* Determines the next time included by the <CODE>DailyCalendar</CODE>
* after the specified time.
*
* @param timeInMillis the initial date/time after which to find an
* included time
* @return the time in milliseconds representing the next time included
* after the specified time.
*/
public long getNextIncludedTime(long timeInMillis) {
long nextIncludedTime = timeInMillis + oneMillis;
while (!isTimeIncluded(nextIncludedTime)) {
if (!invertTimeRange) {
//If the time is in a range excluded by this calendar, we can
// move to the end of the excluded time range and continue
// testing from there. Otherwise, if nextIncludedTime is
// excluded by the baseCalendar, ask it the next time it
// includes and begin testing from there. Failing this, add one
// millisecond and continue testing.
if ((nextIncludedTime >=
getTimeRangeStartingTimeInMillis(nextIncludedTime)) &&
(nextIncludedTime <=
getTimeRangeEndingTimeInMillis(nextIncludedTime))) {
nextIncludedTime =
getTimeRangeEndingTimeInMillis(nextIncludedTime) +
oneMillis;
} else if ((getBaseCalendar() != null) &&
(!getBaseCalendar().isTimeIncluded(nextIncludedTime))){
nextIncludedTime =
getBaseCalendar().getNextIncludedTime(nextIncludedTime);
} else {
nextIncludedTime++;
}
} else {
//If the time is in a range excluded by this calendar, we can
// move to the end of the excluded time range and continue
// testing from there. Otherwise, if nextIncludedTime is
// excluded by the baseCalendar, ask it the next time it
// includes and begin testing from there. Failing this, add one
// millisecond and continue testing.
if (nextIncludedTime <
getTimeRangeStartingTimeInMillis(nextIncludedTime)) {
nextIncludedTime =
getTimeRangeStartingTimeInMillis(nextIncludedTime);
} else if (nextIncludedTime >
getTimeRangeEndingTimeInMillis(nextIncludedTime)) {
//(move to start of next day)
nextIncludedTime = getEndOfDayJavaCalendar(nextIncludedTime).getTime().getTime();
nextIncludedTime += 1l;
} else if ((getBaseCalendar() != null) &&
(!getBaseCalendar().isTimeIncluded(nextIncludedTime))){
nextIncludedTime =
getBaseCalendar().getNextIncludedTime(nextIncludedTime);
} else {
nextIncludedTime++;
}
}
}
return nextIncludedTime;
}
/**
* Returns the start time of the time range (in milliseconds) of the day
* specified in <CODE>timeInMillis</CODE>
*
* @param timeInMillis a time containing the desired date for the starting
* time of the time range.
* @return a date/time (in milliseconds) representing the start time of the
* time range for the specified date.
*/
public long getTimeRangeStartingTimeInMillis(long timeInMillis) {
Calendar rangeStartingTime = createJavaCalendar(timeInMillis);
rangeStartingTime.set(Calendar.HOUR_OF_DAY, rangeStartingHourOfDay);
rangeStartingTime.set(Calendar.MINUTE, rangeStartingMinute);
rangeStartingTime.set(Calendar.SECOND, rangeStartingSecond);
rangeStartingTime.set(Calendar.MILLISECOND, rangeStartingMillis);
return rangeStartingTime.getTime().getTime();
}
/**
* Returns the end time of the time range (in milliseconds) of the day
* specified in <CODE>timeInMillis</CODE>
*
* @param timeInMillis a time containing the desired date for the ending
* time of the time range.
* @return a date/time (in milliseconds) representing the end time of the
* time range for the specified date.
*/
public long getTimeRangeEndingTimeInMillis(long timeInMillis) {
Calendar rangeEndingTime = createJavaCalendar(timeInMillis);
rangeEndingTime.set(Calendar.HOUR_OF_DAY, rangeEndingHourOfDay);
rangeEndingTime.set(Calendar.MINUTE, rangeEndingMinute);
rangeEndingTime.set(Calendar.SECOND, rangeEndingSecond);
rangeEndingTime.set(Calendar.MILLISECOND, rangeEndingMillis);
return rangeEndingTime.getTime().getTime();
}
/**
* Indicates whether the time range represents an inverted time range (see
* class description).
*
* @return a boolean indicating whether the time range is inverted
*/
public boolean getInvertTimeRange() {
return invertTimeRange;
}
/**
* Indicates whether the time range represents an inverted time range (see
* class description).
*
* @param flag the new value for the <CODE>invertTimeRange</CODE> flag.
*/
public void setInvertTimeRange(boolean flag) {
this.invertTimeRange = flag;
}
/**
* Returns a string representing the properties of the
* <CODE>DailyCalendar</CODE>
*
* @return the properteis of the DailyCalendar in a String format
*/
public String toString() {
NumberFormat numberFormatter = NumberFormat.getNumberInstance();
numberFormatter.setMaximumFractionDigits(0);
numberFormatter.setMinimumIntegerDigits(2);
StringBuffer buffer = new StringBuffer();
if (name != null) {
buffer.append(name).append(": ");
}
buffer.append("base calendar: [");
if (getBaseCalendar() != null) {
buffer.append(getBaseCalendar().toString());
} else {
buffer.append("null");
}
buffer.append("], time range: '");
buffer.append(numberFormatter.format(rangeStartingHourOfDay));
buffer.append(":");
buffer.append(numberFormatter.format(rangeStartingMinute));
buffer.append(":");
buffer.append(numberFormatter.format(rangeStartingSecond));
buffer.append(":");
numberFormatter.setMinimumIntegerDigits(3);
buffer.append(numberFormatter.format(rangeStartingMillis));
numberFormatter.setMinimumIntegerDigits(2);
buffer.append(" - ");
buffer.append(numberFormatter.format(rangeEndingHourOfDay));
buffer.append(":");
buffer.append(numberFormatter.format(rangeEndingMinute));
buffer.append(":");
buffer.append(numberFormatter.format(rangeEndingSecond));
buffer.append(":");
numberFormatter.setMinimumIntegerDigits(3);
buffer.append(numberFormatter.format(rangeEndingMillis));
buffer.append("', inverted: " + invertTimeRange + "]");
return buffer.toString();
}
/**
* Helper method to split the given string by the given delimiter.
*/
private String[] split(String string, String delim) {
ArrayList result = new ArrayList();
StringTokenizer stringTokenizer = new StringTokenizer(string, delim);
while (stringTokenizer.hasMoreTokens()) {
result.add(stringTokenizer.nextToken());
}
return (String[])result.toArray(new String[result.size()]);
}
/**
* Sets the time range for the <CODE>DailyCalendar</CODE> to the times
* represented in the specified Strings.
*
* @param rangeStartingTimeString a String representing the start time of
* the time range
* @param rangeEndingTimeString a String representing the end time of the
* excluded time range
*/
public void setTimeRange(String rangeStartingTimeString,
String rangeEndingTimeString) {
String[] rangeStartingTime;
int rangeStartingHourOfDay;
int rangeStartingMinute;
int rangeStartingSecond;
int rangeStartingMillis;
String[] rangeEndingTime;
int rangeEndingHourOfDay;
int rangeEndingMinute;
int rangeEndingSecond;
int rangeEndingMillis;
rangeStartingTime = split(rangeStartingTimeString, colon);
if ((rangeStartingTime.length < 2) || (rangeStartingTime.length > 4)) {
throw new IllegalArgumentException("Invalid time string '" +
rangeStartingTimeString + "'");
}
rangeStartingHourOfDay = Integer.parseInt(rangeStartingTime[0]);
rangeStartingMinute = Integer.parseInt(rangeStartingTime[1]);
if (rangeStartingTime.length > 2) {
rangeStartingSecond = Integer.parseInt(rangeStartingTime[2]);
} else {
rangeStartingSecond = 0;
}
if (rangeStartingTime.length == 4) {
rangeStartingMillis = Integer.parseInt(rangeStartingTime[3]);
} else {
rangeStartingMillis = 0;
}
rangeEndingTime = split(rangeEndingTimeString, colon);
if ((rangeEndingTime.length < 2) || (rangeEndingTime.length > 4)) {
throw new IllegalArgumentException("Invalid time string '" +
rangeEndingTimeString + "'");
}
rangeEndingHourOfDay = Integer.parseInt(rangeEndingTime[0]);
rangeEndingMinute = Integer.parseInt(rangeEndingTime[1]);
if (rangeEndingTime.length > 2) {
rangeEndingSecond = Integer.parseInt(rangeEndingTime[2]);
} else {
rangeEndingSecond = 0;
}
if (rangeEndingTime.length == 4) {
rangeEndingMillis = Integer.parseInt(rangeEndingTime[3]);
} else {
rangeEndingMillis = 0;
}
setTimeRange(rangeStartingHourOfDay,
rangeStartingMinute,
rangeStartingSecond,
rangeStartingMillis,
rangeEndingHourOfDay,
rangeEndingMinute,
rangeEndingSecond,
rangeEndingMillis);
}
/**
* Sets the time range for the <CODE>DailyCalendar</CODE> to the times
* represented in the specified values.
*
* @param rangeStartingHourOfDay the hour of the start of the time range
* @param rangeStartingMinute the minute of the start of the time range
* @param rangeStartingSecond the second of the start of the time range
* @param rangeStartingMillis the millisecond of the start of the time
* range
* @param rangeEndingHourOfDay the hour of the end of the time range
* @param rangeEndingMinute the minute of the end of the time range
* @param rangeEndingSecond the second of the end of the time range
* @param rangeEndingMillis the millisecond of the start of the time
* range
*/
public void setTimeRange(int rangeStartingHourOfDay,
int rangeStartingMinute,
int rangeStartingSecond,
int rangeStartingMillis,
int rangeEndingHourOfDay,
int rangeEndingMinute,
int rangeEndingSecond,
int rangeEndingMillis) {
validate(rangeStartingHourOfDay,
rangeStartingMinute,
rangeStartingSecond,
rangeStartingMillis);
validate(rangeEndingHourOfDay,
rangeEndingMinute,
rangeEndingSecond,
rangeEndingMillis);
Calendar startCal = createJavaCalendar();
startCal.set(Calendar.HOUR_OF_DAY, rangeStartingHourOfDay);
startCal.set(Calendar.MINUTE, rangeStartingMinute);
startCal.set(Calendar.SECOND, rangeStartingSecond);
startCal.set(Calendar.MILLISECOND, rangeStartingMillis);
Calendar endCal = createJavaCalendar();
endCal.set(Calendar.HOUR_OF_DAY, rangeEndingHourOfDay);
endCal.set(Calendar.MINUTE, rangeEndingMinute);
endCal.set(Calendar.SECOND, rangeEndingSecond);
endCal.set(Calendar.MILLISECOND, rangeEndingMillis);
if (!startCal.before(endCal)) {
throw new IllegalArgumentException(invalidTimeRange +
rangeStartingHourOfDay + ":" +
rangeStartingMinute + ":" +
rangeStartingSecond + ":" +
rangeStartingMillis + separator +
rangeEndingHourOfDay + ":" +
rangeEndingMinute + ":" +
rangeEndingSecond + ":" +
rangeEndingMillis);
}
this.rangeStartingHourOfDay = rangeStartingHourOfDay;
this.rangeStartingMinute = rangeStartingMinute;
this.rangeStartingSecond = rangeStartingSecond;
this.rangeStartingMillis = rangeStartingMillis;
this.rangeEndingHourOfDay = rangeEndingHourOfDay;
this.rangeEndingMinute = rangeEndingMinute;
this.rangeEndingSecond = rangeEndingSecond;
this.rangeEndingMillis = rangeEndingMillis;
}
/**
* Sets the time range for the <CODE>DailyCalendar</CODE> to the times
* represented in the specified <CODE>java.util.Calendar</CODE>s.
*
* @param rangeStartingCalendar a Calendar containing the start time for
* the <CODE>DailyCalendar</CODE>
* @param rangeEndingCalendar a Calendar containing the end time for
* the <CODE>DailyCalendar</CODE>
*/
public void setTimeRange(Calendar rangeStartingCalendar,
Calendar rangeEndingCalendar) {
setTimeRange(
rangeStartingCalendar.get(Calendar.HOUR_OF_DAY),
rangeStartingCalendar.get(Calendar.MINUTE),
rangeStartingCalendar.get(Calendar.SECOND),
rangeStartingCalendar.get(Calendar.MILLISECOND),
rangeEndingCalendar.get(Calendar.HOUR_OF_DAY),
rangeEndingCalendar.get(Calendar.MINUTE),
rangeEndingCalendar.get(Calendar.SECOND),
rangeEndingCalendar.get(Calendar.MILLISECOND));
}
/**
* Sets the time range for the <CODE>DailyCalendar</CODE> to the times
* represented in the specified values.
*
* @param rangeStartingTime the starting time (in milliseconds) for the
* time range
* @param rangeEndingTime the ending time (in milliseconds) for the time
* range
*/
public void setTimeRange(long rangeStartingTime,
long rangeEndingTime) {
setTimeRange(
createJavaCalendar(rangeStartingTime),
createJavaCalendar(rangeEndingTime));
}
/**
* Checks the specified values for validity as a set of time values.
*
* @param hourOfDay the hour of the time to check (in military (24-hour)
* time)
* @param minute the minute of the time to check
* @param second the second of the time to check
* @param millis the millisecond of the time to check
*/
private void validate(int hourOfDay, int minute, int second, int millis) {
if (hourOfDay < 0 || hourOfDay > 23) {
throw new IllegalArgumentException(invalidHourOfDay + hourOfDay);
}
if (minute < 0 || minute > 59) {
throw new IllegalArgumentException(invalidMinute + minute);
}
if (second < 0 || second > 59) {
throw new IllegalArgumentException(invalidSecond + second);
}
if (millis < 0 || millis > 999) {
throw new IllegalArgumentException(invalidMillis + millis);
}
}
} |
package jnome.core.expression;
import java.util.ArrayList;
import java.util.List;
import jnome.core.type.JavaTypeReference;
import org.rejuse.association.SingleAssociation;
import org.rejuse.logic.ternary.Ternary;
import org.rejuse.predicate.SafePredicate;
import chameleon.core.MetamodelException;
import chameleon.core.declaration.Declaration;
import chameleon.core.declaration.DeclarationContainer;
import chameleon.core.declaration.SimpleNameSignature;
import chameleon.core.element.Element;
import chameleon.core.expression.Expression;
import chameleon.core.expression.Invocation;
import chameleon.core.expression.InvocationTarget;
import chameleon.core.lookup.DeclarationSelector;
import chameleon.core.lookup.LookupException;
import chameleon.core.lookup.LookupStrategy;
import chameleon.core.relation.WeakPartialOrder;
import chameleon.core.type.ClassBody;
import chameleon.core.type.RegularType;
import chameleon.core.type.Type;
import chameleon.core.type.TypeElement;
import chameleon.core.type.TypeReference;
import chameleon.core.type.inheritance.SubtypeRelation;
import chameleon.oo.language.ObjectOrientedLanguage;
import chameleon.support.member.MoreSpecificTypesOrder;
import chameleon.support.member.simplename.method.NormalMethod;
import chameleon.util.Util;
/**
* @author Marko van Dooren
*
*/
public class ConstructorInvocation extends Invocation<ConstructorInvocation, NormalMethod> implements DeclarationContainer<ConstructorInvocation, Element> {
/**
* @param target
*/
public ConstructorInvocation(JavaTypeReference type, InvocationTarget target) {
super(target);
setTypeReference(type);
}
public Expression getTargetExpression() {
return (Expression)getTarget();
}
/**
* TYPE REFERENCE
*/
private SingleAssociation<ConstructorInvocation,JavaTypeReference> _typeReference = new SingleAssociation<ConstructorInvocation,JavaTypeReference>(this);
public JavaTypeReference getTypeReference() {
return (JavaTypeReference)_typeReference.getOtherEnd();
}
public void setTypeReference(JavaTypeReference type) {
SingleAssociation<? extends TypeReference, ? super ConstructorInvocation> tref = type.parentLink();
SingleAssociation<? extends JavaTypeReference, ? super ConstructorInvocation> ref = (SingleAssociation<? extends JavaTypeReference, ? super ConstructorInvocation>)tref;
_typeReference.connectTo(ref);
}
// public void setAnonymousType(Type type) {
// if(type != null) {
// _anon.connectTo(type.parentLink());
// } else {
// _anon.connectTo(null);
// public Type getAnonymousInnerType() {
// return _anon.getOtherEnd();
private SingleAssociation<ConstructorInvocation,ClassBody> _body = new SingleAssociation<ConstructorInvocation,ClassBody>(this);
public ClassBody body() {
return _body.getOtherEnd();
}
public void setBody(ClassBody body) {
if(body == null) {
_body.connectTo(null);
} else {
_body.connectTo(body.parentLink());
}
}
private Type createAnonymousType() throws LookupException {
final Type anon = new RegularType(new SimpleNameSignature("TODO"));
TypeReference tref = getTypeReference();
Type writtenType = tref.getType();
List<NormalMethod> superMembers = writtenType.directlyDeclaredMembers(NormalMethod.class);
new SafePredicate<NormalMethod>() {
@Override
public boolean eval(NormalMethod object) {
return object.is(language(ObjectOrientedLanguage.class).CONSTRUCTOR) == Ternary.TRUE;
}
}.filter(superMembers);
for(NormalMethod method: superMembers) {
anon.add(method.clone());
}
for(TypeElement element : body().elements()) {
anon.add(element.clone());
}
anon.addInheritanceRelation(new SubtypeRelation(tref.clone()));
// Attach the created type to this element.
anon.setUniParent(this);
return anon;
}
protected Type actualType() throws LookupException {
if (body() == null) {
// Switching to target or not happens in getContext(Element) invoked by the type reference.
return getTypeReference().getType();
}
else {
return getAnonymousInnerType();
}
}
public <X extends Declaration> X getElement(DeclarationSelector<X> selector) throws LookupException {
return actualType().targetContext().lookUp(selector);
// InvocationTarget target = getTarget();
// X result;
// if(target == null) {
// result = lexicalLookupStrategy().lookUp(selector);
// } else {
// result = getTarget().targetContext().lookUp(selector);
// if (result == null) {
// //repeat lookup for debugging purposes.
// if(target == null) {
// result = lexicalLookupStrategy().lookUp(selector);
// } else {
// result = getTarget().targetContext().lookUp(selector);
// throw new LookupException("Method returned by invocation is null", this);
// return result;
}
// private Reference<ConstructorInvocation,Type> _anonymousType= new Reference<ConstructorInvocation,Type>(this);
public Type getAnonymousInnerType() throws LookupException {
if(body() == null) {
return null;
} else {
return createAnonymousType();
}
}
protected ConstructorInvocation cloneInvocation(InvocationTarget target) {
ConstructorInvocation result = new ConstructorInvocation((JavaTypeReference)getTypeReference().clone(), (Expression)target);
if(body() != null) {
result.setBody(body().clone());
}
return result;
}
public void prefix(InvocationTarget target) throws LookupException {
if(getTarget() != null) {
getTarget().prefixRecursive(target);
}
}
/*@
@ also public behavior
@
@ post getAnonymousInnerType() != null ==> \result.contains(getAnonymousInnerType());
@*/
public List<Element> children() {
List<Element> result = super.children();
Util.addNonNull(body(), result);
Util.addNonNull(getTypeReference(), result);
return result;
}
@Override
public LookupStrategy lexicalLookupStrategy(Element element) throws LookupException {
if ((element == getTypeReference()) && (getTargetExpression() != null)) {
return getTargetExpression().targetContext();
} else {
return super.lexicalLookupStrategy(element);
}
}
// public NormalMethod getMethod() throws LookupException {
// InvocationTarget target = getTarget();
// NormalMethod result;
// if(getAnonymousInnerType() != null) {
// LookupStrategy tctx = getAnonymousInnerType().targetContext();
// result = tctx.lookUp(selector());
// } else if(target == null) {
// result = lexicalLookupStrategy().lookUp(selector());
// } else {
// result = getTarget().targetContext().lookUp(selector());
// if (result == null) {
// throw new LookupException("Lookup in constructor invocation returned null",this);
// return result;
public class ConstructorSelector extends DeclarationSelector<NormalMethod> {
public NormalMethod filter(NormalMethod declaration) throws LookupException {
NormalMethod result = null;
NormalMethod<?,?,?> decl = (NormalMethod) declaration;
if(decl.nearestAncestor(Type.class).signature().sameAs(getTypeReference().signature())) {
if(decl.is(language(ObjectOrientedLanguage.class).CONSTRUCTOR)==Ternary.TRUE) {
List<Type> actuals = getActualParameterTypes();
List<Type> formals = decl.header().getParameterTypes();
if (new MoreSpecificTypesOrder().contains(actuals, formals)) {
result = decl;
}
}
}
return result;
}
@Override
public WeakPartialOrder<NormalMethod> order() {
return new WeakPartialOrder<NormalMethod>() {
@Override
public boolean contains(NormalMethod first, NormalMethod second)
throws LookupException {
return new MoreSpecificTypesOrder().contains(first.header().getParameterTypes(), second.header().getParameterTypes());
}
};
}
@Override
public Class<NormalMethod> selectedClass() {
return NormalMethod.class;
}
}
@Override
public DeclarationSelector<NormalMethod> selector() {
return new ConstructorSelector();
}
public List<? extends Type> declarations() throws LookupException {
List<Type> result = new ArrayList<Type>();
if(getAnonymousInnerType() != null) {
result.add(getAnonymousInnerType());
}
return result;
}
public <D extends Declaration> List<D> declarations(DeclarationSelector<D> selector) throws LookupException {
return selector.selection(declarations());
}
} |
package com.redhat.ceylon.compiler.java;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import ceylon.language.ArraySequence;
import ceylon.language.AssertionException;
import ceylon.language.Callable;
import ceylon.language.Integer;
import ceylon.language.Iterable;
import ceylon.language.Iterator;
import ceylon.language.Ranged;
import ceylon.language.Sequential;
import ceylon.language.empty_;
import ceylon.language.finished_;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Class;
import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes;
import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
public class Util {
static {
// Make sure the rethrow class is loaded if ever we need to rethrow
// errors such as StackOverflowError, otherwise if we have to rethrow it
// we will not be able to load that class since we've ran out of stack
ceylon.language.impl.rethrow_.class.toString();
}
public static String declClassName(String name) {
return name.replace("::", ".");
}
public static void loadModule(String name, String version,
ArtifactResult result, ClassLoader classLoader){
Metamodel.loadModule(name, version, result, classLoader);
}
public static boolean isReified(java.lang.Object o, TypeDescriptor type){
return Metamodel.isReified(o, type);
}
/**
* Returns true if the given object satisfies ceylon.language.Identifiable
*/
public static boolean isIdentifiable(java.lang.Object o){
return satisfiesInterface(o, "ceylon.language.Identifiable");
}
/**
* Returns true if the given object extends ceylon.language.Basic
*/
public static boolean isBasic(java.lang.Object o){
return extendsClass(o, "ceylon.language.Basic");
}
/**
* Returns true if the given object extends the given class
*/
public static boolean extendsClass(java.lang.Object o, String className) {
if(o == null)
return false;
if(className == null)
throw new AssertionException("Type name cannot be null");
return classExtendsClass(o.getClass(), className);
}
private static boolean classExtendsClass(java.lang.Class<?> klass, String className) {
if(klass == null)
return false;
if (klass.getName().equals(className))
return true;
if ((className.equals("ceylon.language.Basic"))
&& klass!=java.lang.Object.class
//&& klass!=java.lang.String.class
&& !klass.isAnnotationPresent(Class.class)
&& (!klass.isInterface() || !klass.isAnnotationPresent(Ceylon.class))) {
//TODO: this is broken for a Java class that
// extends a Ceylon class
return true;
}
return classExtendsClass(getCeylonSuperClass(klass), className);
}
private static java.lang.Class<?> getCeylonSuperClass(java.lang.Class<?> klass) {
Class classAnnotation = klass.getAnnotation(Class.class);
// only consider Class.extendsType() if non-empty
if (classAnnotation != null && !classAnnotation.extendsType().isEmpty()) {
String superclassName = declClassName(classAnnotation.extendsType());
int i = superclassName.indexOf('<');
if (i>0) {
superclassName = superclassName.substring(0, i);
}
if (superclassName.isEmpty()) {
throw new RuntimeException("Malformed @Class.extendsType() annotation value: "+classAnnotation.extendsType());
}
try {
return java.lang.Class.forName(superclassName, true, klass.getClassLoader());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
// we consider that subclasses of Object that do not have any @Ceylon.extendsType() are in fact subclasses of Basic
if(klass.getSuperclass() != java.lang.Object.class)
return klass.getSuperclass();
// Anything has no super class
if(klass == ceylon.language.Anything.class)
return null;
// The default super class is Basic
return ceylon.language.Basic.class;
}
/**
* Returns true if the given object satisfies the given interface
*/
public static boolean satisfiesInterface(java.lang.Object o, String className){
if(o == null)
return false;
if(className == null)
throw new AssertionException("Type name cannot be null");
// we use a hash set to speed things up for interfaces, to avoid looking at them twice
Set<java.lang.Class<?>> alreadyVisited = new HashSet<java.lang.Class<?>>();
return classSatisfiesInterface(o.getClass(), className, alreadyVisited);
}
private static boolean classSatisfiesInterface(java.lang.Class<?> klass, String className,
Set<java.lang.Class<?>> alreadyVisited) {
if(klass == null
|| klass == ceylon.language.Anything.class)
return false;
if ((className.equals("ceylon.language.Identifiable"))
&& klass!=java.lang.Object.class
//&& klass!=java.lang.String.class
&& !klass.isAnnotationPresent(Ceylon.class)) {
//TODO: this is broken for a Java class that
// extends a Ceylon class
return true;
}
// try the interfaces
if(lookForInterface(klass, className, alreadyVisited))
return true;
// try its superclass
return classSatisfiesInterface(getCeylonSuperClass(klass), className, alreadyVisited);
}
private static boolean lookForInterface(java.lang.Class<?> klass, String className,
Set<java.lang.Class<?>> alreadyVisited){
if (klass.getName().equals(className))
return true;
// did we already visit this type?
if(!alreadyVisited.add(klass))
return false;
// first see if it satisfies it directly
SatisfiedTypes satisfiesAnnotation = klass.getAnnotation(SatisfiedTypes.class);
if (satisfiesAnnotation!=null){
for (String satisfiedType : satisfiesAnnotation.value()){
satisfiedType = declClassName(satisfiedType);
int i = satisfiedType.indexOf('<');
if (i>0) {
satisfiedType = satisfiedType.substring(0, i);
}
try {
if (lookForInterface(
java.lang.Class.forName(satisfiedType, true, klass.getClassLoader()),
className, alreadyVisited)) {
return true;
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}else{
// otherwise look at this class's interfaces
for (java.lang.Class<?> intrface : klass.getInterfaces()){
if (lookForInterface(intrface, className, alreadyVisited))
return true;
}
}
// no luck
return false;
}
// Java variadic conversions
@SuppressWarnings("unchecked")
public static <T> List<T> collectIterable(Iterable<? extends T, ?> sequence) {
List<T> list = new LinkedList<T>();
if (sequence != null) {
Iterator<? extends T> iterator = sequence.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
list.add((T)o);
}
}
return list;
}
@SuppressWarnings("unchecked")
public static boolean[]
toBooleanArray(ceylon.language.Iterable<? extends ceylon.language.Boolean, ?> sequence,
boolean... initialElements){
if(sequence instanceof ceylon.language.List)
return toBooleanArray((ceylon.language.List<? extends ceylon.language.Boolean>)sequence,
initialElements);
List<ceylon.language.Boolean> list = collectIterable(sequence);
boolean[] ret = new boolean[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Boolean e : list){
ret[i++] = e.booleanValue();
}
return ret;
}
public static boolean[]
toBooleanArray(ceylon.language.List<? extends ceylon.language.Boolean> sequence,
boolean... initialElements){
boolean[] ret = new boolean[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().booleanValue();
sequence = (ceylon.language.List<? extends ceylon.language.Boolean>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static byte[]
toByteArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toByteArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
byte[] ret = new byte[initialElements.length + list.size()];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (byte) initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = (byte)e.longValue();
}
return ret;
}
public static byte[]
toByteArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
byte[] ret = new byte[initialElements.length + (int) sequence.getSize()];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (byte) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (byte) sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static short[]
toShortArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toShortArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
short[] ret = new short[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (short) initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = (short)e.longValue();
}
return ret;
}
public static short[]
toShortArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
short[] ret = new short[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (short) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (short) sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static int[]
toIntArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toIntArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
int[] ret = new int[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (int) initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = (int)e.longValue();
}
return ret;
}
public static int[]
toIntArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
int[] ret = new int[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (int) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (int) sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static long[]
toLongArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toLongArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
long[] ret = new long[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = e.longValue();
}
return ret;
}
public static long[]
toLongArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
long[] ret = new long[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static float[]
toFloatArray(ceylon.language.Iterable<? extends ceylon.language.Float, ?> sequence,
double... initialElements){
if(sequence instanceof ceylon.language.List)
return toFloatArray((ceylon.language.List<? extends ceylon.language.Float>)sequence,
initialElements);
List<ceylon.language.Float> list = collectIterable(sequence);
float[] ret = new float[initialElements.length + list.size()];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (float) initialElements[i];
}
for(ceylon.language.Float e : list){
ret[i++] = (float)e.doubleValue();
}
return ret;
}
public static float[]
toFloatArray(ceylon.language.List<? extends ceylon.language.Float> sequence,
double... initialElements){
float[] ret = new float[initialElements.length + (int) sequence.getSize()];
int i = 0;
for(;i<initialElements.length;i++){
ret[i] = (float) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (float) sequence.getFirst().doubleValue();
sequence = (ceylon.language.List<? extends ceylon.language.Float>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static double[]
toDoubleArray(ceylon.language.Iterable<? extends ceylon.language.Float, ?> sequence,
double... initialElements){
if(sequence instanceof ceylon.language.List)
return toDoubleArray((ceylon.language.List<? extends ceylon.language.Float>)sequence,
initialElements);
List<ceylon.language.Float> list = collectIterable(sequence);
double[] ret = new double[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Float e : list){
ret[i++] = e.doubleValue();
}
return ret;
}
public static double[]
toDoubleArray(ceylon.language.List<? extends ceylon.language.Float> sequence,
double... initialElements){
double[] ret = new double[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().doubleValue();
sequence = (ceylon.language.List<? extends ceylon.language.Float>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static char[]
toCharArray(ceylon.language.Iterable<? extends ceylon.language.Character, ?> sequence,
int... initialElements){
if(sequence instanceof ceylon.language.List)
return toCharArray((ceylon.language.List<? extends ceylon.language.Character>)sequence,
initialElements);
List<ceylon.language.Character> list = collectIterable(sequence);
char[] ret = new char[list.size() + initialElements.length];
int i=0;
// FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two
for(;i<initialElements.length;i++){
ret[i] = (char) initialElements[i];
}
for(ceylon.language.Character e : list){
ret[i++] = (char)e.intValue();
}
return ret;
}
public static char[]
toCharArray(ceylon.language.List<? extends ceylon.language.Character> sequence,
int... initialElements){
char[] ret = new char[(int) sequence.getSize() + initialElements.length];
int i=0;
// FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two
for(;i<initialElements.length;i++){
ret[i] = (char) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (char) sequence.getFirst().intValue();
sequence = (ceylon.language.List<? extends ceylon.language.Character>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static int[]
toCodepointArray(ceylon.language.Iterable<? extends ceylon.language.Character, ?> sequence,
int... initialElements){
if(sequence instanceof ceylon.language.List)
return toCodepointArray((ceylon.language.List<? extends ceylon.language.Character>)sequence,
initialElements);
List<ceylon.language.Character> list = collectIterable(sequence);
int[] ret = new int[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Character e : list){
ret[i++] = e.intValue();
}
return ret;
}
public static int[]
toCodepointArray(ceylon.language.List<? extends ceylon.language.Character> sequence,
int... initialElements){
int[] ret = new int[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().intValue();
sequence = (ceylon.language.List<? extends ceylon.language.Character>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static java.lang.String[]
toJavaStringArray(ceylon.language.Iterable<? extends ceylon.language.String, ?> sequence,
java.lang.String... initialElements){
if(sequence instanceof ceylon.language.List)
return toJavaStringArray((ceylon.language.List<? extends ceylon.language.String>)sequence,
initialElements);
List<ceylon.language.String> list = collectIterable(sequence);
java.lang.String[] ret = new java.lang.String[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.String e : list){
ret[i++] = e.toString();
}
return ret;
}
public static java.lang.String[]
toJavaStringArray(ceylon.language.List<? extends ceylon.language.String> sequence,
java.lang.String... initialElements){
java.lang.String[] ret = new java.lang.String[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().toString();
sequence = (ceylon.language.List<? extends ceylon.language.String>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(ceylon.language.List<? extends T> sequence,
T[] ret, T... initialElements){
System.arraycopy(initialElements, 0, ret, 0, initialElements.length);
int i=initialElements.length;
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst();
sequence = (ceylon.language.List<? extends T>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(ceylon.language.List<? extends T> sequence,
java.lang.Class<T> klass, T... initialElements){
T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass,
(int)sequence.getSize() + initialElements.length);
System.arraycopy(initialElements, 0, ret, 0, initialElements.length);
int i=initialElements.length;
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst();
sequence = (ceylon.language.List<? extends T>)sequence.getRest();
}
return ret;
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(ceylon.language.Iterable<? extends T, ?> iterable,
java.lang.Class<T> klass, T... initialElements){
List<T> list = collectIterable(iterable);
T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass,
list.size() + initialElements.length);
// fast path
if(initialElements.length == 0){
// fast copy of list
list.toArray(ret);
}else{
// fast copy of initialElements
System.arraycopy(initialElements, 0, ret, 0, initialElements.length);
// slow iteration for list :(
int i = initialElements.length;
for(T o : list)
ret[i++] = o;
}
return ret;
}
public static <T> T checkNull(T t) {
if(t == null)
throw new AssertionException("null value returned from native call not assignable to Object");
return t;
}
/**
* Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence}
* wrapping the given elements, depending on whether the given array is
* empty
* @param elements The elements
* @return A Sequential
*/
@SuppressWarnings({"unchecked","rawtypes"})
public static <T> Sequential<T>
sequentialInstance(TypeDescriptor $reifiedT, T[] elements) {
if (elements.length == 0) {
return (Sequential)empty_.get_();
}
// Annoyingly this implies an extra copy
return ArraySequence.<T>instance($reifiedT, elements);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.String>
sequentialInstanceBoxed(java.lang.String[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(java.lang.String element : elements){
newArray[i++] = ceylon.language.String.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.String.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Integer>
sequentialInstanceBoxed(long[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(long element : elements){
newArray[i++] = ceylon.language.Integer.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Integer.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Character>
sequentialInstanceBoxed(int[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(int element : elements){
newArray[i++] = ceylon.language.Character.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Character.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Boolean>
sequentialInstanceBoxed(boolean[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(boolean element : elements){
newArray[i++] = ceylon.language.Boolean.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Boolean.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Float>
sequentialInstanceBoxed(double[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(double element : elements){
newArray[i++] = ceylon.language.Float.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Float.$TypeDescriptor$,
newArray);
}
/**
* Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence}
* wrapping the given elements, depending on whether the given array
* and varargs are empty
* @param rest The elements at the end of the sequence
* @param elements the elements at the start of the sequence
* @return A Sequential
*/
@SuppressWarnings({"unchecked"})
public static <T> Sequential<? extends T>
sequentialInstance(TypeDescriptor $reifiedT, Sequential<? extends T> rest,
T... elements) {
return sequentialInstance($reifiedT, 0,
elements.length, elements, true, rest);
}
/**
* Returns a Sequential made by concatenating the {@code length} elements
* of {@code elements} starting from {@code state} with the elements of
* {@code rest}: <code> {*elements[start:length], *rest}</code>.
*
* <strong>This method does not copy {@code elements} unless it has to</strong>
*/
@SuppressWarnings("unchecked")
public static <T> Sequential<? extends T> sequentialInstance(
TypeDescriptor $reifiedT,
int start, int length, T[] elements, boolean copy,
Sequential<? extends T> rest) {
if (length == 0){
if(rest.getEmpty()) {
return (Sequential<T>)empty_.get_();
}
return rest;
}
// elements is not empty
if(rest.getEmpty()) {
return new ArraySequence<T>($reifiedT, elements,
start, length, copy);
}
// we have both, let's find the total size
int total = (int) (rest.getSize() + length);
java.lang.Object[] newArray = new java.lang.Object[total];
System.arraycopy(elements, start, newArray, 0, length);
Iterator<? extends T> iterator = rest.iterator();
int i = length;
for(Object elem; (elem = iterator.next()) != finished_.get_(); i++){
newArray[i] = elem;
}
return ArraySequence.<T>instance($reifiedT, newArray);
}
/**
* Method for instantiating a Range (or Empty) from a Tree.SpreadOp,
* {@code start:length}.
* @param start The start
* @param length The size of the Range to create
* @return A range
*/
@SuppressWarnings({"unchecked","rawtypes"})
public static <T extends ceylon.language.Ordinal<? extends T>> Sequential<T>
spreadOp(TypeDescriptor $reifiedT, T start, long length) {
if (length <= 0) {
return (Sequential)empty_.get_();
}
if (start instanceof ceylon.language.Integer) {
ceylon.language.Integer startInt = (ceylon.language.Integer)start;
return new ceylon.language.Range($reifiedT, startInt,
ceylon.language.Integer.instance(startInt.longValue() + (length - 1)));
} else if (start instanceof ceylon.language.Character) {
ceylon.language.Character startChar = (ceylon.language.Character)start;
return new ceylon.language.Range($reifiedT, startChar,
ceylon.language.Character.instance((int)(startChar.intValue() + length - 1)));
} else {
T end = start;
long ii = 0L;
while (++ii < length) {
end = end.getSuccessor();
}
return new ceylon.language.Range($reifiedT, start, end);
}
}
/**
* Returns a runtime exception. To be used by implementors
* of mixin methods used to access super-interfaces $impl fields
* for final classes that don't and will never need them
*/
public static RuntimeException makeUnimplementedMixinAccessException() {
return new RuntimeException("Internal error: should never be called");
}
/**
* Specialised version of Tuple.spanFrom for when the
* typechecker determines that it can do better than the
* generic one that returns a Sequential. Here we return
* a Tuple, although our type signature hides this.
*/
public static Sequential<?> tuple_spanFrom(Ranged tuple,
ceylon.language.Integer index){
Sequential<?> seq = (Sequential<?>)tuple;
long i = index.longValue();
while(i
seq = seq.getRest();
}
return seq;
}
public static boolean[] fillArray(boolean[] array, boolean val){
Arrays.fill(array, val);
return array;
}
public static byte[] fillArray(byte[] array, byte val){
Arrays.fill(array, val);
return array;
}
public static short[] fillArray(short[] array, short val){
Arrays.fill(array, val);
return array;
}
public static int[] fillArray(int[] array, int val){
Arrays.fill(array, val);
return array;
}
public static long[] fillArray(long[] array, long val){
Arrays.fill(array, val);
return array;
}
public static float[] fillArray(float[] array, float val){
Arrays.fill(array, val);
return array;
}
public static double[] fillArray(double[] array, double val){
Arrays.fill(array, val);
return array;
}
public static char[] fillArray(char[] array, char val){
Arrays.fill(array, val);
return array;
}
public static <T> T[] fillArray(T[] array, T val){
Arrays.fill(array, val);
return array;
}
@SuppressWarnings("unchecked")
public static <T> T[] makeArray(TypeDescriptor $reifiedElement, int size){
return (T[]) java.lang.reflect.Array.newInstance($reifiedElement.getArrayElementClass(), size);
}
@SuppressWarnings("unchecked")
public static <T> T[] makeArray(TypeDescriptor $reifiedElement, int... dimensions){
return (T[]) java.lang.reflect.Array.newInstance($reifiedElement.getArrayElementClass(), dimensions);
}
/**
* Returns a runtime exception. To be used by implementors
* of Java array methods used to make sure they are never
* called
*/
public static RuntimeException makeJavaArrayWrapperException() {
return new RuntimeException("Internal error: should never be called");
}
/**
* Throws an exception without having to declare it. This
* uses a Ceylon helper that does this because Ceylon does
* not have checked exceptions. This is merely to avoid a
* javac check wrt. checked exceptions.
* Stef tried using Unsafe.throwException() but
* Unsafe.getUnsafe() throws if we have a ClassLoader, and
* the only other way is using reflection to get to it,
* which starts to smell real bad when we can just use a
* Ceylon helper.
*/
public static void rethrow(final Throwable t){
ceylon.language.impl.rethrow_.rethrow(t);
}
/**
* Null-safe equals.
*/
public static boolean eq(Object a, Object b) {
if(a == null)
return b == null;
if(b == null)
return false;
return a.equals(b);
}
/**
* Applies the given function to the given arguments. The
* argument types are assumed to be correct and will not
* be checked. This method will properly deal with variadic
* functions. The arguments are expected to be spread in the
* given sequential, even in the case of variadic functions,
* which means that there will be no spreading of any
* Sequential instance in the given arguments. On the
* contrary, a portion of the given arguments may be packaged
* into a Sequential if the given function is variadic.
*
* @param function the function to apply
* @param arguments the argument values to pass to the function
* @return the function's return value
*/
public static <Return> Return
apply(Callable<? extends Return> function,
Sequential<? extends Object> arguments){
int variadicParameterIndex = function.$getVariadicParameterIndex$();
switch ((int) arguments.getSize()) {
case 0:
// even if the function is variadic it will overload $call so we're good
return function.$call$();
case 1:
// if the first param is variadic, just pass the sequence along
if(variadicParameterIndex == 0)
return function.$callvariadic$(arguments);
return function.$call$(arguments.get(Integer.instance(0)));
case 2:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential<?>)arguments.spanFrom(Integer.instance(1)));
// no variadic param, or after we run out of elements to pass
default:
return function.$call$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)));
}
case 3:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential<?>)arguments.spanFrom(Integer.instance(1)));
// extract the first and second, pass the rest
case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
(Sequential<?>)arguments.spanFrom(Integer.instance(2)));
// no variadic param, or after we run out of elements to pass
default:
return function.$call$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
arguments.get(Integer.instance(2)));
}
default:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential<?>)arguments.spanFrom(Integer.instance(1)));
// extract the first and second, pass the rest
case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
(Sequential<?>)arguments.spanFrom(Integer.instance(2)));
case 3: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
arguments.get(Integer.instance(2)),
(Sequential<?>)arguments.spanFrom(Integer.instance(3)));
// no variadic param
case -1:
java.lang.Object[] args = Util.toArray(arguments,
new java.lang.Object[(int) arguments.getSize()]);
return function.$call$(args);
// we have a variadic param in there bothering us
default:
// we stuff everything before the variadic into an array
int beforeVariadic = (int)Math.min(arguments.getSize(),
variadicParameterIndex);
boolean needsVariadic = beforeVariadic < arguments.getSize();
args = new java.lang.Object[beforeVariadic + (needsVariadic ? 1 : 0)];
Iterator<?> iterator = arguments.iterator();
java.lang.Object it;
int i=0;
while(i < beforeVariadic &&
(it = iterator.next()) != finished_.get_()){
args[i++] = it;
}
// add the remainder as a variadic arg if required
if(needsVariadic){
args[i] = arguments.spanFrom(Integer.instance(beforeVariadic));
return function.$callvariadic$(args);
}
return function.$call$(args);
}
}
}
@SuppressWarnings("unchecked")
public static <T> java.lang.Class<T>
getJavaClassForDescriptor(TypeDescriptor descriptor) {
if(descriptor == TypeDescriptor.NothingType
|| descriptor == ceylon.language.Object.$TypeDescriptor$
|| descriptor == ceylon.language.Anything.$TypeDescriptor$
|| descriptor == ceylon.language.Basic.$TypeDescriptor$
|| descriptor == ceylon.language.Null.$TypeDescriptor$
|| descriptor == ceylon.language.Identifiable.$TypeDescriptor$)
return (java.lang.Class<T>) Object.class;
if(descriptor instanceof TypeDescriptor.Class)
return (java.lang.Class<T>) ((TypeDescriptor.Class) descriptor).getKlass();
if(descriptor instanceof TypeDescriptor.Member)
return getJavaClassForDescriptor(((TypeDescriptor.Member) descriptor).getMember());
if(descriptor instanceof TypeDescriptor.Intersection)
return (java.lang.Class<T>) Object.class;
if(descriptor instanceof TypeDescriptor.Union){
TypeDescriptor.Union union = (TypeDescriptor.Union) descriptor;
TypeDescriptor[] members = union.getMembers();
// special case for optional types
if(members.length == 2){
if(members[0] == ceylon.language.Null.$TypeDescriptor$)
return getJavaClassForDescriptor(members[1]);
if(members[1] == ceylon.language.Null.$TypeDescriptor$)
return getJavaClassForDescriptor(members[0]);
}
return (java.lang.Class<T>) Object.class;
}
return (java.lang.Class<T>) Object.class;
}
public static int arrayLength(Object o) {
if (o instanceof Object[])
return ((Object[])o).length;
else if (o instanceof boolean[])
return ((boolean[])o).length;
else if (o instanceof float[])
return ((float[])o).length;
else if (o instanceof double[])
return ((double[])o).length;
else if (o instanceof char[])
return ((char[])o).length;
else if (o instanceof byte[])
return ((byte[])o).length;
else if (o instanceof short[])
return ((short[])o).length;
else if (o instanceof int[])
return ((int[])o).length;
else if (o instanceof long[])
return ((long[])o).length;
throw new ClassCastException(notArrayType(o));
}
public static long getIntegerArray(Object o, int index) {
if (o instanceof byte[])
return ((byte[])o)[index];
else if (o instanceof short[])
return ((short[])o)[index];
else if (o instanceof int[])
return ((int[])o)[index];
else if (o instanceof long[])
return ((long[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static double getDoubleArray(Object o, int index) {
if (o instanceof float[])
return ((float[])o)[index];
else if (o instanceof double[])
return ((double[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static int getCharacterArray(Object o, int index) {
if (o instanceof char[])
return ((char[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static boolean getBooleanArray(Object o, int index) {
if (o instanceof boolean[])
return ((boolean[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static Object getObjectArray(Object o, int index) {
if (o instanceof Object[])
return ((Object[])o)[index];
else if (o instanceof boolean[])
return ceylon.language.Boolean.instance(((boolean[])o)[index]);
else if (o instanceof float[])
return ceylon.language.Float.instance(((float[])o)[index]);
else if (o instanceof double[])
return ceylon.language.Float.instance(((double[])o)[index]);
else if (o instanceof char[])
return ceylon.language.Character.instance(((char[])o)[index]);
else if (o instanceof byte[])
return ceylon.language.Integer.instance(((byte[])o)[index]);
else if (o instanceof short[])
return ceylon.language.Integer.instance(((short[])o)[index]);
else if (o instanceof int[])
return ceylon.language.Integer.instance(((int[])o)[index]);
else if (o instanceof long[])
return ceylon.language.Integer.instance(((long[])o)[index]);
throw new ClassCastException(notArrayType(o));
}
private static String notArrayType(Object o) {
return (o == null ? "null" : o.getClass().getName()) + " is not an array type";
}
} |
package net.tomp2p.storage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class DataBuffer {
private final List<ByteBuf> buffers;
private int alreadyTransferred = 0;
public DataBuffer() {
this(1);
}
public DataBuffer(int nrArrays) {
buffers = new ArrayList<ByteBuf>(nrArrays);
}
public DataBuffer(final byte[] buffer) {
this(buffer, 0, buffer.length);
}
public DataBuffer(final byte[] buffer, final int offset, final int length) {
buffers = new ArrayList<ByteBuf>(1);
final ByteBuf buf = Unpooled.wrappedBuffer(buffer, offset, length);
buffers.add(buf);
// no need to retain, as we initialized here and ref counter is set to 1
}
/**
* Creates a DataBuffer and adds the ByteBuf to this DataBuffer
*
* @param buf
* The ByteBuf is only added, but no retain() is called!
*/
public DataBuffer(final ByteBuf buf) {
ByteBuf slice = Unpooled.wrappedBuffer(buf);
buffers = new ArrayList<ByteBuf>(1);
buffers.add(slice);
}
private DataBuffer(final List<ByteBuf> buffers) {
this.buffers = new ArrayList<ByteBuf>(buffers.size());
for (final ByteBuf buf : buffers) {
this.buffers.add(buf.duplicate());
buf.retain();
}
}
public DataBuffer add(DataBuffer dataBuffer) {
synchronized (buffers) {
buffers.addAll(dataBuffer.buffers);
}
return this;
}
// from here, work with shallow copies
public DataBuffer shallowCopy() {
final DataBuffer db;
synchronized (buffers) {
db = new DataBuffer(buffers);
}
return db;
}
/**
* Always make a copy with shallowCopy before using the buffer directly.
* This buffer is not thread safe!
*
* @return The backing list of byte buffers
*/
public List<ByteBuffer> bufferList() {
final DataBuffer copy = shallowCopy();
final List<ByteBuffer> nioBuffers = new ArrayList<ByteBuffer>(
copy.buffers.size());
for (final ByteBuf buf : copy.buffers) {
for (final ByteBuffer bb : buf.nioBuffers()) {
nioBuffers.add(bb);
}
}
return nioBuffers;
}
/**
* @return The length of the data that is backed by the data buffer
*/
public int length() {
int length = 0;
final DataBuffer copy = shallowCopy();
for (final ByteBuf buffer : copy.buffers) {
length += buffer.writerIndex();
}
return length;
}
/**
* @return The wrapped ByteBuf backed by the buffers stored in here. The buffer is
* not deep copied here.
*/
public ByteBuf toByteBuf() {
final DataBuffer copy = shallowCopy();
return Unpooled.wrappedBuffer(copy.buffers.toArray(new ByteBuf[0]));
}
/**
* @return The ByteBuf arrays backed by the buffers stored in here. The buffer is
* not deep copied here.
*/
public ByteBuf[] toByteBufs() {
final DataBuffer copy = shallowCopy();
return copy.buffers.toArray(new ByteBuf[0]);
}
/**
* @return The ByteBuffers backed by the buffers stored in here. The buffer
* is not deep copied here.
*/
public ByteBuffer[] toByteBuffer() {
return toByteBuf().nioBuffers();
}
/**
* Transfers the data from this buffer the CompositeByteBuf.
*
* @param buf
* The CompositeByteBuf, where the data from this buffer is
* transfered to
*/
public void transferTo(final AlternativeCompositeByteBuf buf) {
final DataBuffer copy = shallowCopy();
for (final ByteBuf buffer : copy.buffers) {
buf.addComponent(buffer);
alreadyTransferred += buffer.readableBytes();
}
}
public int transferFrom(final ByteBuf buf, final int remaining) {
final int readable = buf.readableBytes();
final int index = buf.readerIndex();
final int length = Math.min(remaining, readable);
if (length == 0) {
return 0;
}
if (buf instanceof AlternativeCompositeByteBuf) {
final List<ByteBuf> decoms = ((AlternativeCompositeByteBuf) buf)
.decompose(index, length);
for (final ByteBuf decom : decoms) {
synchronized (buffers) {
// this is already a slice
buffers.add(decom);
}
decom.retain();
}
} else {
synchronized (buffers) {
buffers.add(buf.slice(index, length));
}
buf.retain();
}
alreadyTransferred += length;
buf.readerIndex(buf.readerIndex() + length);
return length;
}
public int alreadyTransferred() {
return alreadyTransferred;
}
public void resetAlreadyTransferred() {
alreadyTransferred = 0;
}
@Override
public int hashCode() {
return toByteBuffer().hashCode();
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof DataBuffer)) {
return false;
}
if (this == obj) {
return true;
}
final DataBuffer m = (DataBuffer) obj;
return m.toByteBuf().equals(toByteBuf());
}
@Override
protected void finalize() throws Throwable {
final DataBuffer copy = shallowCopy();
for (ByteBuf buf : copy.buffers) {
buf.release();
}
}
public byte[] bytes() {
final ByteBuffer[] bufs = toByteBuffer();
final int bufLength = bufs.length;
int size = 0;
for (int i = 0; i < bufLength; i++) {
size += bufs[i].remaining();
}
byte[] retVal = new byte[size];
for (int i = 0, offset = 0; i < bufLength; i++) {
final int remaining = bufs[i].remaining();
bufs[i].get(retVal, offset, remaining);
offset += remaining;
}
return retVal;
}
} |
package com.exedio.cope;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import bak.pcj.list.IntList;
import com.exedio.dsmf.Driver;
import com.exedio.dsmf.SQLRuntimeException;
import com.exedio.dsmf.Schema;
abstract class AbstractDatabase implements Database // TODO rename
{
protected static final int TWOPOW8 = 1<<8;
protected static final int TWOPOW16 = 1<<16;
protected static final int TWOPOW24 = 1<<24;
private static final String NO_SUCH_ROW = "no such row";
private final ArrayList<Table> tables = new ArrayList<Table>();
private final HashMap<String, UniqueConstraint> uniqueConstraintsByID = new HashMap<String, UniqueConstraint>();
private boolean buildStage = true;
final Driver driver;
private final boolean prepare;
private final boolean log;
private final boolean butterflyPkSource;
private final boolean fulltextIndex;
final ConnectionPool connectionPool;
private final java.util.Properties forcedNames;
final java.util.Properties tableOptions;
final int limitSupport;
final long blobLengthFactor;
final boolean oracle; // TODO remove
protected AbstractDatabase(final Driver driver, final Properties properties)
{
this.driver = driver;
this.prepare = !properties.getDatabaseDontSupportPreparedStatements();
this.log = properties.getDatabaseLog();
this.butterflyPkSource = properties.getPkSourceButterfly();
this.fulltextIndex = properties.getFulltextIndex();
this.connectionPool = new ConnectionPool(properties);
this.forcedNames = properties.getDatabaseForcedNames();
this.tableOptions = properties.getDatabaseTableOptions();
this.limitSupport = properties.getDatabaseDontSupportLimit() ? LIMIT_SUPPORT_NONE : getLimitSupport();
this.blobLengthFactor = getBlobLengthFactor();
this.oracle = getClass().getName().equals("com.exedio.cope.OracleDatabase");
switch(limitSupport)
{
case LIMIT_SUPPORT_NONE:
case LIMIT_SUPPORT_CLAUSE_AFTER_SELECT:
case LIMIT_SUPPORT_CLAUSE_AFTER_WHERE:
case LIMIT_SUPPORT_CLAUSES_AROUND:
break;
default:
throw new RuntimeException(Integer.toString(limitSupport));
}
//System.out.println("using database "+getClass());
}
public final Driver getDriver()
{
return driver;
}
public final java.util.Properties getTableOptions()
{
return tableOptions;
}
public final ConnectionPool getConnectionPool()
{
return connectionPool;
}
public final void addTable(final Table table)
{
if(!buildStage)
throw new RuntimeException();
tables.add(table);
}
public final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint)
{
if(!buildStage)
throw new RuntimeException();
final Object collision = uniqueConstraintsByID.put(constraintID, constraint);
if(collision!=null)
throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision);
}
protected final Statement createStatement()
{
return createStatement(true);
}
protected final Statement createStatement(final boolean qualifyTable)
{
return new Statement(this, prepare, qualifyTable, isDefiningColumnTypes());
}
protected final Statement createStatement(final Query query)
{
return new Statement(this, prepare, query, isDefiningColumnTypes());
}
public void createDatabase()
{
buildStage = false;
makeSchema().create();
}
public void createDatabaseConstraints()
{
buildStage = false;
makeSchema().createConstraints();
}
//private static int checkTableTime = 0;
public void checkDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
final Statement bf = createStatement(true);
bf.append("select count(*) from ").defineColumnInteger();
boolean first = true;
for(final Table table : tables)
{
if(first)
first = false;
else
bf.append(',');
bf.append(table.protectedID);
}
bf.append(" where ");
first = true;
for(final Table table : tables)
{
if(first)
first = false;
else
bf.append(" and ");
final Column primaryKey = table.primaryKey;
bf.append(primaryKey).
append('=').
appendParameter(Type.NOT_A_PK);
for(final Column column : table.getColumns())
{
bf.append(" and ").
append(column);
if(column instanceof BlobColumn || (oracle && column instanceof StringColumn && ((StringColumn)column).maximumLength>=4000))
{
bf.append("is not null");
}
else
{
bf.append('=').
appendParameter(column, column.getCheckValue());
}
}
}
executeSQLQuery(connection, bf,
new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
}
},
false
);
}
public void dropDatabase()
{
buildStage = false;
makeSchema().drop();
}
public void dropDatabaseConstraints()
{
buildStage = false;
makeSchema().dropConstraints();
}
public void tearDownDatabase()
{
buildStage = false;
makeSchema().tearDown();
}
public void tearDownDatabaseConstraints()
{
buildStage = false;
makeSchema().tearDownConstraints();
}
public void checkEmptyDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
for(final Table table : tables)
{
final int count = countTable(connection, table);
if(count>0)
throw new RuntimeException("there are "+count+" items left for table "+table.id);
}
//final long amount = (System.currentTimeMillis()-time);
//checkEmptyTableTime += amount;
//System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime);
}
public final ArrayList<Object> search(final Connection connection, final Query query, final boolean doCountOnly)
{
buildStage = false;
listener.search(connection, query, doCountOnly);
final int limitStart = query.limitStart;
final int limitCount = query.limitCount;
final boolean limitActive = limitStart>0 || limitCount!=Query.UNLIMITED_COUNT;
final ArrayList queryJoins = query.joins;
final Statement bf = createStatement(query);
if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSES_AROUND)
appendLimitClause(bf, limitStart, limitCount);
bf.append("select");
if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSE_AFTER_SELECT)
appendLimitClause(bf, limitStart, limitCount);
bf.append(' ');
final Function[] selects = query.selects;
final Column[] selectColumns = new Column[selects.length];
final Type[] selectTypes = new Type[selects.length];
if(doCountOnly)
{
bf.append("count(*)");
}
else
{
for(int selectableIndex = 0; selectableIndex<selects.length; selectableIndex++)
{
final Function selectable = selects[selectableIndex];
final Column selectColumn;
final Type selectType;
final Table selectTable;
final Column selectPrimaryKey;
final Function<? extends Object> selectAttribute = (Function<? extends Object>)selectable; // TODO rename
selectType = selectAttribute.getType();
if(selectableIndex>0)
bf.append(',');
if(selectable instanceof FunctionAttribute)
{
selectColumn = ((FunctionAttribute)selectAttribute).getColumn();
bf.append((FunctionAttribute)selectable, (Join)null).defineColumn(selectColumn);
if(selectable instanceof ItemAttribute)
{
final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn();
if(typeColumn!=null)
bf.append(',').append(typeColumn).defineColumn(typeColumn);
}
}
else if(selectable instanceof Type.This)
{
selectTable = selectType.getTable();
selectPrimaryKey = selectTable.primaryKey;
selectColumn = selectPrimaryKey;
bf.appendPK(selectType, (Join)null).defineColumn(selectColumn);
if(selectColumn.primaryKey)
{
final StringColumn selectTypeColumn = selectColumn.getTypeColumn();
if(selectTypeColumn!=null)
{
bf.append(',').
append(selectTypeColumn).defineColumn(selectTypeColumn);
}
else
selectTypes[selectableIndex] = selectType.getOnlyPossibleTypeOfInstances();
}
else
selectTypes[selectableIndex] = selectType.getOnlyPossibleTypeOfInstances();
}
else
{
selectColumn = null;
final View view = (View)selectable;
bf.append(view, (Join)null).defineColumn(view);
}
selectColumns[selectableIndex] = selectColumn;
}
}
bf.append(" from ").
appendTypeDefinition((Join)null, query.type);
if(queryJoins!=null)
{
for(Iterator i = queryJoins.iterator(); i.hasNext(); )
{
final Join join = (Join)i.next();
bf.append(' ').
append(join.getKindString()).
append(" join ").
appendTypeDefinition(join, join.type);
final Condition joinCondition = join.condition;
if(joinCondition!=null)
{
bf.append(" on ");
joinCondition.append(bf);
}
bf.appendTypeJoinCondition(joinCondition!=null ? " and " : " on ", join, join.type);
}
}
if(query.condition!=null)
{
bf.append(" where ");
query.condition.append(bf);
}
bf.appendTypeJoinCondition(query.condition!=null ? " and " : " where ", (Join)null, query.type);
if(!doCountOnly)
{
final Function[] orderBy = query.orderBy;
if(orderBy!=null)
{
final boolean[] orderAscending = query.orderAscending;
for(int i = 0; i<orderBy.length; i++)
{
bf.appendOrderBy();
if(orderBy[i] instanceof ItemAttribute)
{
final ItemAttribute<? extends Item> itemOrderBy = (ItemAttribute<? extends Item>)orderBy[i];
itemOrderBy.getTargetType().getPkSource().appendOrderByExpression(bf, itemOrderBy);
}
else if(orderBy[i] instanceof Type.This)
{
final Type.This<? extends Item> itemOrderBy = (Type.This<? extends Item>)orderBy[i];
itemOrderBy.type.getPkSource().appendOrderByExpression(bf, itemOrderBy);
}
else
bf.append(orderBy[i], (Join)null);
if(!orderAscending[i])
bf.append(" desc");
// TODO break here, if already ordered by some unique function
}
}
if(limitActive && limitSupport==LIMIT_SUPPORT_CLAUSE_AFTER_WHERE)
appendLimitClause(bf, limitStart, limitCount);
}
if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSES_AROUND)
appendLimitClause2(bf, limitStart, limitCount);
final Type[] types = selectTypes;
final Model model = query.model;
final ArrayList<Object> result = new ArrayList<Object>();
if(limitStart<0)
throw new RuntimeException();
if(selects.length!=selectColumns.length)
throw new RuntimeException();
if(selects.length!=types.length)
throw new RuntimeException();
//System.out.println(bf.toString());
query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(doCountOnly)
{
resultSet.next();
result.add(Integer.valueOf(resultSet.getInt(1)));
if(resultSet.next())
throw new RuntimeException();
return;
}
if(limitStart>0 && limitSupport==LIMIT_SUPPORT_NONE)
{
// TODO: ResultSet.relative
// Would like to use
// resultSet.relative(limitStart+1);
// but this throws a java.sql.SQLException:
// Invalid operation for forward only resultset : relative
for(int i = limitStart; i>0; i
resultSet.next();
}
int i = ((limitCount==Query.UNLIMITED_COUNT||(limitSupport!=LIMIT_SUPPORT_NONE)) ? Integer.MAX_VALUE : limitCount );
if(i<=0)
throw new RuntimeException(String.valueOf(limitCount));
while(resultSet.next() && (--i)>=0)
{
int columnIndex = 1;
final Object[] resultRow = (selects.length > 1) ? new Object[selects.length] : null;
final Row dummyRow = new Row();
for(int selectableIndex = 0; selectableIndex<selects.length; selectableIndex++)
{
final Function selectable = selects[selectableIndex];
final Object resultCell;
if(selectable instanceof FunctionAttribute)
{
selectColumns[selectableIndex].load(resultSet, columnIndex++, dummyRow);
final FunctionAttribute selectAttribute = (FunctionAttribute)selectable;
if(selectable instanceof ItemAttribute)
{
final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn();
if(typeColumn!=null)
typeColumn.load(resultSet, columnIndex++, dummyRow);
}
resultCell = selectAttribute.get(dummyRow);
}
else if(selectable instanceof View)
{
final View selectFunction = (View)selectable;
resultCell = selectFunction.load(resultSet, columnIndex++);
}
else
{
final Number pk = (Number)resultSet.getObject(columnIndex++);
//System.out.println("pk:"+pk);
if(pk==null)
{
// can happen when using right outer joins
resultCell = null;
}
else
{
final Type type = types[selectableIndex];
final Type currentType;
if(type==null)
{
final String typeID = resultSet.getString(columnIndex++);
currentType = model.findTypeByID(typeID);
if(currentType==null)
throw new RuntimeException("no type with type id "+typeID);
}
else
currentType = type;
resultCell = currentType.getItemObject(pk.intValue());
}
}
if(resultRow!=null)
resultRow[selectableIndex] = resultCell;
else
result.add(resultCell);
}
if(resultRow!=null)
result.add(Collections.unmodifiableList(Arrays.asList(resultRow)));
}
}
}, query.makeStatementInfo));
return result;
}
private void log(final long start, final long end, final String sqlText)
{
final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
System.out.println(df.format(new Date(start)) + " " + (end-start) + "ms: " + sqlText);
}
public void load(final Connection connection, final PersistentState state)
{
buildStage = false;
listener.load(connection, state);
final Statement bf = createStatement(state.type.getSupertype()!=null);
bf.append("select ");
boolean first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
for(final Column column : type.getTable().getColumns())
{
if(!(column instanceof BlobColumn))
{
if(first)
first = false;
else
bf.append(',');
bf.append(column).defineColumn(column);
}
}
}
if(first)
{
// no columns in type
bf.appendPK(state.type, (Join)null);
}
bf.append(" from ");
first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(',');
bf.append(type.getTable().protectedID);
}
bf.append(" where ");
first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(" and ");
bf.appendPK(type, (Join)null).
append('=').
appendParameter(state.pk);
// Additionally check correctness of type column
// If type column is inconsistent, the database
// will return no rows and the result set handler
// will fail
// Here this also checks for Model#findByID,
// that the item has the type given in the ID.
final StringColumn typeColumn = type.getTable().typeColumn;
if(typeColumn!=null)
{
bf.append(" and ").
append(typeColumn).
append('=').
appendParameter(state.type.id);
}
}
//System.out.println(bf.toString());
executeSQLQuery(connection, bf, state, false);
}
public void store(
final Connection connection,
final State state,
final boolean present,
final Map<BlobColumn, byte[]> blobs)
{
store(connection, state, present, blobs, state.type);
}
private void store(
final Connection connection,
final State state,
final boolean present,
final Map<BlobColumn, byte[]> blobs,
final Type type)
{
buildStage = false;
final Type supertype = type.getSupertype();
if(supertype!=null)
store(connection, state, present, blobs, supertype);
final Table table = type.getTable();
final List<Column> columns = table.getColumns();
final Statement bf = createStatement();
final StringColumn typeColumn = table.typeColumn;
if(present)
{
bf.append("update ").
append(table.protectedID).
append(" set ");
boolean first = true;
for(final Column column : columns)
{
if(!(column instanceof BlobColumn) || blobs.containsKey(column))
{
if(first)
first = false;
else
bf.append(',');
bf.append(column.protectedID).
append('=');
if(column instanceof BlobColumn)
bf.appendParameterBlob((BlobColumn)column, blobs.get(column));
else
bf.appendParameter(column, state.store(column));
}
}
if(first) // no columns in table
return;
bf.append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(state.pk);
// Additionally check correctness of type column
// If type column is inconsistent, the database
// will return "0 rows affected" and executeSQLUpdate
// will fail
if(typeColumn!=null)
{
bf.append(" and ").
append(typeColumn.protectedID).
append('=').
appendParameter(state.type.id);
}
}
else
{
bf.append("insert into ").
append(table.protectedID).
append("(").
append(table.primaryKey.protectedID);
if(typeColumn!=null)
{
bf.append(',').
append(typeColumn.protectedID);
}
for(final Column column : columns)
{
if(!(column instanceof BlobColumn) || blobs.containsKey(column))
{
bf.append(',').
append(column.protectedID);
}
}
bf.append(")values(").
appendParameter(state.pk);
if(typeColumn!=null)
{
bf.append(',').
appendParameter(state.type.id);
}
for(final Column column : columns)
{
if(column instanceof BlobColumn)
{
if(blobs.containsKey(column))
{
bf.append(',').
appendParameterBlob((BlobColumn)column, blobs.get(column));
}
}
else
{
bf.append(',').
appendParameter(column, state.store(column));
}
}
bf.append(')');
}
//System.out.println("storing "+bf.toString());
final List uqs = type.declaredUniqueConstraints;
executeSQLUpdate(connection, bf, 1, uqs.size()==1?(UniqueConstraint)uqs.iterator().next():null);
}
public void delete(final Connection connection, final Item item)
{
buildStage = false;
final Type type = item.type;
final int pk = item.pk;
for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype())
{
final Table currentTable = currentType.getTable();
final Statement bf = createStatement();
bf.append("delete from ").
append(currentTable.protectedID).
append(" where ").
append(currentTable.primaryKey.protectedID).
append('=').
appendParameter(pk);
//System.out.println("deleting "+bf.toString());
try
{
executeSQLUpdate(connection, bf, 1);
}
catch(UniqueViolationException e)
{
throw new RuntimeException(e);
}
}
}
public final byte[] load(final Connection connection, final BlobColumn column, final Item item)
{
// TODO reuse code in load blob methods
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("select ").
append(column.protectedID).defineColumn(column).
append(" from ").
append(table.protectedID).
append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk);
// Additionally check correctness of type column
// If type column is inconsistent, the database
// will return no rows and the result set handler
// will fail
final StringColumn typeColumn = table.typeColumn;
if(typeColumn!=null)
{
bf.append(" and ").
append(typeColumn.protectedID).
append('=').
appendParameter(item.type.id);
}
final LoadBlobResultSetHandler handler = new LoadBlobResultSetHandler(supportsGetBytes());
executeSQLQuery(connection, bf, handler, false);
return handler.result;
}
private static class LoadBlobResultSetHandler implements ResultSetHandler
{
final boolean supportsGetBytes;
LoadBlobResultSetHandler(final boolean supportsGetBytes)
{
this.supportsGetBytes = supportsGetBytes;
}
byte[] result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
result = supportsGetBytes ? resultSet.getBytes(1) : loadBlob(resultSet.getBlob(1));
}
private static final byte[] loadBlob(final Blob blob) throws SQLException
{
if(blob==null)
return null;
return DataAttribute.copy(blob.getBinaryStream(), blob.length());
}
}
public final void load(final Connection connection, final BlobColumn column, final Item item, final OutputStream data, final DataAttribute attribute)
{
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("select ").
append(column.protectedID).defineColumn(column).
append(" from ").
append(table.protectedID).
append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk);
// Additionally check correctness of type column
// If type column is inconsistent, the database
// will return no rows and the result set handler
// will fail
final StringColumn typeColumn = table.typeColumn;
if(typeColumn!=null)
{
bf.append(" and ").
append(typeColumn.protectedID).
append('=').
appendParameter(item.type.id);
}
executeSQLQuery(connection, bf, new ResultSetHandler(){
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
final Blob blob = resultSet.getBlob(1);
if(blob!=null)
{
InputStream source = null;
try
{
source = blob.getBinaryStream();
attribute.copy(source, data, blob.length(), item);
}
catch(IOException e)
{
throw new RuntimeException(e);
}
finally
{
if(source!=null)
{
try
{
source.close();
}
catch(IOException e)
{/*IGNORE*/}
}
}
}
}
}, false);
}
public final long loadLength(final Connection connection, final BlobColumn column, final Item item)
{
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("select length(").
append(column.protectedID).defineColumnInteger().
append(") from ").
append(table.protectedID).
append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk);
// Additionally check correctness of type column
// If type column is inconsistent, the database
// will return no rows and the result set handler
// will fail
final StringColumn typeColumn = table.typeColumn;
if(typeColumn!=null)
{
bf.append(" and ").
append(typeColumn.protectedID).
append('=').
appendParameter(item.type.id);
}
final LoadBlobLengthResultSetHandler handler = new LoadBlobLengthResultSetHandler();
executeSQLQuery(connection, bf, handler, false);
return handler.result;
}
private class LoadBlobLengthResultSetHandler implements ResultSetHandler
{
long result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
final Object o = resultSet.getObject(1);
if(o!=null)
{
long value = ((Number)o).longValue();
final long factor = blobLengthFactor;
if(factor!=1)
{
if(value%factor!=0)
throw new RuntimeException("not dividable "+value+'/'+factor);
value /= factor;
}
result = value;
}
else
result = -1;
}
}
public final void store(
final Connection connection, final BlobColumn column, final Item item,
final InputStream data, final DataAttribute attribute)
throws IOException
{
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("update ").
append(table.protectedID).
append(" set ").
append(column.protectedID).
append('=');
if(data!=null)
bf.appendParameterBlob(column, data, attribute, item);
else
bf.append("NULL");
bf.append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk);
// Additionally check correctness of type column
// If type column is inconsistent, the database
// will return "0 rows affected" and executeSQLUpdate
// will fail
final StringColumn typeColumn = table.typeColumn;
if(typeColumn!=null)
{
bf.append(" and ").
append(typeColumn.protectedID).
append('=').
appendParameter(item.type.id);
}
//System.out.println("storing "+bf.toString());
try
{
executeSQLUpdate(connection, bf, 1, null);
}
catch(UniqueViolationException e)
{
throw new RuntimeException(e);
}
}
static interface ResultSetHandler
{
public void run(ResultSet resultSet) throws SQLException;
}
private final static int convertSQLResult(final Object sqlInteger)
{
// IMPLEMENTATION NOTE
// Whether the returned object is an Integer, a Long or a BigDecimal,
// depends on the database used and for oracle on whether
// OracleStatement.defineColumnType is used or not, so we support all
// here.
return ((Number)sqlInteger).intValue();
}
//private static int timeExecuteQuery = 0;
protected final StatementInfo executeSQLQuery(
final Connection connection,
final Statement statement,
final ResultSetHandler resultSetHandler,
final boolean makeStatementInfo)
{
java.sql.Statement sqlStatement = null;
ResultSet resultSet = null;
try
{
final String sqlText = statement.getText();
final long logStart = (log||makeStatementInfo) ? System.currentTimeMillis() : 0;
final long logPrepared;
final long logExecuted;
if(!prepare)
{
sqlStatement = connection.createStatement();
defineColumnTypes(statement.columnTypes, sqlStatement);
logPrepared = (log||makeStatementInfo) ? System.currentTimeMillis() : 0;
resultSet = sqlStatement.executeQuery(sqlText);
logExecuted = (log||makeStatementInfo) ? System.currentTimeMillis() : 0;
resultSetHandler.run(resultSet);
}
else
{
final PreparedStatement prepared = connection.prepareStatement(sqlText);
sqlStatement = prepared;
int parameterIndex = 1;
for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++)
setObject(sqlText, prepared, parameterIndex, i.next());
defineColumnTypes(statement.columnTypes, sqlStatement);
logPrepared = (log||makeStatementInfo) ? System.currentTimeMillis() : 0;
resultSet = prepared.executeQuery();
logExecuted = (log||makeStatementInfo) ? System.currentTimeMillis() : 0;
resultSetHandler.run(resultSet);
}
final long logResultRead = (log||makeStatementInfo) ? System.currentTimeMillis() : 0;
if(resultSet!=null)
{
resultSet.close();
resultSet = null;
}
if(sqlStatement!=null)
{
sqlStatement.close();
sqlStatement = null;
}
final long logEnd = (log||makeStatementInfo) ? System.currentTimeMillis() : 0;
if(log)
log(logStart, logEnd, sqlText);
if(makeStatementInfo)
return makeStatementInfo(statement, connection, logStart, logPrepared, logExecuted, logResultRead, logEnd);
else
return null;
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(resultSet!=null)
{
try
{
resultSet.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows)
throws UniqueViolationException
{
executeSQLUpdate(connection, statement, expectedRows, null);
}
private final void executeSQLUpdate(
final Connection connection,
final Statement statement, final int expectedRows,
final UniqueConstraint onlyThreatenedUniqueConstraint)
throws UniqueViolationException
{
java.sql.Statement sqlStatement = null;
try
{
final String sqlText = statement.getText();
final long logStart = log ? System.currentTimeMillis() : 0;
final int rows;
if(!prepare)
{
sqlStatement = connection.createStatement();
rows = sqlStatement.executeUpdate(sqlText);
}
else
{
final PreparedStatement prepared = connection.prepareStatement(sqlText);
sqlStatement = prepared;
int parameterIndex = 1;
for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++)
setObject(sqlText, prepared, parameterIndex, i.next());
rows = prepared.executeUpdate();
}
final long logEnd = log ? System.currentTimeMillis() : 0;
if(log)
log(logStart, logEnd, sqlText);
//System.out.println("("+rows+"): "+statement.getText());
if(rows!=expectedRows)
throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText);
}
catch(SQLException e)
{
final UniqueViolationException wrappedException = wrapException(e, onlyThreatenedUniqueConstraint);
if(wrappedException!=null)
throw wrappedException;
else
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
private static final void setObject(String s, final PreparedStatement statement, final int parameterIndex, final Object value)
throws SQLException
{
//try{
statement.setObject(parameterIndex, value);
//}catch(SQLException e){ throw new SQLRuntimeException(e, "setObject("+parameterIndex+","+value+")"+s); }
}
protected static final String EXPLAIN_PLAN = "explain plan";
protected StatementInfo makeStatementInfo(
final Statement statement, final Connection connection,
final long start, final long prepared, final long executed, final long resultRead, final long end)
{
final StatementInfo result = new StatementInfo(statement.getText());
result.addChild(new StatementInfo("timing "+(end-start)+'/'+(prepared-start)+'/'+(executed-prepared)+'/'+(resultRead-executed)+'/'+(end-resultRead)+" (total/prepare/execute/readResult/close in ms)"));
return result;
}
protected abstract String extractUniqueConstraintName(SQLException e);
protected final static String ANY_CONSTRAINT = "--ANY
private final UniqueViolationException wrapException(
final SQLException e,
final UniqueConstraint onlyThreatenedUniqueConstraint)
{
final String uniqueConstraintID = extractUniqueConstraintName(e);
if(uniqueConstraintID!=null)
{
final UniqueConstraint constraint;
if(ANY_CONSTRAINT.equals(uniqueConstraintID))
constraint = onlyThreatenedUniqueConstraint;
else
{
constraint = uniqueConstraintsByID.get(uniqueConstraintID);
if(constraint==null)
throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID
+"<, has only "+uniqueConstraintsByID.keySet());
}
return new UniqueViolationException(constraint, null, e);
}
return null;
}
/**
* Trims a name to length for being a suitable qualifier for database entities,
* such as tables, columns, indexes, constraints, partitions etc.
*/
protected static final String trimString(final String longString, final int maxLength)
{
if(maxLength<=0)
throw new RuntimeException("maxLength must be greater zero");
if(longString.length()==0)
throw new RuntimeException("longString must not be empty");
if(longString.length()<=maxLength)
return longString;
int longStringLength = longString.length();
final int[] trimPotential = new int[maxLength];
final ArrayList<String> words = new ArrayList<String>();
{
final StringBuffer buf = new StringBuffer();
for(int i=0; i<longString.length(); i++)
{
final char c = longString.charAt(i);
if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
if(buf.length()<maxLength)
buf.append(c);
else
longStringLength
}
if(buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
}
final int expectedTrimPotential = longStringLength - maxLength;
//System.out.println("expected trim potential = "+expectedTrimPotential);
int wordLength;
int remainder = 0;
for(wordLength = trimPotential.length-1; wordLength>=0; wordLength
{
//System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]);
remainder = trimPotential[wordLength] - expectedTrimPotential;
if(remainder>=0)
break;
}
final StringBuffer result = new StringBuffer(longStringLength);
for(final String word : words)
{
//System.out.println("word "+word+" remainder:"+remainder);
if((word.length()>wordLength) && remainder>0)
{
result.append(word.substring(0, wordLength+1));
remainder
}
else if(word.length()>wordLength)
result.append(word.substring(0, wordLength));
else
result.append(word);
}
if(result.length()!=maxLength)
throw new RuntimeException(result.toString()+maxLength);
return result.toString();
}
public String makeName(final String longName)
{
return makeName(null, longName);
}
public String makeName(final String prefix, final String longName)
{
final String query = prefix==null ? longName : prefix+'.'+longName;
final String forcedName = forcedNames.getProperty(query);
if(forcedName!=null)
return forcedName;
return trimString(longName, 25);
}
public boolean supportsCheckConstraints()
{
return true;
}
public boolean supportsGetBytes()
{
return true;
}
public boolean supportsEmptyStrings()
{
return true;
}
public boolean supportsRightOuterJoins()
{
return true;
}
public boolean fakesSupportReadCommitted()
{
return false;
}
public int getBlobLengthFactor()
{
return 1;
}
public abstract String getIntegerType(int precision);
public abstract String getDoubleType(int precision);
public abstract String getStringType(int maxLength);
public abstract String getDayType();
abstract int getLimitSupport();
protected static final int LIMIT_SUPPORT_NONE = 26;
protected static final int LIMIT_SUPPORT_CLAUSE_AFTER_SELECT = 63;
protected static final int LIMIT_SUPPORT_CLAUSE_AFTER_WHERE = 93;
protected static final int LIMIT_SUPPORT_CLAUSES_AROUND = 134;
/**
* Appends a clause to the statement causing the database limiting the query result.
* This method is never called for <tt>start==0 && count=={@link Query#UNLIMITED_COUNT}</tt>.
* NOTE: Don't forget the space before the keyword 'limit'!
* @param start the number of rows to be skipped
* or zero, if no rows to be skipped.
* Is never negative.
* @param count the number of rows to be returned
* or {@link Query#UNLIMITED_COUNT} if all rows to be returned.
* Is always positive (greater zero).
*/
abstract void appendLimitClause(Statement bf, int start, int count);
/**
* Same as {@link #appendLimitClause(Statement, int, int}.
* Is used for {@link #LIMIT_SUPPORT_CLAUSES_AROUND} only,
* for the postfix.
*/
abstract void appendLimitClause2(Statement bf, int start, int count);
abstract void appendMatchClauseFullTextIndex(Statement bf, StringFunction function, String value);
/**
* Search full text.
*/
public final void appendMatchClause(final Statement bf, final StringFunction function, final String value)
{
if(fulltextIndex)
appendMatchClauseFullTextIndex(bf, function, value);
else
appendMatchClauseByLike(bf, function, value);
}
protected final void appendMatchClauseByLike(final Statement bf, final StringFunction function, final String value)
{
bf.append(function, (Join)null).
append(" like ").
appendParameter(function, '%'+value+'%');
}
private int countTable(final Connection connection, final Table table)
{
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger().
append(table.protectedID);
final CountResultSetHandler handler = new CountResultSetHandler();
executeSQLQuery(connection, bf, handler, false);
return handler.result;
}
private static class CountResultSetHandler implements ResultSetHandler
{
int result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
result = convertSQLResult(resultSet.getObject(1));
}
}
public final PkSource makePkSource(final Table table)
{
return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table);
}
public final int[] getMinMaxPK(final Connection connection, final Table table)
{
buildStage = false;
final Statement bf = createStatement();
final String primaryKeyProtectedID = table.primaryKey.protectedID;
bf.append("select min(").
append(primaryKeyProtectedID).defineColumnInteger().
append("),max(").
append(primaryKeyProtectedID).defineColumnInteger().
append(") from ").
append(table.protectedID);
final NextPKResultSetHandler handler = new NextPKResultSetHandler();
executeSQLQuery(connection, bf, handler, false);
return handler.result;
}
private static class NextPKResultSetHandler implements ResultSetHandler
{
int[] result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
final Object oLo = resultSet.getObject(1);
if(oLo!=null)
{
result = new int[2];
result[0] = convertSQLResult(oLo);
final Object oHi = resultSet.getObject(2);
result[1] = convertSQLResult(oHi);
}
}
}
public final Schema makeSchema()
{
final Schema result = new Schema(driver, connectionPool);
for(final Table t : tables)
t.makeSchema(result);
completeSchema(result);
return result;
}
protected void completeSchema(final Schema schema)
{
// empty default implementation
}
public final Schema makeVerifiedSchema()
{
final Schema result = makeSchema();
result.verify();
return result;
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
@Deprecated
protected static final void printMeta(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
@Deprecated
protected static final void printRow(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
@Deprecated
static final ResultSetHandler logHandler = new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
final int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("columnCount:"+columnCount);
final ResultSetMetaData meta = resultSet.getMetaData();
for(int i = 1; i<=columnCount; i++)
{
System.out.println(meta.getColumnName(i)+"|");
}
while(resultSet.next())
{
for(int i = 1; i<=columnCount; i++)
{
System.out.println(resultSet.getObject(i)+"|");
}
}
}
};
public boolean isDefiningColumnTypes()
{
return false;
}
public void defineColumnTypes(IntList columnTypes, java.sql.Statement statement)
throws SQLException
{
// default implementation does nothing, may be overwritten by subclasses
}
private static final DatabaseListener noopListener = new DatabaseListener()
{
public void load(Connection connection, PersistentState state)
{/* DOES NOTHING */}
public void search(Connection connection, Query query, boolean doCountOnly)
{/* DOES NOTHING */}
};
private DatabaseListener listener = noopListener;
private final Object listenerLock = new Object();
public DatabaseListener setListener(DatabaseListener listener)
{
if(listener==null)
listener = noopListener;
DatabaseListener result;
synchronized(listenerLock)
{
result = this.listener;
this.listener = listener;
}
if(result==noopListener)
result = null;
return result;
}
} |
package org.bouncycastle.math.ec;
import java.math.BigInteger;
/**
* Class holding methods for point multiplication based on the window
* τ-adic nonadjacent form (WTNAF). The algorithms are based on the
* paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves"
* by Jerome A. Solinas. The paper first appeared in the Proceedings of
* Crypto 1997.
*/
class Tnaf
{
private static final BigInteger MINUS_ONE = ECConstants.ONE.negate();
private static final BigInteger MINUS_TWO = ECConstants.TWO.negate();
private static final BigInteger MINUS_THREE = ECConstants.THREE.negate();
/**
* The window width of WTNAF. The standard value of 4 is slightly less
* than optimal for running time, but keeps space requirements for
* precomputation low. For typical curves, a value of 5 or 6 results in
* a better running time. When changing this value, the
* <code>α<sub>u</sub></code>'s must be computed differently, see
* e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson,
* Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004,
* p. 121-122
*/
public static final byte WIDTH = 4;
/**
* 2<sup>4</sup>
*/
public static final byte POW_2_WIDTH = 16;
/**
* The <code>α<sub>u</sub></code>'s for <code>a=0</code> as an array
* of <code>ZTauElement</code>s.
*/
public static final ZTauElement[] alpha0 = {
null,
new ZTauElement(ECConstants.ONE, ECConstants.ZERO), null,
new ZTauElement(MINUS_THREE, MINUS_ONE), null,
new ZTauElement(MINUS_ONE, MINUS_ONE), null,
new ZTauElement(ECConstants.ONE, MINUS_ONE), null
};
/**
* The <code>α<sub>u</sub></code>'s for <code>a=0</code> as an array
* of TNAFs.
*/
public static final byte[][] alpha0Tnaf = {
null, {1}, null, {-1, 0, 1}, null, {1, 0, 1}, null, {-1, 0, 0, 1}
};
/**
* The <code>α<sub>u</sub></code>'s for <code>a=1</code> as an array
* of <code>ZTauElement</code>s.
*/
public static final ZTauElement[] alpha1 = {null,
new ZTauElement(ECConstants.ONE, ECConstants.ZERO), null,
new ZTauElement(MINUS_THREE, ECConstants.ONE), null,
new ZTauElement(MINUS_ONE, ECConstants.ONE), null,
new ZTauElement(ECConstants.ONE, ECConstants.ONE), null
};
/**
* The <code>α<sub>u</sub></code>'s for <code>a=1</code> as an array
* of TNAFs.
*/
public static final byte[][] alpha1Tnaf = {
null, {1}, null, {-1, 0, 1}, null, {1, 0, 1}, null, {-1, 0, 0, -1}
};
/**
* Computes the norm of an element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @return The norm of <code>λ</code>.
*/
public static BigInteger norm(final byte mu, ZTauElement lambda)
{
BigInteger norm;
// s1 = u^2
BigInteger s1 = lambda.u.multiply(lambda.u);
// s2 = u * v
BigInteger s2 = lambda.u.multiply(lambda.v);
// s3 = 2 * v^2
BigInteger s3 = lambda.v.multiply(lambda.v).shiftLeft(1);
if (mu == 1)
{
norm = s1.add(s2).add(s3);
}
else if (mu == -1)
{
norm = s1.subtract(s2).add(s3);
}
else
{
throw new IllegalArgumentException("mu must be 1 or -1");
}
return norm;
}
/**
* Computes the norm of an element <code>λ</code> of
* <code><b>R</b>[τ]</code>, where <code>λ = u + vτ</code>
* and <code>u</code> and <code>u</code> are real numbers (elements of
* <code><b>R</b></code>).
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param u The real part of the element <code>λ</code> of
* <code><b>R</b>[τ]</code>.
* @param v The <code>τ</code>-adic part of the element
* <code>λ</code> of <code><b>R</b>[τ]</code>.
* @return The norm of <code>λ</code>.
*/
public static SimpleBigDecimal norm(final byte mu, SimpleBigDecimal u,
SimpleBigDecimal v)
{
SimpleBigDecimal norm;
// s1 = u^2
SimpleBigDecimal s1 = u.multiply(u);
// s2 = u * v
SimpleBigDecimal s2 = u.multiply(v);
// s3 = 2 * v^2
SimpleBigDecimal s3 = v.multiply(v).shiftLeft(1);
if (mu == 1)
{
norm = s1.add(s2).add(s3);
}
else if (mu == -1)
{
norm = s1.subtract(s2).add(s3);
}
else
{
throw new IllegalArgumentException("mu must be 1 or -1");
}
return norm;
}
public static ZTauElement round(SimpleBigDecimal lambda0,
SimpleBigDecimal lambda1, byte mu)
{
int scale = lambda0.getScale();
if (lambda1.getScale() != scale)
{
throw new IllegalArgumentException("lambda0 and lambda1 do not " +
"have same scale");
}
if (!((mu == 1) || (mu == -1)))
{
throw new IllegalArgumentException("mu must be 1 or -1");
}
BigInteger f0 = lambda0.round();
BigInteger f1 = lambda1.round();
SimpleBigDecimal eta0 = lambda0.subtract(f0);
SimpleBigDecimal eta1 = lambda1.subtract(f1);
// eta = 2*eta0 + mu*eta1
SimpleBigDecimal eta = eta0.add(eta0);
if (mu == 1)
{
eta = eta.add(eta1);
}
else
{
// mu == -1
eta = eta.subtract(eta1);
}
// check1 = eta0 - 3*mu*eta1
// check2 = eta0 + 4*mu*eta1
SimpleBigDecimal threeEta1 = eta1.add(eta1).add(eta1);
SimpleBigDecimal fourEta1 = threeEta1.add(eta1);
SimpleBigDecimal check1;
SimpleBigDecimal check2;
if (mu == 1)
{
check1 = eta0.subtract(threeEta1);
check2 = eta0.add(fourEta1);
}
else
{
// mu == -1
check1 = eta0.add(threeEta1);
check2 = eta0.subtract(fourEta1);
}
byte h0 = 0;
byte h1 = 0;
// if eta >= 1
if (eta.compareTo(ECConstants.ONE) >= 0)
{
if (check1.compareTo(MINUS_ONE) < 0)
{
h1 = mu;
}
else
{
h0 = 1;
}
}
else
{
// eta < 1
if (check2.compareTo(ECConstants.TWO) >= 0)
{
h1 = mu;
}
}
// if eta < -1
if (eta.compareTo(MINUS_ONE) < 0)
{
if (check1.compareTo(ECConstants.ONE) >= 0)
{
h1 = (byte)-mu;
}
else
{
h0 = -1;
}
}
else
{
// eta >= -1
if (check2.compareTo(MINUS_TWO) < 0)
{
h1 = (byte)-mu;
}
}
BigInteger q0 = f0.add(BigInteger.valueOf(h0));
BigInteger q1 = f1.add(BigInteger.valueOf(h1));
return new ZTauElement(q0, q1);
}
/**
* Approximate division by <code>n</code>. For an integer
* <code>k</code>, the value <code>λ = s k / n</code> is
* computed to <code>c</code> bits of accuracy.
* @param k The parameter <code>k</code>.
* @param s The curve parameter <code>s<sub>0</sub></code> or
* <code>s<sub>1</sub></code>.
* @param vm The Lucas Sequence element <code>V<sub>m</sub></code>.
* @param a The parameter <code>a</code> of the elliptic curve.
* @param m The bit length of the finite field
* <code><b>F</b><sub>m</sub></code>.
* @param c The number of bits of accuracy, i.e. the scale of the returned
* <code>SimpleBigDecimal</code>.
* @return The value <code>λ = s k / n</code> computed to
* <code>c</code> bits of accuracy.
*/
public static SimpleBigDecimal approximateDivisionByN(BigInteger k,
BigInteger s, BigInteger vm, byte a, int m, int c)
{
int _k = (m + 5)/2 + c;
BigInteger ns = k.shiftRight(m - _k - 2 + a);
BigInteger gs = s.multiply(ns);
BigInteger hs = gs.shiftRight(m);
BigInteger js = vm.multiply(hs);
BigInteger gsPlusJs = gs.add(js);
BigInteger ls = gsPlusJs.shiftRight(_k-c);
if (gsPlusJs.testBit(_k-c-1))
{
// round up
ls = ls.add(ECConstants.ONE);
}
return new SimpleBigDecimal(ls, c);
}
/**
* Computes the <code>τ</code>-adic NAF (non-adjacent form) of an
* element <code>λ</code> of <code><b>Z</b>[τ]</code>.
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @return The <code>τ</code>-adic NAF of <code>λ</code>.
*/
public static byte[] tauAdicNaf(byte mu, ZTauElement lambda)
{
if (!((mu == 1) || (mu == -1)))
{
throw new IllegalArgumentException("mu must be 1 or -1");
}
BigInteger norm = norm(mu, lambda);
// Ceiling of log2 of the norm
int log2Norm = norm.bitLength();
// If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52
int maxLength = log2Norm > 30 ? log2Norm + 4 : 34;
// The array holding the TNAF
byte[] u = new byte[maxLength];
int i = 0;
// The actual length of the TNAF
int length = 0;
BigInteger r0 = lambda.u;
BigInteger r1 = lambda.v;
while(!((r0.equals(ECConstants.ZERO)) && (r1.equals(ECConstants.ZERO))))
{
// If r0 is odd
if (r0.testBit(0))
{
u[i] = (byte) ECConstants.TWO.subtract((r0.subtract(r1.shiftLeft(1))).mod(ECConstants.FOUR)).intValue();
// r0 = r0 - u[i]
if (u[i] == 1)
{
r0 = r0.clearBit(0);
}
else
{
// u[i] == -1
r0 = r0.add(ECConstants.ONE);
}
length = i;
}
else
{
u[i] = 0;
}
BigInteger t = r0;
BigInteger s = r0.shiftRight(1);
if (mu == 1)
{
r0 = r1.add(s);
}
else
{
// mu == -1
r0 = r1.subtract(s);
}
r1 = t.shiftRight(1).negate();
i++;
}
length++;
// Reduce the TNAF array to its actual length
byte[] tnaf = new byte[length];
System.arraycopy(u, 0, tnaf, 0, length);
return tnaf;
}
/**
* Applies the operation <code>τ()</code> to an
* <code>ECPoint.F2m</code>.
* @param p The ECPoint.F2m to which <code>τ()</code> is applied.
* @return <code>τ(p)</code>
*/
public static ECPoint.F2m tau(ECPoint.F2m p)
{
if (p.isInfinity())
{
return p;
}
ECPoint pn = p.normalize();
ECFieldElement x = pn.getAffineXCoord();
ECFieldElement y = pn.getAffineYCoord();
return new ECPoint.F2m(p.getCurve(), x.square(), y.square(), p.isCompressed());
}
public static byte getMu(ECCurve.F2m curve)
{
if (!curve.isKoblitz())
{
throw new IllegalArgumentException("No Koblitz curve (ABC), TNAF multiplication not possible");
}
if (curve.getA().isZero())
{
return -1;
}
return 1;
}
/**
* Calculates the Lucas Sequence elements <code>U<sub>k-1</sub></code> and
* <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code> and
* <code>V<sub>k</sub></code>.
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param k The index of the second element of the Lucas Sequence to be
* returned.
* @param doV If set to true, computes <code>V<sub>k-1</sub></code> and
* <code>V<sub>k</sub></code>, otherwise <code>U<sub>k-1</sub></code> and
* <code>U<sub>k</sub></code>.
* @return An array with 2 elements, containing <code>U<sub>k-1</sub></code>
* and <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code>
* and <code>V<sub>k</sub></code>.
*/
public static BigInteger[] getLucas(byte mu, int k, boolean doV)
{
if (!((mu == 1) || (mu == -1)))
{
throw new IllegalArgumentException("mu must be 1 or -1");
}
BigInteger u0;
BigInteger u1;
BigInteger u2;
if (doV)
{
u0 = ECConstants.TWO;
u1 = BigInteger.valueOf(mu);
}
else
{
u0 = ECConstants.ZERO;
u1 = ECConstants.ONE;
}
for (int i = 1; i < k; i++)
{
// u2 = mu*u1 - 2*u0;
BigInteger s = null;
if (mu == 1)
{
s = u1;
}
else
{
// mu == -1
s = u1.negate();
}
u2 = s.subtract(u0.shiftLeft(1));
u0 = u1;
u1 = u2;
// System.out.println(i + ": " + u2);
// System.out.println();
}
BigInteger[] retVal = {u0, u1};
return retVal;
}
/**
* Computes the auxiliary value <code>t<sub>w</sub></code>. If the width is
* 4, then for <code>mu = 1</code>, <code>t<sub>w</sub> = 6</code> and for
* <code>mu = -1</code>, <code>t<sub>w</sub> = 10</code>
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param w The window width of the WTNAF.
* @return the auxiliary value <code>t<sub>w</sub></code>
*/
public static BigInteger getTw(byte mu, int w)
{
if (w == 4)
{
if (mu == 1)
{
return BigInteger.valueOf(6);
}
else
{
// mu == -1
return BigInteger.valueOf(10);
}
}
else
{
// For w <> 4, the values must be computed
BigInteger[] us = getLucas(mu, w, false);
BigInteger twoToW = ECConstants.ZERO.setBit(w);
BigInteger u1invert = us[1].modInverse(twoToW);
BigInteger tw;
tw = ECConstants.TWO.multiply(us[0]).multiply(u1invert).mod(twoToW);
// System.out.println("mu = " + mu);
// System.out.println("tw = " + tw);
return tw;
}
}
public static BigInteger[] getSi(ECCurve.F2m curve)
{
if (!curve.isKoblitz())
{
throw new IllegalArgumentException("si is defined for Koblitz curves only");
}
int m = curve.getM();
int a = curve.getA().toBigInteger().intValue();
byte mu = curve.getMu();
int h = curve.getH().intValue();
int index = m + 3 - a;
BigInteger[] ui = getLucas(mu, index, false);
BigInteger dividend0;
BigInteger dividend1;
if (mu == 1)
{
dividend0 = ECConstants.ONE.subtract(ui[1]);
dividend1 = ECConstants.ONE.subtract(ui[0]);
}
else if (mu == -1)
{
dividend0 = ECConstants.ONE.add(ui[1]);
dividend1 = ECConstants.ONE.add(ui[0]);
}
else
{
throw new IllegalArgumentException("mu must be 1 or -1");
}
BigInteger[] si = new BigInteger[2];
if (h == 2)
{
si[0] = dividend0.shiftRight(1);
si[1] = dividend1.shiftRight(1).negate();
}
else if (h == 4)
{
si[0] = dividend0.shiftRight(2);
si[1] = dividend1.shiftRight(2).negate();
}
else
{
throw new IllegalArgumentException("h (Cofactor) must be 2 or 4");
}
return si;
}
/**
* Partial modular reduction modulo
* <code>(τ<sup>m</sup> - 1)/(τ - 1)</code>.
* @param k The integer to be reduced.
* @param m The bitlength of the underlying finite field.
* @param a The parameter <code>a</code> of the elliptic curve.
* @param s The auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code>.
* @param mu The parameter μ of the elliptic curve.
* @param c The precision (number of bits of accuracy) of the partial
* modular reduction.
* @return <code>ρ := k partmod (τ<sup>m</sup> - 1)/(τ - 1)</code>
*/
public static ZTauElement partModReduction(BigInteger k, int m, byte a,
BigInteger[] s, byte mu, byte c)
{
// d0 = s[0] + mu*s[1]; mu is either 1 or -1
BigInteger d0;
if (mu == 1)
{
d0 = s[0].add(s[1]);
}
else
{
d0 = s[0].subtract(s[1]);
}
BigInteger[] v = getLucas(mu, m, true);
BigInteger vm = v[1];
SimpleBigDecimal lambda0 = approximateDivisionByN(
k, s[0], vm, a, m, c);
SimpleBigDecimal lambda1 = approximateDivisionByN(
k, s[1], vm, a, m, c);
ZTauElement q = round(lambda0, lambda1, mu);
// r0 = n - d0*q0 - 2*s1*q1
BigInteger r0 = k.subtract(d0.multiply(q.u)).subtract(
BigInteger.valueOf(2).multiply(s[1]).multiply(q.v));
// r1 = s1*q0 - s0*q1
BigInteger r1 = s[1].multiply(q.u).subtract(s[0].multiply(q.v));
return new ZTauElement(r0, r1);
}
/**
* Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m}
* by a <code>BigInteger</code> using the reduced <code>τ</code>-adic
* NAF (RTNAF) method.
* @param p The ECPoint.F2m to multiply.
* @param k The <code>BigInteger</code> by which to multiply <code>p</code>.
* @return <code>k * p</code>
*/
public static ECPoint.F2m multiplyRTnaf(ECPoint.F2m p, BigInteger k)
{
ECCurve.F2m curve = (ECCurve.F2m) p.getCurve();
int m = curve.getM();
byte a = (byte) curve.getA().toBigInteger().intValue();
byte mu = curve.getMu();
BigInteger[] s = curve.getSi();
ZTauElement rho = partModReduction(k, m, a, s, mu, (byte)10);
return multiplyTnaf(p, rho);
}
/**
* Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m}
* by an element <code>λ</code> of <code><b>Z</b>[τ]</code>
* using the <code>τ</code>-adic NAF (TNAF) method.
* @param p The ECPoint.F2m to multiply.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @return <code>λ * p</code>
*/
public static ECPoint.F2m multiplyTnaf(ECPoint.F2m p, ZTauElement lambda)
{
ECCurve.F2m curve = (ECCurve.F2m)p.getCurve();
byte mu = curve.getMu();
byte[] u = tauAdicNaf(mu, lambda);
ECPoint.F2m q = multiplyFromTnaf(p, u);
return q;
}
/**
* Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m}
* by an element <code>λ</code> of <code><b>Z</b>[τ]</code>
* using the <code>τ</code>-adic NAF (TNAF) method, given the TNAF
* of <code>λ</code>.
* @param p The ECPoint.F2m to multiply.
* @param u The the TNAF of <code>λ</code>..
* @return <code>λ * p</code>
*/
public static ECPoint.F2m multiplyFromTnaf(ECPoint.F2m p, byte[] u)
{
ECCurve.F2m curve = (ECCurve.F2m)p.getCurve();
ECPoint.F2m q = (ECPoint.F2m) curve.getInfinity();
for (int i = u.length - 1; i >= 0; i
{
q = tau(q);
if (u[i] == 1)
{
q = (ECPoint.F2m)q.addSimple(p);
}
else if (u[i] == -1)
{
q = (ECPoint.F2m)q.subtractSimple(p);
}
}
return q;
}
/**
* Computes the <code>[τ]</code>-adic window NAF of an element
* <code>λ</code> of <code><b>Z</b>[τ]</code>.
* @param mu The parameter μ of the elliptic curve.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code> of which to compute the
* <code>[τ]</code>-adic NAF.
* @param width The window width of the resulting WNAF.
* @param pow2w 2<sup>width</sup>.
* @param tw The auxiliary value <code>t<sub>w</sub></code>.
* @param alpha The <code>α<sub>u</sub></code>'s for the window width.
* @return The <code>[τ]</code>-adic window NAF of
* <code>λ</code>.
*/
public static byte[] tauAdicWNaf(byte mu, ZTauElement lambda,
byte width, BigInteger pow2w, BigInteger tw, ZTauElement[] alpha)
{
if (!((mu == 1) || (mu == -1)))
{
throw new IllegalArgumentException("mu must be 1 or -1");
}
BigInteger norm = norm(mu, lambda);
// Ceiling of log2 of the norm
int log2Norm = norm.bitLength();
// If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52
int maxLength = log2Norm > 30 ? log2Norm + 4 + width : 34 + width;
// The array holding the TNAF
byte[] u = new byte[maxLength];
// 2^(width - 1)
BigInteger pow2wMin1 = pow2w.shiftRight(1);
// Split lambda into two BigIntegers to simplify calculations
BigInteger r0 = lambda.u;
BigInteger r1 = lambda.v;
int i = 0;
// while lambda <> (0, 0)
while (!((r0.equals(ECConstants.ZERO))&&(r1.equals(ECConstants.ZERO))))
{
// if r0 is odd
if (r0.testBit(0))
{
// uUnMod = r0 + r1*tw mod 2^width
BigInteger uUnMod
= r0.add(r1.multiply(tw)).mod(pow2w);
byte uLocal;
// if uUnMod >= 2^(width - 1)
if (uUnMod.compareTo(pow2wMin1) >= 0)
{
uLocal = (byte) uUnMod.subtract(pow2w).intValue();
}
else
{
uLocal = (byte) uUnMod.intValue();
}
// uLocal is now in [-2^(width-1), 2^(width-1)-1]
u[i] = uLocal;
boolean s = true;
if (uLocal < 0)
{
s = false;
uLocal = (byte)-uLocal;
}
// uLocal is now >= 0
if (s)
{
r0 = r0.subtract(alpha[uLocal].u);
r1 = r1.subtract(alpha[uLocal].v);
}
else
{
r0 = r0.add(alpha[uLocal].u);
r1 = r1.add(alpha[uLocal].v);
}
}
else
{
u[i] = 0;
}
BigInteger t = r0;
if (mu == 1)
{
r0 = r1.add(r0.shiftRight(1));
}
else
{
// mu == -1
r0 = r1.subtract(r0.shiftRight(1));
}
r1 = t.shiftRight(1).negate();
i++;
}
return u;
}
/**
* Does the precomputation for WTNAF multiplication.
* @param p The <code>ECPoint</code> for which to do the precomputation.
* @param a The parameter <code>a</code> of the elliptic curve.
* @return The precomputation array for <code>p</code>.
*/
public static ECPoint.F2m[] getPreComp(ECPoint.F2m p, byte a)
{
ECPoint.F2m[] pu;
pu = new ECPoint.F2m[16];
pu[1] = p;
byte[][] alphaTnaf;
if (a == 0)
{
alphaTnaf = Tnaf.alpha0Tnaf;
}
else
{
// a == 1
alphaTnaf = Tnaf.alpha1Tnaf;
}
int precompLen = alphaTnaf.length;
for (int i = 3; i < precompLen; i = i + 2)
{
pu[i] = Tnaf.multiplyFromTnaf(p, alphaTnaf[i]);
}
p.getCurve().normalizeAll(pu);
return pu;
}
} |
package ljdp.minechem.common.recipe;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ljdp.minechem.api.core.Chemical;
import ljdp.minechem.api.core.Element;
import ljdp.minechem.api.core.EnumElement;
import ljdp.minechem.api.core.EnumMolecule;
import ljdp.minechem.api.core.Molecule;
import ljdp.minechem.api.recipe.DecomposerRecipe;
import ljdp.minechem.api.recipe.DecomposerRecipeChance;
import ljdp.minechem.api.recipe.DecomposerRecipeSelect;
import ljdp.minechem.api.recipe.SynthesisRecipe;
import ljdp.minechem.api.util.Util;
import ljdp.minechem.common.MinechemBlocks;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.blueprint.MinechemBlueprint;
import ljdp.minechem.common.items.ItemBlueprint;
import ljdp.minechem.common.items.ItemElement;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.Loader;
public class MinechemRecipes {
private static final MinechemRecipes instance = new MinechemRecipes();
public ArrayList unbondingRecipes = new ArrayList();
public ArrayList synthesisRecipes = new ArrayList();
private SynthesisRecipe recipeIron;
private SynthesisRecipe recipeGold;
private SynthesisRecipe recipeCoalChunk;
public static MinechemRecipes getInstance() {
return instance;
}
public void RegisterRecipes() {
ItemStack var1 = new ItemStack(Block.stone);
new ItemStack(Block.cobblestone);
ItemStack var3 = new ItemStack(Block.dirt);
ItemStack var4 = new ItemStack(Block.sand);
ItemStack var5 = new ItemStack(Block.gravel);
ItemStack var6 = new ItemStack(Block.glass);
ItemStack var7 = new ItemStack(Block.thinGlass);
ItemStack oreIron = new ItemStack(Block.oreIron);
ItemStack oreGold = new ItemStack(Block.oreGold);
ItemStack var10 = new ItemStack(Block.oreDiamond);
ItemStack var11 = new ItemStack(Block.oreEmerald);
ItemStack oreCoal = new ItemStack(Block.oreCoal);
ItemStack var13 = new ItemStack(Block.oreRedstone);
ItemStack var14 = new ItemStack(Block.oreLapis);
ItemStack ingotIron = new ItemStack(Item.ingotIron);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator);
ItemStack var18 = new ItemStack(Item.redstone);
ItemStack var19 = new ItemStack(MinechemItems.testTube, 16);
ItemStack paper = new ItemStack(Item.paper);
ItemStack bdye = new ItemStack(Item.dyePowder, 1, 6);
GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
// GameRegistry.addRecipe(new ItemStack(MinechemItems.blueprint, 1, 1), new Object[] { "ZZZ", "SSS", "ZZZ", Character.valueOf('Z'), paper, Character.valueOf('S'), bdye });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.EmptyPillz,4), new Object[] { new ItemStack(Item.sugar), new ItemStack(Item.slimeBall), new ItemStack(Item.slimeBall) });
//Fusion
GameRegistry.addShapelessRecipe(ItemBlueprint.createItemStackFromBlueprint(MinechemBlueprint.fusion), new Object[] { new ItemStack(Item.paper), new ItemStack(Block.blockDiamond)});
//Fission
GameRegistry.addShapelessRecipe(ItemBlueprint.createItemStackFromBlueprint(MinechemBlueprint.fission), new Object[] { new ItemStack(Item.paper), new ItemStack(Item.diamond)});
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
Element var21 = this.element(EnumElement.C, 64);
// DecomposerRecipe.add(new DecomposerRecipe(var8, new
// Chemical[]{this.element(EnumElement.Fe, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(MinechemBlocks.uranium), new Chemical[] { this.element(EnumElement.U, 32) }));
// DecomposerRecipe.add(new DecomposerRecipe(var9, new
// Chemical[]{this.element(EnumElement.Au, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) }));
ItemStack ingotGold = new ItemStack(Item.ingotGold);
ItemStack var23 = new ItemStack(Item.diamond);
ItemStack var24 = new ItemStack(Item.emerald);
ItemStack chunkCoal = new ItemStack(Item.coal);
ItemStack fusionblue = new ItemStack(MinechemItems.blueprint, 1, MinechemBlueprint.fusion.id);
ItemStack fusionBlock1 = new ItemStack(MinechemBlocks.fusion, 0);
ItemStack fusionBlock2 = new ItemStack(MinechemBlocks.fusion, 1);
// DecomposerRecipe.add(new DecomposerRecipe(var15, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
//SynthesisRecipe.add(new SynthesisRecipe(ingotIron, true, 200, new Chemical[] { this.element(EnumElement.Fe, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Item.ingotIron), new Chemical[] { this.element(EnumElement.Fe, 16) }));
// DecomposerRecipe.add(new DecomposerRecipe(var22, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Item.ingotGold), new Chemical[] { this.element(EnumElement.Au, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) }));
// DecomposerRecipe.add(new DecomposerRecipe(var25, new
// Chemical[]{this.element(EnumElement.C, 8)}));
DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) }));
// SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add( new SynthesisRecipe(new ItemStack(Item.ingotIron), false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.ingotGold), false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null }));
SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockSteel), new
// Chemical[]{this.element(EnumElement.Fe, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockGold), new
// Chemical[]{this.element(EnumElement.Au, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) }));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockSteel), true, 5000, new
// Chemical[]{this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockGold), true, 5000, new
// Chemical[]{this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) }));
ItemStack var26 = new ItemStack(Block.sandStone);
ItemStack var27 = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4);
Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4);
SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) }));
ItemStack var30 = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) }));
ItemStack var31 = new ItemStack(Item.arrow);
ItemStack var32 = new ItemStack(Item.paper);
ItemStack var33 = new ItemStack(Item.leather);
ItemStack var34 = new ItemStack(Item.snowball);
ItemStack var35 = new ItemStack(Item.brick);
ItemStack var36 = new ItemStack(Item.clay);
ItemStack var37 = new ItemStack(Block.mycelium);
ItemStack var38 = new ItemStack(Block.sapling, 1, -1);
DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null }));
ItemStack var39 = new ItemStack(Item.slimeBall);
ItemStack var40 = new ItemStack(Item.blazeRod);
ItemStack var41 = new ItemStack(Item.blazePowder);
ItemStack var42 = new ItemStack(Item.magmaCream);
ItemStack var43 = new ItemStack(Item.ghastTear);
ItemStack var44 = new ItemStack(Item.netherStar);
ItemStack var45 = new ItemStack(Item.spiderEye);
ItemStack var46 = new ItemStack(Item.fermentedSpiderEye);
ItemStack var47 = new ItemStack(Item.netherStalkSeeds);
ItemStack var48 = new ItemStack(Block.glowStone);
ItemStack var49 = new ItemStack(Item.glowstone);
ItemStack var50 = new ItemStack(Item.potion, 1, 0);
ItemStack var51 = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) }));
DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) }));
DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) }));
Element var52 = this.element(EnumElement.H, 64);
Element var53 = this.element(EnumElement.He, 64);
DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 }));
DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) }));
DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) }));
DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) }));
DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null }));
SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null }));
SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 }));
SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null }));
ItemStack var54 = new ItemStack(Item.sugar);
ItemStack var55 = new ItemStack(Item.reed);
ItemStack var56 = new ItemStack(Block.pumpkin);
ItemStack var57 = new ItemStack(Block.melon);
ItemStack var58 = new ItemStack(Item.speckledMelon);
ItemStack var59 = new ItemStack(Item.melon);
ItemStack var60 = new ItemStack(Item.carrot);
ItemStack var61 = new ItemStack(Item.goldenCarrot);
ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3);
ItemStack var63 = new ItemStack(Item.potato);
ItemStack var64 = new ItemStack(Item.bread);
ItemStack var65 = new ItemStack(Item.appleRed);
ItemStack var66 = new ItemStack(Item.appleGold, 1, 0);
ItemStack var68 = new ItemStack(Item.chickenCooked);
// Seriously what is with the obfuscated variable names?
DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var62, 0.4F, new Chemical[] { this.molecule(EnumMolecule.theobromine), this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) }));
DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipe(var60, new Chemical[] { this.molecule(EnumMolecule.ret) }));
DecomposerRecipe.add(new DecomposerRecipe(var61, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
// DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64)}));
DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
ItemStack var69 = new ItemStack(Item.gunpowder);
ItemStack var70 = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) }));
DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null }));
ItemStack var71 = new ItemStack(Block.wood, 1, -1);
ItemStack var72 = new ItemStack(Block.planks, 1, -1);
ItemStack var140 = new ItemStack(Block.planks, 1, 0);
ItemStack var141 = new ItemStack(Block.planks, 1, 1);
ItemStack var142 = new ItemStack(Block.planks, 1, 2);
ItemStack var143 = new ItemStack(Block.planks, 1, 3);
ItemStack var73 = new ItemStack(Item.stick);
ItemStack var74 = new ItemStack(Block.wood, 1, 0);
ItemStack var75 = new ItemStack(Block.wood, 1, 1);
ItemStack var76 = new ItemStack(Block.wood, 1, 2);
ItemStack var77 = new ItemStack(Block.wood, 1, 3);
ItemStack var78 = new ItemStack(Item.doorWood);
ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1);
DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) }));
Molecule var81 = this.molecule(EnumMolecule.cellulose, 1);
SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null }));
ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0);
ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1);
ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2);
ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4);
ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5);
ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6);
ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7);
ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8);
ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9);
ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10);
ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11);
ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12);
ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13);
ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14);
ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
ItemStack var97 = new ItemStack(Block.cloth, 1, 0);
ItemStack var98 = new ItemStack(Block.cloth, 1, 1);
ItemStack var99 = new ItemStack(Block.cloth, 1, 2);
ItemStack var100 = new ItemStack(Block.cloth, 1, 3);
ItemStack var101 = new ItemStack(Block.cloth, 1, 4);
ItemStack var102 = new ItemStack(Block.cloth, 1, 5);
ItemStack var103 = new ItemStack(Block.cloth, 1, 6);
ItemStack var104 = new ItemStack(Block.cloth, 1, 7);
ItemStack var105 = new ItemStack(Block.cloth, 1, 8);
ItemStack var106 = new ItemStack(Block.cloth, 1, 9);
ItemStack var107 = new ItemStack(Block.cloth, 1, 10);
ItemStack var108 = new ItemStack(Block.cloth, 1, 11);
ItemStack var109 = new ItemStack(Block.cloth, 1, 12);
ItemStack var110 = new ItemStack(Block.cloth, 1, 13);
ItemStack var111 = new ItemStack(Block.cloth, 1, 14);
ItemStack var112 = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var109, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.tannicacid) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride);
// Music Records
ItemStack itemRecord13 = new ItemStack(Item.record13);
ItemStack itemRecordCat = new ItemStack(Item.recordCat);
ItemStack itemRecordFar = new ItemStack(Item.recordFar);
ItemStack itemRecordMall = new ItemStack(Item.recordMall);
ItemStack itemRecordMellohi = new ItemStack(Item.recordMellohi);
ItemStack itemRecordStal = new ItemStack(Item.recordStal);
ItemStack itemRecordStrad = new ItemStack(Item.recordStrad);
ItemStack itemRecordWard = new ItemStack(Item.recordWard);
ItemStack itemRecordChirp = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(itemRecord13, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordCat, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordFar, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMall, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordMellohi, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStal, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordStrad, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordWard, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(itemRecordChirp, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecord13, true, 1000, new Chemical[] { var113, null, null, null, null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordCat, true, 1000, new Chemical[] { null, var113, null, null, null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordFar, true, 1000, new Chemical[] { null, null, var113, null, null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMall, true, 1000, new Chemical[] { null, null, null, var113, null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordMellohi, true, 1000, new Chemical[] { null, null, null, null, var113, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStal, true, 1000, new Chemical[] { null, null, null, null, null, var113, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordStrad, true, 1000, new Chemical[] { null, null, null, null, null, null, var113, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordWard, true, 1000, new Chemical[] { null, null, null, null, null, null, null, var113, null }));
SynthesisRecipe.add(new SynthesisRecipe(itemRecordChirp, true, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 }));
ItemStack var123 = new ItemStack(Block.mushroomBrown);
ItemStack var124 = new ItemStack(Block.mushroomRed);
ItemStack var125 = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.element(EnumElement.Cu, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.element(EnumElement.Cu) }));
SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.element(EnumElement.Cu), null, null, null, null }));
ItemStack var126 = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) }));
ItemStack var127 = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) }));
ItemStack var128 = new ItemStack(Item.bone);
ItemStack var129 = new ItemStack(Item.silk);
// new ItemStack(Block.cloth, 1, -1);
// new ItemStack(Block.cloth, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
ItemStack var132 = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) }));
ItemStack var133 = new ItemStack(Block.netherrack);
ItemStack var134 = new ItemStack(Block.slowSand);
ItemStack var135 = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
ItemStack var136 = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
ItemStack var137 = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
ItemStack netherQ = new ItemStack(Item.netherQuartz);
DecomposerRecipe.add(new DecomposerRecipe(netherQ, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.galliumarsenide, 1) }));
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
this.registerPoisonRecipes(EnumMolecule.radchlor); // "Whoa, oh, oh, oh, oh, whoa, oh, oh, oh, I'm radioactive, radioactive" - "Radioactive" By Imagine Dragons.
this.registerPoisonRecipes(EnumMolecule.redrocks);
this.registerPoisonRecipes(EnumMolecule.coke);
this.registerPoisonRecipes(EnumMolecule.theobromine);
}
private void addDecomposerRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
Chemical[] var6 = (Chemical[]) var5.toArray(new Chemical[var5.size()]);
ItemStack var7 = new ItemStack(MinechemItems.molecule, 1, var4.id());
DecomposerRecipe.add(new DecomposerRecipe(var7, var6));
}
}
private void addSynthesisRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
ItemStack var6 = new ItemStack(MinechemItems.molecule, 1, var4.id());
SynthesisRecipe.add(new SynthesisRecipe(var6, false, 50, var5));
}
}
private void addUnusedSynthesisRecipes() {
Iterator var1 = DecomposerRecipe.recipes.iterator();
while (var1.hasNext()) {
DecomposerRecipe var2 = (DecomposerRecipe) var1.next();
if (var2.getInput().getItemDamage() != -1) {
boolean var3 = false;
Iterator var4 = SynthesisRecipe.recipes.iterator();
//What kind of crappy code is this?
//I've got to fix it.....If I can figure out what it does
while (true) {
if (var4.hasNext()) {
SynthesisRecipe var5 = (SynthesisRecipe) var4.next();
if (!Util.stacksAreSameKind(var5.getOutput(), var2.getInput())) {
continue;
}
var3 = true;
}
if (!var3) {
ArrayList var6 = var2.getOutputRaw();
if (var6 != null) {
SynthesisRecipe.add(new SynthesisRecipe(var2.getInput(), false, 100, var6));
}
}
break;
}
}
}
}
private ItemStack createPoisonedItemStack(Item var1, int var2, EnumMolecule var3) {
ItemStack var4 = new ItemStack(MinechemItems.molecule, 1, var3.id());
ItemStack var5 = new ItemStack(var1, 1, var2);
ItemStack var6 = new ItemStack(var1, 1, var2);
NBTTagCompound var7 = new NBTTagCompound();
var7.setBoolean("minechem.isPoisoned", true);
var7.setInteger("minechem.effectType", var3.id());
var6.setTagCompound(var7);
GameRegistry.addShapelessRecipe(var6, new Object[]{var4, var5});
return var6;
}
private void registerPoisonRecipes(EnumMolecule var1) {
this.createPoisonedItemStack(Item.appleRed, 0, var1);
this.createPoisonedItemStack(Item.porkCooked, 0, var1);
this.createPoisonedItemStack(Item.beefCooked, 0, var1);
this.createPoisonedItemStack(Item.carrot, 0, var1);
this.createPoisonedItemStack(Item.poisonousPotato, 0, var1);
this.createPoisonedItemStack(Item.bakedPotato, 0, var1);
this.createPoisonedItemStack(Item.bread, 0, var1);
this.createPoisonedItemStack(Item.potato, 0, var1);
this.createPoisonedItemStack(Item.bucketMilk, 0, var1);
this.createPoisonedItemStack(Item.fishCooked, 0, var1);
this.createPoisonedItemStack(Item.cookie, 0, var1);
this.createPoisonedItemStack(Item.pumpkinPie, 0, var1);
this.createPoisonedItemStack(Item.fishRaw, 0, var1);
this.createPoisonedItemStack(Item.appleGold, 0, var1);
this.createPoisonedItemStack(MinechemItems.EmptyPillz, 0, var1);
}
String[] compounds = {"Aluminium","Titanium","Chrome",
"Tungsten", "Lead", "Zinc",
"Platinum", "Nickel", "Osmium",
"Iron", "Gold", "Coal",
"Copper", "Tin", "Silver",
"RefinedIron",
"Steel",
"Bronze", "Brass", "Electrum",
"Invar"};//,"Iridium"};
EnumElement[][] elements = {{EnumElement.Al}, {EnumElement.Ti}, {EnumElement.Cr},
{EnumElement.W}, {EnumElement.Pb}, {EnumElement.Zn},
{EnumElement.Pt}, {EnumElement.Ni}, {EnumElement.Os},
{EnumElement.Fe}, {EnumElement.Au}, {EnumElement.C},
{EnumElement.Cu}, {EnumElement.Sn}, {EnumElement.Ag},
{EnumElement.Fe},
{EnumElement.Fe, EnumElement.C}, //Steel
{EnumElement.Sn, EnumElement.Cu},
{EnumElement.Cu},//Bronze
{EnumElement.Zn, EnumElement.Cu}, //Brass
{EnumElement.Ag, EnumElement.Au}, //Electrum
{EnumElement.Fe, EnumElement.Ni} //Invar
};//, EnumElement.Ir
int[][] proportions = {{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},
{4,4},
{1,3},{1,3},{2,2},{2,1}};
String[] itemTypes = {"dustSmall", "dust", "ore" , "ingot", "block", "gear", "plate"}; //"nugget", "plate"
boolean[] craftable = {true, true, false, false, false, false, false};
int[] sizeCoeff = {1, 4, 8, 4, 36, 16, 4};
@ForgeSubscribe
public void oreEvent(OreDictionary.OreRegisterEvent var1) { // THIS IS A FUCKING MESS BUT IT WILL WORK FOR NOW!!!!!! NO IT REALLU DOESNT
System.out.println(var1.Name);
// BEGIN ORE DICTONARY BULLSHIT
if(var1.Name.contains("oreUranium")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 32)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 32)}));
} else if(var1.Name.contains("ingotUranium")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 8)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)}));
} else if(var1.Name.contains("itemDropUranium")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 8)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)}));
} else if(var1.Name.contains("gemApatite")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)}));
// } else if(var1.Name.contains("Iridium")) {
// DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ir, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ir, 2)}));
} else if(var1.Name.contains("Ruby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
} else if(var1.Name.contains("Sapphire")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)}));
}else if(var1.Name.contains("ingotCopper")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 16)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Fe, 16)}));
}
else if(var1.Name.contains("ingotTin")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Sn, 16)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Sn, 16)}));
}
else if(var1.Name.contains("ingotOsmium")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Os, 16)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Os, 16)}));
}
else if(var1.Name.contains("ingotBronze")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Cu, 16),this.element(EnumElement.Sn, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Cu, 16),this.element(EnumElement.Sn, 2)}));
}
else if(var1.Name.contains("plateSilicon")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Si, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Si, 2)}));
} else if(var1.Name.contains("xychoriumBlue")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)}));
} else if(var1.Name.contains("xychoriumRed")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)}));
} else if(var1.Name.contains("xychoriumGreen")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)}));
} else if(var1.Name.contains("xychoriumDark")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)}));
} else if(var1.Name.contains("xychoriumLight")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)}));
} else if(var1.Name.contains("ingotCobalt")) { // Tungsten - Cobalt Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)}));
} else if(var1.Name.contains("ingotArdite")) { // Tungsten - Iron - Silicon Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)}));
} else if(var1.Name.contains("ingotManyullyn")) { // Tungsten - Iron - Silicon - Cobalt Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 7000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)}));
}
else if(var1.Name.contains("gemRuby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
}
else if(var1.Name.contains("gemSapphire")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide)}));
}
else if(var1.Name.contains("gemPeridot")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.olivine)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.olivine)}));
}
else if(var1.Name.contains("cropMaloberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose)}));
}
else if(var1.Name.contains("cropDuskberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2)}));
}
else if(var1.Name.contains("cropSkyberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2)}));
}
else if(var1.Name.contains("cropBlightberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.asprin), this.element(EnumElement.S, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.asprin), this.element(EnumElement.S, 2)}));
}
else if(var1.Name.contains("cropBlueberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
}
else if(var1.Name.contains("cropRaspberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
}
else if(var1.Name.contains("cropBlackberry")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2)}));
}
// cropStingberry
}
// END
// BEGIN MISC FUNCTIONS
private Element element(EnumElement var1, int var2) {
return new Element(var1, var2);
}
private Element element(EnumElement var1) {
return new Element(var1, 1);
}
private Molecule molecule(EnumMolecule var1, int var2) {
return new Molecule(var1, var2);
}
private Molecule molecule(EnumMolecule var1) {
return new Molecule(var1, 1);
}
// END
} // EOF |
// AppServer.java
package ed.appserver;
import java.io.*;
import java.util.*;
import ed.js.*;
import ed.js.engine.*;
import ed.net.*;
import ed.util.*;
import ed.net.httpserver.*;
import ed.appserver.jxp.*;
public class AppServer implements HttpHandler {
private static final int DEFAULT_PORT = 8080;
static boolean D = Boolean.getBoolean( "DEBUG.APP" );
static String OUR_DOMAINS[] = new String[]{ ".latenightcoders.com" , ".10gen.com" };
static String CDN_HOST[] = new String[]{ "origin." , "origin-local." , "static." , "static-local." , "secure." };
public AppServer( String defaultWebRoot , String root ){
_defaultWebRoot = defaultWebRoot;
_root = root;
_rootFile = _root == null ? null : new File( _root );
}
AppContext getContext( String host , String uri , String newUri[] ){
if ( newUri != null )
newUri[0] = null;
if ( host != null )
host = host.trim();
if ( host == null || _root == null || host.length() == 0 ){
if ( D ) System.out.println( " using default context for [" + host + "]" );
return _getDefaultContext();
}
AppContext ac = _getContextFromMap( host );
if ( ac != null )
return ac;
{
int colon = host.indexOf( ":" );
if ( colon > 0 )
host = host.substring( 0 , colon );
}
// raw {admin.latenightcoders.com}
File temp = new File( _root , host );
if ( temp.exists() )
return getFinalContext( temp , host , host );
// check for virtual hosting under us
// foo.latenightcoders.com -> foo.com
String useHost = host;
for ( String d : OUR_DOMAINS ){
if ( useHost.endsWith( d ) ){
useHost = useHost.substring( 0 , useHost.length() - d.length() ) + ".com";
break;
}
}
if ( useHost.startsWith( "www." ) )
useHost = useHost.substring( 4 );
if ( uri != null && uri.length() > 0 && uri.indexOf( "/" , 1 ) > 0 ){
for ( String d : CDN_HOST ){
if ( useHost.startsWith( d ) ){
String thing = uri.substring(1);
int idx = thing.indexOf( "/" );
String newUriNow = thing.substring( idx );
thing = thing.substring( 0 , thing.indexOf( "/" ) );
if ( newUri != null )
newUri[0] = newUriNow;
return getContext( thing , newUriNow , null );
}
}
}
if ( useHost.equals( "corejs.com" ) ){
return _coreContext;
}
if ( D ) System.out.println( "useHost : " + useHost );
// check for full host
temp = new File( _root , useHost );
if ( temp.exists() )
return getFinalContext( temp , host , useHost );
String domain = useHost.indexOf(".") >= 0 ? DNSUtil.getDomain( useHost ) : useHost;
temp = new File( _rootFile , domain );
if ( temp.exists() )
return getFinalContext( temp , host , useHost );
int idx = domain.indexOf( "." );
if ( idx > 0 ){
temp = new File( _rootFile , domain.substring( 0 , idx ) );
if ( temp.exists() )
return getFinalContext( temp , host , useHost );
}
return _getDefaultContext();
}
AppContext getFinalContext( File f , String host , String useHost ){
if ( ! f.exists() )
throw new RuntimeException( "trying to map to " + f + " which doesn't exist" );
AppContext ac = _getContextFromMap( host );
if ( ac != null )
return ac;
ac = _getContextFromMap( f.toString() );
if ( ac != null )
return ac;
if ( D ) System.out.println( "mapping directory [" + host + "] to " + f );
if ( ! hasGit( f ) ){
if ( D ) System.out.println( "\t this is a holder for branches" );
f = getBranch( f , DNSUtil.getSubdomain( useHost ) );
if ( D ) System.out.println( "\t using full path : " + f );
}
ac = new AppContext( f );
_context.put( host , ac );
_context.put( f.toString() , ac );
return ac;
}
private boolean hasGit( File test ){
File f = new File( test , ".git" );
if ( f.exists() )
return true;
f = new File( test , "dot-git" );
if ( f.exists() )
return true;
return false;
}
private static final String LOCAL_BRANCH_LIST[] = new String[]{ "master" , "test" , "www" };
private static final String WWW_BRANCH_LIST[] = new String[]{ "test" , "master" };
File getBranch( File root , String subdomain ){
File test = new File( root , subdomain );
if ( test.exists() )
return test;
if ( subdomain.equals( "dev" ) ){
test = new File( root , "master" );
if ( test.exists() )
return test;
}
String searchList[] = null;
if ( subdomain.equals( "local" ) )
searchList = LOCAL_BRANCH_LIST;
else if ( subdomain.equals( "www" ) )
searchList = WWW_BRANCH_LIST;
if ( searchList != null ){
for ( int i=0; i<searchList.length; i++ ){
test = new File( root , searchList[i] );
if ( test.exists() )
return test;
}
}
throw new RuntimeException( "can't find branch for subdomain : " + subdomain );
}
public AppContext getContext( HttpRequest request , String newUri[] ){
return getContext( request.getHeader( "Host" ) , request.getURI() , newUri );
}
public AppRequest createRequest( HttpRequest request ){
String newUri[] = new String[1];
AppContext ac = getContext( request , newUri );
return ac.createRequest( request , newUri[0] );
}
public boolean handles( HttpRequest request , Box<Boolean> fork ){
String uri = request.getURI();
if ( ! uri.startsWith( "/" ) )
return false;
AppRequest ar = createRequest( request );
request.setAttachment( ar );
fork.set( ar.fork() );
return true;
}
public void handle( HttpRequest request , HttpResponse response ){
try {
_handle( request , response );
}
catch ( Exception e ){
handleError( request , response , e , null );
}
}
private void _handle( HttpRequest request , HttpResponse response ){
final long start = System.currentTimeMillis();
AppRequest ar = (AppRequest)request.getAttachment();
if ( ar == null )
ar = createRequest( request );
ar.getScope().makeThreadLocal();
ar.getContext()._usage.hit( "bytes_in" , request.totalSize() );
ar.getContext()._usage.hit( "requests" , 1 );
ar.setResponse( response );
ar.getContext().getScope().setTLPreferred( ar.getScope() );
response.setAppRequest( ar );
try {
_handle( request , response , ar );
}
finally {
final long t = System.currentTimeMillis() - start;
if ( t > 1500 )
ar.getContext()._logger.getChild( "slow" ).info( request.getURL() + " " + t + "ms" );
ar.getContext().getScope().setTLPreferred( null );
ar.getContext()._usage.hit( "cpu_millis" , t );
ar.getContext()._usage.hit( "bytes_out" , response.totalSize() );
Scope.clearThreadLocal();
}
}
private void _handle( HttpRequest request , HttpResponse response , AppRequest ar ){
JSString jsURI = new JSString( ar.getURI() );
if ( ar.getScope().get( "allowed" ) != null ){
Object foo = ar.getScope().getFunction( "allowed" ).call( ar.getScope() , request , response , jsURI );
if ( foo != null ){
if ( response.getResponseCode() == 200 ){
response.setResponseCode( 401 );
response.getWriter().print( "not allowed" );
}
return;
}
}
if ( ar.getURI().equals( "/~f" ) ){
JSFile f = ar.getContext().getJSFile( request.getParameter( "id" ) );
if ( f == null ){
response.setResponseCode( 404 );
response.getWriter().print( "not found\n\n" );
return;
}
response.sendFile( f );
return;
}
File f = ar.getFile();
if ( response.getResponseCode() >= 300 )
return;
if ( f.toString().endsWith( ".cgi" ) ){
handleCGI( request , response , ar , f );
return;
}
if ( ar.isStatic() && f.exists() ){
if ( D ) System.out.println( f );
if ( f.isDirectory() ){
response.setResponseCode( 301 );
response.getWriter().print( "listing not allowed\n" );
return;
}
int cacheTime = getCacheTime( ar , jsURI , request , response );
if ( cacheTime >= 0 )
response.setCacheTime( cacheTime );
final String fileString = f.toString();
int idx = fileString.lastIndexOf( "." );
if ( idx > 0 ){
String ext = fileString.substring( idx + 1 );
String type = MimeTypes.get( ext );
if ( type != null )
response.setHeader( "Content-Type" , type );
}
response.sendFile( f );
return;
}
try {
JxpServlet servlet = ar.getContext().getServlet( f );
if ( servlet == null ){
response.setResponseCode( 404 );
response.getWriter().print( "not found" );
}
else {
servlet.handle( request , response , ar );
}
}
catch ( JSException.Quiet q ){
response.setHeader( "X-Exception" , "quiet" );
}
catch ( JSException.Redirect r ){
response.sendRedirectTemporary(r.getTarget());
}
catch ( Exception e ){
handleError( request , response , e , ar.getContext() );
return;
}
}
void handleError( HttpRequest request , HttpResponse response , Throwable t , AppContext ctxt ){
if ( ctxt == null )
ctxt = getContext( request , null );
ctxt._logger.error( request.getURL() , t );
response.setResponseCode( 500 );
JxpWriter writer = response.getWriter();
writer.print( "\n<br><br><hr><b>Error</b><br>" );
writer.print( t.toString() + "<BR>" );
while ( t != null ){
for ( StackTraceElement element : t.getStackTrace() ){
writer.print( element + "<BR>\n" );
}
t = t.getCause();
}
}
int getCacheTime( AppRequest ar , JSString jsURI , HttpRequest request , HttpResponse response ){
if ( ar.getScope().get( "staticCacheTime" ) == null )
return -1;
JSFunction f = ar.getScope().getFunction( "staticCacheTime" );
if ( f == null )
return -1;
Object ret = f.call( ar.getScope() , jsURI , request , response );
if ( ret == null )
return -1;
if ( ret instanceof Number )
return ((Number)ret).intValue();
return -1;
}
void handleCGI( HttpRequest request , HttpResponse response , AppRequest ar , File f ){
try {
if ( ! f.exists() ){
response.setResponseCode( 404 );
response.getWriter().print("file not found" );
return;
}
List<String> env = new ArrayList<String>();
env.add( "REQUEST_METHOD=" + request.getMethod() );
env.add( "SCRIPT_NAME=" + request.getURI() );
env.add( "QUERY_STRING=" + request.getQueryString() );
env.add( "SERVER_NAME=" + request.getHost() );
String envarr[] = new String[env.size()];
env.toArray( envarr );
Process p = Runtime.getRuntime().exec( new String[]{ f.getAbsolutePath() } , envarr , f.getParentFile() );
boolean inHeader = true;
BufferedReader in = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
String line;
while ( ( line = in.readLine() ) != null ){
if ( inHeader ){
if ( line.trim().length() == 0 ){
inHeader = false;
continue;
}
continue;
}
response.getWriter().print( line );
response.getWriter().print( "\n" );
}
in = new BufferedReader( new InputStreamReader( p.getErrorStream() ) );
while ( ( line = in.readLine() ) != null ){
response.getWriter().print( line );
response.getWriter().print( "\n" );
}
}
catch ( Exception e ){
ar.getContext()._logger.error( request.getURL() , e );
response.setResponseCode( 501 );
response.getWriter().print( "<br><br><hr>" );
response.getWriter().print( e.toString() );
}
}
public double priority(){
return 10000;
}
private AppContext _getContextFromMap( String host ){
AppContext ac = _context.get( host );
if ( ac == null )
return null;
if ( ! ac._reset )
return ac;
_context.put( host , null );
return null;
}
private synchronized AppContext _getDefaultContext(){
if ( _defaultContext != null && _defaultContext._reset )
_defaultContext = null;
if ( _defaultContext != null )
return _defaultContext;
_defaultContext = new AppContext( _defaultWebRoot );
return _defaultContext;
}
private final String _defaultWebRoot;
private AppContext _defaultContext;
private final AppContext _coreContext = new AppContext( CoreJS.getDefaultRoot() );
private final String _root;
private final File _rootFile;
private final Map<String,AppContext> _context = Collections.synchronizedMap( new StringMap<AppContext>() );
public static void main( String args[] )
throws Exception {
String webRoot = "/data/sites/admin/";
String serverRoot = "/data/sites";
int portNum = DEFAULT_PORT;
/*
* --port portnum [root]
*/
for (int i = 0; i < args.length; i++) {
if ("--port".equals(args[i])) {
portNum = Integer.valueOf(args[++i]);
}
else if ("--root".equals(args[i])) {
portNum = Integer.valueOf(args[++i]);
}
else {
if (i != args.length - 1) {
System.out.println("error - unknown param " + args[i]);
System.exit(1);
}
else {
webRoot = args[i];
}
}
}
System.out.println("==================================");
System.out.println(" 10gen AppServer vX");
System.out.println(" webRoot = " + webRoot);
System.out.println(" serverRoot = " + serverRoot);
System.out.println(" listen port = " + portNum);
System.out.println("==================================");
AppServer as = new AppServer( webRoot , serverRoot);
HttpServer.addGlobalHandler( as );
HttpServer hs = new HttpServer(portNum);
hs.start();
hs.join();
}
} |
package hivemall.classifier;
import hivemall.common.FeatureValue;
import hivemall.common.PredictionResult;
import hivemall.common.WeightValue;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
/**
* Adaptive Regularization of Weight Vectors (AROW) binary classifier.
* <pre>
* [1] K. Crammer, A. Kulesza, and M. Dredze, "Adaptive Regularization of Weight Vectors",
* In Proc. NIPS, 2009.
* </pre>
*/
public class AROWClassifierUDTF extends BinaryOnlineClassifierUDTF {
/** Regularization parameter r */
protected float r;
@Override
public StructObjectInspector initialize(ObjectInspector[] argOIs) throws UDFArgumentException {
final int numArgs = argOIs.length;
if(numArgs != 2 && numArgs != 3) {
throw new UDFArgumentException("AROWClassifierUDTF takes 2 or 3 arguments: List<String|Int|BitInt> features, Int label [, constant String options]");
}
return super.initialize(argOIs);
}
@Override
protected Options getOptions() {
Options opts = super.getOptions();
opts.addOption("r", "regularization", true, "Regularization parameter for some r > 0 [default 0.1]");
return opts;
}
@Override
protected CommandLine processOptions(ObjectInspector[] argOIs) throws UDFArgumentException {
final CommandLine cl = super.processOptions(argOIs);
float r = 0.1f;
if(cl != null) {
String r_str = cl.getOptionValue("r");
if(r_str != null) {
r = Float.parseFloat(r_str);
if(!(r > 0)) {
throw new UDFArgumentException("Regularization parameter must be greater than 0: "
+ r_str);
}
}
}
this.r = r;
return cl;
}
@Override
protected void train(List<?> features, int label) {
final int y = label > 0 ? 1 : -1;
PredictionResult margin = calcScoreAndVariance(features);
float m = margin.getScore() * y;
if(m < 1.f) {
float var = margin.getVariance();
float beta = 1.f / (var + r);
float alpha = (1.f - m) * beta;
update(features, y, alpha, beta);
}
}
protected float loss(PredictionResult margin, float y) {
float m = margin.getScore() * y;
return m < 0.f ? 1.f : 0.f; // suffer loss = 1 if sign(t) != y
}
protected void update(final List<?> features, final float y, final float alpha, final float beta) {
final ObjectInspector featureInspector = featureListOI.getListElementObjectInspector();
for(Object f : features) {
final Object k;
final float v;
if(parseX) {
FeatureValue fv = FeatureValue.parse(f, feature_hashing);
k = fv.getFeature();
v = fv.getValue();
} else {
k = ObjectInspectorUtils.copyToStandardObject(f, featureInspector);
v = 1.f;
}
WeightValue old_w = weights.get(k);
WeightValue new_w = getNewWeight(old_w, v, y, alpha, beta);
weights.put(k, new_w);
}
if(biasKey != null) {
WeightValue old_bias = weights.get(biasKey);
WeightValue new_bias = getNewWeight(old_bias, bias, y, alpha, beta);
weights.put(biasKey, new_bias);
}
}
private static WeightValue getNewWeight(final WeightValue old, final float x, final float y, final float alpha, final float beta) {
final float old_v;
final float old_cov;
if(old == null) {
old_v = 0.f;
old_cov = 1.f;
} else {
old_v = old.getValue();
old_cov = old.getCovariance();
}
float cv = old_cov * x;
float new_w = old_v + (y * alpha * cv);
float new_cov = old_cov - (beta * cv * cv);
return new WeightValue(new_w, new_cov);
}
} |
package info.tregmine.inventoryspy;
//import java.text.NumberFormat;
import java.util.HashMap;
import java.util.logging.Logger;
//import net.minecraft.server.EntityHuman;
//import net.minecraft.server.EntityPlayer;
//import net.minecraft.server.InventoryPlayer;
//import net.minecraft.server.PlayerInventory;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
//import org.bukkit.craftbukkit.entity.CraftPlayer;
//import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
//import org.bukkit.event.player.PlayerInventoryEvent;
//import org.bukkit.event.Event;
//import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import info.tregmine.Tregmine;
public class Main extends JavaPlugin {
public final Logger log = Logger.getLogger("Minecraft");
public Tregmine tregmine = null;
// public SpyPlayerListener inventory = new SpyPlayerListener(this);
public HashMap<Integer, String> whoDropedItem = new HashMap<Integer, String>();
@Override
public void onEnable(){
Plugin test = this.getServer().getPluginManager().getPlugin("Tregmine");
if(this.tregmine == null) {
if(test != null) {
this.tregmine = ((Tregmine)test);
} else {
log.info(this.getDescription().getName() + " " + this.getDescription().getVersion() + " - could not find Tregmine");
this.getServer().getPluginManager().disablePlugin(this);
}
getServer().getPluginManager().registerEvents(new SpyPlayerListener(this), this);
// getServer().getPluginManager().registerEvent(Event.Type.PLAYER_DROP_ITEM, inventory, Priority.Monitor, this);
// getServer().getPluginManager().registerEvent(Event.Type.PLAYER_PICKUP_ITEM, inventory, Priority.Monitor, this);
// getServer().getPluginManager().registerEvent(Event.Type.PLAYER_GAME_MODE_CHANGE, inventory, Priority.Monitor, this);
// getServer().getPluginManager().registerEvent(Event.Type.PLAYER_INTERACT, inventory, Priority.Monitor, this);
}
}
@Override
public void onDisable(){
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName().toLowerCase();
if(!(sender instanceof Player)) {
return false;
}
Player player = (Player) sender;
info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(player.getName());
boolean isAdmin = tregminePlayer.isAdmin();
if (commandName.matches("cansee") && args.length > 0 && isAdmin) {
Player target = this.getServer().matchPlayer(args[0]).get(0);
if (target != null) {
// tregminePlayer.canSee(target);
tregminePlayer.sendMessage(ChatColor.AQUA + target.getName() + "can now see you");
target.canSee(player);
} else {
tregminePlayer.sendMessage(ChatColor.RED + "player not found");
}
return true;
}
if (commandName.matches("inv") && args.length > 0 && isAdmin) {
Player target = this.getServer().matchPlayer(args[0]).get(0);
if (target != null) {
tregminePlayer.openInventory(target.getInventory());
}
}
return true;
}
@Override
public void onLoad() {
}
} |
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.exception.ExceptionUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
public class SequenceValidator extends CPServlet {
private static final int SEMESTERS_PER_YEAR = 3;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
logger.info("
response.setContentType("text/html");
JSONObject courseSequenceObject = (JSONObject) grabPropertyFromRequest("courseSequenceObject", request);
String validationResults;
try {
validationResults = validateSequence(courseSequenceObject).toString();
} catch(Exception e){
JSONObject validationResultsJsonObj = new JSONObject();
try { // have to put a try, but no real chance of failure
validationResultsJsonObj.put("error", ExceptionUtils.getStackTrace(e));
} catch(JSONException jsonExc){ jsonExc.printStackTrace(); }
validationResults = validationResultsJsonObj.toString();
}
logger.info("Responding with: " + validationResults);
response.getWriter().println(validationResults);
}
/**
* @param cso the json course sequence object
* @return a json object representing the results of the course sequence validation
*/
private JSONObject validateSequence(JSONObject cso)
throws Exception
{
// map course code to semester number (semesters are 'numbered' 0, 1, 2, 3, 4, ...)
// semesters (0, 1, 2) are year 1, semesters (3, 4, 5) are year 2, etc.
HashMap<String, Integer> cc2sn = new HashMap<>();
JSONArray yearList = cso.getJSONArray("yearList");
if (yearList.length() == 0) throw new Exception("empty yearList");
// construct cc2sn on first pass through cso
for (int yearIdx = 0; yearIdx < yearList.length(); yearIdx++)
{
JSONObject year = (JSONObject) yearList.get(yearIdx);
JSONObject fall = (JSONObject) year.get("fall");
JSONObject winter = (JSONObject) year.get("winter");
JSONObject summer = (JSONObject) year.get("summer");
JSONObject[] semsInYear = {fall, winter, summer};
for (int semsInYearIdx = 0; semsInYearIdx < semsInYear.length; semsInYearIdx++)
{
JSONArray coursesInSem = (JSONArray) semsInYear[semsInYearIdx].get("courseList");
for (int i = 0; i < coursesInSem.length(); i++)
{
JSONObject course = (JSONObject) coursesInSem.get(i);
String courseCode = (String) course.get("code");
cc2sn.put(courseCode, yearIdx + semsInYearIdx);
}
}
}
// for each course in order, make sure prereqs and coreqs are first
for (int yearIdx = 0; yearIdx < yearList.length(); yearIdx++)
{
JSONObject year = (JSONObject) yearList.get(yearIdx);
JSONObject fall = (JSONObject) year.get("fall");
JSONObject winter = (JSONObject) year.get("winter");
JSONObject summer = (JSONObject) year.get("summer");
JSONObject[] semsInYear = {fall, winter, summer};
for (int semsInYearIdx = 0; semsInYearIdx < semsInYear.length; semsInYearIdx++)
{
JSONArray coursesInSem = (JSONArray) semsInYear[semsInYearIdx].get("courseList");
for (int i = 0; i < coursesInSem.length(); i++)
{
JSONObject course = (JSONObject) coursesInSem.get(i);
// TODO: check prereqs, check coreqs
}
}
}
return null;
}
} |
package authenticator.network;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javafx.application.Platform;
import javafx.scene.image.Image;
import org.json.JSONObject;
import org.xml.sax.SAXException;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence.ConfidenceType;
import com.google.protobuf.ByteString;
import com.subgraph.orchid.encoders.Hex;
import wallettemplate.Main;
import authenticator.Authenticator;
import authenticator.BASE;
import authenticator.Utils.EncodingUtils;
import authenticator.network.exceptions.TCPListenerCouldNotStartException;
import authenticator.operations.BAOperation;
import authenticator.operations.BAOperation.BANetworkRequirement;
import authenticator.operations.exceptions.BAOperationNetworkRequirementsNotAvailableException;
import authenticator.operations.listeners.OperationListener;
import authenticator.operations.listeners.OperationListenerAdapter;
import authenticator.operations.OperationsFactory;
import authenticator.protobuf.ProtoConfig.ATAccount;
import authenticator.protobuf.ProtoConfig.PairedAuthenticator;
import authenticator.protobuf.ProtoConfig.PendingRequest;
import authenticator.protobuf.ProtoConfig.WalletAccountType;
import authenticator.walletCore.BAPassword;
import authenticator.walletCore.WalletOperation;
import authenticator.walletCore.exceptions.CannotRemovePendingRequestException;
/**
* <b>The heart of the wallet operation.</b><br>
* <br>
* <b>When does it start ?</b><br>
* This listener is launched on wallet startup by {@link authenticator.Authenticator#doStart()} function.<br>
* <br>
* <b>What does it do ?</b><br>
* The listener is responsible for 2 main operations:<br>
* <ol>
* <li>Inbound Operations - The listener will listen on the socket for any inbound communication. When it hooks to another socket, it will expect a requestID for reference.<br>
* When the requestID is received, it will search it in the pending requests file. When the pending operation is found, the TCPListener will follow the
* {@link authenticator.protobuf.ProtoConfig.PendingRequest.Contract Contract} to complete the reques.</li>
* <li>Outbound Operations - When calling {@link authenticator.Authenticator#addOperation(BAOperation operation) addOperation}, the authenticator will add
* an operation to the operation queue. Here, the TCPListener will look for operations to execute from the said queue.</li>
* <ol>
*
* @author alon
*
*/
public class TCPListener extends BASE{
final int LOOPER_BLOCKING_TIMEOUT = 3000;
private Socket socket;
private ConcurrentLinkedQueue<BAOperation> operationsQueue;
private Thread listenerThread;
private UpNp plugnplay;
private boolean isManuallyPortForwarded;
private int forwardedPort;
private BANetworkInfo vBANeworkInfo;
private String[] args;
private ServerSocket ss = null;
private OperationListener longLivingOperationsListener;
private BAOperation CURRENT_OUTBOUND_OPERATION = null;
/**
* Data binder
*/
private TCPListenerExecutionDataBinder dataBinder = new DataBinderAdapter();
public class DataBinderAdapter implements TCPListenerExecutionDataBinder{
@Override
public BAPassword getWalletPassword() {
return new BAPassword();
}
}
WalletOperation wallet;
/**
* Flags
*/
private boolean shouldStopListener;
public TCPListener(){ super(TCPListener.class); }
/**
* args:<br>
* [0] - port number<br>
* @param wallet
* @param isManuallyPortForwarded
* @param args
*/
public TCPListener(WalletOperation wallet, boolean isManuallyPortForwarded,String[] args){
super(TCPListener.class);
this.wallet = wallet;
this.args = args;
this.isManuallyPortForwarded = isManuallyPortForwarded;
if(operationsQueue == null)
operationsQueue = new ConcurrentLinkedQueue<BAOperation>();
}
public void runListener(final String[] args) throws Exception
{
shouldStopListener = false;
this.listenerThread = new Thread(){
@Override
public void run() {
try{
startup();
assert(operationsQueue != null);
notifyStarted();
Authenticator.fireOnAuthenticatorNetworkStatusChange(getNetworkInfo());
System.out.println(TCPListener.this.toString());
looper();
}
catch (Exception e1) {
LOG.info("Fatal Error, TCPListener ShutDown Because Of: \n");
e1.printStackTrace();
System.out.println("\n\n" + toString());
}
finally
{
try { ss.close(); } catch (Exception e) { }
try { plugnplay.removeMapping(); } catch (Exception e) { }
LOG.info("Listener Stopped");
notifyStopped();
}
}
/**
* Setup all necessary things for the TCP looper to run.<br>
* Test:
* <ol>
* <li>UPNP</li>
* <li>Socket listening</li>
* </ol>
*
* @throws TCPListenerCouldNotStartException
*/
@SuppressWarnings("static-access")
private void startup() throws TCPListenerCouldNotStartException{
forwardedPort = Integer.parseInt(args[0]);
/**
* In any case, port forwarded manually/ upnp or not, get Ips and open socket.
*
*/
if(!isManuallyPortForwarded){
if(plugnplay != null)
{
throw new TCPListenerCouldNotStartException("Could not start TCPListener");
}
plugnplay = new UpNp();
try {
plugnplay.run(new String[]{args[0]});
if(plugnplay.isPortMapped(Integer.parseInt(args[0])) == true){
vBANeworkInfo = new BANetworkInfo(plugnplay.getExternalIP(), plugnplay.getLocalIP().substring(1));
vBANeworkInfo.PORT_FORWARDED = true;
LOG.info("Successfuly map ported port: " + forwardedPort);
}
else {
vBANeworkInfo = new BANetworkInfo(getExternalIp(), getInternalIp());
vBANeworkInfo.PORT_FORWARDED = false;
LOG.info("Failed to map port");
}
} catch (Exception e) {
e.printStackTrace();
vBANeworkInfo = new BANetworkInfo(getExternalIp(), getInternalIp());
vBANeworkInfo.PORT_FORWARDED = false;
LOG.info("Failed to map port");
}
}
else
try {
vBANeworkInfo = new BANetworkInfo(getExternalIp(), InetAddress.getLocalHost().getHostAddress());
vBANeworkInfo.PORT_FORWARDED = true;
LOG.info("Marked port " + forwardedPort + " as forwarded");
} catch (Exception e) {
e.printStackTrace();
throw new TCPListenerCouldNotStartException("Could not start TCPListener");
}
//if(PORT_FORWARDED)
try {
ss = new ServerSocket (forwardedPort);
ss.setSoTimeout(LOOPER_BLOCKING_TIMEOUT);
vBANeworkInfo.SOCKET_OPERATIONAL = true;
LOG.info("Socket operational");
} catch (Exception e) {
e.printStackTrace();
try { plugnplay.removeMapping(); } catch (IOException | SAXException e1) { }
throw new TCPListenerCouldNotStartException("Could not start TCPListener");
}
}
/**
* IMPORTANT !
*
* Some operations require the Authenticator the set its AUTHENTICATOR_PW variable for pending requests.
* One example is the SignAndBroadcastAuthenticatorTx operation which has 2 parts, the first send a Tx to be
* signed by the Authenticator app and the second part which completes the operation. This second part requires
* signing the Tx and therefore a valid AUTHENTICATOR_PW.
*
* @throws FileNotFoundException
* @throws IOException
*/
@SuppressWarnings("unused")
private void looper() throws FileNotFoundException, IOException{
boolean isConnected;
sendUpdatedIPsToPairedAuthenticators();
while(true)
{
isConnected = false;
try{
socket = ss.accept();
isConnected = true;
}
catch (SocketTimeoutException | java.net.SocketException e){ isConnected = false; }
//
// Inbound
//
PendingRequest pendingReq = null;
try{
if(isConnected){
/**
* Check for network requirements availability
*/
// if we have an inbound operation that means upnp and socket work
LOG.info("Processing Pending Operation ...");
DataInputStream inStream = new DataInputStream(socket.getInputStream());
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
/*
* Send a pong message to confirm
*/
PongPayload pp = new PongPayload();
outStream.writeInt(pp.getPayloadSize());
outStream.write(pp.getBytes());
LOG.info("Sent a pong answer");
//get request ID
String requestID = "";
int keysize = inStream.readInt();
byte[] reqIdPayload = new byte[keysize];
inStream.read(reqIdPayload);
JSONObject jo = new JSONObject(new String(reqIdPayload));
requestID = jo.getString("requestID");
String pairingID = jo.getString("pairingID");
LOG.info("Looking for pending request ID: " + requestID);
for(Object o:wallet.getPendingRequests()){
PendingRequest po = (PendingRequest)o;
if(po.getRequestID().equals(requestID))
{
pendingReq = po;
break;
}
}
if(pendingReq == null){
SecretKey secretkey = new SecretKeySpec(Hex.decode(wallet.getAESKey(pairingID)), "AES");
CannotProcessRequestPayload p = new CannotProcessRequestPayload("Cannot find pending request\nPlease resend operation",
secretkey);
outStream.writeInt(p.getPayloadSize());
outStream.write(p.toEncryptedBytes());
LOG.info("No Pending Request Found, aborting inbound operation");
if(longLivingOperationsListener != null)
longLivingOperationsListener.onError(null, new Exception("Authenticator tried to complete a pending request but the request was not found, please try again"), null);
}
else{
// Should we send something on connection ?
if(pendingReq.getContract().getShouldSendPayloadOnConnection()){
byte[] p = pendingReq.getPayloadToSendInCaseOfConnection().toByteArray();
outStream.writeInt(p.length);
outStream.write(p);
LOG.info("Sent transaction");
}
// Should we receive something ?
if(pendingReq.getContract().getShouldReceivePayloadAfterSendingPayloadOnConnection()){
keysize = inStream.readInt();
byte[] in = new byte[keysize];
inStream.read(in);
PendingRequest.Builder b = PendingRequest.newBuilder(pendingReq);
b.setPayloadIncoming(ByteString.copyFrom(in));
pendingReq = b.build();
}
//cleanup
inStream.close();
outStream.close();
// Complete Operation ?
switch(pendingReq.getOperationType()){
case SignAndBroadcastAuthenticatorTx:
byte[] txBytes = Hex.decode(pendingReq.getRawTx());
Transaction tx = new Transaction(wallet.getNetworkParams(),txBytes);
BAOperation op = OperationsFactory.SIGN_AND_BROADCAST_AUTHENTICATOR_TX_OPERATION(wallet,
tx,
pendingReq.getPairingID(),
null,
null,
true,
pendingReq.getPayloadIncoming().toByteArray(),
pendingReq,
dataBinder.getWalletPassword());
operationsQueue.add(op);
break;
}
if(!pendingReq.getContract().getShouldLetPendingRequestHandleRemoval())
wallet.removePendingRequest(pendingReq);
}
}
else
;
}
catch(Exception e){
if(pendingReq != null)
try {
wallet.removePendingRequest(pendingReq);
} catch (CannotRemovePendingRequestException e1) {
e1.printStackTrace();
}
e.printStackTrace();
LOG.info("Error Occured while executing Inbound operation:\n"
+ e.toString());
}
//
// Outbound
//
if(operationsQueue.size() > 0)
{
LOG.info("Found " + operationsQueue.size() + " Operations in queue");
while (operationsQueue.size() > 0){
BAOperation op = operationsQueue.poll();
if (op == null){
break;
}
/**
* Check for network requirements availability
*/
LOG.info("Checking network requirements availability for outbound operation");
if(checkForOperationNetworkRequirements(op) == false )
{
op.OnExecutionError(new BAOperationNetworkRequirementsNotAvailableException("Required Network requirements not available"));
break;
}
LOG.info("Executing Operation: " + op.getDescription());
CURRENT_OUTBOUND_OPERATION = op;
try{
op.run(ss, vBANeworkInfo);
CURRENT_OUTBOUND_OPERATION = null;
}
catch (Exception e)
{
e.printStackTrace();
LOG.info("Error Occured while executing Outbound operation:\n"
+ e.toString());
if(op.getOperationListener() != null)
op.OnExecutionError(e);
else
/*
* we still need to notify user even if we don't have an operation listener
* (like in a paired account tx signing)
*/
if(longLivingOperationsListener != null)
longLivingOperationsListener.onError(op, e, null);
}
}
}
else
; // do nothing
if(shouldStopListener)
break;
}
}
};
listenerThread.start();
}
public boolean checkForOperationNetworkRequirements(BAOperation op){
if(vBANeworkInfo == null) // in case the setup process is not finished yet
return false;
if((op.getOperationNetworkRequirements().getValue() & BANetworkRequirement.PORT_MAPPING.getValue()) > 0){
if(! vBANeworkInfo.PORT_FORWARDED || !vBANeworkInfo.SOCKET_OPERATIONAL){
return false;
}
}
if((op.getOperationNetworkRequirements().getValue() & BANetworkRequirement.SOCKET.getValue()) > 0){
if(!vBANeworkInfo.SOCKET_OPERATIONAL){
return false;
}
}
return true;
}
//
// Queue
//
public boolean addOperation(BAOperation operation)
{
checkForOperationNetworkRequirements(operation);
if(isRunning()){
operationsQueue.add(operation);
return true;
}
return false;
}
public int getQueuePendingOperations(){
return operationsQueue.size();
}
//
// General
//
@Override
public String toString() {
return "Authenticator TCPListener: \n" +
String.format("%-30s: %10s\n", "State", this.isRunning()? "Running":"Not Running") +
String.format("%-30s: %10s\n", "External IP", this.getNetworkInfo().EXTERNAL_IP) +
String.format("%-30s: %10s\n", "Internal IP", this.getNetworkInfo().INTERNAL_IP) +
"Network Requirements: \n" +
String.format(" %-30s: %10s\n", "Port Mapped/ Forwarded", this.getNetworkInfo().PORT_FORWARDED? "True":"False") +
String.format(" %-30s: %10s\n", "Socket", this.getNetworkInfo().SOCKET_OPERATIONAL? "Operational":"Not Operational");
}
/**
* Check if the TCPListener has all the various operation network requirements
*/
public void sendUpdatedIPsToPairedAuthenticators(){
for(ATAccount acc:wallet.getAllAccounts())
if(acc.getAccountType() == WalletAccountType.AuthenticatorAccount){
PairedAuthenticator po = wallet.getPairingObjectForAccountIndex(acc.getIndex());
BAOperation op = OperationsFactory.UPDATE_PAIRED_AUTHENTICATORS_IPS(wallet,
po.getPairingID());
operationsQueue.add(op);
}
}
public boolean areAllNetworkRequirementsAreFullyRunning(){
if(!vBANeworkInfo.PORT_FORWARDED || !vBANeworkInfo.SOCKET_OPERATIONAL)
return false;
return true;
}
/**
* Used in case UPNP mapping doesn't work
*
* @return
* @throws IOException
*/
private String getExternalIp(){
URL whatismyip;
try {
whatismyip = new URL("http://icanhazip.com");
BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
return in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Used in case UPNP mapping doesn't work
*
* @return
* @throws UnknownHostException
*/
private String getInternalIp() {
try {
Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
while( b.hasMoreElements()){
for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
if ( f.getAddress().isSiteLocalAddress())
return f.getAddress().getHostAddress();
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
public void INTERRUPT_CURRENT_OUTBOUND_OPERATION() throws IOException{
INTERRUPT_OUTBOUND_OPERATION(CURRENT_OUTBOUND_OPERATION);
}
public void INTERRUPT_OUTBOUND_OPERATION(BAOperation op) throws IOException{
if(CURRENT_OUTBOUND_OPERATION == null)
return;
if(CURRENT_OUTBOUND_OPERATION.getOperationID().equals(op.getOperationID())){
LOG.info("Interrupting Operation with ID " + op.getOperationID());
CURRENT_OUTBOUND_OPERATION.interruptOperation();
// restore socket
vBANeworkInfo.SOCKET_OPERATIONAL = false;
ss = new ServerSocket (forwardedPort);
ss.setSoTimeout(LOOPER_BLOCKING_TIMEOUT);
vBANeworkInfo.SOCKET_OPERATIONAL = true;
}
else
LOG.info("Operation Not Found: Cannot Interrupt Operation with ID " + op.getOperationID());
}
public BANetworkInfo getNetworkInfo() {
return vBANeworkInfo;
}
//
// Data Binder
//
/**
* An interface that implements necessary methods that get critical data to the listener at runtime.<br>
* This interface is critical for the correct operation and execution of a {@link authenticator.operations.BAOperation BAOperation}.<br>
* <b>Failing to implement this listener could cause operations to crash on execution</b>
*
* @author Alon Muroch
*
*/
public interface TCPListenerExecutionDataBinder{
public BAPassword getWalletPassword();
}
public void setExecutionDataBinder(TCPListenerExecutionDataBinder b){
dataBinder = b;
}
//
// Long living operations listener
//
/**
* see {@link authenticator.network.TCPListener#longLivingOperationsListener TCPListener#longLivingOperationsListener}
* @param listener
*/
public void setOperationListener(OperationListener listener) {
this.longLivingOperationsListener = listener;
}
//
// Service methods
//
protected void doStart() {
try {
runListener(args);
} catch (Exception e) {
e.printStackTrace();
notifyFailed(new Throwable("Failed to run TCPListener"));
}
}
@Override
protected void doStop() {
shouldStopListener = true;
LOG.info("Stopping Listener ... ");
}
} |
/**
* The main package (to get started, look at the {@link clay.Clay} class).
*/
package clay; |
package br.jus.trf2.balcaovirtual;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.crivano.swaggerservlet.SwaggerUtils;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import br.jus.cnj.intercomunicacao_2_2.ModalidadePoloProcessual;
import br.jus.cnj.intercomunicacao_2_2.ModalidadeRelacionamentoProcessual;
import br.jus.cnj.intercomunicacao_2_2.ModalidadeRepresentanteProcessual;
import br.jus.cnj.intercomunicacao_2_2.TipoAvisoComunicacaoPendente;
import br.jus.cnj.intercomunicacao_2_2.TipoCabecalhoProcesso;
import br.jus.cnj.intercomunicacao_2_2.TipoComunicacaoProcessual;
import br.jus.cnj.intercomunicacao_2_2.TipoDocumento;
import br.jus.cnj.intercomunicacao_2_2.TipoParametro;
import br.jus.cnj.intercomunicacao_2_2.TipoParte;
import br.jus.cnj.intercomunicacao_2_2.TipoPessoa;
import br.jus.cnj.intercomunicacao_2_2.TipoPoloProcessual;
import br.jus.cnj.intercomunicacao_2_2.TipoProcessoJudicial;
import br.jus.cnj.intercomunicacao_2_2.TipoQualificacaoPessoa;
import br.jus.cnj.intercomunicacao_2_2.TipoRepresentanteProcessual;
import br.jus.cnj.servico_intercomunicacao_2_2.ServicoIntercomunicacao222;
import br.jus.cnj.servico_intercomunicacao_2_2.ServicoIntercomunicacao222_Service;
import br.jus.trf2.balcaovirtual.IBalcaoVirtual.Aviso;
import br.jus.trf2.balcaovirtual.IBalcaoVirtual.ListStatus;
import br.jus.trf2.balcaovirtual.IBalcaoVirtual.ProcessoNumeroAvisoIdReceberPostResponse;
import br.jus.trf2.balcaovirtual.SessionsCreatePost.Usuario;
public class SoapMNI {
private static final DateTimeFormatter dtfMNI = DateTimeFormat.forPattern("yyyyMMddHHmmss");
private static final DateTimeFormatter dtfBR = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
// private static final DateTimeFormatter dtfFILE =
// DateTimeFormat.forPattern("yyyy-MM-dd-HH-mm");
private static class ConsultaProcessualExclStrat implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
return f.getName().equals("endereco");
}
}
private static class OutroParametroSerializer implements JsonSerializer<List<TipoParametro>> {
@Override
public JsonElement serialize(List<TipoParametro> src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = new JsonObject();
for (TipoParametro p : src) {
String nome = p.getNome();
String valor = p.getValor();
if (object.has(nome)) {
if (object.get(nome).isJsonArray()) {
object.getAsJsonArray(nome).add(valor);
} else {
JsonArray a = new JsonArray();
a.add(object.get(nome).getAsString());
a.add(valor);
object.add(nome, a);
}
} else
object.addProperty(nome, valor);
}
return object;
}
}
public static String consultarProcesso(String idManif, String orgao, String numProc) throws Exception {
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<TipoProcessoJudicial> processo = new Holder<>();
Map<String, Object> requestContext = ((BindingProvider) client).getRequestContext();
requestContext.put("javax.xml.ws.client.receiveTimeout", "3600000");
requestContext.put("javax.xml.ws.client.connectionTimeout", "5000");
client.consultarProcesso(idManif, null, numProc, null, true, true, true, null, sucesso, mensagem, processo);
if (!sucesso.value)
throw new Exception(mensagem.value);
Type collectionType = new TypeToken<List<TipoParametro>>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(collectionType, new OutroParametroSerializer())
.setExclusionStrategies(new ConsultaProcessualExclStrat()).create();
return gson.toJson(processo);
}
public static byte[] obterPecaProcessual(String idManif, String orgao, String numProc, String documento)
throws Exception {
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<TipoProcessoJudicial> processo = new Holder<>();
List<String> l = new ArrayList<>();
l.add(documento);
client.consultarProcesso(idManif, null, numProc, null, false, false, false, l, sucesso, mensagem, processo);
if (!sucesso.value)
throw new Exception(mensagem.value);
return processo.value.getDocumento().get(0).getConteudo();
}
public static void consultarAvisosPendentes(String idConsultante, List<Aviso> list, List<ListStatus> status)
throws Exception {
Usuario u = SessionsCreatePost.assertUsuario();
for (String orgao : Utils.getOrgaos().split(",")) {
String system = orgao.toLowerCase();
if (!u.usuarios.containsKey(system))
continue;
URL url = new URL(Utils.getMniWsdlUrl(system));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<List<TipoAvisoComunicacaoPendente>> aviso = new Holder<>();
ListStatus ls = new ListStatus();
ls.system = system;
status.add(ls);
Map<String, Object> requestContext = ((BindingProvider) client).getRequestContext();
requestContext.put("javax.xml.ws.client.receiveTimeout", "3600000");
requestContext.put("javax.xml.ws.client.connectionTimeout", "5000");
try {
client.consultarAvisosPendentes(null, idConsultante, null, null, sucesso, mensagem, aviso);
if (!sucesso.value)
throw new Exception(mensagem.value);
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Erro obtendo a lista de {}", system, ex);
ls.errormsg = SwaggerUtils.messageAsString(ex);
ls.stacktrace = SwaggerUtils.stackAsString(ex);
}
if (aviso != null && aviso.value != null) {
for (TipoAvisoComunicacaoPendente a : aviso.value) {
Aviso i = new Aviso();
switch (a.getTipoComunicacao()) {
case "INT":
i.tipo = "Intimação";
break;
case "CIT":
i.tipo = "Citação";
break;
}
i.processo = a.getProcesso().getNumero();
i.dataaviso = Utils.parsearApoloDataHoraMinuto(a.getDataDisponibilizacao());
i.idaviso = a.getIdAviso();
i.orgao = orgao;
i.unidade = a.getProcesso().getOrgaoJulgador().getCodigoOrgao();
i.unidadenome = a.getProcesso().getOrgaoJulgador().getNomeOrgao();
if (a.getProcesso().getAssunto() != null && a.getProcesso().getAssunto().size() > 0
&& a.getProcesso().getAssunto().get(0) != null
&& a.getProcesso().getAssunto().get(0).getCodigoNacional() != null)
i.assunto = a.getProcesso().getAssunto().get(0).getCodigoNacional().toString();
for (TipoParametro p : a.getProcesso().getOutroParametro()) {
if (p.getNome().equals("tipoOrgaoJulgador"))
i.unidadetipo = p.getValor();
if (p.getNome().equals("dtLimitIntimAut"))
i.datalimiteintimacaoautomatica = Utils.parsearApoloDataHoraMinuto(p.getValor());
if (p.getNome().equals("eventoIntimacao"))
i.eventointimacao = p.getValor();
if (p.getNome().equals("numeroPrazo"))
i.numeroprazo = p.getValor();
if (p.getNome().equals("tipoPrazo"))
i.tipoprazo = p.getValor();
if (p.getNome().equals("multiplicadorPrazo"))
i.multiplicadorprazo = p.getValor();
if (p.getNome().equals("motivoIntimacao"))
i.motivointimacao = p.getValor();
}
i.localidade = a.getProcesso().getCodigoLocalidade();
list.add(i);
}
}
}
}
public static void consultarTeorComunicacao(String idConsultante, String numProc, String idAviso, String orgao,
ProcessoNumeroAvisoIdReceberPostResponse resp) throws Exception {
Map<String, Object> jwt = SessionsCreatePost.assertUsuarioAutorizado();
String email = (String) jwt.get("email");
String nome = (String) jwt.get("name");
String usuario = (String) jwt.get("username");
String numProcFormated = Utils.formatarNumeroProcesso(numProc);
String system = orgao.toLowerCase();
URL url = new URL(Utils.getMniWsdlUrl(system));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<List<TipoComunicacaoProcessual>> comunicacao = new Holder<>();
client.consultarTeorComunicacao(idConsultante, idAviso, null, null, sucesso, mensagem, comunicacao);
if (!sucesso.value)
throw new Exception(mensagem.value);
if (comunicacao.value.size() != 1)
throw new Exception("Número de comunicações deve ser exatamente igual a 1");
TipoComunicacaoProcessual c = comunicacao.value.get(0);
if (c.getTipoComunicacao() != null)
switch (c.getTipoComunicacao()) {
case "INT":
resp.tipo = "Intimação";
break;
case "CIT":
resp.tipo = "Citação";
break;
default:
resp.tipo = "Aviso";
}
resp.processo = numProc;
resp.dataaviso = c.getDataReferencia();
resp.idaviso = idAviso;
resp.orgao = orgao;
resp.teor = c.getTeor();
// byte[] pdf = null;
// if (c.getDocumento() != null && c.getDocumento().size() > 0)
// pdf = c.getDocumento().get(0).getConteudo();
DateTime dt = DateTime.parse(c.getDataReferencia(), dtfMNI);
boolean sent = false;
boolean sigilo = c.getNivelSigilo() != null ? c.getNivelSigilo() != 0 : true;
if (email != null) {
email = "renato.crivano@gmail.com";
try {
String assunto = "Balcão Virtual: Confirmação de " + resp.tipo;
String conteudo = "Prezado(a) " + nome + ",\n\nAcusamos a confirmação de " + resp.tipo.toLowerCase()
+ " conforme dados abaixo:" + "\n\nProcesso Número: " + numProcFormated.replace("/", "")
+ "\nData/Hora de Término do Prazo: " + dt.toString(dtfBR) + "\nSigilo: "
+ (sigilo ? "Sim" : "Não") + "\n\nAtenciosamente,\n\nTribunal Regional Federal da 2a Região";
// String nomeArquivo = numProcFormated + "-" +
// Utils.removeAcento(resp.tipo).toLowerCase() + "-"
// + dt.toString(dtfFILE) + ".pdf";
// if (sigilo)
Correio.enviar(email, assunto, conteudo, null, null, null);
// else
// Correio.enviar(email, assunto, conteudo, nomeArquivo,
// "application/pdf", pdf);
sent = true;
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Email não enviado", ex);
}
}
SwaggerUtils.log(SoapMNI.class).warn("*** Processo: " + numProcFormated + " Aviso confirmado: " + resp.idaviso
+ " Por: " + usuario + " Email: " + email + (sent ? "" : " (email não enviado)"));
}
public static String enviarPeticaoIntercorrente(String idManif, String orgao, String numProc, String tpDoc,
int nvlSigilo, String nomePdfs, byte pdf[]) throws Exception {
Map<String, Object> jwt = SessionsCreatePost.assertUsuarioAutorizado();
String email = (String) jwt.get("email");
String nome = (String) jwt.get("name");
String usuario = (String) jwt.get("username");
if (nomePdfs == null && pdf == null)
throw new Exception("Não é possível peticionar sem que seja fornecido um PDF");
String numProcFormated = Utils.formatarNumeroProcesso(numProc);
String dataEnvio = new DateTime(new Date()).toString("yyyyMMddHHmmss");
String dirFinal = Utils.getDirFinal();
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
List<TipoDocumento> l = new ArrayList<>();
if (nomePdfs != null) {
for (String nomePdf : nomePdfs.split(",")) {
TipoDocumento doc = new TipoDocumento();
doc.setMimetype("application/pdf");
doc.setDataHora(dataEnvio);
doc.setNivelSigilo(nvlSigilo == 0 ? 0 : 5);
doc.setTipoDocumento(tpDoc);
Path path = Paths.get(dirFinal + "/" + nomePdf + ".pdf");
byte[] data = Files.readAllBytes(path);
doc.setConteudo(data);
l.add(doc);
}
}
if (pdf != null) {
TipoDocumento doc = new TipoDocumento();
doc.setMimetype("application/pdf");
doc.setDataHora(dataEnvio);
doc.setNivelSigilo(0);
doc.setTipoDocumento(tpDoc);
doc.setConteudo(pdf);
l.add(doc);
}
TipoCabecalhoProcesso dadosBasicos = new TipoCabecalhoProcesso();
dadosBasicos.setCodigoLocalidade("1");
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<String> protocoloRecebimento = new Holder<>();
Holder<String> dataOperacao = new Holder<>();
Holder<byte[]> recibo = new Holder<>();
Holder<List<TipoParametro>> parametro = new Holder<>();
client.entregarManifestacaoProcessual(idManif, null, numProc, null, l, dataEnvio,
new ArrayList<TipoParametro>(), sucesso, mensagem, protocoloRecebimento, dataOperacao, recibo,
parametro);
if (!sucesso.value)
throw new Exception(mensagem.value);
DateTime dt = DateTime.parse(dataOperacao.value, dtfMNI);
boolean sent = false;
if (email != null) {
try {
String conteudo = "Prezado(a) " + nome
+ ",\n\nAcusamos o recebimento da petição intercorrente conforme dados abaixo:"
+ "\n\nProcesso Número: " + numProcFormated + "\nProtocolo: " + protocoloRecebimento.value
+ "\nData/Hora do Protocolo: " + dt.toString(dtfBR)
+ "\n\nAtenciosamente,\n\nTribunal Regional Federal da 2a Região";
Correio.enviar(email, "Balcão Virtual: Protocolo de Recebimento", conteudo,
numProcFormated + "-protocolo-" + protocoloRecebimento.value + ".pdf", "application/pdf",
recibo.value);
sent = true;
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Email não enviado", ex);
}
}
SwaggerUtils.log(SoapMNI.class)
.warn("*** Processo: " + numProcFormated + " Petição Intercorrente protocolada: "
+ protocoloRecebimento.value + " Por: " + usuario + " Email: " + email
+ (sent ? "" : " (email não enviado)"));
return "Protocolo: " + protocoloRecebimento.value + ", Data: " + dt.toString(dtfBR)
+ (sent ? "" : " (email não enviado)");
}
public static class Parte {
int polo; // 1=Ativo, 2=Passivo
int tipopessoa; // 1=PF, 2=PJ, 3=Entidade, 4=Advogado
String documento;
String nome;
}
public static String enviarPeticaoInicial(String idManif, String orgao, String localidade, String especialidade,
String classe, double valorCausa, String cdas, String pas, int nvlSigilo, boolean justicagratuita,
boolean tutelaantecipada, boolean prioridadeidoso, List<Parte> partes, String nomePdfs, String tpDocPdfs)
throws Exception {
Map<String, Object> jwt = SessionsCreatePost.assertUsuarioAutorizado();
String email = (String) jwt.get("email");
String nome = (String) jwt.get("name");
String usuario = (String) jwt.get("username");
String dataEnvio = new DateTime(new Date()).toString("yyyyMMddHHmmss");
String dirFinal = Utils.getDirFinal();
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
List<TipoDocumento> l = new ArrayList<>();
// String tpDocs[] = tpDocPdfs.split(",");
int i = 0;
String classificacoes[] = tpDocPdfs.split(",");
for (String nomePdf : nomePdfs.split(",")) {
TipoDocumento doc = new TipoDocumento();
doc.setMimetype("application/pdf");
doc.setDataHora(dataEnvio);
doc.setNivelSigilo(nvlSigilo == 0 ? 0 : 5);
// doc.setTipoDocumento(tpDocs[i]);
Path path = Paths.get(dirFinal + "/" + nomePdf + ".pdf");
byte[] data = Files.readAllBytes(path);
doc.setConteudo(data);
TipoParametro classificacao = new TipoParametro();
classificacao.setNome("CLASSIFICACAO");
classificacao.setValor(classificacoes[i]);
doc.getOutroParametro().add(classificacao);
l.add(doc);
i++;
}
TipoCabecalhoProcesso dadosBasicos = new TipoCabecalhoProcesso();
TipoParte tp = null;
for (Parte parte : partes) {
ModalidadePoloProcessual m = parte.polo == 1 ? ModalidadePoloProcessual.AT : ModalidadePoloProcessual.PA;
TipoPoloProcessual tpp = null;
for (TipoPoloProcessual itpp : dadosBasicos.getPolo()) {
if (itpp.getPolo().equals(m)) {
tpp = itpp;
break;
}
}
if (tpp == null) {
tpp = new TipoPoloProcessual();
tpp.setPolo(m);
dadosBasicos.getPolo().add(tpp);
}
TipoQualificacaoPessoa tqp = null;
switch (parte.tipopessoa) {
case 1:
tqp = TipoQualificacaoPessoa.FISICA;
break;
case 2:
tqp = TipoQualificacaoPessoa.JURIDICA;
break;
case 3:
tqp = TipoQualificacaoPessoa.JURIDICA;
break;
case 4:
if (tp == null)
throw new Exception("Não há pessoa para vincular ao advogado");
TipoRepresentanteProcessual rp = new TipoRepresentanteProcessual();
rp.setNome(parte.nome);
rp.setInscricao(Utils.removePontuacao(parte.documento));
rp.setTipoRepresentante(ModalidadeRepresentanteProcessual.A);
// rp.setNumeroDocumentoPrincipal("11111111111");
// rp.setIntimacao(false);
tp.getAdvogado().add(rp);
tqp = TipoQualificacaoPessoa.ORGAOREPRESENTACAO;
continue;
}
tp = new TipoParte();
// if (justicagratuita && tqp == TipoQualificacaoPessoa.FISICA)
// tp.setAssistenciaJudiciaria(true);
tp.setRelacionamentoProcessual(ModalidadeRelacionamentoProcessual.RP);
TipoPessoa pess = new TipoPessoa();
pess.setNome(parte.nome);
pess.setNumeroDocumentoPrincipal(Utils.removePontuacao(parte.documento));
// pess.setCidadeNatural("Rio de Janeiro");
// pess.setEstadoNatural("RJ");
pess.setTipoPessoa(tqp);
tp.setPessoa(pess);
tpp.getParte().add(tp);
}
dadosBasicos.setCodigoLocalidade(localidade);
// dadosBasicos.setClasseProcessual(20);
dadosBasicos.setValorCausa(valorCausa);
List<TipoParametro> parametros = dadosBasicos.getOutroParametro();// new
// ArrayList<TipoParametro>();
// Apolo
String aClasse[] = classe.split("\\|");
dadosBasicos.setClasseProcessual(Integer.parseInt(aClasse[0]));
if (aClasse.length == 2) {
TipoParametro p = new TipoParametro();
p.setNome("CLASSEINTERNA");
p.setValor(aClasse[1]);
parametros.add(p);
}
if (prioridadeidoso) {
dadosBasicos.getPrioridade().add("IDOSO");
}
if (justicagratuita) {
TipoParametro jg = new TipoParametro();
jg.setNome("JUSTICAGRATUITA");
jg.setValor("TRUE");
parametros.add(jg);
}
if (justicagratuita) {
TipoParametro jg = new TipoParametro();
jg.setNome("JUSTICAGRATUITA");
jg.setValor("TRUE");
parametros.add(jg);
}
if (tutelaantecipada) {
TipoParametro tla = new TipoParametro();
tla.setNome("TUTELAANTECIPADA");
tla.setValor("TRUE");
parametros.add(tla);
}
if (cdas != null) {
for (String s : cdas.split(",")) {
String ss = Utils.removePontuacao(s).trim();
if (ss.length() == 0)
continue;
TipoParametro cda = new TipoParametro();
cda.setNome("NUMEROCDA");
cda.setValor(ss);
parametros.add(cda);
}
}
if (pas != null) {
for (String s : pas.split(",")) {
String ss = Utils.removePontuacao(s).trim();
if (ss.length() == 0)
continue;
TipoParametro pa = new TipoParametro();
pa.setNome("NUMEROPROCESSOADMINISTRATIVO");
pa.setValor(ss);
parametros.add(pa);
}
}
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<String> protocoloRecebimento = new Holder<>();
Holder<String> dataOperacao = new Holder<>();
Holder<byte[]> recibo = new Holder<>();
Holder<List<TipoParametro>> parametro = new Holder<>();
client.entregarManifestacaoProcessual(idManif, null, null, dadosBasicos, l, dataEnvio, parametros, sucesso,
mensagem, protocoloRecebimento, dataOperacao, recibo, parametro);
if (!sucesso.value)
throw new Exception(mensagem.value);
DateTime dt = DateTime.parse(dataOperacao.value, dtfMNI);
boolean sent = false;
String numProcFormated = "?";
if (email != null) {
try {
String conteudo = "Prezado(a) " + nome
+ ",\n\nAcusamos o recebimento da petição inicial conforme dados abaixo:"
+ "\n\nProcesso Autuado Número: " + numProcFormated + "\nProtocolo: "
+ protocoloRecebimento.value + "\nData/Hora do Protocolo: " + dt.toString(dtfBR)
+ "\n\nAtenciosamente,\n\nTribunal Regional Federal da 2a Região";
Correio.enviar(email, "Balcão Virtual: Protocolo de Recebimento", conteudo,
numProcFormated + "-protocolo-" + protocoloRecebimento.value + ".pdf", "application/pdf",
recibo.value);
sent = true;
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Email não enviado", ex);
}
}
SwaggerUtils.log(SoapMNI.class)
.warn("*** Processo: " + numProcFormated + " Petição Inicial protocolada: " + protocoloRecebimento.value
+ " Por: " + usuario + " Email: " + email + (sent ? "" : " (email não enviado)"));
return "Protocolo: " + protocoloRecebimento.value + ", Data: " + dt.toString(dtfBR)
+ (sent ? "" : " (email não enviado)");
}
} |
package cat.nyaa.nyaautils;
import cat.nyaa.nyaautils.exhibition.ExhibitionCommands;
import cat.nyaa.utils.*;
import cat.nyaa.utils.internationalizer.I16rEnchantment;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.Random;
public class CommandHandler extends CommandReceiver<NyaaUtils> {
private NyaaUtils plugin;
public CommandHandler(NyaaUtils plugin, Internationalization i18n) {
super(plugin, i18n);
this.plugin = plugin;
}
@Override
public String getHelpPrefix() {
return "";
}
@SubCommand("exhibition")
public ExhibitionCommands exhibitionCommands;
@SubCommand(value = "addenchsrc", permission = "nu.addenchsrc")
public void commandAddEnchSrc(CommandSender sender, Arguments args) {
ItemStack item = getItemInHand(sender);
if (BasicItemMatcher.containsMatch(NyaaUtils.instance.cfg.enchantSrc, item)) {
sender.sendMessage(I18n._("user.enchant.enchantsrc_already_exists"));
return;
}
BasicItemMatcher matcher = new BasicItemMatcher();
matcher.itemTemplate = item.clone();
matcher.enchantMatch = BasicItemMatcher.MatchingMode.ARBITRARY;
matcher.nameMatch = BasicItemMatcher.MatchingMode.EXACT;
matcher.repairCostMatch = BasicItemMatcher.MatchingMode.EXACT;
NyaaUtils.instance.cfg.enchantSrc.add(matcher);
NyaaUtils.instance.cfg.save();
}
@SubCommand(value = "enchant", permission = "nu.enchant")
public void commandEnchant(CommandSender sender, Arguments args) {
Player p = asPlayer(sender);
if (args.top() == null) {
sender.sendMessage(I18n._("user.enchant.list_ench_header"));
for (Enchantment e : Enchantment.values()) {
if (I16rEnchantment.fromEnchantment(e) != null) {
Message msg = new Message(e.getName() + ": ");
msg.append(I16rEnchantment.fromEnchantment(e).getUnlocalizedName());
msg.append(" " + I18n._("user.enchant.max_level", plugin.cfg.enchantMaxLevel.get(e)));
p.spigot().sendMessage(msg.inner);
} else {
if (e == null || e.getName() == null || e.getName().equalsIgnoreCase("Custom Enchantment")) {
continue;
}
p.sendMessage(e.getName() + ": " + e.getName() + " " +
I18n._("user.enchant.max_level", plugin.cfg.enchantMaxLevel.get(e)));
}
}
sender.sendMessage(I18n._("manual.enchant.usage"));
} else {
ItemStack main = getItemInHand(sender);
ItemStack off = getItemInOffHand(sender);
if (!BasicItemMatcher.containsMatch(NyaaUtils.instance.cfg.enchantSrc, off)) {
sender.sendMessage(I18n._("user.enchant.invalid_src"));
return;
}
if (main.getAmount() != 1 || !(main.getType().getMaxDurability() > 0)) {
sender.sendMessage(I18n._("user.enchant.invalid_item"));
return;
}
String enchStr = args.next().toUpperCase();
Enchantment ench = Enchantment.getByName(enchStr);
if (ench == null) {
sender.sendMessage(I18n._("user.enchant.invalid_ench", enchStr));
return;
}
int level = args.nextInt();
if (level <= 0 || level > plugin.cfg.enchantMaxLevel.get(ench)) {
sender.sendMessage(I18n._("user.enchant.invalid_level"));
return;
}
long cooldown = 0;
if (plugin.enchantCooldown.containsKey(p.getUniqueId())) {
cooldown = plugin.enchantCooldown.get(p.getUniqueId()) + (plugin.cfg.enchantCooldown / 20 * 1000);
}
int chance1 = plugin.cfg.chanceSuccess;
int chance2 = plugin.cfg.chanceModerate;
int chance3 = plugin.cfg.chanceFail;
int chance4 = plugin.cfg.chanceDestroy;
if (cooldown > System.currentTimeMillis()) {
chance1 = 0;
}
int rand = new Random().nextInt(chance1 + chance2 + chance3 + chance4) + 1;
boolean success = true;
boolean deleteItem = true;
if (chance1 > 0 && rand <= chance1) {
success = true;
deleteItem = false;
} else if (chance2 > 0 && rand <= chance1 + chance2) {
success = true;
deleteItem = false;
level = (int) Math.floor(level / 2);
if (level == 0) {
success = false;
}
} else if (chance3 > 0 && rand <= chance1 + chance2 + chance3) {
success = false;
deleteItem = false;
} else if (chance4 > 0 && rand <= chance1 + chance2 + chance3 + chance4) {
success = false;
deleteItem = true;
}
if (off.getType() == Material.ENCHANTED_BOOK) {
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) off.getItemMeta();
int realLvl = meta.getStoredEnchantLevel(ench);
if (level > realLvl
|| (level + main.getEnchantmentLevel(ench) > plugin.cfg.enchantMaxLevel.get(ench))) {
sender.sendMessage(I18n._("user.enchant.invalid_level"));
return;
} else {
meta.removeStoredEnchant(ench);
off.setItemMeta(meta);
if (meta.getStoredEnchants().size() == 0) {
off = new ItemStack(Material.AIR);
}
}
} else {
int realLvl = off.getEnchantmentLevel(ench);
if (level > realLvl
|| (level + main.getEnchantmentLevel(ench) > plugin.cfg.enchantMaxLevel.get(ench))) {
sender.sendMessage(I18n._("user.enchant.invalid_level"));
return;
} else {
off.removeEnchantment(ench);
if (off.getEnchantments().size() == 0) {
off = new ItemStack(Material.AIR);
}
}
}
if (success && level > 0) {
if (main.getType() == Material.ENCHANTED_BOOK) {
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) main.getItemMeta();
int origLvl = meta.getStoredEnchantLevel(ench);
meta.addStoredEnchant(ench, origLvl + level, true);
main.setItemMeta(meta);
} else {
int origLvl = main.getEnchantmentLevel(ench);
main.addUnsafeEnchantment(ench, origLvl + level);
}
}
if (success) {
p.sendMessage(I18n._("user.enchant.success"));
} else {
p.sendMessage(I18n._("user.enchant.fail"));
if (deleteItem) {
main = new ItemStack(Material.AIR);
}
}
plugin.enchantCooldown.put(p.getUniqueId(), System.currentTimeMillis());
p.getInventory().setItemInMainHand(main);
p.getInventory().setItemInOffHand(off);
}
}
@SubCommand(value = "show", permission = "nu.show")
public void commandShow(CommandSender sender, Arguments args) {
ItemStack item = getItemInHand(sender);
new Message("").append(item, I18n._("user.showitem.message", sender.getName())).broadcast();
}
@SubCommand(value = "launch", permission = "nu.launch")
public void commandLaunch(CommandSender sender, Arguments args) {
if (args.top() == null) {
sender.sendMessage(I18n._("user.launch.usage"));
} else {
double yaw = args.nextDouble();
double pitch = args.nextDouble();
double speed = args.nextDouble();
int delay = args.nextInt();
int launchSpeed = args.nextInt();
String pName = args.next();
if (pName == null) {
if (sender instanceof Player) {
pName = sender.getName();
} else {
sender.sendMessage(I18n._("user.launch.missing_name"));
return;
}
}
Player p = Bukkit.getPlayer(pName);
if (p == null) {
sender.sendMessage(I18n._("user.launch.player_not_online", pName));
return;
}
ItemStack chestPlate = p.getInventory().getChestplate();
if (chestPlate == null || chestPlate.getType() != Material.ELYTRA) {
sender.sendMessage(I18n._("user.launch.not_ready_to_fly_sender"));
p.sendMessage(I18n._("user.launch.not_ready_to_fly"));
return;
}
new BukkitRunnable() {
private final static int ELYTRA_DELAY = 3;
final int d = delay;
final Vector v = toVector(yaw, pitch, speed);
final Player player = p;
int current = 0;
@Override
public void run() {
if (player.isOnline()) {
if (current < d) {
current++;
player.setVelocity(v);
if (current == ELYTRA_DELAY) {
player.setGliding(true);
}
} else {
if (!player.isGliding()) {
player.setGliding(true);
}
player.setVelocity(player.getEyeLocation().getDirection().normalize().multiply(launchSpeed));
cancel();
}
} else {
cancel();
}
}
}.runTaskTimer(plugin, 1, 1);
}
}
private static Vector toVector(double yaw, double pitch, double length) {
return new Vector(
Math.cos(yaw / 180 * Math.PI) * Math.cos(pitch / 180 * Math.PI) * length,
Math.sin(pitch / 180 * Math.PI) * length,
Math.sin(yaw / 180 * Math.PI) * Math.cos(pitch / 180 * Math.PI) * length
);
}
@SubCommand(value = "reload", permission = "nu.reload")
public void commandReload(CommandSender sender, Arguments args) {
NyaaUtils p = NyaaUtils.instance;
p.reloadConfig();
p.cfg.deserialize(p.getConfig());
p.cfg.serialize(p.getConfig());
p.saveConfig();
p.i18n.reset();
p.i18n.load(p.cfg.language);
}
@SubCommand(value = "lp", permission = "nu.lootprotect")
public void commandLootProtectToggle(CommandSender sender, Arguments args) {
Player p = asPlayer(sender);
if (plugin.lpListener.toggleStatus(p.getUniqueId())) {
p.sendMessage(I18n._("user.lp.turned_on"));
} else {
p.sendMessage(I18n._("user.lp.turned_off"));
}
p.sendMessage(I18n._("user.lp.mode_" + plugin.cfg.lootProtectMode.name()));
}
@SubCommand(value = "prefix", permission = "nu.prefix")
public void commandPrefix(CommandSender sender, Arguments args) {
if (!(args.length() > 1)) {
msg(sender, "manual.prefix.usage");
return;
}
Player p = asPlayer(sender);
String prefix = args.next().replace("§", "");
for (String k : plugin.cfg.custom_fixes_prefix_disabledFormattingCodes) {
if (prefix.toUpperCase().contains("&" + k.toUpperCase())) {
msg(sender, "user.warn.blocked_format_codes", "&" + k);
return;
}
}
prefix = ChatColor.translateAlternateColorCodes('&', prefix);
for (String k : plugin.cfg.custom_fixes_prefix_blockedWords) {
if (ChatColor.stripColor(prefix).toUpperCase().contains(k.toUpperCase())) {
msg(sender, "user.warn.blocked_words", k);
return;
}
}
if (ChatColor.stripColor(prefix).length() > plugin.cfg.custom_fixes_prefix_maxlength) {
msg(sender, "user.prefix.prefix_too_long", plugin.cfg.custom_fixes_prefix_maxlength);
return;
}
if (plugin.cfg.custom_fixes_prefix_expCost > 0 &&
!(p.getTotalExperience() >= plugin.cfg.custom_fixes_prefix_expCost)) {
msg(sender, "user.warn.not_enough_exp");
return;
}
if (plugin.cfg.custom_fixes_prefix_moneyCost > 0 &&
!plugin.vaultUtil.enoughMoney(p, plugin.cfg.custom_fixes_prefix_moneyCost)) {
msg(sender, "user.warn.no_enough_money");
return;
}
ExpUtil.setTotalExperience(p, p.getTotalExperience() - plugin.cfg.custom_fixes_prefix_expCost);
plugin.vaultUtil.withdraw(p, plugin.cfg.custom_fixes_prefix_moneyCost);
plugin.vaultUtil.setPlayerPrefix(p, ChatColor.translateAlternateColorCodes('&', plugin.cfg.custom_fixes_prefix_format).replace("{prefix}", prefix));
msg(sender, "user.prefix.success", prefix);
}
@SubCommand(value = "suffix", permission = "nu.suffix")
public void commandSuffix(CommandSender sender, Arguments args) {
if (!(args.length() > 1)) {
msg(sender, "manual.suffix.usage");
return;
}
Player p = asPlayer(sender);
String suffix = args.next().replace("§", "");
for (String k : plugin.cfg.custom_fixes_suffix_disabledFormattingCodes) {
if (suffix.toUpperCase().contains("&" + k.toUpperCase())) {
msg(sender, "user.warn.blocked_format_codes", "&" + k);
return;
}
}
suffix = ChatColor.translateAlternateColorCodes('&', suffix);
for (String k : plugin.cfg.custom_fixes_suffix_blockedWords) {
if (ChatColor.stripColor(suffix).toUpperCase().contains(k.toUpperCase())) {
msg(sender, "user.warn.blocked_words", k);
return;
}
}
if (ChatColor.stripColor(suffix).length() > plugin.cfg.custom_fixes_suffix_maxlength) {
msg(sender, "user.suffix.suffix_too_long", plugin.cfg.custom_fixes_suffix_maxlength);
return;
}
if (plugin.cfg.custom_fixes_suffix_expCost > 0 &&
!(p.getTotalExperience() >= plugin.cfg.custom_fixes_suffix_expCost)) {
msg(sender, "user.warn.not_enough_exp");
return;
}
if (plugin.cfg.custom_fixes_suffix_moneyCost > 0 &&
!plugin.vaultUtil.enoughMoney(p, plugin.cfg.custom_fixes_suffix_moneyCost)) {
msg(sender, "user.warn.no_enough_money");
return;
}
plugin.vaultUtil.withdraw(p, plugin.cfg.custom_fixes_suffix_moneyCost);
ExpUtil.setTotalExperience(p, p.getTotalExperience() - plugin.cfg.custom_fixes_suffix_expCost);
plugin.vaultUtil.setPlayerSuffix(p, ChatColor.translateAlternateColorCodes('&', plugin.cfg.custom_fixes_suffix_format).replace("{suffix}", suffix));
msg(sender, "user.suffix.success", suffix);
}
@SubCommand(value = "resetprefix", permission = "nu.prefix")
public void commandResetPrefix(CommandSender sender, Arguments args) {
Player p = asPlayer(sender);
if (!(plugin.vaultUtil.getPlayerPrefix(p).length() > 0)) {
return;
}
plugin.vaultUtil.setPlayerPrefix(p, "");
msg(sender, "user.resetprefix.success");
}
@SubCommand(value = "resetsuffix", permission = "nu.suffix")
public void commandResetSuffix(CommandSender sender, Arguments args) {
Player p = asPlayer(sender);
if (!(plugin.vaultUtil.getPlayerSuffix(p).length() > 0)) {
return;
}
plugin.vaultUtil.setPlayerSuffix(p, "");
msg(sender, "user.resetsuffix.success");
}
@SubCommand(value = "format", permission = "nu.format")
public void commandFormat(CommandSender sender, Arguments args) {
msg(sender, "user.format.message");
}
} |
package com.jcabi.ssh;
import com.jcabi.aspects.RetryOnFailure;
import com.jcabi.aspects.Tv;
import com.jcabi.log.Logger;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.Validate;
@ToString
@EqualsAndHashCode(of = { "addr", "port", "login", "key" })
@SuppressWarnings("PMD.TooManyMethods")
public final class SSH implements Shell {
/**
* Default SSH port.
*/
public static final int PORT = 22;
/**
* IP address of the server.
*/
private final transient String addr;
/**
* Port to use.
*/
private final transient int port;
/**
* User name.
*/
private final transient String login;
/**
* Private SSH key.
*/
private final transient String key;
/**
* Constructor.
* @param adr IP address
* @param user Login
* @param priv Private SSH key
* @throws IOException If fails
* @since 1.4
*/
public SSH(final String adr, final String user, final URL priv)
throws IOException {
this(adr, SSH.PORT, user, priv);
}
/**
* Constructor.
* @param adr IP address
* @param user Login
* @param priv Private SSH key
* @throws IOException If fails
* @since 1.4
*/
public SSH(final InetAddress adr, final String user, final URL priv)
throws IOException {
this(adr, SSH.PORT, user, priv);
}
/**
* Constructor.
* @param adr IP address
* @param user Login
* @param priv Private SSH key
* @throws UnknownHostException If fails
* @since 1.4
*/
public SSH(final String adr, final String user, final String priv)
throws UnknownHostException {
this(adr, SSH.PORT, user, priv);
}
/**
* Constructor.
* @param adr IP address
* @param user Login
* @param priv Private SSH key
* @throws UnknownHostException If fails
* @since 1.4
*/
public SSH(final InetAddress adr, final String user, final String priv)
throws UnknownHostException {
this(adr.getCanonicalHostName(), SSH.PORT, user, priv);
}
/**
* Constructor.
* @param adr IP address
* @param prt Port of server
* @param user Login
* @param priv Private SSH key
* @throws IOException If fails
* @checkstyle ParameterNumberCheck (6 lines)
* @since 1.4
*/
public SSH(final String adr, final int prt,
final String user, final URL priv) throws IOException {
this(adr, prt, user, IOUtils.toString(priv));
}
/**
* Constructor.
* @param adr IP address
* @param prt Port of server
* @param user Login
* @param priv Private SSH key
* @throws IOException If fails
* @checkstyle ParameterNumberCheck (6 lines)
* @since 1.4
*/
public SSH(final InetAddress adr, final int prt,
final String user, final URL priv) throws IOException {
this(adr.getCanonicalHostName(), prt, user, IOUtils.toString(priv));
}
/**
* Constructor.
* @param adr IP address
* @param prt Port of server
* @param user Login
* @param priv Private SSH key
* @throws UnknownHostException If fails
* @checkstyle ParameterNumberCheck (6 lines)
*/
public SSH(final String adr, final int prt,
final String user, final String priv) throws UnknownHostException {
this.addr = InetAddress.getByName(adr).getHostAddress();
Validate.matchesPattern(
this.addr,
"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}",
"Invalid IP address of the server `%s`",
this.addr
);
this.login = user;
Validate.notEmpty(this.login, "user name can't be empty");
this.key = priv;
this.port = prt;
}
// @checkstyle ParameterNumberCheck (5 lines)
@Override
public int exec(final String command, final InputStream stdin,
final OutputStream stdout, final OutputStream stderr)
throws IOException {
return new Execution.Default(
command, stdin, stdout, stderr, this.session()
).exec();
}
/**
* Escape SSH argument.
* @param arg Argument to escape
* @return Escaped
*/
public static String escape(final String arg) {
return String.format("'%s'", arg.replace("'", "'\\''"));
}
/**
* Create and return a session, connected.
* @return JSch session
* @throws IOException If some IO problem inside
*/
@RetryOnFailure(
attempts = Tv.SEVEN,
delay = 1,
unit = TimeUnit.MINUTES,
verbose = false,
randomize = true,
types = IOException.class
)
private Session session() throws IOException {
try {
JSch.setConfig("StrictHostKeyChecking", "no");
JSch.setLogger(new JschLogger());
final JSch jsch = new JSch();
final File file = File.createTempFile("jcabi-ssh", ".key");
FileUtils.forceDeleteOnExit(file);
FileUtils.write(
file,
this.key.replaceAll("\r", "")
.replaceAll("\n\\s+|\n{2,}", "\n")
.trim(),
CharEncoding.UTF_8
);
jsch.setHostKeyRepository(new EasyRepo());
jsch.addIdentity(file.getAbsolutePath());
Logger.debug(
this,
"Opening SSH session to %s@%s:%s (%d bytes in RSA key)...",
this.login, this.addr, this.port,
file.length()
);
final Session session = jsch.getSession(
this.login, this.addr, this.port
);
session.setServerAliveInterval(
(int) TimeUnit.SECONDS.toMillis((long) Tv.TEN)
);
session.setServerAliveCountMax(Tv.MILLION);
session.connect();
FileUtils.deleteQuietly(file);
return session;
} catch (final JSchException ex) {
throw new IOException(ex);
}
}
} |
package connector;
import java.io.IOException;
import java.util.Arrays;
import org.json.simple.JSONObject;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
public class MONGODB {
private static MongoCredential credential;
private static MongoClient mongoClient;
private static JSONObject jsonProp;
public static DB GetMongoDB() throws Exception{
try {
if(jsonProp == null)
jsonProp = getPropValues();
/*if(credential == null)
credential = MongoCredential.createMongoCRCredential(
jsonProp.get("db_user").toString(),
jsonProp.get("db_name").toString(),
jsonProp.get("db_pass").toString().toCharArray());*/
if(mongoClient == null)
mongoClient = new MongoClient(new ServerAddress(
jsonProp.get("db_host").toString(),
Integer.parseInt(jsonProp.get("db_port").toString())), Arrays.asList(credential));
return mongoClient.getDB(jsonProp.get("db_name").toString());
} catch (Throwable e) {
e.printStackTrace();
throw new Exception(e.toString());
}
}
@SuppressWarnings("unchecked")
private static JSONObject getPropValues() throws IOException {
JSONObject resultObj = new JSONObject();
/*
String propFileName = "config.properties";
Properties prop = new Properties();
prop.load(new FileInputStream(propFileName));
JSONObject resultObj = new JSONObject();
resultObj.put("db_host", prop.getProperty("db_host"));
resultObj.put("db_port", prop.getProperty("db_port"));
resultObj.put("db_user", prop.getProperty("db_user"));
resultObj.put("db_pass", prop.getProperty("db_pass"));
resultObj.put("db_name", prop.getProperty("db_name"));
*/
resultObj.put("db_host", "localhost");
resultObj.put("db_port", "27017");
resultObj.put("db_user", "labf");
resultObj.put("db_pass", "udinus");
resultObj.put("db_name", "semanticwebservice");
return resultObj;
}
} |
package cn.momia.mapi.api.v1;
import cn.momia.api.base.MetaUtil;
import cn.momia.api.user.leader.Leader;
import cn.momia.common.api.http.MomiaHttpResponse;
import cn.momia.api.product.comment.Comment;
import cn.momia.api.product.comment.PagedComments;
import cn.momia.common.webapp.config.Configuration;
import cn.momia.image.api.ImageFile;
import cn.momia.api.deal.DealServiceApi;
import cn.momia.api.product.ProductServiceApi;
import cn.momia.api.product.Product;
import cn.momia.api.product.sku.Sku;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping("/v1/product")
public class ProductV1Api extends AbstractV1Api {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductV1Api.class);
@RequestMapping(value = "/weekend", method = RequestMethod.GET)
public MomiaHttpResponse listByWeekend(@RequestParam(value = "city") int cityId, @RequestParam int start) {
if (cityId < 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(processPagedProducts(ProductServiceApi.PRODUCT.listByWeekend(cityId, start, Configuration.getInt("PageSize.Product")), IMAGE_MIDDLE));
}
@RequestMapping(value = "/month", method = RequestMethod.GET)
public MomiaHttpResponse listByMonth(@RequestParam(value = "city") int cityId, @RequestParam int month) {
if (cityId < 0 || month <= 0 || month > 12) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(processGroupedProducts(ProductServiceApi.PRODUCT.listByMonth(cityId, month), IMAGE_MIDDLE));
}
@RequestMapping(value = "/leader", method = RequestMethod.GET)
public MomiaHttpResponse listNeedLeader(@RequestParam(value = "city") int cityId, @RequestParam int start) {
if (cityId < 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(processPagedProducts(ProductServiceApi.PRODUCT.listNeedLeader(cityId, start, Configuration.getInt("PageSize.Product")), IMAGE_MIDDLE));
}
@RequestMapping(value = "/sku/leader", method = RequestMethod.GET)
public MomiaHttpResponse listSkusNeedLeader(@RequestParam(value = "pid") long id) {
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
Product product = ProductServiceApi.PRODUCT.get(id, Product.Type.BASE);
List<Sku> skus = ProductServiceApi.SKU.listWithLeader(id);
Set<Long> leaderUserIds = new HashSet<Long>();
for (Sku sku : skus) {
if (sku.getLeaderUserId() > 0) leaderUserIds.add(sku.getLeaderUserId());
}
List<Leader> leaders = UserServiceApi.LEADER.list(leaderUserIds);
Map<Long, Leader> leadersMap = new HashMap<Long, Leader>();
for (Leader leader : leaders) leadersMap.put(leader.getUserId(), leader);
for (Sku sku : skus) {
if (!sku.isNeedLeader()) {
sku.setLeaderInfo("");
} else {
Leader leader = leadersMap.get(sku.getLeaderUserId());
if (leader == null || StringUtils.isBlank(leader.getName())) sku.setLeaderInfo("");
else sku.setLeaderInfo(leader.getName() + "");
}
}
JSONObject productSkusJson = new JSONObject();
productSkusJson.put("product", processProduct(product, IMAGE_MIDDLE));
productSkusJson.put("skus", skus);
return MomiaHttpResponse.SUCCESS(productSkusJson);
}
@RequestMapping(method = RequestMethod.GET)
public MomiaHttpResponse get(@RequestParam(defaultValue = "") String utoken, @RequestParam long id, HttpServletRequest request) {
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
Product product = processProduct(ProductServiceApi.PRODUCT.get(id, Product.Type.FULL), utoken, getClientType(request));
JSONObject productJson = JSON.parseObject(JSON.toJSONString(product));
try {
List<String> avatars = DealServiceApi.ORDER.listCustomerAvatars(id, Configuration.getInt("PageSize.ProductCustomer"));
productJson.put("customers", buildCustomers(avatars, product.getStock()));
productJson.put("comments", listComments(id, 0, Configuration.getInt("PageSize.ProductDetailComment")));
long userId = StringUtils.isBlank(utoken) ? 0 : UserServiceApi.USER.get(utoken).getId();
if (ProductServiceApi.PRODUCT.favored(userId, id)) productJson.put("favored", true);
} catch (Exception e) {
LOGGER.error("exception!!", e);
}
return MomiaHttpResponse.SUCCESS(productJson);
}
private PagedComments listComments(long id, int start, int count) {
PagedComments pagedComments = ProductServiceApi.COMMENT.list(id, start, count);
List<Long> userIds = new ArrayList<Long>();
for (Comment comment : pagedComments.getList()) userIds.add(comment.getUserId());
List<User> users = UserServiceApi.USER.list(userIds, User.Type.MINI);
Map<Long, User> usersMap = new HashMap<Long, User>();
for (User user : users) usersMap.put(user.getId(), user);
for (Comment comment : pagedComments.getList()) {
User user = usersMap.get(comment.getUserId());
if (user == null || !user.exists()) {
comment.setNickName("");
comment.setAvatar("");
} else {
comment.setNickName(user.getNickName());
comment.setAvatar(ImageFile.smallUrl(user.getAvatar()));
}
}
return processPagedComments(pagedComments);
}
private JSONObject buildCustomers(List<String> avatars, int stock) {
JSONObject customersJson = new JSONObject();
customersJson.put("text", "" + ((stock > 0 && stock <= Configuration.getInt("Product.StockAlert")) ? "" + stock + "" : ""));
customersJson.put("avatars", processAvatars(avatars));
return customersJson;
}
@RequestMapping(value = "/detail", method = RequestMethod.GET)
public MomiaHttpResponse getDetail(@RequestParam long id) {
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(processProductDetail(ProductServiceApi.PRODUCT.getDetail(id)));
}
@RequestMapping(value = "/order", method = RequestMethod.GET)
public MomiaHttpResponse placeOrder(@RequestParam String utoken, @RequestParam long id) {
if(StringUtils.isBlank(utoken) || id <= 0) return MomiaHttpResponse.BAD_REQUEST;
JSONObject placeOrderJson = new JSONObject();
placeOrderJson.put("contacts", UserServiceApi.USER.getContacts(utoken));
List<Sku> skus = ProductServiceApi.SKU.list(id, Sku.Status.AVALIABLE);
placeOrderJson.put("places", extractPlaces(skus));
placeOrderJson.put("skus", skus);
return MomiaHttpResponse.SUCCESS(placeOrderJson);
}
private JSONArray extractPlaces(List<Sku> skus) {
JSONArray placesJson = new JSONArray();
Set<Integer> placeIds = new HashSet<Integer>();
for (Sku sku : skus) {
int placeId = sku.getPlaceId();
if (placeId <= 0 || placeIds.contains(placeId)) continue;
placeIds.add(placeId);
JSONObject placeJson = new JSONObject();
placeJson.put("id", placeId);
placeJson.put("name", sku.getPlaceName());
placeJson.put("region", MetaUtil.getRegionName(sku.getRegionId()));
placeJson.put("address", sku.getAddress());
placesJson.add(placeJson);
}
return placesJson;
}
@RequestMapping(value = "/playmate", method = RequestMethod.GET)
public MomiaHttpResponse listPlaymates(@RequestParam long id) {
if (id <= 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(processPlaymates(DealServiceApi.ORDER.listPlaymates(id, Configuration.getInt("PageSize.PlaymateSku"))));
}
@RequestMapping(value = "/favor", method = RequestMethod.POST)
public MomiaHttpResponse favor(@RequestParam String utoken, @RequestParam long id){
if (StringUtils.isBlank(utoken) || id <= 0) return MomiaHttpResponse.BAD_REQUEST;
User user = UserServiceApi.USER.get(utoken);
ProductServiceApi.PRODUCT.favor(user.getId(), id);
return MomiaHttpResponse.SUCCESS;
}
@RequestMapping(value = "/unfavor", method = RequestMethod.POST)
public MomiaHttpResponse unfavor(@RequestParam String utoken, @RequestParam long id){
if (StringUtils.isBlank(utoken) || id <= 0) return MomiaHttpResponse.BAD_REQUEST;
User user = UserServiceApi.USER.get(utoken);
ProductServiceApi.PRODUCT.unfavor(user.getId(), id);
return MomiaHttpResponse.SUCCESS;
}
@RequestMapping(value = "/comment", method = RequestMethod.POST)
public MomiaHttpResponse addComment(@RequestParam String utoken, @RequestParam String comment) {
if (StringUtils.isBlank(utoken) || StringUtils.isBlank(comment)) return MomiaHttpResponse.BAD_REQUEST;
User user = UserServiceApi.USER.get(utoken);
JSONObject commentJson = JSON.parseObject(comment);
commentJson.put("userId", user.getId());
long orderId = commentJson.getLong("orderId");
long productId = commentJson.getLong("productId");
long skuId = commentJson.getLong("skuId");
if (!DealServiceApi.ORDER.check(utoken, orderId, productId, skuId)) return MomiaHttpResponse.FAILED("");
ProductServiceApi.COMMENT.add(commentJson);
return MomiaHttpResponse.SUCCESS;
}
@RequestMapping(value = "/comment", method = RequestMethod.GET)
public MomiaHttpResponse listComments(@RequestParam long id, @RequestParam int start) {
if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST;
return MomiaHttpResponse.SUCCESS(listComments(id, start, Configuration.getInt("PageSize.ProductComment")));
}
} |
package de.prob2.ui;
import java.io.File;
import java.util.Locale;
import java.util.Optional;
import java.util.ResourceBundle;
import com.google.inject.Guice;
import com.google.inject.Injector;
import de.prob.cli.ProBInstanceProvider;
import de.prob.scripting.Api;
import de.prob2.ui.config.Config;
import de.prob2.ui.config.RuntimeOptions;
import de.prob2.ui.internal.ProB2Module;
import de.prob2.ui.internal.StageManager;
import de.prob2.ui.internal.StopActions;
import de.prob2.ui.persistence.UIPersistence;
import de.prob2.ui.prob2fx.CurrentProject;
import de.prob2.ui.prob2fx.CurrentTrace;
import de.prob2.ui.project.ProjectManager;
import de.prob2.ui.project.runconfigurations.Runconfiguration;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.application.Preloader;
import javafx.event.Event;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProB2 extends Application {
private static final Logger LOGGER = LoggerFactory.getLogger(ProB2.class);
private RuntimeOptions runtimeOptions;
private Injector injector;
private ResourceBundle bundle;
private Stage primaryStage;
public static void main(String... args) {
Application.launch(args);
}
@Override
public void init() {
runtimeOptions = parseRuntimeOptions(this.getParameters().getRaw().toArray(new String[0]));
if (runtimeOptions.isLoadConfig()) {
final Locale localeOverride = Config.getLocaleOverride();
if (localeOverride != null) {
Locale.setDefault(localeOverride);
}
}
ProB2Module module = new ProB2Module(runtimeOptions);
Platform.runLater(() -> {
injector = Guice.createInjector(com.google.inject.Stage.PRODUCTION, module);
bundle = injector.getInstance(ResourceBundle.class);
injector.getInstance(StopActions.class)
.add(() -> injector.getInstance(ProBInstanceProvider.class).shutdownAll());
StageManager stageManager = injector.getInstance(StageManager.class);
Thread.setDefaultUncaughtExceptionHandler((thread, exc) -> {
LOGGER.error("Uncaught exception on thread {}", thread, exc);
Platform.runLater(() -> {
final String message = String.format(
"An internal exception occurred and was not caught. This is probably a bug.%nThread: %s",
thread);
final Alert alert = stageManager.makeExceptionAlert(Alert.AlertType.ERROR, message, exc);
alert.setHeaderText("Uncaught internal exception");
alert.show();
});
});
final Api api = injector.getInstance(Api.class);
LOGGER.info("probcli version: {}", api.getVersion());
// Disable subscribing to variables by default, StatesView handles all subscribing itself
api.setLoadVariablesByDefault(false);
// Load config file
injector.getInstance(Config.class);
CurrentProject currentProject = injector.getInstance(CurrentProject.class);
currentProject.addListener((observable, from, to) -> this.updateTitle());
currentProject.savedProperty().addListener((observable, from, to) -> this.updateTitle());
CurrentTrace currentTrace = injector.getInstance(CurrentTrace.class);
currentTrace.addListener((observable, from, to) -> this.updateTitle());
});
}
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.updateTitle();
Parent root = injector.getInstance(MainController.class);
Scene mainScene = new Scene(root, 1024, 768);
primaryStage.setScene(mainScene);
StageManager stageManager = injector.getInstance(StageManager.class);
stageManager.registerMainStage(primaryStage, this.getClass().getName());
CurrentProject currentProject = injector.getInstance(CurrentProject.class);
primaryStage.setOnCloseRequest(event -> handleCloseRequest(event, currentProject, stageManager));
this.notifyPreloader(new Preloader.ProgressNotification(100));
this.primaryStage.show();
UIPersistence uiPersistence = injector.getInstance(UIPersistence.class);
uiPersistence.open();
if (runtimeOptions.getProject() != null) {
injector.getInstance(ProjectManager.class).openProject(new File(runtimeOptions.getProject()));
}
if (runtimeOptions.getRunconfig() != null) {
Runconfiguration found = null;
for (final Runconfiguration r : currentProject.getRunconfigurations()) {
if (r.getName().equals(runtimeOptions.getRunconfig())) {
found = r;
break;
}
}
if (found == null) {
stageManager
.makeAlert(Alert.AlertType.ERROR, String.format("No runconfiguration %s exists in project %s.",
runtimeOptions.getRunconfig(), currentProject.getName()))
.show();
} else {
currentProject.startAnimation(found);
}
}
}
private void updateTitle() {
final CurrentProject currentProject = injector.getInstance(CurrentProject.class);
final CurrentTrace currentTrace = injector.getInstance(CurrentTrace.class);
final StringBuilder title = new StringBuilder();
if (currentProject.getCurrentRunconfiguration() != null) {
title.append(currentProject.getCurrentRunconfiguration());
if (currentTrace.exists()) {
final File modelFile = currentTrace.getModel().getModelFile();
if (modelFile != null) {
title.append(" (");
title.append(modelFile.getName());
title.append(')');
}
}
title.append(" - ");
}
if (currentProject.exists()) {
title.append(currentProject.getName());
title.append(" - ");
}
title.append("ProB 2.0");
if (!currentProject.isSaved()) {
title.append('*');
}
this.primaryStage.setTitle(title.toString());
}
private static IllegalStateException die(final String message, final int exitCode) {
System.err.println(message);
Platform.exit();
System.exit(exitCode);
return new IllegalStateException(message);
}
private static RuntimeOptions parseRuntimeOptions(final String[] args) {
LOGGER.info("Parsing arguments: {}", (Object) args);
final Options options = new Options();
options.addOption(null, "project", true, "Open the specified project on startup.");
options.addOption(null, "runconfig", true,
"Run the specified run configuration on startup. Requires a project to be loaded first (using --open-project).");
options.addOption(null, "no-load-config", false,
"Do not load the user config file, use the default config instead.");
options.addOption(null, "no-save-config", false, "Do not save the user config file.");
final CommandLineParser clParser = new PosixParser();
final CommandLine cl;
try {
cl = clParser.parse(options, args);
} catch (ParseException e) {
LOGGER.error("Failed to parse command line", e);
throw die(e.getLocalizedMessage(), 2);
}
LOGGER.info("Parsed command line: args {}, options {}", cl.getArgs(), cl.getOptions());
if (!cl.getArgList().isEmpty()) {
throw die("Positional arguments are not allowed: " + cl.getArgList(), 2);
}
if (cl.hasOption("runconfig") && !cl.hasOption("project")) {
throw die("Invalid combination of options: --runconfig requires --project", 2);
}
final RuntimeOptions runtimeOpts = new RuntimeOptions(cl.getOptionValue("project"),
cl.getOptionValue("runconfig"), !cl.hasOption("no-load-config"), !cl.hasOption("no-save-config"));
LOGGER.info("Created runtime options: {}", runtimeOpts);
return runtimeOpts;
}
@Override
public void stop() {
if (injector != null) {
injector.getInstance(StopActions.class).run();
}
}
private void handleCloseRequest(Event event, CurrentProject currentProject, StageManager stageManager) {
if (!currentProject.isSaved()) {
ButtonType save = new ButtonType(bundle.getString("common.save"), ButtonBar.ButtonData.YES);
ButtonType doNotSave = new ButtonType(bundle.getString("common.doNotSave"), ButtonBar.ButtonData.NO);
Alert alert = stageManager.makeAlert(
Alert.AlertType.CONFIRMATION,
String.format(bundle.getString("common.unsavedProjectChanges.message"), currentProject.getName()),
save, ButtonType.CANCEL, doNotSave);
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get().equals(ButtonType.CANCEL)) {
event.consume();
} else if (result.isPresent() && result.get().equals(save)) {
injector.getInstance(ProjectManager.class).saveCurrentProject();
Platform.exit();
}
} else {
Platform.exit();
}
}
} |
package cn.momia.mapi.api.v1;
import cn.momia.mapi.common.config.Configuration;
import cn.momia.mapi.common.http.MomiaHttpParamBuilder;
import cn.momia.mapi.common.http.MomiaHttpRequest;
import cn.momia.mapi.common.http.MomiaHttpResponseCollector;
import cn.momia.mapi.common.img.ImageFile;
import cn.momia.mapi.web.response.ResponseMessage;
import cn.momia.service.product.api.ProductServiceApi;
import cn.momia.service.product.api.product.Product;
import cn.momia.service.product.api.sku.Sku;
import cn.momia.service.user.api.UserServiceApi;
import cn.momia.service.user.api.user.User;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/v1/product")
public class ProductV1Api extends AbstractV1Api {
@Autowired private ProductServiceApi productServiceApi;
@Autowired private UserServiceApi userServiceApi;
@RequestMapping(value = "/weekend", method = RequestMethod.GET)
public ResponseMessage listByWeekend(@RequestParam(value = "city") int cityId, @RequestParam int start) {
if (cityId < 0 || start < 0) return ResponseMessage.BAD_REQUEST;
return ResponseMessage.SUCCESS(processPagedProducts(productServiceApi.PRODUCT.listByWeekend(cityId, start, Configuration.getInt("PageSize.Product"))));
}
@RequestMapping(value = "/month", method = RequestMethod.GET)
public ResponseMessage listByMonth(@RequestParam(value = "city") int cityId, @RequestParam int month) {
if (cityId < 0 || month <= 0 || month > 12) return ResponseMessage.BAD_REQUEST;
return ResponseMessage.SUCCESS(processGroupedProducts(productServiceApi.PRODUCT.listByMonth(cityId, month)));
}
@RequestMapping(value = "/leader", method = RequestMethod.GET)
public ResponseMessage listNeedLeader(@RequestParam(value = "city") int cityId, @RequestParam int start) {
if (cityId < 0 || start < 0) return ResponseMessage.BAD_REQUEST;
return ResponseMessage.SUCCESS(processPagedProducts(productServiceApi.PRODUCT.listNeedLeader(cityId, start, Configuration.getInt("PageSize.Product"))));
}
@RequestMapping(value = "/sku/leader", method = RequestMethod.GET)
public ResponseMessage listSkusNeedLeader(@RequestParam(value = "pid") long id) {
if (id <= 0) return ResponseMessage.BAD_REQUEST;
Product product = productServiceApi.PRODUCT.get(id, false);
List<Sku> skus = productServiceApi.SKU.listWithLeader(id);
JSONObject productSkusJson = new JSONObject();
productSkusJson.put("product", processProduct(product));
productSkusJson.put("skus", skus);
return ResponseMessage.SUCCESS(productSkusJson);
}
@RequestMapping(method = RequestMethod.GET)
public ResponseMessage get(@RequestParam(defaultValue = "") String utoken, @RequestParam long id) {
if (id <= 0) return ResponseMessage.BAD_REQUEST;
List<MomiaHttpRequest> requests = buildProductRequests(utoken, id);
return executeRequests(requests, new Function<MomiaHttpResponseCollector, Object>() {
@Override
public Object apply(MomiaHttpResponseCollector collector) {
JSONObject productJson = (JSONObject) productFunc.apply(collector.getResponse("product"));
productJson.put("customers", processCustomers((JSONObject) collector.getResponse("customers"), productJson.getInteger("stock")));
boolean opened = productJson.getBoolean("opened");
if (!opened) productJson.put("soldOut", true);
return productJson;
}
});
}
private List<MomiaHttpRequest> buildProductRequests(String utoken, long productId) {
List<MomiaHttpRequest> requests = new ArrayList<MomiaHttpRequest>();
requests.add(buildProductRequest(utoken, productId));
requests.add(buildProductCustomersRequest(productId));
return requests;
}
private MomiaHttpRequest buildProductRequest(String utoken, long productId) {
MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder().add("utoken", utoken);
return MomiaHttpRequest.GET("product", true, url("product", productId), builder.build());
}
private MomiaHttpRequest buildProductCustomersRequest(long productId) {
MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
.add("start", 0)
.add("count", Configuration.getInt("PageSize.ProductCustomer"));
return MomiaHttpRequest.GET("customers", false, url("product", productId, "customer"), builder.build());
}
private JSONObject processCustomers(JSONObject customersJson, int stock) {
if (customersJson != null) {
if (stock > 0 && stock <= Configuration.getInt("Product.StockAlert"))
customersJson.put("text", customersJson.getString("text") + "" + stock + "");
JSONArray avatarsJson = customersJson.getJSONArray("avatars");
if (avatarsJson != null) {
for (int i = 0; i < avatarsJson.size(); i++) {
String avatar = avatarsJson.getString(i);
avatarsJson.set(i, ImageFile.url(avatar));
}
}
}
return customersJson;
}
@RequestMapping(value = "/detail", method = RequestMethod.GET)
public ResponseMessage getDetail(@RequestParam long id) {
if (id <= 0) return ResponseMessage.BAD_REQUEST;
MomiaHttpRequest request = MomiaHttpRequest.GET(url("product", id, "detail"));
return executeRequest(request);
}
@RequestMapping(value = "/order", method = RequestMethod.GET)
public ResponseMessage placeOrder(@RequestParam String utoken, @RequestParam long id) {
if(StringUtils.isBlank(utoken) || id <= 0) return ResponseMessage.BAD_REQUEST;
final List<MomiaHttpRequest> requests = buildProductOrderRequests(id, utoken);
return executeRequests(requests, new Function<MomiaHttpResponseCollector, Object>() {
@Override
public Object apply(MomiaHttpResponseCollector collector) {
JSONObject placeOrderJson = new JSONObject();
placeOrderJson.put("contacts", collector.getResponse("contacts"));
placeOrderJson.put("skus", collector.getResponse("skus"));
return placeOrderJson;
}
});
}
private List<MomiaHttpRequest> buildProductOrderRequests(long productId, String utoken) {
List<MomiaHttpRequest> requests = new ArrayList<MomiaHttpRequest>();
requests.add(buildContactsRequest(utoken));
requests.add(buildProductSkusRequest(productId));
return requests;
}
private MomiaHttpRequest buildContactsRequest(String utoken) {
MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder().add("utoken", utoken);
MomiaHttpRequest request = MomiaHttpRequest.GET("contacts", true, url("user/contacts"), builder.build());
return request;
}
private MomiaHttpRequest buildProductSkusRequest(long productId) {
return MomiaHttpRequest.GET("skus", true, url("product", productId, "sku"));
}
@RequestMapping(value = "/playmate", method = RequestMethod.GET)
public ResponseMessage listPlaymates(@RequestParam long id) {
if (id <= 0) return ResponseMessage.BAD_REQUEST;
MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
.add("start", 0)
.add("count", Configuration.getInt("PageSize.PlaymateSku"));
MomiaHttpRequest request = MomiaHttpRequest.GET(url("product", id, "playmate"), builder.build());
return executeRequest(request, new Function<Object, Object>() {
@Override
public Object apply(Object data) {
JSONArray skusPlaymatesJson = (JSONArray) data;
for (int i = 0; i < skusPlaymatesJson.size(); i++) {
JSONObject skuPlaymatesJson = skusPlaymatesJson.getJSONObject(i);
JSONArray playmatesJson = skuPlaymatesJson.getJSONArray("playmates");
for (int j = 0; j < playmatesJson.size(); j++) {
JSONObject playmateJson = playmatesJson.getJSONObject(j);
playmateJson.put("avatar", ImageFile.url(playmateJson.getString("avatar")));
}
}
return data;
}
});
}
@RequestMapping(value = "/favor", method = RequestMethod.POST)
public ResponseMessage favor(@RequestParam String utoken, @RequestParam long id){
if (StringUtils.isBlank(utoken) || id <= 0) return ResponseMessage.BAD_REQUEST;
User user = userServiceApi.USER.get(utoken);
productServiceApi.PRODUCT.favor(user.getId(), id);
return ResponseMessage.SUCCESS;
}
@RequestMapping(value = "/unfavor", method = RequestMethod.POST)
public ResponseMessage unFavor(@RequestParam String utoken, @RequestParam long id){
if (StringUtils.isBlank(utoken) || id <= 0) return ResponseMessage.BAD_REQUEST;
User user = userServiceApi.USER.get(utoken);
productServiceApi.PRODUCT.unfavor(user.getId(), id);
return ResponseMessage.SUCCESS;
}
} |
package es.uniovi.asw;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import es.uniovi.parser.*;
public class Cli {
private static final Logger log = Logger.getLogger(Cli.class.getName());
private String[] args = null;
private Options options = new Options();
public Cli(String[] args) {
this.args = args;
options.addOption("h", "help", false, "show help.");
options.addOption("v", "var", true, "Here you can set parameter .");
options.addOption("p", "parse", true, "Name of the exel file .");
}
public void parse() {
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
if (cmd.hasOption("h"))
help();
if (cmd.hasOption("v")) {
log.log(Level.INFO, "Using cli argument -v=" + cmd.getOptionValue("v"));
// Whatever you want to do with the setting goes here
if (cmd.hasOption("p")) {
parser(cmd.getOptionValue("p"), new ReadXlsx());
}
} else {
log.log(Level.SEVERE, "MIssing v option");
help();
}
} catch (ParseException e) {
log.log(Level.SEVERE, "Failed to parse comand line properties", e);
help();
}
}
private void help() {
// This prints out some help
HelpFormatter formater = new HelpFormatter();
formater.printHelp("Main", options);
System.exit(0);
}
private void parser(String filename, VoterFileReader reader){
Parser parser = new Parser();
parser.ReadFile(filename, reader);
}
} |
package com.akiban.rest;
import com.akiban.rest.resources.DataAccessOperationsResource;
import com.akiban.rest.resources.FaviconResource;
import com.akiban.rest.resources.SqlExecutionResource;
import com.akiban.rest.resources.SqlGroupsResource;
import com.akiban.rest.resources.SqlQueryResource;
import com.akiban.rest.resources.SqlSchemataResource;
import com.akiban.rest.resources.SqlTablesResource;
import com.akiban.rest.resources.VersionResource;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.ServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Guice Module which registers essential classes.
*/
public class RestServiceModule extends ServletModule {
// Hang onto reference or setting will get GC-ed.
private Logger guiceFilterLogger = null;
@Override
protected void configureServlets() {
// GuiceFilter has a static member that causes a superfluous (for us) warning when services
// (the injector, really) are cycled during the ITs. Disable it.
guiceFilterLogger = Logger.getLogger(GuiceFilter.class.getName());
guiceFilterLogger.setLevel(Level.OFF);
bind(FaviconResource.class).asEagerSingleton();
bind(DataAccessOperationsResource.class).asEagerSingleton();
bind(SqlGroupsResource.class).asEagerSingleton();
bind(SqlQueryResource.class).asEagerSingleton();
bind(SqlSchemataResource.class).asEagerSingleton();
bind(SqlTablesResource.class).asEagerSingleton();
bind(SqlExecutionResource.class).asEagerSingleton();
bind(VersionResource.class).asEagerSingleton();
bind(ConnectionCloseFilter.class).asEagerSingleton();
serve("*").with(GuiceContainer.class);
filter("*").through(ConnectionCloseFilter.class);
}
} |
package kembe;
import fj.Effect;
import fj.F;
import fj.P1;
import fj.Show;
import fj.data.Either;
import fj.data.NonEmptyList;
import fj.data.Validation;
public abstract class StreamEvent<A> {
public static <A, B> F<Either<StreamEvent<A>, StreamEvent<B>>, StreamEvent<Either<A, B>>> normEither() {
return new F<Either<StreamEvent<A>, StreamEvent<B>>, StreamEvent<Either<A, B>>>() {
@Override public StreamEvent<Either<A, B>> f(Either<StreamEvent<A>, StreamEvent<B>> either) {
if (either.isLeft())
return either.left().value().map( Either.<A, B>left_() );
else
return either.right().value().map( Either.<A, B>right_() );
}
};
}
public static <A, B> F<StreamEvent<A>, StreamEvent<B>> lift(final F<A, B> f) {
return new F<StreamEvent<A>, StreamEvent<B>>() {
@Override
public StreamEvent<B> f(StreamEvent<A> aStreamEvent) {
return aStreamEvent.map( f );
}
};
}
public static <A, E, B> F<StreamEvent<A>, StreamEvent<B>> liftV(final F<A, Validation<NonEmptyList<E>, B>> f, final Show<E> msgConverter) {
return new F<StreamEvent<A>, StreamEvent<B>>() {
@Override public StreamEvent<B> f(StreamEvent<A> aStreamEvent) {
return aStreamEvent
.fold(
new F<A, StreamEvent<B>>() {
@Override public StreamEvent<B> f(A a) {
Validation<NonEmptyList<E>, B> v = f.f( a );
if (v.isSuccess())
return StreamEvent.next( v.success() );
else
return StreamEvent.error( new Exception( Show.nonEmptyListShow( msgConverter ).showS( v.fail() ) ) );
}
}, new F<Exception, StreamEvent<B>>() {
@Override public StreamEvent<B> f(Exception e) {
return StreamEvent.error( e );
}
}, new P1<StreamEvent<B>>() {
@Override public StreamEvent<B> _1() {
return StreamEvent.done();
}
}
);
}
};
}
public static <A> Next<A> next(A value) {
return new Next<>( value );
}
public static <A> F<A, Next<A>> next() {
return new F<A, Next<A>>() {
@Override public Next<A> f(A a) {
return next( a );
}
};
}
public static <A> Error<A> error(Exception e) {
return new Error<>( e );
}
public static <A> Done<A> done() {
return new Done<>();
}
public <E, B> StreamEvent<B> mapV(F<A, Validation<NonEmptyList<E>, B>> f, Show<E> msgConverter) {
return liftV( f, msgConverter ).f( this );
}
public void effect(final EventStreamHandler handler) {
effect( new Effect<Next<A>>() {
@Override public void e(Next<A> aNext) {
handler.next( aNext.value );
}
}, new Effect<Error<A>>() {
@Override public void e(Error<A> aError) {
handler.error( aError.e );
}
}, new Effect<Done<A>>() {
@Override public void e(Done<A> aDone) {
handler.done();
}
}
);
}
public abstract void effect(Effect<Next<A>> onNext, Effect<Error<A>> onError, Effect<Done<A>> onDone);
public abstract <T> T fold(F<A, T> onNext, F<Exception, T> onError, P1<T> onDone);
public abstract <B> StreamEvent<B> map(F<A, B> f);
public static class Done<A> extends StreamEvent<A> {
@Override public void effect(Effect<Next<A>> onNext, Effect<Error<A>> onError, Effect<Done<A>> onDone) {
onDone.e( this );
}
@Override
public <T> T fold(F<A, T> onNext, F<Exception, T> onError, P1<T> onDone) {
return onDone._1();
}
@Override
public <B> StreamEvent<B> map(F<A, B> f) {
return new Done<>();
}
}
public static class Error<A> extends StreamEvent<A> {
public final Exception e;
public Error(Exception e) {
this.e = e;
}
@Override public void effect(Effect<Next<A>> onNext, Effect<Error<A>> onError, Effect<Done<A>> onDone) {
onError.e( this );
}
@Override
public <T> T fold(F<A, T> onNext, F<Exception, T> onError, P1<T> onDone) {
return onError.f( e );
}
@Override
public <B> StreamEvent<B> map(F<A, B> f) {
return new Error<>( e );
}
}
public static class Next<A> extends StreamEvent<A> {
public final A value;
public Next(A value) {
this.value = value;
}
@Override public void effect(Effect<Next<A>> onNext, Effect<Error<A>> onError, Effect<Done<A>> onDone) {
onNext.e( this );
}
@Override
public <T> T fold(F<A, T> onNext, F<Exception, T> onError, P1<T> onDone) {
return onNext.f( value );
}
@Override
public <B> StreamEvent<B> map(F<A, B> f) {
return new Next<>( f.f( value ) );
}
}
} |
package com.amee.domain.data;
import com.amee.base.utils.XMLUtils;
import com.amee.domain.AMEEEnvironmentEntity;
import com.amee.domain.AMEEStatus;
import com.amee.domain.IMetadataService;
import com.amee.domain.LocaleHolder;
import com.amee.domain.Metadata;
import com.amee.domain.ObjectType;
import com.amee.domain.environment.Environment;
import com.amee.domain.path.Pathable;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Index;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Configurable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.annotation.Resource;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Entity
@Table(name = "DATA_CATEGORY")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Configurable(autowire = Autowire.BY_TYPE)
public class DataCategory extends AMEEEnvironmentEntity implements Pathable {
public final static int NAME_MIN_SIZE = 3;
public final static int NAME_MAX_SIZE = 255;
public final static int PATH_MIN_SIZE = 0;
public final static int PATH_MAX_SIZE = 255;
public final static int WIKI_NAME_MIN_SIZE = 3;
public final static int WIKI_NAME_MAX_SIZE = 255;
public final static int WIKI_DOC_MAX_SIZE = Metadata.VALUE_SIZE;
public final static int PROVENANCE_MAX_SIZE = 255;
public final static int AUTHORITY_MAX_SIZE = 255;
@Transient
@Resource
private IMetadataService metadataService;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "DATA_CATEGORY_ID")
private DataCategory dataCategory;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "ITEM_DEFINITION_ID")
private ItemDefinition itemDefinition;
@Column(name = "NAME", length = NAME_MAX_SIZE, nullable = false)
private String name = "";
@Column(name = "PATH", length = PATH_MAX_SIZE, nullable = false)
@Index(name = "PATH_IND")
private String path = "";
@Column(name = "WIKI_NAME", length = WIKI_NAME_MAX_SIZE, nullable = false)
@Index(name = "WIKI_NAME_IND")
private String wikiName = "";
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ALIASED_TO_ID")
private DataCategory aliasedTo;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "ALIASED_TO_ID")
private List<DataCategory> aliases = new ArrayList<DataCategory>();
// @OneToMany(mappedBy = "entity", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @MapKey(name = "locale")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Transient
private Map<String, LocaleName> localeNames = new HashMap<String, LocaleName>();
@Transient
private Map<String, Metadata> metadatas = new HashMap<String, Metadata>();
public DataCategory() {
super();
}
public DataCategory(Environment environment) {
super(environment);
}
public DataCategory(Environment environment, String name, String path) {
this(environment);
setName(name);
setPath(path);
}
public DataCategory(DataCategory dataCategory) {
this(dataCategory.getEnvironment());
setDataCategory(dataCategory);
}
public DataCategory(DataCategory dataCategory, String name, String path) {
this(dataCategory);
setName(name);
setPath(path);
}
public DataCategory(DataCategory dataCategory, String name, String path, ItemDefinition itemDefinition) {
this(dataCategory, name, path);
setItemDefinition(itemDefinition);
}
@Override
public String toString() {
return "DataCategory_" + getUid();
}
public JSONObject getJSONObject() throws JSONException {
return getJSONObject(true);
}
public JSONObject getJSONObject(boolean detailed) throws JSONException {
JSONObject obj = new JSONObject();
obj.put("uid", getUid());
obj.put("path", getPath());
obj.put("name", getName());
obj.put("deprecated", isDeprecated());
if (detailed) {
obj.put("created", getCreated().toString());
obj.put("modified", getModified().toString());
obj.put("environment", getEnvironment().getJSONObject(false));
if (getDataCategory() != null) {
obj.put("dataCategory", getDataCategory().getIdentityJSONObject());
}
if (getItemDefinition() != null) {
obj.put("itemDefinition", getItemDefinition().getJSONObject());
}
}
return obj;
}
public JSONObject getIdentityJSONObject() throws JSONException {
return getJSONObject(false);
}
public Element getElement(Document document, boolean detailed) {
Element element = document.createElement("DataCategory");
element.setAttribute("uid", getUid());
element.appendChild(XMLUtils.getElement(document, "Name", getName()));
element.appendChild(XMLUtils.getElement(document, "Path", getPath()));
element.appendChild(XMLUtils.getElement(document, "Deprecated", "" + isDeprecated()));
if (detailed) {
element.setAttribute("created", getCreated().toString());
element.setAttribute("modified", getModified().toString());
element.appendChild(getEnvironment().getIdentityElement(document));
if (getDataCategory() != null) {
element.appendChild(getDataCategory().getIdentityElement(document));
}
if (getItemDefinition() != null) {
element.appendChild(getItemDefinition().getIdentityElement(document));
}
}
return element;
}
public Element getIdentityElement(Document document) {
return getElement(document, false);
}
public String getDisplayPath() {
return getPath();
}
public String getDisplayName() {
if (getName().length() > 0) {
return getName();
} else {
return getDisplayPath();
}
}
public DataCategory getDataCategory() {
return dataCategory;
}
public void setDataCategory(DataCategory dataCategory) {
if (dataCategory != null) {
this.dataCategory = dataCategory;
}
}
public ItemDefinition getItemDefinition() {
return itemDefinition;
}
public void setItemDefinition(ItemDefinition itemDefinition) {
this.itemDefinition = itemDefinition;
}
public String getName() {
String localeName = getLocaleName();
if (localeName != null) {
return localeName;
} else {
return name;
}
}
public void setName(String name) {
if (name == null) {
name = "";
}
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
if (path == null) {
path = "";
}
this.path = path;
}
public String getWikiName() {
return wikiName;
}
public void setWikiName(String wikiName) {
if (wikiName == null) {
wikiName = "";
}
this.wikiName = wikiName;
}
@Override
public boolean isTrash() {
return status.equals(AMEEStatus.TRASH) || ((getItemDefinition() != null) && getItemDefinition().isTrash());
}
public DataCategory getAliasedCategory() {
return aliasedTo;
}
public void setAliasedTo(DataCategory aliasedTo) {
this.aliasedTo = aliasedTo;
}
public List<DataCategory> getAliases() {
return aliases;
}
/**
* Get the collection of locale specific names for this DataCategory.
*
* @return the collection of locale specific names. The collection will be empty
* if no locale specific names exist.
*/
public Map<String, LocaleName> getLocaleNames() {
Map<String, LocaleName> activeLocaleNames = new TreeMap<String, LocaleName>();
for (String locale : localeNames.keySet()) {
LocaleName name = localeNames.get(locale);
if (!name.isTrash()) {
activeLocaleNames.put(locale, name);
}
}
return activeLocaleNames;
}
/*
* Get the locale specific name of this DataCategory for the locale of the current thread.
*
* The locale specific name of this DataCategory for the locale of the current thread.
* If no locale specific name is found, the default name will be returned.
*/
@SuppressWarnings("unchecked")
private String getLocaleName() {
String name = null;
LocaleName localeName = localeNames.get(LocaleHolder.getLocale());
if (localeName != null && !localeName.isTrash()) {
name = localeName.getName();
}
return name;
}
public void addLocaleName(LocaleName localeName) {
localeNames.put(localeName.getLocale(), localeName);
}
public String getWikiDoc() {
return getMetadataValue("wikiDoc");
}
public void setWikiDoc(String wikiDoc) {
getOrCreateMetadata("wikiDoc").setValue(wikiDoc);
}
public String getProvenance() {
return getMetadataValue("provenance");
}
public void setProvenance(String provenance) {
getOrCreateMetadata("provenance").setValue(provenance);
}
public String getAuthority() {
return getMetadataValue("authority");
}
public void setAuthority(String authority) {
getOrCreateMetadata("authority").setValue(authority);
}
// TODO: The following three methods are cut-and-pasted between various entities. They should be consolidated.
private Metadata getMetadata(String key) {
if (!metadatas.containsKey(key)) {
metadatas.put(key, metadataService.getMetadataForEntity(this, key));
}
return metadatas.get(key);
}
private String getMetadataValue(String key) {
Metadata metadata = getMetadata(key);
if (metadata != null) {
return metadata.getValue();
} else {
return "";
}
}
protected Metadata getOrCreateMetadata(String key) {
Metadata metadata = getMetadata(key);
if (metadata == null) {
metadata = new Metadata(this, key);
metadataService.persist(metadata);
metadatas.put(key, metadata);
}
return metadata;
}
@Override
public void setStatus(AMEEStatus status) {
this.status = status;
for (DataCategory alias : aliases) {
alias.setStatus(status);
}
}
public ObjectType getObjectType() {
return ObjectType.DC;
}
} |
package leetcode;
public class HeapSort {
public static void main(String[] args) {
int[] a = { 3, 2, 1, 5, 6, 4 };
System.out.println(findKthLargest(a, 1));
int[] b = { -1,2,0};
System.out.println(findKthLargest(b, 3));
int[] c = { 3,1,5,7,2};
System.out.println(findKthLargest(c, 2));
}
public static int findKthLargest(int[] nums, int k) {
for(int i=0;i<nums.length;i++) {
sort(nums, i);
}
return nums[nums.length - k];
}
private static void sort(int[] nums, int index) {
final int length = nums.length;
//validation
if (index > length) {
return;
}
//we only sort none-leaves nodes in b-tree
final int end = length / 2 - 1 - index;
for (int i = 0; i < end; i++) {
sortTreeDesc(nums, i, length-index);
}
for (int i = end; i < length-index; i++) {
sortTreeAsc(nums, i);
}
//We assume the tree has been sorted correctly
//We will sort array by switching root with last leave of the tree;
sortArray(nums, index);
}
private static void logAry(int[] nums) {
System.out.println("
for (int i = 0; i< nums.length; i++) {
System.out.print(nums[i]);
}
System.out.println("\n
}
private static void sortArray(int[] nums, int index) {
final int len = nums.length;
final int last = len - index - 1;
if (last > 0) {
swap(nums, 0, last);
}
}
public static void sortTreeDesc(int[] items, int i, int end) {
int left = 2*i + 1;
int right = 2*(i+1);
int max = i;
if (left < end && items[max] < items[left]) {
swap(items, max, left);
max = left;
}
if (right < end && items[max] < items[right]) {
swap(items, max, right);
max = right;
sortTreeDesc(items, max, end);
}
}
public static void sortTreeAsc(int[] items, int i) {
int parent = (i - 1) / 2;
if (i == parent) {
return;
}
int max = i;
//if current node is bigger than parent, switch
//otherwise, sort with it's parent
if (parent >= 0 && items[max] > items[parent]) {
swap(items, max, parent);
}
sortTreeAsc(items, parent);
}
private static void swap(int[] heap, int p, int parent) {
int temp = heap[parent];
heap[parent] = heap[p];
heap[p] = temp;
}
} |
package com.biggestnerd.civradar;
import java.io.File;
import java.io.IOException;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent;
import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent;
import org.apache.commons.io.FileUtils;
import org.lwjgl.input.Keyboard;
import com.biggestnerd.civradar.gui.GuiAddWaypoint;
import com.biggestnerd.civradar.gui.GuiRadarOptions;
@Mod(modid=CivRadar.MODID, name=CivRadar.MODNAME, version=CivRadar.VERSION)
public class CivRadar {
public final static String MODID = "civradar";
public final static String MODNAME = "CivRadar";
public final static String VERSION = "beta-1.2.5";
private RenderHandler renderHandler;
private Config radarConfig;
private File configFile;
private KeyBinding radarOptions = new KeyBinding("CivRadar Settings", Keyboard.KEY_R, "CivRadar");
private KeyBinding addWaypoint = new KeyBinding("Add Waypoint", Keyboard.KEY_P, "CivRadar");
Minecraft mc;
public static CivRadar instance;
private WaypointSave currentWaypoints;
private File saveFile;
public static String currentServer = "";
public static File waypointDir;
private File radarDir;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
mc = Minecraft.getMinecraft();
instance = this;
File oldConfig = new File(event.getModConfigurationDirectory(), "civRadar.json");
File radarDir = new File(mc.mcDataDir, "/civradar/");
if(!radarDir.isDirectory()) {
radarDir.mkdir();
}
configFile = new File(radarDir, "config.json");
if(oldConfig.exists()) {
try {
FileUtils.copyFile(oldConfig, configFile);
oldConfig.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
if(!configFile.isFile()) {
try {
configFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
radarConfig = new Config();
radarConfig.save(configFile);
} else {
radarConfig = Config.load(configFile);
if(radarConfig == null) {
radarConfig = new Config();
}
radarConfig.save(configFile);
}
renderHandler = new RenderHandler();
waypointDir = new File(radarDir, "/waypoints/");
if(!waypointDir.isDirectory()) {
waypointDir.mkdir();
}
currentWaypoints = new WaypointSave();
currentWaypoints.convertZanWayPoint();
FMLCommonHandler.instance().bus().register(renderHandler);
MinecraftForge.EVENT_BUS.register(renderHandler);
FMLCommonHandler.instance().bus().register(this);
ClientRegistry.registerKeyBinding(radarOptions);
ClientRegistry.registerKeyBinding(addWaypoint);
}
@SubscribeEvent
public void keyPress(KeyInputEvent event) {
if(radarOptions.isKeyDown()) {
mc.displayGuiScreen(new GuiRadarOptions(mc.currentScreen));
}
if(addWaypoint.isKeyDown()) {
mc.displayGuiScreen(new GuiAddWaypoint(mc.currentScreen));
}
}
@SubscribeEvent
public void onTick(ClientTickEvent event) {
if(mc.theWorld != null) {
if(mc.isSingleplayer()) {
String worldName = mc.getIntegratedServer().getWorldName();
if(worldName == null) {
return;
}
if(!currentServer.equals(worldName)) {
currentServer = worldName;
loadWaypoints(new File(waypointDir, worldName + ".points"));
}
} else if (mc.getCurrentServerData() != null) {
if(!currentServer.equals(mc.getCurrentServerData().serverIP)) {
currentServer = mc.getCurrentServerData().serverIP;
loadWaypoints(new File(waypointDir, currentServer + ".points"));
}
}
}
}
@SubscribeEvent
public void onDisconnect(ClientDisconnectionFromServerEvent event) {
currentServer = "";
}
public void loadWaypoints(File saveFile) {
if(!saveFile.isFile()) {
try {
saveFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
currentWaypoints.save(saveFile);
} else {
currentWaypoints = WaypointSave.load(saveFile);
currentWaypoints.save(saveFile);
this.saveFile = saveFile;
}
}
public Config getConfig() {
return radarConfig;
}
public void saveConfig() {
radarConfig.save(configFile);
}
public WaypointSave getWaypointSave() {
return currentWaypoints;
}
public void saveWaypoints() {
currentWaypoints.save(saveFile);
}
} |
package mezz.jei.util;
import mezz.jei.JustEnoughItems;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.message.MessageFormatMessage;
public class Log {
public static void trace(String message, Object... params) {
log(Level.TRACE, message, params);
}
public static void debug(String message, Object... params) {
log(Level.DEBUG, message, params);
}
public static void info(String message, Object... params) {
log(Level.INFO, message, params);
}
public static void warning(String message, Object... params) {
log(Level.WARN, message, params);
}
public static void error(String message, Object... params) {
log(Level.ERROR, message, params);
}
public static void log(Level logLevel, String message, Object... params) {
LogManager.getLogger(JustEnoughItems.MODID).log(logLevel, message, params);
}
} |
package org.jdbdt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Data set.
*
* <p>A data set represents a collection of rows.</p>
*
* @since 0.1
*
*/
public class DataSet implements Iterable<Row> {
/**
* Data source.
*/
final DataSource source;
/**
* Rows in the data set.
*/
private final List<Row> rows;
/**
* Constructs a new data set.
* @param ds Data source.
*/
DataSet(DataSource ds) {
this(ds, new ArrayList<>());
}
/**
* Constructs a new row set.
* @param ds Data source.
* @param l Row list.
*/
DataSet(DataSource ds, ArrayList<Row> l) {
this.source = ds;
this.rows = l;
}
/**
* Get data source.
* @return The data source associated to this
* data set.
*/
public final DataSource getSource() {
return source;
}
/**
* Test if set is empty.
* @return <code>true</code> is set is empty.
*/
final boolean isEmpty() {
return rows.isEmpty();
}
/**
* Get size set.
* @return The number of rows in the set.
*/
public int size() {
return rows.size();
}
/**
* Clear contents.
*/
final void clear() {
rows.clear();
}
/**
* Add a row to the data set.
* @param columnValues Column values forming a row.
* @return The data set instance (for chained calls).
*/
public final DataSet row(Object... columnValues) {
if (columnValues.length != source.getColumnCount()) {
throw new InvalidUsageException(source.getColumnCount() +
" columns expected, not " + columnValues.length + ".");
}
addRow(new RowImpl(columnValues));
return this;
}
/**
* Add rows to the data set.
* @param rows Array of rows.
* @return The data set instance (for chained calls).
*/
public final DataSet row(Object[][] rows) {
for (Object[] columnValues : rows) {
row(columnValues);
}
return this;
}
/**
* Add a row to the set (package-private version).
* @param r Row to add.
*/
final void addRow(Row r) {
rows.add(r);
}
/**
* Get an iterator for the row set.
* @return An iterator object.
*/
@Override
public Iterator<Row> iterator() {
return rows.iterator();
}
@Override
public boolean equals(Object o) {
return o == this ||
( o instanceof DataSet &&
rows.equals(((DataSet) o).rows) );
}
/**
* Create sub-set of a given data set.
* @param data Data set.
* @param startIndex Start index.
* @param endIndex End index.
* @return A new data set containing
* the rows in the specified range.
*/
public static DataSet subset(DataSet data, int startIndex, int endIndex) {
DataSet sub = new DataSet(data.getSource());
ListIterator<Row> itr = data.rows.listIterator(startIndex);
int index = startIndex;
while (itr.hasNext() && index < endIndex) {
sub.rows.add(itr.next());
}
return sub;
}
/**
* Add rows of given data set to this set.
* @param other This data set.
* @return The data set instance (for chained calls).
*/
public DataSet add(DataSet other) {
rows.addAll(other.rows);
return this;
}
/**
* Sort data set by row hash code (for testing purposes only).
*/
void enforceHOrdering() {
Collections.sort(rows, (a,b) -> Integer.compare(a.hashCode(), b.hashCode()));
}
} |
package com.client.core.base.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import com.client.core.base.model.relatedentity.BullhornRelatedEntity;
import com.client.core.base.model.relatedentity.StandardRelatedEntity;
import com.client.core.base.workflow.node.WorkflowAction;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.json.JSONArray;
import com.bullhornsdk.data.api.BullhornData;
import com.bullhornsdk.data.model.entity.core.type.BullhornEntity;
import com.bullhornsdk.data.model.entity.core.type.QueryEntity;
import com.bullhornsdk.data.model.entity.core.type.SearchEntity;
import com.bullhornsdk.data.model.entity.embedded.Address;
import com.bullhornsdk.data.model.parameter.QueryParams;
import com.bullhornsdk.data.model.parameter.SearchParams;
import com.bullhornsdk.data.model.parameter.standard.ParamFactory;
import com.bullhornsdk.data.model.response.list.ListWrapper;
import com.client.core.AppContext;
import com.google.common.collect.Lists;
public class Utility {
public static Map<? extends BullhornRelatedEntity, Set<String>> getRequestedFields(BullhornRelatedEntity[] relatedEntities,
List<? extends WorkflowAction<?, ?>> actions) {
Map<? extends BullhornRelatedEntity, Set<String>> requestedFields = actions.stream().map(WorkflowAction::getRelatedEntityFields).reduce(Maps.newLinkedHashMap(), (firstMap, secondMap) -> {
return Stream.concat(firstMap.entrySet().stream(), secondMap.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
Utility::mergeFieldSets));
});
return Stream.concat(Stream.of(relatedEntities), Stream.of(StandardRelatedEntity.values())).collect(Collectors.toMap(Function.identity(), relatedEntity -> {
if (requestedFields.containsKey(relatedEntity)) {
return Utility.mergeFieldSets(relatedEntity.getDefaultFields(), requestedFields.get(relatedEntity));
}
return relatedEntity.getDefaultFields();
}));
}
public static Set<String> mergeFieldSets(Set<String> set1, Set<String> set2) {
return mergeNestedFields(Sets.union(set1, set2));
}
public static Set<String> mergeNestedFields(Set<String> fields) {
return fields.parallelStream().map(field -> {
return field.replaceAll("\\s+", "");
}).collect(Collectors.groupingBy(field -> {
return StringUtils.substringBefore(field, "(").trim();
})).entrySet().parallelStream().map(entry -> {
if (entry.getValue().size() == 1) {
return entry.getValue().get(0).trim();
} else {
Set<String> nestedFields = entry.getValue().parallelStream().map(nestedField -> {
return StringUtils.substringBeforeLast(StringUtils.substringAfter(nestedField, "("), ")");
}).flatMap(nestedField -> {
return splitOutsideParentheses(nestedField).stream();
}).collect(Collectors.toSet());
return mergeNestedFields(nestedFields).parallelStream().collect(Collectors.joining(",", entry.getKey() + "(", ")"));
}
}).collect(Collectors.toSet());
}
public static Set<String> splitOutsideParentheses(String value) {
Set<String> result = Sets.newHashSet();
StringBuilder current = new StringBuilder();
Integer isParenthesis = 0;
for (Integer index = 0; index < value.length(); index++) {
if (value.charAt(index) == '(') {
isParenthesis++;
current.append('(');
} else if (value.charAt(index) == ')' && isParenthesis > 0) {
isParenthesis
current.append(')');
} else if (value.charAt(index) == ',' && isParenthesis == 0) {
result.add(current.toString());
current = new StringBuilder();
} else {
current.append(value.charAt(index));
}
}
if (StringUtils.isNotBlank(current)) {
result.add(current.toString());
}
return result;
}
public static boolean isNumbersOnly(String str) {
if (str == null || str.isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isNumeric(String value) {
if (value == null || value.isEmpty()) {
return false;
}
for (int i = 0; i < value.length(); i++) {
if (!Character.isDigit(value.charAt(i)) && !".".equalsIgnoreCase(Character.toString(value.charAt(i)))) {
return false;
}
}
return true;
}
public static Set<Integer> parseCommaSeparatedIntegers(String value) {
return parseCommaSeparated(value, Utility::forceParseInteger);
}
public static Set<String> parseCommaSeparatedStrings(String value) {
return parseCommaSeparated(value, Function.identity());
}
private static <T> Set<T> parseCommaSeparated(String value, Function<String, T> map) {
return Stream.of(StringUtils.defaultIfBlank(value, "").split(",")).parallel().map(map).collect(Collectors.toSet());
}
public static <T, R> Boolean valueChanged(T oldEntity, T newEntity, Function<T, R> get) {
R oldValue = get.apply(oldEntity);
R newValue = get.apply(newEntity);
if (oldValue instanceof Address) {
return valueChanged((Address) oldEntity, (Address) newEntity, Address::getAddress1)
|| valueChanged((Address) oldEntity, (Address) newEntity, Address::getAddress2)
|| valueChanged((Address) oldEntity, (Address) newEntity, Address::getCity)
|| valueChanged((Address) oldEntity, (Address) newEntity, Address::getState)
|| valueChanged((Address) oldEntity, (Address) newEntity, Address::getZip)
|| valueChanged((Address) oldEntity, (Address) newEntity, Address::getCountryID);
} else if (oldValue instanceof BullhornEntity) {
return valueChanged((BullhornEntity) oldValue, (BullhornEntity) newValue, BullhornEntity::getId);
}
return valueChanged(oldValue, newValue);
}
public static <T> Boolean valueChanged(T oldValue, T newValue) {
if (oldValue == null) {
return newValue != null;
} else if (newValue == null) {
return true;
} else if (oldValue instanceof String) {
String oldString = StringUtils.defaultIfBlank((String) oldValue, "");
String newString = StringUtils.defaultIfBlank((String) newValue, "");
return !oldString.equals(newString);
} else if (oldValue instanceof Boolean) {
return oldValue != newValue;
} else if (oldValue instanceof Integer) {
return !oldValue.equals(newValue);
} else if (oldValue instanceof BigDecimal) {
return ((BigDecimal) oldValue).compareTo((BigDecimal) newValue) != 0;
} else if (oldValue instanceof DateTime) {
return Days.daysBetween((DateTime) oldValue, (DateTime) newValue).getDays() != 0;
} else if (oldValue instanceof BullhornEntity) {
return valueChanged((BullhornEntity) oldValue, (BullhornEntity) newValue, BullhornEntity::getId);
}
return !oldValue.equals(newValue);
}
private static final String SEARCH_DATE_FORMAT = "yyyyMMddHHmmss";
public static String formatDateForSearch(DateTime value) {
return value.toString(SEARCH_DATE_FORMAT);
}
public static String escapeWhitespaceForSearch(String value) {
return value.replaceAll("\\s", "\\\\ ").replaceAll("\\)", "\\\\)").replaceAll("\\(", "\\\\(");
}
public static String escapeQuotesForQuery(String value) {
return value.replaceAll("'", "''");
}
public static Map<String, String> commaDelimitedStringToMap(String commaDelimited) {
List<String> parsed = Arrays.asList(commaDelimited.split(","));
Map<String, String> theMap = new LinkedHashMap<String, String>();
for (String value : parsed) {
theMap.put(value, value);
}
return theMap;
}
public static void combineJsonArrays(JSONArray jsonArray1, JSONArray jsonArray2) {
IntStream.range(0, jsonArray2.length()).forEach(index -> {
jsonArray1.put(jsonArray2.get(index));
});
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
public static Boolean isPositive(Integer value) {
return value != null && value > 0;
}
public static Boolean isPositive(BigDecimal value) {
return value != null && value.compareTo(BigDecimal.ZERO) > 0;
}
public static Boolean isPositive(Object value) {
return isPositive(forceParseBigDecimal(value));
}
public static BigDecimal parseBigDecimal(Object value) {
if (value == null || value.toString().isEmpty()) {
return null;
} else {
try {
Double check = Double.parseDouble(value.toString());
return new BigDecimal(check);
} catch (NumberFormatException e) {
return null;
}
}
}
public static BigDecimal forceParseBigDecimal(Object value) {
if (value == null || value.toString().isEmpty()) {
return BigDecimal.ZERO;
} else {
try {
Double check = Double.parseDouble(value.toString());
return new BigDecimal(check);
} catch (NumberFormatException e) {
return BigDecimal.ZERO;
}
}
}
public static Integer parseInteger(Object value) {
if (value == null || value.toString().isEmpty()) {
return null;
} else {
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return null;
}
}
}
public static Integer forceParseInteger(Object value) {
if (value == null || value.toString().isEmpty()) {
return 0;
} else {
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return 0;
}
}
}
public static Double parseDouble(Object value) {
if (value == null || value.toString().isEmpty()) {
return null;
} else {
try {
return Double.parseDouble(value.toString());
} catch (NumberFormatException e) {
return null;
}
}
}
public static Double forceParseDouble(Object value) {
if (value == null || value.toString().isEmpty()) {
return 0D;
} else {
try {
return Double.parseDouble(value.toString());
} catch (NumberFormatException e) {
return 0D;
}
}
}
public static Long forceParseLong(Object value) {
if (value == null || value.toString().isEmpty()) {
return 0L;
} else {
try {
return Long.parseLong(value.toString());
} catch (NumberFormatException e) {
return 0L;
}
}
}
public static BigInteger forceParseBigInteger(Object value) {
if (value == null || value.toString().isEmpty()) {
return new BigInteger("0");
} else {
try {
return new BigInteger(value.toString());
} catch (NumberFormatException e) {
return new BigInteger("0");
}
}
}
public static Date parseStringToDate(String dateStr, String dateFormat) {
if (dateStr == null || dateStr.isEmpty() || dateFormat == null || dateFormat.isEmpty()) {
return null;
} else {
DateFormat format = new SimpleDateFormat(dateFormat);
try {
return format.parse(dateStr);
} catch (ParseException e) {
return null;
}
}
}
public static Date forceParseStringToDate(String dateStr, String dateFormat) {
if (dateStr == null || dateStr.isEmpty() || dateFormat == null || dateFormat.isEmpty()) {
return DateTime.now().toDate();
} else {
TimeZone timeZone = TimeZone.getTimeZone("America/Detroit");
DateFormat format = new SimpleDateFormat(dateFormat);
format.setTimeZone(timeZone);
format.setLenient(false);
try {
return format.parse(dateStr);
} catch (ParseException e) {
return new Date(0);
}
}
}
public static DateTime parseStringToDateTime(String dateStr, String dateFormat) {
Date date = parseStringToDate(dateStr, dateFormat);
if (date == null) {
return null;
}
DateTime now = nowUsingTimeZone(null);
DateTime theCorrectDate = new DateTime(date, DateTimeZone.UTC);
theCorrectDate = theCorrectDate.plusHours(now.getHourOfDay());
theCorrectDate = theCorrectDate.plusMinutes(now.getMinuteOfHour());
return theCorrectDate;
}
public static DateTimeZone defaultTimeZone() {
return DateTimeZone.forID("EST5EDT");
}
/**
* Returns today based on time zone; defaults timeZone to "EST5EDT" if null passed in.
*
* @param timeZone a valid time zone, if null then defaults to "EST5EDT";
* @return today's date in DateTime for the passed in timeZone
*/
public static DateTime nowUsingTimeZone(DateTimeZone timeZone) {
if (timeZone == null) {
timeZone = defaultTimeZone();
}
return new DateTime(timeZone);
}
public static DateTime forceParseStringToDateTime(String dateStr, String dateFormat) {
return new DateTime(forceParseStringToDate(dateStr, dateFormat));
}
public static XMLGregorianCalendar forceParseStringToXMLGregorianCalendar(String dateStr, String dateFormat) {
return dateToXMLGregorianCal(forceParseStringToDate(dateStr, dateFormat));
}
public static String formatDate(Date date, String format) {
if (date == null) {
return "";
}
TimeZone timeZone = TimeZone.getTimeZone("America/Detroit");
DateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
dateFormat.setTimeZone(timeZone);
return dateFormat.format(date);
}
public static String formatDateTime(DateTime date, String format) {
if (date == null) {
return "";
}
return formatDate(date.toDate(), format);
}
public static XMLGregorianCalendar dateToXMLGregorianCal(Date date) {
if (date == null) {
return null;
}
TimeZone timeZone = TimeZone.getTimeZone("America/Detroit");
GregorianCalendar gregorianCal = new GregorianCalendar(timeZone);
gregorianCal.setTime(date);
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCal);
} catch (DatatypeConfigurationException e) {
return null;
}
}
public static XMLGregorianCalendar dateToXMLGregorianCalWithTimezone(Date date, TimeZone timezone) {
if (date == null) {
return null;
}
DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(timezone);
DateTime datetime = new DateTime(date.getTime(), dateTimeZone);
return dateTimeToXmlGregorianCalendar(datetime);
}
public static Date xmlGregorianCalToDate(XMLGregorianCalendar xmlGregCal) {
if (xmlGregCal == null) {
return null;
}
return xmlGregCal.toGregorianCalendar().getTime();
}
public static Boolean stringContains(String toCheckIn, String toCheckFor) {
if (toCheckIn == null || toCheckFor == null || toCheckFor.isEmpty()) {
return false;
}
if (toCheckIn.isEmpty()) {
return true;
}
List<String> valuesForCheck = Arrays.asList(toCheckIn.split(","));
for (String value : valuesForCheck) {
if (value.trim().equalsIgnoreCase(toCheckFor.trim())) {
return true;
}
}
return false;
}
public static Boolean listContains(Collection<String> toCheckIn, String toCheckFor) {
for (String object : toCheckIn) {
if (object.equalsIgnoreCase(toCheckFor)) {
return true;
}
}
return false;
}
public static String arrayToString(String[] a, String separator) {
StringBuilder result = new StringBuilder();
if (a == null) {
return null;
} else if (a.length > 0) {
result.append(a[0]);
for (int i = 1; i < a.length; i++) {
result.append(separator);
result.append(a[i]);
}
}
return result.toString();
}
public static Boolean parseBoolean(String bool) {
if (bool == null || bool.isEmpty()) {
return false;
}
if (bool.equalsIgnoreCase(Boolean.TRUE.toString())) {
return true;
}
return false;
}
public static String parseString(Object value) {
return value == null ? "" : value.toString();
}
public static DateTime xmlGregorianCalendarToDateTime(XMLGregorianCalendar calendar) {
if (calendar == null) {
return null;
}
DateTimeZone timeZone = DateTimeZone.forTimeZone(calendar.getTimeZone(0));
DateTime dateTime = new DateTime(calendar.toGregorianCalendar().getTime(), timeZone);
return dateTime;
}
public static XMLGregorianCalendar dateTimeToXmlGregorianCalendar(DateTime dateTime) {
if (dateTime == null) {
return null;
}
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeInMillis(dateTime.toLocalDateTime().toDate().getTime());
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
} catch (DatatypeConfigurationException e) {
return null;
}
}
public static String createEntireInStatement(Collection<String> values) {
return createEntireInStatement("", values);
}
public static String createEntireInStatement(String field, Collection<String> values) {
String commaSeparated = values.parallelStream().map(value -> {
return "'" + value + "'";
}).collect(Collectors.joining(","));
return field + " IN (" + commaSeparated + ")";
}
public static Integer nullCheck(Integer value) {
return nullCheck(value, 0);
}
public static <T> T nullCheck(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
public static BigDecimal nullCheck(BigDecimal value) {
return nullCheck(value, BigDecimal.ZERO);
}
public static String nullCheck(String value) {
return nullCheck(value, "");
}
public static String longDateFormatToShort(String applicationDateFormat) {
String shortDateFormat = StringUtils.defaultIfBlank(applicationDateFormat, "").replaceAll("MM", "M").replaceAll("dd", "d").replaceAll("yyyy", "yy");
return new StringBuilder(shortDateFormat).append(" h:mm a").toString();
}
public static String javaDateFormatToJavascriptDateFormat(String format) {
return StringUtils.defaultIfBlank(format, "").replaceAll("d", "D").replaceAll("y", "Y");
}
public static String getHostFromBullhornUrl(String currentBullhornUrl) {
return currentBullhornUrl.substring(0, StringUtils.indexOfIgnoreCase(currentBullhornUrl, "/bullhornstaffing/"));
}
public static <T extends QueryEntity, R> void queryAndProcessAll(Class<T> type, String where, Set<String> fields, Consumer<T> process) {
queryForAll(type, where, fields, (batch) -> {
batch.parallelStream().forEach(process);
});
}
public static <T extends QueryEntity, R> void sequentialQueryAndProcessAll(Class<T> type, String where, Set<String> fields, Consumer<T> process) {
queryForAll(type, where, fields, (batch) -> {
batch.forEach(process);
});
}
public static <T extends QueryEntity, R> List<R> queryAndMapAll(Class<T> type, String where, Set<String> fields, Function<T, R> map) {
List<R> result = Lists.newArrayList();
queryForAll(type, where, fields, (batch) -> {
result.addAll(batch.parallelStream().map(map).collect(Collectors.toList()));
});
return result;
}
public static <T extends QueryEntity, R> List<R> sequentialQueryAndMapAll(Class<T> type, String where, Set<String> fields, Function<T, R> map) {
List<R> result = Lists.newArrayList();
queryForAll(type, where, fields, (batch) -> {
result.addAll(batch.stream().map(map).collect(Collectors.toList()));
});
return result;
}
public static <T extends QueryEntity> List<T> queryAndFilterAll(Class<T> type, String where, Set<String> fields, Predicate<T> filter) {
List<T> result = Lists.newArrayList();
queryForAll(type, where, fields, (batch) -> {
result.addAll(batch.parallelStream().filter(filter).collect(Collectors.toList()));
});
return result;
}
public static <T extends QueryEntity> List<T> sequentialQueryAndFilterAll(Class<T> type, String where, Set<String> fields, Predicate<T> filter) {
List<T> result = Lists.newArrayList();
queryForAll(type, where, fields, (batch) -> {
result.addAll(batch.stream().filter(filter).collect(Collectors.toList()));
});
return result;
}
public static <T extends QueryEntity, A, R> R queryAndCollectAll(Class<T> type, String where, Set<String> fields, Collector<T, A, R> collect) {
A result = collect.supplier().get();
queryForAll(type, where, fields, (batch) -> {
A batchResult = collect.supplier().get();
batch.parallelStream().forEach(entity -> {
collect.accumulator().accept(batchResult, entity);
});
collect.combiner().apply(result, batchResult);
});
return collect.finisher().apply(result);
}
public static <T extends QueryEntity, A, R> R sequentialQueryAndCollectAll(Class<T> type, String where, Set<String> fields, Collector<T, A, R> collect) {
A result = collect.supplier().get();
queryForAll(type, where, fields, (batch) -> {
A batchResult = collect.supplier().get();
batch.forEach(entity -> {
collect.accumulator().accept(batchResult, entity);
});
collect.combiner().apply(result, batchResult);
});
return collect.finisher().apply(result);
}
public static <T extends SearchEntity, R> void searchAndProcessAll(Class<T> type, String where, Set<String> fields, Consumer<T> process) {
searchForAll(type, where, fields, (batch) -> {
batch.parallelStream().forEach(process);
});
}
public static <T extends SearchEntity, R> void sequentialSearchAndProcessAll(Class<T> type, String where, Set<String> fields, Consumer<T> process) {
searchForAll(type, where, fields, (batch) -> {
batch.forEach(process);
});
}
public static <T extends SearchEntity, R> List<R> searchAndMapAll(Class<T> type, String where, Set<String> fields, Function<T, R> map) {
List<R> result = Lists.newArrayList();
searchForAll(type, where, fields, (batch) -> {
result.addAll(batch.parallelStream().map(map).collect(Collectors.toList()));
});
return result;
}
public static <T extends SearchEntity, R> List<R> sequentialSearchAndMapAll(Class<T> type, String where, Set<String> fields, Function<T, R> map) {
List<R> result = Lists.newArrayList();
searchForAll(type, where, fields, (batch) -> {
result.addAll(batch.stream().map(map).collect(Collectors.toList()));
});
return result;
}
public static <T extends SearchEntity> List<T> searchAndFilterAll(Class<T> type, String where, Set<String> fields, Predicate<T> filter) {
List<T> result = Lists.newArrayList();
searchForAll(type, where, fields, (batch) -> {
result.addAll(batch.parallelStream().filter(filter).collect(Collectors.toList()));
});
return result;
}
public static <T extends SearchEntity> List<T> sequentialSearchAndFilterAll(Class<T> type, String where, Set<String> fields, Predicate<T> filter) {
List<T> result = Lists.newArrayList();
searchForAll(type, where, fields, (batch) -> {
result.addAll(batch.stream().filter(filter).collect(Collectors.toList()));
});
return result;
}
public static <T extends SearchEntity, A, R> R searchAndCollectAll(Class<T> type, String where, Set<String> fields, Collector<T, A, R> collect) {
A result = collect.supplier().get();
searchForAll(type, where, fields, (batch) -> {
A batchResult = collect.supplier().get();
batch.parallelStream().forEach(entity -> {
collect.accumulator().accept(batchResult, entity);
});
collect.combiner().apply(result, batchResult);
});
return collect.finisher().apply(result);
}
public static <T extends SearchEntity, A, R> R sequentialSearchAndCollectAll(Class<T> type, String where, Set<String> fields, Collector<T, A, R> collect) {
A result = collect.supplier().get();
searchForAll(type, where, fields, (batch) -> {
A batchResult = collect.supplier().get();
batch.forEach(entity -> {
collect.accumulator().accept(batchResult, entity);
});
collect.combiner().apply(result, batchResult);
});
return collect.finisher().apply(result);
}
private static <T extends QueryEntity> void queryForAll(Class<T> type, String where, Set<String> fields, Consumer<List<T>> process) {
queryForAll(type, where, fields, process, 0);
}
private static <T extends QueryEntity> void queryForAll(Class<T> type, String where, Set<String> fields, Consumer<List<T>> process, Integer start) {
BullhornData bullhornData = getBullhornData();
QueryParams params = ParamFactory.queryParams();
params.setStart(start);
params.setCount(BATCH_SIZE);
params.setOrderBy("id");
params.setShowTotalMatched(true);
ListWrapper<T> result = bullhornData.query(type, where, fields, params);
process.accept(result.getData());
if (result.getStart() + result.getCount() < result.getTotal()) {
queryForAll(type, where, fields, process, result.getStart() + result.getCount());
}
}
private static <T extends SearchEntity> void searchForAll(Class<T> type, String where, Set<String> fields, Consumer<List<T>> process) {
searchForAll(type, where, fields, process, 0);
}
private static <T extends SearchEntity> void searchForAll(Class<T> type, String where, Set<String> fields, Consumer<List<T>> process, Integer start) {
BullhornData bullhornData = getBullhornData();
SearchParams params = ParamFactory.searchParams();
params.setStart(start);
params.setCount(BATCH_SIZE);
params.setSort("id");
ListWrapper<T> result = bullhornData.search(type, where, fields, params);
process.accept(result.getData());
if (result.getStart() + result.getCount() < result.getTotal()) {
searchForAll(type, where, fields, process, result.getStart() + result.getCount());
}
}
private static final int BATCH_SIZE = 200;
private static synchronized BullhornData getBullhornData() {
if (BULLHORN_DATA == null) {
BULLHORN_DATA = AppContext.getApplicationContext().getBean(BullhornData.class);
}
return BULLHORN_DATA;
}
private static BullhornData BULLHORN_DATA;
} |
package com.clinichelper.Entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.UUID;
@Entity
@Table(name="equipments")
public class Equipment implements Serializable{
@Id
private String equipmentId;
@NotNull
private String equipmentName;
@NotNull
private String equipmentUse;
private String equipmentDescription;
private Integer equipmentInStock;
@ManyToOne
private Clinic clinic;
// Constructores
public Equipment(){
}
public Equipment(Clinic clinic, String equipmentName, String equipmentUse, String equipmentDescription, Integer equipmentInStock) {
this.setEquipmentId(clinic.getClinicPrefix() + "-E-" + UUID.randomUUID().toString().split("-")[0].toUpperCase());
this.setEquipmentName(equipmentName.toUpperCase());
this.setEquipmentUse(equipmentUse);
this.setEquipmentDescription(equipmentDescription);
this.clinic = clinic;
this.setEquipmentInStock(equipmentInStock);
}
//Getters and Setters
public String getEquipmentId() {
return equipmentId;
}
public void setEquipmentId(String equipmentId) {
this.equipmentId = equipmentId;
}
public String getEquipmentName() {
return equipmentName;
}
public void setEquipmentName(String equipmentName) {
this.equipmentName = equipmentName;
}
public String getEquipmentUse() {
return equipmentUse;
}
public void setEquipmentUse(String equipmentUse) {
this.equipmentUse = equipmentUse;
}
public String getEquipmentDescription() {
return equipmentDescription;
}
public void setEquipmentDescription(String equipmentDescription) {
this.equipmentDescription = equipmentDescription;
}
public Integer getEquipmentInStock() {
return equipmentInStock;
}
public void setEquipmentInStock(Integer equipmentInStock) {
this.equipmentInStock = equipmentInStock;
}
} |
package rxjava;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
/**
*
* @author
*
*/
public class HelloWorld {
public static void main(String[] args) {
Flowable<String> flowable = Flowable.create(new FlowableOnSubscribe<String>() {
@Override
public void subscribe(FlowableEmitter<String> e) throws Exception {
e.onNext("xxx");
e.onNext("hello RxJava 2");
e.onComplete();
}
}, BackpressureStrategy.BUFFER);
Subscriber<String> subscriber = new Subscriber<String>() {
@Override
public void onSubscribe(Subscription s) {
System.out.println("onSubscribe");
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(String s) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
System.out.println("onCompxxx");
}
};
flowable.subscribe(subscriber);
}
} |
package com.crowdin.cli.commands;
import com.crowdin.Credentials;
import com.crowdin.Crwdn;
import com.crowdin.cli.BaseCli;
import com.crowdin.cli.properties.CliProperties;
import com.crowdin.cli.properties.FileBean;
import com.crowdin.cli.properties.PropertiesBean;
import com.crowdin.cli.utils.*;
import com.crowdin.cli.utils.FileReader;
import com.crowdin.cli.utils.tree.DrawTree;
import com.crowdin.client.CrowdinApiClient;
import com.crowdin.parameters.CrowdinApiParametersBuilder;
import com.sun.jersey.api.client.ClientResponse;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.*;
/**
* @author ihor
*/
public class Commands extends BaseCli {
private String branch = null;
private HashMap<String, Object> cliConfig = new HashMap<>();
private CrowdinCliOptions cliOptions = new CrowdinCliOptions();
private CliProperties cliProperties = new CliProperties();
private File configFile = null;
private Credentials credentials = null;
private CommandUtils commandUtils = new CommandUtils();
private boolean dryrun = false;
private FileReader fileReader = new FileReader();
private boolean help = false;
private File identity = null;
private HashMap<String, Object> identityCliConfig = null;
private boolean isDebug = false;
private boolean isVerbose = false;
private String language = null;
private JSONObject projectInfo = null;
private PropertiesBean propertiesBean = new PropertiesBean();
private ConsoleSpinner spin = new ConsoleSpinner();
private JSONArray supportedLanguages = null;
private boolean version = false;
private void initialize(String resultCmd, CommandLine commandLine) {
if (!resultCmd.startsWith(HELP)
&& !GENERATE.equals(resultCmd)
&& !"".equals(resultCmd)
&& !commandLine.hasOption(CrowdinCliOptions.HELP_LONG)
&& !commandLine.hasOption(CrowdinCliOptions.HELP_SHORT)) {
PropertiesBean configFromParameters = commandUtils.makeConfigFromParameters(commandLine, this.propertiesBean);
if (configFromParameters != null) {
this.propertiesBean = configFromParameters;
} else {
if (commandLine.getOptionValue(CrowdinCliOptions.CONFIG_LONG) != null && !commandLine.getOptionValue(CrowdinCliOptions.CONFIG_LONG).isEmpty()) {
this.configFile = new File(commandLine.getOptionValue(CrowdinCliOptions.CONFIG_LONG));
} else {
this.configFile = new File("crowdin.yml");
if (!this.configFile.isFile()) {
this.configFile = new File("crowdin.yaml");
}
}
if (this.configFile.isFile()) {
try {
this.cliConfig = this.fileReader.readCliConfig(this.configFile.getAbsolutePath(), this.isDebug);
} catch (Exception e) {
System.out.println(RESOURCE_BUNDLE.getString("error_reading_configuration_file") + " '" + this.configFile.getAbsolutePath() + "'");
if (this.isDebug) {
e.printStackTrace();
}
System.exit(0);
}
} else {
System.out.println("Configuration file '" + this.configFile.getAbsolutePath() + "' does not exist");
System.exit(0);
}
if (this.cliConfig != null) {
try {
this.propertiesBean = this.cliProperties.loadProperties(this.cliConfig);
} catch (Exception e) {
System.out.println(RESOURCE_BUNDLE.getString("load_properties_error"));
if (this.isDebug) {
e.printStackTrace();
}
System.exit(0);
}
} else {
System.out.println("Configuration file '" + this.configFile.getAbsolutePath() + "' does not exist");
System.exit(0);
}
if (this.identity != null && this.identity.isFile()) {
this.propertiesBean = this.readIdentityProperties(this.propertiesBean);
}
}
this.propertiesBean.setBaseUrl(commandUtils.getBaseUrl(this.propertiesBean));
this.credentials = new Credentials(this.propertiesBean.getBaseUrl(), this.propertiesBean.getProjectIdentifier(), this.propertiesBean.getApiKey(), this.propertiesBean.getAccountKey(), Utils.getUserAgent());
this.initCli();
String basePath = commandUtils.getBasePath(this.propertiesBean, this.configFile, this.isDebug);
if (basePath != null) {
this.propertiesBean.setBasePath(basePath);
} else {
this.propertiesBean.setBasePath("");
}
this.propertiesBean = cliProperties.validateProperties(propertiesBean);
this.projectInfo = this.commandUtils.projectInfo(this.credentials, this.isVerbose, this.isDebug);
if (this.isVerbose) {
System.out.println(this.projectInfo);
}
this.supportedLanguages = this.commandUtils.getSupportedLanguages(this.credentials, this.isVerbose, this.isDebug);
if (this.isVerbose) {
System.out.println(this.supportedLanguages);
}
}
}
private PropertiesBean readIdentityProperties(PropertiesBean propertiesBean) {
try {
this.identityCliConfig = this.fileReader.readCliConfig(this.identity.getAbsolutePath(), this.isDebug);
} catch (Exception e) {
System.out.println(RESOURCE_BUNDLE.getString("error_reading_configuration_file") + " '" + this.identity.getAbsolutePath() + "'");
if (this.isDebug) {
e.printStackTrace();
}
System.exit(0);
}
if (this.identityCliConfig != null) {
if (this.identityCliConfig.get("project_identifier_env") != null) {
propertiesBean.setProjectIdentifier(this.identityCliConfig.get("project_identifier_env").toString());
}
if (this.identityCliConfig.get("api_key_env") != null) {
propertiesBean.setApiKey(this.identityCliConfig.get("api_key_env").toString());
}
if (this.identityCliConfig.get("base_path_env") != null) {
propertiesBean.setBasePath(this.identityCliConfig.get("base_path_env").toString());
}
if (this.identityCliConfig.get("base_url_env") != null) {
propertiesBean.setBaseUrl(this.identityCliConfig.get("base_url_env").toString());
}
if (this.identityCliConfig.get("project_identifier") != null) {
propertiesBean.setProjectIdentifier(this.identityCliConfig.get("project_identifier").toString());
}
if (this.identityCliConfig.get("api_key") != null) {
propertiesBean.setApiKey(this.identityCliConfig.get("api_key").toString());
}
if (this.identityCliConfig.get("base_path") != null) {
propertiesBean.setBasePath(this.identityCliConfig.get("base_path").toString());
}
if (this.identityCliConfig.get("base_url") != null) {
propertiesBean.setBaseUrl(this.identityCliConfig.get("base_url").toString());
}
}
return propertiesBean;
}
public void run(String resultCmd, CommandLine commandLine) {
if (commandLine == null) {
System.out.println(RESOURCE_BUNDLE.getString("commandline_null"));
System.exit(0);
}
if (resultCmd == null) {
System.out.println(RESOURCE_BUNDLE.getString("command_not_found"));
System.exit(0);
}
this.branch = this.commandUtils.getBranch(commandLine);
this.language = this.commandUtils.getLanguage(commandLine);
this.identity = this.commandUtils.getIdentityFile(commandLine);
this.isDebug = commandLine.hasOption(CrowdinCliOptions.DEBUG_LONG);
this.isVerbose = commandLine.hasOption(CrowdinCliOptions.VERBOSE_LONG) || commandLine.hasOption(CrowdinCliOptions.VERBOSE_SHORT);
this.dryrun = commandLine.hasOption(CrowdinCliOptions.DRY_RUN_LONG);
this.help = commandLine.hasOption(HELP) || commandLine.hasOption(HELP_SHORT);
this.version = commandLine.hasOption(CrowdinCliOptions.VERSION_LONG);
this.initialize(resultCmd, commandLine);
switch (resultCmd) {
case UPLOAD :
case UPLOAD_SOURCES :
boolean isAutoUpdate = commandLine.getOptionValue(COMMAND_NO_AUTO_UPDATE) == null;
if (this.help) {
cliOptions.cmdUploadSourcesOptions();
} else if (this.dryrun) {
this.dryrunSources(commandLine);
} else {
this.uploadSources(isAutoUpdate);
}
break;
case UPLOAD_TRANSLATIONS :
boolean isImportDuplicates = commandLine.hasOption(CrowdinCliOptions.IMPORT_DUPLICATES);
boolean isImportEqSuggestions = commandLine.hasOption(CrowdinCliOptions.IMPORT_EQ_SUGGESTIONS);
boolean isAutoApproveImported = commandLine.hasOption(CrowdinCliOptions.AUTO_APPROVE_IMPORTED);
if (this.help) {
this.cliOptions.cmdUploadTranslationsOptions();
} else if (this.dryrun) {
dryrunTranslation(commandLine);
} else {
this.uploadTranslation(isImportDuplicates, isImportEqSuggestions, isAutoApproveImported);
}
break;
case DOWNLOAD:
case DOWNLOAD_TRANSLATIONS:
boolean ignoreMatch = commandLine.hasOption(IGNORE_MATCH);
if (this.help) {
this.cliOptions.cmdDownloadOptions();
} else if (this.dryrun) {
this.dryrunTranslation(commandLine);
} else {
this.downloadTranslation(ignoreMatch);
}
break;
case LIST :
this.cliOptions.cmdListOptions();
break;
case LIST_PROJECT :
if (this.help) {
this.cliOptions.cmdListProjectOptions();
} else {
this.dryrunProject(commandLine);
}
break;
case LIST_SOURCES :
if (this.help) {
this.cliOptions.cmdListSourcesOptions();
} else {
this.dryrunSources(commandLine);
}
break;
case LIST_TRANSLATIONS :
if (this.help) {
this.cliOptions.cmdListTranslationsIOptions();
} else {
this.dryrunTranslation(commandLine);
}
break;
case LINT :
if (this.help) {
this.cliOptions.cmdLintOptions();
} else {
this.lint();
}
break;
case GENERATE :
if (this.help) {
this.cliOptions.cmdGenerateOptions();
} else {
String config = null;
if (commandLine.getOptionValue(DESTINATION_LONG) != null && !commandLine.getOptionValue(DESTINATION_LONG).isEmpty()) {
config = commandLine.getOptionValue(DESTINATION_LONG);
} else if (commandLine.getOptionValue(DESTINATION_SHORT) != null && !commandLine.getOptionValue(DESTINATION_SHORT).isEmpty()) {
config = commandLine.getOptionValue(DESTINATION_SHORT);
}
this.generate(config);
}
break;
case HELP :
boolean p = commandLine.hasOption(HELP_P);
if (this.help) {
this.cliOptions.cmdHelpOptions();
} else if (p) {
System.out.println(UPLOAD);
System.out.println(DOWNLOAD);
System.out.println(LIST);
System.out.println(LINT);
System.out.println(GENERATE);
System.out.println(HELP);
} else {
this.help(resultCmd);
}
break;
case HELP_HELP :
this.cliOptions.cmdHelpOptions();
break;
case HELP_UPLOAD :
case HELP_UPLOAD_SOURCES :
case HELP_UPLOAD_TRANSLATIONS :
case HELP_DOWNLOAD :
case HELP_GENERATE :
case HELP_LIST :
case HELP_LIST_PROJECT :
case HELP_LIST_SOURCES :
case HELP_LIST_TRANSLATIONS :
case HELP_LINT :
this.help(resultCmd);
break;
default:
if (this.version) {
System.out.println("Crowdin CLI version is " + Utils.getAppVersion());
} else {
StringBuilder wrongArgs = new StringBuilder();
for (String wrongCmd : commandLine.getArgList()) {
wrongArgs.append(wrongCmd).append(" ");
}
if (!"".equalsIgnoreCase(wrongArgs.toString().trim())){
System.out.println("Command '" + wrongArgs.toString().trim() + "' not found");
}
this.cliOptions.cmdGeneralOptions();
}
break;
}
}
/*
*
* Command 'crowdin generate'
*
*/
public void generate(String path) {
File skeleton;
if (path != null && !path.isEmpty()) {
skeleton = new File(path);
} else {
skeleton = new File("crowdin.yml");
}
InputStream is = Commands.class.getResourceAsStream("/crowdin.yml");
Path destination = Paths.get(skeleton.toURI());
System.out.print(RESOURCE_BUNDLE.getString("command_generate_description") + " '" + destination + "'- ");
try {
Files.copy(is, destination);
System.out.println(OK);
} catch (FileAlreadyExistsException ex) {
System.out.println(SKIPPED);
System.out.println("File '" + destination + "' already exists.");
if (this.isDebug) {
ex.printStackTrace();
}
} catch (Exception ex) {
System.out.println(RESOURCE_BUNDLE.getString("error_generate"));
if (this.isDebug) {
ex.printStackTrace();
}
}
}
private void createBranch(String name) {
CrowdinApiClient crwdn = new Crwdn();
Parser parser = new Parser();
CrowdinApiParametersBuilder crowdinApiParametersBuilder = new CrowdinApiParametersBuilder();
crowdinApiParametersBuilder.json()
.name(name)
.isBranch(true)
.headers(HEADER_ACCEPT, HEADER_ACCAEPT_VALUE)
.headers(HEADER_CLI_VERSION, HEADER_CLI_VERSION_VALUE)
.headers(HEADER_JAVA_VERSION, HEADER_JAVA_VERSION_VALUE)
.headers(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
ClientResponse clientResponse = null;
try {
clientResponse = crwdn.addDirectory(this.credentials, crowdinApiParametersBuilder);
} catch (Exception e) {
System.out.println("Error: creating branch '" + name + "' failed");
if (this.isDebug) {
e.printStackTrace();
}
System.exit(0);
}
JSONObject branch = parser.parseJson(clientResponse.getEntity(String.class));
if (this.isVerbose) {
System.out.println(clientResponse.getHeaders());
System.out.println(branch);
}
if (branch != null && branch.getBoolean(RESPONSE_SUCCESS)) {
System.out.println(RESOURCE_BUNDLE.getString("creating_branch") + " '" + name + "' - OK");
} else if (branch != null && !branch.getBoolean(RESPONSE_SUCCESS) && branch.getJSONObject(RESPONSE_ERROR) != null && branch.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE) == 50
&& "Directory with such name already exists".equals(branch.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE))) {
System.out.println(RESOURCE_BUNDLE.getString("creating_branch") + " '" + name + "' - SKIPPED");
} else {
System.out.println(RESOURCE_BUNDLE.getString("creating_branch") + " '" + name + "' - ERROR");
if (branch != null && branch.getJSONObject(RESPONSE_ERROR) != null && branch.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE) != null) {
System.out.println(branch.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE));
}
System.exit(0);
}
}
/*
*
* Command 'crowdin upload sources'
*
*/
public JSONObject uploadSources(boolean autoUpdate) {
CrowdinApiClient crwdn = new Crwdn();
JSONObject result = null;
Parser parser = new Parser();
Boolean preserveHierarchy = this.propertiesBean.getPreserveHierarchy();
List<FileBean> files = this.propertiesBean.getFiles();
boolean noFiles = true;
if (this.branch != null) {
this.createBranch(this.branch);
}
for (FileBean file : files) {
if (file.getSource() == null
|| file.getSource().isEmpty()
|| file.getTranslation() == null
|| file.getTranslation().isEmpty()) {
continue;
}
List<String> sources = this.commandUtils.getSourcesWithoutIgnores(file, this.propertiesBean);
if (sources != null && sources.size() > 0) {
noFiles = false;
}
String commonPath = "";
if (!preserveHierarchy) {
commonPath = this.commandUtils.getCommonPath(sources, this.propertiesBean);
}
for (String source : sources) {
File sourceFile = new File(source);
if (!sourceFile.isFile()) {
continue;
}
Boolean isDest = file.getDest() != null && !file.getDest().isEmpty() && !this.commandUtils.isSourceContainsPattern(file.getSource());
String preservePath = file.getDest();
preservePath = this.commandUtils.preserveHierarchy(file, sourceFile.getAbsolutePath(), commonPath, this.propertiesBean, this.branch, this.credentials, this.isVerbose);
String fName;
if (isDest) {
fName = new File(file.getDest()).getName();
} else {
fName = sourceFile.getName();
}
preservePath = preservePath + Utils.PATH_SEPARATOR + fName;
preservePath = preservePath.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
if (preservePath.startsWith(Utils.PATH_SEPARATOR)) {
preservePath = preservePath.replaceFirst(Utils.PATH_SEPARATOR_REGEX, "");
}
CrowdinApiParametersBuilder parameters = new CrowdinApiParametersBuilder();
parameters.headers(HEADER_ACCEPT, HEADER_ACCAEPT_VALUE)
.headers(HEADER_CLI_VERSION, HEADER_CLI_VERSION_VALUE)
.headers(HEADER_JAVA_VERSION, HEADER_JAVA_VERSION_VALUE)
.headers(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
preservePath = preservePath.replaceAll(Utils.PATH_SEPARATOR_REGEX, "/");
if (this.branch != null && !this.branch.isEmpty()) {
parameters.branch(this.branch);
}
if (sourceFile.getAbsoluteFile().isFile()) {
parameters.files(sourceFile.getAbsolutePath());
}
if (preservePath != null && !preservePath.isEmpty()) {
parameters.titles(preservePath, preservePath);
}
if (file.getType() != null && !file.getType().isEmpty()) {
parameters.type(file.getType());
}
if (file.getFirstLineContainsHeader() != null && file.getFirstLineContainsHeader() == true) {
parameters.firstLineContainsHeader();
}
if (file.getScheme() != null && !file.getScheme().isEmpty()) {
parameters.scheme(file.getScheme());
}
if (file.getTranslateContent() != null) {
parameters.translateContent(file.getTranslateContent());
}
if (file.getTranslateAttributes() != null) {
parameters.translateAttributes(file.getTranslateAttributes());
}
if (file.getContentSegmentation() != null) {
parameters.contentSegmentation(file.getContentSegmentation());
}
if (file.getTranslatableElements() != null) {
parameters.translatableElements(file.getTranslatableElements());
}
if (file.getEscapeQuotes() >= 0) {
parameters.escapeQuotes((int) file.getEscapeQuotes());
}
if (file.getUpdateOption() != null) {
parameters.updateOption(file.getUpdateOption());
}
String translationWithReplacedAsterisk = null;
if (sourceFile.getAbsolutePath() != null && !sourceFile.getAbsolutePath().isEmpty() && file.getTranslation() != null && !file.getTranslation().isEmpty()) {
String translations = file.getTranslation();
if (translations.contains("**")) {
translationWithReplacedAsterisk = this.commandUtils.replaceDoubleAsteriskInTranslation(file.getTranslation(), sourceFile.getAbsolutePath(), file.getSource(), this.propertiesBean);
}
if (translationWithReplacedAsterisk != null) {
if (translationWithReplacedAsterisk.indexOf("\\") != -1) {
translationWithReplacedAsterisk = translationWithReplacedAsterisk.replaceAll(Utils.PATH_SEPARATOR_REGEX, "/");
translationWithReplacedAsterisk = translationWithReplacedAsterisk.replaceAll("/+", "/");
}
parameters.exportPatterns(preservePath, translationWithReplacedAsterisk);
} else {
String pattern = file.getTranslation();
if (pattern != null && pattern.indexOf("\\") != -1) {
pattern = pattern.replaceAll(Utils.PATH_SEPARATOR_REGEX, "/");
pattern = pattern.replaceAll("/+", "/");
}
parameters.exportPatterns(preservePath, pattern);
}
}
parameters.json();
String outPath;
if (this.branch != null && !this.branch.isEmpty()) {
outPath = this.branch + "/" + preservePath;
outPath = outPath.replaceAll("/+", "/");
outPath = outPath.replaceAll("\\+", "\\");
} else {
outPath = preservePath;
}
System.out.print(RESOURCE_BUNDLE.getString("uploading_file") + " '" + outPath + "'");
Thread spinner = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
spin.turn();
}
}
});
spinner.start();
if (autoUpdate) {
ClientResponse clientResponse;
try {
clientResponse = crwdn.addFile(credentials, parameters);
spinner.stop();
} catch (Exception e) {
System.out.println(" - ERROR");
System.out.println("code : " + result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE));
System.out.println("message : " + result.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE));
if (this.isDebug) {
e.printStackTrace();
}
continue;
}
result = parser.parseJson(clientResponse.getEntity(String.class));
if (this.isVerbose) {
System.out.println(clientResponse.getHeaders());
System.out.println(result);
}
if (result != null && !result.getBoolean(RESPONSE_SUCCESS)) {
if (result.getJSONObject(RESPONSE_ERROR) != null && result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE) == 5) {
try {
clientResponse = crwdn.updateFile(credentials, parameters);
spinner.stop();
} catch (Exception e) {
System.out.println(" - ERROR");
System.out.println("code : " + result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE));
System.out.println("message : " + result.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE));
if (this.isDebug) {
e.printStackTrace();
}
continue;
}
result = parser.parseJson(clientResponse.getEntity(String.class));
if (this.isVerbose) {
System.out.println(clientResponse.getHeaders());
System.out.println(result);
}
}
}
} else {
ClientResponse clientResponse;
try {
clientResponse = crwdn.addFile(credentials, parameters);
spinner.stop();
} catch (Exception e) {
System.out.println(" - ERROR");
System.out.println("code : " + result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE));
System.out.println("message : " + result.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE));
if (this.isDebug) {
e.printStackTrace();
}
continue;
}
result = parser.parseJson(clientResponse.getEntity(String.class));
if (this.isVerbose) {
System.out.println(clientResponse.getHeaders());
System.out.println(result);
}
}
if (result != null && result.getBoolean(RESPONSE_SUCCESS)) {
if (result.has("files") && result.getJSONObject("files") != null) {
if (result.getJSONObject("files").has(preservePath) && "updated".equals(result.getJSONObject("files").getString(preservePath))) {
System.out.println(" - OK");
} else {
System.out.println(" - SKIPPED");
}
} else if (result.has("stats")) {
System.out.println(" - OK");
} else if (result.getJSONObject("notes") != null && result.getJSONObject("notes").getJSONArray("files") != null) {
System.out.println(" - OK");
} else {
System.out.println(" - SKIPPED");
}
} else if (result != null && !result.getBoolean(RESPONSE_SUCCESS) && result.getJSONObject(RESPONSE_ERROR) != null && result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE) == 5) {
System.out.println(" - SKIPPED");
} else if (result != null && !result.getBoolean(RESPONSE_SUCCESS)) {
System.out.println(" - ERROR");
System.out.println("code : " + result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE));
System.out.println("message : " + result.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE));
}
}
}
if (noFiles) {
System.out.println("Error: No source files to upload.\n" +
"Check your configuration file to ensure that they contain valid directives.");
System.exit(0);
}
return result;
}
/*
*
* Command 'crowdin upload translations'
*
*/
public JSONObject uploadTranslation(boolean importDuplicates, boolean importEqSuggestions, boolean autoApproveImported) {
CrowdinApiClient crwdn = new Crwdn();
JSONObject result = null;
Parser parser = new Parser();
List<FileBean> files = propertiesBean.getFiles();
boolean isLanguageExist = false;
for (FileBean file : files) {
JSONArray projectLanguages = projectInfo.getJSONArray("languages");
for (Object projectLanguage : projectLanguages) {
JSONObject languages = parser.parseJson(projectLanguage.toString());
if (languages != null && languages.getString("code") != null) {
JSONObject languageInfo = commandUtils.getLanguageInfo(languages.getString("name"), supportedLanguages);
if (language != null && !language.isEmpty() && languageInfo != null && !language.equals(languageInfo.getString("crowdin_code"))) {
continue;
}
isLanguageExist = true;
List<String> sourcesWithoutIgnores = commandUtils.getSourcesWithoutIgnores(file, propertiesBean);
for (String sourcesWithoutIgnore : sourcesWithoutIgnores) {
File sourcesWithoutIgnoreFile = new File(sourcesWithoutIgnore);
CrowdinApiParametersBuilder parameters = new CrowdinApiParametersBuilder();
parameters.headers(HEADER_ACCEPT, HEADER_ACCAEPT_VALUE)
.headers(HEADER_CLI_VERSION, HEADER_CLI_VERSION_VALUE)
.headers(HEADER_JAVA_VERSION, HEADER_JAVA_VERSION_VALUE)
.headers(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
String lng = (language == null || language.isEmpty()) ? languages.getString("code") : language;
List<String> translations = commandUtils.getTranslations(lng, sourcesWithoutIgnore, file, projectInfo, supportedLanguages, propertiesBean, "translations");
Map<String,String> mapping = commandUtils.doLanguagesMapping(projectInfo, supportedLanguages, propertiesBean);
List<File> translationFiles = new ArrayList<>();
String commonPath = "";
if (!propertiesBean.getPreserveHierarchy()) {
String[] common = new String[sourcesWithoutIgnores.size()];
common = sourcesWithoutIgnores.toArray(common);
commonPath = Utils.commonPath(common);
commonPath = Utils.replaceBasePath(commonPath, propertiesBean);
}
commonPath = (commonPath == null) ? "" : commonPath;
for (String translation : translations) {
translation = Utils.PATH_SEPARATOR + translation;
translation = translation.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
String mappedTranslations = translation;
if (Utils.isWindows() && translation.contains("\\")) {
translation = translation.replaceAll("\\\\+", "/").replaceAll(" \\+", "/");
}
if (mapping != null && (mapping.get(translation) != null || mapping.get("/" + translation) != null)) {
mappedTranslations = mapping.get(translation);
}
mappedTranslations = propertiesBean.getBasePath() + Utils.PATH_SEPARATOR + mappedTranslations;
mappedTranslations = mappedTranslations.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
translationFiles.add(new File(mappedTranslations));
}
for (File translationFile : translationFiles) {
if (!translationFile.isFile()) {
System.out.println("Translation file '" + translationFile.getAbsolutePath() + "' does not exist");
continue;
}
if (!sourcesWithoutIgnoreFile.isFile()) {
System.out.println("Source file '" + Utils.replaceBasePath(sourcesWithoutIgnoreFile.getAbsolutePath(), propertiesBean) + "' does not exist");
continue;
}
String translationSrc = Utils.replaceBasePath(sourcesWithoutIgnoreFile.getAbsolutePath(), propertiesBean);
if (!propertiesBean.getPreserveHierarchy()) {
if (Utils.isWindows()) {
if (translationSrc.contains("\\")) {
translationSrc = translationSrc.replaceAll("\\\\", "/");
translationSrc = translationSrc.replaceAll("/+", "/");
}
if (commonPath.contains("\\")) {
commonPath = commonPath.replaceAll("\\\\", "/");
commonPath = commonPath.replaceAll("/+", "/");
}
}
if (translationSrc.startsWith(commonPath)) {
translationSrc = translationSrc.replaceFirst(commonPath, "");
}
if (Utils.isWindows() && translationSrc.contains("/")) {
translationSrc = translationSrc.replaceAll("/", Utils.PATH_SEPARATOR_REGEX);
}
}
if (branch != null) {
parameters.branch(branch);
}
if (Utils.isWindows()) {
translationSrc = translationSrc.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/");
}
if (translationSrc.startsWith("/")) {
translationSrc = translationSrc.replaceFirst("/", "");
}
Boolean isDest = file.getDest() != null && !file.getDest().isEmpty() && !this.commandUtils.isSourceContainsPattern(file.getSource());
if (isDest) {
translationSrc = file.getDest();
if (!propertiesBean.getPreserveHierarchy()) {
if (translationSrc.lastIndexOf(Utils.PATH_SEPARATOR) != -1) {
translationSrc = translationSrc.substring(translationSrc.lastIndexOf(Utils.PATH_SEPARATOR));
}
translationSrc = translationSrc.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
}
if (Utils.isWindows()) {
translationSrc = translationSrc.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/");
}
if (translationSrc.startsWith("/")) {
translationSrc = translationSrc.replaceFirst("/", "");
}
}
parameters.files(translationFile.getAbsolutePath());
parameters.titles(translationSrc, translationSrc);
parameters.language(languages.getString("code"));
parameters.importDuplicates(importDuplicates);
parameters.importEqSuggestion(importEqSuggestions);
parameters.autoApproveImported(autoApproveImported);
parameters.json();
if (file.getUpdateOption() != null) {
parameters.updateOption(file.getUpdateOption());
}
System.out.print("Uploading translation file '" + Utils.replaceBasePath(translationFile.getAbsolutePath(), propertiesBean) + "'");
ClientResponse clientResponse;
Thread spinner = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
spin.turn();
}
}
});
try {
spinner.start();
clientResponse = crwdn.uploadTranslations(credentials, parameters);
spinner.stop();
} catch (Exception e) {
System.out.println(" - failed");
if (isDebug) {
e.printStackTrace();
}
continue;
}
result = parser.parseJson(clientResponse.getEntity(String.class));
if (result != null && result.getBoolean(RESPONSE_SUCCESS)) {
JSONObject jsonObjFiles = result.getJSONObject("files");
if (jsonObjFiles != null) {
Iterator<?> keys = jsonObjFiles.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
System.out.println(" - " + jsonObjFiles.getString(key));
}
}
} else if (result != null && !result.getBoolean(RESPONSE_SUCCESS)) {
JSONObject jsonObjError = result.getJSONObject(RESPONSE_ERROR);
if (jsonObjError != null && jsonObjError.getInt(RESPONSE_CODE) == 17 && "Specified directory was not found".equals(jsonObjError.getString(RESPONSE_MESSAGE))) {
if (branch != null) {
System.out.println(" error: branch '" + branch + "' does not exist in the project");
} else {
System.out.println(" error: directory does not exist in the project");
}
} else {
System.out.println(" error: " + jsonObjError.get("message"));
}
} else {
System.out.println(" - " + result);
}
if (isVerbose) {
System.out.println(clientResponse.getHeaders());
System.out.println(result);
}
}
}
}
}
}
if (!isLanguageExist) {
System.out.println("Language '" + language + "' does not exist in the project");
}
return result;
}
public void initCli() {
if (credentials == null) {
System.out.println(RESOURCE_BUNDLE.getString("wrong_connection"));
System.exit(0);
}
if (credentials.getProjectIdentifier() == null || credentials.getProjectKey() == null || credentials.getBaseUrl() == null
||credentials.getProjectIdentifier().isEmpty() || credentials.getProjectKey().isEmpty() || credentials.getBaseUrl().isEmpty()) {
if (credentials.getProjectIdentifier() == null || credentials.getProjectIdentifier().isEmpty()) {
System.out.println("Project identifier is empty");
}
if (credentials.getProjectKey() == null || credentials.getProjectKey().isEmpty()) {
System.out.println("Project key is empty");
}
if (credentials.getBaseUrl() == null || credentials.getBaseUrl().isEmpty()) {
System.out.println("Base url is empty");
}
System.exit(0);
}
CrowdinApiClient crwdn = new Crwdn();
JSONObject result = null;
Parser parser = new Parser();
String cliVersion = Utils.getAppVersion();
CrowdinApiParametersBuilder crowdinApiParametersBuilder = new CrowdinApiParametersBuilder();
crowdinApiParametersBuilder.json()
.version(cliVersion)
.headers(HEADER_ACCEPT, HEADER_ACCAEPT_VALUE)
.headers(HEADER_CLI_VERSION, HEADER_CLI_VERSION_VALUE)
.headers(HEADER_JAVA_VERSION, HEADER_JAVA_VERSION_VALUE)
.headers(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
ClientResponse clientResponse;
try {
clientResponse = crwdn.init(credentials,crowdinApiParametersBuilder);
result = parser.parseJson(clientResponse.getEntity(String.class));
} catch (Exception e) {
System.out.println(RESOURCE_BUNDLE.getString("initialisation_failed"));
if (isDebug) {
e.printStackTrace();
}
System.exit(0);
}
if (result == null) {
System.out.println(RESOURCE_BUNDLE.getString("initialisation_failed"));
System.exit(0);
}
if (result.has(RESPONSE_SUCCESS)) {
Boolean responseStatus = result.getBoolean(RESPONSE_SUCCESS);
if (responseStatus) {
if (result.has(RESPONSE_MESSAGE)) {
String message = result.getString(RESPONSE_MESSAGE);
if (message != null) {
System.out.println(message);
}
}
} else {
if (result.has(RESPONSE_ERROR)) {
JSONObject error = result.getJSONObject(RESPONSE_ERROR);
if (error == null) {
System.out.println("Initialization failed");
System.exit(0);
}
if (error.has(RESPONSE_CODE)) {
if ("0".equals(error.get(RESPONSE_CODE).toString())) {
if (error.has(RESPONSE_MESSAGE)) {
String message = error.getString(RESPONSE_MESSAGE);
if (message != null) {
System.out.println(message);
System.exit(0);
}
}
}
}
}
}
} else {
System.out.println(RESOURCE_BUNDLE.getString("initialisation_failed"));
System.exit(0);
}
}
private void download(String lang, boolean ignoreMatch) {
JSONObject result;
CrowdinApiClient crwdn = new Crwdn();
Parser parser = new Parser();
CrowdinApiParametersBuilder crowdinApiParametersBuilder = new CrowdinApiParametersBuilder();
crowdinApiParametersBuilder.headers(HEADER_ACCEPT, HEADER_ACCAEPT_VALUE)
.headers(HEADER_CLI_VERSION, HEADER_CLI_VERSION_VALUE)
.headers(HEADER_JAVA_VERSION, HEADER_JAVA_VERSION_VALUE)
.headers(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
Thread spinner = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
spin.turn();
}
}
});
String projectLanguage;
if (language != null) {
projectLanguage = language;
} else {
projectLanguage = lang;
}
if (branch != null) {
crowdinApiParametersBuilder.branch(branch);
}
if (projectLanguage != null) {
crowdinApiParametersBuilder.downloadPackage(projectLanguage);
crowdinApiParametersBuilder.exportLanguage(projectLanguage);
}
crowdinApiParametersBuilder.json();
System.out.print(RESOURCE_BUNDLE.getString("build_archive") + " for '" + projectLanguage + "'");
ClientResponse clientResponse = null;
try {
spinner.start();
clientResponse = crwdn.exportTranslations(credentials, crowdinApiParametersBuilder);
spinner.stop();
} catch (Exception e) {
System.out.println(" - error");
if (isDebug) {
e.printStackTrace();
}
System.exit(0);
}
result = parser.parseJson(clientResponse.getEntity(String.class));
if (result != null) {
if (result.get(RESPONSE_SUCCESS) instanceof JSONObject) {
if ("built".equals(result.getJSONObject(RESPONSE_SUCCESS).getString(RESPONSE_STATUS))) {
System.out.println(" - OK");
} else if ("skipped".equals(result.getJSONObject(RESPONSE_SUCCESS).getString(RESPONSE_STATUS))) {
System.out.println(" - skipped");
System.out.println(RESOURCE_BUNDLE.getString("export_skipped"));
}
} else if (!result.getBoolean(RESPONSE_SUCCESS)) {
if (result.getJSONObject(RESPONSE_ERROR) != null && result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE) == 10
&& "Language was not found".equals(result.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE))) {
System.out.println(" - error");
System.out.println("language '" + projectLanguage + "' does not exist in the project");
} else if (result.getJSONObject(RESPONSE_ERROR) != null && result.getJSONObject(RESPONSE_ERROR).getInt(RESPONSE_CODE) == 17
&& "Specified directory was not found".equals(result.getJSONObject(RESPONSE_ERROR).getString(RESPONSE_MESSAGE))) {
System.out.println("error");
System.out.println("branch '" + branch + "' does not exist in the project");
}
System.exit(0);
}
}
if (isVerbose) {
System.out.println(clientResponse.getHeaders());
System.out.println(result);
}
if (result != null && result.get(RESPONSE_SUCCESS) instanceof JSONObject) {
String fileName;
crowdinApiParametersBuilder = new CrowdinApiParametersBuilder();
crowdinApiParametersBuilder.headers(HEADER_ACCEPT, HEADER_ACCAEPT_VALUE)
.headers(HEADER_CLI_VERSION, HEADER_CLI_VERSION_VALUE)
.headers(HEADER_JAVA_VERSION, HEADER_JAVA_VERSION_VALUE)
.headers(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
if (projectLanguage != null) {
crowdinApiParametersBuilder.downloadPackage(projectLanguage);
fileName = projectLanguage + ".zip";
} else {
crowdinApiParametersBuilder.downloadPackage("all");
fileName = "all.zip";
}
if (branch != null) {
crowdinApiParametersBuilder.branch(branch);
}
String basePath = propertiesBean.getBasePath();
String baseTempDir;
if (basePath.endsWith(Utils.PATH_SEPARATOR)) {
baseTempDir = basePath + new Timestamp(System.currentTimeMillis()).getTime();
} else {
baseTempDir = basePath + Utils.PATH_SEPARATOR + new Timestamp(System.currentTimeMillis()).getTime();
}
crowdinApiParametersBuilder.destinationFolder(basePath);
try {
if (Thread.State.TERMINATED.equals(spinner.getState())) {
spinner = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
spin.turn();
}
}
});
}
spinner.start();
} catch (IllegalThreadStateException e) {
}
clientResponse = crwdn.downloadTranslations(credentials, crowdinApiParametersBuilder);
try {
spinner.stop();
} catch (IllegalThreadStateException e) {
}
String downloadResult = clientResponse.getEntity(String.class);
if (isVerbose) {
System.out.println(clientResponse.getHeaders());
System.out.println(downloadResult);
}
File downloadedZipArchive;
if (propertiesBean.getBasePath() != null && !propertiesBean.getBasePath().endsWith(Utils.PATH_SEPARATOR)) {
downloadedZipArchive = new File(propertiesBean.getBasePath() + Utils.PATH_SEPARATOR + fileName);
} else {
downloadedZipArchive = new File(propertiesBean.getBasePath() + fileName);
}
try {
List<String> downloadedFiles = commandUtils.getListOfFileFromArchive(downloadedZipArchive, isDebug);
List<String> downloadedFilesProc = new ArrayList<>();
for (String downloadedFile : downloadedFiles) {
if (Utils.isWindows()) {
downloadedFile = downloadedFile.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/");
}
downloadedFilesProc.add(downloadedFile);
}
List<String> files = new ArrayList<>();
Map<String, String> mapping = commandUtils.doLanguagesMapping(projectInfo, supportedLanguages, propertiesBean);
List<String> translations = this.list(TRANSLATIONS, "download");
for (String translation : translations) {
translation = translation.replaceAll("/+", "/");
if (!files.contains(translation)) {
//TODO: This usage is a bit unclear. Is the string supposed to be a regex or not?
if (translation.contains(Utils.PATH_SEPARATOR_REGEX)) {
translation = translation.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/");
} else if (translation.contains(Utils.PATH_SEPARATOR)) {
translation = translation.replaceAll(Utils.PATH_SEPARATOR_REGEX + Utils.PATH_SEPARATOR_REGEX, "/");
}
translation = translation.replaceAll("/+", "/");
files.add(translation);
}
}
List<String> sources = this.list(SOURCES, null);
String commonPath;
String[] common = new String[sources.size()];
common = sources.toArray(common);
commonPath = Utils.commonPath(common);
commonPath = Utils.replaceBasePath(commonPath, propertiesBean);
if (commonPath.contains("\\")) {
commonPath = commonPath.replaceAll("\\\\+", "/");
}
commandUtils.sortFilesName(downloadedFilesProc);
commandUtils.extractFiles(downloadedFilesProc, files, baseTempDir, ignoreMatch, downloadedZipArchive, mapping, isDebug, branch, propertiesBean, commonPath);
commandUtils.renameMappingFiles(mapping, baseTempDir, propertiesBean, commonPath);
FileUtils.deleteDirectory(new File(baseTempDir));
downloadedZipArchive.delete();
} catch (java.util.zip.ZipException e) {
System.out.println(RESOURCE_BUNDLE.getString("error_open_zip"));
if (isDebug) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println(RESOURCE_BUNDLE.getString("error_extracting_files"));
if (isDebug) {
e.printStackTrace();
}
}
}
}
public void downloadTranslation(boolean ignoreMatch) {
Parser parser = new Parser();
if (language != null) {
this.download(language, ignoreMatch);
} else {
JSONArray projectLanguages = projectInfo.getJSONArray("languages");
for (Object projectLanguage : projectLanguages) {
JSONObject languages = parser.parseJson(projectLanguage.toString());
if (languages != null && languages.getString("code") != null) {
JSONObject languageInfo = commandUtils.getLanguageInfo(languages.getString("name"), supportedLanguages);
String crowdinCode = languageInfo.getString("crowdin_code");
this.download(crowdinCode, ignoreMatch);
}
}
}
}
public List<String> list(String subcommand, String command) {
List<String> result = new ArrayList<>();
if (subcommand != null && !subcommand.isEmpty()) {
if (PROJECT.equals(subcommand)) {
List<String> files = commandUtils.projectList(projectInfo.getJSONArray("files"), null);
if (branch != null) {
for (String file : files) {
if (file.startsWith(branch) || file.startsWith("/" + branch)) {
result.add(Utils.PATH_SEPARATOR + file);
}
}
} else {
result = files;
}
} else if (SOURCES.equals(subcommand)) {
List<FileBean> files = propertiesBean.getFiles();
for (FileBean file : files) {
result.addAll(commandUtils.getSourcesWithoutIgnores(file, propertiesBean));
}
} else if (TRANSLATIONS.equals(subcommand)) {
List<FileBean> files = propertiesBean.getFiles();
for (FileBean file : files) {
result.addAll(commandUtils.getTranslations(null, null, file, projectInfo, supportedLanguages, propertiesBean, command));
}
}
}
return result;
}
public void help(String resultCmd) {
if (null != resultCmd) {
if (HELP.equals(resultCmd) || "".equals(resultCmd)) {
cliOptions.cmdGeneralOptions();
} else if (HELP_UPLOAD.equals(resultCmd)) {
cliOptions.cmdUploadOptions();
} else if (HELP_UPLOAD_SOURCES.equals(resultCmd)) {
cliOptions.cmdUploadSourcesOptions();
} else if (HELP_UPLOAD_TRANSLATIONS.equals(resultCmd)) {
cliOptions.cmdUploadTranslationsOptions();
} else if (HELP_DOWNLOAD.equals(resultCmd)) {
cliOptions.cmdDownloadOptions();
} else if (HELP_LIST.equals(resultCmd)) {
cliOptions.cmdListOptions();
} else if (HELP_LINT.equals(resultCmd)) {
cliOptions.cmdLintOptions();
} else if (HELP_LIST_PROJECT.equals(resultCmd)) {
cliOptions.cmdListProjectOptions();
} else if (HELP_LIST_SOURCES.equals(resultCmd)) {
cliOptions.cmdListSourcesOptions();
} else if (HELP_LIST_TRANSLATIONS.equals(resultCmd)) {
cliOptions.cmdListTranslationsIOptions();
} else if (HELP_GENERATE.equals(resultCmd)) {
cliOptions.cmdGenerateOptions();
}
}
}
private void dryrunSources(CommandLine commandLine) {
List<String> files = this.list(SOURCES, "sources");
if (files.size() < 1 ) {
System.exit(0);
}
commandUtils.sortFilesName(files);
String commonPath = "";
if (!propertiesBean.getPreserveHierarchy()) {
commonPath = commandUtils.getCommonPath(files, propertiesBean);
}
if (commandLine.hasOption(COMMAND_TREE)) {
DrawTree drawTree = new DrawTree();
List filesTree = new ArrayList();
for (String file : files) {
if (propertiesBean.getPreserveHierarchy()) {
filesTree.add(Utils.replaceBasePath(file, propertiesBean));
} else {
StringBuilder resultFiles = new StringBuilder();
StringBuilder f = new StringBuilder();
String path = Utils.replaceBasePath(file, propertiesBean);
if (Utils.isWindows()) {
if (path.contains("\\")) {
path = path.replaceAll("\\\\", "/");
path = path.replaceAll("/+", "/");
}
if (commonPath.contains("\\")) {
commonPath = commonPath.replaceAll("\\\\", "/");
commonPath = commonPath.replaceAll("/+", "/");
}
}
if (path.startsWith(commonPath)) {
path = path.replaceFirst(commonPath, "");
} else if (path.startsWith("/" + commonPath)) {
path = path.replaceFirst("/" + commonPath, "");
}
if (Utils.isWindows() && path.contains("/")) {
path = path.replaceAll("/", Utils.PATH_SEPARATOR_REGEX);
}
if (path.startsWith(Utils.PATH_SEPARATOR)) {
path = path.replaceFirst(Utils.PATH_SEPARATOR_REGEX, "");
}
String[] nodes = path.split(Utils.PATH_SEPARATOR_REGEX);
for (String node : nodes) {
if (node != null && !node.isEmpty()) {
f.append(node).append(Utils.PATH_SEPARATOR);
String preservePath = propertiesBean.getBasePath() + Utils.PATH_SEPARATOR + commonPath + Utils.PATH_SEPARATOR + f;
preservePath = preservePath.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
File treeFile = new File(preservePath);
if (treeFile.isDirectory()) {
resultFiles.append(node).append(Utils.PATH_SEPARATOR);
} else {
resultFiles.append(node);
}
}
}
filesTree.add(resultFiles.toString());
}
}
if (branch != null) {
System.out.println(branch);
}
int ident = propertiesBean.getPreserveHierarchy() ? -1 : 0;
drawTree.draw(filesTree, ident);
} else {
String src;
for (String file : files) {
if (propertiesBean.getPreserveHierarchy()) {
src = Utils.replaceBasePath(file, propertiesBean);
if (branch != null && !branch.isEmpty()) {
src = Utils.PATH_SEPARATOR + branch + Utils.PATH_SEPARATOR + src;
}
src = src.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
System.out.println(src);
} else {
src = Utils.replaceBasePath(file, propertiesBean);
if (Utils.isWindows()) {
if (src.contains("\\")) {
src = src.replaceAll("\\\\", "/");
src = src.replaceAll("/+", "/");
}
if (commonPath.contains("\\")) {
commonPath = commonPath.replaceAll("\\\\", "/");
commonPath = commonPath.replaceAll("/+", "/");
}
}
if (src.startsWith(commonPath)) {
src = src.replaceFirst(commonPath, "");
} else if (src.startsWith("/" + commonPath)) {
src = src.replaceFirst("/" + commonPath, "");
}
if (Utils.isWindows() && src.contains("/")) {
src = src.replaceAll("/", Utils.PATH_SEPARATOR_REGEX);
}
if (branch != null && !branch.isEmpty()) {
src = branch + Utils.PATH_SEPARATOR + src;
}
src = src.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
System.out.println(src);
}
}
}
}
private void dryrunTranslation(CommandLine commandLine) {
List<String> files = new ArrayList<>();
Set<String> translations = new HashSet<>();
Map<String, String> mappingTranslations = commandUtils.doLanguagesMapping(projectInfo, supportedLanguages, propertiesBean);
String commonPath;
String[] common = new String[mappingTranslations.values().size()];
common = mappingTranslations.values().toArray(common);
commonPath = Utils.commonPath(common);
for (Map.Entry<String, String> mappingTranslation : mappingTranslations.entrySet()) {
String s = mappingTranslation.getValue().replaceAll("/+", Utils.PATH_SEPARATOR_REGEX);
if (!propertiesBean.getPreserveHierarchy()) {
if (s.startsWith(commonPath)) {
s = s.replaceFirst(commonPath, "");
}
}
translations.add(s);
}
files.addAll(translations);
commandUtils.sortFilesName(files);
if (commandLine.hasOption(COMMAND_TREE)) {
DrawTree drawTree = new DrawTree();
int ident = -1;
drawTree.draw(files, ident);
} else {
for (String file : files) {
System.out.println(file);
}
}
}
private void dryrunProject(CommandLine commandLine) {
List<String> files = this.list(PROJECT, "project");
List<String> filesWin = new ArrayList<>();
for (String file : files) {
file = file.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX);
filesWin.add(file);
}
commandUtils.sortFilesName(files);
commandUtils.sortFilesName(filesWin);
if (commandLine.hasOption(COMMAND_TREE)) {
DrawTree drawTree = new DrawTree();
int ident = -1;
drawTree.draw(filesWin, ident);
} else {
for (String file : files) {
System.out.println(file.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX));
}
}
}
private void lint() {
if (cliConfig == null) {
System.out.println(RESOURCE_BUNDLE.getString("configuration_file_empty"));
System.exit(0);
} else {
CliProperties cliProperties = new CliProperties();
PropertiesBean propertiesBean = cliProperties.loadProperties(cliConfig);
PropertiesBean propertiesBeanIdentity = null;
if (identityCliConfig != null) {
propertiesBeanIdentity = cliProperties.loadProperties(identityCliConfig);
}
if (propertiesBean == null && propertiesBeanIdentity == null) {
System.out.println(RESOURCE_BUNDLE.getString("configuration_file_empty"));
System.exit(0);
}
if (propertiesBean == null || (propertiesBean != null && propertiesBean.getProjectIdentifier() == null)) {
if (propertiesBeanIdentity == null || (propertiesBeanIdentity != null && propertiesBeanIdentity.getProjectIdentifier() == null)) {
System.out.println(RESOURCE_BUNDLE.getString("error_missed_project_identifier"));
System.exit(0);
}
}
if (propertiesBean == null || (propertiesBean != null && propertiesBean.getApiKey() == null)) {
if (propertiesBeanIdentity == null || (propertiesBeanIdentity != null && propertiesBeanIdentity.getApiKey() == null)) {
System.out.println(RESOURCE_BUNDLE.getString("error_missed_api_key"));
System.exit(0);
}
}
if (propertiesBean == null || (propertiesBean != null && propertiesBean.getBaseUrl() == null)) {
if (propertiesBeanIdentity == null || (propertiesBeanIdentity != null && propertiesBeanIdentity.getBaseUrl() == null)) {
String baseUrl = Utils.getBaseUrl();
if (baseUrl == null || baseUrl.isEmpty()) {
System.out.println(RESOURCE_BUNDLE.getString("missed_base_url"));
System.exit(0);
}
}
}
String basePath = null;
if (propertiesBean == null || (propertiesBean != null && propertiesBean.getBasePath() == null)) {
if (propertiesBeanIdentity == null || (propertiesBeanIdentity != null && propertiesBeanIdentity.getBasePath() == null)) {
} else {
basePath = propertiesBeanIdentity.getBasePath();
}
} else {
basePath = propertiesBean.getBasePath();
}
if (basePath != null && !basePath.isEmpty()) {
File base = new File(basePath);
if (!base.exists()) {
System.out.println(RESOURCE_BUNDLE.getString("bad_base_path"));
System.exit(0);
}
}
if (propertiesBean.getFiles() == null) {
System.out.println(RESOURCE_BUNDLE.getString("error_missed_section_files"));
System.exit(0);
} else if (propertiesBean.getFiles().isEmpty()) {
System.out.println(RESOURCE_BUNDLE.getString("empty_section_file"));
System.exit(0);
} else {
for (FileBean fileBean : propertiesBean.getFiles()) {
if (fileBean.getSource() == null || fileBean.getSource().isEmpty()) {
System.out.println(RESOURCE_BUNDLE.getString("error_empty_section_source_or_translation"));
System.exit(0);
}
if (fileBean.getTranslation() == null || fileBean.getTranslation().isEmpty()) {
System.out.println(RESOURCE_BUNDLE.getString("error_empty_section_source_or_translation"));
System.exit(0);
}
}
}
}
System.out.println(RESOURCE_BUNDLE.getString("configuration_ok"));
}
} |
package com.d2fn.passage.geometry;
/**
* Point3D
* @author Dietrich Featherston
*/
public class Point3D implements Projectable3D {
private final float x, y, z;
public Point3D(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public float x() {
return x;
}
@Override
public float y() {
return y;
}
@Override
public float z() {
return z;
}
@Override
public Projectable3D add(Projectable3D p) {
return new Point3D(x() + p.x(), y() + p.y(), z() + p.z());
}
public Projectable2D add(Projectable2D b) {
return new Point2D(x() + b.x(), y() + b.y());
}
public Projectable2D sub(Projectable2D b) {
return new Point2D(x() - b.x(), y() - b.y());
}
public Projectable2D mid(Projectable2D b) {
return new Point2D((x() + b.x())/2, (y() + b.y())/2);
}
public Projectable2D scale(float amt) {
return new Point2D(x * amt, y * amt);
}
public static final Point3D origin = new Point3D(0, 0, 0);
} |
package com.fhaidary.xmlcmd.core;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonWriter;
public final class JsonTool {
private static final JsonParser parser = new JsonParser();
public static void convert2Json(String file) throws IOException, XMLStreamException {
// Set it up...
StringWriter out = new StringWriter();
JsonWriter writer = new JsonWriter(out);
writer.setIndent(" ");
// Work...
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
XMLStreamReader xml = factory.createXMLStreamReader(new FileInputStream(file), "UTF8");
convert2Json(xml, writer);
// Finish...
xml.close();
writer.close();
// Output it!
System.out.println(out.toString().trim());
}
private static void convert2Json(XMLStreamReader xml, JsonWriter json) throws XMLStreamException, IOException {
for (int event = xml.getEventType();; event = xml.next()) {
String itemName;
switch (event) {
case XMLStreamReader.START_DOCUMENT:
json.beginObject();
break;
case XMLStreamReader.START_ELEMENT:
String fix = xml.getPrefix();
String name = xml.getLocalName();
itemName = fix == null || fix.isEmpty() ? name : fix + "_" + name;
json.name(itemName);
json.beginObject();
for (int i = 0; i < xml.getAttributeCount(); i++) {
String attrFix = xml.getAttributePrefix(i);
String attrName = xml.getAttributeLocalName(i);
String attrVal = xml.getAttributeValue(i);
attrName = attrFix == null || attrFix.isEmpty() ? attrName : attrFix + "_" + attrName;
json.name(attrName);
json.value(attrVal);
}
for (int i = 0; i < xml.getNamespaceCount(); i++) {
String nsName = xml.getNamespacePrefix(i);
nsName = nsName == null ? "xmlns" : "xmlns_" + nsName;
String nsVal = xml.getNamespaceURI(i);
json.name(nsName);
json.value(nsVal);
}
break;
case XMLStreamReader.CHARACTERS:
String txt = xml.getText().trim();
if (!txt.isEmpty()) {
try {
JsonElement elem = parser.parse('{' + txt + '}');
json.name("#sub");
json.jsonValue(elem.toString());
} catch (JsonSyntaxException jse) {
json.name("#txt");
json.value(txt);
}
}
break;
case XMLStreamReader.END_ELEMENT:
itemName = xml.getLocalName();
json.endObject();
break;
case XMLStreamReader.END_DOCUMENT:
json.endObject();
return;
default:
throw new UnsupportedOperationException(findConstant(event) + "!");
}
}
}
private static String findConstant(int code) {
try {
for (Field field : XMLStreamConstants.class.getFields()) {
int value = (Integer) field.get(null);
if (code == value)
return field.getName();
}
return null;
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
} |
package com.github.davidmoten.rx2;
import java.util.concurrent.atomic.AtomicBoolean;
import io.reactivex.functions.Action;
public final class Actions {
private Actions() {
// prevent instantiation
}
public static Action setToTrue(final AtomicBoolean b) {
return new Action() {
@Override
public void run() throws Exception {
b.set(true);
}
};
}
public static Action throwing(final Exception e) {
return new Action() {
@Override
public void run() throws Exception {
throw e;
}
};
}
} |
package com.github.onsdigital.json;
import com.github.onsdigital.generator.Folder;
public class DataT3 extends Data {
public DataT3(Folder folder) {
super(folder, 3);
level = "t3";
lede = "Consumer price inflation is the speed at which the prices of goods and services bought by households rise or fall.";
more = "Some more content goes here. This will expand and contract if you have JS enabled. If JS is disabled, "
+ "this will show by default. Yay progressive enhancement!";
}
} |
package com.jaamsim.BasicObjects;
import java.util.ArrayList;
import com.jaamsim.Graphics.DisplayEntity;
import com.jaamsim.ProbabilityDistributions.Distribution;
import com.jaamsim.Samples.SampleConstant;
import com.jaamsim.Samples.SampleExpInput;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.datatypes.DoubleVector;
import com.jaamsim.input.InputErrorException;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.units.DimensionlessUnit;
public class Resource extends DisplayEntity {
@Keyword(description = "The number of equivalent resource units that are available.\n" +
"The input can be a constant value, a time series, or an expression.",
exampleList = {"3", "TimeSeries1", "this.attrib1"})
private final SampleExpInput capacity;
private int unitsInUse; // number of resource units that are being used at present
private ArrayList<Seize> seizeList; // Seize objects that require this resource
// Statistics
protected double timeOfLastUpdate; // time at which the statistics were last updated
protected double startOfStatisticsCollection; // time at which statistics collection was started
protected int minUnitsInUse; // minimum observed number of units in use
protected int maxUnitsInUse; // maximum observed number of units in use
protected double unitSeconds; // total time that units have been used
protected double squaredUnitSeconds; // total time for the square of the number of units in use
protected int unitsSeized; // number of units that have been seized
protected int unitsReleased; // number of units that have been released
protected DoubleVector unitsInUseDist; // entry at position n is the total time that n units have been in use
{
attributeDefinitionList.setHidden(false);
capacity = new SampleExpInput("Capacity", "Key Inputs", new SampleConstant(1.0));
capacity.setUnitType(DimensionlessUnit.class);
capacity.setEntity(this);
capacity.setValidRange(0, Double.POSITIVE_INFINITY);
this.addInput(capacity);
}
public Resource() {
unitsInUseDist = new DoubleVector();
seizeList = new ArrayList<>();
}
@Override
public void validate() {
boolean found = false;
for (Seize ent : Entity.getClonesOfIterator(Seize.class)) {
if( ent.requiresResource(this) )
found = true;
}
if (!found)
throw new InputErrorException( "At least one Seize object must use this resource." );
if( capacity.getValue() instanceof Distribution )
throw new InputErrorException( "The Capacity keyword cannot accept a probability distribution.");
}
@Override
public void earlyInit() {
super.earlyInit();
unitsInUse = 0;
// Clear statistics
this.clearStatistics();
// Prepare a list of the Seize objects that use this resource
seizeList.clear();
for (Seize ent : Entity.getClonesOfIterator(Seize.class)) {
if( ent.requiresResource(this) )
seizeList.add(ent);
}
}
/**
* Return the number of units that are available for use at the present time
* @return
*/
public int getAvailableUnits() {
return (int) capacity.getValue().getNextSample(this.getSimTime()) - unitsInUse;
}
/**
* Seize the given number of units from the resource.
* @param n = number of units to seize
*/
public void seize(int n) {
this.updateStatistics(unitsInUse, unitsInUse+n);
unitsInUse += n;
unitsSeized += n;
}
/**
* Release the given number of units back to the resource.
* @param n = number of units to release
*/
public void release(int m) {
int n = Math.min(m, unitsInUse);
this.updateStatistics(unitsInUse, unitsInUse-n);
unitsInUse -= n;
unitsReleased += n;
}
/**
* Notify all the Seize object that the number of available units of this Resource has increased.
*/
public void notifySeizeObjects() {
// Notify the Seize object(s) that can use the released units
int cap = (int) capacity.getValue().getNextSample(this.getSimTime());
while( cap > unitsInUse ) {
// Pick the Seize object that has waited the longest
Seize selection = null;
double maxTime = 0;
for(Seize s : seizeList) {
Queue que = s.getQueue();
if( que.getCount() > 0 ) {
if( selection == null || que.getQueueTime() > maxTime ) {
selection = s;
maxTime = que.getQueueTime();
}
}
}
// Ensure that the selected Seize object is able to start
if (selection == null || !selection.isReadyToStart())
return;
selection.startAction();
}
}
// STATISTICS
/**
* Clear queue statistics
*/
@Override
public void clearStatistics() {
double simTime = this.getSimTime();
startOfStatisticsCollection = simTime;
timeOfLastUpdate = simTime;
minUnitsInUse = unitsInUse;
maxUnitsInUse = unitsInUse;
unitSeconds = 0.0;
squaredUnitSeconds = 0.0;
unitsSeized = 0;
unitsReleased = 0;
for (int i=0; i<unitsInUseDist.size(); i++) {
unitsInUseDist.set(i, 0.0d);
}
}
public void updateStatistics( int oldValue, int newValue) {
minUnitsInUse = Math.min(newValue, minUnitsInUse);
maxUnitsInUse = Math.max(newValue, maxUnitsInUse);
// Add the necessary number of additional bins to the queue length distribution
int n = newValue + 1 - unitsInUseDist.size();
for( int i=0; i<n; i++ ) {
unitsInUseDist.add(0.0);
}
double simTime = this.getSimTime();
double dt = simTime - timeOfLastUpdate;
if( dt > 0.0 ) {
unitSeconds += dt * oldValue;
squaredUnitSeconds += dt * oldValue * oldValue;
unitsInUseDist.addAt(dt,oldValue); // add dt to the entry at index queueSize
timeOfLastUpdate = simTime;
}
}
// OUTPUT METHODS
@Output(name = "UnitsSeized",
description = "The total number of resource units that have been seized.",
unitType = DimensionlessUnit.class,
reportable = true)
public int getUnitsSeized(double simTime) {
return unitsSeized;
}
@Output(name = "UnitsReleased",
description = "The total number of resource units that have been released.",
unitType = DimensionlessUnit.class,
reportable = true)
public int getUnitsReleased(double simTime) {
return unitsReleased;
}
@Output(name = "UnitsInUse",
description = "The present number of resource units that are in use.",
unitType = DimensionlessUnit.class)
public double getUnitsInUse(double simTime) {
return unitsInUse;
}
@Output(name = "UnitsInUseAverage",
description = "The average number of resource units that are in use.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getUnitsInUseAverage(double simTime) {
double dt = simTime - timeOfLastUpdate;
double totalTime = simTime - startOfStatisticsCollection;
if( totalTime > 0.0 ) {
return (unitSeconds + dt*unitsInUse)/totalTime;
}
return 0.0;
}
@Output(name = "UnitsInUseStandardDeviation",
description = "The standard deviation of the number of resource units that are in use.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getUnitsInUseStandardDeviation(double simTime) {
double dt = simTime - timeOfLastUpdate;
double mean = this.getUnitsInUseAverage(simTime);
double totalTime = simTime - startOfStatisticsCollection;
if( totalTime > 0.0 ) {
return Math.sqrt( (squaredUnitSeconds + dt*unitsInUse*unitsInUse)/totalTime - mean*mean );
}
return 0.0;
}
@Output(name = "UnitsInUseMinimum",
description = "The minimum number of resource units that are in use.",
unitType = DimensionlessUnit.class,
reportable = true)
public int getUnitsInUseMinimum(double simTime) {
return minUnitsInUse;
}
@Output(name = "UnitsInUseMaximum",
description = "The maximum number of resource units that are in use.",
unitType = DimensionlessUnit.class,
reportable = true)
public int getUnitsInUseMaximum(double simTime) {
// A unit that is seized and released immediately
// does not count as a non-zero maximum in use
if( maxUnitsInUse == 1 && unitsInUseDist.get(1) == 0.0 )
return 0;
return maxUnitsInUse;
}
@Output(name = "UnitsInUseDistribution",
description = "The fraction of time that the number of resource units in use was 0, 1, 2, etc.",
unitType = DimensionlessUnit.class,
reportable = true)
public DoubleVector getUnitsInUseDistribution(double simTime) {
DoubleVector ret = new DoubleVector(unitsInUseDist);
double dt = simTime - timeOfLastUpdate;
double totalTime = simTime - startOfStatisticsCollection;
if( totalTime > 0.0 ) {
if( ret.size() == 0 )
ret.add(0.0);
ret.addAt(dt, unitsInUse); // adds dt to the entry at index unitsInUse
for( int i=0; i<ret.size(); i++ ) {
ret.set(i, ret.get(i)/totalTime);
}
}
else {
ret.clear();
}
return ret;
}
} |
package com.nhl.bootique.jopt;
import static java.util.stream.Collectors.toList;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import javax.swing.JOptionPane;
import com.nhl.bootique.cli.Options;
import com.nhl.bootique.log.BootLogger;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
/**
* {@link Options} implementation on top of {@link JOptionPane} library.
*/
public class JoptOptions implements Options {
private OptionParser parser;
private OptionSet optionSet;
private BootLogger bootLogger;
public JoptOptions(BootLogger bootLogger, OptionParser parser, OptionSet parsed) {
this.parser = parser;
this.optionSet = parsed;
this.bootLogger = bootLogger;
}
@Override
public void printHelp(Writer out) {
try {
parser.printHelpOn(out);
} catch (IOException e) {
bootLogger.stderr("Error printing help", e);
}
}
@Override
public boolean hasOption(String optionName) {
return optionSet.has(optionName);
}
@Override
public Collection<String> stringsFor(String optionName) {
return optionSet.valuesOf(optionName).stream().map(o -> String.valueOf(o)).collect(toList());
}
} |
package com.orctom.mojo.was;
import com.orctom.mojo.was.model.WebSphereModel;
import com.orctom.mojo.was.service.WebSphereServiceFactory;
import com.orctom.mojo.was.utils.AntTaskUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.util.StringUtils;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Mojo(name = "deploy", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresDirectInvocation = true, threadSafe = true)
public class WASDeployMojo extends AbstractWASMojo {
@Parameter
protected String parallel;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info(Constants.PLUGIN_ID + " - deploy");
Set<WebSphereModel> models = getWebSphereModels();
if (models.isEmpty()) {
getLog().info("[SKIPPED DEPLOYMENT] empty target server configured, please check your configuration");
return;
}
boolean parallelDeploy = StringUtils.isEmpty(parallel) ? models.size() > 1 : Boolean.valueOf(parallel);
if (parallelDeploy) {
ExecutorService executor = Executors.newFixedThreadPool(models.size());
for (final WebSphereModel model : models) {
executor.execute(new Runnable() {
@Override
public void run() {
execute(model);
}
});
}
executor.shutdown();
try {
executor.awaitTermination(20, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for (WebSphereModel model : models) {
execute(model);
}
}
}
private void execute(WebSphereModel model) {
getLog().info("============================================================");
getLog().info("[DEPLOY] " + model.getHost() + " " + model.getApplicationName());
getLog().info("============================================================");
executeAntTasks(model, super.preSteps);
getLog().info("====================== deploy ========================");
WebSphereServiceFactory.getService(mode, model, project.getBuild().getDirectory()).deploy();
executeAntTasks(model, super.postSteps);
}
private void executeAntTasks(WebSphereModel model, PlexusConfiguration[] targets) {
if (null == targets || 0 == targets.length) {
return;
}
for (PlexusConfiguration target : targets) {
try {
AntTaskUtils.execute(model, target, project, projectHelper, pluginArtifacts, getLog());
} catch (IOException e) {
e.printStackTrace();
} catch (MojoExecutionException e) {
e.printStackTrace();
}
}
}
} |
package com.raycloud.util.daogen;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.raycloud.util.daogen.util.StringUtil;
public class GenTable {
private final Logger logger = Logger.getLogger(GenTable.class);
private DbConn conn;
private Settings settings;
private List<String> allTableName;
private String alltables;
private Map<String,List<String>> allTablePK;
public GenTable(DbConn dbConn){
conn = dbConn;
settings = dbConn.getSettings();
allTableName = getTableName();
alltables = allTableName.toString().replaceAll("\\[", "'").replaceAll("\\]", "'").replaceAll(", ", "','");
// allTablePK = getAllTablePK();
allTablePK = getAllTablePKBYIndex();
}
/**
*
*
* @param tableName
* @param conf
* @return
*/
public TableBean prepareTableBean(String tableName, TableConfig conf) {
if (conf == null) conf = TableConfig.DEFAULT;
if(StringUtils.isBlank(tableName)) return null;
tableName = tableName.toLowerCase();
logger.info("" + tableName);
if(!allTableName.contains(tableName)){
logger.error("["+tableName+"],DAO");
return null;
}
TableBean tableBean = new TableBean(tableName, conf);
this.setTableColumn(tableBean);
//Bean
this.convertTableBean(tableBean);
//Bean
if(!checkTableBean(tableBean)){
return null;
}
logger.info("" + tableName);
return tableBean;
}
private boolean checkTableBean(TableBean tableBean){
// if (tableBean.getPkcol() == null) {
// logger.error("["+tableBean.getTableName()+"],DAO");
// return false;
// id,id
// if (!"id".equals(tableBean.getPkcol().getColName())) {
// logger.error("["+tableBean.getTableName()+"]id,DAO");
// return false;
// gmt_creategmt_modified
// List<ColBean> cbList = tableBean.getColList();
// boolean hasGmtCreate = false;
// boolean hasGmtModified = false;
// for(ColBean cb:cbList){
// if("gmtCreate".equals(cb.getPropertyName())) hasGmtCreate = true;
// if("gmtModified".equals(cb.getPropertyName())) hasGmtModified = true;
// if(!hasGmtCreate||!hasGmtModified){
// logger.error("["+tableBean.getTableName()+"]gmt_creategmt_modified,DAO");
// return false;
return true;
}
/**
*
* @param tableBean
* @return
*/
private TableBean convertTableBean(TableBean tableBean) {
if (tableBean.getPkcol() != null) {
List<ColBean> cbs = tableBean.getPkcol();
for (ColBean cb : cbs) {
cb.setPropertyName(ColBean.getPropName(cb.getColName()));
// cb.setPropertyName("id");
cb.setMethodName(ColBean.getMethodName(cb.getPropertyName()));
cb.setPropertyType(SqlType2Feild.mapJavaType(cb.getColSQLType()));
// cb.setHibernateType(FieldMapping.mapHibernateType(cb.getColSQLType()));
}
}
List<ColBean> ll = tableBean.getColList();
for (Iterator<ColBean> it = ll.iterator(); it.hasNext();) {
ColBean cb = it.next();
cb.setPropertyName(ColBean.getPropName(cb.getColName()));
cb.setMethodName(ColBean.getMethodName(cb.getPropertyName()));
cb.setPropertyType(SqlType2Feild.mapJavaType(cb.getColSQLType()));
}
if (tableBean.getPkcol().size() > 0) {
for (ColBean bean : tableBean.getPkcol()) {
if(!tableBean.getColMap().containsKey(bean.getColName())){
tableBean.getColMap().put(bean.getColName(), bean);
ll.add(0, bean);
}
}
}
return tableBean;
}
/**
*
* @return
*/
public List<String> getTableName() {
if(allTableName!=null&&!allTableName.isEmpty()) return allTableName;
DatabaseMetaData dbmd = null;
ResultSet rs = null;
List<String> tableList = new ArrayList<String>();
try {
dbmd = conn.getDatabaseMetaData();
/*(catalog,schemaPattern,tableNamePattern,types)
* 5,(schema,catalog,table_name,table_type,?)*/
String[] types = { "TABLE" }; //"TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM"
rs = dbmd.getTables(null, null, "%", types);
logger.info("============================");
while (rs.next()) {
tableList.add(rs.getString(3).trim());
logger.info("Schema" + StringUtil.genLengthStr(rs.getString(1),10)
+""+ StringUtil.genLengthStr(rs.getString(3),25)
+""+ StringUtil.genLengthStr(rs.getString(4),10)
+""+ StringUtil.genLengthStr(rs.getString(5),30)+""); //Mysql
}
} catch (SQLException e) {
logger.error("", e);
}
if(!Gen.tconfig.keySet().isEmpty()){
List<String> tabs = new ArrayList<String>();
for(String t:Gen.tconfig.keySet()){
if(tableList.contains(t)){
tabs.add(t);
}else{
logger.error("["+t+"]");
}
}
tableList = tabs;
}
return tableList;
}
/**
*
* @return
*/
private Map<String, List<String>> getAllTablePK(){
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
DatabaseMetaData dbmd = null;
ResultSet rs = null;
try {
dbmd = conn.getDatabaseMetaData();
/*(catalog,schemaPattern,tableName)
*6,
*DatabaseMetaData.getPrimaryKeys(catalog, schema, table)
*/
logger.info("============================");
for(String t:allTableName){
rs = dbmd.getPrimaryKeys(null, null, t);
Map<Integer,String> keyIndexMap = new HashMap<Integer,String>();
while (rs.next()) {
keyIndexMap.put(rs.getInt(5),rs.getString(4));
logger.info("Schema" + StringUtil.genLengthStr(rs.getString(1),10)
+""+ StringUtil.genLengthStr(rs.getString(3),25)
+""+ StringUtil.genLengthStr(rs.getString(4),10)
+""+ StringUtil.genLengthStr(rs.getString(5),2)
+""+ StringUtil.genLengthStr(rs.getString(6),15)+"");
}
/**API**/
map.put(t.toLowerCase(), keySequence(keyIndexMap));
}
} catch (SQLException e) {
logger.error("", e);
}
return map;
}
/**
*
* @return
*/
private Map<String, List<String>> getAllTablePKBYIndex(){
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
DatabaseMetaData dbmd = null;
ResultSet rs = null;
try {
dbmd = conn.getDatabaseMetaData();
logger.info("============================:");
for(String t:allTableName){
rs = dbmd.getIndexInfo(null, null, t, true,false);
List<String> list =new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString("COLUMN_NAME"));
}
map.put(t.toLowerCase(), list);
}
} catch (SQLException e) {
logger.error("", e);
}
return map;
}
/**
*
* @param keyIndexMap <seq_index,key_name>
* @return
*/
private List<String> keySequence(Map<Integer, String> keyIndexMap) {
List<Integer> index = new ArrayList<Integer>(keyIndexMap.keySet());
Collections.sort(index, new Comparator() {
@Override
public int compare(Object arg0, Object arg1) {
int muti0 = (Integer) arg0;
int muti1 = (Integer) arg1;
if (muti0 < muti1) {
return 1;
} else {
return 0;
}
}
});
return new ArrayList<String>(keyIndexMap.values());
}
/**
*
* @return
*/
private TableBean setTableColumn(TableBean tableBean){
DatabaseMetaData dbmd = null;
ResultSet rs = null;
try {
dbmd = conn.getDatabaseMetaData();
/*(catalog,schemaPattern,tableNamePattern,types)
* 23,*/
rs = dbmd.getColumns(null, null, tableBean.getTableName(), "%");
while (rs.next()) {
logger.info("" + StringUtil.genLengthStr(rs.getString(3),25)
+""+ StringUtil.genLengthStr(rs.getString(4),15)
+"sqltype"+ StringUtil.genLengthStr(rs.getInt(5),3)
+"typename"+ StringUtil.genLengthStr(rs.getString(6),10)
+"precision"+ StringUtil.genLengthStr(rs.getInt(7),5)
+"scale"+ StringUtil.genLengthStr(rs.getInt(9),5)
+"isNullable"+ StringUtil.genLengthStr(rs.getInt(11),2)
+"isNullable2"+ StringUtil.genLengthStr(rs.getString(18),3)
+"comment"+ StringUtil.genLengthStr(rs.getString(12),20)
+"defaultValue"+ StringUtil.genLengthStr(rs.getString(13),5)
+"isAutocrement"+ StringUtil.genLengthStr(rs.getString(23),5)+"");
ColBean cb = new ColBean();
String colName = rs.getString(4);
/**cb.setColName(colName.toLowerCase());**/
cb.setColName(colName);
cb.setColType(rs.getString(6));
cb.setColComment(StringUtils.isBlank(rs.getString(12))?cb.getColName():rs.getString(12));
cb.setNullable(rs.getInt(11)==0?false:true);
cb.setDefaultValue(rs.getString(13));
cb.setPrecision(rs.getInt(7));
cb.setScale(rs.getInt(9));
cb.setAutoIncrement("YES".equals(rs.getString(23))?true:false);
// SQL
int sqltype = rs.getInt(5);
cb.setColSQLType(sqltype);
if(!as.containsKey(sqltype)){
as.put(sqltype, "typeName:" + rs.getString(6) + " -> className:");
}
List<String> pkfieldnames = allTablePK.get(tableBean.getTableName());
for (String pkfieldname : pkfieldnames) {
if (colName.equalsIgnoreCase(pkfieldname)) {
cb.setPK(true);
tableBean.addPkcol(cb);
break;
} else {
cb.setPK(false);
tableBean.addColBean(cb);
}
}
}
} catch (SQLException e) {
logger.error("", e);
}
return tableBean;
}
public Map<Integer,String> as = new HashMap<Integer,String>();
} |
package com.sdl.selenium.web;
import com.google.common.base.Strings;
import com.sdl.selenium.utils.config.WebDriverConfig;
import com.sdl.selenium.utils.config.WebLocatorConfig;
import com.sdl.selenium.web.utils.Utils;
import com.sdl.selenium.web.utils.internationalization.InternationalizationUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* This class is used to simple construct xpath for WebLocator's
*/
@Getter
@Slf4j
public class XPathBuilder implements Cloneable {
public List<SearchType> defaultSearchTextType = new ArrayList<>();
private String className = "WebLocator";
private String root = "
private String tag = "*";
private String id;
private String elPath;
private String elCssSelector;
private String baseCls;
private String cls;
private List<String> classes;
private List<String> excludeClasses;
private String name;
private String text;
private List<SearchType> searchTextType = WebLocatorConfig.getSearchTextType();
private List<SearchType> searchTitleType = new ArrayList<>();
private List<SearchType> searchLabelType = new ArrayList<>();
private String style;
private String title;
private Map<String, String> templates = new LinkedHashMap<>();
private Map<String, WebLocator> templateTitle = new LinkedHashMap<>();
private Map<String, String[]> templatesValues = new LinkedHashMap<>();
private Map<String, String> elPathSuffix = new LinkedHashMap<>();
private String infoMessage;
private String label;
private String labelTag = "label";
private String labelPosition = WebLocatorConfig.getDefaultLabelPosition();
private boolean labelBeforeField;
private String position;
private String resultIdx;
private String type;
private Map<String, SearchText> attribute = new LinkedHashMap<>();
//private int elIndex; // TODO try to find how can be used
private boolean visibility;
private long renderMillis = WebLocatorConfig.getDefaultRenderMillis();
private int activateSeconds = 60;
private WebLocator container;
private List<WebLocator> childNodes;
protected XPathBuilder() {
setTemplate("visibility", "count(ancestor-or-self::*[contains(@style, 'display: none')]) = 0");
setTemplate("id", "@id='%s'");
setTemplate("name", "@name='%s'");
setTemplate("class", "contains(concat(' ', @class, ' '), ' %s ')");
setTemplate("excludeClass", "not(contains(@class, '%s'))");
setTemplate("cls", "@class='%s'");
setTemplate("type", "@type='%s'");
setTemplate("title", "@title='%s'");
setTemplate("titleEl", "count(.%s) > 0");
setTemplate("DEEP_CHILD_NODE_OR_SELF", "(%1$s or count(*//text()[%1$s]) > 0)");
setTemplate("DEEP_CHILD_NODE", "count(*//text()[%s]) > 0");
setTemplate("CHILD_NODE", "count(text()[%s]) > 0");
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param root If the path starts with // then all elements in the document which fulfill following criteria are selected. eg. // or /
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setRoot(final String root) {
this.root = root;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param tag (type of DOM element) eg. input or h2
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setTag(final String tag) {
this.tag = tag;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param id eg. id="buttonSubmit"
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setId(final String id) {
this.id = id;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* Once used all other attributes will be ignored. Try using this class to a minimum!
*
* @param elPath absolute way (xpath) to identify element
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setElPath(final String elPath) {
this.elPath = elPath;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate css selectors address)</b></p>
* Once used all other attributes will be ignored. Try using this class to a minimum!
*
* @param elCssSelector absolute way (css selectors) to identify element
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setElCssSelector(final String elCssSelector) {
this.elCssSelector = elCssSelector;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param baseCls base class
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setBaseCls(final String baseCls) {
this.baseCls = baseCls;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* <p>Find element with <b>exact math</b> of specified class (equals)</p>
*
* @param cls class of element
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setCls(final String cls) {
this.cls = cls;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* <p>Use it when element must have all specified css classes (order is not important).</p>
* <p>Example:</p>
* <pre>
* WebLocator element = new WebLocator().setClasses("bg-btn", "new-btn");
* </pre>
* <ul>
* <li>Provided classes must be conform css rules.</li>
* </ul>
*
* @param classes list of classes
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setClasses(final String... classes) {
if (classes != null) {
this.classes = Arrays.asList(classes);
}
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param excludeClasses list of class to be excluded
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setExcludeClasses(final String... excludeClasses) {
if (excludeClasses != null) {
this.excludeClasses = Arrays.asList(excludeClasses);
}
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setChildNodes(final WebLocator... childNodes) {
if (childNodes != null) {
this.childNodes = Arrays.asList(childNodes);
}
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param name eg. name="buttonSubmit"
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setName(final String name) {
this.name = name;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param text with which to identify the item
* @param searchTypes type search text element: see more details see {@link SearchType}
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setText(final String text, final SearchType... searchTypes) {
this.text = text;
// notSupportedForCss(text, "text");
// if(text == null) {
// xpath.remove("text");
// } else {
// xpath.add("text");
setSearchTextType(searchTypes);
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* This method reset searchTextTypes and set to new searchTextTypes.
*
* @param searchTextTypes accepted values are: {@link SearchType#EQUALS}
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setSearchTextType(SearchType... searchTextTypes) {
if (searchTextTypes == null) {
this.searchTextType = WebLocatorConfig.getSearchTextType();
} else {
this.searchTextType.addAll(0, Arrays.asList(searchTextTypes));
}
this.searchTextType.addAll(defaultSearchTextType);
this.searchTextType = cleanUpSearchType(this.searchTextType);
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* This method add new searchTextTypes to existing searchTextTypes.
*
* @param searchTextTypes accepted values are: {@link SearchType#EQUALS}
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T addSearchTextType(SearchType... searchTextTypes) {
if (searchTextTypes != null) {
this.searchTextType.addAll(0, Arrays.asList(searchTextTypes));
}
this.searchTextType = cleanUpSearchType(this.searchTextType);
return (T) this;
}
protected List<SearchType> cleanUpSearchType(List<SearchType> searchTextTypes) {
List<SearchType> searchTypes = searchTextTypes;
if (searchTextTypes.size() > 1) {
Set<String> unique = new HashSet<>();
searchTypes = searchTextTypes.stream()
.filter(c -> unique.add(c.getGroup()))
.collect(Collectors.toList());
}
return searchTypes;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param searchLabelTypes accepted values are: {@link SearchType}
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
private <T extends XPathBuilder> T setSearchLabelType(SearchType... searchLabelTypes) {
this.searchLabelType = new ArrayList<>();
if (searchLabelTypes != null) {
this.searchLabelType.addAll(0, Arrays.asList(searchLabelTypes));
}
this.searchLabelType = cleanUpSearchType(this.searchLabelType);
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param style of element
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setStyle(final String style) {
this.style = style;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* <p><b>Title only applies to Panel, and if you set the item "setTemplate("title", "@title='%s'")" a template.</b></p>
*
* @param title of element
* @param searchTypes see {@link SearchType}
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setTitle(final String title, final SearchType... searchTypes) {
this.title = title;
if (searchTypes != null && searchTypes.length > 0) {
setSearchTitleType(searchTypes);
} else {
this.searchTitleType.addAll(defaultSearchTextType);
}
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setSearchTitleType(SearchType... searchTitleTypes) {
if (searchTitleTypes == null) {
this.searchTitleType = WebLocatorConfig.getSearchTextType();
} else {
this.searchTitleType.addAll(0, Arrays.asList(searchTitleTypes));
}
this.searchTitleType.addAll(defaultSearchTextType);
this.searchTitleType = cleanUpSearchType(this.searchTitleType);
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setTemplateTitle(WebLocator titleEl) {
if (titleEl == null) {
templateTitle.remove("title");
} else {
templateTitle.put("title", titleEl);
setSearchTitleType(titleEl.getPathBuilder().getSearchTitleType().stream().toArray(SearchType[]::new));
}
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* <p>Example:</p>
* <pre>
* TODO
* </pre>
*
* @param key suffix key
* @param elPathSuffix additional identification xpath element that will be added at the end
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setElPathSuffix(final String key, final String elPathSuffix) {
if (Strings.isNullOrEmpty(elPathSuffix)) {
this.elPathSuffix.remove(key);
} else {
this.elPathSuffix.put(key, elPathSuffix);
}
return (T) this;
}
public Map<String, String[]> getTemplatesValues() {
return templatesValues;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
* <p>Example:</p>
* <pre>
* TODO
* </pre>
*
* @param key template
* @param value template
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setTemplateValue(final String key, final String... value) {
if (value == null) {
this.templatesValues.remove(key);
} else {
this.templatesValues.put(key, value);
}
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setTemplate(final String key, final String value) {
if (value == null) {
templates.remove(key);
} else {
templates.put(key, value);
}
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T addToTemplate(final String key, final String value) {
String template = getTemplate(key);
if (StringUtils.isNotEmpty(template)) {
template += " and ";
} else {
template = "";
}
setTemplate(key, template + value);
return (T) this;
}
public String getTemplate(final String key) {
return templates.get(key);
}
/**
* <p><b><i>Used in logging process</i></b></p>
*
* @param infoMessage info Message
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setInfoMessage(final String infoMessage) {
this.infoMessage = infoMessage;
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setVisibility(final boolean visibility) {
this.visibility = visibility;
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setRenderMillis(final long renderMillis) {
this.renderMillis = renderMillis;
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setActivateSeconds(final int activateSeconds) {
this.activateSeconds = activateSeconds;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param container parent containing element.
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setContainer(WebLocator container) {
this.container = container;
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param label text label element
* @param searchTypes type search text element: see more details see {@link SearchType}
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setLabel(final String label, final SearchType... searchTypes) {
this.label = label;
if (searchTypes != null && searchTypes.length > 0) {
setSearchLabelType(searchTypes);
}
return (T) this;
}
/**
* <p><b>Used for finding element process (to generate xpath address)</b></p>
*
* @param labelTag label tag element
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setLabelTag(final String labelTag) {
this.labelTag = labelTag;
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setLabelPosition(final String labelPosition) {
this.labelPosition = labelPosition;
return (T) this;
}
* //*[contains(@class, 'x-grid-panel')][position() = 1]
* </pre>
*
* @param position starting index = 1
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setPosition(final int position) {
this.position = position + "";
return (T) this;
}
* //*[contains(@class, 'x-grid-panel')][last()]
* </pre>
*
* @param position {@link Position}
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setPosition(final Position position) {
this.position = position.getValue();
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setResultIdx(final int resultIdx) {
this.resultIdx = resultIdx + "";
return (T) this;
}
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setResultIdx(final Position resultIdx) {
this.resultIdx = resultIdx.getValue();
return (T) this;
}
* //*[@type='type']
* </pre>
*
* @param type eg. 'checkbox' or 'button'
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setType(final String type) {
this.type = type;
return (T) this;
}
* //*[@placeholder='Search']
* </pre>
*
* @param attribute eg. placeholder
* @param value eg. Search
* @param searchTypes accept only SearchType.EQUALS, SearchType.CONTAINS, SearchType.STARTS_WITH, SearchType.TRIM
* @param <T> the element which calls this method
* @return this element
*/
@SuppressWarnings("unchecked")
public <T extends XPathBuilder> T setAttribute(final String attribute, String value, final SearchType... searchTypes) {
if (attribute != null) {
if (value == null) {
this.attribute.remove(attribute);
} else {
if (!Arrays.asList(searchTypes).contains(SearchType.NOT_INTERNATIONALIZED)) {
if (attribute.equals("placeholder") || attribute.equals("alt") || attribute.equals("title")) {
value = InternationalizationUtils.getInternationalizedText(value);
}
}
this.attribute.put(attribute, new SearchText(value, searchTypes));
}
}
return (T) this;
}
protected void setClassName(final String className) {
this.className = className;
}
protected boolean hasId() {
return !Strings.isNullOrEmpty(id);
}
protected boolean hasCls() {
return !Strings.isNullOrEmpty(cls);
}
protected boolean hasClasses() {
return classes != null && classes.size() > 0;
}
protected boolean hasChildNodes() {
return childNodes != null && childNodes.size() > 0;
}
protected boolean hasExcludeClasses() {
return excludeClasses != null && excludeClasses.size() > 0;
}
protected boolean hasBaseCls() {
return !Strings.isNullOrEmpty(baseCls);
}
protected boolean hasName() {
return !Strings.isNullOrEmpty(name);
}
protected boolean hasText() {
return !Strings.isNullOrEmpty(text);
}
protected boolean hasStyle() {
return !Strings.isNullOrEmpty(style);
}
protected boolean hasElPath() {
return !Strings.isNullOrEmpty(elPath);
}
protected boolean hasTag() {
return tag != null && !"*".equals(tag);
}
protected boolean hasLabel() {
return !Strings.isNullOrEmpty(label);
}
protected boolean hasTitle() {
return !Strings.isNullOrEmpty(title);
}
protected boolean hasPosition() {
int anInt;
try {
anInt = Integer.parseInt(position);
} catch (NumberFormatException e) {
anInt = 1;
}
return !Strings.isNullOrEmpty(position) && anInt > 0;
}
protected boolean hasResultIdx() {
int anInt;
try {
anInt = Integer.parseInt(resultIdx);
} catch (NumberFormatException e) {
anInt = 1;
}
return !Strings.isNullOrEmpty(resultIdx) && anInt > 0;
}
protected boolean hasType() {
return !Strings.isNullOrEmpty(type);
}
/**
* Containing baseCls, class, name and style
*
* @return baseSelector
*/
protected String getBasePathSelector() {
// TODO use disabled
// TODO verify what need to be equal OR contains
List<String> selector = new ArrayList<>();
CollectionUtils.addIgnoreNull(selector, getBasePath());
if (!WebDriverConfig.isIE()) {
if (hasStyle()) {
selector.add("contains(@style ,'" + getStyle() + "')");
}
// TODO make specific for WebLocator
if (isVisibility()) {
// TODO selector.append(" and count(ancestor-or-self::*[contains(replace(@style, '\s*:\s*', ':'), 'display:none')]) = 0");
CollectionUtils.addIgnoreNull(selector, applyTemplate("visibility", isVisibility()));
}
}
return selector.isEmpty() ? "" : StringUtils.join(selector, " and ");
}
public String getBasePath() {
List<String> selector = new ArrayList<>();
if (hasId()) {
selector.add(applyTemplate("id", getId()));
}
if (hasName()) {
selector.add(applyTemplate("name", getName()));
}
if (hasBaseCls()) {
selector.add(applyTemplate("class", getBaseCls()));
}
if (hasCls()) {
selector.add(applyTemplate("cls", getCls()));
}
if (hasClasses()) {
selector.addAll(getClasses().stream().map(cls -> applyTemplate("class", cls)).collect(Collectors.toList()));
}
if (hasExcludeClasses()) {
selector.addAll(getExcludeClasses().stream().map(excludeClass -> applyTemplate("excludeClass", excludeClass)).collect(Collectors.toList()));
}
if (hasTitle()) {
String title = getTitle();
WebLocator titleTplEl = templateTitle.get("title");
if (titleTplEl != null) {
titleTplEl.setText(title, searchTitleType.stream().toArray(SearchType[]::new));
addTemplate(selector, "titleEl", titleTplEl.getXPath());
} else if (searchTitleType.isEmpty()) {
// title = getTextAfterEscapeQuotes(title, searchTitleType);
addTemplate(selector, "title", title);
} else {
addTextInPath(selector, title, "@title", searchTitleType);
}
}
if (hasType()) {
addTemplate(selector, "type", getType());
}
if (!attribute.isEmpty()) {
for (Map.Entry<String, SearchText> entry : attribute.entrySet()) {
List<SearchType> searchType = entry.getValue().getSearchTypes();
String text = entry.getValue().getValue();
addTextInPath(selector, text, "@" + entry.getKey(), searchType);
}
}
if (hasText()) {
addTextInPath(selector, getText(), ".", searchTextType);
}
for (Map.Entry<String, String[]> entry : getTemplatesValues().entrySet()) {
addTemplate(selector, entry.getKey(), entry.getValue());
}
selector.addAll(elPathSuffix.values().stream().collect(Collectors.toList()));
selector.addAll(getChildNodesToSelector());
return selector.isEmpty() ? null : StringUtils.join(selector, " and ");
}
public void addTextInPath(List<String> selector, String text, String pattern, List<SearchType> searchTextType) {
text = getTextAfterEscapeQuotes(text, searchTextType);
boolean hasContainsAll = searchTextType.contains(SearchType.CONTAINS_ALL) || searchTextType.contains(SearchType.CONTAINS_ALL_CHILD_NODES);
if (!Strings.isNullOrEmpty(getTemplate("text"))) {
selector.add(String.format(templates.get("text"), text));
} else if (hasContainsAll || searchTextType.contains(SearchType.CONTAINS_ANY)) {
String splitChar = String.valueOf(text.charAt(0));
String[] strings = Pattern.compile(Pattern.quote(splitChar)).split(text.substring(1));
for (int i = 0; i < strings.length; i++) {
String escapeQuotesText = Utils.getEscapeQuotesText(strings[i]);
if (searchTextType.contains(SearchType.CONTAINS_ALL_CHILD_NODES)) {
if (searchTextType.contains(SearchType.CASE_INSENSITIVE)) {
strings[i] = "count(*//text()[contains(translate(.," + escapeQuotesText.toUpperCase().replaceAll("CONCAT\\(", "concat(") + "," + escapeQuotesText.toLowerCase() + ")," + escapeQuotesText.toLowerCase() + ")]) > 0";
} else {
strings[i] = "count(*//text()[contains(.," + escapeQuotesText + ")]) > 0";
}
} else {
strings[i] = "contains(" + (".".equals(pattern) ? "." : pattern) + "," + escapeQuotesText + ")";
}
}
selector.add(hasContainsAll ? StringUtils.join(strings, " and ") : "(" + StringUtils.join(strings, " or ") + ")");
} else if (searchTextType.contains(SearchType.DEEP_CHILD_NODE_OR_SELF)) {
String selfPath = getTextWithSearchType(searchTextType, text, pattern);
addTemplate(selector, "DEEP_CHILD_NODE_OR_SELF", selfPath);
} else if (searchTextType.contains(SearchType.DEEP_CHILD_NODE)) {
String selfPath = getTextWithSearchType(searchTextType, text, pattern);
addTemplate(selector, "DEEP_CHILD_NODE", selfPath);
} else if (searchTextType.contains(SearchType.CHILD_NODE)) {
String selfPath = getTextWithSearchType(searchTextType, text, pattern);
addTemplate(selector, "CHILD_NODE", selfPath);
} else if (searchTextType.contains(SearchType.HTML_NODE)) {
addTemplate(selector, "HTML_NODE", text);
} else {
selector.add(getTextWithSearchType(searchTextType, text, ".".equals(pattern) ? "text()" : pattern));
}
}
private List<String> getChildNodesToSelector() {
List<String> selector = new ArrayList<>();
if (hasChildNodes()) {
selector.addAll(getChildNodes().stream().map(this::getChildNodeSelector).collect(Collectors.toList()));
}
return selector;
}
private String getChildNodeSelector(WebLocator child) {
WebLocator breakElement = null;
WebLocator childIterator = child;
WebLocator parentElement = null;
// break parent tree if is necessary
while (childIterator.getPathBuilder().getContainer() != null && breakElement == null) {
WebLocator parentElementIterator = childIterator.getPathBuilder().getContainer();
// child element has myself as parent
if (parentElementIterator.getPathBuilder() == this) {
childIterator.setContainer(null); // break parent tree while generating child address
parentElement = parentElementIterator;
breakElement = childIterator;
} else {
childIterator = parentElementIterator;
}
}
String selector = "count(." + child.getXPath() + ") > 0";
if (breakElement != null) {
breakElement.setContainer(parentElement);
}
return selector;
}
private void addTemplate(List<String> selector, String key, Object... arguments) {
String tpl = applyTemplate(key, arguments);
if (StringUtils.isNotEmpty(tpl)) {
selector.add(tpl);
}
}
protected String applyTemplate(String key, Object... arguments) {
String tpl = templates.get(key);
if (StringUtils.isNotEmpty(tpl)) {
return String.format(tpl, arguments);
}
return null;
}
private String applyTemplateValue(String key) {
return applyTemplate(key, getTemplate(key));
}
/**
* this method is meant to be overridden by each component
*
* @param disabled disabled
* @return String
*/
protected String getItemPath(boolean disabled) {
String selector = getBaseItemPath();
String subPath = applyTemplateValue(disabled ? "disabled" : "enabled");
if (subPath != null) {
selector += StringUtils.isNotEmpty(selector) ? " and " + subPath : subPath;
}
selector = getRoot() + getTag() + (StringUtils.isNotEmpty(selector) ? "[" + selector + "]" : "");
return selector;
}
private String getTextWithSearchType(List<SearchType> searchType, String text, String pattern) {
if (searchType.contains(SearchType.TRIM)) {
pattern = "normalize-space(" + pattern + ")";
}
if (searchType.contains(SearchType.CASE_INSENSITIVE)) {
pattern = "translate(" + pattern + "," + text.toUpperCase().replaceAll("CONCAT\\(", "concat(") + "," + text.toLowerCase() + ")";
text = text.toLowerCase();
}
if (searchType.contains(SearchType.EQUALS)) {
text = pattern + "=" + text;
} else if (searchType.contains(SearchType.STARTS_WITH)) {
text = "starts-with(" + pattern + "," + text + ")";
} else {
text = "contains(" + pattern + "," + text + ")";
}
return text;
}
private String getTextAfterEscapeQuotes(String text, List<SearchType> searchType) {
if (searchType.contains(SearchType.CONTAINS_ALL) || searchType.contains(SearchType.CONTAINS_ANY) || searchType.contains(SearchType.CONTAINS_ALL_CHILD_NODES)) {
return text;
}
return Utils.getEscapeQuotesText(text);
}
private String getBaseItemPath() {
return getBasePathSelector();
}
private String getItemCssSelector() {
List<String> selector = new ArrayList<>();
if (hasTag()) {
selector.add(getTag());
}
if (hasId()) {
selector.add("#" + getId());
}
if (hasBaseCls()) {
selector.add("." + getBaseCls());
}
if (hasCls()) {
selector.add("[class=" + getCls() + "]");
}
if (hasClasses()) {
selector.addAll(getClasses().stream().map(cls -> "." + cls).collect(Collectors.toList()));
}
if (hasExcludeClasses()) {
// LOGGER.warn("excludeClasses is not supported yet");
selector.addAll(getExcludeClasses().stream().map(excludeClass -> ":not(." + excludeClass + ")").collect(Collectors.toList()));
}
if (hasName()) {
selector.add("[name='" + getName() + "']");
}
if (hasType()) {
selector.add("[type='" + getType() + "']");
}
if (!attribute.isEmpty()) {
selector.addAll(attribute.entrySet().stream()
.map(e -> "[" + e.getKey() + "='" + e.getValue().getValue() + "']")
.collect(Collectors.toList()));
}
// for (Map.Entry<String, String> entry : getTemplatesValues().entrySet()) {
// addTemplate(selector, entry.getKey(), entry.getValue());
// for (String suffix : elPathSuffix.values()) {
// selector.add(suffix);
return selector.isEmpty() ? "*" : StringUtils.join(selector, "");
}
public final By getSelector() {
String cssSelector = getCssSelector();
return !Strings.isNullOrEmpty(cssSelector) ? By.cssSelector(cssSelector) : By.xpath(getXPath());
}
private boolean isCssSelectorSupported() {
return !(hasText() || hasElPath() || hasChildNodes() || hasStyle() || hasLabel() || hasTitle() || hasResultIdx());
}
public final String getCssSelector() {
String cssSelector = null;
cssSelector = getElCssSelector();
if (WebLocatorConfig.isGenerateCssSelector()) {
if (StringUtils.isEmpty(cssSelector)) {
if (isCssSelectorSupported()) {
cssSelector = getItemCssSelector();
if (hasPosition()) {
if ("first()".equals(position)) {
cssSelector += ":first-child";
} else if ("last()".equals(position)) {
cssSelector += ":last-child";
} else {
cssSelector += ":nth-child(" + getPosition() + ")";
}
}
}
} //else {
// String baseCssSelector = getItemCssSelector();
// if (StringUtils.isNotEmpty(baseCssSelector)) {
// TODO "inject" baseItemPath to elPath
}
// add container path
if (cssSelector != null && getContainer() != null) {
String parentCssSelector = getContainer().getCssSelector();
if (StringUtils.isEmpty(parentCssSelector)) {
log.warn("Can't generate css selector for parent: {}", getContainer());
cssSelector = null;
} else {
String root = getRoot();
String deep = "";
if (StringUtils.isNotEmpty(root)) {
if (root.equals("/")) {
deep = " > ";
} else if (root.equals("
deep = " ";
} else {
log.warn("this root ({}) is no implemented in css selector: ", root);
}
}
cssSelector = parentCssSelector + deep + cssSelector;
}
}
return cssSelector;
}
/**
* @return final xpath (including containers xpath), used for interacting with browser
*/
public final String getXPath() {
return getXPath(false);
}
public final String getXPath(boolean disabled) {
String returnPath;
if (hasElPath()) {
returnPath = getElPath();
// String baseItemPath = getBaseItemPath();
// if (!Strings.isNullOrEmpty(baseItemPath)) {
// TODO "inject" baseItemPath to elPath
} else {
returnPath = getItemPath(disabled);
}
returnPath = afterItemPathCreated(returnPath);
// add container path
if (getContainer() != null) {
returnPath = getContainer().getXPath() + returnPath;
}
return addResultIndexToPath(returnPath);
}
private String addResultIndexToPath(String xPath) {
if (hasResultIdx()) {
xPath = "(" + xPath + ")[" + getResultIdx() + "]";
}
return xPath;
}
@Override
public String toString() {
String info = getInfoMessage();
if (Strings.isNullOrEmpty(info)) {
info = itemToString();
}
if (WebLocatorConfig.isLogUseClassName() && !getClassName().equals(info)) {
info += " - " + getClassName();
}
// add container path
if (WebLocatorConfig.isLogContainers() && getContainer() != null) {
info = getContainer().toString() + " -> " + info;
}
return info;
}
public String itemToString() {
String info = "";
if (hasText()) {
info = getText();
} else if (hasTitle()) {
info = getTitle();
} else if (hasId()) {
info = getId();
} else if (hasName()) {
info = getName();
} else if (hasBaseCls()) {
info = getBaseCls();
} else if (hasClasses()) {
info = classes.size() == 1 ? classes.get(0) : classes.toString();
} else if (hasCls()) {
info = getCls();
} else if (hasLabel()) {
info = getLabel();
} else if (hasElPath()) {
info = getElPath();
} else if (!attribute.isEmpty()) {
for (Map.Entry<String, SearchText> entry : attribute.entrySet()) {
info += "@" + entry.getKey() + "=" + entry.getValue().getValue();
}
} else if (hasTag()) {
info = getTag();
} else {
info = getClassName();
}
return info;
}
protected String afterItemPathCreated(String itemPath) {
if (hasLabel()) {
// remove '//' because labelPath already has and include
if (itemPath.indexOf("
itemPath = itemPath.substring(2);
}
itemPath = getLabelPath() + getLabelPosition() + itemPath;
}
itemPath = addPositionToPath(itemPath);
return itemPath;
}
protected String addPositionToPath(String itemPath) {
if (hasPosition()) {
itemPath += "[position() = " + getPosition() + "]";
}
return itemPath;
}
protected String getLabelPath() {
if (searchLabelType.size() == 0) {
searchLabelType.add(SearchType.EQUALS);
}
SearchType[] st = searchLabelType.stream().toArray(SearchType[]::new);
return new WebLocator().setText(getLabel(), st).setTag(getLabelTag()).getXPath();
}
@Override
@SuppressWarnings("unchecked")
public Object clone() throws CloneNotSupportedException {
XPathBuilder builder = (XPathBuilder) super.clone();
LinkedHashMap<String, String> templates = (LinkedHashMap<String, String>) builder.templates;
LinkedHashMap<String, WebLocator> templateTitle = (LinkedHashMap<String, WebLocator>) builder.templateTitle;
LinkedHashMap<String, String[]> templatesValues = (LinkedHashMap<String, String[]>) builder.templatesValues;
LinkedHashMap<String, String> elPathSuffix = (LinkedHashMap<String, String>) builder.elPathSuffix;
builder.templates = (Map<String, String>) templates.clone();
builder.templatesValues = (Map<String, String[]>) templatesValues.clone();
builder.elPathSuffix = (Map<String, String>) elPathSuffix.clone();
builder.templateTitle = (Map<String, WebLocator>) templateTitle.clone();
WebLocator titleTplEl = templateTitle.get("title");
if (titleTplEl != null) {
XPathBuilder titleTplElBuilder = (XPathBuilder) titleTplEl.getPathBuilder().clone();
WebLocator titleTplElCloned = new WebLocator().setPathBuilder(titleTplElBuilder);
builder.templateTitle.put("title", titleTplElCloned);
}
return builder;
}
} |
package org.requs;
import com.jcabi.log.VerboseProcess;
import com.jcabi.matchers.XhtmlMatchers;
import com.jcabi.xml.XML;
import com.jcabi.xml.XMLDocument;
import com.jcabi.xml.XSL;
import com.jcabi.xml.XSLDocument;
import java.io.File;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
/**
* Test case for {@link org.requs.Compiler}.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 1.1
* @checkstyle MultipleStringLiteralsCheck (500 lines)
*/
public final class CompilerTest {
/**
* XSTLPROC binary.
*/
private static final String BIN = "xsltproc";
/**
* Temporary folder.
* @checkstyle VisibilityModifier (3 lines)
*/
@Rule
public transient TemporaryFolder temp = new TemporaryFolder();
/**
* Compiler can parse all samples.
* @throws Exception When necessary
*/
@Test
public void parsesAllSamples() throws Exception {
final String[] files = {
"samples/all-possible-constructs.xml",
"samples/all-possible-mistakes.xml",
"samples/clean-spec.xml",
};
for (final String file : files) {
this.parses(
IOUtils.toString(
CompilerTest.class.getResourceAsStream(file),
CharEncoding.UTF_8
)
);
}
}
/**
* Compiler can parse given text.
* @param text Text to parse
* @throws Exception When necessary
*/
private void parses(final String text) throws Exception {
final XML xml = new XMLDocument(text);
final File input = this.temp.newFolder();
final File output = this.temp.newFolder();
FileUtils.write(
new File(input, "input.req"),
xml.xpath("/sample/spec/text()").get(0),
CharEncoding.UTF_8
);
new Compiler(input, output).compile();
final XML srs = new XMLDocument(new File(output, "requs.xml"));
final XSL xsl = new XSLDocument(
new XMLDocument(new File(output, "requs.xsl"))
);
final Collection<String> xpaths = xml.xpath(
"/sample/xpaths/xpath/text()"
);
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(srs.toString()),
XhtmlMatchers.hasXPaths(
xpaths.toArray(new String[xpaths.size()])
)
);
MatcherAssert.assertThat(
xsl.transform(srs),
XhtmlMatchers.hasXPath("//xhtml:body")
);
CompilerTest.assumeXsltproc();
MatcherAssert.assertThat(
new VerboseProcess(
new ProcessBuilder()
.directory(output)
.command(
CompilerTest.BIN,
"-o",
"requs.html",
"requs.xml"
)
.start()
).stdout(),
Matchers.isEmptyString()
);
MatcherAssert.assertThat(
FileUtils.readFileToString(new File(output, "requs.html")),
XhtmlMatchers.hasXPath("//xhtml:body")
);
}
/**
* Assume that it is installed.
*/
private static void assumeXsltproc() {
String ver;
try {
ver = new VerboseProcess(
new ProcessBuilder()
.command(CompilerTest.BIN, "-version")
.redirectErrorStream(true)
).stdoutQuietly();
} catch (final IllegalStateException ex) {
ver = "";
}
Assume.assumeThat(
ver,
Matchers.containsString("libxml")
);
}
} |
// This file is part of the Whiley-to-Java Compiler (wyjc).
// The Whiley-to-Java Compiler is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// The Whiley-to-Java Compiler is distributed in the hope that it
// You should have received a copy of the GNU General Public
package wyil.lang;
import java.io.PrintStream;
import java.util.*;
import wyil.util.Pair;
import wyjvm.lang.Constant;
public abstract class Type {
// Type Constructors
public static final Any T_ANY = new Any();
public static final Void T_VOID = new Void();
public static final Null T_NULL = new Null();
public static final Bool T_BOOL = new Bool();
public static final Int T_INT = new Int();
public static final Real T_REAL = new Real();
public static final Meta T_META = new Meta();
/**
* Construct a tuple type using the given element types.
*
* @param element
*/
public static final Tuple T_TUPLE(Type... elements) {
int len = 1;
for(Type b : elements) {
// could be optimised slightly
len += nodes(b).length;
}
Node[] nodes = new Node[len];
int[] children = new int[elements.length];
int start = 1;
for(int i=0;i!=elements.length;++i) {
children[i] = start;
Node[] comps = nodes(elements[i]);
insertNodes(start,comps,nodes);
start += comps.length;
}
nodes[0] = new Node(K_TUPLE, children);
return new Tuple(nodes);
}
/**
* Construct a process type using the given element type.
*
* @param element
*/
public static final Process T_PROCESS(Type element) {
if (element instanceof Leaf) {
return new Process(new Node[] { new Node(K_PROCESS, 1),
new Node(leafKind((Leaf) element), null) });
} else {
// Compound type
Node[] nodes = insertComponent(((Compound) element).nodes);
nodes[0] = new Node(K_PROCESS, 1);
return new Process(nodes);
}
}
public static final Existential T_EXISTENTIAL(NameID name) {
if (name == null) {
throw new IllegalArgumentException(
"existential name cannot be null");
}
return new Existential(name);
}
/**
* Construct a set type using the given element type.
*
* @param element
*/
public static final Set T_SET(Type element) {
if (element instanceof Leaf) {
return new Set(new Node[] { new Node(K_SET, 1),
new Node(leafKind((Leaf) element), null) });
} else {
// Compound type
Node[] nodes = insertComponent(((Compound) element).nodes);
nodes[0] = new Node(K_SET, 1);
return new Set(nodes);
}
}
/**
* Construct a list type using the given element type.
*
* @param element
*/
public static final List T_LIST(Type element) {
if (element instanceof Leaf) {
return new List(new Node[] { new Node(K_LIST, 1),
new Node(leafKind((Leaf) element), null) });
} else {
// Compound type
Node[] nodes = insertComponent(((Compound) element).nodes);
nodes[0] = new Node(K_LIST, 1);
return new List(nodes);
}
}
/**
* Construct a dictionary type using the given key and value types.
*
* @param element
*/
public static final Dictionary T_DICTIONARY(Type key, Type value) {
Node[] keyComps = nodes(key);
Node[] valueComps = nodes(value);
Node[] nodes = new Node[1 + keyComps.length + valueComps.length];
insertNodes(1,keyComps,nodes);
insertNodes(1+keyComps.length,valueComps,nodes);
nodes[0] = new Node(K_DICTIONARY, new Pair(1,1+keyComps.length));
return new Dictionary(nodes);
}
/**
* Construct a union type using the given type bounds
*
* @param element
*/
public static final Union T_UNION(Collection<Type> bounds) {
Type[] ts = new Type[bounds.size()];
int i = 0;
for(Type t : bounds) {
ts[i++] = t;
}
return T_UNION(ts);
}
/**
* Construct a union type using the given type bounds
*
* @param element
*/
public static final Union T_UNION(Type... bounds) {
// include child unions
int len = 1;
for(Type b : bounds) {
// could be optimised slightly
len += nodes(b).length;
}
Node[] nodes = new Node[len];
int[] children = new int[bounds.length];
int start = 1;
for(int i=0;i!=bounds.length;++i) {
children[i] = start;
Node[] comps = nodes(bounds[i]);
insertNodes(start,comps,nodes);
start += comps.length;
}
nodes[0] = new Node(K_UNION, children);
return new Union(nodes);
}
public static final Fun T_FUN(Process receiver, Type ret,
Collection<Type> params) {
Type[] ts = new Type[params.size()];
int i = 0;
for (Type t : params) {
ts[i++] = t;
}
return T_FUN(receiver, ret, ts);
}
/**
* Construct a function type using the given return and parameter types.
*
* @param element
*/
public static final Fun T_FUN(Process receiver, Type ret, Type... params) {
Node[] reccomps;
if(receiver != null) {
reccomps = nodes(receiver);
} else {
reccomps = new Node[0];
}
Node[] retcomps = nodes(ret);
int len = 1 + reccomps.length + retcomps.length;
for(Type b : params) {
// could be optimised slightly
len += nodes(b).length;
}
Node[] nodes = new Node[len];
int[] children = new int[2 + params.length];
insertNodes(1,reccomps,nodes);
insertNodes(1+reccomps.length,retcomps,nodes);
children[0] = receiver == null ? -1 : 1;
children[1] = 1 + reccomps.length;
int start = 1 + reccomps.length + retcomps.length;
for(int i=0;i!=params.length;++i) {
children[i+2] = start;
Node[] comps = nodes(params[i]);
insertNodes(start,comps,nodes);
start += comps.length;
}
nodes[0] = new Node(K_FUNCTION, children);
return new Fun(nodes);
}
/**
* Construct a record type using the given fields.
*
* @param element
*/
public static final Record T_RECORD(Map<String,Type> fields) {
ArrayList<String> keys = new ArrayList<String>(fields.keySet());
Collections.sort(keys);
int len = 1;
for(int i=0;i!=keys.size();++i) {
String k = keys.get(i);
Type t = fields.get(k);
len += nodes(t).length;
}
Node[] nodes = new Node[len];
Pair<String,Integer>[] children = new Pair[fields.size()];
int start = 1;
for(int i=0;i!=children.length;++i) {
String k = keys.get(i);
children[i] = new Pair<String,Integer>(k,start);
Node[] comps = nodes(fields.get(k));
insertNodes(start,comps,nodes);
start += comps.length;
}
nodes[0] = new Node(K_RECORD,children);
return new Record(nodes);
}
/**
* Construct a label type. These are used in the construction of recursive
* types. Essentially, a label corresponds to the leaf of a recursive type,
* which we can then "close" later on as we build up the type. For example,
* we construct the recursive type <code>X<null|{X next}></code> as follows:
*
* <pre>
* HashMap<String,Type> fields = new HashMap<String,Type>();
* fields.put("next",T_LABEL("X")); *
* Type tmp = T_UNION(T_NULL,T_RECORD(fields));
* Type type = T_RECURSIVE("X",tmp);
* </pre>
*
* <b>NOTE:</b> a type containing a label is not considered valid until it
* is closed using a recursive type.
*
* @param label
* @return
*/
public static final Type T_LABEL(String label) {
return new Compound(new Node[]{new Node(K_LABEL,label)});
}
public static final Type T_RECURSIVE(String label, Type type) {
// first stage, identify all matching labels
if(type instanceof Leaf) { throw new IllegalArgumentException("cannot close a leaf type"); }
Compound compound = (Compound) type;
Node[] nodes = compound.nodes;
int[] rmap = new int[nodes.length];
int nmatches = 0;
for(int i=0;i!=nodes.length;++i) {
Node c = nodes[i];
if(c.kind == K_LABEL && c.data.equals(label)) {
rmap[i] = 0;
nmatches++;
} else {
rmap[i] = i - nmatches;
}
}
if (nmatches == 0) {
throw new IllegalArgumentException(
"type cannot be closed, as it contains no matching labels");
}
Node[] newnodes = new Node[nodes.length-nmatches];
nmatches = 0;
for(int i=0;i!=nodes.length;++i) {
Node c = nodes[i];
if(c.kind == K_LABEL && c.data.equals(label)) {
nmatches++;
} else {
newnodes[i-nmatches] = remap(nodes[i],rmap);
}
}
return construct(newnodes);
}
/**
* The following code converts a "type string" into an actual type. This is
* useful, amongst other things, for debugging.
*
* @param str
* @return
*/
public static Type fromString(String str) {
return new TypeParser(str).parse();
}
private static class TypeParser {
private int index;
private String str;
public TypeParser(String str) {
this.str = str;
}
public Type parse() {
Type term = parseTerm();
skipWhiteSpace();
while(index < str.length() && str.charAt(index) == '|') {
// union type
match("|");
term = T_UNION(term,parse());
skipWhiteSpace();
}
return term;
}
public Type parseTerm() {
skipWhiteSpace();
char lookahead = str.charAt(index);
switch (lookahead) {
case 'a':
match("any");
return T_ANY;
case 'v':
match("void");
return T_VOID;
case 'n':
match("null");
return T_NULL;
case 'b':
match("bool");
return T_BOOL;
case 'i':
match("int");
return T_INT;
case 'r':
match("real");
return T_REAL;
case '[':
{
match("[");
Type elem = parse();
match("]");
return T_LIST(elem);
}
case '{':
{
match("{");
Type elem = parse();
skipWhiteSpace();
if(index < str.length() && str.charAt(index) != '}') {
// record
HashMap<String,Type> fields = new HashMap<String,Type>();
String id = parseIdentifier();
fields.put(id, elem);
skipWhiteSpace();
while(index < str.length() && str.charAt(index) == ',') {
match(",");
elem = parse();
id = parseIdentifier();
fields.put(id, elem);
skipWhiteSpace();
}
match("}");
return T_RECORD(fields);
}
match("}");
return T_SET(elem);
}
default:
throw new IllegalArgumentException("invalid type string: "
+ str);
}
}
private String parseIdentifier() {
skipWhiteSpace();
int start = index;
while (index < str.length()
&& Character.isJavaIdentifierPart(str.charAt(index))) {
index++;
}
return str.substring(start,index);
}
private void skipWhiteSpace() {
while (index < str.length()
&& Character.isWhitespace(str.charAt(index))) {
index++;
}
}
private void match(String match) {
skipWhiteSpace();
if ((str.length() - index) < match.length()
|| !str.startsWith(match, index)) {
throw new IllegalArgumentException("invalid type string: "
+ str);
}
index += match.length();
}
}
/**
* This is a utility helper for constructing types. In particular, it's
* useful for determine whether or not a type needs to be closed. An open
* type is one which contains a "dangling" reference to some node which
* needs to be connected to back to form a cycle.
*
* @param label
* @param t
* @return
*/
public static boolean isOpen(String label, Type t) {
if (t instanceof Leaf) {
return false;
}
Compound graph = (Compound) t;
for (Node n : graph.nodes) {
if (n.kind == K_LABEL && n.data.equals(label)) {
return true;
}
}
return false;
}
// Serialisation Helpers
/**
* The Type.Builder interface is essentially a way of separating the
* internals of the type implementation from clients which may want to
* serialise a given type graph.
*/
public interface Builder {
/**
* Set the number of nodes required for the type being built. This
* method is called once, before all other methods are called. The
* intention is to give builders a chance to statically initialise data
* structures based on the number of nodes required.
*
* @param numNodes
*/
void initialise(int numNodes);
void buildPrimitive(int index, Type.Leaf type);
void buildExistential(int index, NameID name);
void buildSet(int index, int element);
void buildList(int index, int element);
void buildProcess(int index, int element);
void buildDictionary(int index, int key, int value);
void buildTuple(int index, int... elements);
void buildRecord(int index, Pair<String, Integer>... fields);
void buildFunction(int index, int receiver, int ret, int... parameters);
void buildUnion(int index, int... bounds);
}
/**
* This class provides an empty implementation of a type builder, which is
* useful for define simple builders.
*
* @author djp
*
*/
public static class AbstractBuilder implements Type.Builder {
public void initialise(int numNodes) {
}
public void buildPrimitive(int index, Type.Leaf type) {
}
public void buildExistential(int index, NameID name) {
}
public void buildSet(int index, int element) {
}
public void buildList(int index, int element) {
}
public void buildProcess(int index, int element) {
}
public void buildDictionary(int index, int key, int value) {
}
public void buildTuple(int index, int... elements) {
}
public void buildRecord(int index, Pair<String, Integer>... fields) {
}
public void buildFunction(int index, int receiver, int ret,
int... parameters) {
}
public void buildUnion(int index, int... bounds) {
}
}
public static class InternalBuilder implements Type.Builder {
private Node[] nodes;
public Type type() {
return construct(nodes);
}
public void initialise(int numNodes) {
nodes = new Node[numNodes];
}
public void buildPrimitive(int index, Type.Leaf type) {
nodes[index] = new Node(leafKind(type),null);
}
public void buildExistential(int index, NameID name) {
if (name == null) {
throw new IllegalArgumentException(
"existential name cannot be null");
}
nodes[index] = new Node(K_EXISTENTIAL,name);
}
public void buildSet(int index, int element) {
nodes[index] = new Node(K_SET,element);
}
public void buildList(int index, int element) {
nodes[index] = new Node(K_LIST,element);
}
public void buildProcess(int index, int element) {
nodes[index] = new Node(K_PROCESS,element);
}
public void buildDictionary(int index, int key, int value) {
nodes[index] = new Node(K_DICTIONARY,new Pair(key,value));
}
public void buildTuple(int index, int... elements) {
nodes[index] = new Node(K_TUPLE,elements);
}
public void buildRecord(int index, Pair<String, Integer>... fields) {
nodes[index] = new Node(K_RECORD,fields);
}
public void buildFunction(int index, int receiver, int ret,
int... parameters) {
int[] items = new int[parameters.length+2];
items[0] = receiver;
items[1] = ret;
System.arraycopy(parameters,0,items,2,parameters.length);
nodes[index] = new Node(K_FUNCTION,items);
}
public void buildUnion(int index, int... bounds) {
nodes[index] = new Node(K_UNION,bounds);
}
}
/**
* The print builder is an example implementation of type builder which
* simply constructs a textual representation of the type in the form of a
* graph.
*/
public static class PrintBuilder implements Builder {
private final PrintStream out;
public PrintBuilder(PrintStream out) {
this.out = out;
}
public void initialise(int numNodes) { }
public void buildPrimitive(int index, Type.Leaf type) {
out.println("#" + index + " = " + type);
}
public void buildExistential(int index, NameID name) {
out.println("#" + index + " = ?" + name);
}
public void buildSet(int index, int element) {
out.println("#" + index + " = {#" + element + "}");
}
public void buildList(int index, int element) {
out.println("#" + index + " = [#" + element + "]");
}
public void buildProcess(int index, int element) {
out.println("#" + index + " = process #" + element);
}
public void buildDictionary(int index, int key, int value) {
out.println("#" + index + " = {#" + key + "->#" + value + "}");
}
public void buildTuple(int index, int... elements) {
out.print("#" + index + " = (");
boolean firstTime=true;
for(int e : elements) {
if(!firstTime) {
out.print(", ");
}
firstTime=false;
out.print("
}
out.println(")");
}
public void buildRecord(int index, Pair<String, Integer>... fields) {
out.print("#" + index + " = {");
boolean firstTime=true;
for(Pair<String,Integer> e : fields) {
if(!firstTime) {
out.print(", ");
}
firstTime=false;
out.print("#" + e.second() + " " + e.first());
}
out.println("}");
}
public void buildFunction(int index, int receiver, int ret, int... parameters) {
out.print("#" + index + " = ");
if(receiver != -1) {
out.print("#" + receiver + "::");
}
out.print("#" + ret + "(");
boolean firstTime=true;
for(int e : parameters) {
if(!firstTime) {
out.print(", ");
}
firstTime=false;
out.print("
}
out.println(")");
}
public void buildUnion(int index, int... bounds) {
out.print("#" + index + " = ");
boolean firstTime=true;
for(int e : bounds) {
if(!firstTime) {
out.print(" | ");
}
firstTime=false;
out.print("
}
out.println();
}
}
public static void build(Builder writer, Type type) {
if(type instanceof Leaf) {
writer.initialise(1);
writer.buildPrimitive(0,(Type.Leaf)type);
} else {
Compound graph = (Compound) type;
writer.initialise(graph.nodes.length);
Node[] nodes = graph.nodes;
for(int i=0;i!=nodes.length;++i) {
Node node = nodes[i];
switch (node.kind) {
case K_VOID:
writer.buildPrimitive(i,T_VOID);
break;
case K_ANY:
writer.buildPrimitive(i,T_ANY);
break;
case K_NULL:
writer.buildPrimitive(i,T_NULL);
break;
case K_BOOL:
writer.buildPrimitive(i,T_BOOL);
break;
case K_INT:
writer.buildPrimitive(i,T_INT);
break;
case K_RATIONAL:
writer.buildPrimitive(i,T_REAL);
break;
case K_SET:
writer.buildSet(i,(Integer) node.data);
break;
case K_LIST:
writer.buildList(i,(Integer) node.data);
break;
case K_PROCESS:
writer.buildProcess(i,(Integer) node.data);
break;
case K_EXISTENTIAL:
writer.buildExistential(i,(NameID) node.data);
break;
case K_DICTIONARY: {
// binary node
Pair<Integer, Integer> p = (Pair<Integer, Integer>) node.data;
writer.buildDictionary(i,p.first(),p.second());
break;
}
case K_UNION: {
int[] bounds = (int[]) node.data;
writer.buildUnion(i,bounds);
break;
}
case K_TUPLE: {
int[] bounds = (int[]) node.data;
writer.buildTuple(i,bounds);
break;
}
case K_FUNCTION: {
int[] bounds = (int[]) node.data;
int[] params = new int[bounds.length-2];
System.arraycopy(bounds, 2, params,0, params.length);
writer.buildFunction(i,bounds[0],bounds[1],params);
break;
}
case K_RECORD: {
// labeled nary node
Pair<String, Integer>[] fields = (Pair<String, Integer>[]) node.data;
writer.buildRecord(i,fields);
break;
}
default:
throw new IllegalArgumentException("Invalid type encountered");
}
}
}
}
// Type operations
/**
* A subtype relation encodes both a subtype and a supertype relation
* between two separate domains (called <code>from</code> and
* <code>to</code>).
*/
public final static class SubtypeRelation {
/**
* Indicates the size of the "source" domain.
*/
private final int fromDomain;
/**
* Indicates the size of the "target" domain.
*/
private final int toDomain;
/**
* Stores subtype relation as a binary matrix for dimenaion
* <code>fromDomain</code> x <code>toDomain</code>. This matrix
* <code>r</code> is organised into row-major order, where
* <code>r[i][j]</code> implies <code>i :> j</code>.
*/
private final BitSet subTypes;
/**
* Stores subtype relation as a binary matrix for dimenaion
* <code>fromDomain</code> x <code>toDomain</code>. This matrix
* <code>r</code> is organised into row-major order, where
* <code>r[i][j]</code> implies <code>i <: j</code>.
*/
private final BitSet superTypes;
public SubtypeRelation(int fromDomain, int toDomain) {
this.fromDomain = fromDomain;
this.toDomain = toDomain;
this.subTypes = new BitSet(fromDomain*toDomain);
this.superTypes = new BitSet(fromDomain*toDomain);
// Initially, set all sub- and super-types as true
subTypes.set(0,subTypes.size(),true);
superTypes.set(0,superTypes.size(),true);
}
/**
* Check whether a a given node is a subtype of another.
*
* @param from
* @param to
* @return
*/
public boolean isSubtype(int from, int to) {
return subTypes.get((fromDomain*from) + to);
}
/**
* Check whether a a given node is a supertype of another.
*
* @param from
* @param to
* @return
*/
public boolean isSupertype(int from, int to) {
return superTypes.get((fromDomain*from) + to);
}
/**
* Set the subtype flag for a given pair in the relation.
*
* @param from
* @param to
* @param flag
*/
public void setSubtype(int from, int to, boolean flag) {
subTypes.set((fromDomain*from) + to,false);
}
/**
* Set the supertype flag for a given pair in the relation.
*
* @param from
* @param to
* @param flag
*/
public void setSupertype(int from, int to, boolean flag) {
superTypes.set((fromDomain*from) + to,false);
}
}
/**
* A subtype inference is responsible for computing a complete subtype
* relation between two given graphs. The class is abstract because there
* are different possible implementations of this. In particular, the case
* when coercions are being considered, versus the case when they are not.
*
* @author djp
*
*/
public static abstract class SubtypeInference {
protected final Node[] fromGraph;
protected final Node[] toGraph;
protected final SubtypeRelation assumptions;
public SubtypeInference(Node[] fromGraph, Node[] toGraph) {
this.fromGraph = fromGraph;
this.toGraph = toGraph;
this.assumptions = new SubtypeRelation(fromGraph.length,toGraph.length);
}
public SubtypeRelation doInference() {
int fromDomain = fromGraph.length;
int toDomain = toGraph.length;
boolean changed = true;
while(changed) {
changed=false;
for(int i=0;i!=fromDomain;i++) {
for(int j=0;j!=toDomain;j++) {
boolean isubj = isSubType(i,j);
boolean isupj = isSuperType(i,j);
if(assumptions.isSubtype(i,j) != isubj) {
assumptions.setSubtype(i,j,false);
changed = true;
}
if(assumptions.isSupertype(i,j) != isupj) {
assumptions.setSupertype(i,j,false);
changed = true;
}
}
}
}
return assumptions;
}
public abstract boolean isSubType(int from, int to);
public abstract boolean isSuperType(int from, int to);
}
public static final class DefaultSubtypeOperator extends SubtypeInference {
public DefaultSubtypeOperator(Node[] fromGraph, Node[] toGraph) {
super(fromGraph,toGraph);
}
public boolean isSubType(int from, int to) {
Node fromNode = fromGraph[from];
Node toNode = toGraph[to];
if(fromNode.kind == toNode.kind) {
switch(fromNode.kind) {
case K_EXISTENTIAL:
NameID nid1 = (NameID) fromNode.data;
NameID nid2 = (NameID) toNode.data;
return nid1.equals(nid2);
case K_SET:
case K_LIST:
case K_PROCESS: {
return assumptions.isSubtype((Integer) fromNode.data,(Integer) toNode.data);
}
case K_DICTIONARY: {
// binary node
Pair<Integer, Integer> p1 = (Pair<Integer, Integer>) fromNode.data;
Pair<Integer, Integer> p2 = (Pair<Integer, Integer>) toNode.data;
return assumptions.isSubtype(p1.first(),p2.first()) && assumptions.isSubtype(p1.second(),p2.second());
}
case K_TUPLE: {
// nary nodes
int[] elems1 = (int[]) fromNode.data;
int[] elems2 = (int[]) toNode.data;
if(elems1.length != elems2.length){ return false; }
for(int i=0;i<elems1.length;++i) {
if(!assumptions.isSubtype(elems1[i],elems2[i])) { return false; }
}
return true;
}
case K_FUNCTION: {
// nary nodes
int[] elems1 = (int[]) fromNode.data;
int[] elems2 = (int[]) toNode.data;
if(elems1.length != elems2.length){
return false;
}
// Check (optional) receiver value first (which is contravariant)
int e1 = elems1[0];
int e2 = elems2[0];
if((e1 == -1 || e2 == -1) && e1 != e2) {
return false;
} else if (e1 != -1 && e2 != -1
&& !assumptions.isSupertype(e1,e2)) {
return false;
}
// Check return value first (which is covariant)
e1 = elems1[1];
e2 = elems2[1];
if(!assumptions.isSubtype(e1,e2)) {
return false;
}
// Now, check parameters (which are contra-variant)
for(int i=2;i<elems1.length;++i) {
e1 = elems1[i];
e2 = elems2[i];
if(!assumptions.isSupertype(e1,e2)) {
return false;
}
}
return true;
}
case K_RECORD:
{
Pair<String, Integer>[] fields1 = (Pair<String, Integer>[]) fromNode.data;
Pair<String, Integer>[] fields2 = (Pair<String, Integer>[]) toNode.data;
if(fields1.length != fields2.length) {
return false;
}
for (int i = 0; i != fields1.length; ++i) {
Pair<String, Integer> e1 = fields1[i];
Pair<String, Integer> e2 = fields2[i];
if (!e1.first().equals(e2.first())
|| !assumptions.isSubtype(e1.second(),e2.second())) {
return false;
}
}
/*
* follwing implements width subtyping and is disabled.
if(sign) {
// labeled nary nodes
Pair<String, Integer>[] _fields1 = (Pair<String, Integer>[]) c1.data;
Pair<String, Integer>[] fields2 = (Pair<String, Integer>[]) toNode.data;
HashMap<String,Integer> fields1 = new HashMap<String,Integer>();
for(Pair<String,Integer> f : _fields1) {
fields1.put(f.first(), f.second());
}
for (int i = 0; i != fields2.length; ++i) {
Pair<String, Integer> e2 = fields2[i];
Integer e1 = fields1.get(e2.first());
if (e1 == null
|| !subtypeMatrix.get((e1 * g2Size) + e2)) {
return false;
}
}
} else {
// labeled nary nodes
Pair<String, Integer>[] fields1 = (Pair<String, Integer>[]) c1.data;
Pair<String, Integer>[] _fields2 = (Pair<String, Integer>[]) toNode.data;
HashMap<String,Integer> fields2 = new HashMap<String,Integer>();
for(Pair<String,Integer> f : _fields2) {
fields2.put(f.first(), f.second());
}
for (int i = 0; i != fields1.length; ++i) {
Pair<String, Integer> e1 = fields1[i];
Integer e2 = fields2.get(e1.first());
if (e2 == null
|| !subtypeMatrix.get((e1.second() * g2Size) + e2)) {
return false;
}
}
*/
return true;
}
case K_UNION: {
int[] bounds1 = (int[]) fromNode.data;
// check every bound in c1 is a subtype of some bound in toNode.
for(int i : bounds1) {
if(!assumptions.isSubtype(i,to)) { return false; }
}
return true;
}
case K_LABEL:
throw new IllegalArgumentException("attempting to minimise open recurisve type");
default:
// primitive types true immediately
return true;
}
} else if(fromNode.kind == K_ANY || toNode.kind == K_VOID) {
return true;
} else if(fromNode.kind == K_UNION) {
int[] bounds1 = (int[]) fromNode.data;
// check every bound in c1 is a subtype of some bound in c2.
for(int i : bounds1) {
if(assumptions.isSubtype(i,to)) {
return true;
}
}
return false;
} else if(toNode.kind == K_UNION) {
int[] bounds2 = (int[]) toNode.data;
// check some bound in c1 is a subtype of some bound in c2.
for(int j : bounds2) {
if(!assumptions.isSubtype(from,j)) {
return false;
}
}
return true;
}
return false;
}
public boolean isSuperType(int from, int to) {
Node fromNode = fromGraph[from];
Node toNode = toGraph[to];
if(fromNode.kind == toNode.kind) {
switch(fromNode.kind) {
case K_EXISTENTIAL:
NameID nid1 = (NameID) fromNode.data;
NameID nid2 = (NameID) toNode.data;
return nid1.equals(nid2);
case K_SET:
case K_LIST:
case K_PROCESS: {
return assumptions.isSupertype((Integer) fromNode.data,(Integer) toNode.data);
}
case K_DICTIONARY: {
// binary node
Pair<Integer, Integer> p1 = (Pair<Integer, Integer>) fromNode.data;
Pair<Integer, Integer> p2 = (Pair<Integer, Integer>) toNode.data;
return assumptions.isSupertype(p1.first(),p2.first()) && assumptions.isSupertype(p1.second(),p2.second());
}
case K_TUPLE: {
// nary nodes
int[] elems1 = (int[]) fromNode.data;
int[] elems2 = (int[]) toNode.data;
if(elems1.length != elems2.length){ return false; }
for(int i=0;i<elems1.length;++i) {
if(!assumptions.isSupertype(elems1[i],elems2[i])) { return false; }
}
return true;
}
case K_FUNCTION: {
// nary nodes
int[] elems1 = (int[]) fromNode.data;
int[] elems2 = (int[]) toNode.data;
if(elems1.length != elems2.length){
return false;
}
// Check (optional) receiver value first (which is contravariant)
int e1 = elems1[0];
int e2 = elems2[0];
if((e1 == -1 || e2 == -1) && e1 != e2) {
return false;
} else if (e1 != -1 && e2 != -1
&& !assumptions.isSubtype(e1,e2)) {
return false;
}
// Check return value first (which is covariant)
e1 = elems1[1];
e2 = elems2[1];
if(!assumptions.isSupertype(e1,e2)) {
return false;
}
// Now, check parameters (which are contra-variant)
for(int i=2;i<elems1.length;++i) {
e1 = elems1[i];
e2 = elems2[i];
if(!assumptions.isSubtype(e1,e2)) {
return false;
}
}
return true;
}
case K_RECORD:
{
Pair<String, Integer>[] fields1 = (Pair<String, Integer>[]) fromNode.data;
Pair<String, Integer>[] fields2 = (Pair<String, Integer>[]) toNode.data;
if(fields1.length != fields2.length) {
return false;
}
for (int i = 0; i != fields1.length; ++i) {
Pair<String, Integer> e1 = fields1[i];
Pair<String, Integer> e2 = fields2[i];
if (!e1.first().equals(e2.first())
|| !assumptions.isSupertype(e1.second(),e2.second())) {
return false;
}
}
return true;
}
case K_UNION: {
int[] bounds2 = (int[]) toNode.data;
// check every bound in c1 is a subtype of some bound in toNode.
for(int i : bounds2) {
if(!assumptions.isSupertype(from,i)) {
return false;
}
}
return true;
}
case K_LABEL:
throw new IllegalArgumentException("attempting to minimise open recurisve type");
default:
// primitive types true immediately
return true;
}
} else if(fromNode.kind == K_VOID || toNode.kind == K_ANY) {
return true;
} else if(fromNode.kind == K_UNION) {
int[] bounds1 = (int[]) fromNode.data;
// check every bound in c1 is a subtype of some bound in c2.
for(int i : bounds1) {
if(!assumptions.isSupertype(i,to)) {
return false;
}
}
return true;
} else if(toNode.kind == K_UNION) {
int[] bounds2 = (int[]) toNode.data;
// check some bound in c1 is a subtype of some bound in c2.
for(int j : bounds2) {
if(assumptions.isSupertype(from,j)) {
return true;
}
}
}
return false;
}
}
/**
* Determine whether type <code>t2</code> is a <i>subtype</i> of type
* <code>t1</code> (written t1 :> t2). In other words, whether the set of
* all possible values described by the type <code>t2</code> is a subset of
* that described by <code>t1</code>.
*/
public static boolean isSubtype(Type t1, Type t2) {
Node[] g1 = nodes(t1);
Node[] g2 = nodes(t2);
SubtypeInference inference = new DefaultSubtypeOperator(g1,g2);
SubtypeRelation rel = inference.doInference();
return rel.isSubtype(0, 0);
}
/**
* Check whether two types are <i>isomorphic</i>. This is true if they are
* identical, or encode the same structure.
*
* @param t1
* @param t2
* @return
*/
public static boolean isomorphic(Type t1, Type t2) {
return isSubtype(t1,t2) && isSubtype(t2,t1);
}
/**
* Compute the <i>least upper bound</i> of two types t1 and t2. The least upper
* bound is a type t3 where <code>t3 :> t1</code>, <code>t3 :> t2</code> and
* there does not exist a type t4, where <code>t3 :> t4</code>,
* <code>t4 :> t1</code>, <code>t4 :> t2</code>.
*
* @param t1
* @param t2
* @return
*/
public static Type leastUpperBound(Type t1, Type t2) {
return minimise(T_UNION(t1,t2)); // so easy
}
/**
* Compute the <i>greatest lower bound</i> of two types t1 and t2. The
* greatest lower bound is a type t3 where <code>t1 :> t3</code>,
* <code>t2 :> t3</code> and there does not exist a type t4, where
* <code>t1 :> t4</code>, <code>t2 :> t4</code> and <code>t4 :> t3</code>.
*
* @param t1
* @param t2
* @return
*/
public static Type greatestLowerBound(Type t1, Type t2) {
// BUG FIX: this algorithm still isn't implemented correctly.
if(isSubtype(t1,t2)) {
return t2;
} else if(isSubtype(t2,t1)) {
return t1;
} else {
Node[] graph1, graph2;
if(t1 instanceof Leaf) {
graph1 = new Node[] { new Node(leafKind((Type.Leaf) t1), null) };
} else {
graph1 = ((Compound)t1).nodes;
}
if(t2 instanceof Leaf) {
graph2 = new Node[] { new Node(leafKind((Type.Leaf) t2), null) };
} else {
graph2 = ((Compound)t2).nodes;
}
ArrayList<Node> newNodes = new ArrayList<Node>();
intersect(0,graph1,0,graph2,newNodes, new HashMap());
Type glb = construct(newNodes.toArray(new Node[newNodes.size()]));
return minimise(glb);
}
}
/**
* Let <code>S</code> be determined by subtracting the set of values
* described by type <code>t2</code> from that described by <code>t1</code>.
* Then, this method returns the <i>least</i> type <code>t3</code> which
* covers <code>S</code> (that is, every value in <code>S</code> is in the
* set of values described by <code>t3</code>). Unfortunately, in some
* cases, <code>t3</code> may contain other (spurious) values not found in
* <code>S</code>.
*
* @param t1
* @param t2
* @return
*/
public static Type leastDifference(Type t1, Type t2) {
// BUG FIX: this algorithm still isn't implemented correctly.
if(isSubtype(t2,t1)) {
return T_VOID;
} else {
Node[] graph1, graph2;
if(t1 instanceof Leaf) {
graph1 = new Node[] { new Node(leafKind((Type.Leaf) t1), null) };
} else {
graph1 = ((Compound)t1).nodes;
}
if(t2 instanceof Leaf) {
graph2 = new Node[] { new Node(leafKind((Type.Leaf) t2), null) };
} else {
graph2 = ((Compound)t2).nodes;
}
SubtypeRelation assumptions = new DefaultSubtypeOperator(graph1,graph2).doInference();
ArrayList<Node> newNodes = new ArrayList<Node>();
difference(0,graph1,0,graph2,newNodes, new HashMap(),assumptions);
Type ldiff = construct(newNodes.toArray(new Node[newNodes.size()]));
return minimise(ldiff);
}
}
/**
* The effective record type gives a subset of the visible fields which are
* guaranteed to be in the type. For example, consider this type:
*
* <pre>
* {int op, int x} | {int op, [int] y}
* </pre>
*
* Here, the field op is guaranteed to be present. Therefore, the effective
* record type is just <code>{int op}</code>.
*
* @param t
* @return
*/
public static Record effectiveRecordType(Type t) {
if (t instanceof Type.Record) {
return (Type.Record) t;
} else if (t instanceof Type.Union) {
Union ut = (Type.Union) t;
Record r = null;
for (Type b : ut.bounds()) {
if (!(b instanceof Record)) {
return null;
}
Record br = (Record) b;
if (r == null) {
r = br;
} else {
HashMap<String, Type> rfields = r.fields();
HashMap<String, Type> bfields = br.fields();
HashMap<String, Type> nfields = new HashMap();
for (Map.Entry<String, Type> e : rfields.entrySet()) {
Type bt = bfields.get(e.getKey());
if (bt != null) {
nfields.put(e.getKey(),
leastUpperBound(e.getValue(), bt));
}
}
r = T_RECORD(nfields);
}
}
return r;
}
return null;
}
public static Set effectiveSetType(Type t) {
if (t instanceof Type.Set) {
return (Type.Set) t;
} else if (t instanceof Type.Union) {
Union ut = (Type.Union) t;
Set r = null;
for (Type b : ut.bounds()) {
if (!(b instanceof Set)) {
return null;
}
Set br = (Set) b;
if (r == null) {
r = br;
} else {
r = T_SET(leastUpperBound(r.element(),br.element()));
}
}
return r;
}
return null;
}
public static List effectiveListType(Type t) {
if (t instanceof Type.List) {
return (Type.List) t;
} else if (t instanceof Type.Union) {
Union ut = (Type.Union) t;
List r = null;
for (Type b : ut.bounds()) {
if (!(b instanceof List)) {
return null;
}
List br = (List) b;
if (r == null) {
r = br;
} else {
r = T_LIST(leastUpperBound(r.element(),br.element()));
}
}
return r;
}
return null;
}
public static Dictionary effectiveDictionaryType(Type t) {
if (t instanceof Type.Dictionary) {
return (Type.Dictionary) t;
} else if (t instanceof Type.Union) {
Union ut = (Type.Union) t;
Dictionary r = null;
for (Type b : ut.bounds()) {
if (!(b instanceof Dictionary)) {
return null;
}
Dictionary br = (Dictionary) b;
if (r == null) {
r = br;
} else {
r = T_DICTIONARY(leastUpperBound(r.key(), br.key()),
leastUpperBound(r.value(), br.value()));
}
}
return r;
}
return null;
}
/**
* Minimise the given type to produce a fully minimised version.
*
* @param type
* @return
*/
public static Type minimise(Type type) {
// leaf types never need minmising!
if (type instanceof Leaf) {
return type;
}
// compound types need minimising.
Node[] nodes = ((Compound) type).nodes;
SubtypeRelation relation = new DefaultSubtypeOperator(nodes,nodes).doInference();
//build(new PrintBuilder(System.out),type);
//System.out.println(toString(matrix,nodes.length,nodes.length));
ArrayList<Node> newnodes = new ArrayList<Node>();
int[] allocated = new int[nodes.length];
rebuild(0, nodes, allocated, newnodes, relation);
return construct(newnodes.toArray(new Node[newnodes.size()]));
}
private static String toString(BitSet matrix, int width, int height) {
String r = " |";
for(int i=0;i!=width;++i) {
r = r + " " + (i%10);
}
r = r + "\n-+";
for(int i=0;i!=width;++i) {
r = r + "
}
r = r + "\n";
for(int i=0;i!=height;++i) {
r = r + (i%10) + "|";;
for(int j=0;j!=width;++j) {
if(matrix.get((i*width)+j)) {
r += " 1";
} else {
r += " 0";
}
}
r = r + "\n";
}
return r;
}
/**
* This method reconstructs a graph given a set of equivalent nodes. The
* equivalence classes for a node are determined by the given subtype
* matrix, whilst the allocate array identifies when a node has already been
* allocated for a given equivalence class.
*
* @param idx
* @param graph
* @param allocated
* @param newNodes
* @param matrix
* @return
*/
private static int rebuild(int idx, Node[] graph, int[] allocated,
ArrayList<Node> newNodes, SubtypeRelation assumptions) {
int graph_size = graph.length;
Node node = graph[idx];
int cidx = allocated[idx];
if(cidx > 0) {
// node already constructed for this equivalence class
return cidx - 1;
}
cidx = newNodes.size(); // my new index
// now, allocate all nodes in equivalence class
for(int i=0;i!=graph_size;++i) {
if(assumptions.isSubtype(i,idx) && assumptions.isSubtype(idx, i)) {
allocated[i] = cidx + 1;
}
}
newNodes.add(null); // reserve space for my node
Object data = null;
switch(node.kind) {
case K_EXISTENTIAL:
data = node.data;
break;
case K_SET:
case K_LIST:
case K_PROCESS: {
int element = (Integer) node.data;
data = (Integer) rebuild(element,graph,allocated,newNodes,assumptions);
break;
}
case K_DICTIONARY: {
Pair<Integer,Integer> p = (Pair) node.data;
int from = (Integer) rebuild(p.first(),graph,allocated,newNodes,assumptions);
int to = (Integer) rebuild(p.second(),graph,allocated,newNodes,assumptions);
data = new Pair(from,to);
break;
}
case K_TUPLE:
case K_FUNCTION: {
int[] elems = (int[]) node.data;
int[] nelems = new int[elems.length];
for(int i = 0; i!=elems.length;++i) {
if(elems[i] == -1) {
// possible for K_FUNCTION
nelems[i] = -1;
} else {
nelems[i] = (Integer) rebuild(elems[i],graph,allocated,newNodes,assumptions);
}
}
data = nelems;
break;
}
case K_RECORD: {
Pair<String, Integer>[] elems = (Pair[]) node.data;
Pair<String, Integer>[] nelems = new Pair[elems.length];
for (int i = 0; i != elems.length; ++i) {
Pair<String, Integer> p = elems[i];
int j = (Integer) rebuild(p.second(), graph, allocated,
newNodes, assumptions);
nelems[i] = new Pair<String, Integer>(p.first(), j);
}
data = nelems;
break;
}
case K_UNION: {
int[] elems = (int[]) node.data;
// The aim here is to try and remove equivalent nodes, and nodes
// which are subsumed by other nodes.
HashSet<Integer> nelems = new HashSet<Integer>();
for(int i : elems) { nelems.add(i); }
for(int i=0;i!=elems.length;i++) {
int n1 = elems[i];
for(int j=0;j<elems.length;j++) {
if(i==j) { continue; }
int n2 = elems[j];
if(assumptions.isSubtype(n2,n1) && (!assumptions.isSubtype(n1,n2) || i < j)) {
nelems.remove(n2);
}
}
}
// ok, let's see what we've got left
if (nelems.size() == 1) {
// ok, union node should be removed as it's entirely subsumed. I
// need to undo what I've already done in allocating a new node.
newNodes.remove(cidx);
for (int i = 0; i != graph_size; ++i) {
if(assumptions.isSubtype(i,idx) && assumptions.isSubtype(idx,i)) {
allocated[i] = 0;
}
}
return rebuild(nelems.iterator().next(), graph, allocated, newNodes,
assumptions);
} else {
// first off, we have to normalise this sucker
ArrayList<Integer> nnelems = new ArrayList(nelems);
Collections.sort(nnelems,new MinimiseComparator(graph,assumptions));
// ok, now rebuild
int[] melems = new int[nelems.size()];
int i=0;
for (Integer j : nnelems) {
melems[i++] = (Integer) rebuild(j, graph,
allocated, newNodes, assumptions);
}
data = melems;
}
break;
}
}
// finally, create the new node!!!
newNodes.set(cidx, new Node(node.kind,data));
return cidx;
}
private static final class MinimiseComparator implements Comparator<Integer> {
private Node[] graph;
private SubtypeRelation subtypeMatrix;
public MinimiseComparator(Node[] graph, SubtypeRelation matrix) {
this.graph = graph;
this.subtypeMatrix = matrix;
}
public int compare(Integer a, Integer b) {
Node n1 = graph[a];
Node n2 = graph[b];
if(n1.kind < n2.kind) {
return -1;
} else if(n1.kind > n2.kind) {
return 1;
} else {
// First try subtype relation
int gSize = graph.length;
if (subtypeMatrix.isSubtype(a,b)) {
return -1;
} else if (subtypeMatrix.isSubtype(b,a)) {
return 1;
}
// Second try harder stuff
Object data1 = n1.data;
Object data2 = n2.data;
switch(n1.kind){
case K_VOID:
case K_ANY:
case K_META:
case K_NULL:
case K_BOOL:
case K_INT:
case K_RATIONAL:
return 0;
case K_EXISTENTIAL: {
String s1 = (String) data1;
String s2 = (String) data2;
return s1.compareTo(s2);
}
case K_RECORD: {
Pair[] fields1 = (Pair[]) data1;
Pair[] fields2 = (Pair[]) data2;
if(fields1.length < fields2.length) {
return -1;
} else if(fields1.length > fields2.length) {
return 1;
}
// FIXME: could presumably do more here.
}
// FIXME: could do more here!!
}
if(a < b) {
return -1;
} else if(a > b) {
return 1;
} else {
return 0;
}
}
}
}
private static int intersect(int n1, Node[] graph1, int n2, Node[] graph2,
ArrayList<Node> newNodes,
HashMap<Pair<Integer, Integer>, Integer> allocations) {
Integer idx = allocations.get(new Pair(n1,n2));
if(idx != null) {
// this indicates an allocation has already been performed for this
// pair.
return idx;
}
Node c1 = graph1[n1];
Node c2 = graph2[n2];
int nid = newNodes.size(); // my node id
newNodes.add(null); // reserve space for my node
allocations.put(new Pair(n1,n2), nid);
Node node; // new node being created
if(c1.kind == c2.kind) {
switch(c1.kind) {
case K_VOID:
case K_ANY:
case K_META:
case K_NULL:
case K_BOOL:
case K_INT:
case K_RATIONAL:
node = c1;
break;
case K_EXISTENTIAL:
NameID nid1 = (NameID) c1.data;
NameID nid2 = (NameID) c2.data;
if(nid1.name().equals(nid2.name())) {
node = c1;
} else {
node = new Node(K_VOID,null);
}
break;
case K_SET:
case K_LIST:
case K_PROCESS: {
// unary node
int e1 = (Integer) c1.data;
int e2 = (Integer) c2.data;
int element = intersect(e1,graph1,e2,graph2,newNodes,allocations);
node = new Node(c1.kind,element);
break;
}
case K_DICTIONARY: {
// binary node
Pair<Integer, Integer> p1 = (Pair<Integer, Integer>) c1.data;
Pair<Integer, Integer> p2 = (Pair<Integer, Integer>) c2.data;
int key = intersect(p1.first(),graph2,p2.first(),graph2,newNodes,allocations);
int value = intersect(p1.second(),graph2,p2.second(),graph2,newNodes,allocations);
node = new Node(K_DICTIONARY,new Pair(key,value));
break;
}
case K_TUPLE: {
// nary nodes
int[] elems1 = (int[]) c1.data;
int[] elems2 = (int[]) c2.data;
if(elems1.length != elems2.length) {
// TODO: can we do better here?
node = new Node(K_VOID,null);
} else {
int[] nelems = new int[elems1.length];
for(int i=0;i!=nelems.length;++i) {
nelems[i] = intersect(elems1[i],graph1,elems2[i],graph2,newNodes,allocations);
}
node = new Node(K_TUPLE,nelems);
}
break;
}
case K_FUNCTION: {
// nary nodes
int[] elems1 = (int[]) c1.data;
int[] elems2 = (int[]) c2.data;
int e1 = elems1[0];
int e2 = elems2[0];
if(elems1.length != elems2.length){
node = new Node(K_VOID,null);
} else if ((e1 == -1 || e2 == -1) && e1 != e2) {
node = new Node(K_VOID, null);
} else {
int[] nelems = new int[elems1.length];
// TODO: need to check here whether or not this is the right
// thing to do. My gut is telling me that covariant and
// contravariance should be treated differently ...
for (int i = 0; i != nelems.length; ++i) {
nelems[i] = intersect(elems1[i], graph1, elems2[i],
graph2, newNodes,allocations);
}
node = new Node(K_FUNCTION, nelems);
}
break;
}
case K_RECORD:
// labeled nary nodes
outer: {
Pair<String, Integer>[] fields1 = (Pair<String, Integer>[]) c1.data;
Pair<String, Integer>[] fields2 = (Pair<String, Integer>[]) c2.data;
int old = newNodes.size();
if(fields1.length != fields2.length) {
node = new Node(K_VOID,null);
} else {
Pair<String, Integer>[] nfields = new Pair[fields1.length];
for (int i = 0; i != nfields.length; ++i) {
Pair<String,Integer> e1 = fields1[i];
Pair<String,Integer> e2 = fields2[i];
if (!e1.first().equals(e2.first())) {
node = new Node(K_VOID, null);
break outer;
} else {
int nidx = intersect(e1.second(), graph1, e2.second(), graph2, newNodes,
allocations);
if (newNodes.get(nidx).kind == K_VOID) {
// A record with a field of void type cannot
while (newNodes.size() != old) {
newNodes.remove(newNodes.size() - 1);
}
node = new Node(K_VOID, null);
break outer;
}
nfields[i] = new Pair<String, Integer>(e1.first(), nidx);
}
}
node = new Node(K_RECORD, nfields);
}
}
break;
case K_UNION: {
// This is the hardest (i.e. most expensive) case. Essentially, I
// just check that for each bound in one node, there is an
// equivalent bound in the other.
int[] bounds1 = (int[]) c1.data;
int[] nbounds = new int[bounds1.length];
// check every bound in c1 is a subtype of some bound in c2.
for (int i = 0; i != bounds1.length; ++i) {
nbounds[i] = intersect(bounds1[i], graph1, n2, graph2,
newNodes,allocations);
}
node = new Node(K_UNION,nbounds);
break;
}
default:
throw new IllegalArgumentException("attempting to minimise open recurisve type");
}
} else if(c1.kind == K_INT && c2.kind == K_RATIONAL) {
node = new Node(K_INT,null);
} else if(c1.kind == K_RATIONAL && c2.kind == K_INT) {
node = new Node(K_INT,null);
} else if(c1.kind == K_ANY) {
newNodes.remove(newNodes.size()-1);
extractOnto(n2,graph2,newNodes);
return nid;
} else if(c2.kind == K_ANY) {
newNodes.remove(newNodes.size()-1);
extractOnto(n1,graph1,newNodes);
return nid;
} else if (c1.kind == K_UNION){
int[] obounds = (int[]) c1.data;
int[] nbounds = new int[obounds.length];
// check every bound in c1 is a subtype of some bound in c2.
for (int i = 0; i != obounds.length; ++i) {
nbounds[i] = intersect(obounds[i], graph1, n2, graph2,
newNodes,allocations);
}
node = new Node(K_UNION,nbounds);
} else if (c2.kind == K_UNION) {
int[] obounds = (int[]) c2.data;
int[] nbounds = new int[obounds.length];
// check every bound in c1 is a subtype of some bound in c2.
for (int i = 0; i != obounds.length; ++i) {
nbounds[i] = intersect(n1,graph1,obounds[i], graph2,
newNodes,allocations);
}
node = new Node(K_UNION,nbounds);
} else {
// default case --> go to void
node = new Node(K_VOID,null);
}
// finally, create the new node!!!
newNodes.set(nid, node);
return nid;
}
private static int difference(int n1, Node[] graph1, int n2, Node[] graph2,
ArrayList<Node> newNodes,
HashMap<Pair<Integer, Integer>, Integer> allocations, SubtypeRelation matrix) {
int nid = newNodes.size(); // my node id
if(matrix.isSupertype(n1,n2)) {
newNodes.add(new Node(K_VOID,null));
return nid;
}
Integer idx = allocations.get(new Pair(n1,n2));
if(idx != null) {
// this indicates an allocation has already been performed for this
// pair.
return idx;
}
Node c1 = graph1[n1];
Node c2 = graph2[n2];
allocations.put(new Pair(n1,n2), nid);
newNodes.add(null); // reserve space for my node
Node node; // new node being created
if(c1.kind == c2.kind) {
switch(c1.kind) {
case K_VOID:
case K_ANY:
case K_META:
case K_NULL:
case K_BOOL:
case K_INT:
case K_RATIONAL:
node = new Node(K_VOID,null);
break;
case K_EXISTENTIAL:
NameID nid1 = (NameID) c1.data;
NameID nid2 = (NameID) c2.data;
if(nid1.name().equals(nid2.name())) {
node = new Node(K_VOID,null);
} else {
node = c1;
}
break;
case K_SET:
case K_LIST:
case K_PROCESS: {
// unary node
int e1 = (Integer) c1.data;
int e2 = (Integer) c2.data;
int element = difference(e1,graph1,e2,graph2,newNodes,allocations,matrix);
node = new Node(c1.kind,element);
break;
}
case K_DICTIONARY: {
// binary node
Pair<Integer, Integer> p1 = (Pair<Integer, Integer>) c1.data;
Pair<Integer, Integer> p2 = (Pair<Integer, Integer>) c2.data;
int key = difference(p1.first(),graph2,p2.first(),graph2,newNodes,allocations,matrix);
int value = difference(p1.second(),graph2,p2.second(),graph2,newNodes,allocations,matrix);
node = new Node(K_DICTIONARY,new Pair(key,value));
break;
}
case K_TUPLE: {
// nary nodes
int[] elems1 = (int[]) c1.data;
int[] elems2 = (int[]) c2.data;
if(elems1.length != elems2.length) {
node = c1;
} else {
int[] nelems = new int[elems1.length];
for(int i=0;i!=nelems.length;++i) {
nelems[i] = difference(elems1[i],graph1,elems2[i],graph2,newNodes,allocations,matrix);
}
node = new Node(K_TUPLE,nelems);
}
break;
}
case K_FUNCTION: {
// nary nodes
int[] elems1 = (int[]) c1.data;
int[] elems2 = (int[]) c2.data;
int e1 = elems1[0];
int e2 = elems2[0];
if(elems1.length != elems2.length){
node = c1;
} else if ((e1 == -1 || e2 == -1) && e1 != e2) {
node = c1;
} else {
int[] nelems = new int[elems1.length];
// TODO: need to check here whether or not this is the right
// thing to do. My gut is telling me that covariant and
// contravariance should be treated differently ...
for (int i = 0; i != nelems.length; ++i) {
nelems[i] = difference(elems1[i], graph1, elems2[i],
graph2, newNodes,allocations,matrix);
}
node = new Node(K_FUNCTION, nelems);
}
break;
}
case K_RECORD:
// labeled nary nodes
Pair<String, Integer>[] fields1 = (Pair<String, Integer>[]) c1.data;
Pair<String, Integer>[] fields2 = (Pair<String, Integer>[]) c2.data;
if(fields1.length != fields2.length) {
node = c1;
} else {
outer: {
Pair<String, Integer>[] nfields = new Pair[fields1.length];
// FIXME: need to support WIDTH subtyping here.
for (int i = 0; i != fields1.length; ++i) {
Pair<String, Integer> e1 = fields1[i];
Pair<String, Integer> e2 = fields2[i];
if (!e1.first().equals(e2.first())) {
node = c1;
break outer;
} else {
nfields[i] = new Pair<String, Integer>(
e1.first(), difference(e1.second(),
graph1, e2.second(), graph2,
newNodes,allocations,matrix));
}
}
node = new Node(K_RECORD, nfields);
}
}
break;
case K_UNION: {
// This is the hardest (i.e. most expensive) case. Essentially, I
// just check that for each bound in one node, there is an
// equivalent bound in the other.
int[] bounds1 = (int[]) c1.data;
int[] nbounds = new int[bounds1.length];
// check every bound in c1 is a subtype of some bound in c2.
for (int i = 0; i != bounds1.length; ++i) {
nbounds[i] = difference(bounds1[i], graph1, n2, graph2,
newNodes,allocations,matrix);
}
node = new Node(K_UNION,nbounds);
break;
}
default:
throw new IllegalArgumentException("attempting to minimise open recurisve type");
}
} else if(c1.kind == K_INT && c2.kind == K_RATIONAL) {
// this is obviously imprecise
node = new Node(K_VOID,null);
} else if(c1.kind == K_RATIONAL && c2.kind == K_INT) {
// this is obviously imprecise
node = new Node(K_RATIONAL,null);
} else if(c1.kind == K_ANY) {
// TODO: try to do better
node = new Node(K_ANY,null);
} else if(c2.kind == K_ANY) {
node = new Node(K_VOID,null);
} else if (c1.kind == K_UNION){
int[] obounds = (int[]) c1.data;
int[] nbounds = new int[obounds.length];
for (int i = 0; i != obounds.length; ++i) {
nbounds[i] = difference(obounds[i], graph1, n2, graph2,
newNodes,allocations,matrix);
}
node = new Node(K_UNION,nbounds);
} else if (c2.kind == K_UNION) {
int[] obounds = (int[]) c2.data;
int[] nbounds = new int[obounds.length];
for (int i = 0; i != obounds.length; ++i) {
nbounds[i] = difference(n1,graph1,obounds[i], graph2,
newNodes,allocations,matrix);
}
// FIXME: this is broken. need intersection types.
node = new Node(K_UNION,nbounds);
} else {
// default case --> go to no change
node = c1;
}
if(node == c1) {
while(newNodes.size() > nid) {
newNodes.remove(newNodes.size()-1);
}
extractOnto(n1,graph1,newNodes);
return nid;
} else {
// finally, create the new node!!!
newNodes.set(nid, node);
return nid;
}
}
// Primitive Types
/**
* A leaf type represents a type which has no component types. For example,
* primitive types like <code>int</code> and <code>real</code> are leaf
* types.
*
* @author djp
*
*/
public static class Leaf extends Type {}
/**
* A void type represents the type whose variables cannot exist! That is,
* they cannot hold any possible value. Void is used to represent the return
* type of a function which does not return anything. However, it is also
* used to represent the element type of an empty list of set. <b>NOTE:</b>
* the void type is a subtype of everything; that is, it is bottom in the
* type lattice.
*
* @author djp
*
*/
public static final class Void extends Leaf {
private Void() {}
public boolean equals(Object o) {
return this == o;
}
public int hashCode() {
return 1;
}
public String toString() {
return "void";
}
}
/**
* The type any represents the type whose variables may hold any possible
* value. <b>NOTE:</b> the any type is top in the type lattice.
*
* @author djp
*
*/
public static final class Any extends Leaf {
private Any() {}
public boolean equals(Object o) {
return o == T_ANY;
}
public int hashCode() {
return 1;
}
public String toString() {
return "any";
}
}
/**
* The null type is a special type which should be used to show the absence
* of something. It is distinct from void, since variables can hold the
* special <code>null</code> value (where as there is no special "void"
* value). With all of the problems surrounding <code>null</code> and
* <code>NullPointerException</code>s in languages like Java and C, it may
* seem that this type should be avoided. However, it remains a very useful
* abstraction to have around and, in Whiley, it is treated in a completely
* safe manner (unlike e.g. Java).
*
* @author djp
*
*/
public static final class Null extends Leaf {
private Null() {}
public boolean equals(Object o) {
return this == o;
}
public int hashCode() {
return 2;
}
public String toString() {
return "null";
}
}
/**
* The type mets represents the type of types. That is, values of this type
* are themselves types. (think reflection, where we have
* <code>class Class {}</code>).
*
* @author djp
*
*/
public static final class Meta extends Leaf {
private Meta() {}
public boolean equals(Object o) {
return o == T_META;
}
public int hashCode() {
return 1;
}
public String toString() {
return "type";
}
}
/**
* The existential type represents the an unknown type, defined at a given
* position.
*
* @author djp
*
*/
public static final class Existential extends Compound{
private Existential(NameID name) {
super(new Node[] { new Node(K_EXISTENTIAL,name) });
}
public boolean equals(Object o) {
if(o instanceof Existential) {
Existential e = (Existential) o;
return nodes[0].data.equals(nodes[0].data);
}
return false;
}
public NameID name() {
return (NameID) nodes[0].data;
}
public int hashCode() {
return nodes[0].data.hashCode();
}
public String toString() {
return "?" + name();
}
}
/**
* Represents the set of boolean values (i.e. true and false)
* @author djp
*
*/
public static final class Bool extends Leaf {
private Bool() {}
public boolean equals(Object o) {
return o == T_BOOL;
}
public int hashCode() {
return 3;
}
public String toString() {
return "bool";
}
}
/**
* Represents the set of (unbound) integer values. Since integer types in
* Whiley are unbounded, there is no equivalent to Java's
* <code>MIN_VALUE</code> and <code>MAX_VALUE</code> for <code>int</code>
* types.
*
* @author djp
*
*/
public static final class Int extends Leaf {
private Int() {}
public boolean equals(Object o) {
return o == T_INT;
}
public int hashCode() {
return 4;
}
public String toString() {
return "int";
}
}
/**
* Represents the set of (unbound) rational numbers.
*
* @author djp
*
*/
public static final class Real extends Leaf {
private Real() {}
public boolean equals(Object o) {
return o == T_REAL;
}
public int hashCode() {
return 5;
}
public String toString() {
return "real";
}
}
// Compound Type
/**
* A Compound data structure is essentially a graph encoding of a type. Each
* node in the graph corresponds to a component of the type. Recursive
* cycles in the graph are permitted. <b>NOTE:</b> care must be take to
* ensure that the root of the graph (namely node at index 0) matches the
* actual Compound class (i.e. if its kind is K_SET, then this is an
* instance of Set).
*/
private static class Compound extends Type {
protected final Node[] nodes;
public Compound(Node[] nodes) {
this.nodes = nodes;
}
/**
* Determine the hashCode of a type.
*/
public int hashCode() {
int r = 0;
for(Node c : nodes) {
r = r + c.hashCode();
}
return r;
}
/**
* This method compares two compound types to test whether they are
* <i>identical</i>. Observe that it does not perform an
* <i>isomorphism</i> test. Thus, two distinct types which are
* structurally isomorphic will <b>not</b> be considered equal under
* this method. <b>NOTE:</b> to test whether two types are structurally
* isomorphic, using the <code>isomorphic(t1,t2)</code> method.
*/
public boolean equals(Object o) {
if(o instanceof Compound) {
Node[] cs = ((Compound) o).nodes;
if(cs.length != nodes.length) {
return false;
}
for(int i=0;i!=cs.length;++i) {
if(!nodes[i].equals(cs[i])) {
return false;
}
}
return true;
}
return false;
}
protected final Type extract(int root) {
return construct(Type.extract(root,nodes));
}
public String toString() {
// First, we need to find the headers of the computation. This is
// necessary in order to mark the start of a recursive type.
BitSet headers = new BitSet(nodes.length);
BitSet visited = new BitSet(nodes.length);
BitSet onStack = new BitSet(nodes.length);
findHeaders(0,visited,onStack,headers,nodes);
visited.clear();
String[] titles = new String[nodes.length];
int count = 0;
for(int i=0;i!=nodes.length;++i) {
if(headers.get(i)) {
titles[i] = headerTitle(count++);
}
}
return Type.toString(0,visited,titles,nodes);
}
}
private static final Node[] extract(int root, Node[] nodes) {
// First, we perform the DFS.
BitSet visited = new BitSet(nodes.length);
// extracted maps new indices to old indices
ArrayList<Integer> extracted = new ArrayList<Integer>();
subgraph(root,visited,extracted,nodes);
// rextracted is the reverse of extracted
int[] rextracted = new int[nodes.length];
int i=0;
for(int j : extracted) {
rextracted[j]=i++;
}
Node[] newNodes = new Node[extracted.size()];
i=0;
for(int j : extracted) {
newNodes[i++] = remap(nodes[j],rextracted);
}
return newNodes;
}
private static final void extractOnto(int root, Node[] nodes,
ArrayList<Node> newNodes) {
// First, we perform the DFS.
BitSet visited = new BitSet(nodes.length);
// extracted maps new indices to old indices
ArrayList<Integer> extracted = new ArrayList<Integer>();
subgraph(root, visited, extracted, nodes);
// rextracted is the reverse of extracted
int[] rextracted = new int[nodes.length];
int i = newNodes.size();
for (int j : extracted) {
rextracted[j] = i++;
}
for (int j : extracted) {
newNodes.add(remap(nodes[j], rextracted));
}
}
private final static void subgraph(int index, BitSet visited,
ArrayList<Integer> extracted, Node[] graph) {
if(visited.get(index)) { return; } // node already visited}
extracted.add(index);
visited.set(index);
Node node = graph[index];
switch(node.kind) {
case K_SET:
case K_LIST:
case K_PROCESS:
// unary nodes
subgraph((Integer) node.data,visited,extracted,graph);
break;
case K_DICTIONARY:
// binary node
Pair<Integer,Integer> p = (Pair<Integer,Integer>) node.data;
subgraph(p.first(),visited,extracted,graph);
subgraph(p.second(),visited,extracted,graph);
break;
case K_TUPLE:
case K_UNION:
case K_FUNCTION:
// nary node
int[] bounds = (int[]) node.data;
for(int b : bounds) {
if(b == -1) { continue; } // possible with K_FUNCTION
subgraph(b,visited,extracted,graph);
}
break;
case K_RECORD:
// labeled nary node
Pair<String,Integer>[] fields = (Pair<String,Integer>[]) node.data;
for(Pair<String,Integer> f : fields) {
subgraph(f.second(),visited,extracted,graph);
}
break;
}
}
private final static void findHeaders(int index, BitSet visited,
BitSet onStack, BitSet headers, Node[] graph) {
if(visited.get(index)) {
// node already visited
if(onStack.get(index)) {
headers.set(index);
}
return;
}
onStack.set(index);
visited.set(index);
Node node = graph[index];
switch(node.kind) {
case K_SET:
case K_LIST:
case K_PROCESS:
// unary nodes
findHeaders((Integer) node.data,visited,onStack,headers,graph);
break;
case K_DICTIONARY:
// binary node
Pair<Integer,Integer> p = (Pair<Integer,Integer>) node.data;
findHeaders(p.first(),visited,onStack,headers,graph);
findHeaders(p.second(),visited,onStack,headers,graph);
break;
case K_TUPLE:
case K_UNION:
case K_FUNCTION:
// nary node
int[] bounds = (int[]) node.data;
for(int b : bounds) {
if(b == -1) { continue; } // possible with K_FUNCTION
findHeaders(b,visited,onStack,headers,graph);
}
break;
case K_RECORD:
// labeled nary node
Pair<String,Integer>[] fields = (Pair<String,Integer>[]) node.data;
for(Pair<String,Integer> f : fields) {
findHeaders(f.second(),visited,onStack,headers,graph);
}
break;
}
onStack.set(index,false);
}
private final static String toString(int index, BitSet visited,
String[] headers, Node[] graph) {
if (visited.get(index)) {
// node already visited
return headers[index];
} else if(headers[index] != null) {
visited.set(index);
}
Node node = graph[index];
String middle;
switch (node.kind) {
case K_VOID:
return "void";
case K_ANY:
return "any";
case K_NULL:
return "null";
case K_BOOL:
return "bool";
case K_INT:
return "int";
case K_RATIONAL:
return "rat";
case K_SET:
middle = "{" + toString((Integer) node.data, visited, headers, graph)
+ "}";
break;
case K_LIST:
middle = "[" + toString((Integer) node.data, visited, headers, graph)
+ "]";
break;
case K_EXISTENTIAL:
middle = "?" + node.data.toString();
break;
case K_PROCESS:
middle = "*" + toString((Integer) node.data, visited, headers, graph);
break;
case K_DICTIONARY: {
// binary node
Pair<Integer, Integer> p = (Pair<Integer, Integer>) node.data;
String k = toString(p.first(), visited, headers, graph);
String v = toString(p.second(), visited, headers, graph);
middle = "{" + k + "->" + v + "}";
break;
}
case K_UNION: {
int[] bounds = (int[]) node.data;
middle = "";
for (int i = 0; i != bounds.length; ++i) {
if (i != 0) {
middle += "|";
}
middle += toString(bounds[i], visited, headers, graph);
}
break;
}
case K_TUPLE: {
middle = "";
int[] bounds = (int[]) node.data;
for (int i = 0; i != bounds.length; ++i) {
if (i != 0) {
middle += ",";
}
middle += toString(bounds[i], visited, headers, graph);
}
middle = "(" + middle + ")";
break;
}
case K_FUNCTION: {
middle = "";
int[] bounds = (int[]) node.data;
String rec = bounds[0] == -1 ? null : toString(bounds[0],visited,headers,graph);
String ret = toString(bounds[1], visited, headers, graph);
for (int i = 2; i != bounds.length; ++i) {
if (i != 2) {
middle += ",";
}
middle += toString(bounds[i], visited, headers, graph);
}
if(rec != null) {
middle = rec + "::" + ret + "(" + middle + ")";
} else {
middle = ret + "(" + middle + ")";
}
break;
}
case K_RECORD: {
// labeled nary node
middle = "{";
Pair<String, Integer>[] fields = (Pair<String, Integer>[]) node.data;
for (int i = 0; i != fields.length; ++i) {
if (i != 0) {
middle += ",";
}
Pair<String, Integer> f = fields[i];
middle += toString(f.second(), visited, headers, graph) + " " + f.first();
}
middle = middle + "}";
break;
}
default:
throw new IllegalArgumentException("Invalid type encountered");
}
// Finally, check whether this is a header node, or not. If it is a
// header then we need to insert the recursive type.
String header = headers[index];
if(header != null) {
return header + "<" + middle + ">";
} else {
return middle;
}
}
private static final char[] headers = { 'X','Y','Z','U','V','W','L','M','N','O','P','Q','R','S','T'};
private static String headerTitle(int count) {
String r = Character.toString(headers[count%headers.length]);
int n = count / headers.length;
if(n > 0) {
return r + n;
} else {
return r;
}
}
// Compound Faces
/*
* The compound faces are not technically necessary, as they simply provide
* interfaces to the underlying nodes of a compound type. However, they
* certainly make it more pleasant to use this library.
*/
/**
* A tuple type describes a compound type made up of two or more
* subcomponents. It is similar to a record, except that fields are
* effectively anonymous.
*
* @author djp
*
*/
public static final class Tuple extends Compound {
private Tuple(Node[] nodes) {
super(nodes);
}
public java.util.List<Type> elements() {
int[] values = (int[]) nodes[0].data;
ArrayList<Type> elems = new ArrayList<Type>();
for(Integer i : values) {
elems.add(extract(i));
}
return elems;
}
}
/**
* A set type describes set values whose elements are subtypes of the
* element type. For example, <code>{1,2,3}</code> is an instance of set
* type <code>{int}</code>; however, <code>{1.345}</code> is not.
*
* @author djp
*
*/
public static final class Set extends Compound {
private Set(Node[] nodes) {
super(nodes);
}
public Type element() {
return extract(1);
}
}
/**
* A list type describes list values whose elements are subtypes of the
* element type. For example, <code>[1,2,3]</code> is an instance of list
* type <code>[int]</code>; however, <code>[1.345]</code> is not.
*
* @author djp
*
*/
public static final class List extends Compound {
private List(Node[] nodes) {
super(nodes);
}
public Type element() {
return extract(1);
}
}
/**
* A process represents a reference to an actor in Whiley.
*
* @author djp
*
*/
public static final class Process extends Compound {
private Process(Node[] nodes) {
super(nodes);
}
public Type element() {
int i = (Integer) nodes[0].data;
return extract(i);
}
}
/**
* A dictionary represents a one-many mapping from variables of one type to
* variables of another type. For example, the dictionary type
* <code>int->real</code> represents a map from integers to real values. A
* valid instance of this type might be <code>{1->1.2,2->3}</code>.
*
* @author djp
*
*/
public static final class Dictionary extends Compound {
private Dictionary(Node[] nodes) {
super(nodes);
}
public Type key() {
Pair<Integer,Integer> p = (Pair) nodes[0].data;
return extract(p.first());
}
public Type value() {
Pair<Integer,Integer> p = (Pair) nodes[0].data;
return extract(p.second());
}
}
/**
* A record is made up of a number of fields, each of which has a unique
* name. Each field has a corresponding type. One can think of a record as a
* special kind of "fixed" dictionary (i.e. where we know exactly which
* entries we have).
*
* @author djp
*
*/
public static final class Record extends Compound {
private Record(Node[] nodes) {
super(nodes);
}
/**
* Extract just the key set for this field. This is a cheaper operation
* than extracting the keys and their types (since types must be
* extracted).
*
* @return
*/
public HashSet<String> keys() {
Pair<String,Integer>[] fields = (Pair[]) nodes[0].data;
HashSet<String> r = new HashSet<String>();
for(Pair<String,Integer> f : fields) {
r.add(f.first());
}
return r;
}
/**
* Return a mapping from field names to their types.
*
* @return
*/
public HashMap<String,Type> fields() {
Pair<String,Integer>[] fields = (Pair[]) nodes[0].data;
HashMap<String,Type> r = new HashMap<String,Type>();
for(Pair<String,Integer> f : fields) {
r.put(f.first(),extract(f.second()));
}
return r;
}
}
/**
* A union type represents a type whose variables may hold values from any
* of its "bounds". For example, the union type null|int indicates a
* variable can either hold an integer value, or null. <b>NOTE:</b>There
* must be at least two bounds for a union type to make sense.
*
* @author djp
*
*/
public static final class Union extends Compound {
private Union(Node[] nodes) {
super(nodes);
}
/**
* Return the bounds of this union type.
*
* @return
*/
public HashSet<Type> bounds() {
HashSet<Type> r = new HashSet<Type>();
// FIXME: this is a bit of a cludge. The essential idea is to
// flattern unions, so we never see a union of unions. This is
// helpful for simplifying various algorithms which use them
Stack<Union> stack = new Stack<Union>();
stack.add(this);
while(!stack.isEmpty()) {
Union u = stack.pop();
int[] fields = (int[]) u.nodes[0].data;
for(int i : fields) {
Type b = u.extract(i);
if(b instanceof Union) {
stack.add((Union)b);
} else {
r.add(b);
}
}
}
return r;
}
}
/**
* A function type, consisting of a list of zero or more parameters and a
* return type.
*
* @author djp
*
*/
public static final class Fun extends Compound {
Fun(Node[] nodes) {
super(nodes);
}
/**
* Get the return type of this function type.
*
* @return
*/
public Type ret() {
int[] fields = (int[]) nodes[0].data;
return extract(fields[1]);
}
/**
* Get the return type of this function type.
*
* @return
*/
public Type receiver() {
int[] fields = (int[]) nodes[0].data;
int r = fields[0];
if(r == -1) { return null; }
return extract(r);
}
/**
* Get the parameter types of this function type.
*
* @return
*/
public ArrayList<Type> params() {
int[] fields = (int[]) nodes[0].data;
ArrayList<Type> r = new ArrayList<Type>();
for(int i=2;i<fields.length;++i) {
r.add(extract(fields[i]));
}
return r;
}
}
// Components
private static final byte K_VOID = 0;
private static final byte K_ANY = 1;
private static final byte K_META = 2;
private static final byte K_NULL = 3;
private static final byte K_BOOL = 4;
private static final byte K_INT = 5;
private static final byte K_RATIONAL = 6;
private static final byte K_TUPLE = 7;
private static final byte K_SET = 8;
private static final byte K_LIST = 9;
private static final byte K_DICTIONARY = 10;
private static final byte K_PROCESS = 11;
private static final byte K_RECORD = 12;
private static final byte K_UNION = 13;
private static final byte K_FUNCTION = 14;
private static final byte K_EXISTENTIAL = 15;
private static final byte K_LABEL = 16;
/**
* Represents a node in the type graph. Each node has a kind, along with a
* data value identifying any children. For set, list and reference kinds
* the data value is an Integer; for records, it's a Pair<String,Integer>[]
* (sorted by key). For dictionaries, it's a Pair<Integer,Integer> and, for
* unions and functions it's int[] (for functions first element is return).
*
* @author djp
*
*/
private static final class Node {
final byte kind;
final Object data;
public Node(byte kind, Object data) {
this.kind = kind;
this.data = data;
}
public boolean equals(final Object o) {
if(o instanceof Node) {
Node c = (Node) o;
if(kind == c.kind) {
switch(kind) {
case K_VOID:
case K_ANY:
case K_META:
case K_NULL:
case K_BOOL:
case K_INT:
case K_RATIONAL:
return true;
case K_SET:
case K_LIST:
case K_PROCESS:
case K_EXISTENTIAL:
case K_DICTIONARY:
return data.equals(c.data);
case K_TUPLE:
case K_FUNCTION:
case K_UNION:
return Arrays.equals((int[])data, (int[])c.data);
case K_RECORD:
return Arrays.equals((Pair[])data, (Pair[])c.data);
}
}
}
return false;
}
public int hashCode() {
if(data == null) {
return kind;
} else {
return kind + data.hashCode();
}
}
public final static String[] kinds = { "void", "any", "meta", "null", "bool",
"int", "rat", "tuple", "dict", "set", "list", "ref", "record", "union",
"fun", "label" };
public String toString() {
if(data instanceof Pair[]) {
return kinds[kind] + " : " + Arrays.toString((Pair[])data);
} else if(data instanceof int[]) {
return kinds[kind] + " : " + Arrays.toString((int[])data);
} else {
return kinds[kind] + " : " + data;
}
}
}
private static final Node[] nodes(Type t) {
if (t instanceof Leaf) {
return new Node[]{new Node(leafKind((Leaf) t), null)};
} else {
// compound type
return ((Compound)t).nodes;
}
}
private static final byte leafKind(Leaf leaf) {
if(leaf instanceof Void) {
return K_VOID;
} else if(leaf instanceof Any) {
return K_ANY;
} else if(leaf instanceof Null) {
return K_NULL;
} else if(leaf instanceof Bool) {
return K_BOOL;
} else if(leaf instanceof Int) {
return K_INT;
} else if(leaf instanceof Real) {
return K_RATIONAL;
} else if(leaf instanceof Meta) {
return K_META;
} else {
// should be dead code
throw new IllegalArgumentException("Invalid leaf node: " + leaf);
}
}
/**
* This method inserts a blank node at the head of the nodes
* array, whilst remapping all existing nodes appropriately.
*
* @param nodes
* @return
*/
private static Node[] insertComponent(Node[] nodes) {
Node[] newnodes = new Node[nodes.length+1];
int[] rmap = new int[nodes.length];
for(int i=0;i!=nodes.length;++i) {
rmap[i] = i+1;
}
for(int i=0;i!=nodes.length;++i) {
newnodes[i+1] = remap(nodes[i],rmap);
}
return newnodes;
}
/**
* The method inserts the nodes in
* <code>from</from> into those in <code>into</code> at the given index.
* This method remaps nodes in <code>from</code>, but does not remap
* any in <code>into</code>
*
* @param start
* @param from
* @param into
* @return
*/
private static Node[] insertNodes(int start, Node[] from, Node[] into) {
int[] rmap = new int[from.length];
for(int i=0;i!=from.length;++i) {
rmap[i] = i+start;
}
for(int i=0;i!=from.length;++i) {
into[i+start] = remap(from[i],rmap);
}
return into;
}
private static Node remap(Node node, int[] rmap) {
Object data;
switch (node.kind) {
case K_SET:
case K_LIST:
case K_PROCESS:
// unary nodes
int element = (Integer) node.data;
data = rmap[element];
break;
case K_DICTIONARY:
// binary node
Pair<Integer, Integer> p = (Pair<Integer, Integer>) node.data;
data = new Pair(rmap[p.first()], rmap[p.second()]);
break;
case K_TUPLE:
case K_UNION:
case K_FUNCTION:
// nary node
int[] bounds = (int[]) node.data;
int[] nbounds = new int[bounds.length];
for (int i = 0; i != bounds.length; ++i) {
if(bounds[i] == -1) {
nbounds[i] = -1; // possible with K_FUNCTION
} else {
nbounds[i] = rmap[bounds[i]];
}
}
data = nbounds;
break;
case K_RECORD:
// labeled nary node
Pair<String, Integer>[] fields = (Pair<String, Integer>[]) node.data;
Pair<String, Integer>[] nfields = new Pair[fields.length];
for (int i = 0; i != fields.length; ++i) {
Pair<String, Integer> field = fields[i];
nfields[i] = new Pair(field.first(), rmap[field.second()]);
}
data = nfields;
break;
default:
return node;
}
return new Node(node.kind, data);
}
/**
* The construct methods constructs a Type from an array of Components.
* It carefully ensures the kind of the root node matches the class
* created (e.g. a kind K_SET results in a class Set).
*
* @param nodes
* @return
*/
private final static Type construct(Node[] nodes) {
Node root = nodes[0];
switch(root.kind) {
case K_VOID:
return T_VOID;
case K_ANY:
return T_ANY;
case K_META:
return T_META;
case K_NULL:
return T_NULL;
case K_BOOL:
return T_BOOL;
case K_INT:
return T_INT;
case K_RATIONAL:
return T_REAL;
case K_TUPLE:
return new Tuple(nodes);
case K_SET:
return new Set(nodes);
case K_LIST:
return new List(nodes);
case K_EXISTENTIAL:
if(root.data == null) {
throw new RuntimeException("Problem");
}
return new Existential((NameID) root.data);
case K_PROCESS:
return new Process(nodes);
case K_DICTIONARY:
return new Dictionary(nodes);
case K_RECORD:
return new Record(nodes);
case K_UNION:
return new Union(nodes);
case K_FUNCTION:
return new Fun(nodes);
default:
throw new IllegalArgumentException("invalid node kind: " + root.kind);
}
}
public static void main(String[] args) {
PrintBuilder printer = new PrintBuilder(System.out);
Type t1 = fromString("{int x,int y}");
Type t2 = fromString("{int x,any y}");
//Type t1 = T_REAL;
//Type t2 = T_INT;
System.out.println("Type: " + t1 + "\n
build(printer,t1);
System.out.println("\nType: " + t2 + "\n
build(printer,t2);
System.out.println("====================");
System.out.println(isSubtype(t1,t2));
System.out.println(isSubtype(t2,t1));
Type glb = greatestLowerBound(t1,t2);
System.out.println(glb);
Type lub = leastUpperBound(t1,t2);
System.out.println(lub);
}
} |
package com.sksamuel.jqm4gwt.list;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.sksamuel.jqm4gwt.HasInset;
import com.sksamuel.jqm4gwt.JQMPage;
import com.sksamuel.jqm4gwt.JQMWidget;
import com.sksamuel.jqm4gwt.html.ListWidget;
public class JQMList extends JQMWidget implements HasClickHandlers, HasInset, HasFilter {
/**
* The underlying <li>or
* <ul>
* widget
*/
private final ListWidget list;
/**
* The index of the last click
*/
private int clickIndex;
/**
* The collection of items added to this list
*/
private final List<JQMListItem> items = new ArrayList();
/**
* Create a new unordered {@link JQMList}
*/
public JQMList() {
this(false);
}
/**
* Create a new {@link JQMList} that is unordered or ordered depending on
* the given boolean.
*
* @param ordered
* true if you want an ordered list, false otherwise.
*/
public JQMList(boolean ordered) {
String id = Document.get().createUniqueId();
list = new ListWidget(ordered);
initWidget(list);
setId(id);
setStyleName("jqm4gwt-list");
setDataRole("listview");
}
/**
* Registers a new {@link ClickHandler} on this list.
*
* When a click event has been fired, you can get a reference to the
* position that was clicked by getClickIndex() and a reference to the
* item that was clicked with getClickItem()
*/
@Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
return list.addDomHandler(handler, ClickEvent.getType());
}
protected void addDivider(JQMListDivider d) {
list.add(d);
}
/**
* Add a new divider with the given text and an automatically assigned id.
*
* @return the created {@link JQMListDivider} which can be used to change
* the text dynamically. Changes to that instance write back to
* this list.
*/
public JQMListDivider addDivider(String text) {
JQMListDivider d = new JQMListDivider(text);
addDivider(d);
return d;
}
protected void addItem(final JQMListItem item) {
list.add(item);
items.add(item);
item.setList(this);
item.addDomHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
setClickIndex(list.getWidgetIndex(item));
}
}, ClickEvent.getType());
}
/**
* Add a new read only item
*/
public JQMListItem addItem(String text) {
return addItem(text, (String) null);
}
/**
* Adds a new {@link JQMListItem} that contains the given @param text as
* the heading element.
*
* The list item is made linkable to the given page
*
* @param text
* the text to use as the content of the header element
* @param page
* the page to make the list item link to
*/
public JQMListItem addItem(String text, JQMPage page) {
return addItem(text, "#" + page.getId());
}
/**
* Adds a new {@link JQMListItem} that contains the given @param text as
* the content.
*
* The list item is made linkable to the @param url
*/
public JQMListItem addItem(String text, String url) {
JQMListItem item = new JQMListItem(text, url);
addItem(item);
return item;
}
/**
* Add a collection of read only items.
*/
public void addItems(Collection<String> items) {
for (String item : items)
addItem(item);
}
/**
* Remove all items from this list.
*/
public void clear() {
list.clear();
items.clear();
}
/**
* Returns true if this list contains the given item
*
* @param item
* the {@link JQMListItem} to check for
*/
public boolean contains(JQMListItem item) {
return items.contains(item);
}
/**
* Returns the index of the last click. This is useful in event handlers
* when one wants to get a reference to which item was clicked.
*
* @return the index of the last clicked item
*/
public int getClickIndex() {
return clickIndex;
}
/**
* Returns the JQMListItem that was last clicked on. This is useful in
* event handlers when one wants to get a reference to which item was
* clicked.
*
* @return the last clicked item
*/
public JQMListItem getClickItem() {
return items.get(getClickIndex());
}
/**
* Returns the currently set theme for dividers
*
* @return the data divider theme string, eg "b"
*/
public String getDividerTheme() {
return getAttribute("data-dividertheme");
}
public String getFilterPlaceholder() {
return getAttribute("data-filter-placeholder");
}
/**
* Returns the {@link JQMListItem} at the given position
*
* @return
*/
public JQMListItem getItem(int pos) {
return items.get(pos);
}
/**
* Returns a List of {@link JQMListItem}s currently set on this list.
*/
public List<JQMListItem> getItems() {
return items;
}
/**
* Returns the value of the filterable option on this list.
*
* @return true if this list is set to filterable, false otherwise.
*/
@Override
public String isFilterable() {
return getAttribute("data-filter");
}
@Override
public boolean isInset() {
return "true".equals(getElement().getAttribute("inset"));
}
protected void onTap(String id) {
Window.alert("I was tapped!");
}
/**
* Call to refresh the list after a programatic change is made.
*/
public void refresh() {
refresh(getId());
}
protected native void refresh(String id) /*-{
$wnd.$("#" + id).listview('refresh');
}-*/;
/**
* Remove the divider with the given text. This method will search all the
* dividers and remove the first divider found with the given text.
*
*
* @return true if a divider with the given text was found and removed,
* otherwise false.
*/
public boolean removeDivider(String text) {
for (int k = 0; k < list.getWidgetCount(); k++) {
Widget w = list.getWidget(k);
if ("list-divider".equals(w.getElement().getAttribute("data-role"))) {
list.remove(k);
return true;
}
}
return false;
}
/**
* Removes the item at the given position.
*
* @param pos
* the integer position, 0 indexed
*/
public void removeItem(int pos) {
JQMListItem item = items.remove(pos);
list.remove(item);
}
/**
* Removes the given item from the list
*
* @param item
* the item to remove
*/
public void removeItem(JQMListItem item) {
items.remove(item);
list.remove(item);
}
/**
* Removes all the given items. Conveniece method for calling
* removeItem(JQMListItem)multiple times.
*/
public void removeItems(List<JQMListItem> items) {
for (JQMListItem item : items)
removeItem(item);
}
protected void setClickIndex(int clickIndex) {
this.clickIndex = clickIndex;
}
void setClickItem(JQMListItem item) {
setClickIndex(list.getWidgetIndex(item));
}
/**
* Sets the theme attribute for the data dividers
*/
public void setDividerTheme(String theme) {
setAttribute("data-dividertheme", theme);
}
@Override
public void setFilterable(boolean filterable) {
if (filterable)
setAttribute("data-filter", "true");
else
removeAttribute("data-filter");
}
public void setFilterPlaceholder(String placeholderText) {
if (placeholderText == null)
removeAttribute("data-filter-placeholder");
else
setAttribute("data-filter-placeholder", "true");
}
@Override
public void setInset(boolean inset) {
if (inset)
getElement().setAttribute("data-inset", "true");
else
getElement().removeAttribute("data-inset");
}
} |
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import au.com.bytecode.opencsv_voltpatches.CSVReader;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a table
* (or pass it to any stored proc, but ignoring any result other than the success code.).
*
* TODO:
* - Nulls are not handled (or at least I didn't test them).
* - Assumes localhost
* - Assumes no username/password
* - Usage help is ugly and cryptic: options are listed but not described.
* - No associated test suite.
* - Forces JVM into UTC. All input date TZs assumed to be GMT+0
* - Requires canonical JDBC SQL timestamp format
*/
class CSVLoader {
public synchronized static void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
}
private static final AtomicLong inCount = new AtomicLong(0);
private static final AtomicLong outCount = new AtomicLong(0);
private static int reportEveryNRows = 10000;
private static int limitRows = Integer.MAX_VALUE;
private static int skipRows = 0;
private static int auditRows = 0;
private static int waitSeconds = 10;
private static boolean stripQuotes = false;
private static int[] colProjection = null;
private static List<Long> invalidLines = new ArrayList<Long>();
private static final class MyCallback implements ProcedureCallback {
private final long m_lineNum;
MyCallback(long lineNumber)
{
m_lineNum = lineNumber;
}
@Override
public void clientCallback(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
// if (m_lineNum == 0) {
// System.err.print("Line ~" + inCount.get() + "-" + outCount.get() + ":");
// } else {
// System.err.print("Line " + m_lineNum + ":");
System.err.println(response.getStatusString());
System.err.println("<xin>Stop at line " + (inCount.get()));
synchronized (invalidLines) {
if (!invalidLines.contains(m_lineNum))
invalidLines.add(m_lineNum);
}
//System.exit(1);
}
long currentCount = inCount.incrementAndGet();
System.out.println("<xin> put line " + inCount.get() + " to databse");
if (currentCount % reportEveryNRows == 0) {
System.out.println("Inserted " + currentCount + " rows");
}
}
}
/**
* TODO(xin): add line number data into the callback and add the invalid line number
* into a list that will help us to produce a separate file to record the invalid line
* data in the csv file.
*
* Asynchronously invoking procedures to response the actual wrong line number and
* start from last wrong line in the csv file is not easy. You can not ensure the
* FIFO order of the callback.
* @param args
*/
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Two arguments, csv filename and insert procedure name, required");
System.exit(1);
}
final String filename = args[0];
final String insertProcedure = args[1];
int argsUsed = 2;
processCommandLineOptions(argsUsed, args);
int waits = 0;
int shortWaits = 0;
try {
final CSVReader reader = new CSVReader(new FileReader(filename));
//final ProcedureCallback oneCallbackFitsAll = new MyCallback(0);
ProcedureCallback cb = null;
final Client client = ClientFactory.createClient();
client.createConnection("localhost");
boolean lastOK = true;
String line[] = null;
for (int i = 0; i < skipRows; ++i) {
reader.readNext();
// Keep these sync'ed with line numbers.
outCount.incrementAndGet();
inCount.incrementAndGet();
}
while ((limitRows-- > 0) && (line = reader.readNext()) != null) {
long counter = outCount.incrementAndGet();
boolean queued = false;
while (queued == false) {
String[] correctedLine = line;
if (colProjection != null) {
System.out.println(String.format("colProject:%s | correctedLine: %s", colProjection, correctedLine));
correctedLine = projectColumns(colProjection, correctedLine);
}
if (stripQuotes) {
correctedLine = stripMatchingColumnQuotes(correctedLine);
}
if (auditRows > 0) {
--auditRows;
System.err.println(joinIntoString(", ", line));
System.err.println(joinIntoString(", ", correctedLine));
System.err.println("
cb = new MyCallback(counter);
} else {
cb = new MyCallback(outCount.get());
}
String msg = "<xin>params: ";
for (int i=0; i < correctedLine.length; i++) {
msg += correctedLine[i] + ",";
}
System.out.println(msg);
if (!checkLineFormat(correctedLine)){
System.err.println("Stop at line " + (outCount.get()));
}
queued = client.callProcedure(cb, insertProcedure, (Object[])correctedLine);
if (queued == false) {
++waits;
if (lastOK == false) {
++shortWaits;
}
Thread.sleep(waitSeconds);
}
lastOK = queued;
}
}
reader.close();
client.drain();
client.close();
Collections.sort(invalidLines);
System.out.println("All the invalid row numbers are:" + invalidLines);
produceInvalidRowsFile(filename, "/Users/xinjia/invalidrows.csv");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Inserted " + (outCount.get() - skipRows) + " and acknowledged " + (inCount.get() - skipRows) + " rows (final)");
if (waits > 0) {
System.out.println("Waited " + waits + " times");
if (shortWaits > 0) {
System.out.println("Waited too briefly? " + shortWaits + " times");
}
}
}
/**
* Check for each line
* TODO(zheng):
* Use the client handler to get the schema of the table, and then check the number of
* parameters it expects with the input line fragements and each range for each data type.
* And does other pre-checks...(figure out it later)
* @param linefragement
*/
private static boolean checkLineFormat(Object[] linefragement) {
return true;
}
/**
* TODO(xin):
* produce the invalid row file from
* @param inputFile
*/
private static void produceInvalidRowsFile(String inputFile, String outputFile) {
//StringBuilder query = new StringBuilder();
File file = new File(outputFile);
try {
// Create file if it does not exist
boolean success = file.createNewFile();
// Do the file name checking at beginning of the main function
if (success) {
// File did not exist and was created
} else {
// File already exists
}
BufferedReader csvfile = new BufferedReader(new FileReader(inputFile));
String line;
while ((line = csvfile.readLine()) != null) {
}
} catch (FileNotFoundException e) {
System.err.println("CSV file '" + inputFile + "' could not be found.");
} catch(Exception x) {
System.err.println(x.getMessage());
}
}
private static void processCommandLineOptions(int argsUsed, String args[]) {
final String columnsMatch = "--columns";
final String stripMatch = "--stripquotes";
final String waitMatch = "--wait";
final String auditMatch = "--audit";
final String limitMatch = "--limit";
final String skipMatch = "--skip";
final String reportMatch = "--report";
final String columnsStyle = "comma-separated-zero-based-column-numbers";
while (argsUsed < args.length) {
final String optionPrefix = args[argsUsed++];
if (optionPrefix.equalsIgnoreCase(columnsMatch)) {
if (argsUsed < args.length) {
final String colsListed = args[argsUsed++];
final String[] cols = colsListed.split(",");
if (cols != null && cols.length > 0) {
colProjection = new int[cols.length];
for (int i = 0; i < cols.length; i++) {
try {
colProjection[i] = Integer.parseInt(cols[i]);
continue;
} catch (NumberFormatException e) {
}
}
if (colProjection.length == cols.length) {
continue;
}
}
}
} else if (optionPrefix.equalsIgnoreCase(waitMatch)) {
if (argsUsed < args.length) {
try {
waitSeconds = Integer.parseInt(args[argsUsed++]);
if (waitSeconds >= 0) {
continue;
}
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(auditMatch)) {
if (argsUsed < args.length) {
try {
auditRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(limitMatch)) {
if (argsUsed < args.length) {
try {
limitRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(skipMatch)) {
if (argsUsed < args.length) {
try {
skipRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(reportMatch)) {
if (argsUsed < args.length) {
try {
reportEveryNRows = Integer.parseInt(args[argsUsed++]);
if (reportEveryNRows > 0) {
continue;
}
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(stripMatch)) {
stripQuotes = true;
continue;
}
// Fall through means an error.
System.err.println("Option arguments are invalid, expected csv filename and insert procedure name (required) and optionally" +
" '" + columnsMatch + " " + columnsStyle + "'," +
" '" + waitMatch + " s (default=10 seconds)'," +
" '" + auditMatch + " n (default=0 rows)'," +
" '" + limitMatch + " n (default=all rows)'," +
" '" + skipMatch + " n (default=0 rows)'," +
" '" + reportMatch + " n (default=10000)'," +
" and/or '" + stripMatch + " (disabled by default)'");
System.exit(2);
}
}
private static String[] stripMatchingColumnQuotes(String[] line) {
final String[] strippedLine = new String[line.length];
Pattern pattern = Pattern.compile("^([\"'])(.*)\\1$");
for (int i = 0; i < line.length; i++) {
Matcher matcher = pattern.matcher(line[i]);
if (matcher.find()) {
strippedLine[i] = matcher.group(2);
} else {
strippedLine[i] = line[i];
}
}
return strippedLine;
}
private static String[] projectColumns(int[] colSelection, String[] line) {
final String[] projectedLine = new String[colSelection.length];
for (int i = 0; i < projectedLine.length; i++) {
projectedLine[i] = line[colSelection[i]];
}
return projectedLine;
}
// This function borrowed/mutated from http:/stackoverflow.com/questions/1515437
static String joinIntoString(String glue, Object... elements)
{
int k = elements.length;
if (k == 0) {
return null;
}
StringBuilder out = new StringBuilder();
out.append(elements[0].toString());
for (int i = 1; i < k; ++i) {
out.append(glue).append(elements[i]);
}
return out.toString();
}
// This function borrowed/mutated from http:/stackoverflow.com/questions/1515437
static String joinIntoString(String glue, String... elements)
{
int k = elements.length;
if (k == 0) {
return null;
}
StringBuilder out = new StringBuilder();
out.append(elements[0]);
for (int i = 1; i < k; ++i) {
out.append(glue).append(elements[i]);
}
return out.toString();
}
} |
package com.sorcix.sirc;
/**
* Thrown when the server password was wrong.
*/
public final class PasswordException extends Exception {
/** Serial Version ID */
private static final long serialVersionUID = -7856391898471344111L;
/**
* Creates a new PasswordException.
*
* @param string Error string.
*/
public PasswordException(final String string) {
super(string);
}
} |
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import org.voltcore.logging.VoltLogger;
import org.voltdb.CLIConfig;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import au.com.bytecode.opencsv_voltpatches.CSVParser;
import au.com.bytecode.opencsv_voltpatches.CSVReader;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a
* table (or pass it to any stored proc, but ignoring any result other than the
* success code.).
*/
public class CSVLoader {
private static final AtomicLong inCount = new AtomicLong(0);
private static final AtomicLong outCount = new AtomicLong(0);
private static final int reportEveryNRows = 10000;
private static final int waitSeconds = 10;
private static CSVConfig config = null;
private static long latency = 0;
private static long start = 0;
private static boolean standin = false;
public static String pathInvalidrowfile = "";
public static String pathReportfile = "csvloaderReport.log";
public static String pathLogfile = "csvloaderLog.log";
private static BufferedWriter out_invaliderowfile;
private static BufferedWriter out_logfile;
private static BufferedWriter out_reportfile;
private static String insertProcedure = "";
private static Map<Long, String[]> errorInfo = new TreeMap<Long, String[]>();
private static CSVReader csvReader;
private static Client csvClient;
protected static final VoltLogger m_log = new VoltLogger("CONSOLE");
private static final class MyCallback implements ProcedureCallback {
private final long m_lineNum;
private final CSVConfig m_config;
private final String m_rowdata;
MyCallback(long lineNumber, CSVConfig cfg, String rowdata) {
m_lineNum = lineNumber;
m_config = cfg;
m_rowdata = rowdata;
}
@Override
public void clientCallback(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
m_log.error( response.getStatusString() );
synchronized (errorInfo) {
if (!errorInfo.containsKey(m_lineNum)) {
String[] info = { m_rowdata, response.getStatusString() };
errorInfo.put(m_lineNum, info);
}
if (errorInfo.size() >= m_config.maxerrors) {
m_log.error("The number of Failure row data exceeds " + m_config.maxerrors);
produceFiles();
close_cleanup();
System.exit(-1);
}
}
return;
}
long currentCount = inCount.incrementAndGet();
if (currentCount % reportEveryNRows == 0) {
m_log.info( "Inserted " + currentCount + " rows" );
}
}
}
private static class CSVConfig extends CLIConfig {
@Option(shortOpt = "f", desc = "location of CSV input file")
String file = "";
@Option(shortOpt = "p", desc = "procedure name to insert the data into the database")
String procedure = "";
@Option(desc = "maximum rows to be read from the CSV file")
int limitrows = Integer.MAX_VALUE;
@Option(shortOpt = "r", desc = "directory path for report files")
String reportdir = System.getProperty("user.dir");
@Option(shortOpt = "m", desc = "maximum errors allowed")
int maxerrors = 100;
@Option(desc = "delimiter to use for separating entries")
char separator = CSVParser.DEFAULT_SEPARATOR;
@Option(desc = "character to use for quoted elements (default: \")")
char quotechar = CSVParser.DEFAULT_QUOTE_CHARACTER;
@Option(desc = "character to use for escaping a separator or quote (default: \\)")
char escape = CSVParser.DEFAULT_ESCAPE_CHARACTER;
@Option(desc = "require all input values to be enclosed in quotation marks", hasArg = false)
boolean strictquotes = CSVParser.DEFAULT_STRICT_QUOTES;
@Option(desc = "number of lines to skip before inserting rows into the database")
int skip = CSVReader.DEFAULT_SKIP_LINES;
@Option(desc = "do not allow whitespace between values and separators", hasArg = false)
boolean nowhitespace = !CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE;
@Option(shortOpt = "s", desc = "list of servers to connect to (default: localhost)")
String servers = "localhost";
@Option(desc = "username when connecting to the servers")
String user = "";
@Option(desc = "password to use when connecting to servers")
String password = "";
@Option(desc = "port to use when connecting to database (default: 21212)")
int port = Client.VOLTDB_SERVER_PORT;
@AdditionalArgs(desc = "insert the data into database by TABLENAME.insert procedure by default")
String table = "";
@Override
public void validate() {
if (maxerrors < 0)
exitWithMessageAndUsage("abortfailurecount must be >=0");
if (procedure.equals("") && table.equals(""))
exitWithMessageAndUsage("procedure name or a table name required");
if (!procedure.equals("") && !table.equals(""))
exitWithMessageAndUsage("Only a procedure name or a table name required, pass only one please");
if (skip < 0)
exitWithMessageAndUsage("skipline must be >= 0");
if (limitrows > Integer.MAX_VALUE)
exitWithMessageAndUsage("limitrows to read must be < "
+ Integer.MAX_VALUE);
if (port < 0)
exitWithMessageAndUsage("port number must be >= 0");
}
@Override
public void printUsage() {
System.out
.println("Usage: csvloader [args] tablename");
System.out
.println(" csvloader [args] -p procedurename");
super.printUsage();
}
}
public static void main(String[] args) throws IOException,
InterruptedException {
start = System.currentTimeMillis();
int waits = 0;
int shortWaits = 0;
CSVConfig cfg = new CSVConfig();
cfg.parse(CSVLoader.class.getName(), args);
config = cfg;
configuration();
try {
if (CSVLoader.standin)
csvReader = new CSVReader(new BufferedReader(
new InputStreamReader(System.in)), config.separator,
config.quotechar, config.escape, config.skip,
config.strictquotes, config.nowhitespace);
else
csvReader = new CSVReader(new FileReader(config.file),
config.separator, config.quotechar, config.escape,
config.skip, config.strictquotes, config.nowhitespace);
} catch (FileNotFoundException e) {
m_log.error("CSV file '" + config.file + "' could not be found.");
System.exit(-1);
}
// Split server list
String[] serverlist = config.servers.split(",");
// Create connection
ClientConfig c_config = new ClientConfig(config.user, config.password);
c_config.setProcedureCallTimeout(0); // Set procedure all to infinite
// timeout, see ENG-2670
try {
csvClient = CSVLoader.getClient(c_config, serverlist, config.port);
} catch (Exception e) {
m_log.error("Error to connect to the servers:"
+ config.servers);
close_cleanup();
System.exit(-1);
}
try {
ProcedureCallback cb = null;
boolean lastOK = true;
String line[] = null;
int columnCnt = 0;
VoltTable procInfo = null;
boolean isProcExist = false;
try {
procInfo = csvClient.callProcedure("@SystemCatalog",
"PROCEDURECOLUMNS").getResults()[0];
while (procInfo.advanceRow()) {
if (insertProcedure.matches((String) procInfo.get(
"PROCEDURE_NAME", VoltType.STRING))) {
columnCnt++;
isProcExist = true;
}
}
} catch (Exception e) {
m_log.error(e.getMessage(), e);
close_cleanup();
System.exit(-1);
}
if (isProcExist == false) {
m_log.error("No matching insert procedure available");
close_cleanup();
System.exit(-1);
}
while ((config.limitrows
&& (line = csvReader.readNext()) != null) {
outCount.incrementAndGet();
boolean queued = false;
while (queued == false) {
StringBuilder linedata = new StringBuilder();
for (int i = 0; i < line.length; i++) {
linedata.append("\"" + line[i] + "\"");
if (i != line.length - 1)
linedata.append(",");
}
String[] correctedLine = line;
cb = new MyCallback(outCount.get(), config,
linedata.toString());
String lineCheckResult;
if ((lineCheckResult = checkparams_trimspace(correctedLine,
columnCnt)) != null) {
synchronized (errorInfo) {
if (!errorInfo.containsKey(outCount.get())) {
String[] info = { linedata.toString(),
lineCheckResult };
errorInfo.put(outCount.get(), info);
}
if (errorInfo.size() >= config.maxerrors) {
m_log.error("The number of Failure row data exceeds "
+ config.maxerrors);
produceFiles();
close_cleanup();
System.exit(-1);
}
}
break;
}
queued = csvClient.callProcedure(cb, insertProcedure,
(Object[]) correctedLine);
if (queued == false) {
++waits;
if (lastOK == false) {
++shortWaits;
}
Thread.sleep(waitSeconds);
}
lastOK = queued;
}
}
csvClient.drain();
} catch (Exception e) {
e.printStackTrace();
}
m_log.info("Inserted " + outCount.get() + " and acknowledged "
+ inCount.get() + " rows (final)");
if (waits > 0) {
m_log.info("Waited " + waits + " times");
if (shortWaits > 0) {
m_log.info( "Waited too briefly? " + shortWaits
+ " times" );
}
}
produceFiles();
close_cleanup();
csvClient.close();
}
private static String checkparams_trimspace(String[] slot,
int columnCnt) {
if (slot.length == 1 && slot[0].equals("")) {
return "Error: blank line";
}
if (slot.length != columnCnt) {
return "Error: Incorrect number of columns. " + slot.length
+ " found, " + columnCnt + " expected.";
}
for (int i = 0; i < slot.length; i++) {
// trim white space in this line.
slot[i] = slot[i].trim();
// treat NULL, \N and "\N" as actual null value
if ((slot[i]).equals("NULL") || slot[i].equals("\\N")
|| !config.strictquotes && slot[i].equals("\"\\N\""))
slot[i] = null;
}
return null;
}
private static void configuration() {
if (config.file.equals(""))
standin = true;
if (!config.table.equals("")) {
insertProcedure = config.table.toUpperCase() + ".insert";
} else {
insertProcedure = config.procedure;
}
if (!config.reportdir.endsWith("/"))
config.reportdir += "/";
try {
File dir = new File(config.reportdir);
if (!dir.exists()) {
dir.mkdirs();
}
} catch (Exception x) {
m_log.error(x.getMessage(), x);
System.exit(-1);
}
String myinsert = insertProcedure;
myinsert = myinsert.replaceAll("\\.", "_");
pathInvalidrowfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "invalidrows.csv";
pathLogfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "log.log";
pathReportfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "report.log";
try {
out_invaliderowfile = new BufferedWriter(new FileWriter(
pathInvalidrowfile));
out_logfile = new BufferedWriter(new FileWriter(pathLogfile));
out_reportfile = new BufferedWriter(new FileWriter(pathReportfile));
} catch (IOException e) {
m_log.error(e.getMessage());
System.exit(-1);
}
}
private static Client getClient(ClientConfig config, String[] servers,
int port) throws Exception {
final Client client = ClientFactory.createClient(config);
for (String server : servers)
client.createConnection(server.trim(), port);
return client;
}
private static void produceFiles() {
latency = System.currentTimeMillis() - start;
m_log.info("CSVLoader elaspsed: " + latency / 1000F
+ " seconds");
int bulkflush = 300; // by default right now
try {
long linect = 0;
for (Long irow : errorInfo.keySet()) {
String info[] = errorInfo.get(irow);
if (info.length != 2)
System.out
.println("internal error, infomation is not enough");
linect++;
out_invaliderowfile.write(info[0] + "\n");
String message = "Invalid input on line " + irow + ".\n Contents:" + info[0];
m_log.error(message);
out_logfile.write(message + "\n " + info[1] + "\n");
if (linect % bulkflush == 0) {
out_invaliderowfile.flush();
out_logfile.flush();
}
}
// Get elapsed time in seconds
float elapsedTimeSec = latency / 1000F;
out_reportfile.write("csvloader elaspsed: " + elapsedTimeSec
+ " seconds\n");
out_reportfile.write("Number of rows read from input: "
+ outCount.get() + "\n");
out_reportfile.write("Number of rows successfully inserted: "
+ inCount.get() + "\n");
// if prompted msg changed, change it also for test case
out_reportfile.write("Number of rows that could not be inserted: "
+ errorInfo.size() + "\n");
out_reportfile.write("CSVLoader rate: " + outCount.get()
/ elapsedTimeSec + " row/s\n");
m_log.info("invalid row file is generated to:" + pathInvalidrowfile);
m_log.info("log file is generated to:" + pathLogfile);
m_log.info("report file is generated to:" + pathReportfile);
out_invaliderowfile.flush();
out_logfile.flush();
out_reportfile.flush();
} catch (FileNotFoundException e) {
m_log.error("CSV report directory '" + config.reportdir
+ "' does not exist.");
} catch (Exception x) {
m_log.error(x.getMessage());
}
}
private static void close_cleanup() throws IOException,
InterruptedException {
inCount.set(0);
outCount.set(0);
errorInfo.clear();
csvReader.close();
out_invaliderowfile.close();
out_logfile.close();
out_reportfile.close();
}
} |
package com.wangc.test_plan.jmeter;
import com.wangc.comm.Param;
import com.wangc.comm.StringUtils;
import com.wangc.test_plan.bean.RunPlanBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
public class RunJmx {
private static String FORMAT_1 = "ddHHmmssSSS";
private static String JMETER_COMMOND = "jmeter -n -t ${jmx} -l ${jtl} -j ${log} -e -o ${html}";
private static String[] JMETER_RUN_COMMOND = new String[]{"","",""};
private static String LINUX_COMMOND = "/bin/sh";
private static String LINUX_COMMOND_PARAM = "-C";
private static String WIN_COMMOND = "cmd";
private static String WIN_COMMOND_PARAM = "/c";
private static String os = System.getProperty("os.name");
private static final Logger logger = LoggerFactory.getLogger(RunJmx.class);
public static void run(RunPlanBean rpb) {
String jmxPath = Param.USER_DIR +rpb.getTestPlanBean().getJmxSavePath();
// TODO: wangc@2017/6/6 jtlloghtmluuid
String jtlPath = new StringBuilder("")
.append(StringUtils.creAndGetDir(Param.USER_DIR + Param.JTL_PATH))
.append(File.separator)
.append(System.currentTimeMillis())
.append(Param.SEPARATOR_MY)
.append(StringUtils.getDate(FORMAT_1))
.append(Param.JTL_SUFFIX).toString();
String logPath = new StringBuilder("")
.append(StringUtils.creAndGetDir(Param.USER_DIR + Param.LOG_PATH))
.append(File.separator)
.append(System.currentTimeMillis())
.append(Param.SEPARATOR_MY)
.append(StringUtils.getDate(FORMAT_1))
.append(Param.LOG_SUFFIX)
.toString();
System.out.println("======"+System.currentTimeMillis());
String htmlPath = new StringBuilder("")
.append(StringUtils.creAndGetDir(Param.USER_DIR + Param.HTML_PATH))
.append(File.separator)
.append(System.currentTimeMillis())
.append(Param.SEPARATOR_MY)
.append(StringUtils.getDate(FORMAT_1))
.toString();
rpb.setJtlPath(jtlPath);
rpb.setLogPath(logPath);
rpb.setHtmlPath(htmlPath+File.separator+"index.html");
String myCmd = JMETER_COMMOND.replace("${jmx}", jmxPath)
.replace("${jtl}", Param.USER_DIR + Param.JTL_PATH+jtlPath)
.replace("${log}", Param.USER_DIR + Param.LOG_PATH+logPath)
.replace("${html}", Param.USER_DIR + Param.HTML_PATH+htmlPath);
Runtime runtime = Runtime.getRuntime();
try {
// TODO: wangc@2017/3/14 exec
if( os.contains("Linux") ){ //linux todo
runtime.exec(getCommandStrLinux(myCmd));
}else if(os.contains("Windows")){
runtime.exec(getCommandStrWin(myCmd));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error!");
}
}
private static String getCommandStrLinux(String myCmd){
myCmd = System.getenv("JMETER_HOME")+File.separator+"bin"+File.separator+myCmd;
logger.info(myCmd );
return myCmd;
}
private static String[] getCommandStrWin(String myCmd) {
JMETER_RUN_COMMOND[0] = WIN_COMMOND;
JMETER_RUN_COMMOND[1] = WIN_COMMOND_PARAM;
JMETER_RUN_COMMOND[2] = myCmd;
logger.info(Arrays.toString(JMETER_RUN_COMMOND) );
return JMETER_RUN_COMMOND;
}
private static String getName(String jmxPath) {
File file = new File(jmxPath);
return file.getName().split("\\.")[0];
}
public static void main(String[] args){
System.out.println( System.getenv("JAVA_HOME") );
System.out.println( System.getenv("JMETER_HOME") );
System.out.println( System.getenv("PATH") );
/*Map<String, String> map = System.getenv();
for(Iterator<String> itr = map.keySet().iterator();itr.hasNext();){
String key = itr.next();
System.out.println(key + "=" + map.get(key));
}*/
if(true){
return ;
}
//[cmd, /c,
String a = "cmd.exe /c jmeter -n -t D:\\workspace_HelloWorld\\testing_platform\\jmeter\\jmx\\2017\\08\\tp_20170817173811my0.jmx -l D:\\workspace_HelloWorld\\testing_platform\\jmeter\\jtl\\2017\\08\\1502962711107_17173831107.jtl -j D:\\workspace_HelloWorld\\testing_platform\\jmeter\\log\\2017\\08\\1502962711107_17173831107.log -e -o D:\\workspace_HelloWorld\\testing_platform\\jmeter\\html\\2017\\08\\1502962711108_17173831108";
a = "/usr/local/apache-jmeter-3.2/bin/jmeter -n -t /home/wangchao/testing_platform/jmeter/jmx/2017/08/tp_20170823121605my0.jmx -l /home/wangchao/testing_platform/jmeter/jtl/2017/08/1503467216724_23134656724.jtl -j /home/wangchao/testing_platform/jmeter/log/2017/08/1503467216724_23134656724.log ";
String[] aa = new String[]{"/bin/sh","-c",a};
Runtime runtime = Runtime.getRuntime();
try {
// TODO: wangc@2017/3/14 exec
runtime.exec(a);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error!");
}
}
} |
package de.slikey.effectlib;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import de.slikey.effectlib.util.ParticleEffect;
import org.apache.commons.lang.StringUtils;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import de.slikey.effectlib.util.Disposable;
import org.bukkit.util.Vector;
/**
* Dispose the EffectManager if you don't need him anymore.
*
* @author Kevin
*
*/
public final class EffectManager implements Disposable {
private final Plugin owningPlugin;
private final Map<Effect, BukkitTask> effects;
private static List<EffectManager> effectManagers;
private boolean disposed;
private boolean disposeOnTermination;
private boolean debug = false;
public static void initialize() {
effectManagers = new ArrayList<EffectManager>();
}
public static List<EffectManager> getManagers() {
if (effectManagers == null) {
initialize();
}
return effectManagers;
}
public static void disposeAll() {
if (effectManagers != null) {
for (Iterator<EffectManager> i = effectManagers.iterator(); i.hasNext(); ) {
EffectManager em = i.next();
i.remove();
em.dispose();
}
}
}
public EffectManager(Plugin owningPlugin) {
this.owningPlugin = owningPlugin;
effects = new HashMap<Effect, BukkitTask>();
disposed = false;
disposeOnTermination = false;
}
public void start(Effect effect) {
if (disposed)
throw new IllegalStateException("EffectManager is disposed and not able to accept any effects.");
if (disposeOnTermination)
throw new IllegalStateException("EffectManager is awaiting termination to dispose and not able to accept any effects.");
if (effects.containsKey(effect)) {
effect.cancel(false);
}
BukkitScheduler s = Bukkit.getScheduler();
BukkitTask task = null;
switch (effect.type) {
case INSTANT:
task = s.runTask(owningPlugin, effect);
break;
case DELAYED:
task = s.runTaskLater(owningPlugin, effect, effect.delay);
break;
case REPEATING:
task = s.runTaskTimer(owningPlugin, effect, effect.delay, effect.period);
break;
}
synchronized (this) {
effects.put(effect, task);
}
}
public Effect start(String effectClass, ConfigurationSection parameters, Location origin, Location target, Entity originEntity, Entity targetEntity, Map<String, String> textMap) {
Class<? extends Effect> effectLibClass;
try {
// A shaded manager may provide a fully-qualified path.
if (!effectClass.contains(".")) {
effectClass = "de.slikey.effectlib.effect." + effectClass;
}
effectLibClass = (Class<? extends Effect>)Class.forName(effectClass);
} catch (Throwable ex) {
owningPlugin.getLogger().info("Error loading EffectLib class: " + effectClass + ": " + ex.getMessage());
return null;
}
Effect effect = null;
try {
Constructor constructor = effectLibClass.getConstructor(EffectManager.class);
effect = (Effect) constructor.newInstance(this);
} catch (Exception ex) {
owningPlugin.getLogger().warning("Error creating Effect class: " + effectClass);
}
if (effect == null) {
return null;
}
Collection<String> keys = parameters.getKeys(false);
for (String key : keys) {
if (key.equals("class")) continue;
if (!setField(effect, key, parameters, textMap)) {
owningPlugin.getLogger().warning("Unable to assign EffectLib property " + key + " of class " + effectLibClass.getName());
}
}
effect.setLocation(origin);
effect.setTarget(target);
effect.setTargetEntity(targetEntity);
effect.setEntity(originEntity);
effect.start();
return effect;
}
protected boolean setField(Object effect, String key, ConfigurationSection section, Map<String, String> textMap) {
try {
Field field = effect.getClass().getField(key);
if (field.getType().equals(Integer.TYPE)) {
field.set(effect, section.getInt(key));
} else if (field.getType().equals(Float.TYPE)) {
field.set(effect, (float)section.getDouble(key));
} else if (field.getType().equals(Double.TYPE)) {
field.set(effect, section.getDouble(key));
} else if (field.getType().equals(Boolean.TYPE)) {
field.set(effect, section.getBoolean(key));
} else if (field.getType().equals(Long.TYPE)) {
field.set(effect, section.getLong(key));
} else if (field.getType().isAssignableFrom(String.class)) {
String value = section.getString(key);
if (textMap != null) {
for (Map.Entry<String, String> replaceEntry : textMap.entrySet()) {
value = value.replace(replaceEntry.getKey(), replaceEntry.getValue());
}
}
field.set(effect, value);
} else if (field.getType().isAssignableFrom(ParticleEffect.class)) {
String typeName = section.getString(key);
ParticleEffect particleType = ParticleEffect.valueOf(typeName.toUpperCase());
field.set(effect, particleType);
} else if (field.getType().equals(Sound.class)) {
String soundName = section.getString(key);
try {
Sound sound = Sound.valueOf(soundName.toUpperCase());
field.set(effect, sound);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (field.getType().equals(Color.class)) {
String hexColor = section.getString(key);
try {
Integer rgb = Integer.parseInt(hexColor, 16);
Color color = Color.fromRGB(rgb);
field.set(effect, color);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (field.getType().equals(Vector.class)) {
double x = 0;
double y = 0;
double z = 0;
try {
String[] pieces = StringUtils.split(section.getString(key), ',');
x = pieces.length > 0 ? Double.parseDouble(pieces[0]) : 0;
y = pieces.length > 1 ? Double.parseDouble(pieces[1]) : 0;
z = pieces.length > 2 ? Double.parseDouble(pieces[2]) : 0;
} catch (Exception ex) {
ex.printStackTrace();
}
field.set(effect, new Vector(x, y, z));
} else {
return false;
}
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public void cancel(boolean callback) {
for (Map.Entry<Effect, BukkitTask> entry : effects.entrySet())
entry.getKey().cancel(callback);
}
public void done(Effect effect) {
synchronized (this) {
BukkitTask existingTask = effects.get(effect);
if (existingTask != null) {
existingTask.cancel();
}
effects.remove(effect);
}
if (effect.callback != null)
Bukkit.getScheduler().runTask(owningPlugin, effect.callback);
if (disposeOnTermination && effects.size() == 0)
dispose();
}
public void dispose() {
if (disposed)
return;
disposed = true;
cancel(false);
if (effectManagers != null) {
effectManagers.remove(this);
}
}
public void disposeOnTermination() {
disposeOnTermination = true;
if (effects.size() == 0)
dispose();
}
public void enableDebug(boolean enable) {
debug = enable;
}
public void onError(Throwable ex) {
if (debug) {
owningPlugin.getLogger().log(Level.WARNING, "Particle Effect error", ex);
}
}
} |
/**
*
* Sample.java
* @author echeng (table2type.pl)
*
* the Sample object
*
*
*/
package edu.yu.einstein.wasp.model;
import org.hibernate.*;
import org.hibernate.envers.Audited;
import org.hibernate.envers.NotAudited;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.*;
@Entity
@Audited
@Table(name="sample")
public class Sample extends WaspModel {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
protected int sampleId;
public void setSampleId (int sampleId) {
this.sampleId = sampleId;
}
public int getSampleId () {
return this.sampleId;
}
@Column(name="typesampleid")
protected int typeSampleId;
public void setTypeSampleId (int typeSampleId) {
this.typeSampleId = typeSampleId;
}
public int getTypeSampleId () {
return this.typeSampleId;
}
@Column(name="submitter_labid")
protected int submitterLabId;
public void setSubmitterLabId (int submitterLabId) {
this.submitterLabId = submitterLabId;
}
public int getSubmitterLabId () {
return this.submitterLabId;
}
@Column(name="submitter_userid")
protected int submitterUserId;
public void setSubmitterUserId (int submitterUserId) {
this.submitterUserId = submitterUserId;
}
public int getSubmitterUserId () {
return this.submitterUserId;
}
@Column(name="submitter_jobid")
protected Integer submitterJobId;
public void setSubmitterJobId (Integer submitterJobId) {
this.submitterJobId = submitterJobId;
}
public Integer getSubmitterJobId () {
return this.submitterJobId;
}
@Column(name="isreceived")
protected int isReceived;
public void setIsReceived (int isReceived) {
this.isReceived = isReceived;
}
public int getIsReceived () {
return this.isReceived;
}
@Column(name="receiver_userid")
protected Integer receiverUserId;
public void setReceiverUserId (Integer receiverUserId) {
this.receiverUserId = receiverUserId;
}
public Integer getReceiverUserId () {
return this.receiverUserId;
}
@Column(name="receivedts")
protected Date receiveDts;
public void setReceiveDts (Date receiveDts) {
this.receiveDts = receiveDts;
}
public Date getReceiveDts () {
return this.receiveDts;
}
@Column(name="name")
@NotEmpty
protected String name;
public void setName (String name) {
this.name = name;
}
public String getName () {
return this.name;
}
@Column(name="isgood")
protected Integer isGood;
public void setIsGood (Integer isGood) {
this.isGood = isGood;
}
public Integer getIsGood () {
return this.isGood;
}
@Column(name="isactive")
protected int isActive;
public void setIsActive (int isActive) {
this.isActive = isActive;
}
public int getIsActive () {
return this.isActive;
}
@Column(name="lastupdts")
protected Date lastUpdTs;
public void setLastUpdTs (Date lastUpdTs) {
this.lastUpdTs = lastUpdTs;
}
public Date getLastUpdTs () {
return this.lastUpdTs;
}
@Column(name="lastupduser")
protected int lastUpdUser;
public void setLastUpdUser (int lastUpdUser) {
this.lastUpdUser = lastUpdUser;
}
public int getLastUpdUser () {
return this.lastUpdUser;
}
@NotAudited
@ManyToOne
@JoinColumn(name="typesampleid", insertable=false, updatable=false)
protected TypeSample typeSample;
public void setTypeSample (TypeSample typeSample) {
this.typeSample = typeSample;
this.typeSampleId = typeSample.typeSampleId;
}
public TypeSample getTypeSample () {
return this.typeSample;
}
@NotAudited
@ManyToOne
@JoinColumn(name="submitter_jobid", insertable=false, updatable=false)
protected Job job;
public void setJob (Job job) {
this.job = job;
this.submitterJobId = job.jobId;
}
public Job getJob () {
return this.job;
}
@NotAudited
@ManyToOne
@JoinColumn(name="submitter_labid", insertable=false, updatable=false)
protected Lab lab;
public void setLab (Lab lab) {
this.lab = lab;
this.submitterLabId = lab.labId;
}
public Lab getLab () {
return this.lab;
}
@NotAudited
@ManyToOne
@JoinColumn(name="submitter_userid", insertable=false, updatable=false)
protected User user;
public void setUser (User user) {
this.user = user;
this.submitterUserId = user.UserId;
}
public User getUser () {
return this.user;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<SampleMeta> sampleMeta;
public List<SampleMeta> getSampleMeta() {
return this.sampleMeta;
}
public void setSampleMeta (List<SampleMeta> sampleMeta) {
this.sampleMeta = sampleMeta;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<SampleSource> sampleSource;
public List<SampleSource> getSampleSource() {
return this.sampleSource;
}
public void setSampleSource (List<SampleSource> sampleSource) {
this.sampleSource = sampleSource;
}
@NotAudited
@OneToMany
@JoinColumn(name="source_sampleid", insertable=false, updatable=false)
protected List<SampleSource> sampleSourceViaSourceSampleId;
public List<SampleSource> getSampleSourceViaSourceSampleId() {
return this.sampleSourceViaSourceSampleId;
}
public void setSampleSourceViaSourceSampleId (List<SampleSource> sampleSource) {
this.sampleSourceViaSourceSampleId = sampleSource;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<SampleBarcode> sampleBarcode;
public List<SampleBarcode> getSampleBarcode() {
return this.sampleBarcode;
}
public void setSampleBarcode (List<SampleBarcode> sampleBarcode) {
this.sampleBarcode = sampleBarcode;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<SampleLab> sampleLab;
public List<SampleLab> getSampleLab() {
return this.sampleLab;
}
public void setSampleLab (List<SampleLab> sampleLab) {
this.sampleLab = sampleLab;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<JobSample> jobSample;
public List<JobSample> getJobSample() {
return this.jobSample;
}
public void setJobSample (List<JobSample> jobSample) {
this.jobSample = jobSample;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<SampleFile> sampleFile;
public List<SampleFile> getSampleFile() {
return this.sampleFile;
}
public void setSampleFile (List<SampleFile> sampleFile) {
this.sampleFile = sampleFile;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<Run> run;
public List<Run> getRun() {
return this.run;
}
public void setRun (List<Run> run) {
this.run = run;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<RunLane> runLane;
public List<RunLane> getRunLane() {
return this.runLane;
}
public void setRunLane (List<RunLane> runLane) {
this.runLane = runLane;
}
@NotAudited
@OneToMany
@JoinColumn(name="sampleid", insertable=false, updatable=false)
protected List<Statesample> statesample;
public List<Statesample> getStatesample() {
return this.statesample;
}
public void setStatesample (List<Statesample> statesample) {
this.statesample = statesample;
}
} |
package eu.fbk.mpba.sensorflow;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
public class SensorFlow {
// Fields
private final String sessionTag;
private volatile boolean closed = false;
private final Map<String, InputManager> userInputs = new TreeMap<>();
private final Map<Output, OutputManager> userOutputs = new HashMap<>();
// Status Interfaces
private final InputObserver input = new InputObserver() {
@Override
public void inputStatusChanged(InputManager sender, PluginStatus state) {
// onStatusChanged
}
};
private final OutputObserver output = new OutputObserver() {
@Override
public void outputStatusChanged(OutputManager sender, PluginStatus state) {
// onStatusChanged
}
};
// Data and Events Interface, will be re-added for profiling
// Engine implementation
public SensorFlow() {
this(new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date()));
}
public SensorFlow(String sessionTag) {
this.sessionTag = sessionTag;
}
public String getSessionTag() {
return sessionTag;
}
// Plugins
private SensorFlow add(InputGroup p, boolean routedEverywhere) {
InputManager added = null;
// Check if only the name is already contained
synchronized (userInputs) {
if (!userInputs.containsKey(p.getName())) {
added = new InputManager(p, this.input);
userInputs.put(p.getName(), added);
}
}
if (added != null) {
// InputGroups are not recursive, just one level
// p.setManager(this.flow);
added.onCreate();
if (routedEverywhere)
routeAll(added);
added.onAdded();
}
return this;
}
public SensorFlow add(InputGroup p) {
return add(p, true);
}
public SensorFlow add(Collection<InputGroup> p) {
for (InputGroup inputGroup : p)
add(inputGroup);
return this;
}
public SensorFlow addNotRouted(InputGroup p) {
return add(p, false);
}
public SensorFlow addNotRouted(Collection<InputGroup> p) {
for (InputGroup p1 : p)
addNotRouted(p1);
return this;
}
private void add(Output p, boolean threaded, boolean routeEverywhere) {
OutputManager added = null;
// Check if only the name is already contained
synchronized (userOutputs) {
if (!userOutputs.containsKey(p)) {
userOutputs.put(p, added = new OutputManager(p, this.output, threaded));
}
}
if (added != null) {
// Reversed the following two statements:
// Before: onCreate call precedes all data
// Now: some data after onCreate call may be lost.
// It is ok as the important rule is that onAdded call precedes all data.
added.onCreateAndAdded(sessionTag);
if (routeEverywhere)
routeAll(added);
}
}
public SensorFlow add(Output p) {
add(p, true, true);
return this;
}
public SensorFlow addNotRouted(Output p) {
add(p, true, false);
return this;
}
public SensorFlow addInThread(Output p) {
add(p, false, true);
return this;
}
public SensorFlow addInThreadNotRouted(Output p) {
add(p, false, false);
return this;
}
public SensorFlow remove(InputGroup p) {
InputManager removed = null;
// Check if only the name is already contained
synchronized (userInputs) {
if (userInputs.containsKey(p.getName())) {
removed = userInputs.remove(p.getName());
}
}
if (removed != null) {
// InputGroups are not recursive, just one level
for (Input s : p.getChildren()) {
ArrayList<OutputManager> outputs = new ArrayList<>(s.getOutputs());
for (OutputManager o : outputs)
removeRoute(s, o);
}
removed.onRemovedAndClose();
// p.setManager(null);
}
return this;
}
public SensorFlow remove(Output p) {
OutputManager removed = null;
// Check if only the name is already contained
synchronized (userOutputs) {
if (userOutputs.containsKey(p))
removed = userOutputs.remove(p);
}
if (removed != null) {
final OutputManager o = removed;
ArrayList<Input> inputs = new ArrayList<>(o.getInputs());
for (Input i : inputs)
removeRoute(i, o);
o.onStopAndClose();
}
return this;
}
public SensorFlow addRoute(Input from, Output to) {
if (from != null && to != null) {
OutputManager outMan;
synchronized (userOutputs) {
outMan = userOutputs.get(to);
}
addRoute(from, outMan);
}
return this;
}
public SensorFlow removeRoute(Input from, Output to) {
if (from != null && to != null) {
OutputManager outMan;
synchronized (userOutputs) {
outMan = userOutputs.get(to);
}
removeRoute(from, outMan);
}
return this;
}
public boolean isRouted(Input from, Output to) {
if (from != null && to != null) {
OutputManager outMan;
synchronized (userOutputs) {
outMan = userOutputs.get(to);
}
return isRouted(from, outMan);
}
return false;
}
private void addRoute(Input from, OutputManager outMan) {
outMan.addInput(from);
from.addOutput(outMan);
}
private void removeRoute(Input fromSensor, OutputManager outMan) {
fromSensor.removeOutput(outMan);
outMan.removeInput(fromSensor);
}
// Concurrently unsafe
private boolean isRouted(Input fromSensor, OutputManager outMan) {
return fromSensor.getOutputs().contains(outMan) && outMan.getInputs().contains(fromSensor);
}
public SensorFlow enableOutput(Output o) {
return setOutputEnabled(true, o);
}
public SensorFlow disableOutput(Output o) {
return setOutputEnabled(false, o);
}
private SensorFlow setOutputEnabled(boolean enabled, Output o) {
synchronized (userOutputs) {
if (userOutputs.containsKey(o)) {
(userOutputs.get(o)).setEnabled(enabled);
} else
throw new IllegalArgumentException("Output not added.");
}
return this;
}
// Gets
public boolean isOutputEnabled(Output o) {
boolean b;
synchronized (userOutputs) {
b = userOutputs.containsKey(o) && (userOutputs.get(o)).isEnabled();
}
return b;
}
public InputGroup getInput(String name) {
InputManager r;
synchronized (userInputs) {
r = userInputs.get(name);
}
return r == null ? null : r.getInputGroup();
}
// public Output getOutput(String name) {
// Object r;
// synchronized (userInputs) {
// r = userOutputs.get(name);
// return r == null ? null : ((OutputManager)r).getOutput();
public Collection<InputGroup> getInputs() {
ArrayList<InputGroup> x;
synchronized (userInputs) {
x = new ArrayList<>(userInputs.size());
for (InputManager o : userInputs.values())
x.add(o.getInputGroup());
}
return Collections.unmodifiableCollection(x);
}
public Collection<Output> getOutputs() {
ArrayList<Output> x;
synchronized (userOutputs) {
x = new ArrayList<>(userOutputs.size());
for (OutputManager o : userOutputs.values())
x.add(o.getOutput());
}
return Collections.unmodifiableCollection(x);
}
// Engine operation
// Does not create duplicates
public SensorFlow routeClear() {
// REMOVE ALL
for (InputManager d : userInputs.values())
for (Input s : d.getInputs()) // FOREACH SENSOR
for (OutputManager o : userOutputs.values()) // Remove LINK TO EACH OUTPUT
removeRoute(s, o);
return this;
}
// Does not create duplicates
public SensorFlow routeAll() {
// SENSORS x OUTPUTS
for (InputManager d : userInputs.values())
routeAll(d);
return this;
}
private SensorFlow routeAll(InputManager d) {
for (Input s : d.getInputs()) // FOREACH SENSOR
for (OutputManager o : userOutputs.values()) // LINK TO EACH OUTPUT
addRoute(s, o);
return this;
}
private SensorFlow routeAll(OutputManager o) {
// SENSORS x OUTPUTS
for (InputManager d : userInputs.values())
for (Input s : d.getInputs()) // FOREACH SENSOR
addRoute(s, o);
return this;
}
// // Does not create duplicates
// public SensorFlow routeNthToNth() {
// // max SENSORS, OUTPUTS
// int maxi = Math.max(userInputs.size(), userOutputs.size());
// for (int i = 0; i < maxi; i++) // FOREACH OF THE LONGEST
// for (Input s : new ArrayList<>(userInputs.values()).get(i % userInputs.size()).getInputs()) // LINK MODULE LOOPING ON THE SHORTEST
// addRoute(s, new ArrayList<>(userOutputs.values()).get(i % userOutputs.size()));
// return this;
// private void changeStatus(Status status) {
// this.closed = status;
// public Status getStatus() {
// return closed;
public synchronized void close() {
if (!closed) {
for (InputManager d : userInputs.values()) {
// for (Input s : d.getInputGroup().getChildren()) {
// s.onRemoved();
// s.onClose();
d.getInputGroup().onRemoved();
d.getInputGroup().onClose();
}
routeClear();
for (OutputManager o : userOutputs.values())
o.onStopAndClose();
closed = true;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
} |
package falgout.jrepl.command;
import static com.google.common.reflect.Types2.addArraysToType;
import static falgout.jrepl.antlr4.ParseTreeUtils.getChildIndex;
import static falgout.jrepl.antlr4.ParseTreeUtils.getChildren;
import static falgout.jrepl.reflection.Types.getType;
import static falgout.jrepl.reflection.Types.isFinal;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DefaultErrorStrategy;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.xpath.XPath;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.reflect.TypeToken;
import falgout.jrepl.Environment;
import falgout.jrepl.Import;
import falgout.jrepl.Variable;
import falgout.jrepl.antlr4.WriterErrorListener;
import falgout.jrepl.parser.JavaLexer;
import falgout.jrepl.parser.JavaParser;
import falgout.jrepl.parser.JavaParser.ImportDeclarationContext;
import falgout.jrepl.parser.JavaParser.LocalVariableDeclarationContext;
import falgout.jrepl.parser.JavaParser.VariableDeclaratorContext;
import falgout.jrepl.parser.JavaParser.VariableDeclaratorRestContext;
import falgout.jrepl.parser.JavaParser.VariableInitializerContext;
import falgout.jrepl.reflection.ModifierException;
public class JavaCommand implements Command {
private static enum ParserRule {
IMPORT("/importDeclaration") {
@Override
protected ParserRuleContext tryInvoke(JavaParser parser) throws RecognitionException,
ParseCancellationException {
return parser.importDeclaration();
}
},
TOP_LEVEL("/classOrInterfaceDeclaration") {
// TODO
// classOrInterfaceDeclaration
@Override
protected ParserRuleContext tryInvoke(JavaParser parser) {
return parser.classOrInterfaceDeclaration();
}
},
LOCAL("/blockStatement/") {
@Override
protected ParserRuleContext tryInvoke(JavaParser parser) {
return parser.blockStatement();
}
},
METHOD("/classBodyDeclaration") {
// TODO
// semicolon
// modifier* memberDecl
// methodOrField (won't be field, LOCAL picks it up first)
// voidMethodDeclarator
// constructor (don't want this)
// genericMethodOrConstructor (don' want constructor
// static? block
@Override
protected ParserRuleContext tryInvoke(JavaParser parser) {
return parser.classBodyDeclaration();
}
};
private final String prefix;
private ParserRule(String prefix) {
this.prefix = prefix;
}
public String getPrefix() {
return prefix;
}
public ParserRuleContext invoke(JavaParser parser) {
try {
return tryInvoke(parser);
} catch (ParseCancellationException | RecognitionException e) {
// either we're in stage 1 where we want to ignore these
// exceptions or we're in stage 2 where these exceptions won't
// be thrown
}
return null;
}
protected abstract ParserRuleContext tryInvoke(JavaParser parser) throws RecognitionException,
ParseCancellationException;
}
private static enum Type {
IMPORT(ParserRule.IMPORT, "") {
@Override
public boolean execute(Environment e, ParseTree command) throws IOException {
e.getImports().add(Import.create((ImportDeclarationContext) command));
return true;
}
},
LOCAL_VARAIBLE_DECLARATION(ParserRule.LOCAL, "localVariableDeclarationStatement/localVariableDeclaration") {
@Override
public boolean execute(Environment e, ParseTree command) throws IOException {
LocalVariableDeclarationContext ctx = (LocalVariableDeclarationContext) command;
boolean _final;
try {
_final = isFinal(ctx.variableModifier());
} catch (ModifierException e1) {
e.getError().println(e1.getMessage());
return false;
}
TypeToken<?> baseType;
try {
baseType = getType(e, ctx.type());
} catch (ClassNotFoundException e1) {
e.getError().println(e1.getMessage());
return false;
}
Map<String, Variable<?>> variables = new LinkedHashMap<>();
for (VariableDeclaratorContext var : ctx.variableDeclarators().variableDeclarator()) {
String name = var.Identifier().getText();
if (e.containsVariable(name)) {
e.getError().printf("%s already exists.\n", name);
return false;
}
VariableDeclaratorRestContext rest = var.variableDeclaratorRest();
int extraArrays = rest.L_BRACKET().size();
TypeToken<?> varType = addArraysToType(baseType, extraArrays);
VariableInitializerContext init = rest.variableInitializer();
Object value = null;
if (init != null) {
// TODO
// value = evaluate(init);
}
variables.put(name, new Variable<>(value, varType, _final));
}
if (!e.addVariables(variables)) {
throw new Error("Something went horribly wrong");
}
return true;
}
},
STATEMENT(ParserRule.LOCAL, "statement") {
@Override
public boolean execute(Environment e, ParseTree command) throws IOException {
// TODO Auto-generated method stub
return true;
}
};
private final ParserRule parent;
private final String xPathPredicate;
private Type(ParserRule parent, String suffix) {
this.parent = parent;
xPathPredicate = parent.getPrefix() + suffix;
}
public abstract boolean execute(Environment e, ParseTree command) throws IOException;
public static Map<ParseTree, Type> split(final ParseResult result, JavaParser parser) {
Map<ParseTree, Type> split = new TreeMap<>(new Comparator<ParseTree>() {
@Override
public int compare(ParseTree o1, ParseTree o2) {
// sort based on occurrence in tree (left to first)
int p1 = getChildIndex(result.ctx, o1);
int p2 = getChildIndex(result.ctx, o2);
return Integer.compare(p1, p2);
}
});
for (Type t : Type.values()) {
if (result.method == t.parent) {
for (ParseTree c : XPath.findAll(result.ctx, t.xPathPredicate, parser)) {
if (split.containsKey(c)) {
throw new Error("ruh roh");
}
split.put(c, t);
}
}
}
return split;
}
}
private static class ParseResult {
public final ParserRuleContext ctx;
public final ParserRule method;
public ParseResult(ParserRuleContext ctx, ParserRule method) {
this.ctx = ctx;
this.method = method;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ParseResult [method=");
builder.append(method);
builder.append("]");
return builder.toString();
}
}
private final ParseTree ctx;
private final Type type;
private JavaCommand(ParseTree ctx, Type type) {
this.ctx = ctx;
this.type = type;
}
@Override
public boolean execute(Environment e) throws IOException {
return type.execute(e, ctx);
}
public static CompoundCommand<JavaCommand> getCommand(String input, Writer err) throws IOException {
JavaLexer lex = new JavaLexer(new ANTLRInputStream(input));
JavaParser parser = new JavaParser(new CommonTokenStream(lex));
parser.removeErrorListeners();
ParseResult r = stageOne(parser);
if (r == null) {
r = stageTwo(parser, err);
}
if (r == null) {
return null;
}
List<JavaCommand> commands = new ArrayList<>();
for (Entry<ParseTree, Type> e : Type.split(r, parser).entrySet()) {
commands.add(new JavaCommand(e.getKey(), e.getValue()));
}
return new CompoundCommand<>(commands);
}
private static ParseResult tryParse(JavaParser parser, Predicate<? super ParserRuleContext> ret) {
for (ParserRule m : ParserRule.values()) {
ParserRuleContext ctx = m.invoke(parser);
if (ctx != null && ret.apply(ctx)) {
return new ParseResult(ctx, m);
}
parser.reset();
}
return null;
}
private static ParseResult stageOne(JavaParser parser) {
parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
parser.setErrorHandler(new BailErrorStrategy());
return tryParse(parser, Predicates.alwaysTrue());
}
private static ParseResult stageTwo(JavaParser parser, Writer err) throws IOException {
parser.getInterpreter().setPredictionMode(PredictionMode.LL);
parser.setErrorHandler(new DefaultErrorStrategy());
final CharArrayWriter sink = new CharArrayWriter();
parser.addErrorListener(new WriterErrorListener(sink));
final Set<String> errors = new LinkedHashSet<>();
final AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
ParseResult ctx = tryParse(parser, new Predicate<ParserRuleContext>() {
@Override
public boolean apply(ParserRuleContext input) {
int numErrors = getChildren(input, ErrorNode.class).size();
if (numErrors == 0) {
return true;
}
// only keep the error message(s) for the ParseTrees which have
// the best heuristic. The heuristic we're currently using is
// which parse tree has the fewest errors
if (numErrors < min.get()) {
min.set(numErrors);
errors.clear();
}
if (numErrors <= min.get()) {
errors.add(sink.toString());
}
sink.reset();
return false;
}
});
if (ctx == null) {
for (String error : errors) {
err.write(error);
}
}
return ctx;
}
} |
package fi.csc.chipster.auth.model;
import java.io.Serializable;
import javax.persistence.Embeddable;
@Embeddable
public class UserId implements Serializable {
private static final String DELIMITER = "/";
private String username;
/**
* Authenticator
*
* Username or other string identifier of the service who authenticated this user.
* Effectively creates username namespaces which ensure that each authenticator can
* only login its own users.
*/
private String auth;
public UserId() { }
public UserId(String auth, String username) {
this.auth = auth;
this.username = username;
}
public UserId(String userId) {
String[] parts = userId.split(DELIMITER);
if (parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) {
this.auth = parts[0];
this.username = parts[1];
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((auth == null) ? 0 : auth.hashCode());
result = prime * result + ((username == null) ? 0 : username.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;
UserId other = (UserId) obj;
if (auth == null) {
if (other.auth != null)
return false;
} else if (!auth.equals(other.auth))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
public String toUserIdString() {
if (auth.contains(DELIMITER) || username.contains(DELIMITER)) {
throw new IllegalStateException(DELIMITER + " not allowed in username (" + username + ")");
}
return this.auth + DELIMITER + this.username;
}
} |
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedos of a ship
*/
public class TorpedoStore {
private int torpedos = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedos = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){
throw new IllegalArgumentException("numberOfTorpedos");
}
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.1) {
// successful firing
this.torpedos -= numberOfTorpedos;
return true;
}
return false;
}
public boolean isEmpty(){
return this.torpedos <= 0;
}
public int getNumberOfTorpedos() {
return this.torpedos;
}
} |
package hu.unideb.inf.View;
import hu.unideb.inf.Core.Main;
import hu.unideb.inf.Core.Ship;
import hu.unideb.inf.Dao.HighScore;
import hu.unideb.inf.Dao.HighScoreDAOImp;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Background;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import static hu.unideb.inf.Core.Main.*;
/**
* The {@code ViewController} class implement the graphical elements.
* @author MJ
*/
public class ViewController {
/** {@link Logger} for logging.*/
private static Logger logger = LoggerFactory.getLogger( Main.class );
private HighScoreDAOImp highScoreDAOImp = new HighScoreDAOImp();
private ArrayList<HighScore> highScoreArrayList;
private ObservableList<HighScore> lista;
/** "Description" label. */
public Label descLabel = new Label("Flappy spaceship");
/** "Score" label. */
public static Label scoreLabel = new Label("Score: " + score);
/** "Fail" label. */
public Label failLabel = new Label("FAIL");
/** "New Game" label. */
public Label newGameLabel = new Label("New Game");
/** "HighScore" label. */
public Label highScoreLabel = new Label("HighScore");
/** "Exit" label. */
public Label exitLabel = new Label("Exit");
/** "Options" label. */
public Label optionsLabel = new Label("Options");
/** "Back" label. */
public Label backLabel = new Label("< Back");
/** "Sound" label. */
public Label soundText = new Label("Sound:");
/** "Leadboard" label. */
public Label leadBoardLabel = new Label("Add to leadboard");
/** "Done" label. */
public Label doneLabel = new Label("Done");
/** "Name" label. */
public Label playerNameLabel = new Label("Name:");
/** "Resume" label. */
public Label resumeLabel = new Label("Resume");
/** Sound on/off button. */
public static RadioButton onButton = new RadioButton("ON");
/** Name field. */
public TextField playerName = new TextField();
/** Highscore table. */
public TableView<HighScore> tableView = new TableView<>();
/** Name of the player. */
private static String player;
/** Creates an empty instance of {@code ViewController}. */
public ViewController() {
init();
initTable();
}
/** Set the stlye to the elements. */
public void init() {
playerNameLabel.setStyle("-fx-translate-x: 310; -fx-translate-y: 405; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
playerNameLabel.setVisible(false);
playerName.setBackground(Background.EMPTY);
playerName.setStyle("-fx-translate-x: 410; -fx-translate-y: 400; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
playerName.setVisible(false);
doneLabel.setStyle("-fx-translate-x: 340; -fx-translate-y: 550; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
doneLabel.setVisible(false);
leadBoardLabel.setStyle("-fx-translate-x: 250; -fx-translate-y: 350; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
leadBoardLabel.setVisible(false);
soundText.setStyle("-fx-translate-x: 310; -fx-translate-y: 405; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
soundText.setVisible(false);
onButton.getStyleClass().remove("radio-button");
onButton.getStyleClass().add("toggle-button");
onButton.setBackground(Background.EMPTY);
onButton.setStyle("-fx-translate-x: 430; -fx-translate-y: 400; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
onButton.setVisible(false);
scoreLabel.setStyle("-fx-translate-x: 600; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
descLabel.setStyle("-fx-translate-x: 80; -fx-translate-y: 250; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 40px;");
descLabel.setVisible(false);
failLabel.setStyle("-fx-translate-x: 300; -fx-translate-y: 200; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 60px;");
failLabel.setVisible(false);
resumeLabel.setStyle("-fx-translate-x: 345; -fx-translate-y: 350; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
resumeLabel.setVisible(false);
newGameLabel.setStyle("-fx-translate-x: 330; -fx-translate-y: 400; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
newGameLabel.setVisible(false);
highScoreLabel.setStyle("-fx-translate-x: 320; -fx-translate-y: 450; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
highScoreLabel.setVisible(false);
exitLabel.setStyle("-fx-translate-x: 370; -fx-translate-y: 550; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
exitLabel.setVisible(false);
backLabel.setStyle("-fx-translate-x: 340; -fx-translate-y: 550; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
backLabel.setVisible(false);
optionsLabel.setFont(Font.font("Press Start 2P", 20));
optionsLabel.setTextFill(Color.WHITE);
optionsLabel.setTranslateX(340);
optionsLabel.setTranslateY(500);
optionsLabel.setVisible(false);
tableView.setStyle("-fx-font-family: 'Press Start 2P'; -fx-font-size: 20px; -fx-text-fill: white; " +
"-fx-background-color: transparent; -fx-base: rgba(0,0,0,0);"+
"-fx-table-header-border-color: transparent; -fx-border-color: transparent; " +
"-fx-table-cell-border-color: transparent; -fx-control-inner-background: transparent;" +
"-fx-translate-x: 240; -fx-translate-y: 300; -fx-pref-width: 450; -fx-pref-height: 262;");
tableView.setVisible(false);
tableView.setSelectionModel(null);
}
/** Initialize the table and load content. */
public void initTable() {
TableColumn name = new TableColumn("");
name.setMinWidth(100);
name.setCellValueFactory(
new PropertyValueFactory<>("name"));
TableColumn score = new TableColumn("");
score.setMinWidth(50);
score.setCellValueFactory(
new PropertyValueFactory<>("score"));
tableView.getColumns().addAll(name, score);
score.setStyle("-fx-background-color: transparent;");
name.setStyle("-fx-background-color: transparent;");
highScoreArrayList = highScoreDAOImp.getAllHighScores().getHighScore();
lista = FXCollections.observableArrayList();
for (HighScore highScore : highScoreArrayList) {
lista.add(highScore);
}
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tableView.setItems(lista);
}
/** Refreshing the content of the table. */
public void refreshTable(){
logger.debug("Refreshing table...");
highScoreArrayList = highScoreDAOImp.getAllHighScores().getHighScore();
lista = FXCollections.observableArrayList();
for (HighScore highScore : highScoreArrayList) {
lista.add(highScore);
}
tableView.setItems(lista);
tableView.refresh();
logger.debug("Table refreshed.");
}
/** Hide the specified labels. */
private void hideLabels() {
descLabel.setVisible(false);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(false);
optionsLabel.setVisible(false);
exitLabel.setVisible(false);
leadBoardLabel.setVisible(false);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
}
/**
* Play scale effect to the newGameLabel or begins a new game.
* @param ship The spaceship.
*/
public void newGame(Ship ship) {
if (!backLabel.isVisible())
newGameLabel.setVisible(true);
newGameLabel.setOnMouseEntered(MouseEvent -> {
newGameLabel.setScaleX(1.5);
newGameLabel.setScaleY(1.5);
});
newGameLabel.setOnMouseExited(MouseEvent -> {
newGameLabel.setScaleX(1);
newGameLabel.setScaleY(1);
});
newGameLabel.setOnMouseClicked(MouseEvent -> {
logger.info("New game.");
if (!failGame) {
running = true;
score = 0;
hideLabels();
} else if (failGame) {
running = true;
ship.shipNull();
score = 0;
hideLabels();
}
});
}
/** Play scale effect to the {@link ViewController#highScoreLabel} or refreshing the content. */
public void highScore() {
if (!backLabel.isVisible())
highScoreLabel.setVisible(true);
highScoreLabel.setOnMouseEntered(MouseEvent -> {
highScoreLabel.setScaleX(1.5);
highScoreLabel.setScaleY(1.5);
});
highScoreLabel.setOnMouseExited(MouseEvent -> {
highScoreLabel.setScaleX(1);
highScoreLabel.setScaleY(1);
});
highScoreLabel.setOnMouseClicked(MouseEvent -> {
logger.info("Highscore menu.");
isHighScore = true;
refreshTable();
highScoreLabel.setTranslateX(320);
highScoreLabel.setTranslateY(250);
tableView.setVisible(true);
backLabel.setVisible(true);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(true);
optionsLabel.setVisible(false);
exitLabel.setVisible(false);
leadBoardLabel.setVisible(false);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
backMenu();
});
}
/** Play scale effect to the {@link ViewController#optionsLabel} or opening the options menu. */
public void optionsMenu() {
if (!backLabel.isVisible())
optionsLabel.setVisible(true);
optionsLabel.setOnMouseEntered(MouseEvent -> {
optionsLabel.setScaleX(1.5);
optionsLabel.setScaleY(1.5);
});
optionsLabel.setOnMouseExited(MouseEvent -> {
optionsLabel.setScaleX(1);
optionsLabel.setScaleY(1);
});
optionsLabel.setOnMouseClicked(MouseEvent -> {
logger.info("Options menu.");
isOptions = true;
optionsLabel.setFont(Font.font("Press Start 2P", 40));
optionsLabel.setTranslateX(270);
optionsLabel.setTranslateY(300);
backLabel.setVisible(true);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(false);
leadBoardLabel.setVisible(false);
exitLabel.setVisible(false);
soundText.setVisible(true);
onButton.setVisible(true);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
backMenu();
});
}
/** Play scale effect to the {@link ViewController#exitLabel} or close the game. */
public void exit() {
if (!backLabel.isVisible())
exitLabel.setVisible(true);
exitLabel.setOnMouseEntered(MouseEvent -> {
exitLabel.setScaleX(1.5);
exitLabel.setScaleY(1.5);
});
exitLabel.setOnMouseExited(MouseEvent -> {
exitLabel.setScaleX(1);
exitLabel.setScaleY(1);
});
exitLabel.setOnMouseClicked(MouseEvent -> {
logger.info("Exiting application!");
System.exit(0);
});
}
/** Play scale effect to the {@link ViewController#backLabel} or back to the previous menu. */
public void backMenu() {
backLabel.setOnMouseEntered(MouseEvent -> {
backLabel.setScaleY(1.5);
backLabel.setScaleX(1.5);
});
backLabel.setOnMouseExited(MouseEvent -> {
backLabel.setScaleX(1);
backLabel.setScaleY(1);
});
backLabel.setOnMouseClicked(MouseEvent -> {
logger.debug("Back to a previous menu.");
isOptions = false;
isHighScore = false;
if (!running && !failGame) {
descLabel.setVisible(true);
} else {
failLabel.setVisible(true);
}
if (!isOptions) {
optionsLabel.setFont(Font.font("Press Start 2P", 20));
optionsLabel.setTranslateX(340);
optionsLabel.setTranslateY(500);
}
if (!isHighScore) {
leadBoardLabel.setVisible(false);
}
if (score > 0 && isHighScore) {
leadBoardLabel.setVisible(true);
} else if (score > 0 && !isHighScore) {
leadBoardLabel.setVisible(false);
}
newGameLabel.setVisible(true);
highScoreLabel.setVisible(true);
optionsLabel.setVisible(true);
exitLabel.setVisible(true);
backLabel.setVisible(false);
onButton.setVisible(false);
soundText.setVisible(false);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
highScoreLabel.setTranslateX(320);
highScoreLabel.setTranslateY(450);
});
}
/** Play scale effect to the {@link ViewController#leadBoardLabel} or add new highscore the the HighScores.xml. */
public void addToLeadBoardMenu() {
if (score >= 1 && !isHighScore && !isOptions)
leadBoardLabel.setVisible(true);
leadBoardLabel.setOnMouseEntered(MouseEvent -> {
leadBoardLabel.setScaleY(1.5);
leadBoardLabel.setScaleX(1.5);
});
leadBoardLabel.setOnMouseExited(MouseEvent -> {
leadBoardLabel.setScaleX(1);
leadBoardLabel.setScaleY(1);
});
leadBoardLabel.setOnMouseClicked(MouseEvent -> {
backLabel.setVisible(true);
playerName.setVisible(true);
playerNameLabel.setVisible(true);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(false);
optionsLabel.setVisible(false);
exitLabel.setVisible(false);
leadBoardLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
backMenu();
playerName.setOnKeyPressed((event) -> {
if(event.getCode() == KeyCode.ENTER) {
player = playerName.getText();
initData(player,Main.score);
playerName.setText("");
newGameLabel.setVisible(true);
highScoreLabel.setVisible(true);
optionsLabel.setVisible(true);
exitLabel.setVisible(true);
backLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
backLabel.setVisible(false);
tableView.setVisible(false);
leadBoardLabel.setVisible(false);
}
});
});
}
/** Play scale effect to the {@link ViewController#highScoreLabel} or pausing the game. */
public void resumeMenu() {
if (!backLabel.isVisible())
resumeLabel.setVisible(true);
resumeLabel.setOnMouseEntered(MouseEvent -> {
resumeLabel.setScaleX(1.5);
resumeLabel.setScaleY(1.5);
});
resumeLabel.setOnMouseExited(MouseEvent -> {
resumeLabel.setScaleX(1);
resumeLabel.setScaleY(1);
});
resumeLabel.setOnMouseClicked(MouseEvent -> {
logger.debug("Playing again.");
running = true;
hideLabels();
});
}
} |
package icircles.concrete;
import icircles.abstractdescription.AbstractBasicRegion;
import icircles.abstractdescription.AbstractCurve;
import icircles.abstractdescription.AbstractDescription;
import icircles.geometry.Rectangle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.*;
import java.util.stream.Collectors;
/**
* Represents a diagram at the concrete level.
* Technically, this is a concrete form of AbstractDescription.
*/
public class ConcreteDiagram {
private static final Logger log = LogManager.getLogger(ConcreteDiagram.class);
private final Rectangle box;
private final List<CircleContour> circles;
private final List<ConcreteZone> shadedZones, allZones;
private final AbstractDescription original, actual;
private final Map<AbstractCurve, CircleContour> curveToContour;
ConcreteDiagram(AbstractDescription original, AbstractDescription actual,
List<CircleContour> circles,
Map<AbstractCurve, CircleContour> curveToContour, int size) {
this.original = original;
this.actual = actual;
this.box = new Rectangle(0, 0, size, size);
this.curveToContour = curveToContour;
this.circles = circles;
setSize(size);
log.trace("Initial diagram: " + original);
log.trace("Final diagram : " + actual);
this.shadedZones = createShadedZones();
this.allZones = actual.getZonesUnmodifiable()
.stream()
.map(this::makeConcreteZone)
.collect(Collectors.toList());
Map<AbstractCurve, List<CircleContour> > duplicates = findDuplicateContours();
log.trace("Duplicates: " + duplicates);
duplicates.values().forEach(contours -> {
for (CircleContour contour : contours) {
log.trace("Contour " + contour + " is in " + getZonesContainingContour(contour));
}
});
}
/**
* Creates shaded (extra) zones based on the difference
* between the initial diagram and final diagram.
* In other words, finds which zones in final diagram were not in initial diagram.
*
* @return list of shaded zones
*/
private List<ConcreteZone> createShadedZones() {
List<ConcreteZone> result = actual.getZonesUnmodifiable()
.stream()
.filter(zone -> !original.hasLabelEquivalentZone(zone))
.map(this::makeConcreteZone)
.collect(Collectors.toList());
log.trace("Extra zones: " + result);
return result;
}
/**
* Creates a concrete zone out of an abstract zone.
*
* @param zone the abstract zone
* @return the concrete zone
*/
private ConcreteZone makeConcreteZone(AbstractBasicRegion zone) {
List<CircleContour> includingCircles = new ArrayList<>();
List<CircleContour> excludingCircles = new ArrayList<>(circles);
for (AbstractCurve curve : zone.getCurvesUnmodifiable()) {
CircleContour contour = curveToContour.get(curve);
excludingCircles.remove(contour);
includingCircles.add(contour);
}
return new ConcreteZone(zone, includingCircles, excludingCircles);
}
/**
* @return bounding box of the whole diagram
*/
public Rectangle getBoundingBox() {
return box;
}
/**
* @return diagram contours
*/
public List<CircleContour> getCircles() {
return circles;
}
/**
* @return extra zones
*/
public List<ConcreteZone> getShadedZones() {
return shadedZones;
}
/**
* Returns original abstract description, i.e. the one that was requested.
*
* @return original abstract description
*/
public AbstractDescription getOriginalDescription() {
return original;
}
/**
* Returns actual abstract description, i.e. the one that was generated.
*
* @return actual abstract description
*/
public AbstractDescription getActualDescription() {
return actual;
}
/**
* @return all zones this concrete diagram has
*/
public List<ConcreteZone> getAllZones() {
return allZones;
}
public void setSize(int size) {
// work out a suitable size
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (CircleContour cc : circles) {
if (cc.getMinX() < minX) {
minX = cc.getMinX();
}
if (cc.getMinY() < minY) {
minY = cc.getMinY();
}
if (cc.getMaxX() > maxX) {
maxX = cc.getMaxX();
}
if (cc.getMaxY() > maxY) {
maxY = cc.getMaxY();
}
}
double midX = (minX + maxX) * 0.5;
double midY = (minY + maxY) * 0.5;
for (CircleContour cc : circles) {
cc.shift(-midX, -midY);
}
double width = maxX - minX;
double height = maxY - minY;
double biggest_HW = Math.max(height, width);
double scale = (size * 0.95) / biggest_HW;
for (CircleContour cc : circles) {
cc.scaleAboutZero(scale);
}
for (CircleContour cc : circles) {
cc.shift(size * 0.5, size * 0.5);
}
}
/**
* Returns a map, where keys are abstract curves that map to all concrete contours
* for that curve. The map only contains duplicates, i.e. it won't contain a curve
* which only maps to a single contour.
*
* @return duplicate contours
*/
public Map<AbstractCurve, List<CircleContour> > findDuplicateContours() {
Map<String, List<CircleContour> > groups = circles.stream()
.collect(Collectors.groupingBy(contour -> contour.getCurve().getLabel()));
Map<AbstractCurve, List<CircleContour> > duplicates = new TreeMap<>();
groups.forEach((label, contours) -> {
if (contours.size() > 1)
duplicates.put(original.getCurveByLabel(label).get(), contours);
});
return duplicates;
}
/**
* Returns zones in the drawn diagram that contain the given contour.
*
* @param contour the contour
* @return zones containing contour
*/
public List<ConcreteZone> getZonesContainingContour(CircleContour contour) {
return allZones.stream()
.filter(zone -> zone.getContainingCircles().contains(contour))
.collect(Collectors.toList());
}
public static double checksum(List<CircleContour> circles) {
double result = 0.0;
if (circles == null) {
return result;
}
Iterator<CircleContour> cIt = circles.iterator();
while (cIt.hasNext()) {
CircleContour c = cIt.next();
result += c.centerX * 0.345 + c.centerY * 0.456 + c.radius * 0.567 + c.getCurve().checksum() * 0.555;
result *= 1.2;
}
return result;
}
public String toDebugString() {
return "ConcreteDiagram[box=" + box + "\n"
+ "contours: " + circles + "\n"
+ "shaded zones: " + shadedZones + "]";
}
@Override
public String toString() {
return toDebugString();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.