answer
stringlengths
17
10.2M
package me.lucko.helper.hologram; import com.google.common.base.Preconditions; import com.google.gson.JsonObject; import me.lucko.helper.Events; import me.lucko.helper.gson.JsonBuilder; import me.lucko.helper.serialize.Position; import me.lucko.helper.terminable.registry.TerminableRegistry; import me.lucko.helper.utils.Color; import org.bukkit.Location; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerInteractAtEntityEvent; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; class SimpleHologram implements Hologram { private Position position; private final List<String> lines = new ArrayList<>(); private final List<ArmorStand> spawnedEntities = new ArrayList<>(); private boolean spawned = false; private TerminableRegistry listeners = null; private Consumer<Player> clickCallback = null; SimpleHologram(Position position, List<String> lines) { this.position = Preconditions.checkNotNull(position, "position"); updateLines(lines); } private Position getNewLinePosition() { if (spawnedEntities.isEmpty()) { return position; } else { // get the last entry ArmorStand last = spawnedEntities.get(spawnedEntities.size() - 1); return Position.of(last.getLocation()).subtract(0.0d, 0.25d, 0.0d); } } @Override public void spawn() { // resize to fit any new lines int linesSize = lines.size(); int spawnedSize = spawnedEntities.size(); // remove excess lines if (linesSize < spawnedSize) { int diff = spawnedSize - linesSize; for (int i = 0; i < diff; i++) { // get and remove the last entry ArmorStand as = spawnedEntities.remove(spawnedEntities.size() - 1); as.remove(); } } // now enough armorstands are spawned, we can now update the text for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (i >= spawnedEntities.size()) { // add a new line Location loc = getNewLinePosition().toLocation(); // remove any armorstands already at this location. (leftover from a server restart) loc.getWorld().getNearbyEntities(loc, 1.0, 1.0, 1.0).forEach(e -> { if (e.getType() == EntityType.ARMOR_STAND && locationsEqual(e.getLocation(), loc)) { e.remove(); } }); ArmorStand as = loc.getWorld().spawn(loc, ArmorStand.class, stand -> { stand.setSmall(true); stand.setMarker(true); stand.setArms(false); stand.setBasePlate(false); stand.setGravity(false); stand.setVisible(false); stand.setAI(false); stand.setCollidable(false); stand.setInvulnerable(true); stand.setCustomName(line); stand.setCustomNameVisible(true); }); spawnedEntities.add(as); } else { // update existing line if necessary ArmorStand as = spawnedEntities.get(i); if (as.getCustomName() != null && as.getCustomName().equals(line)) { continue; } as.setCustomName(line); } } if (this.listeners == null && this.clickCallback != null) { setClickCallback(this.clickCallback); } spawned = true; } @Override public void despawn() { spawnedEntities.forEach(Entity::remove); spawnedEntities.clear(); spawned = false; if (listeners != null) { listeners.terminate(); } listeners = null; } @Override public void updatePosition(Position position) { Preconditions.checkNotNull(position, "position"); if (this.position.equals(position)) { return; } this.position = position; despawn(); spawn(); } @Override public void updateLines(List<String> lines) { Preconditions.checkNotNull(lines, "lines"); Preconditions.checkArgument(!lines.isEmpty(), "lines cannot be empty"); for (String line : lines) { Preconditions.checkArgument(line != null, "null line"); } List<String> ret = lines.stream().map(Color::colorize).collect(Collectors.toList()); if (this.lines.equals(ret)) { return; } this.lines.clear(); this.lines.addAll(ret); } public void setClickCallback(Consumer<Player> clickCallback) { // unregister any existing listeners if (clickCallback == null) { if (this.listeners != null) { this.listeners.terminate(); } this.clickCallback = null; this.listeners = null; return; } this.clickCallback = clickCallback; if (this.listeners == null) { this.listeners = TerminableRegistry.create(); Events.subscribe(PlayerInteractAtEntityEvent.class) .filter(e -> e.getRightClicked() instanceof ArmorStand) .handler(e -> { Player p = e.getPlayer(); ArmorStand as = (ArmorStand) e.getRightClicked(); for (ArmorStand spawned : this.spawnedEntities) { if (spawned.equals(as)) { e.setCancelled(true); this.clickCallback.accept(p); return; } } }) .bindWith(this.listeners); Events.subscribe(EntityDamageByEntityEvent.class) .filter(e -> e.getEntity() instanceof ArmorStand) .filter(e -> e.getDamager() instanceof Player) .handler(e -> { Player p = (Player) e.getDamager(); ArmorStand as = (ArmorStand) e.getEntity(); for (ArmorStand spawned : this.spawnedEntities) { if (spawned.equals(as)) { e.setCancelled(true); this.clickCallback.accept(p); return; } } }) .bindWith(this.listeners); } } @Override public boolean terminate() { despawn(); return true; } @Override public boolean hasTerminated() { return !spawned; } @Override public JsonObject serialize() { return JsonBuilder.object() .add("position", position) .add("lines", JsonBuilder.array().addStrings(lines).build()) .build(); } private static boolean locationsEqual(Location l1, Location l2) { return Double.doubleToLongBits(l1.getX()) == Double.doubleToLongBits(l2.getX()) && Double.doubleToLongBits(l1.getY()) == Double.doubleToLongBits(l2.getY()) && Double.doubleToLongBits(l1.getZ()) == Double.doubleToLongBits(l2.getZ()); } }
package org.dellroad.stuff.vaadin; import com.vaadin.Application; import com.vaadin.terminal.Terminal; import com.vaadin.terminal.gwt.server.HttpServletRequestListener; import com.vaadin.ui.Window; import java.net.SocketException; import java.util.EventObject; import java.util.HashSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link Application} subclass that provides subclasses with a {@link Logger} * and logs and displays any exceptions thrown in an overlay error window, * as well as static methods to access the current {@link ContextApplication} instance. * * @since 1.0.134 */ @SuppressWarnings("serial") public abstract class ContextApplication extends Application implements HttpServletRequestListener { /** * Default notification linger time for error notifications (in milliseconds): Value is {@value}ms. */ public static final int DEFAULT_NOTIFICATION_DELAY = 30000; private static final ThreadLocal<ContextApplication> CURRENT_APPLICATION = new ThreadLocal<ContextApplication>(); private static final ThreadLocal<HttpServletRequest> CURRENT_REQUEST = new ThreadLocal<HttpServletRequest>(); private static final ThreadLocal<HttpServletResponse> CURRENT_RESPONSE = new ThreadLocal<HttpServletResponse>(); protected final Logger log = LoggerFactory.getLogger(this.getClass()); private final HashSet<CloseListener> closeListeners = new HashSet<CloseListener>(); // Initialization /** * Initialize the application. * * <p> * The implementation in {@link ContextApplication} delegates to {@link #initApplication}. * </p> */ @Override public final void init() { CURRENT_APPLICATION.set(this); this.initApplication(); } /** * Initialize the application. Sub-classes of {@link ContextApplication} must implement this method. */ protected abstract void initApplication(); // Error handling /** * Handle an uncaugt exception thrown by a Vaadin HTTP request. * * <p> * The implementation in {@link ContextApplication} logs the error and displays in on the * user's screen via {@link #showError(String, Throwable)}. */ @Override public void terminalError(Terminal.ErrorEvent event) { // Delegate to superclass super.terminalError(event); // Get exception; ignore client "hangups" final Throwable t = event.getThrowable(); if (t instanceof SocketException) return; // Notify user and log it this.showError("Internal Error", "" + t); this.log.error("error within Vaadin operation", t); } /** * Display an error message to the user. */ public void showError(String title, String description) { Window.Notification notification = new Window.Notification(title, description, Window.Notification.TYPE_ERROR_MESSAGE); notification.setStyleName("warning"); notification.setDelayMsec(this.getNotificationDelay()); this.getMainWindow().showNotification(notification); } /** * Display an error message to the user caused by an exception. */ public void showError(String title, Throwable t) { for (int i = 0; i < 100 && t.getCause() != null; i++) t = t.getCause(); this.showError(title, this.getErrorMessage(t)); } /** * Get the notification linger time for error notifications (in milliseconds). * * <p> * The implementation in {@link ContextApplication} returns {@link #DEFAULT_NOTIFICATION_DELAY}. */ protected int getNotificationDelay() { return DEFAULT_NOTIFICATION_DELAY; } /** * Convert an exception into a displayable error message. */ protected String getErrorMessage(Throwable t) { return t.getClass().getSimpleName() + ": " + t.getMessage(); } // ThreadLocal stuff public void invoke(Runnable action) { final ContextApplication previous = ContextApplication.CURRENT_APPLICATION.get(); if (previous != null && previous != this) throw new IllegalStateException("there is already a current application for this thread"); ContextApplication.CURRENT_APPLICATION.set(this); try { synchronized (this) { action.run(); } } finally { ContextApplication.CURRENT_APPLICATION.set(previous); } } /** * Handle the start of a request. * * <p> * The implementation in {@link ContextApplication} delegates to {@link #doOnRequestStart}. * </p> */ @Override public final void onRequestStart(HttpServletRequest request, HttpServletResponse response) { ContextApplication.CURRENT_APPLICATION.set(this); ContextApplication.CURRENT_REQUEST.set(request); ContextApplication.CURRENT_RESPONSE.set(response); this.doOnRequestStart(request, response); } /** * Handle the end of a request. * * <p> * The implementation in {@link ContextApplication} delegates to {@link #doOnRequestEnd}. * </p> */ @Override public final void onRequestEnd(HttpServletRequest request, HttpServletResponse response) { try { this.doOnRequestEnd(request, response); } finally { ContextApplication.CURRENT_APPLICATION.remove(); ContextApplication.CURRENT_REQUEST.remove(); ContextApplication.CURRENT_RESPONSE.remove(); } } /** * Sub-class hook for handling the start of a request. This method is invoked by {@link #onRequestStart}. * * <p> * The implementation in {@link ContextApplication} does nothing. Subclasses should override as necessary. * </p> */ protected void doOnRequestStart(HttpServletRequest request, HttpServletResponse response) { } /** * Sub-class hook for handling the end of a request. This method is invoked by {@link #onRequestEnd}. * * <p> * The implementation in {@link ContextApplication} does nothing. Subclasses should override as necessary. * </p> */ protected void doOnRequestEnd(HttpServletRequest request, HttpServletResponse response) { } /** * Get the {@link ContextApplication} instance associated with the current thread. * * <p> * If the current thread is handling a Vaadin web request that is executing within an {@link ContextApplication} instance, * then this method will return the associated {@link ContextApplication}. * </p> * * @return the {@link ContextApplication} associated with the current thread, or {@code null} if the current thread * is not servicing a Vaadin web request or the current Vaadin {@link Application} is not an {@link ContextApplication} */ public static ContextApplication currentApplication() { return ContextApplication.CURRENT_APPLICATION.get(); } /** * Get the {@link ContextApplication} associated with the current thread, cast to the desired type. * * @param type expected application type * @return the {@link ContextApplication} associated with the current thread * @see #currentApplication() * @throws ClassCastException if the current application is not assignable to {@code type} */ public static <A extends ContextApplication> A currentApplication(Class<A> type) { return type.cast(ContextApplication.currentApplication()); } public static ContextApplication get() { ContextApplication app = ContextApplication.currentApplication(); if (app != null) return app; throw new IllegalStateException("no current application found"); } public static <A extends ContextApplication> A get(Class<A> type) { A app = ContextApplication.currentApplication(type); if (app != null) return app; throw new IllegalStateException("no current application found"); } /** * Get the {@link HttpServletRequest} associated with the current thread. * * <p> * If the current thread is handling a Vaadin web request for an instance of this class, * this method will return the associated {@link HttpServletRequest}. * </p> * * @return the {@link HttpServletRequest} associated with the current thread, or {@code null} if the current thread * is not servicing a Vaadin web request or the current Vaadin {@link Application} is not an instance of this class */ public static HttpServletRequest currentRequest() { return ContextApplication.CURRENT_REQUEST.get(); } /** * Get the {@link HttpServletResponse} associated with the current thread. * * <p> * If the current thread is handling a Vaadin web request for an instance of this class, * this method will return the associated {@link HttpServletResponse}. * </p> * * @return the {@link HttpServletResponse} associated with the current thread, or {@code null} if the current thread * is not servicing a Vaadin web request or the current Vaadin {@link Application} is not an instance of this class */ public static HttpServletResponse currentResponse() { return ContextApplication.CURRENT_RESPONSE.get(); } // Listener stuff /** * Close this instance. * * <p> * The implementation in {@link ContextApplication} first delegates to the superclass and then * notifies any registered {@link CloseListener}s. * </p> */ @Override public void close() { super.close(); CloseEvent closeEvent = new CloseEvent(this); for (CloseListener closeListener : this.getCloseListeners()) { try { closeListener.applicationClosed(closeEvent); } catch (ThreadDeath t) { throw t; } catch (Throwable t) { this.log.error("exception thrown by CloseListener", t); } } } /** * Add a {@link CloseListener} to be notified when this instance is closed. */ public void addListener(CloseListener listener) { synchronized (this.closeListeners) { this.closeListeners.add(listener); } } /** * Remove a {@link CloseListener}. */ public void removeListener(CloseListener listener) { synchronized (this.closeListeners) { this.closeListeners.remove(listener); } } private HashSet<CloseListener> getCloseListeners() { synchronized (this.closeListeners) { return new HashSet<CloseListener>(this.closeListeners); } } /** * Implemented by listeners that wish to be notified when a {@link ContextApplication} is closed. */ public interface CloseListener { /** * Notification upon {@link ContextApplication} closing. */ void applicationClosed(CloseEvent closeEvent); } /** * Event delivered to listeners when a {@link ContextApplication} is closed. */ public static class CloseEvent extends EventObject { public CloseEvent(ContextApplication application) { super(application); } /** * Get the {@link ContextApplication} that is being closed. */ public ContextApplication getContextApplication() { return (ContextApplication)super.getSource(); } } }
package edu.wustl.catissuecore.query; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import edu.wustl.catissuecore.dao.JDBCDAO; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; public abstract class Query { /** * Advanced query type constant */ public static final String ADVANCED_QUERY = "AdvancedQuery"; /** * Simple query type constant */ public static final String SIMPLE_QUERY = "SimpleQuery"; /** * Vector of DataElement objects that need to be selected in the output */ private Vector resultView = new Vector(); /** * Starting object from which all related objects can be part of the query */ protected String queryStartObject = new String(); /** * Parent object of the queryStartObject i.e. the object from which the * queryStartObject is derived */ private String parentOfQueryStartObject = new String(); /** * Object that forms the where part of query. * This is SimpleConditionsImpl object in case of Simple query * and AdvancedConditionsImpl object in case of Advanced query */ protected ConditionsImpl whereConditions; /** * Suffix that is appended to all table aliases which is helpful in case of nested queries * to differentiate between super query object from the subquery object of same type */ protected int tableSufix = 1; /** * Participant object constant */ public static final String PARTICIPANT = "Participant"; public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration"; public static final String COLLECTION_PROTOCOL = "CollectionProtocol"; public static final String COLLECTION_PROTOCOL_EVENT = "CollectionProtocolEvent"; public static final String SPECIMEN_COLLECTION_GROUP = "SpecimenCollectionGroup"; public static final String SPECIMEN = "Specimen"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER = "ParticipantMedicalIdentifier"; public static final String INSTITUTION = "Institution"; public static final String DEPARTMENT = "Department"; public static final String CANCER_RESEARCH_GROUP = "CancerResearchGroup"; public static final String USER = "User"; public static final String ADDRESS = "Address"; public static final String CSM_USER = "CsmUser"; public static final String SITE = "Site"; public static final String STORAGE_TYPE = "StorageType"; public static final String STORAGE_CONTAINER_CAPACITY = "StorageContainerCapacity"; public static final String BIO_HAZARD = "BioHazard"; public static final String SPECIMEN_PROTOCOL = "SpecimenProtocol"; public static final String COLLECTION_COORDINATORS = "CollectionCoordinators"; public static final String SPECIMEN_REQUIREMENT = "SpecimenRequirement"; public static final String COLLECTION_SPECIMEN_REQUIREMENT = "CollectionSpecimenRequirement"; public static final String DISTRIBUTION_SPECIMEN_REQUIREMENT = "DistributionSpecimenRequirement"; public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol"; public static final String REPORTED_PROBLEM = "ReportedProblem"; public static final String CELL_SPECIMEN_REQUIREMENT = "CellSpecimenRequirement"; public static final String MOLECULAR_SPECIMEN_REQUIREMENT = "MolecularSpecimenRequirement"; public static final String TISSUE_SPECIMEN_REQUIREMENT = "TissueSpecimenRequirement"; public static final String FLUID_SPECIMEN_REQUIREMENT = "FluidSpecimenRequirement"; public static final String STORAGE_CONTAINER = "StorageContainer"; /** * This method executes the query string formed from getString method and creates a temporary table. * @return Returns true in case everything is successful else false */ public List execute() throws DAOException { try { JDBCDAO dao = new JDBCDAO(); dao.openSession(); Logger.out.debug("SQL************"+getString()); List list = dao.executeQuery(getString()); return list; // dao.delete(tableName); // dao.create(tableName,Constants.DEFAULT_SPREADSHEET_COLUMNS); // Iterator iterator = list.iterator(); // while (iterator.hasNext()) // List row = (List) iterator.next(); // dao.insert(tableName, row); // dao.closeSession(); } catch(DAOException daoExp) { throw new DAOException(daoExp.getMessage(), daoExp); } catch(ClassNotFoundException classExp) { throw new DAOException(classExp.getMessage(), classExp); } } /** * Adds the dataElement to result view * @param dataElement - Data Element to be added * @return - true (as per the general contract of Collection.add). */ public boolean addElementToView(DataElement dataElement) { return resultView.add(dataElement); } public String [] setViewElements(String aliasName) throws DAOException { try { String sql = "SELECT tableData2.ALIAS_NAME, temp.COLUMN_NAME "+ " from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 join"+ " ( SELECT columnData.COLUMN_NAME, columnData.TABLE_ID "+ " FROM CATISSUE_QUERY_INTERFACE_COLUMN_DATA columnData, " + " CATISSUE_TABLE_RELATION relationData, "+ " CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData " + " where relationData.CHILD_TABLE_ID = columnData.TABLE_ID " + " and relationData.PARENT_TABLE_ID = tableData.TABLE_ID " + " and tableData.ALIAS_NAME = '"+aliasName+"') as temp "+ " on temp.TABLE_ID = tableData2.TABLE_ID "; Logger.out.debug("DATAELEMENT SQL : "+sql); JDBCDAO jdbcDao = new JDBCDAO(); jdbcDao.openSession(); List list = jdbcDao.executeQuery(sql); jdbcDao.closeSession(); Vector vector = new Vector(); String [] columnNames = new String[list.size()]; Iterator iterator = list.iterator(); int i = 0; while(iterator.hasNext()) { List rowList = (List) iterator.next(); DataElement dataElement = new DataElement(); dataElement.setTable((String)rowList.get(0)); Logger.out.debug("TABLE NAME : "+dataElement.getTable()); dataElement.setField((String)rowList.get(1)); Logger.out.debug("ALIAS NAME : "+dataElement.getField()); vector.add(dataElement); columnNames[i++] = (String)rowList.get(1); Logger.out.debug("COLUMN NAME : "+columnNames[i-1]); } setResultView(vector); return columnNames; } catch(DAOException daoExp) { throw new DAOException(daoExp.getMessage(),daoExp); } catch(ClassNotFoundException classExp) { throw new DAOException(classExp.getMessage(),classExp); } } /** * Returns the SQL representation of this query object * @return */ public String getString() { StringBuffer query = new StringBuffer(); HashSet set = new HashSet(); /** * Forming SELECT part of the query */ query.append("Select "); if (resultView.size() == 0) { query.append(" * "); } else { DataElement dataElement; for (int i = 0; i < resultView.size(); i++) { dataElement = (DataElement) resultView.get(i); set.add(dataElement.getTable()); if (i != resultView.size() - 1) query.append(dataElement.getTable() + tableSufix + "." + dataElement.getField() + ", "); else query.append(dataElement.getTable() + tableSufix + "." + dataElement.getField() + " "); } } /** * Forming FROM part of query */ set.addAll(whereConditions.getQueryObjects()); set.add(this.queryStartObject); // HashSet relatedTables = new HashSet(); // Iterator it = set.iterator(); // while(it.hasNext()) // relatedTables.addAll(getRelatedTables((String) it.next())); // set.addAll(relatedTables); // it=set.iterator(); // Logger.out.debug("Tables in set are:"); // while(it.hasNext()) // Logger.out.debug(it.next()); // HashSet set = this.getQueryObjects(this.queryStartObject); // for(int i = 0 ; i < resultView.size(); i++) // set.add(((DataElement)resultView.get(i)).getTable()); System.out.println("Set : " + set.toString()); query.append("\nFROM "); query.append(this.formFromString(set)); /** * Forming WHERE part of the query */ query.append("\nWHERE "); String joinConditionString = this.getJoinConditionString(set); query.append(joinConditionString); String whereConditionsString = whereConditions.getString(tableSufix); if (whereConditionsString != null) { if (joinConditionString != null && joinConditionString.length() != 0) { query.append(" " + Operator.AND); } query.append(whereConditionsString); } return query.toString(); } /** * This method returns set of all objects related to queryStartObject transitively * @param string - Starting object to which all related objects should be found * @return set of all objects related to queryStartObject transitively */ private HashSet getQueryObjects(String queryStartObject) { HashSet set = new HashSet(); set.add(queryStartObject); Vector relatedObjectsCollection = (Vector) Client.relations .get(queryStartObject); if (relatedObjectsCollection == null) { return set; } set.addAll(relatedObjectsCollection); for (int i = 0; i < relatedObjectsCollection.size(); i++) { set .addAll(getQueryObjects((String) relatedObjectsCollection .get(i))); } // while(queryStartObject != null) // set.add(queryStartObject); // queryStartObject = (String) Client.relations.get(queryStartObject); return set; } /** * This method returns the Join Conditions string that joins all the tables/objects in the set. * In case its a subquery relation with the superquery is also appended in this string * @param set - objects in the query * @return - string containing all join conditions */ private String getJoinConditionString(final HashSet set) { StringBuffer joinConditionString = new StringBuffer(); Object[] tablesArray = set.toArray(); RelationCondition relationCondition = null; //If subquery then join with the superquery if (tableSufix > 1) { relationCondition = (RelationCondition) Client.relationConditionsForRelatedTables .get(new Relation(this.parentOfQueryStartObject, this.queryStartObject)); if (relationCondition != null) { joinConditionString.append(" " + relationCondition.getRightDataElement().toSQLString( tableSufix)); joinConditionString.append(Operator.EQUAL); joinConditionString.append(relationCondition .getRightDataElement().toSQLString(tableSufix - 1) + " "); } } //For all permutations of tables find the joining conditions for (int i = 0; i < tablesArray.length; i++) { for (int j = i + 1; j < tablesArray.length; j++) { relationCondition = (RelationCondition) Client.relationConditionsForRelatedTables .get(new Relation((String) tablesArray[i], (String) tablesArray[j])); if (relationCondition != null) { System.out.println(tablesArray[i] + " " + tablesArray[j] + " " + relationCondition.toSQLString(tableSufix)); if (joinConditionString.length() != 0) { joinConditionString.append(Operator.AND + " "); } joinConditionString.append(relationCondition .toSQLString(tableSufix)); } else { relationCondition = (RelationCondition) Client.relationConditionsForRelatedTables .get(new Relation((String) tablesArray[j], (String) tablesArray[i])); if (relationCondition != null) { System.out.println(tablesArray[j] + " " + tablesArray[i] + " " + relationCondition.toSQLString(tableSufix)); if (joinConditionString.length() != 0) { joinConditionString.append(Operator.AND + " "); } joinConditionString.append(relationCondition .toSQLString(tableSufix)); } } } } return joinConditionString.toString(); } /** * This method returns the string of table names in set that forms FROM part of query * which forms the FROM part of the query * @param set - set of tables * @return A comma separated list of the tables in the set */ private String formFromString(final HashSet set) { StringBuffer fromString = new StringBuffer(); Iterator it = set.iterator(); Object tableAlias; while (it.hasNext()) { fromString.append(" "); tableAlias = it.next(); fromString.append(Client.objectTableNames.get(tableAlias) + " " + tableAlias + tableSufix + " "); if (it.hasNext()) { fromString.append(","); } } fromString.append(" "); return fromString.toString(); } public int getTableSufix() { return tableSufix; } public void setTableSufix(int tableSufix) { this.tableSufix = tableSufix; } public String getParentOfQueryStartObject() { return parentOfQueryStartObject; } public void setParentOfQueryStartObject(String parentOfQueryStartObject) { this.parentOfQueryStartObject = parentOfQueryStartObject; } /** * @param resultView The resultView to set. */ public void setResultView(Vector resultView) { this.resultView = resultView; } public Set getRelatedTables(String aliasName) { List list = null; Set relatedTableNames = new HashSet(); try { JDBCDAO dao = new JDBCDAO(); dao.openSession(); String sqlString = "SELECT tableData2.ALIAS_NAME from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 " + "join (SELECT CHILD_TABLE_ID FROM CATISSUE_TABLE_RELATION relationData," + "CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData " + "where relationData.PARENT_TABLE_ID = tableData.TABLE_ID and tableData.ALIAS_NAME = '" + aliasName + "') as relatedTables on relatedTables.CHILD_TABLE_ID = tableData2.TABLE_ID"; list = dao.executeQuery(getString()); Iterator iterator = list.iterator(); while (iterator.hasNext()) { List row = (List) iterator.next(); relatedTableNames.add(row.get(0)); } dao.closeSession(); } catch (DAOException daoExp) { Logger.out.debug("Could not obtain related tables. Exception:" + daoExp.getMessage(), daoExp); } catch (ClassNotFoundException classExp) { Logger.out.debug("Could not obtain related tables. Exception:" + classExp.getMessage(), classExp); } Logger.out.debug("Tables related to "+aliasName+" "+relatedTableNames.toString()); return relatedTableNames; } }
package tests.net.sf.jabref.imports; import java.io.IOException; import java.io.StringReader; import java.util.Collection; import junit.framework.TestCase; import net.sf.jabref.BibtexEntry; import net.sf.jabref.BibtexEntryType; import net.sf.jabref.imports.BibtexParser; import net.sf.jabref.imports.ParserResult; import net.sf.jabref.util.XMPUtil; public class BibtexParserTest extends TestCase { public void testParseReader() throws IOException { ParserResult result = BibtexParser.parse(new StringReader( "@article{test,author={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e = (BibtexEntry) c.iterator().next(); assertEquals("test", e.getCiteKey()); assertEquals(2, e.getAllFields().length); Object[] o = e.getAllFields(); assertTrue(o[0].toString().equals("author") || o[1].toString().equals("author")); assertEquals("Ed von Test", e.getField("author")); } public void testBibtexParser() { try { BibtexParser p = new BibtexParser(null); fail("Should not accept null."); } catch (NullPointerException npe) { } } public void testIsRecognizedFormat() throws IOException { assertTrue(BibtexParser .isRecognizedFormat(new StringReader( "This file was created with JabRef 2.1 beta 2." + "\n" + "Encoding: Cp1252" + "\n" + "" + "\n" + "@INPROCEEDINGS{CroAnnHow05," + "\n" + " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}," + "\n" + " title = {Effective work practices for floss development: A model and propositions}," + "\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)}," + "\n" + " year = {2005}," + "\n" + " owner = {oezbek}," + "\n" + " timestamp = {2006.05.29}," + "\n" + " url = {http://james.howison.name/publications.html}" + "\n" + "}))"))); assertTrue(BibtexParser.isRecognizedFormat(new StringReader( "This file was created with JabRef 2.1 beta 2." + "\n" + "Encoding: Cp1252" + "\n"))); assertTrue(BibtexParser .isRecognizedFormat(new StringReader( "@INPROCEEDINGS{CroAnnHow05," + "\n" + " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}," + "\n" + " title = {Effective work practices for floss development: A model and propositions}," + "\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)}," + "\n" + " year = {2005}," + "\n" + " owner = {oezbek}," + "\n" + " timestamp = {2006.05.29}," + "\n" + " url = {http://james.howison.name/publications.html}" + "\n" + "}))"))); assertFalse(BibtexParser .isRecognizedFormat(new StringReader( " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}," + "\n" + " title = {Effective work practices for floss development: A model and propositions}," + "\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)}," + "\n" + " year = {2005}," + "\n" + " owner = {oezbek}," + "\n" + " timestamp = {2006.05.29}," + "\n" + " url = {http://james.howison.name/publications.html}" + "\n" + "}))"))); assertFalse(BibtexParser.isRecognizedFormat(new StringReader( "This was created with JabRef 2.1 beta 2." + "\n" + "Encoding: Cp1252" + "\n"))); } public void testParse() throws IOException { // Test Standard parsing BibtexParser parser = new BibtexParser(new StringReader( "@article{test,author={Ed von Test}}")); ParserResult result = parser.parse(); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e = (BibtexEntry) c.iterator().next(); assertEquals("test", e.getCiteKey()); assertEquals(2, e.getAllFields().length); Object[] o = e.getAllFields(); assertTrue(o[0].toString().equals("author") || o[1].toString().equals("author")); assertEquals("Ed von Test", e.getField("author")); // Calling parse again will return the same result assertEquals(result, parser.parse()); } public void testParse2() throws IOException { BibtexParser parser = new BibtexParser(new StringReader( "@article{test,author={Ed von Test}}")); ParserResult result = parser.parse(); BibtexEntry e = new BibtexEntry("", BibtexEntryType.ARTICLE); e.setField("author", "Ed von Test"); e.setField("bibtexkey", "test"); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e2 = (BibtexEntry) c.iterator().next(); // What needs to be done to create two identical bibtex entries? assertEquals(e, e2); } public void testNewlineHandling() throws IOException { ParserResult result = BibtexParser.parse(new StringReader("@article{canh05," + "title = {\nHallo \nWorld \nthis \n is\n\nnot \n\nan \n\n exercise \n \n.\n \n\n},\n" + "tabs = {\nHallo \tWorld \tthis \t is\t\tnot \t\tan \t\n exercise \t \n.\t \n\t},\n" + "}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e = (BibtexEntry) c.iterator().next(); assertEquals("canh05", e.getCiteKey()); assertEquals(BibtexEntryType.ARTICLE, e.getType()); assertEquals("Hallo World this is not an exercise .", e.getField("title")); assertEquals("Hallo World this is not an exercise .", e.getField("tabs")); } }
package edu.wustl.common.cde; /** * @author mandar_deshmukh * */ import edu.wustl.common.cde.xml.XMLCDE; import edu.wustl.common.cde.xml.impl.XMLCDEImpl; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.cadsr.domain.DataElement; import gov.nih.nci.cadsr.domain.EnumeratedValueDomain; import gov.nih.nci.cadsr.domain.PermissibleValue; import gov.nih.nci.cadsr.domain.ValueDomain; import gov.nih.nci.cadsr.domain.ValueDomainPermissibleValue; import gov.nih.nci.cadsr.domain.impl.DataElementImpl; import gov.nih.nci.system.applicationservice.ApplicationService; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class CDEDownloader { private String vocabularyName; private int limit; private ApplicationService appService; /** * @param proxyhost is used to specify the host to connect * @param proxyport is used to specify the port to be used for connection * @param username is used to specify the local username * @param password is used to specify the local password * @param dbserver is used to specify the database url to connect * @return returns true if the connection with the dtabase server is successful. * sets the ApplicationService object if successful. * * This method will be used for establishing the connection with the server. */ private boolean connect() { try { // creates the passwordauthenticaton object to be used for establishing // the connection with the databse server. createPasswordAuthentication(CDEConConfig.proxyhostip, CDEConConfig.proxyport, CDEConConfig.username, CDEConConfig.password); //Logger.out.debug("appService"); appService = ApplicationService.getRemoteInstance(CDEConConfig.dbserver); } // try catch (Exception conexp) { conexp.printStackTrace(); //Logger.out.error("1Error: " + conexp); return false; } // catch return true; } // connect /** * @param cdeCon It is the Configuration object. Contains all required * information for connection. * @param cdePublicId It is the public id of the cde to download. * @param vocabularyName evs database to connect * @return an CDE with all the PermissibleValues. * * @throws Exception */ public CDE loadCDE(XMLCDE xmlCDE , String vocabularyName, int limit) throws Exception { Logger.out.debug("In CDEDownloader..................."); setCDEConConfig(); boolean bCon = connect(); if (bCon) { // to remove the Logger configuration from the file System.setProperty("catissue.home", "Logs"); //Logger.configure("ApplicationResources.properties"); this.vocabularyName = vocabularyName; CDE resultCde = retrieveDataElement(xmlCDE); return resultCde; } // connection successful else { return null; } // connection failed } // loadCDE // this method returns the dataelement list /** * @param CDEPublicID PublicID of the CDE to download * @return the CDE if available or null if cde not available * @throws Exception */ private CDE retrieveDataElement(XMLCDE xmlCDE) throws Exception { //return null; //Create the dataelement and set the dataEelement properties DataElement dataElementQuery = new DataElementImpl(); // dataElementQuery.setPublicID(new Long(xmlCDE.getPublicId())); dataElementQuery.setPreferredName(xmlCDE.getName()); //Logger.out.debug("XMLCDE : " + xmlCDE.getName()); dataElementQuery.setLatestVersionIndicator("Yes"); List resultList = appService.search(DataElement.class, dataElementQuery); if(resultList == null) { resultList = new ArrayList(); resultList.add(dataElementQuery); } // check if any cde exists with the given public id. if (!resultList.isEmpty()) { // retreive the Data Element for the given publicid DataElement dataElement = (DataElement) resultList.get(0); // Logger.out.debug("dataElement Details in loadCDE "); // Logger.out.debug("PublicID "+dataElement.getPublicID()); // Logger.out.debug("LongName "+dataElement.getLongName()); // create the cde object and set the values. CDEImpl cdeobj = new CDEImpl(); cdeobj.setPublicId(dataElement.getPublicID().toString()); Logger.out.debug("CDE Public Id : "+cdeobj.getPublicId()); cdeobj.setDefination(dataElement.getPreferredDefinition()); Logger.out.debug("CDE Def : "+cdeobj.getDefination()); cdeobj.setLongName(dataElement.getLongName()); Logger.out.debug("CDE Long Name : "+cdeobj.getLongName()); cdeobj.setVersion(dataElement.getVersion().toString()); Logger.out.debug("CDE Version : "+cdeobj.getVersion()); cdeobj.setPreferredName(dataElement.getPreferredName()); Logger.out.debug("CDE Perferred Name : "+cdeobj.getPreferredName()); cdeobj.setDateLastModified(dataElement.getDateModified()); Logger.out.debug("CDE Last Modified Date : "+cdeobj.getDateLastModified()); // working on PV ValueDomain vd = dataElement.getValueDomain(); Logger.out.debug("vd class : " + vd.getClass()); String vdClass = vd.getClass().toString().substring(vd.getClass().toString().lastIndexOf(".")+1); Logger.out.debug("vdClass : " + vdClass); if(vdClass.charAt(0) == 'E') { Collection valueDomainPermissibleValueCollection = ((EnumeratedValueDomain)vd).getValueDomainPermissibleValueCollection(); Set permissibleValues = getPermissibleValues(valueDomainPermissibleValueCollection); cdeobj.setPermissibleValues(permissibleValues); } Logger.out.debug("Permissible Value Size................."+cdeobj.getPermissibleValues().size()); return cdeobj; } // list not empty else // no Data Element retreived { return null; } // list empty } // retrieveDataElements /** * Returns the Set of Permissible values from the collection of value domains. * @param valueDomainCollection The value domain collection. * @param cde The CDE to which this permissible values belong. * @return the Set of Permissibel values from the collection of value domains. */ private Set getPermissibleValues(Collection valueDomainCollection) { Logger.out.debug("Value Domain Size : "+valueDomainCollection.size()); Set permissibleValuesSet = new HashSet(); Iterator iterator = valueDomainCollection.iterator(); while(iterator.hasNext()) { ValueDomainPermissibleValue valueDomainPermissibleValue = (ValueDomainPermissibleValue) iterator.next(); PermissibleValue permissibleValue = (PermissibleValue) valueDomainPermissibleValue.getPermissibleValue(); edu.wustl.common.cde.PermissibleValue newPermissibleValue = new PermissibleValueImpl(); newPermissibleValue.setConceptid(permissibleValue.getId()); Logger.out.debug("Concept ID : "+newPermissibleValue.getConceptid()); newPermissibleValue.setValue(permissibleValue.getValue()); Logger.out.debug("Value : "+newPermissibleValue.getValue()); // newPermissibleValue.setCde(cde); // Logger.out.debug("CDE : "+newPermissibleValue.getCde()); // newPermissibleValue.setParentPermissibleValue(parentPermissibleValue); // Set subPermissibleValueSet = getPermissibleValues(permissibleValue.getValueDomainPermissibleValueCollection(), cde, newPermissibleValue); // if (subPermissibleValueSet != null) // newPermissibleValue.setSubPermissibleValues(subPermissibleValueSet); permissibleValuesSet.add(newPermissibleValue); } return permissibleValuesSet; } /** * @param dataElement Data Element for which Value Domain is to be retrieved. * @return A List of ValueDomains * @throws Exception * OK */ // code commented on 13Mar06 By MD /* private List retrieveValueDomain(DataElement dataElement) throws Exception { List resValueDomain = null; resValueDomain = appService.search("gov.nih.nci.cadsr.domain.ValueDomain", dataElement); return resValueDomain; } // retrieveValueDomain */ /** * @param lstValueDomain the value domain for which the Permissible Values are to be searched * @return A List of the PermissibleValues for a Value Domain of the dataelement. * @throws Exception */ // code commented on 13Mar06 By MD /* private List retrievePermissibleValue(DataElement dataElement,XMLPermissibleValueType xmlPermissibleValue) throws Exception { //get the Value Domain for the Data Element List valueDomainList = retrieveValueDomain(dataElement); // valuedomain list Logger.out.debug("valueDomainList "+valueDomainList.size()); // list of permissible values for the given ValueDomain List pvList = new ArrayList(); Iterator iterator = valueDomainList.iterator(); while(iterator.hasNext()) { Logger.out.debug("1"); ValueDomain valueDomain = (ValueDomain) iterator.next(); if(valueDomain instanceof EnumeratedValueDomain)//Enumerated { Logger.out.debug("EnumeratedValueDomain "); //get the enumerated ValueDomain EnumeratedValueDomain enumValDom = (EnumeratedValueDomain) valueDomain; pvList = getPermissibleValues(enumValDom, xmlPermissibleValue); } else //NonEnumerated { NonenumeratedValueDomain nonEnumValDom = (NonenumeratedValueDomain)valueDomain; pvList.add(nonEnumValDom); } } return pvList; } // retrievePermissibleValueForValueDomainPermissibleValue */ /* private List getPermissibleValues(EnumeratedValueDomain enumValDom, XMLPermissibleValueType xmlPermissibleValue) throws Exception { List pvList = new ArrayList(); Logger.out.debug("enumValDom.getValueDomainPermissibleValueCollection().size() "+enumValDom.getValueDomainPermissibleValueCollection().size()); // get the Collection of PermissibleValues for the ValueDomain Iterator pvIterator = enumValDom.getValueDomainPermissibleValueCollection().iterator(); while (pvIterator.hasNext()) { Logger.out.debug("pvIterator.hasNext()"); // ValueDomainPermissibleValue for the enumValDom ValueDomainPermissibleValue valDomPerVal = (ValueDomainPermissibleValue) pvIterator.next(); //PermissibleValues for the given VDPV List permissibleValueList = appService.search(PermissibleValue.class, valDomPerVal); Logger.out.debug("permissibleValueList "+permissibleValueList.size()); if (!permissibleValueList.isEmpty()) { //collecting all the PermissibleValues for (int cnt = 0; cnt < permissibleValueList.size(); cnt++) { PermissibleValue permissibleValue = (PermissibleValue) permissibleValueList .get(cnt); pvList.add(permissibleValue); Logger.out.debug("Value "+permissibleValue.getValue()); Logger.out.debug("Id "+permissibleValue.getId()); // String searchTerm = permissibleValue.getValue(); // Logger.out.debug("SearchTerm : "+ searchTerm); // List validValues = evsdata(searchTerm, limit); // if (validValues!=null ) // pvList.addAll(validValues) ; } // for } // if } // while return pvList; } */ /** * @param proxyhost url of the database to connect * @param proxyport port to be used for connection * @param username Username of the local system * @param password Password of the local system * @throws Exception * This method which accepts the local username,password, * proxy host and proxy port to create a PasswordAuthentication * that will be used for establishing the connection. */ private void createPasswordAuthentication(String proxyhost,String proxyport, String username,String password) throws Exception { /** * username is a final variable for the username. */ final String localusername = username; /** * password is a final variable for the password. */ final String localpassword = password; /** * authenticator is an object of Authenticator used for * authentication of the username and password. */ Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { // sets http authentication return new PasswordAuthentication(localusername, localpassword.toCharArray()); } }; // setting the authenticator Authenticator.setDefault(authenticator); /** * Checking the proxy port for validity */ boolean validnum = CommonUtilities.checknum(proxyport, 0, 0); if (validnum == false) { //Logger.out.info("Invalid Proxy Port: " + proxyport); throw new Exception("Invalid ProxyPort"); } /** * Validating the Proxy IpAddress */ // boolean validip = CommonUtilities.isvalidIP(proxyhost); // if (validip == false) // //Logger.out.info("Invalid Proxy Host: " + proxyhost); // throw new Exception("Invalid ProxyHost"); // setting the system settings System.setProperty("proxyHost", proxyhost); System.setProperty("proxyPort", proxyport); } //createPasswordAuthentication // code commented on 13Mar06 By MD /* private List evsdata(String searchTerm, int limit) { List evsDataList = new ArrayList(); try { evsDataList = getEvsConceptTree(searchTerm, limit); } // try catch (Exception ex) { //Logger.out.error("2"+ex); } // catch return evsDataList; } // evsdata */ /** * @param searchTerm The PermissibleValue to search for the concept * @param limit The depth of the PermissibleValue tree * @return A List of all possible Concepts for the given Permissible Value * upto the limit specified */ /* private List getEvsConceptTree(String searchTerm, int limit) { try { EVSQuery aEVSQuery = new EVSQueryImpl(); List resultList = null; Vector roles = new Vector(); String lev = "" + limit; int j = 0; aEVSQuery.getTree(vocabularyName, searchTerm, true, false, 0, lev, roles); resultList = appService.evsSearch(aEVSQuery); if (!resultList.isEmpty()) { Object conceptCode = resultList.get(j); // Logger.out.debug(j + "]\t " + conceptCode + " :: | " // + resultList.get(j)); //Logger.out.info(j + "]\t " + conceptCode + " :: | " + resultList.get(j)); DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) conceptCode; Object uo = dmtn.getUserObject(); DescLogicConcept dlc = (DescLogicConcept) uo; // to check the tree object printTree(dmtn); } return resultList; } // try catch (Exception e2) { //Logger.out.error("3Error: " + e2); return null; } } //getEvsConceptTree */ // to be deleted later. /** * @param root The Root node of the tree to print * This method prints the entire tree from the given node up to its leaves. */ // code commented on 13Mar06 By MD public static void main(String []args) throws Exception { CDEDownloader cdeDownloader = new CDEDownloader(); XMLCDE xmlCDE = new XMLCDEImpl(); xmlCDE.setName("PT_RACE_CAT" ); xmlCDE.setPublicId("106" ); Logger.out.debug("\nIn Main : \n"); Logger.out.debug("cdeDownloader................."+cdeDownloader); CDE cde = cdeDownloader.loadCDE(xmlCDE,"NCI_Thesaurus",10); printCDE(cde); } /** * This method prints the given cde's information. * @param cde The cde to print. */ public static void printCDE(CDE cde) { Logger.out.debug("\nPrinting CDE\n Logger.out.debug("\nLong Name : "+ cde.getLongName()); Logger.out.debug("\nPublicID : "+cde.getPublicId()); Logger.out.debug("\nDef : " + cde.getDefination()); Logger.out.debug("\nDate Last Modified : " + cde.getDateLastModified()); Logger.out.debug("\n HashSet hs =(HashSet) cde.getPermissibleValues(); Iterator itr = hs.iterator(); while(itr.hasNext() ) { edu.wustl.common.cde.PermissibleValue pv = (edu.wustl.common.cde.PermissibleValue) itr.next(); Logger.out.debug(" Id : " + pv.getConceptid()); Logger.out.debug(" Value : " + pv.getValue()); } Logger.out.debug("\nDone"); } private void setCDEConConfig() { CDEConConfig.proxyhostip ="scproxy.persistent.co.in"; CDEConConfig.proxyport = "80"; CDEConConfig.password =""; CDEConConfig.username = "gautam_shetty"; CDEConConfig.dbserver ="http://cabio.nci.nih.gov/cacore30/server/HTTPServer"; } } // class CDEDownloader
/// TODO : consider symbols that don't appear in the SRS? package logicrepository.plugins.srs; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Iterator; import java.util.Set; //This uses a slightly modified Aho-Corasick automaton public class PatternMatchAutomaton extends LinkedHashMap<State, HashMap<Symbol, ActionState>> { private State s0 = new State(0); private ArrayList<Set<State>> depthMap = new ArrayList<Set<State>>(); private HashMap<State, State> fail; private int longestLhsSize; public PatternMatchAutomaton(SRS srs){ longestLhsSize = srs.getLongestLhsSize(); mkGotoMachine(srs); addFailureTransitions(srs.getTerminals()); } private void mkGotoMachine(SRS srs){ State currentState; put(s0, new HashMap<Symbol, ActionState>()); Set<State> depthStates = new HashSet<State>(); depthStates.add(s0); depthMap.add(depthStates); //compute one path through the tree for each lhs for(Rule r : srs){ currentState = s0; Sequence pattern = r.getLhs(); int patternRemaining = pattern.size() - 1; for(Symbol s : pattern){ HashMap<Symbol, ActionState> transition = get(currentState); ActionState nextActionState = transition.get(s); State nextState; if(nextActionState == null){ int nextDepth = currentState.getDepth() + 1; nextState = new State(nextDepth); nextActionState = new ActionState(0, nextState); transition.put(s, nextActionState); put(nextState, new HashMap<Symbol, ActionState>()); if(nextDepth == depthMap.size()){ depthStates = new HashSet<State>(); depthMap.add(depthStates); } else{ depthStates = depthMap.get(nextDepth); } depthStates.add(nextState); } else{ nextState = nextActionState.getState(); } if(patternRemaining == 0){ nextState.setMatch(r); } currentState = nextState; --patternRemaining; } } //now add self transitions on s0 for any symbols that don't //exit from s0 already HashMap<Symbol, ActionState> s0transition = get(s0); for(Symbol s : srs.getTerminals()){ if(!s0transition.containsKey(s)){ s0transition.put(s, new ActionState(0, s0)); } } } private void addFailureTransitions(Set<Symbol> terminals){ fail = new HashMap<State, State>(); if(depthMap.size() == 1) return; //handle all depth 1 for(State state : depthMap.get(1)){ HashMap<Symbol, ActionState> transition = get(state); fail.put(state, s0); for(Symbol symbol : terminals){ if(!transition.containsKey(symbol)){ transition.put(symbol, new ActionState(1, s0)); } } } if(depthMap.size() == 2) return; //handle depth d > 1 for(int i = 2; i < depthMap.size(); ++i){ for(State state : depthMap.get(i)){ HashMap<Symbol, ActionState> transition = get(state); for(Symbol symbol : terminals){ if(!transition.containsKey(symbol)){ State failState = findState(state, depthMap.get(i - 1), fail, terminals); transition.put(symbol, new ActionState(state.getDepth() - failState.getDepth(), failState)); fail.put(state, failState); } } } } //System.out.println("!!!!!!!!!!"); //System.out.println(fail); //System.out.println("!!!!!!!!!!"); } private State findState(State state, Set<State> shallowerStates, HashMap<State, State> fail, Set<Symbol> terminals){ for(State shallowerState : shallowerStates){ HashMap<Symbol, ActionState> transition = get(shallowerState); for(Symbol symbol : terminals){ ActionState destination = transition.get(symbol); if(destination.getState() == state){ // System.out.println(state + " " + destination.getState()); State failState = fail.get(shallowerState); while(failState != s0 && get(failState).get(symbol).getAction() != 0){ failState = fail.get(failState); } return get(failState).get(symbol).getState(); } } } return s0; } public void rewrite(SinglyLinkedList<Symbol> l){ System.out.println("rewriting:"); System.out.println(" " + l + "\n========================================="); if(l.size() == 0) return; Iterator<Symbol> first = l.iterator(); first.next(); //make sure first points to an element Iterator<Symbol> second = l.iterator(); Iterator<Symbol> lastRepl; State currentState = s0; ActionState as; Symbol symbol = second.next(); while(true){ as = get(currentState).get(symbol); System.out.println("*" + symbol + " //adjust the first pointer if(currentState == s0 && as.getState() == s0){ System.out.println("false 0 transition"); if(!first.hasNext()) break; first.next(); } else { for(int i = 0; i < as.getAction(); ++i){ first.next(); } } if(as.getState().getMatch() != null){ AbstractSequence repl = as.getState().getMatch().getRhs(); if(repl instanceof Fail){ System.out.println("Fail!"); return; } if(repl instanceof Succeed){ System.out.println("Succeed!"); return; } if(repl instanceof Sequence){ System.out.println("==========Replacing==============" + first); System.out.println("==========Replacing==============" + second); System.out.println("in: " + l); l.nonDestructiveReplace(first, second, (Sequence) repl); if(l.isEmpty()) break; first = l.iterator(); System.out.println("out: " + l); System.out.println("out: " + first); //lastRepl = l.iterator(second); //System.out.println("lastRepl: " + lastRepl); symbol = first.next(); second = l.iterator(first); //System.out.println("first: " + first); //System.out.println("second: " + second); currentState = s0; continue; } } if(!second.hasNext()) break; currentState = as.getState(); //normal transition if(as.getAction() == 0){ symbol = second.next(); } //fail transition, need to reconsider he same symbol in next state } System.out.println("substituted form = " + l.toString()); } public void rewrite(SpliceList<Symbol> l){ System.out.println("rewriting:"); System.out.println(" " + l + "\n========================================="); if(l.isEmpty()) return; SLIterator<Symbol> first; SLIterator<Symbol> second; SLIterator<Symbol> lastRepl = null; State currentState = s0; ActionState as; Symbol symbol; boolean changed; DONE: do { changed = false; first = l.head(); second = l.head(); symbol = second.get(); System.out.println("******************outer"); if(second.equals(lastRepl)){ System.out.println("second == lastRepl"); break DONE; } while(true){ as = get(currentState).get(symbol); System.out.println("*" + symbol + " //adjust the first pointer if(currentState == s0 && as.getState() == s0){ System.out.println("false 0 transition"); if(!first.next()) break; } else { for(int i = 0; i < as.getAction(); ++i){ first.next(); } } if(as.getState().getMatch() != null){ AbstractSequence repl = as.getState().getMatch().getRhs(); if(repl instanceof Fail){ System.out.println("Fail!"); return; } if(repl instanceof Succeed){ System.out.println("Succeed!"); return; } if(repl instanceof Sequence){ changed = true; System.out.println("==========Replacing==============" + first); System.out.println("==========Replacing==============" + second); System.out.println("in: " + l); first.nonDestructiveSplice(second, (Sequence) repl); if(l.isEmpty()) break DONE; System.out.println("out: " + l); System.out.println("out: " + first); lastRepl = second; System.out.println("lastRepl: " + lastRepl); second = first.copy(); System.out.println("first: " + first); System.out.println("second: " + second); currentState = s0; symbol = second.get(); continue; } } currentState = as.getState(); //normal transition if(as.getAction() == 0){ if(!second.next()) break; symbol = second.get(); } //fail transition, need to reconsider he same symbol in next state } } while(changed); System.out.println("substituted form = " + l.toString()); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); for(State state : keySet()){ sb.append(state); sb.append("\n["); HashMap<Symbol, ActionState> transition = get(state); for(Symbol symbol : transition.keySet()){ sb.append(" "); sb.append(symbol); sb.append(" -> "); sb.append(transition.get(symbol)); sb.append("\n"); } sb.append("]\n"); } return sb.toString(); } } class ActionState { private int action; private State state; public int getAction(){ return action; } public State getState(){ return state; } public ActionState(int action, State state){ this.action = action; this.state = state; } @Override public String toString(){ return "[" + action + "] " + state.toString(); } } class State { private static int counter = 0; private int number; private int depth; private Rule matchedRule = null; public State(int depth){ number = counter++; this.depth = depth; } public int getNumber(){ return number; } public int getDepth(){ return depth; } public Rule getMatch(){ return matchedRule; } public void setMatch(Rule r){ matchedRule = r; } @Override public String toString(){ return "<" + number + " @ " + depth + ((matchedRule == null)? "" : " matches " + matchedRule.toString() ) + ">"; } }
/// TODO : consider symbols that don't appear in the SRS? package logicrepository.plugins.srs; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Iterator; import java.util.Set; //This uses a slightly modified Aho-Corasick automaton public class PatternMatchAutomaton extends LinkedHashMap<State, HashMap<Symbol, ActionState>> { private State s0 = new State(0); private ArrayList<Set<State>> depthMap = new ArrayList<Set<State>>(); private HashMap<State, State> fail; public PatternMatchAutomaton(SRS srs){ mkGotoMachine(srs, srs.getTerminals()); addFailureTransitions(srs.getTerminals()); } public PatternMatchAutomaton(SRS srs, Set<Symbol> extraTerminals){ Set<Symbol> terminals = new HashSet<Symbol>(); terminals.addAll(srs.getTerminals()); terminals.addAll(extraTerminals); mkGotoMachine(srs, terminals); addFailureTransitions(terminals); } private void mkGotoMachine(SRS srs, Set<Symbol> terminals){ State currentState; put(s0, new HashMap<Symbol, ActionState>()); Set<State> depthStates = new HashSet<State>(); depthStates.add(s0); depthMap.add(depthStates); //compute one path through the tree for each lhs for(Rule r : srs){ currentState = s0; Sequence pattern = r.getLhs(); int patternRemaining = pattern.size() - 1; for(Symbol s : pattern){ HashMap<Symbol, ActionState> transition = get(currentState); ActionState nextActionState = transition.get(s); State nextState; if(nextActionState == null){ int nextDepth = currentState.getDepth() + 1; nextState = new State(nextDepth); nextActionState = new ActionState(0, nextState); transition.put(s, nextActionState); put(nextState, new HashMap<Symbol, ActionState>()); if(nextDepth == depthMap.size()){ depthStates = new HashSet<State>(); depthMap.add(depthStates); } else{ depthStates = depthMap.get(nextDepth); } depthStates.add(nextState); } else{ nextState = nextActionState.getState(); } if(patternRemaining == 0){ nextState.setMatch(r); } currentState = nextState; --patternRemaining; } } //now add self transitions on s0 for any symbols that don't //exit from s0 already HashMap<Symbol, ActionState> s0transition = get(s0); for(Symbol s : terminals){ if(!s0transition.containsKey(s)){ s0transition.put(s, new ActionState(0, s0)); } } } private void addFailureTransitions(Set<Symbol> terminals){ fail = new HashMap<State, State>(); if(depthMap.size() == 1) return; //handle all depth 1 for(State state : depthMap.get(1)){ HashMap<Symbol, ActionState> transition = get(state); fail.put(state, s0); for(Symbol symbol : terminals){ if(!transition.containsKey(symbol)){ transition.put(symbol, new ActionState(1, s0)); } } } if(depthMap.size() == 2) return; //handle depth d > 1 for(int i = 2; i < depthMap.size(); ++i){ for(State state : depthMap.get(i)){ HashMap<Symbol, ActionState> transition = get(state); for(Symbol symbol : terminals){ if(!transition.containsKey(symbol)){ State failState = findState(state, depthMap.get(i - 1), fail, terminals); transition.put(symbol, new ActionState(state.getDepth() - failState.getDepth(), failState)); fail.put(state, failState); } } } } //System.out.println("!!!!!!!!!!"); //System.out.println(fail); //System.out.println("!!!!!!!!!!"); } private State findState(State state, Set<State> shallowerStates, HashMap<State, State> fail, Set<Symbol> terminals){ for(State shallowerState : shallowerStates){ HashMap<Symbol, ActionState> transition = get(shallowerState); for(Symbol symbol : terminals){ ActionState destination = transition.get(symbol); if(destination.getState() == state){ // System.out.println(state + " " + destination.getState()); State failState = fail.get(shallowerState); while(failState != s0 && get(failState).get(symbol).getAction() != 0){ failState = fail.get(failState); } return get(failState).get(symbol).getState(); } } } return s0; } public void rewrite(SinglyLinkedList<Symbol> l){ System.out.println("rewriting:"); if(l.size() == 0) return; Iterator<Symbol> first = l.iterator(); first.next(); //make sure first points to an element Iterator<Symbol> second = l.iterator(); Iterator<Symbol> lastRepl; State currentState = s0; ActionState as; Symbol symbol = second.next(); while(true){ as = get(currentState).get(symbol); //System.out.println("*" + symbol + " -- " + as); //adjust the first pointer if(currentState == s0 && as.getState() == s0){ //System.out.println("false 0 transition"); if(!first.hasNext()) break; first.next(); } else { for(int i = 0; i < as.getAction(); ++i){ first.next(); } } if(as.getState().getMatch() != null){ AbstractSequence repl = as.getState().getMatch().getRhs(); if(repl instanceof Fail){ System.out.println("Fail!"); return; } if(repl instanceof Succeed){ System.out.println("Succeed!"); return; } if(repl instanceof Sequence){ //System.out.println("in: " + l); l.nonDestructiveReplace(first, second, (Sequence) repl); if(l.isEmpty()) break; first = l.iterator(); //System.out.println("out: " + l); //System.out.println("out: " + first); //lastRepl = l.iterator(second); //System.out.println("lastRepl: " + lastRepl); symbol = first.next(); second = l.iterator(first); //System.out.println("first: " + first); //System.out.println("second: " + second); currentState = s0; continue; } } if(!second.hasNext()) break; currentState = as.getState(); //normal transition if(as.getAction() == 0){ symbol = second.next(); } //fail transition, need to reconsider he same symbol in next state } System.out.println("substituted form = " + l.toString()); } public void rewrite(SpliceList<Symbol> l){ System.out.println("rewriting:"); System.out.println(" " + l + "\n========================================="); if(l.isEmpty()) return; SLIterator<Symbol> first; SLIterator<Symbol> second; SLIterator<Symbol> lastRepl = null; State currentState; ActionState as; Symbol symbol; boolean changed; boolean atOrPastLastChange; DONE: do { currentState = s0; atOrPastLastChange = false; changed = false; first = l.head(); second = l.head(); symbol = second.get(); while(true){ as = get(currentState).get(symbol); //System.out.println("*" + symbol + " -- " + as); //adjust the first pointer if(currentState == s0 && as.getState() == s0){ //System.out.println("false 0 transition"); if(!first.next()) break; } else { for(int i = 0; i < as.getAction(); ++i){ first.next(); } } if(as.getState().getMatch() != null){ AbstractSequence repl = as.getState().getMatch().getRhs(); if(repl instanceof Fail){ System.out.println("Fail!"); return; } if(repl instanceof Succeed){ System.out.println("Succeed!"); return; } if(repl instanceof Sequence){ changed = true; atOrPastLastChange = false; //System.out.println("in: " + l); first.nonDestructiveSplice(second, (Sequence) repl); if(l.isEmpty()) break DONE; //System.out.println("out: " + l); //System.out.println("out: " + first); lastRepl = second; //System.out.println("lastRepl: " + lastRepl); second = first.copy(); //System.out.println("first: " + first); //System.out.println("second: " + second); currentState = s0; symbol = second.get(); if(symbol == null) break; continue; } } currentState = as.getState(); //normal transition if(as.getAction() == 0){ if(!second.next()) break; if(!changed){ if(second.equals(lastRepl)){ atOrPastLastChange = true; } if(atOrPastLastChange && currentState == s0){ //System.out.println("early exit at symbol " + second); break DONE; } } symbol = second.get(); } //fail transition, need to reconsider he same symbol in next state } } while(changed); System.out.println("substituted form = " + l.toString()); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); for(State state : keySet()){ sb.append(state); sb.append("\n["); HashMap<Symbol, ActionState> transition = get(state); for(Symbol symbol : transition.keySet()){ sb.append(" "); sb.append(symbol); sb.append(" -> "); sb.append(transition.get(symbol)); sb.append("\n"); } sb.append("]\n"); } return sb.toString(); } public String toDotString(){ StringBuilder sb = new StringBuilder("digraph A"); sb.append((long) (Math.random()* 2e61d)); sb.append("{\n rankdir=TB;\n node [shape=circle];\n"); // sb.append(" edge [style=\">=stealth' ,shorten >=1pt\"];\n"); for(State state : keySet()){ sb.append(" "); sb.append(state.toFullDotString()); sb.append("\n"); } for(State state : keySet()){ HashMap<Symbol, ActionState> transition = get(state); sb.append(transitionToDotString(state, transition)); } sb.append("}"); return sb.toString(); } public Map<Symbol, Integer> mkSymToNum(){ HashMap<Symbol, ActionState> transition = get(s0); HashMap<Symbol, Integer> symToNum = new HashMap<Symbol, Integer>(); int i = 0; for(Symbol key : transition.keySet()){ symToNum.put(key, i++); } return symToNum; } public String toImplString(){ Map<Symbol, Integer> symToNum = mkSymToNum(); StringBuilder sb = new StringBuilder(); sb.append(symToNum.toString()); sb.append("\n\n"); sb.append("static MOPPMATransitionImpl [][] pma = {"); for(State state : keySet()){ sb.append("{"); HashMap<Symbol, ActionState> transition = get(state); for(Symbol symbol : transition.keySet()){ ActionState astate = transition.get(symbol); State s = astate.getState(); sb.append("new MOPPMATransitionImpl("); sb.append(astate.getAction()); sb.append(", new MOPPMAStateImpl("); sb.append(s.getNumber()); if(s.getMatch() != null){ s.getMatch().getRhs().getImpl(sb, symToNum); } sb.append(")),\n"); } sb.append("},\n\n"); } sb.append("};\n"); return sb.toString(); } public StringBuilder transitionToDotString(State state, Map<Symbol, ActionState> transition){ Map<ActionState, ArrayList<Symbol>> edgeCondensingMap = new LinkedHashMap<ActionState, ArrayList<Symbol>>(); for(Symbol symbol : transition.keySet()){ ActionState next = transition.get(symbol); ArrayList<Symbol> edges = edgeCondensingMap.get(next); if(edges == null){ edges = new ArrayList<Symbol>(); edgeCondensingMap.put(next, edges); } edges.add(symbol); } // System.out.println(edgeCondensingMap); // if(true) throw new RuntimeException(); StringBuilder sb = new StringBuilder(); for(ActionState next : edgeCondensingMap.keySet()){ sb.append(" "); sb.append(state.toNameDotString()); sb.append(" -> "); sb.append(next.getState().toNameDotString()); sb.append(" [label=\""); StringBuilder label = new StringBuilder(); for(Symbol symbol : edgeCondensingMap.get(next)){ label.append(symbol.toString()); label.append(", "); } label.setCharAt(label.length() - 1, '/'); label.setCharAt(label.length() - 2, ' '); label.append(" "); label.append(next.getAction()); sb.append(label); sb.append("\"];\n"); } return sb; // for(Symbol symbol : transition.keySet()){ // sb.append(" "); // sb.append(state.toNameDotString()); // sb.append(" -> "); // ActionState next = transition.get(symbol); // sb.append(next.getState().toNameDotString()); // sb.append(" [texlbl=\"$"); // sb.append(symbol.toDotString()); // sb.append(" / "); // sb.append(next.getAction()); // sb.append("$\"];\n"); } } class ActionState { private int action; private State state; public int getAction(){ return action; } public State getState(){ return state; } public ActionState(int action, State state){ this.action = action; this.state = state; } @Override public String toString(){ return "[" + action + "] " + state.toString(); } @Override public int hashCode(){ return action ^ state.hashCode(); } @Override public boolean equals(Object o){ if(this == o) return true; if(!(o instanceof ActionState)) return false; ActionState as = (ActionState) o; return(as.action == action && state.equals(as.state)); } } class State { private static int counter = 0; private int number; private int depth; private Rule matchedRule = null; public State(int depth){ number = counter++; this.depth = depth; } public int getNumber(){ return number; } public int getDepth(){ return depth; } public Rule getMatch(){ return matchedRule; } public void setMatch(Rule r){ matchedRule = r; } //matched rule must always be equal if number is equal //ditto with depth @Override public int hashCode(){ return number; } @Override public boolean equals(Object o){ if(this == o) return true; if(!(o instanceof State)) return false; State s = (State) o; return s.number == number; } @Override public String toString(){ return "<" + number + " @ " + depth + ((matchedRule == null)? "" : " matches " + matchedRule.toString() ) + ">"; } public String toFullDotString(){ String name = toNameDotString(); String ruleStr; int ruleLen; if(matchedRule == null){ ruleStr = ""; ruleLen = 0; } else { ruleStr = "\\\\ (" + matchedRule.toDotString() + ")"; ruleLen = matchedRule.dotLength() + 4; //add a bit extra padding } String texlbl= number + " : " + depth + ruleStr; return name + " [texlbl=\"$\\begin{array}{c}" + texlbl + "\\end{array}$\" label=\"" + mkSpaces(Math.max(new Integer(number).toString().length() + new Integer(depth).toString().length() + 5, ruleLen)) + "\"];"; } static String mkSpaces(int len){ StringBuilder sb = new StringBuilder(); for(; len > 0; --len){ sb.append(' '); } return sb.toString(); } public String toNameDotString(){ return "s_" + number; } }
/** * Container for link between two Osm nodes * * @author ab */ package btools.router; import btools.mapaccess.OsmLink; import btools.mapaccess.OsmNode; import btools.mapaccess.OsmTransferNode; import btools.mapaccess.TurnRestriction; final class StdPath extends OsmPath { /** * The elevation-hysteresis-buffer (0-10 m) */ private int ehbd; // in micrometer private int ehbu; // in micrometer private float totalTime; // travel time (seconds) private float totalEnergy; // total route energy (Joule) private float elevation_buffer; // just another elevation buffer (for travel time) // Gravitational constant, g private static final double GRAVITY = 9.81; // in meters per second^(-2) @Override public void init( OsmPath orig ) { StdPath origin = (StdPath)orig; this.ehbd = origin.ehbd; this.ehbu = origin.ehbu; this.totalTime = origin.totalTime; this.totalEnergy = origin.totalEnergy; this.elevation_buffer = origin.elevation_buffer; } @Override protected void resetState() { ehbd = 0; ehbu = 0; totalTime = 0.f; totalEnergy = 0.f; elevation_buffer = 0.f; } @Override protected double processWaySection( RoutingContext rc, double distance, double delta_h, double elevation, double angle, double cosangle, boolean isStartpoint, int nsection, int lastpriorityclassifier ) { // calculate the costfactor inputs float turncostbase = rc.expctxWay.getTurncost(); float cfup = rc.expctxWay.getUphillCostfactor(); float cfdown = rc.expctxWay.getDownhillCostfactor(); float cf = rc.expctxWay.getCostfactor(); cfup = cfup == 0.f ? cf : cfup; cfdown = cfdown == 0.f ? cf : cfdown; int dist = (int)distance; // legacy arithmetics needs int // penalty for turning angle int turncost = (int)((1.-cosangle) * turncostbase + 0.2 ); // e.g. turncost=90 -> 90 degree = 90m penalty if ( message != null ) { message.linkturncost += turncost; message.turnangle = (float)angle; } double sectionCost = turncost; // only the part of the descend that does not fit into the elevation-hysteresis-buffers // leads to an immediate penalty int delta_h_micros = (int)(1000000. * delta_h); ehbd += -delta_h_micros - dist * rc.downhillcutoff; ehbu += delta_h_micros - dist * rc.uphillcutoff; float downweight = 0.f; if ( ehbd > rc.elevationpenaltybuffer ) { downweight = 1.f; int excess = ehbd - rc.elevationpenaltybuffer; int reduce = dist * rc.elevationbufferreduce; if ( reduce > excess ) { downweight = ((float)excess)/reduce; reduce = excess; } excess = ehbd - rc.elevationmaxbuffer; if ( reduce < excess ) { reduce = excess; } ehbd -= reduce; if ( rc.downhillcostdiv > 0 ) { int elevationCost = reduce/rc.downhillcostdiv; sectionCost += elevationCost; if ( message != null ) { message.linkelevationcost += elevationCost; } } } else if ( ehbd < 0 ) { ehbd = 0; } float upweight = 0.f; if ( ehbu > rc.elevationpenaltybuffer ) { upweight = 1.f; int excess = ehbu - rc.elevationpenaltybuffer; int reduce = dist * rc.elevationbufferreduce; if ( reduce > excess ) { upweight = ((float)excess)/reduce; reduce = excess; } excess = ehbu - rc.elevationmaxbuffer; if ( reduce < excess ) { reduce = excess; } ehbu -= reduce; if ( rc.uphillcostdiv > 0 ) { int elevationCost = reduce/rc.uphillcostdiv; sectionCost += elevationCost; if ( message != null ) { message.linkelevationcost += elevationCost; } } } else if ( ehbu < 0 ) { ehbu = 0; } // get the effective costfactor (slope dependent) float costfactor = cfup*upweight + cf*(1.f - upweight - downweight) + cfdown*downweight; if ( message != null ) { message.costfactor = costfactor; } sectionCost += dist * costfactor + 0.5f; return sectionCost; } @Override protected double processTargetNode( RoutingContext rc ) { // finally add node-costs for target node if ( targetNode.nodeDescription != null ) { boolean nodeAccessGranted = rc.expctxWay.getNodeAccessGranted() != 0.; rc.expctxNode.evaluate( nodeAccessGranted , targetNode.nodeDescription ); float initialcost = rc.expctxNode.getInitialcost(); if ( initialcost >= 1000000. ) { return -1.; } if ( message != null ) { message.linknodecost += (int)initialcost; message.nodeKeyValues = rc.expctxNode.getKeyValueDescription( nodeAccessGranted, targetNode.nodeDescription ); } return initialcost; } return 0.; } // @Override protected void xxxaddAddionalPenalty(OsmTrack refTrack, boolean detailMode, OsmPath origin, OsmLink link, RoutingContext rc ) { byte[] description = link.descriptionBitmap; if ( description == null ) throw new IllegalArgumentException( "null description for: " + link ); boolean recordTransferNodes = detailMode || rc.countTraffic; boolean recordMessageData = detailMode; rc.nogomatch = false; // extract the 3 positions of the first section int lon0 = origin.originLon; int lat0 = origin.originLat; OsmNode p1 = sourceNode; int lon1 = p1.getILon(); int lat1 = p1.getILat(); short ele1 = origin.selev; int linkdisttotal = 0; MessageData msgData = recordMessageData ? new MessageData() : null; boolean isReverse = link.isReverse( sourceNode ); // evaluate the way tags rc.expctxWay.evaluate( rc.inverseDirection ^ isReverse, description ); // calculate the costfactor inputs boolean isTrafficBackbone = cost == 0 && rc.expctxWay.getIsTrafficBackbone() > 0.f; float turncostbase = rc.expctxWay.getTurncost(); float cfup = rc.expctxWay.getUphillCostfactor(); float cfdown = rc.expctxWay.getDownhillCostfactor(); float cf = rc.expctxWay.getCostfactor(); cfup = cfup == 0.f ? cf : cfup; cfdown = cfdown == 0.f ? cf : cfdown; float newClassifier = rc.expctxWay.getInitialClassifier(); if ( newClassifier == 0. ) { newClassifier = (cfup + cfdown + cf)/3; } float classifierDiff = newClassifier - lastClassifier; if ( classifierDiff > 0.0005 || classifierDiff < -0.0005 ) { lastClassifier = newClassifier; float initialcost = rc.expctxWay.getInitialcost(); int iicost = (int)initialcost; if ( recordMessageData ) { msgData.linkinitcost += iicost; } cost += iicost; } OsmTransferNode transferNode = link.geometry == null ? null : rc.geometryDecoder.decodeGeometry( link.geometry, p1, targetNode, isReverse ); boolean isFirstSection = true; for(;;) { originLon = lon1; originLat = lat1; int lon2; int lat2; short ele2; if ( transferNode == null ) { lon2 = targetNode.ilon; lat2 = targetNode.ilat; ele2 = targetNode.selev; } else { lon2 = transferNode.ilon; lat2 = transferNode.ilat; ele2 = transferNode.selev; } // check turn restrictions: do we have one with that origin? boolean checkTRs = false; if ( isFirstSection ) { isFirstSection = false; // TODO: TRs for inverse routing would need inverse TR logic, // inverse routing for now just for target island check, so don't care (?) // in detail mode (=final pass) no TR to not mess up voice hints checkTRs = rc.considerTurnRestrictions && !rc.inverseDirection && !detailMode; } if ( checkTRs ) { boolean hasAnyPositive = false; boolean hasPositive = false; boolean hasNegative = false; TurnRestriction tr = sourceNode.firstRestriction; while( tr != null ) { boolean trValid = ! (tr.exceptBikes() && rc.bikeMode); if ( trValid && tr.fromLon == lon0 && tr.fromLat == lat0 ) { if ( tr.isPositive ) { hasAnyPositive = true; } if ( tr.toLon == lon2 && tr.toLat == lat2 ) { if ( tr.isPositive ) { hasPositive = true; } else { hasNegative = true; } } } tr = tr.next; } if ( !hasPositive && ( hasAnyPositive || hasNegative ) ) { cost = -1; return; } } // if recording, new MessageData for each section (needed for turn-instructions) if ( recordMessageData && msgData.wayKeyValues != null ) { originElement.message = msgData; msgData = new MessageData(); } int dist = rc.calcDistance( lon1, lat1, lon2, lat2 ); boolean stopAtEndpoint = false; if ( rc.shortestmatch ) { if ( rc.isEndpoint ) { stopAtEndpoint = true; ele2 = interpolateEle( ele1, ele2, rc.wayfraction ); } else { // we just start here, reset cost cost = 0; ehbd = 0; ehbu = 0; lon0 = -1; // reset turncost-pipe lat0 = -1; if ( recordTransferNodes ) { if ( rc.wayfraction > 0. ) { ele1 = interpolateEle( ele1, ele2, 1. - rc.wayfraction ); originElement = OsmPathElement.create( rc.ilonshortest, rc.ilatshortest, ele1, null, rc.countTraffic ); } else { originElement = null; // prevent duplicate point } } } } if ( recordMessageData ) { msgData.linkdist += dist; } linkdisttotal += dist; // apply a start-direction if appropriate (by faking the origin position) if ( lon0 == -1 && lat0 == -1 ) { double coslat = Math.cos( ( lat1 - 90000000 ) * 0.00000001234134 ); if ( rc.startDirectionValid && coslat > 0. ) { double dir = rc.startDirection.intValue() / 57.29578; lon0 = lon1 - (int) ( 1000. * Math.sin( dir ) / coslat ); lat0 = lat1 - (int) ( 1000. * Math.cos( dir ) ); } } if ( !isTrafficBackbone && lon0 != -1 && lat0 != -1 ) { // penalty proportional to direction change double angle = rc.calcAngle( lon0, lat0, lon1, lat1, lon2, lat2 ); double cos = 1. - rc.getCosAngle(); int actualturncost = (int)(cos * turncostbase + 0.2 ); // e.g. turncost=90 -> 90 degree = 90m penalty cost += actualturncost; if ( recordMessageData ) { msgData.linkturncost += actualturncost; msgData.turnangle = (float)rc.calcAngle( lon0, lat0, lon1, lat1, lon2, lat2 ); } } // only the part of the descend that does not fit into the elevation-hysteresis-buffer // leads to an immediate penalty int elefactor = 250000; if ( ele2 == Short.MIN_VALUE ) ele2 = ele1; if ( ele1 != Short.MIN_VALUE ) { ehbd += (ele1 - ele2)*elefactor - dist * rc.downhillcutoff; ehbu += (ele2 - ele1)*elefactor - dist * rc.uphillcutoff; } float downweight = 0.f; if ( ehbd > rc.elevationpenaltybuffer ) { downweight = 1.f; int excess = ehbd - rc.elevationpenaltybuffer; int reduce = dist * rc.elevationbufferreduce; if ( reduce > excess ) { downweight = ((float)excess)/reduce; reduce = excess; } excess = ehbd - rc.elevationmaxbuffer; if ( reduce < excess ) { reduce = excess; } ehbd -= reduce; if ( rc.downhillcostdiv > 0 ) { int elevationCost = reduce/rc.downhillcostdiv; cost += elevationCost; if ( recordMessageData ) { msgData.linkelevationcost += elevationCost; } } } else if ( ehbd < 0 ) { ehbd = 0; } float upweight = 0.f; if ( ehbu > rc.elevationpenaltybuffer ) { upweight = 1.f; int excess = ehbu - rc.elevationpenaltybuffer; int reduce = dist * rc.elevationbufferreduce; if ( reduce > excess ) { upweight = ((float)excess)/reduce; reduce = excess; } excess = ehbu - rc.elevationmaxbuffer; if ( reduce < excess ) { reduce = excess; } ehbu -= reduce; if ( rc.uphillcostdiv > 0 ) { int elevationCost = reduce/rc.uphillcostdiv; cost += elevationCost; if ( recordMessageData ) { msgData.linkelevationcost += elevationCost; } } } else if ( ehbu < 0 ) { ehbu = 0; } // get the effective costfactor (slope dependent) float costfactor = cfup*upweight + cf*(1.f - upweight - downweight) + cfdown*downweight; if ( isTrafficBackbone ) { costfactor = 0.f; } float fcost = dist * costfactor + 0.5f; if ( ( costfactor > 9998. && !detailMode ) || fcost + cost >= 2000000000. ) { cost = -1; return; } int waycost = (int)(fcost); cost += waycost; // calculate traffic if ( rc.countTraffic ) { int minDist = (int)rc.trafficSourceMinDist; int cost2 = cost < minDist ? minDist : cost; traffic += dist*rc.expctxWay.getTrafficSourceDensity()*Math.pow(cost2/10000.f,rc.trafficSourceExponent); } if ( recordMessageData ) { msgData.costfactor = costfactor; msgData.priorityclassifier = (int)rc.expctxWay.getPriorityClassifier(); msgData.classifiermask = (int)rc.expctxWay.getClassifierMask(); msgData.lon = lon2; msgData.lat = lat2; msgData.ele = ele2; msgData.wayKeyValues = rc.expctxWay.getKeyValueDescription( isReverse, description ); } if ( stopAtEndpoint ) { if ( recordTransferNodes ) { originElement = OsmPathElement.create( rc.ilonshortest, rc.ilatshortest, ele2, originElement, rc.countTraffic ); originElement.cost = cost; if ( recordMessageData ) { originElement.message = msgData; } } if ( rc.nogomatch ) { cost = -1; } return; } if ( transferNode == null ) { if ( refTrack != null && refTrack.containsNode( targetNode ) && refTrack.containsNode( sourceNode ) ) { int reftrackcost = linkdisttotal; cost += reftrackcost; } selev = ele2; break; } transferNode = transferNode.next; if ( recordTransferNodes ) { originElement = OsmPathElement.create( lon2, lat2, ele2, originElement, rc.countTraffic ); originElement.cost = cost; originElement.addTraffic( traffic ); traffic = 0; } lon0 = lon1; lat0 = lat1; lon1 = lon2; lat1 = lat2; ele1 = ele2; } // check for nogo-matches (after the *actual* start of segment) if ( rc.nogomatch ) { cost = -1; return; } // finally add node-costs for target node if ( targetNode.nodeDescription != null ) { boolean nodeAccessGranted = rc.expctxWay.getNodeAccessGranted() != 0.; rc.expctxNode.evaluate( nodeAccessGranted , targetNode.nodeDescription ); float initialcost = rc.expctxNode.getInitialcost(); if ( initialcost >= 1000000. ) { cost = -1; return; } int iicost = (int)initialcost; cost += iicost; if ( recordMessageData ) { msgData.linknodecost += iicost; msgData.nodeKeyValues = rc.expctxNode.getKeyValueDescription( nodeAccessGranted, targetNode.nodeDescription ); } } if ( recordMessageData ) { message = msgData; } } @Override public int elevationCorrection( RoutingContext rc ) { return ( rc.downhillcostdiv > 0 ? ehbd/rc.downhillcostdiv : 0 ) + ( rc.uphillcostdiv > 0 ? ehbu/rc.uphillcostdiv : 0 ); } @Override public boolean definitlyWorseThan( OsmPath path, RoutingContext rc ) { StdPath p = (StdPath)path; int c = p.cost; if ( rc.downhillcostdiv > 0 ) { int delta = p.ehbd - ehbd; if ( delta > 0 ) c += delta/rc.downhillcostdiv; } if ( rc.uphillcostdiv > 0 ) { int delta = p.ehbu - ehbu; if ( delta > 0 ) c += delta/rc.uphillcostdiv; } return cost > c; } private double calcIncline( double dist ) { double min_delta = 3.; double shift; if ( elevation_buffer > min_delta ) { shift = -min_delta; } else if ( elevation_buffer < min_delta ) { shift = -min_delta; } else { return 0.; } double decayFactor = exp( - dist / 100. ); float new_elevation_buffer = (float)( (elevation_buffer+shift) * decayFactor - shift); double incline = ( elevation_buffer - new_elevation_buffer ) / dist; elevation_buffer = new_elevation_buffer; return incline; } @Override protected void computeKinematic( RoutingContext rc, double dist, double delta_h, boolean detailMode ) { if ( !detailMode ) { return; } // compute incline elevation_buffer += delta_h; double incline = calcIncline( dist ); double speed; // Travel speed double f_roll = rc.bikeMass * GRAVITY * ( rc.defaultC_r + incline ); if (rc.footMode ) { // Use Tobler's hiking function for walking sections speed = 6 * Math.exp(-3.5 * Math.abs( incline + 0.05)) / 3.6; } else if (rc.bikeMode) { speed = solveCubic( rc.S_C_x, f_roll, rc.bikerPower ); speed = Math.min(speed, rc.maxSpeed); } else { return; } float dt = (float) ( dist / speed ); totalTime += dt; totalEnergy += dist*(rc.S_C_x*speed*speed + f_roll); } private static double solveCubic( double a, double c, double d ) { // Solves a * v^3 + c * v = d with a Newton method // to get the speed v for the section. double v = 8.; boolean findingStartvalue = true; for ( int i = 0; i < 10; i++ ) { double y = ( a * v * v + c ) * v - d; if ( y < .1 ) { if ( findingStartvalue ) { v *= 2.; continue; } break; } findingStartvalue = false; double y_prime = 3 * a * v * v + c; v -= y / y_prime; } return v; } @Override public double getTotalTime() { return totalTime; } @Override public double getTotalEnergy() { return totalEnergy; } }
package ccw.launching; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.ProgressMonitorWrapper; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.JavaLaunchDelegate; import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; import org.eclipse.ui.console.IConsoleListener; import ccw.CCWPlugin; import ccw.ClojureCore; import ccw.ClojureProject; import ccw.repl.REPLView; import ccw.util.DisplayUtil; import clojure.lang.RT; import clojure.lang.Symbol; import clojure.lang.Var; import clojure.tools.nrepl.SafeFn; public class ClojureLaunchDelegate extends JavaLaunchDelegate { private static Var currentLaunch = Var.create(); private static IConsole lastConsoleOpened; private static ServerSocket ackREPLServer; static { try { ackREPLServer = (ServerSocket)((List)Var.find(Symbol.intern("clojure.tools.nrepl/start-server")).invoke()).get(0); CCWPlugin.log("Started ccw nREPL server on port " + ackREPLServer.getLocalPort()); } catch (Exception e) { CCWPlugin.logError("Could not start plugin-hosted REPL server for launch ack", e); } ConsolePlugin.getDefault().getConsoleManager().addConsoleListener(new IConsoleListener() { public void consolesRemoved(IConsole[] consoles) {} public void consolesAdded(IConsole[] consoles) { lastConsoleOpened = consoles.length > 0 ? consoles[0] : null; } }); } private class REPLViewLaunchMonitor extends ProgressMonitorWrapper { private ILaunch launch; private REPLViewLaunchMonitor (IProgressMonitor m, ILaunch launch) { super(m); this.launch = launch; } public void done() { super.done(); Job ackJob = new Job("Waiting for new REPL process ack") { @Override protected IStatus run(final IProgressMonitor monitor) { final int STEPS_BEFORE_GIVING_UP = 200; final int MILLIS_BETWEEN_STEPS = 50; monitor.beginTask("Waiting for new REPL process ack", STEPS_BEFORE_GIVING_UP); Integer maybePort = null; for (int i = 0; i < STEPS_BEFORE_GIVING_UP; i++) { maybePort = (Integer)SafeFn.find("clojure.tools.nrepl", "wait-for-ack").sInvoke(MILLIS_BETWEEN_STEPS); monitor.worked(1); if (maybePort != null) { break; } } if (maybePort == null) { CCWPlugin.logError("Waiting for new REPL process ack timed out"); return new Status(IStatus.ERROR, CCWPlugin.PLUGIN_ID, "Waiting for new REPL process ack timed out"); } final Integer port = maybePort; DisplayUtil.asyncExec(new Runnable() { public void run() { if (isAutoReloadEnabled(launch) && getProject() != null) { try { getProject().touch(new NullProgressMonitor() { public void done() { connectRepl(); } }); } catch (CoreException e) { CCWPlugin.logError("unexpected exception during project refresh for auto-load on startup", e); } } else { connectRepl(); } monitor.done(); } private IProject getProject() { try { return LaunchUtils.getProject(launch); } catch (CoreException e) { CCWPlugin.logWarning("Unable to get project for launch configuration", e); return null; } } private void connectRepl() { try { REPLView.connect("localhost", port, lastConsoleOpened, launch); } catch (Exception e) { CCWPlugin.logError("Could not connect REPL to local launch", e); } } }); return Status.OK_STATUS; } }; ackJob.setUser(true); ackJob.schedule(); } } @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { launch.setAttribute(LaunchUtils.ATTR_PROJECT_NAME, configuration.getAttribute(LaunchUtils.ATTR_PROJECT_NAME, (String) null)); launch.setAttribute(LaunchUtils.ATTR_IS_AUTO_RELOAD_ENABLED, Boolean.toString(configuration.getAttribute(LaunchUtils.ATTR_IS_AUTO_RELOAD_ENABLED, false))); SafeFn.find("clojure.tools.nrepl", "reset-ack-port!").sInvoke(); try { Var.pushThreadBindings(RT.map(currentLaunch, launch)); super.launch(configuration, mode, launch, (monitor == null || !isLaunchREPL(configuration)) ? monitor : new REPLViewLaunchMonitor(monitor, launch)); } finally { Var.popThreadBindings(); } } @Override public String getVMArguments(ILaunchConfiguration configuration) throws CoreException { String launchId = UUID.randomUUID().toString(); return String.format(" -D%s=%s %s", LaunchUtils.SYSPROP_LAUNCH_ID, launchId, super.getVMArguments(configuration)); } @Override public String getProgramArguments(ILaunchConfiguration configuration) throws CoreException { String userProgramArguments = super.getProgramArguments(configuration); if (isLaunchREPL(configuration)) { String filesToLaunchArguments = LaunchUtils.getFilesToLaunchAsCommandLineList(configuration, false); // TODO why don't we just add the ccw stuff to the classpath as we do for nrepl? String toolingFile = null; try { URL toolingFileURL = CCWPlugin.getDefault().getBundle().getResource("ccw/debug/serverrepl.clj"); toolingFile = FileLocator.toFileURL(toolingFileURL).getFile(); } catch (IOException e) { throw new WorkbenchException("Could not find ccw.debug.serverrepl source file", e); } String nREPLInit = "(require 'clojure.tools.nrepl)" + // don't want start-server return value printed String.format("(do (clojure.tools.nrepl/start-server 0 %s) nil)", ackREPLServer.getLocalPort()); return String.format("-i \"%s\" -e \"%s\" %s %s", toolingFile, nREPLInit, filesToLaunchArguments, userProgramArguments); } else { String filesToLaunchArguments = LaunchUtils.getFilesToLaunchAsCommandLineList(configuration, true); return filesToLaunchArguments + " " + userProgramArguments; } } private static boolean isLaunchREPL(ILaunchConfiguration configuration) throws CoreException { return configuration.getAttribute(LaunchUtils.ATTR_CLOJURE_START_REPL, true); } public static boolean isAutoReloadEnabled (ILaunch launch) { return Boolean.valueOf(launch.getAttribute(LaunchUtils.ATTR_IS_AUTO_RELOAD_ENABLED)); } @Override public String getMainTypeName(ILaunchConfiguration configuration) throws CoreException { String main = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)null); return main == null ? clojure.main.class.getName() : main; } @Override public String[] getClasspath(ILaunchConfiguration configuration) throws CoreException { List<String> classpath = new ArrayList<String>(Arrays.asList(super.getClasspath(configuration))); ClojureProject clojureProject = ClojureCore.getClojureProject(LaunchUtils.getProject(configuration)); for (IFolder f: clojureProject.sourceFolders()) { String sourcePath = f.getLocation().toOSString(); while (classpath.contains(sourcePath)) { // The sourcePath already exists, remove it first classpath.remove(sourcePath); } classpath.add(0, sourcePath); } if (clojureProject.getJavaProject().findElement(new Path("clojure/tools/nrepl")) == null) { try { File repllib = FileLocator.getBundleFile(Platform.getBundle("org.clojure.tools.nrepl")); classpath.add(repllib.getAbsolutePath()); } catch (IOException e) { throw new WorkbenchException("Failed to find nrepl library", e); } } return classpath.toArray(new String[classpath.size()]); } }
package beaform.gui.formulaeditor; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; import java.util.List; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.transaction.NotSupportedException; import javax.transaction.SystemException; import org.apache.commons.collections.IteratorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import beaform.entities.Formula; import beaform.entities.FormulaDAO; import beaform.entities.FormulaTag; import beaform.entities.Ingredient; /** * This class represents a GUI for editing formulas. * * @author Steven Post * */ public class FormulaEditor extends JPanel { /** A serial */ private static final long serialVersionUID = 2557014310487638917L; /** A logger */ private static final Logger LOG = LoggerFactory.getLogger(FormulaEditor.class); /** Dimensions for most text fields */ private static final Dimension DIM_TEXTFIELDS = new Dimension(100, 30); /** Dimensions for the description field */ private static final Dimension DIM_TEXTAREA = new Dimension(100, 90); /** A label for the total amount of a formula */ private static final JLabel LBL_TOTAL_AMOUNT = new JLabel("total amount"); /** A label for the name of a formula */ private static final JLabel LBL_NAME = new JLabel("Name"); /** A label for the description of a formula */ private static final JLabel LBL_DESCRIPTION = new JLabel("Description"); /** A text field for the name of the formula */ private final JTextField txtName = new JTextField(); /** A text field for the description of a formula */ private final JTextArea txtDescription = new JTextArea(); /** A text field for the total amount of a formula */ private final JTextField txtTotalAmount = new JTextField(); /** The 'save' button */ private final JButton btnSubmit = new JButton("Submit"); /** The panel with all the tag components */ private final TagPane tagPane = new TagPane(); /** The panel with all the ingredient components */ private final IngredientPane ingredientPane = new IngredientPane(); /** The formula that needs editing */ private Formula formula; /** * Main constructor for this editor to add a new formula. * If you want to edit an existing one, * use the overridden constructor that takes a formula as argument. */ public FormulaEditor() { super(new GridBagLayout()); init(true); this.btnSubmit.addActionListener(new ActionListener() { /** * Invoked when the button is pressed. */ @Override public void actionPerformed(final ActionEvent event) { addNewFormula(); } }); } /** * Constructor that makes this an editor for existing formulas. * * @param formula The formula that needs editing. */ public FormulaEditor(final Formula formula) { super(new GridBagLayout()); init(false); this.formula = formula; this.txtName.setText(formula.getName()); this.txtDescription.setText(formula.getDescription()); this.txtTotalAmount.setText(formula.getTotalAmount()); try { // Add ingredients to the list final List<Ingredient> ingredientList = new FormulaDAO().getIngredients(formula); for (final Ingredient ingredient : ingredientList) { this.ingredientPane.addIngredient(ingredient); } // Add tags to the list final Iterator<FormulaTag> tagIterator = formula.getTags(); this.tagPane.addMultipleTags(tagIterator); } catch (NotSupportedException | SystemException e) { LOG.error("Failed to add all tags and ingredients", e); } this.btnSubmit.addActionListener(new ActionListener() { /** * Invoked when the button is pressed. */ @Override public void actionPerformed(final ActionEvent event) { updateFormula(); } }); } private void init(final boolean isNew) { int gridy = 0; // Formula requirements final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = gridy; this.add(LBL_NAME, constraints); constraints.gridx = 1; constraints.gridy = gridy; setDimensions(this.txtName, DIM_TEXTFIELDS); this.txtName.setEnabled(isNew); this.add(this.txtName, constraints); gridy++; constraints.gridx = 0; constraints.gridy = gridy; this.add(LBL_DESCRIPTION, constraints); constraints.gridx = 1; constraints.gridy = gridy; setDimensions(this.txtDescription, DIM_TEXTAREA); this.add(this.txtDescription, constraints); gridy++; constraints.gridx = 0; constraints.gridy = gridy; setDimensions(LBL_TOTAL_AMOUNT, DIM_TEXTFIELDS); this.add(LBL_TOTAL_AMOUNT, constraints); constraints.gridx = 1; constraints.gridy = gridy; setDimensions(this.txtTotalAmount, DIM_TEXTFIELDS); this.add(this.txtTotalAmount, constraints); // Ingredients gridy++; constraints.gridx = 0; constraints.gridy = gridy; constraints.gridwidth = 3; constraints.gridheight = 4; this.add(this.ingredientPane, constraints); constraints.gridheight = 1; constraints.gridwidth = 1; // Tags gridy = gridy + 5; constraints.gridx = 0; constraints.gridy = gridy; constraints.gridwidth = 3; constraints.gridheight = 4; this.add(this.tagPane, constraints); constraints.gridheight = 1; constraints.gridwidth = 1; // Submit gridy = gridy + 5; constraints.gridx = 0; constraints.gridy = gridy; constraints.gridwidth = 2; this.add(this.btnSubmit, constraints); } /** * This method sets 3 different sizes to a component: * minimum, preferred and maximum * * @param comp The component * @param dim The dimensions for the sizing */ private void setDimensions(final JComponent comp, final Dimension dim) { comp.setMinimumSize(dim); comp.setPreferredSize(dim); comp.setMaximumSize(dim); } /** * Invoked when the action occurs. * */ public void addNewFormula() { if (LOG.isInfoEnabled()) { LOG.info("Add: " + this.txtName.getText() + " with description: " + this.txtDescription.getText()); } final List<Ingredient> ingredients = getIngredientList(); final List<FormulaTag> tags = getTagList(); try { new FormulaDAO().addFormula(this.txtName.getText(), this.txtDescription.getText(), this.txtTotalAmount.getText(), ingredients, tags); } catch (SystemException | NotSupportedException e1) { LOG.error("Something wen wrong adding the new formula", e1); } } @SuppressWarnings("unchecked") private List<Ingredient> getIngredientList() { return IteratorUtils.toList(this.ingredientPane.getIngredients()); } @SuppressWarnings("unchecked") private List<FormulaTag> getTagList() { return IteratorUtils.toList(this.tagPane.getTags()); } /** * Updates an existing formula. */ public void updateFormula() { if (LOG.isInfoEnabled()) { LOG.info("Edit: " + this.formula.getName() + " with description: " + this.txtDescription.getText()); } final List<Ingredient> ingredients = getIngredientList(); final List<FormulaTag> tags = getTagList(); try { new FormulaDAO().updateExisting(this.formula.getName(), this.txtDescription.getText(), this.txtTotalAmount.getText(), ingredients, tags); } catch (SystemException | NotSupportedException e1) { LOG.error("Something went wrong updating the formula", e1); } } }
package com.alvazan.orm.impl.meta.data; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.alvazan.orm.api.exc.ChildWithNoPkException; import com.alvazan.orm.api.z5api.NoSqlSession; import com.alvazan.orm.api.z8spi.Row; import com.alvazan.orm.api.z8spi.action.Column; import com.alvazan.orm.api.z8spi.conv.StandardConverters; import com.alvazan.orm.api.z8spi.meta.DboColumnMeta; import com.alvazan.orm.api.z8spi.meta.DboColumnToManyMeta; import com.alvazan.orm.api.z8spi.meta.DboTableMeta; import com.alvazan.orm.api.z8spi.meta.IndexData; import com.alvazan.orm.api.z8spi.meta.InfoForIndex; import com.alvazan.orm.api.z8spi.meta.ReflectionUtil; import com.alvazan.orm.api.z8spi.meta.RowToPersist; import com.alvazan.orm.impl.meta.data.collections.ListProxyFetchAll; import com.alvazan.orm.impl.meta.data.collections.MapProxyFetchAll; import com.alvazan.orm.impl.meta.data.collections.OurAbstractCollection; import com.alvazan.orm.impl.meta.data.collections.SetProxyFetchAll; public final class MetaToManyField<OWNER, PROXY> extends MetaAbstractField<OWNER> { private MetaAbstractClass<PROXY> classMeta; private Field fieldForKey; private DboColumnToManyMeta metaDbo = new DboColumnToManyMeta(); public DboColumnMeta getMetaDbo() { return metaDbo; } @Override public void translateFromColumn(Row row, OWNER entity, NoSqlSession session) { Object proxy; if(field.getType().equals(Map.class)) proxy = translateFromColumnMap(row, entity, session); else if(field.getType().equals(Collection.class) || field.getType().equals(List.class)) proxy = translateFromColumnList(row, entity, session); else if(field.getType().equals(Set.class)) proxy = translateFromColumnSet(row, entity, session); else throw new RuntimeException("bug, we do not support type="+field.getType()); ReflectionUtil.putFieldValue(entity, field, proxy); } private Object translateFromColumnSet(Row row, OWNER entity, NoSqlSession session) { List<byte[]> keys = parseColNamePostfix(columnName, row); Set<PROXY> retVal = new SetProxyFetchAll<PROXY>(entity, session, classMeta, keys, field); return retVal; } @SuppressWarnings({ "rawtypes" }) private Map translateFromColumnMap(Row row, OWNER entity, NoSqlSession session) { List<byte[]> keys = parseColNamePostfix(columnName, row); MapProxyFetchAll proxy = MapProxyFetchAll.create(entity, session, classMeta, keys, fieldForKey, field); //MapProxyFetchAll proxy = new MapProxyFetchAll(entity, session, classMeta, keys, fieldForKey); return proxy; } private List<PROXY> translateFromColumnList(Row row, OWNER entity, NoSqlSession session) { List<byte[]> keys = parseColNamePostfix(columnName, row); List<PROXY> retVal = new ListProxyFetchAll<PROXY>(entity, session, classMeta, keys, field); return retVal; } static List<byte[]> parseColNamePostfix(String columnName, Row row) { byte[] bytes = StandardConverters.convertToBytes(columnName); Collection<Column> columns = row.columnByPrefix(bytes); List<byte[]> entities = new ArrayList<byte[]>(); //NOTE: Current implementation is just like a Set not a List in that it //cannot have repeats right now. We could take the approach the column name //would be <prefix><index><pk> such that duplicates are allowed and when loaded //we would have to keep the index in the proxy so if removed, we could put the col name //back together so we could remove it and add the new one. This is very complex though when //it comes to removing one item and shifting all other column names by one(ie. lots of removes/adds) //so for now, just make everything Set like. for(Column col : columns) { byte[] colNameData = col.getName(); //strip off the prefix to get the foreign key int pkLen = colNameData.length-bytes.length; byte[] pk = new byte[pkLen]; for(int i = bytes.length; i < colNameData.length; i++) { pk[i-bytes.length] = colNameData[i]; } entities.add(pk); } return entities; } @Override public Object fetchField(Object entity) { throw new UnsupportedOperationException("only used for partitioning and multivalue column can't partition. easy to implement if anyone else starts using this though, but for now unsupported"); } @Override public String translateToString(Object fieldsValue) { throw new UnsupportedOperationException("only used for partitioning and multievalue column can't partition. easy to implement if anyone else starts using this though, but for now unsupported"); } @Override public void translateToColumn(InfoForIndex<OWNER> info) { OWNER entity = info.getEntity(); RowToPersist row = info.getRow(); if(field.getType().equals(Map.class)) translateToColumnMap(entity, row); else translateToColumnList(entity, row); } @SuppressWarnings("unchecked") private void translateToColumnList(OWNER entity, RowToPersist row) { Collection<PROXY> values = (Collection<PROXY>) ReflectionUtil.fetchFieldValue(entity, field); Collection<PROXY> toBeAdded = values; //all values in the list get added if not an OurAbstractCollection Collection<PROXY> toBeRemoved = new ArrayList<PROXY>(); if(values instanceof OurAbstractCollection) { OurAbstractCollection<PROXY> coll = (OurAbstractCollection<PROXY>)values; toBeRemoved = coll.getToBeRemoved(); toBeAdded = coll.getToBeAdded(); } translateToColumnImpl(toBeAdded, row, toBeRemoved); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void translateToColumnMap(OWNER entity, RowToPersist row) { Map mapOfProxies = (Map) ReflectionUtil.fetchFieldValue(entity, field); Collection<PROXY> toBeAdded = mapOfProxies.values(); Collection<PROXY> toBeRemoved = new ArrayList<PROXY>(); if(mapOfProxies instanceof MapProxyFetchAll) { MapProxyFetchAll mapProxy = (MapProxyFetchAll) mapOfProxies; toBeRemoved = mapProxy.getToBeRemoved(); toBeAdded = mapProxy.getToBeAdded(); } translateToColumnImpl(toBeAdded, row, toBeRemoved); } private void translateToColumnImpl(Collection<PROXY> toBeAdded, RowToPersist row, Collection<PROXY> toBeRemoved) { //removes first for(PROXY p : toBeRemoved) { byte[] name = formTheName(p); row.addEntityToRemove(name); } //now process all the existing columns (we can add same entity as many times as we like and it does not //get duplicated) if (toBeAdded != null) { for(PROXY proxy : toBeAdded) { byte[] name = formTheName(proxy); Column c = new Column(); c.setName(name); row.getColumns().add(c); } } } private byte[] formTheName(PROXY p) { byte[] pkData = translateOne(p); return formTheNameImpl(columnName, pkData); } static byte[] formTheNameImpl(String colName, byte[] postFix) { byte[] prefix = StandardConverters.convertToBytes(colName); byte[] name = new byte[prefix.length + postFix.length]; for(int i = 0; i < name.length; i++) { if(i < prefix.length) name[i] = prefix[i]; else name[i] = postFix[i-prefix.length]; } return name; } private byte[] translateOne(PROXY proxy) { byte[] byteVal = classMeta.convertEntityToId(proxy); if(byteVal == null) { String owner = "'"+field.getDeclaringClass().getSimpleName()+"'"; String child = "'"+classMeta.getMetaClass().getSimpleName()+"'"; String fieldName = "'"+field.getType().getSimpleName()+" "+field.getName()+"'"; throw new ChildWithNoPkException("The entity you are saving of type="+owner+" has a field="+fieldName +" which has an entity in the collection that does not yet have a primary key so you cannot save it. \n" + "The offending object is="+proxy+" To correct this\n" + "problem, you can either\n" +"1. SAVE the "+child+" BEFORE you save the "+owner+" OR\n" +"2. Call entityManager.fillInWithKey(Object entity), then SAVE your "+owner+"', then save your "+child+" NOTE that this" + "\nmethod #2 is used for when you have a bi-directional relationship where each is a child of the other"); } return byteVal; } public void setup(DboTableMeta tableMeta, Field field, String colName, MetaAbstractClass<PROXY> classMeta, Field fieldForKey) { DboTableMeta fkToTable = classMeta.getMetaDbo(); metaDbo.setup(tableMeta, colName, fkToTable, false); super.setup(field, colName); this.classMeta = classMeta; this.fieldForKey = fieldForKey; } @Override public String toString() { return "MetaListField [field='" + field.getDeclaringClass().getName()+"."+field.getName()+"(field type=" +field.getType().getName() + "<"+classMeta.getMetaClass().getName()+">), columnName=" + columnName + "]"; } @Override public byte[] translateValue(Object value) { throw new UnsupportedOperationException("Bug, this operation shold never be called for lists"); } @Override protected Object unwrapIfNeeded(Object value) { throw new UnsupportedOperationException("Bug, this should never be called"); } @Override public void removingEntity(InfoForIndex<OWNER> info, List<IndexData> indexRemoves, byte[] rowKey) { throw new UnsupportedOperationException("Bug, this should never be called"); } }
package co.phoenixlab.discord; import co.phoenixlab.common.localization.Localizer; import co.phoenixlab.discord.api.entities.Message; import co.phoenixlab.discord.stats.RunningAverage; import org.slf4j.Logger; import java.util.HashMap; import java.util.Map; import java.util.StringJoiner; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.LongAdder; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; public class CommandDispatcher { private static final Logger LOGGER = VahrhedralBot.LOGGER; private final VahrhedralBot bot; private final Map<String, CommandWrapper> commands; private AtomicBoolean active; private String commandPrefix; private final Statistics statistics; public CommandDispatcher(VahrhedralBot bot, String commandPrefix) { this.bot = bot; this.commandPrefix = commandPrefix; active = new AtomicBoolean(true); commands = new HashMap<>(); statistics = new Statistics(); addHelpCommand(); } public String getCommandPrefix() { return commandPrefix; } public void setCommandPrefix(String commandPrefix) { this.commandPrefix = commandPrefix; } private void addHelpCommand() { Command helpCommand = (context, args) -> { Localizer l = context.getBot().getLocalizer(); String header = l.localize("commands.help.response.head", commands.size()); StringJoiner joiner = new StringJoiner("\n", header, ""); for (Map.Entry<String, CommandWrapper> entry : commands.entrySet()) { joiner.add(l.localize("commands.help.response.entry", commandPrefix, entry.getKey(), entry.getValue().helpDesc)); } final String result = joiner.toString(); context.getBot().getApiClient().sendMessage(result, context.getMessage().getChannelId()); }; registerCommand("commands.help.command", helpCommand, "commands.help.help"); } public void registerCommand(String commandNameKey, Command command, String descKey) { commandNameKey = bot.getLocalizer().localize(commandNameKey); descKey = bot.getLocalizer().localize(descKey); commands.put(commandNameKey, new CommandWrapper(command, descKey)); LOGGER.debug("Registered command \"{}\"", commandNameKey); } public void registerAlwaysActiveCommand(String commandNameKey, Command command, String descKey) { commandNameKey = bot.getLocalizer().localize(commandNameKey); descKey = bot.getLocalizer().localize(descKey); commands.put(commandNameKey, new CommandWrapper(command, descKey, true)); LOGGER.debug("Registered command \"{}\"", commandNameKey); } public void handleCommand(Message msg) { long cmdStartTime = System.nanoTime(); try { statistics.commandsReceived.increment(); String content = msg.getContent(); LOGGER.info("Received command {} from {} ({})", content, msg.getAuthor().getUsername(), msg.getAuthor().getId()); // Remove prefix String noPrefix = content.substring(commandPrefix.length()); // Split String[] split = noPrefix.split(" ", 2); if (split.length == 0) { // Invalid command LOGGER.info("Invalid command ignored: {}", content); statistics.commandsRejected.increment(); return; } String cmd = split[0]; String args = (split.length > 1 ? split[1] : "").trim(); CommandWrapper wrapper = commands.get(cmd); if (wrapper != null) { if (active.get() || wrapper.alwaysActive) { // Blacklist check if (!bot.getConfig().getBlacklist().contains(msg.getAuthor().getId())) { LOGGER.debug("Dispatching command {}", cmd); long handleStartTime = System.nanoTime(); wrapper.command.handleCommand(new MessageContext(msg, bot, this), args); statistics.acceptedCommandHandleTime. add(MILLISECONDS.convert(System.nanoTime() - handleStartTime, NANOSECONDS)); statistics.commandsHandledSuccessfully.increment(); return; } } } else { LOGGER.info("Unknown command \"{}\"", cmd); } statistics.commandsRejected.increment(); } finally { statistics.commandHandleTime.add(MILLISECONDS.convert(System.nanoTime() - cmdStartTime, NANOSECONDS)); } } public Statistics getStatistics() { return statistics; } public AtomicBoolean active() { return active; } public static class Statistics { public final RunningAverage acceptedCommandHandleTime; public final RunningAverage commandHandleTime; public final LongAdder commandsReceived; public final LongAdder commandsHandledSuccessfully; public final LongAdder commandsRejected; Statistics() { acceptedCommandHandleTime = new RunningAverage(); commandHandleTime = new RunningAverage(); commandsReceived = new LongAdder(); commandsHandledSuccessfully = new LongAdder(); commandsRejected = new LongAdder(); } } } class CommandWrapper { final Command command; final String helpDesc; final boolean alwaysActive; public CommandWrapper(Command command, String helpDesc) { this(command, helpDesc, false); } public CommandWrapper(Command command, String helpDesc, boolean alwaysActive) { this.command = command; this.helpDesc = helpDesc; this.alwaysActive = alwaysActive; } }
package com.adik993.tpbclient.proxy.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Proxy { private String domain; private float speed; private boolean secure; private String country; private boolean probed; }
package com.blogspot.nurkiewicz.lazyseq; import java.util.*; import java.util.function.*; import java.util.stream.Collector; import java.util.stream.Stream; /** * @author Tomasz Nurkiewicz * @since 5/6/13, 9:20 PM */ public abstract class LazySeq<E> extends AbstractList<E> { private static final LazySeq<?> NIL = new Nil<>(); public abstract E head(); public Optional<E> headOption() { return Optional.of(head()); } public abstract LazySeq<E> tail(); public static <E> LazySeq<E> of(E element) { return cons(element, empty()); } public static <E> LazySeq<E> of(E element1, E element2, E element3) { return cons(element1, of(element2, element3)); } public static <E> LazySeq<E> of(E element1, E element2, E element3, Supplier<LazySeq<E>> tailFun) { return cons(element1, of(element2, element3, tailFun)); } public static <E> LazySeq<E> of(E element1, E element2, Supplier<LazySeq<E>> tailFun) { return cons(element1, of(element2, tailFun)); } public static <E> LazySeq<E> of(E element, Supplier<LazySeq<E>> tailFun) { return cons(element, tailFun); } public static <E> LazySeq<E> of(E element1, E element2) { return cons(element1, of(element2)); } public static <E> LazySeq<E> of(E... elements) { return of(Arrays.asList(elements).iterator()); } public static <E> LazySeq<E> of(Iterable<E> elements) { return of(elements.iterator()); } public static <E> LazySeq<E> concat(Iterable<E> elements, Supplier<LazySeq<E>> tailFun) { return concat(elements.iterator(), tailFun); } public static <E> LazySeq<E> concat(Iterable<E> elements, LazySeq<E> tail) { return concat(elements.iterator(), tail); } public static <E> LazySeq<E> concat(Iterator<E> iterator, LazySeq<E> tail) { if (iterator.hasNext()) { return concatNonEmptyIterator(iterator, tail); } else { return tail; } } private static <E> LazySeq<E> concatNonEmptyIterator(Iterator<E> iterator, LazySeq<E> tail) { final E next = iterator.next(); if (iterator.hasNext()) { return cons(next, concatNonEmptyIterator(iterator, tail)); } else { return cons(next, tail); } } public static <E> LazySeq<E> concat(Iterator<E> iterator, Supplier<LazySeq<E>> tailFun) { if (iterator.hasNext()) { return concatNonEmptyIterator(iterator, tailFun); } else { return tailFun.get(); } } private static <E> LazySeq<E> concatNonEmptyIterator(Iterator<E> iterator, Supplier<LazySeq<E>> tailFun) { final E next = iterator.next(); if (iterator.hasNext()) { return cons(next, concatNonEmptyIterator(iterator, tailFun)); } else { return cons(next, tailFun); } } public static <E> LazySeq<E> of(Iterator<E> iterator) { if (iterator.hasNext()) { return cons(iterator.next(), of(iterator)); } else { return empty(); } } public static <E> LazySeq<E> cons(E head, Supplier<LazySeq<E>> tailFun) { return new Cons<>(head, tailFun); } public static <E> LazySeq<E> cons(E head, LazySeq<E> tail) { return new FixedCons<>(head, tail); } @SuppressWarnings("unchecked") public static <E> LazySeq<E> empty() { return (LazySeq<E>) NIL; } public static <E> LazySeq<E> iterate(E initial, Function<E, E> fun) { return new Cons<>(initial, () -> iterate(fun.apply(initial), fun)); } public static <E> Collector<E, LazySeq<E>> toLazySeq() { return DummyLazySeqCollector.getInstance(); } public static <E> LazySeq<E> tabulate(int start, Function<Integer, E> generator) { return cons(generator.apply(start), () -> tabulate(start + 1, generator)); } public static <E> LazySeq<E> continually(Supplier<E> generator) { return cons(generator.get(), () -> continually(generator)); } public static <E> LazySeq<E> constant(E value) { return cons(value, () -> constant(value)); } protected abstract boolean isTailDefined(); @Override public E get(final int index) { if (index < 0) { throw new IndexOutOfBoundsException(Integer.toString(index)); } LazySeq<E> cur = this; for (int curIdx = index; curIdx > 0; --curIdx) { if (cur.tail().isEmpty()) { throw new IndexOutOfBoundsException(Integer.toString(index)); } cur = cur.tail(); } return cur.head(); } public abstract <R> LazySeq<R> map(Function<? super E, ? extends R> mapper); @Override public Stream<E> stream() { return new LazySeqStream<E>(this); } @Override public String toString() { final StringBuilder s = new StringBuilder("["); LazySeq<E> cur = this; while (!cur.isEmpty()) { s.append(cur.head()); if (cur.isTailDefined()) { if (!cur.tail().isEmpty()) { s.append(", "); } cur = cur.tail(); } else { s.append(", ?"); break; } } return s.append("]").toString(); } public abstract LazySeq<E> filter(Predicate<? super E> predicate); public abstract <R> LazySeq<R> flatMap(Function<? super E, ? extends Iterable<? extends R>> mapper); public LazySeq<E> limit(long maxSize) { return take(maxSize); } /** * Converts this {@link LazySeq} to immutable {@link List}. * * Notice that this method will eventually fail at runtime when called on infinite sequence. * @return {@link List} of all elements in this lazy sequence. */ public List<E> toList() { return Collections.unmodifiableList(this); } public LazySeq<E> take(long maxSize) { if (maxSize < 0) { throw new IllegalArgumentException(Long.toString(maxSize)); } return takeUnsafe(maxSize); } protected abstract LazySeq<E> takeUnsafe(long maxSize); public LazySeq<E> drop(long startInclusive) { if (startInclusive < 0) { throw new IllegalArgumentException(Long.toString(startInclusive)); } return dropUnsafe(startInclusive); } protected LazySeq<E> dropUnsafe(long startInclusive) { if (startInclusive > 0) { return tail().drop(startInclusive - 1); } else { return this; } } public LazySeq<E> slice(long startInclusive, long endExclusive) { if (startInclusive < 0 || startInclusive > endExclusive) { throw new IllegalArgumentException("slice(" + startInclusive + ", " + endExclusive + ")"); } return dropUnsafe(startInclusive).takeUnsafe(endExclusive - startInclusive); } public void forEach(Consumer<? super E> action) { action.accept(head()); tail().forEach(action); } public E reduce(E identity, BinaryOperator<E> accumulator) { E result = identity; LazySeq<E> cur = this; while (!cur.isEmpty()) { result = accumulator.apply(result, cur.head()); cur = cur.tail(); } return result; } public Optional<E> reduce(BinaryOperator<E> accumulator) { if (isEmpty() || tail().isEmpty()) { return Optional.empty(); } return Optional.of(tail().reduce(head(), accumulator)); } public <U> U reduce(U identity, BiFunction<U, ? super E, U> accumulator) { U result = identity; LazySeq<E> cur = this; while (!cur.isEmpty()) { result = accumulator.apply(result, cur.head()); cur = cur.tail(); } return result; } public <C extends Comparable<? super C>> Optional<E> maxBy(Function<E, C> propertyFun) { return max(propertyFunToComparator(propertyFun)); } public Optional<E> max(Comparator<? super E> comparator) { return greatestByComparator(comparator); } public <C extends Comparable<? super C>> Optional<E> minBy(Function<E, C> propertyFun) { return min(propertyFunToComparator(propertyFun)); } public Optional<E> min(Comparator<? super E> comparator) { return greatestByComparator(comparator.reverseOrder()); } private <C extends Comparable<? super C>> Comparator<? super E> propertyFunToComparator(Function<E, C> propertyFun) { return (a, b) -> { final C aProperty = propertyFun.apply(a); final C bProperty = propertyFun.apply(b); return aProperty.compareTo(bProperty); }; } private Optional<E> greatestByComparator(Comparator<? super E> comparator) { if (tail().isEmpty()) { return Optional.of(head()); } E minSoFar = head(); LazySeq<E> cur = this.tail(); while (!cur.isEmpty()) { minSoFar = maxByComparator(minSoFar, cur.head(), comparator); cur = cur.tail(); } return Optional.of(minSoFar); } private static <E> E maxByComparator(E first, E second, Comparator<? super E> comparator) { return comparator.compare(first, second) >= 0? first : second; } @Override public int size() { return 1 + tail().size(); } @Override public Iterator<E> iterator() { return new LazySeqIterator<E>(this); } public boolean anyMatch(Predicate<? super E> predicate) { return predicate.test(head()) || tail().anyMatch(predicate); } public boolean allMatch(Predicate<? super E> predicate) { return predicate.test(head()) && tail().allMatch(predicate); } public boolean noneMatch(Predicate<? super E> predicate) { return allMatch(predicate.negate()); } public <S, R> LazySeq<R> zip(LazySeq<? extends S> second, BiFunction<? super E, ? super S, ? extends R> zipper) { if (second.isEmpty()) { return empty(); } else { final R headsZipped = zipper.apply(head(), second.head()); return cons(headsZipped, () -> tail().zip(second.tail(), zipper)); } } public LazySeq<E> takeWhile(Predicate<? super E> predicate) { if (predicate.test(head())) { return cons(head(), () -> tail().takeWhile(predicate)); } else { return empty(); } } public LazySeq<E> dropWhile(Predicate<? super E> predicate) { if (predicate.test(head())) { return tail().dropWhile(predicate); } else { return this; } } public LazySeq<List<E>> sliding(int size) { if (size <= 0) { throw new IllegalArgumentException(Integer.toString(size)); } return slidingUnsafe(size); } protected LazySeq<List<E>> slidingUnsafe(int size) { final List<E> window = take(size).toList(); return cons(window, () -> tail().slidingFullOnly(size)); } protected LazySeq<List<E>> slidingFullOnly(int size) { final List<E> window = take(size).toList(); if (window.size() < size) { return empty(); } else { return cons(window, () -> tail().slidingFullOnly(size)); } } public LazySeq<List<E>> grouped(int size) { if (size <= 0) { throw new IllegalArgumentException(Integer.toString(size)); } return groupedUnsafe(size); } protected LazySeq<List<E>> groupedUnsafe(int size) { final List<E> window = take(size).toList(); return cons(window, () -> drop(size).groupedUnsafe(size)); } public LazySeq<E> scan(E initial, BinaryOperator<E> fun) { return cons(initial, () -> tail().scan(fun.apply(initial, head()), fun)); } }
package com.codegame.codeseries.notreal2d; import com.codeforces.commons.geometry.Point2D; import com.codeforces.commons.geometry.Vector2D; import com.codeforces.commons.math.NumberUtil; import com.codeforces.commons.pair.LongPair; import com.codeforces.commons.process.ThreadUtil; import com.codegame.codeseries.notreal2d.bodylist.BodyList; import com.codegame.codeseries.notreal2d.bodylist.SimpleBodyList; import com.codegame.codeseries.notreal2d.collision.*; import com.codegame.codeseries.notreal2d.listener.CollisionListener; import com.codegame.codeseries.notreal2d.provider.MomentumTransferFactorProvider; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.log4j.Level; import org.apache.log4j.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static com.codeforces.commons.math.Math.*; @SuppressWarnings("WeakerAccess") public class World { private static final Logger logger = Logger.getLogger(World.class); @SuppressWarnings("ConstantConditions") private static final CollisionInfo NULL_COLLISION_INFO = new CollisionInfo(null, null, null, null, 0.0D, 0.0D); /** * The only supported value is 2. */ private static final int PARALLEL_THREAD_COUNT = 2; private final int iterationCountPerStep; private final int stepCountPerTimeUnit; private final double updateFactor; private final double epsilon; private final double squaredEpsilon; private final BodyList bodyList; private final MomentumTransferFactorProvider momentumTransferFactorProvider; @Nullable private final ExecutorService parallelTaskExecutor; private final Map<String, ColliderEntry> colliderEntryByName = new HashMap<>(); private final SortedSet<ColliderEntry> colliderEntries = new TreeSet<>(ColliderEntry.comparator); private final Map<String, CollisionListenerEntry> collisionListenerEntryByName = new HashMap<>(); private final SortedSet<CollisionListenerEntry> collisionListenerEntries = new TreeSet<>(CollisionListenerEntry.comparator); public World() { this(Defaults.ITERATION_COUNT_PER_STEP); } public World(int iterationCountPerStep) { this(iterationCountPerStep, Defaults.STEP_COUNT_PER_TIME_UNIT); } public World(int iterationCountPerStep, int stepCountPerTimeUnit) { this(iterationCountPerStep, stepCountPerTimeUnit, Defaults.EPSILON); } public World(int iterationCountPerStep, int stepCountPerTimeUnit, double epsilon) { this(iterationCountPerStep, stepCountPerTimeUnit, epsilon, new SimpleBodyList()); } public World(int iterationCountPerStep, int stepCountPerTimeUnit, double epsilon, BodyList bodyList) { this(iterationCountPerStep, stepCountPerTimeUnit, epsilon, bodyList, null); } public World(int iterationCountPerStep, int stepCountPerTimeUnit, double epsilon, BodyList bodyList, @Nullable MomentumTransferFactorProvider momentumTransferFactorProvider) { this(iterationCountPerStep, stepCountPerTimeUnit, epsilon, bodyList, momentumTransferFactorProvider, false); } public World(int iterationCountPerStep, int stepCountPerTimeUnit, double epsilon, BodyList bodyList, @Nullable MomentumTransferFactorProvider momentumTransferFactorProvider, boolean multithreaded) { if (iterationCountPerStep < 1) { throw new IllegalArgumentException("Argument 'iterationCountPerStep' is zero or negative."); } if (stepCountPerTimeUnit < 1) { throw new IllegalArgumentException("Argument 'stepCountPerTimeUnit' is zero or negative."); } if (Double.isNaN(epsilon) || Double.isInfinite(epsilon) || epsilon < 1.0E-100D || epsilon > 1.0D) { throw new IllegalArgumentException("Argument 'epsilon' should be between 1.0E-100 and 1.0."); } if (bodyList == null) { throw new IllegalArgumentException("Argument 'bodyList' is null."); } this.stepCountPerTimeUnit = stepCountPerTimeUnit; this.iterationCountPerStep = iterationCountPerStep; this.updateFactor = 1.0D / (stepCountPerTimeUnit * iterationCountPerStep); this.epsilon = epsilon; this.squaredEpsilon = epsilon * epsilon; this.bodyList = bodyList; this.momentumTransferFactorProvider = momentumTransferFactorProvider; this.parallelTaskExecutor = multithreaded ? new ThreadPoolExecutor( 0, PARALLEL_THREAD_COUNT - 1, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadFactory() { private final AtomicInteger threadIndex = new AtomicInteger(); @Override public Thread newThread(@Nonnull Runnable runnable) { return ThreadUtil.newThread( "notreal2d.World#ParallelExecutionThread-" + threadIndex.incrementAndGet(), runnable, (t, e) -> logger.error("Can't complete parallel task in thread '" + t + "'.", e), true ); } } ) : null; registerCollider(new ArcAndArcCollider(epsilon)); registerCollider(new ArcAndCircleCollider(epsilon)); registerCollider(new CircleAndCircleCollider(epsilon)); registerCollider(new LineAndArcCollider(epsilon)); registerCollider(new LineAndCircleCollider(epsilon)); registerCollider(new LineAndLineCollider(epsilon)); registerCollider(new LineAndRectangleCollider(epsilon)); registerCollider(new RectangleAndArcCollider(epsilon)); registerCollider(new RectangleAndCircleCollider(epsilon)); registerCollider(new RectangleAndRectangleCollider(epsilon)); } public int getIterationCountPerStep() { return iterationCountPerStep; } public int getStepCountPerTimeUnit() { return stepCountPerTimeUnit; } public double getEpsilon() { return epsilon; } public void addBody(@Nonnull Body body) { if (body.getForm() == null || body.getMass() == 0.0D) { throw new IllegalArgumentException("Specify form and mass of 'body' before adding to the world."); } bodyList.addBody(body); } public void removeBody(@Nonnull Body body) { bodyList.removeBody(body); } public void removeBody(long id) { bodyList.removeBody(id); } public void removeBodyQuietly(@Nullable Body body) { bodyList.removeBodyQuietly(body); } public void removeBodyQuietly(long id) { bodyList.removeBodyQuietly(id); } public boolean hasBody(@Nonnull Body body) { return bodyList.hasBody(body); } public boolean hasBody(long id) { return bodyList.hasBody(id); } public Body getBody(long id) { return bodyList.getBody(id); } public boolean isColliding(@Nonnull Body body) { return getCollisionInfo(body) != null; } public List<Body> getBodies() { return bodyList.getBodies(); } @Nullable public CollisionInfo getCollisionInfo(@Nonnull Body body) { if (!bodyList.hasBody(body)) { return null; } for (Body otherBody : bodyList.getPotentialIntersections(body)) { if (body.isStatic() && otherBody.isStatic()) { continue; } for (ColliderEntry colliderEntry : colliderEntries) { if (colliderEntry.collider.matches(body, otherBody)) { return colliderEntry.collider.collide(body, otherBody); } } } return null; } @Nonnull public List<CollisionInfo> getCollisionInfos(@Nonnull Body body) { if (!bodyList.hasBody(body)) { return Collections.emptyList(); } List<CollisionInfo> collisionInfos = new ArrayList<>(); for (Body otherBody : bodyList.getPotentialIntersections(body)) { if (body.isStatic() && otherBody.isStatic()) { continue; } for (ColliderEntry colliderEntry : colliderEntries) { if (colliderEntry.collider.matches(body, otherBody)) { CollisionInfo collisionInfo = colliderEntry.collider.collide(body, otherBody); if (collisionInfo != null) { collisionInfos.add(collisionInfo); } break; } } } return Collections.unmodifiableList(collisionInfos); } @SuppressWarnings("ForLoopWithMissingComponent") public void proceed() { Collection<Body> bodyCollection = getBodies(); int bodyCount = bodyCollection.size(); Body[] bodies = bodyCollection.toArray(new Body[bodyCount]); if (bodyCount < 1000 || parallelTaskExecutor == null) { beforeStep(bodies, 0, bodyCount); for (int i = iterationCountPerStep; --i >= 0; ) { beforeIteration(bodies, 0, bodyCount); processIteration(bodies); } afterStep(bodies, 0, bodyCount); } else { int middleIndex = bodyCount / PARALLEL_THREAD_COUNT; Future<?> parallelTask = parallelTaskExecutor.submit(() -> beforeStep(bodies, 0, middleIndex)); beforeStep(bodies, middleIndex, bodyCount); awaitParallelTask(parallelTask); for (int i = iterationCountPerStep; --i >= 0; ) { parallelTask = parallelTaskExecutor.submit(() -> beforeIteration(bodies, 0, middleIndex)); beforeIteration(bodies, middleIndex, bodyCount); awaitParallelTask(parallelTask); processIteration(bodies); } parallelTask = parallelTaskExecutor.submit(() -> afterStep(bodies, 0, middleIndex)); afterStep(bodies, middleIndex, bodyCount); awaitParallelTask(parallelTask); } } private static void awaitParallelTask(@Nonnull Future<?> parallelTask) { try { parallelTask.get(5L, TimeUnit.MINUTES); } catch (InterruptedException e) { parallelTask.cancel(true); logger.error("Thread has been interrupted while executing parallel task.", e); throw new RuntimeException("Thread has been interrupted while executing parallel task.", e); } catch (ExecutionException e) { parallelTask.cancel(true); logger.error("Thread has failed while executing parallel task.", e); throw new RuntimeException("Thread has failed while executing parallel task.", e); } catch (TimeoutException e) { parallelTask.cancel(true); logger.error("Thread has timed out while executing parallel task.", e); throw new RuntimeException("Thread has timed out while executing parallel task.", e); } } private void beforeStep(@Nonnull Body[] bodies, int leftIndex, int rightIndex) { for (int bodyIndex = leftIndex; bodyIndex < rightIndex; ++bodyIndex) { Body body = bodies[bodyIndex]; if (!hasBody(body)) { continue; } body.normalizeAngle(); body.saveBeforeStepState(); } } private void beforeIteration(@Nonnull Body[] bodies, int leftIndex, int rightIndex) { for (int bodyIndex = leftIndex; bodyIndex < rightIndex; ++bodyIndex) { Body body = bodies[bodyIndex]; if (!hasBody(body)) { continue; } body.saveBeforeIterationState(); updateState(body); body.normalizeAngle(); } } private void processIteration(@Nonnull Body[] bodies) { Map<LongPair, CollisionInfo> collisionInfoByBodyIdsPair = new HashMap<>(); for (int bodyIndex = 0, bodyCount = bodies.length; bodyIndex < bodyCount; ++bodyIndex) { Body body = bodies[bodyIndex]; if (body.isStatic() || !hasBody(body)) { continue; } for (Body otherBody : bodyList.getPotentialIntersections(body)) { if (!hasBody(body)) { break; } if (hasBody(otherBody)) { collide(body, otherBody, collisionInfoByBodyIdsPair); } } } } private void afterStep(@Nonnull Body[] bodies, int leftIndex, int rightIndex) { for (int bodyIndex = leftIndex; bodyIndex < rightIndex; ++bodyIndex) { Body body = bodies[bodyIndex]; if (!hasBody(body)) { continue; } body.setForce(0.0D, 0.0D); body.setTorque(0.0D); } } private void collide(@Nonnull Body body, @Nonnull Body otherBody, @Nonnull Map<LongPair, CollisionInfo> collisionInfoByBodyIdsPair) { Body bodyA; Body bodyB; if (body.getId() > otherBody.getId()) { bodyA = otherBody; bodyB = body; } else { bodyA = body; bodyB = otherBody; } LongPair bodyIdsPair = new LongPair(bodyA.getId(), bodyB.getId()); CollisionInfo collisionInfo = collisionInfoByBodyIdsPair.get(bodyIdsPair); if (collisionInfo != null) { return; } for (CollisionListenerEntry collisionListenerEntry : collisionListenerEntries) { if (!collisionListenerEntry.listener.beforeStartingCollision(bodyA, bodyB)) { collisionInfoByBodyIdsPair.put(bodyIdsPair, NULL_COLLISION_INFO); return; } if (!hasBody(bodyA) || !hasBody(bodyB)) { return; } } for (ColliderEntry colliderEntry : colliderEntries) { if (colliderEntry.collider.matches(bodyA, bodyB)) { collisionInfo = colliderEntry.collider.collide(bodyA, bodyB); break; } } if (collisionInfo == null) { collisionInfoByBodyIdsPair.put(bodyIdsPair, NULL_COLLISION_INFO); } else { collisionInfoByBodyIdsPair.put(bodyIdsPair, collisionInfo); resolveCollision(collisionInfo); } } private void resolveCollision(@Nonnull CollisionInfo collisionInfo) { Body bodyA = collisionInfo.getBodyA(); Body bodyB = collisionInfo.getBodyB(); if (bodyA.isStatic() && bodyB.isStatic()) { throw new IllegalArgumentException("Both " + bodyA + " and " + bodyB + " are static."); } for (CollisionListenerEntry collisionListenerEntry : collisionListenerEntries) { if (!collisionListenerEntry.listener.beforeResolvingCollision(collisionInfo)) { return; } if (!hasBody(bodyA) || !hasBody(bodyB)) { return; } } logCollision(collisionInfo); Vector3D collisionNormalB = toVector3D(collisionInfo.getNormalB()); Vector3D vectorAC = toVector3D(bodyA.getCenterOfMass(), collisionInfo.getPoint()); Vector3D vectorBC = toVector3D(bodyB.getCenterOfMass(), collisionInfo.getPoint()); Vector3D angularVelocityPartAC = toVector3DZ(bodyA.getAngularVelocity()).crossProduct(vectorAC); Vector3D angularVelocityPartBC = toVector3DZ(bodyB.getAngularVelocity()).crossProduct(vectorBC); Vector3D velocityAC = toVector3D(bodyA.getVelocity()).add(angularVelocityPartAC); Vector3D velocityBC = toVector3D(bodyB.getVelocity()).add(angularVelocityPartBC); Vector3D relativeVelocityC = velocityAC.subtract(velocityBC); double normalRelativeVelocityLengthC = -relativeVelocityC.dotProduct(collisionNormalB); if (normalRelativeVelocityLengthC > -epsilon) { resolveImpact(bodyA, bodyB, collisionNormalB, vectorAC, vectorBC, relativeVelocityC); resolveSurfaceFriction(bodyA, bodyB, collisionNormalB, vectorAC, vectorBC, relativeVelocityC); } if (collisionInfo.getDepth() >= epsilon) { pushBackBodies(bodyA, bodyB, collisionInfo); } bodyA.normalizeAngle(); bodyB.normalizeAngle(); for (CollisionListenerEntry collisionListenerEntry : collisionListenerEntries) { collisionListenerEntry.listener.afterResolvingCollision(collisionInfo); } } @SuppressWarnings("Duplicates") private void resolveImpact( @Nonnull Body bodyA, @Nonnull Body bodyB, @Nonnull Vector3D collisionNormalB, @Nonnull Vector3D vectorAC, @Nonnull Vector3D vectorBC, @Nonnull Vector3D relativeVelocityC) { Double momentumTransferFactor; if (momentumTransferFactorProvider == null || (momentumTransferFactor = momentumTransferFactorProvider.getFactor(bodyA, bodyB)) == null) { momentumTransferFactor = bodyA.getMomentumTransferFactor() * bodyB.getMomentumTransferFactor(); } Vector3D denominatorPartA = vectorAC.crossProduct(collisionNormalB) .scalarMultiply(bodyA.getInvertedAngularMass()).crossProduct(vectorAC); Vector3D denominatorPartB = vectorBC.crossProduct(collisionNormalB) .scalarMultiply(bodyB.getInvertedAngularMass()).crossProduct(vectorBC); double denominator = bodyA.getInvertedMass() + bodyB.getInvertedMass() + collisionNormalB.dotProduct(denominatorPartA.add(denominatorPartB)); double impulseChange = -1.0D * (1.0D + momentumTransferFactor) * relativeVelocityC.dotProduct(collisionNormalB) / denominator; if (abs(impulseChange) < epsilon) { return; } if (!bodyA.isStatic()) { Vector3D velocityChangeA = collisionNormalB.scalarMultiply(impulseChange * bodyA.getInvertedMass()); Vector3D newVelocityA = toVector3D(bodyA.getVelocity()).add(velocityChangeA); bodyA.setVelocity(newVelocityA.getX(), newVelocityA.getY()); Vector3D angularVelocityChangeA = vectorAC.crossProduct(collisionNormalB.scalarMultiply(impulseChange)) .scalarMultiply(bodyA.getInvertedAngularMass()); Vector3D newAngularVelocityA = toVector3DZ(bodyA.getAngularVelocity()).add(angularVelocityChangeA); bodyA.setAngularVelocity(newAngularVelocityA.getZ()); } if (!bodyB.isStatic()) { Vector3D velocityChangeB = collisionNormalB.scalarMultiply(impulseChange * bodyB.getInvertedMass()); Vector3D newVelocityB = toVector3D(bodyB.getVelocity()).subtract(velocityChangeB); bodyB.setVelocity(newVelocityB.getX(), newVelocityB.getY()); Vector3D angularVelocityChangeB = vectorBC.crossProduct(collisionNormalB.scalarMultiply(impulseChange)) .scalarMultiply(bodyB.getInvertedAngularMass()); Vector3D newAngularVelocityB = toVector3DZ(bodyB.getAngularVelocity()).subtract(angularVelocityChangeB); bodyB.setAngularVelocity(newAngularVelocityB.getZ()); } } @SuppressWarnings("Duplicates") private void resolveSurfaceFriction( @Nonnull Body bodyA, @Nonnull Body bodyB, @Nonnull Vector3D collisionNormalB, @Nonnull Vector3D vectorAC, @Nonnull Vector3D vectorBC, @Nonnull Vector3D relativeVelocityC) { Vector3D tangent = relativeVelocityC .subtract(collisionNormalB.scalarMultiply(relativeVelocityC.dotProduct(collisionNormalB))); if (tangent.getNormSq() < squaredEpsilon) { return; } tangent = tangent.normalize(); double surfaceFriction = sqrt(bodyA.getSurfaceFrictionFactor() * bodyB.getSurfaceFrictionFactor()) * SQRT_2 * abs(relativeVelocityC.dotProduct(collisionNormalB)) / relativeVelocityC.getNorm(); if (surfaceFriction < epsilon) { return; } Vector3D denominatorPartA = vectorAC.crossProduct(tangent) .scalarMultiply(bodyA.getInvertedAngularMass()).crossProduct(vectorAC); Vector3D denominatorPartB = vectorBC.crossProduct(tangent) .scalarMultiply(bodyB.getInvertedAngularMass()).crossProduct(vectorBC); double denominator = bodyA.getInvertedMass() + bodyB.getInvertedMass() + tangent.dotProduct(denominatorPartA.add(denominatorPartB)); double impulseChange = -1.0D * surfaceFriction * relativeVelocityC.dotProduct(tangent) / denominator; if (abs(impulseChange) < epsilon) { return; } if (!bodyA.isStatic()) { Vector3D velocityChangeA = tangent.scalarMultiply(impulseChange * bodyA.getInvertedMass()); Vector3D newVelocityA = toVector3D(bodyA.getVelocity()).add(velocityChangeA); bodyA.setVelocity(newVelocityA.getX(), newVelocityA.getY()); Vector3D angularVelocityChangeA = vectorAC.crossProduct(tangent.scalarMultiply(impulseChange)) .scalarMultiply(bodyA.getInvertedAngularMass()); Vector3D newAngularVelocityA = toVector3DZ(bodyA.getAngularVelocity()).add(angularVelocityChangeA); bodyA.setAngularVelocity(newAngularVelocityA.getZ()); } if (!bodyB.isStatic()) { Vector3D velocityChangeB = tangent.scalarMultiply(impulseChange * bodyB.getInvertedMass()); Vector3D newVelocityB = toVector3D(bodyB.getVelocity()).subtract(velocityChangeB); bodyB.setVelocity(newVelocityB.getX(), newVelocityB.getY()); Vector3D angularVelocityChangeB = vectorBC.crossProduct(tangent.scalarMultiply(impulseChange)) .scalarMultiply(bodyB.getInvertedAngularMass()); Vector3D newAngularVelocityB = toVector3DZ(bodyB.getAngularVelocity()).subtract(angularVelocityChangeB); bodyB.setAngularVelocity(newAngularVelocityB.getZ()); } } private void updateState(@Nonnull Body body) { updatePosition(body); updateAngle(body); } private void updatePosition(@Nonnull Body body) { if (body.getVelocity().getSquaredLength() > 0.0D) { body.getPosition().add(body.getVelocity().copy().multiply(updateFactor)); } if (body.getForce().getSquaredLength() > 0.0D) { body.getVelocity().add(body.getForce().copy().multiply(body.getInvertedMass()).multiply(updateFactor)); } if (body.getMovementAirFrictionFactor() >= 1.0D) { body.setVelocity(body.getMedianVelocity().copy()); } else if (body.getMovementAirFrictionFactor() > 0.0D) { body.applyMovementAirFriction(updateFactor); if (body.getVelocity().nearlyEquals(body.getMedianVelocity(), epsilon)) { body.setVelocity(body.getMedianVelocity().copy()); } } body.getVelocity().subtract(body.getMedianVelocity()); body.applyFriction(updateFactor); body.getVelocity().add(body.getMedianVelocity()); } private void updateAngle(@Nonnull Body body) { body.setAngle(body.getAngle() + body.getAngularVelocity() * updateFactor); body.setAngularVelocity( body.getAngularVelocity() + body.getTorque() * body.getInvertedAngularMass() * updateFactor ); if (body.getRotationAirFrictionFactor() >= 1.0D) { body.setAngularVelocity(body.getMedianAngularVelocity()); } else if (body.getRotationAirFrictionFactor() > 0.0D) { body.applyRotationAirFriction(updateFactor); if (NumberUtil.nearlyEquals(body.getAngularVelocity(), body.getMedianAngularVelocity(), epsilon)) { body.setAngularVelocity(body.getMedianAngularVelocity()); } } double angularVelocity = body.getAngularVelocity() - body.getMedianAngularVelocity(); if (abs(angularVelocity) > 0.0D) { double rotationFrictionFactor = body.getRotationFrictionFactor() * updateFactor; if (rotationFrictionFactor >= abs(angularVelocity)) { body.setAngularVelocity(body.getMedianAngularVelocity()); } else if (rotationFrictionFactor > 0.0D) { if (angularVelocity > 0.0D) { body.setAngularVelocity(angularVelocity - rotationFrictionFactor + body.getMedianAngularVelocity()); } else { body.setAngularVelocity(angularVelocity + rotationFrictionFactor + body.getMedianAngularVelocity()); } } } } private void pushBackBodies(@Nonnull Body bodyA, @Nonnull Body bodyB, @Nonnull CollisionInfo collisionInfo) { if (bodyA.isStatic()) { bodyB.getPosition().subtract(collisionInfo.getNormalB().multiply(collisionInfo.getDepth() + epsilon)); } else if (bodyB.isStatic()) { bodyA.getPosition().add(collisionInfo.getNormalB().multiply(collisionInfo.getDepth() + epsilon)); } else { Vector2D normalOffset = collisionInfo.getNormalB().multiply(0.5D * (collisionInfo.getDepth() + epsilon)); bodyA.getPosition().add(normalOffset); bodyB.getPosition().subtract(normalOffset); } } public void registerCollider(@Nonnull Collider collider, @Nonnull String name, double priority) { NamedEntry.validateName(name); if (colliderEntryByName.containsKey(name)) { throw new IllegalArgumentException("Collider '" + name + "' is already registered."); } ColliderEntry colliderEntry = new ColliderEntry(name, priority, collider); colliderEntryByName.put(name, colliderEntry); colliderEntries.add(colliderEntry); } public void registerCollider(@Nonnull Collider collider, @Nonnull String name) { registerCollider(collider, name, 0.0D); } private void registerCollider(@Nonnull Collider collider) { registerCollider(collider, collider.getClass().getSimpleName()); } public void unregisterCollider(@Nonnull String name) { NamedEntry.validateName(name); ColliderEntry colliderEntry = colliderEntryByName.remove(name); if (colliderEntry == null) { throw new IllegalArgumentException("Collider '" + name + "' is not registered."); } colliderEntries.remove(colliderEntry); } public boolean hasCollider(@Nonnull String name) { NamedEntry.validateName(name); return colliderEntryByName.containsKey(name); } public void registerCollisionListener(@Nonnull CollisionListener listener, @Nonnull String name, double priority) { NamedEntry.validateName(name); if (collisionListenerEntryByName.containsKey(name)) { throw new IllegalArgumentException("Listener '" + name + "' is already registered."); } CollisionListenerEntry collisionListenerEntry = new CollisionListenerEntry(name, priority, listener); collisionListenerEntryByName.put(name, collisionListenerEntry); collisionListenerEntries.add(collisionListenerEntry); } public void registerCollisionListener(@Nonnull CollisionListener listener, @Nonnull String name) { registerCollisionListener(listener, name, 0.0D); } private void registerCollisionListener(@Nonnull CollisionListener listener) { registerCollisionListener(listener, listener.getClass().getSimpleName()); } public void unregisterCollisionListener(@Nonnull String name) { NamedEntry.validateName(name); CollisionListenerEntry collisionListenerEntry = collisionListenerEntryByName.remove(name); if (collisionListenerEntry == null) { throw new IllegalArgumentException("Listener '" + name + "' is not registered."); } collisionListenerEntries.remove(collisionListenerEntry); } public boolean hasCollisionListener(@Nonnull String name) { NamedEntry.validateName(name); return collisionListenerEntryByName.containsKey(name); } private static void logCollision(CollisionInfo collisionInfo) { if (collisionInfo.getDepth() >= collisionInfo.getBodyA().getForm().getCircumcircleRadius() * 0.25D || collisionInfo.getDepth() >= collisionInfo.getBodyB().getForm().getCircumcircleRadius() * 0.25D) { if (logger.isEnabledFor(Level.WARN)) { logger.warn("Resolving collision (big depth) " + collisionInfo + '.'); } } else { if (logger.isDebugEnabled()) { logger.debug("Resolving collision " + collisionInfo + '.'); } } } @Nonnull private static Vector3D toVector3DZ(double z) { return new Vector3D(0.0D, 0.0D, z); } @Nonnull private static Vector3D toVector3D(@Nonnull Vector2D vector) { return new Vector3D(vector.getX(), vector.getY(), 0.0D); } @Nonnull private static Vector3D toVector3D(@Nonnull Point2D point1, @Nonnull Point2D point2) { return toVector3D(new Vector2D(point1, point2)); } @SuppressWarnings("PublicField") private static final class ColliderEntry extends NamedEntry { private static final Comparator<ColliderEntry> comparator = (colliderEntryA, colliderEntryB) -> { int comparisonResult = Double.compare(colliderEntryB.priority, colliderEntryA.priority); if (comparisonResult != 0) { return comparisonResult; } return colliderEntryA.name.compareTo(colliderEntryB.name); }; public final double priority; public final Collider collider; private ColliderEntry(String name, double priority, Collider collider) { super(name); this.priority = priority; this.collider = collider; } } @SuppressWarnings("PublicField") private static final class CollisionListenerEntry extends NamedEntry { private static final Comparator<CollisionListenerEntry> comparator = (listenerEntryA, listenerEntryB) -> { int comparisonResult = Double.compare(listenerEntryB.priority, listenerEntryA.priority); if (comparisonResult != 0) { return comparisonResult; } return listenerEntryA.name.compareTo(listenerEntryB.name); }; public final double priority; public final CollisionListener listener; private CollisionListenerEntry(String name, double priority, CollisionListener listener) { super(name); this.priority = priority; this.listener = listener; } } }
package com.codegame.codeseries.notreal2d; import com.codeforces.commons.geometry.Point2D; import com.codeforces.commons.geometry.Vector2D; import com.codeforces.commons.math.NumberUtil; import com.codeforces.commons.pair.LongPair; import com.codegame.codeseries.notreal2d.bodylist.BodyList; import com.codegame.codeseries.notreal2d.bodylist.SimpleBodyList; import com.codegame.codeseries.notreal2d.collision.*; import com.codegame.codeseries.notreal2d.listener.CollisionListener; import com.codegame.codeseries.notreal2d.provider.MomentumTransferFactorProvider; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.log4j.Level; import org.apache.log4j.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import static com.codeforces.commons.math.Math.*; public class World { private static final Logger logger = Logger.getLogger(World.class); @SuppressWarnings("ConstantConditions") private static final CollisionInfo NULL_COLLISION_INFO = new CollisionInfo(null, null, null, null, 0.0D, 0.0D); private final int iterationCountPerStep; private final int stepCountPerTimeUnit; private final double updateFactor; private final double epsilon; private final double squaredEpsilon; private final BodyList bodyList; private final MomentumTransferFactorProvider momentumTransferFactorProvider; private final Map<String, ColliderEntry> colliderEntryByName = new HashMap<>(); private final SortedSet<ColliderEntry> colliderEntries = new TreeSet<>(ColliderEntry.comparator); private final Map<String, CollisionListenerEntry> collisionListenerEntryByName = new HashMap<>(); private final SortedSet<CollisionListenerEntry> collisionListenerEntries = new TreeSet<>(CollisionListenerEntry.comparator); public World() { this(Defaults.ITERATION_COUNT_PER_STEP); } public World(int iterationCountPerStep) { this(iterationCountPerStep, Defaults.STEP_COUNT_PER_TIME_UNIT); } public World(int iterationCountPerStep, int stepCountPerTimeUnit) { this(iterationCountPerStep, stepCountPerTimeUnit, Defaults.EPSILON); } public World(int iterationCountPerStep, int stepCountPerTimeUnit, double epsilon) { this(iterationCountPerStep, stepCountPerTimeUnit, epsilon, new SimpleBodyList()); } public World(int iterationCountPerStep, int stepCountPerTimeUnit, double epsilon, BodyList bodyList) { this(iterationCountPerStep, stepCountPerTimeUnit, epsilon, bodyList, null); } public World(int iterationCountPerStep, int stepCountPerTimeUnit, double epsilon, BodyList bodyList, @Nullable MomentumTransferFactorProvider momentumTransferFactorProvider) { if (iterationCountPerStep < 1) { throw new IllegalArgumentException("Argument 'iterationCountPerStep' is zero or negative."); } if (stepCountPerTimeUnit < 1) { throw new IllegalArgumentException("Argument 'stepCountPerTimeUnit' is zero or negative."); } if (Double.isNaN(epsilon) || Double.isInfinite(epsilon) || epsilon < 1.0E-100D || epsilon > 1.0D) { throw new IllegalArgumentException("Argument 'epsilon' should be between 1.0E-100 and 1.0."); } if (bodyList == null) { throw new IllegalArgumentException("Argument 'bodyList' is null."); } this.stepCountPerTimeUnit = stepCountPerTimeUnit; this.iterationCountPerStep = iterationCountPerStep; this.updateFactor = 1.0D / (stepCountPerTimeUnit * iterationCountPerStep); this.epsilon = epsilon; this.squaredEpsilon = epsilon * epsilon; this.bodyList = bodyList; this.momentumTransferFactorProvider = momentumTransferFactorProvider; registerCollider(new ArcAndArcCollider(epsilon)); registerCollider(new ArcAndCircleCollider(epsilon)); registerCollider(new CircleAndCircleCollider(epsilon)); registerCollider(new LineAndArcCollider(epsilon)); registerCollider(new LineAndCircleCollider(epsilon)); registerCollider(new LineAndLineCollider(epsilon)); registerCollider(new LineAndRectangleCollider(epsilon)); registerCollider(new RectangleAndArcCollider(epsilon)); registerCollider(new RectangleAndCircleCollider(epsilon)); registerCollider(new RectangleAndRectangleCollider(epsilon)); } public int getIterationCountPerStep() { return iterationCountPerStep; } public int getStepCountPerTimeUnit() { return stepCountPerTimeUnit; } public double getEpsilon() { return epsilon; } public void addBody(@Nonnull Body body) { if (body.getForm() == null || body.getMass() == 0.0D) { throw new IllegalArgumentException("Specify form and mass of 'body' before adding to the world."); } bodyList.addBody(body); } public void removeBody(@Nonnull Body body) { bodyList.removeBody(body); } public void removeBody(long id) { bodyList.removeBody(id); } public void removeBodyQuietly(@Nullable Body body) { bodyList.removeBodyQuietly(body); } public void removeBodyQuietly(long id) { bodyList.removeBodyQuietly(id); } public boolean hasBody(@Nonnull Body body) { return bodyList.hasBody(body); } public boolean hasBody(long id) { return bodyList.hasBody(id); } public Body getBody(long id) { return bodyList.getBody(id); } public boolean isColliding(@Nonnull Body body) { return getCollisionInfo(body) != null; } public List<Body> getBodies() { return bodyList.getBodies(); } @Nullable public CollisionInfo getCollisionInfo(@Nonnull Body body) { if (!bodyList.hasBody(body)) { return null; } for (Body otherBody : bodyList.getPotentialIntersections(body)) { if (body.isStatic() && otherBody.isStatic()) { continue; } for (ColliderEntry colliderEntry : colliderEntries) { if (colliderEntry.collider.matches(body, otherBody)) { return colliderEntry.collider.collide(body, otherBody); } } } return null; } public void proceed() { List<Body> bodies = new ArrayList<>(getBodies()); for (Body body : bodies) { if (!hasBody(body)) { continue; } body.normalizeAngle(); body.saveBeforeStepState(); } for (int i = 1; i <= iterationCountPerStep; ++i) { for (Body body : bodies) { if (!hasBody(body)) { continue; } body.saveBeforeIterationState(); updateState(body); body.normalizeAngle(); } Map<LongPair, CollisionInfo> collisionInfoByBodyIdsPair = new HashMap<>(); for (Body body : bodies) { if (body.isStatic() || !hasBody(body)) { continue; } for (Body otherBody : bodyList.getPotentialIntersections(body)) { if (hasBody(body) && hasBody(otherBody)) { collide(body, otherBody, collisionInfoByBodyIdsPair); } } } } for (Body body : bodies) { if (!hasBody(body)) { continue; } body.setForce(0.0D, 0.0D); body.setTorque(0.0D); } } private void collide(@Nonnull Body body, @Nonnull Body otherBody, @Nonnull Map<LongPair, CollisionInfo> collisionInfoByBodyIdsPair) { Body bodyA; Body bodyB; if (body.getId() > otherBody.getId()) { bodyA = otherBody; bodyB = body; } else { bodyA = body; bodyB = otherBody; } LongPair bodyIdsPair = new LongPair(bodyA.getId(), bodyB.getId()); CollisionInfo collisionInfo = collisionInfoByBodyIdsPair.get(bodyIdsPair); if (collisionInfo != null) { return; } for (CollisionListenerEntry collisionListenerEntry : collisionListenerEntries) { if (!collisionListenerEntry.listener.beforeStartingCollision(bodyA, bodyB)) { collisionInfoByBodyIdsPair.put(bodyIdsPair, NULL_COLLISION_INFO); return; } if (!hasBody(bodyA) || !hasBody(bodyB)) { return; } } for (ColliderEntry colliderEntry : colliderEntries) { if (colliderEntry.collider.matches(bodyA, bodyB)) { collisionInfo = colliderEntry.collider.collide(bodyA, bodyB); break; } } if (collisionInfo == null) { collisionInfoByBodyIdsPair.put(bodyIdsPair, NULL_COLLISION_INFO); } else { collisionInfoByBodyIdsPair.put(bodyIdsPair, collisionInfo); resolveCollision(collisionInfo); } } private void resolveCollision(@Nonnull CollisionInfo collisionInfo) { Body bodyA = collisionInfo.getBodyA(); Body bodyB = collisionInfo.getBodyB(); if (bodyA.isStatic() && bodyB.isStatic()) { throw new IllegalArgumentException("Both " + bodyA + " and " + bodyB + " are static."); } for (CollisionListenerEntry collisionListenerEntry : collisionListenerEntries) { if (!collisionListenerEntry.listener.beforeResolvingCollision(collisionInfo)) { return; } if (!hasBody(bodyA) || !hasBody(bodyB)) { return; } } logCollision(collisionInfo); Vector3D collisionNormalB = toVector3D(collisionInfo.getNormalB()); Vector3D vectorAC = toVector3D(bodyA.getCenterOfMass(), collisionInfo.getPoint()); Vector3D vectorBC = toVector3D(bodyB.getCenterOfMass(), collisionInfo.getPoint()); Vector3D angularVelocityPartAC = toVector3DZ(bodyA.getAngularVelocity()).crossProduct(vectorAC); Vector3D angularVelocityPartBC = toVector3DZ(bodyB.getAngularVelocity()).crossProduct(vectorBC); Vector3D velocityAC = toVector3D(bodyA.getVelocity()).add(angularVelocityPartAC); Vector3D velocityBC = toVector3D(bodyB.getVelocity()).add(angularVelocityPartBC); Vector3D relativeVelocityC = velocityAC.subtract(velocityBC); double normalRelativeVelocityLengthC = -relativeVelocityC.dotProduct(collisionNormalB); if (normalRelativeVelocityLengthC > -epsilon) { resolveImpact(bodyA, bodyB, collisionNormalB, vectorAC, vectorBC, relativeVelocityC); resolveSurfaceFriction(bodyA, bodyB, collisionNormalB, vectorAC, vectorBC, relativeVelocityC); } if (collisionInfo.getDepth() >= epsilon) { pushBackBodies(bodyA, bodyB, collisionInfo); } bodyA.normalizeAngle(); bodyB.normalizeAngle(); for (CollisionListenerEntry collisionListenerEntry : collisionListenerEntries) { collisionListenerEntry.listener.afterResolvingCollision(collisionInfo); } } private void resolveImpact( @Nonnull Body bodyA, @Nonnull Body bodyB, @Nonnull Vector3D collisionNormalB, @Nonnull Vector3D vectorAC, @Nonnull Vector3D vectorBC, @Nonnull Vector3D relativeVelocityC) { Double momentumTransferFactor; if (momentumTransferFactorProvider == null || (momentumTransferFactor = momentumTransferFactorProvider.getFactor(bodyA, bodyB)) == null) { momentumTransferFactor = bodyA.getMomentumTransferFactor() * bodyB.getMomentumTransferFactor(); } Vector3D denominatorPartA = vectorAC.crossProduct(collisionNormalB) .scalarMultiply(bodyA.getInvertedAngularMass()).crossProduct(vectorAC); Vector3D denominatorPartB = vectorBC.crossProduct(collisionNormalB) .scalarMultiply(bodyB.getInvertedAngularMass()).crossProduct(vectorBC); double denominator = bodyA.getInvertedMass() + bodyB.getInvertedMass() + collisionNormalB.dotProduct(denominatorPartA.add(denominatorPartB)); double impulseChange = -1.0D * (1.0D + momentumTransferFactor) * relativeVelocityC.dotProduct(collisionNormalB) / denominator; if (abs(impulseChange) < epsilon) { return; } if (!bodyA.isStatic()) { Vector3D velocityChangeA = collisionNormalB.scalarMultiply(impulseChange * bodyA.getInvertedMass()); Vector3D newVelocityA = toVector3D(bodyA.getVelocity()).add(velocityChangeA); bodyA.setVelocity(newVelocityA.getX(), newVelocityA.getY()); Vector3D angularVelocityChangeA = vectorAC.crossProduct(collisionNormalB.scalarMultiply(impulseChange)) .scalarMultiply(bodyA.getInvertedAngularMass()); Vector3D newAngularVelocityA = toVector3DZ(bodyA.getAngularVelocity()).add(angularVelocityChangeA); bodyA.setAngularVelocity(newAngularVelocityA.getZ()); } if (!bodyB.isStatic()) { Vector3D velocityChangeB = collisionNormalB.scalarMultiply(impulseChange * bodyB.getInvertedMass()); Vector3D newVelocityB = toVector3D(bodyB.getVelocity()).subtract(velocityChangeB); bodyB.setVelocity(newVelocityB.getX(), newVelocityB.getY()); Vector3D angularVelocityChangeB = vectorBC.crossProduct(collisionNormalB.scalarMultiply(impulseChange)) .scalarMultiply(bodyB.getInvertedAngularMass()); Vector3D newAngularVelocityB = toVector3DZ(bodyB.getAngularVelocity()).subtract(angularVelocityChangeB); bodyB.setAngularVelocity(newAngularVelocityB.getZ()); } } private void resolveSurfaceFriction( @Nonnull Body bodyA, @Nonnull Body bodyB, @Nonnull Vector3D collisionNormalB, @Nonnull Vector3D vectorAC, @Nonnull Vector3D vectorBC, @Nonnull Vector3D relativeVelocityC) { Vector3D tangent = relativeVelocityC .subtract(collisionNormalB.scalarMultiply(relativeVelocityC.dotProduct(collisionNormalB))); if (tangent.getNormSq() < squaredEpsilon) { return; } tangent = tangent.normalize(); double surfaceFriction = sqrt(bodyA.getSurfaceFrictionFactor() * bodyB.getSurfaceFrictionFactor()) * SQRT_2 * abs(relativeVelocityC.dotProduct(collisionNormalB)) / relativeVelocityC.getNorm(); if (surfaceFriction < epsilon) { return; } Vector3D denominatorPartA = vectorAC.crossProduct(tangent) .scalarMultiply(bodyA.getInvertedAngularMass()).crossProduct(vectorAC); Vector3D denominatorPartB = vectorBC.crossProduct(tangent) .scalarMultiply(bodyB.getInvertedAngularMass()).crossProduct(vectorBC); double denominator = bodyA.getInvertedMass() + bodyB.getInvertedMass() + tangent.dotProduct(denominatorPartA.add(denominatorPartB)); double impulseChange = -1.0D * surfaceFriction * relativeVelocityC.dotProduct(tangent) / denominator; if (abs(impulseChange) < epsilon) { return; } if (!bodyA.isStatic()) { Vector3D velocityChangeA = tangent.scalarMultiply(impulseChange * bodyA.getInvertedMass()); Vector3D newVelocityA = toVector3D(bodyA.getVelocity()).add(velocityChangeA); bodyA.setVelocity(newVelocityA.getX(), newVelocityA.getY()); Vector3D angularVelocityChangeA = vectorAC.crossProduct(tangent.scalarMultiply(impulseChange)) .scalarMultiply(bodyA.getInvertedAngularMass()); Vector3D newAngularVelocityA = toVector3DZ(bodyA.getAngularVelocity()).add(angularVelocityChangeA); bodyA.setAngularVelocity(newAngularVelocityA.getZ()); } if (!bodyB.isStatic()) { Vector3D velocityChangeB = tangent.scalarMultiply(impulseChange * bodyB.getInvertedMass()); Vector3D newVelocityB = toVector3D(bodyB.getVelocity()).subtract(velocityChangeB); bodyB.setVelocity(newVelocityB.getX(), newVelocityB.getY()); Vector3D angularVelocityChangeB = vectorBC.crossProduct(tangent.scalarMultiply(impulseChange)) .scalarMultiply(bodyB.getInvertedAngularMass()); Vector3D newAngularVelocityB = toVector3DZ(bodyB.getAngularVelocity()).subtract(angularVelocityChangeB); bodyB.setAngularVelocity(newAngularVelocityB.getZ()); } } private void updateState(@Nonnull Body body) { updatePosition(body); updateAngle(body); } private void updatePosition(@Nonnull Body body) { if (body.getVelocity().getSquaredLength() > 0.0D) { body.getPosition().add(body.getVelocity().copy().multiply(updateFactor)); } if (body.getForce().getSquaredLength() > 0.0D) { body.getVelocity().add(body.getForce().copy().multiply(body.getInvertedMass()).multiply(updateFactor)); } if (body.getMovementAirFrictionFactor() >= 1.0D) { body.setVelocity(body.getMedianVelocity().copy()); } else if (body.getMovementAirFrictionFactor() > 0.0D) { body.applyMovementAirFriction(updateFactor); if (body.getVelocity().nearlyEquals(body.getMedianVelocity(), epsilon)) { body.setVelocity(body.getMedianVelocity().copy()); } } body.getVelocity().subtract(body.getMedianVelocity()); body.applyFriction(updateFactor); body.getVelocity().add(body.getMedianVelocity()); } private void updateAngle(@Nonnull Body body) { body.setAngle(body.getAngle() + body.getAngularVelocity() * updateFactor); body.setAngularVelocity( body.getAngularVelocity() + body.getTorque() * body.getInvertedAngularMass() * updateFactor ); if (body.getRotationAirFrictionFactor() >= 1.0D) { body.setAngularVelocity(body.getMedianAngularVelocity()); } else if (body.getRotationAirFrictionFactor() > 0.0D) { body.applyRotationAirFriction(updateFactor); if (NumberUtil.nearlyEquals(body.getAngularVelocity(), body.getMedianAngularVelocity(), epsilon)) { body.setAngularVelocity(body.getMedianAngularVelocity()); } } double angularVelocity = body.getAngularVelocity() - body.getMedianAngularVelocity(); if (abs(angularVelocity) > 0.0D) { double rotationFrictionFactor = body.getRotationFrictionFactor() * updateFactor; if (rotationFrictionFactor >= abs(angularVelocity)) { body.setAngularVelocity(body.getMedianAngularVelocity()); } else if (rotationFrictionFactor > 0.0D) { if (angularVelocity > 0.0D) { body.setAngularVelocity(angularVelocity - rotationFrictionFactor + body.getMedianAngularVelocity()); } else { body.setAngularVelocity(angularVelocity + rotationFrictionFactor + body.getMedianAngularVelocity()); } } } } private void pushBackBodies(@Nonnull Body bodyA, @Nonnull Body bodyB, @Nonnull CollisionInfo collisionInfo) { if (bodyA.isStatic()) { bodyB.getPosition().subtract(collisionInfo.getNormalB().multiply(collisionInfo.getDepth() + epsilon)); } else if (bodyB.isStatic()) { bodyA.getPosition().add(collisionInfo.getNormalB().multiply(collisionInfo.getDepth() + epsilon)); } else { Vector2D normalOffset = collisionInfo.getNormalB().multiply(0.5D * (collisionInfo.getDepth() + epsilon)); bodyA.getPosition().add(normalOffset); bodyB.getPosition().subtract(normalOffset); } } public void registerCollider(@Nonnull Collider collider, @Nonnull String name, double priority) { NamedEntry.validateName(name); if (colliderEntryByName.containsKey(name)) { throw new IllegalArgumentException("Collider '" + name + "' is already registered."); } ColliderEntry colliderEntry = new ColliderEntry(name, priority, collider); colliderEntryByName.put(name, colliderEntry); colliderEntries.add(colliderEntry); } public void registerCollider(@Nonnull Collider collider, @Nonnull String name) { registerCollider(collider, name, 0.0D); } private void registerCollider(@Nonnull Collider collider) { registerCollider(collider, collider.getClass().getSimpleName()); } public void unregisterCollider(@Nonnull String name) { NamedEntry.validateName(name); ColliderEntry colliderEntry = colliderEntryByName.remove(name); if (colliderEntry == null) { throw new IllegalArgumentException("Collider '" + name + "' is not registered."); } colliderEntries.remove(colliderEntry); } public boolean hasCollider(@Nonnull String name) { NamedEntry.validateName(name); return colliderEntryByName.containsKey(name); } public void registerCollisionListener(@Nonnull CollisionListener listener, @Nonnull String name, double priority) { NamedEntry.validateName(name); if (collisionListenerEntryByName.containsKey(name)) { throw new IllegalArgumentException("Listener '" + name + "' is already registered."); } CollisionListenerEntry collisionListenerEntry = new CollisionListenerEntry(name, priority, listener); collisionListenerEntryByName.put(name, collisionListenerEntry); collisionListenerEntries.add(collisionListenerEntry); } public void registerCollisionListener(@Nonnull CollisionListener listener, @Nonnull String name) { registerCollisionListener(listener, name, 0.0D); } private void registerCollisionListener(@Nonnull CollisionListener listener) { registerCollisionListener(listener, listener.getClass().getSimpleName()); } public void unregisterCollisionListener(@Nonnull String name) { NamedEntry.validateName(name); CollisionListenerEntry collisionListenerEntry = collisionListenerEntryByName.remove(name); if (collisionListenerEntry == null) { throw new IllegalArgumentException("Listener '" + name + "' is not registered."); } collisionListenerEntries.remove(collisionListenerEntry); } public boolean hasCollisionListener(@Nonnull String name) { NamedEntry.validateName(name); return collisionListenerEntryByName.containsKey(name); } private static void logCollision(CollisionInfo collisionInfo) { if (collisionInfo.getDepth() >= collisionInfo.getBodyA().getForm().getCircumcircleRadius() * 0.25D || collisionInfo.getDepth() >= collisionInfo.getBodyB().getForm().getCircumcircleRadius() * 0.25D) { if (logger.isEnabledFor(Level.WARN)) { logger.warn("Resolving collision (big depth) " + collisionInfo + '.'); } } else { if (logger.isDebugEnabled()) { logger.debug("Resolving collision " + collisionInfo + '.'); } } } @Nonnull private static Vector3D toVector3DZ(double z) { return new Vector3D(0.0D, 0.0D, z); } @Nonnull private static Vector3D toVector3D(@Nonnull Vector2D vector) { return new Vector3D(vector.getX(), vector.getY(), 0.0D); } @Nonnull private static Vector3D toVector3D(@Nonnull Point2D point1, @Nonnull Point2D point2) { return toVector3D(new Vector2D(point1, point2)); } @SuppressWarnings("PublicField") private static final class ColliderEntry extends NamedEntry { private static final Comparator<ColliderEntry> comparator = new Comparator<ColliderEntry>() { @Override public int compare(ColliderEntry colliderEntryA, ColliderEntry colliderEntryB) { int comparisonResult = Double.compare(colliderEntryB.priority, colliderEntryA.priority); if (comparisonResult != 0) { return comparisonResult; } return colliderEntryA.name.compareTo(colliderEntryB.name); } }; public final double priority; public final Collider collider; private ColliderEntry(String name, double priority, Collider collider) { super(name); this.priority = priority; this.collider = collider; } } @SuppressWarnings("PublicField") private static final class CollisionListenerEntry extends NamedEntry { private static final Comparator<CollisionListenerEntry> comparator = new Comparator<CollisionListenerEntry>() { @Override public int compare(CollisionListenerEntry listenerEntryA, CollisionListenerEntry listenerEntryB) { int comparisonResult = Double.compare(listenerEntryB.priority, listenerEntryA.priority); if (comparisonResult != 0) { return comparisonResult; } return listenerEntryA.name.compareTo(listenerEntryB.name); } }; public final double priority; public final CollisionListener listener; private CollisionListenerEntry(String name, double priority, CollisionListener listener) { super(name); this.priority = priority; this.listener = listener; } } }
package com.demonwav.mcdev.update; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.plugins.PluginManagerMain; import com.intellij.ide.plugins.PluginNode; import com.intellij.ide.plugins.RepositoryHelper; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.updateSettings.impl.PluginDownloader; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.io.HttpRequests; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.net.URLEncoder; import java.util.List; import java.util.function.Function; public class PluginUpdater { private static final PluginUpdater instance = new PluginUpdater(); public static PluginUpdater getInstance() { return instance; } public void runUpdateCheck(final Function<PluginUpdateStatus, Boolean> callback) { ApplicationManager.getApplication().executeOnPooledThread(() -> updateCheck(callback)); } private void updateCheck(Function<PluginUpdateStatus, Boolean> callback) { PluginUpdateStatus updateStatus; try { updateStatus = checkUpdatesInMainRepo(); for (String host : RepositoryHelper.getPluginHosts()) { if (host == null) { continue; } updateStatus = updateStatus.mergeWith(checkUpdatesInCustomRepo(host)); } final PluginUpdateStatus finalUpdate = updateStatus; ApplicationManager.getApplication().invokeLater(() -> callback.apply(finalUpdate), ModalityState.current()); } catch (Exception e) { PluginUpdateStatus.fromException("Minecraft Development plugin update check failed", e); } } private PluginUpdateStatus checkUpdatesInMainRepo() throws IOException { final String buildNumber = ApplicationInfo.getInstance().getBuild().asString(); final String currentVersion = PluginUtil.getPluginVersion(); final String os = URLEncoder.encode(SystemInfo.OS_NAME + " " + SystemInfo.OS_VERSION, CharsetToolkit.UTF8); final String url = "https://plugins.jetbrains.com/plugins/list?pluginId=8327&build=" + buildNumber + "&pluginVersion=" + currentVersion + "&os=" + os; final Element responseDoc = HttpRequests.request(url).connect(request -> { try { return JDOMUtil.load(request.getInputStream()); } catch (JDOMException e) { e.printStackTrace(); } return null; }); if (responseDoc == null) { return new PluginUpdateStatus.CheckFailed("Unexpected plugin repository response", null); } if (!responseDoc.getName().equals("plugin-repository")) { return new PluginUpdateStatus.CheckFailed("Unexpected plugin repository response", JDOMUtil.writeElement(responseDoc, "\n")); } if (responseDoc.getChildren().isEmpty()) { return new PluginUpdateStatus.LatestVersionInstalled(); } String newVersion; try { newVersion = responseDoc.getChild("category").getChild("idea-plugin").getChild("version").getText(); } catch (NullPointerException e) { // Okay, look, hate me all you want for catching a NPE, but I don't have a null-safe propagation operator in Java // and I really don't feel like checking every one of those calls... newVersion = null; } if (newVersion == null) { return new PluginUpdateStatus.CheckFailed("Couldn't find plugin version in repository response", JDOMUtil.writeElement(responseDoc, "\n")); } final IdeaPluginDescriptor plugin = PluginManager.getPlugin(PluginUtil.PLUGIN_ID); assert plugin != null; final PluginNode pluginNode = new PluginNode(PluginUtil.PLUGIN_ID); pluginNode.setVersion(newVersion); pluginNode.setName(plugin.getName()); pluginNode.setDescription(plugin.getDescription()); if (pluginNode.getVersion().equals(PluginUtil.getPluginVersion())) { return new PluginUpdateStatus.LatestVersionInstalled(); } return new PluginUpdateStatus.Update(pluginNode, null); } private PluginUpdateStatus checkUpdatesInCustomRepo(String host) { final List<IdeaPluginDescriptor> plugins; try { plugins = RepositoryHelper.loadPlugins(host, null); } catch (IOException e) { return PluginUpdateStatus.fromException("Checking custom plugin repository " + host + " failed", e); } final IdeaPluginDescriptor minecraftPlugin = plugins.stream() .filter(plugin -> plugin.getPluginId().equals(PluginUtil.PLUGIN_ID)) .findFirst().orElse(null); // Effectively remove isEmpty call if (minecraftPlugin == null) { return new PluginUpdateStatus.LatestVersionInstalled(); } return updateIfNotLatest(minecraftPlugin, host); } private PluginUpdateStatus updateIfNotLatest(IdeaPluginDescriptor plugin, String host) { if (plugin.getVersion().equals(PluginUtil.getPluginVersion())) { return new PluginUpdateStatus.LatestVersionInstalled(); } return new PluginUpdateStatus.Update(plugin, host); } public void installPluginUpdate(PluginUpdateStatus.Update update) throws IOException { final IdeaPluginDescriptor plugin = update.getPluginDescriptor(); final PluginDownloader downloader = PluginDownloader.createDownloader(plugin, update.getHostToInstallFrom(), null); ProgressManager.getInstance().run(new Task.Backgroundable(null, "Downloading Plugin", true) { @Override public void run(@NotNull ProgressIndicator indicator) { try { if (downloader.prepareToInstall(indicator)) { final IdeaPluginDescriptor descriptor = downloader.getDescriptor(); if (descriptor != null) { downloader.install(); ApplicationManager.getApplication().invokeLater(() -> PluginManagerMain.notifyPluginsUpdated(null)); } } } catch (IOException e) { e.printStackTrace(); } } }); } }
// ETConfiguration.java - package com.exacttarget.fuelsdk; import java.io.IOException; import java.util.Properties; public class ETConfiguration { private static final String DEFAULT_FILE_NAME = "/fuelsdk.properties"; private String endpoint = null; private String authEndpoint = null; private String soapEndpoint = null; private String clientId = null; private String clientSecret = null; public ETConfiguration() throws ETSdkException { this(DEFAULT_FILE_NAME); } public ETConfiguration(String file) throws ETSdkException { if (file == null) { file = DEFAULT_FILE_NAME; } Properties properties = new Properties(); try { properties.load(getClass().getResourceAsStream(file)); } catch (IOException ex) { throw new ETSdkException("error opening " + file, ex); } endpoint = properties.getProperty("endpoint"); authEndpoint = properties.getProperty("authEndpoint"); soapEndpoint = properties.getProperty("soapEndpoint"); clientId = properties.getProperty("clientId"); clientSecret = properties.getProperty("clientSecret"); } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public String getAuthEndpoint() { return authEndpoint; } public void setAuthEndpoint(String authEndpoint) { this.authEndpoint = authEndpoint; } public String getSoapEndpoint() { return soapEndpoint; } public void setSoapEndpoint(String soapEndpoint) { this.soapEndpoint = soapEndpoint; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } }
package com.extrahardmode.task; import com.extrahardmode.ExtraHardMode; import com.extrahardmode.config.RootConfig; import com.extrahardmode.config.RootNode; import com.extrahardmode.module.DataStoreModule; import com.extrahardmode.module.EntityHelper; import com.extrahardmode.module.PlayerModule; import com.extrahardmode.service.Feature; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.AbstractMap.SimpleEntry; /** * Task to spawn more monsters, especially in light. */ public class MoreMonstersTask implements Runnable { //TODO Return to this and make it actually spawn and not just take the old locations //TODO if block not valid check random block nearby /** * Plugin instance. */ private final ExtraHardMode plugin; /** * Config instanz */ private final RootConfig CFG; private final PlayerModule playerModule; /** * Constructor. * * @param plugin - Plugin instance. */ public MoreMonstersTask(ExtraHardMode plugin) { this.plugin = plugin; CFG = plugin.getModuleForClass(RootConfig.class); playerModule = plugin.getModuleForClass(PlayerModule.class); } @Override public void run() { DataStoreModule dataStore = plugin.getModuleForClass(DataStoreModule.class); // spawn monsters from the last pass for (SimpleEntry<Player, Location> entry : dataStore.getPreviousLocations()) { Location location = entry.getValue(); World world = location.getWorld(); try { location = verifyLocation(location); if (location != null && location.getChunk().isLoaded()) {// spawn random monster(s) if (world.getEnvironment() == Environment.NORMAL && !EntityHelper.arePlayersNearby(location, 16.0)) { Entity mob = EntityHelper.spawnRandomMob(location); EntityHelper.markAsOurs(plugin, mob); } } } catch (IllegalArgumentException ignored) { } // in case the player is in a different world from the saved location } // plan for the next pass dataStore.getPreviousLocations().clear(); for (Player player : plugin.getServer().getOnlinePlayers()) { Location verifiedLocation = null; //only if player hasn't got bypass and is in survival check location if (!playerModule.playerBypasses(player, Feature.MONSTERRULES)) verifiedLocation = verifyLocation(player.getLocation()); if (verifiedLocation != null) dataStore.getPreviousLocations().add(new SimpleEntry<Player, Location>(player, verifiedLocation)); } } //TODO move this into a utility class /** * Tests if a a given location is elligible to be spawned on * * @return a valid Location or null if the location is invalid */ private Location verifyLocation(Location location) { World world = location.getWorld(); Location verifiedLoc = null; final int maxY = CFG.getInt(RootNode.MONSTER_SPAWNS_IN_LIGHT_MAX_Y, world.getName()); // Only spawn monsters in normal world. End is crowded with endermen and nether is too extreme anyway, add config later int lightLvl = location.getBlock().getLightFromSky(); if (world.getEnvironment() == World.Environment.NORMAL && (location.getY() < maxY && lightLvl < 3)) verifiedLoc = EntityHelper.isLocSafeSpawn(location); return verifiedLoc; } }
package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.swig.*; import com.frostwire.jlibtorrent.swig.torrent_handle.status_flags_t; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * You will usually have to store your torrent handles somewhere, since it's * the object through which you retrieve information about the torrent and * aborts the torrent. * <p/> * .. warning:: * Any member function that returns a value or fills in a value has to be * made synchronously. This means it has to wait for the main thread to * complete the query before it can return. This might potentially be * expensive if done from within a GUI thread that needs to stay * responsive. Try to avoid quering for information you don't need, and * try to do it in as few calls as possible. You can get most of the * interesting information about a torrent from the * torrent_handle::status() call. * <p/> * The default constructor will initialize the handle to an invalid state. * Which means you cannot perform any operation on it, unless you first * assign it a valid handle. If you try to perform any operation on an * uninitialized handle, it will throw ``invalid_handle``. * <p/> * .. warning:: * All operations on a torrent_handle may throw libtorrent_exception * exception, in case the handle is no longer refering to a torrent. * There is one exception is_valid() will never throw. Since the torrents * are processed by a background thread, there is no guarantee that a * handle will remain valid between two calls. * * @author gubatron * @author aldenml */ public final class TorrentHandle { private static final long REQUEST_STATUS_RESOLUTION_MILLIS = 500; private final torrent_handle th; private long lastStatusRequestTime; private TorrentStatus lastStatus; public TorrentHandle(torrent_handle th) { this.th = th; } public torrent_handle getSwig() { return th; } /** * This function starts an asynchronous read operation of the specified * piece from this torrent. You must have completed the download of the * specified piece before calling this function. * <p/> * When the read operation is completed, it is passed back through an * alert, {@link com.frostwire.jlibtorrent.alerts.ReadPieceAlert}. * Since this alert is a response to an explicit * call, it will always be posted, regardless of the alert mask. * <p/> * Note that if you read multiple pieces, the read operations are not * guaranteed to finish in the same order as you initiated them. * * @param piece */ public void readPiece(int piece) { th.read_piece(piece); } /** * Returns true if this piece has been completely downloaded, and false * otherwise. * * @param piece * @return */ public boolean havePiece(int piece) { return th.have_piece(piece); } /** * takes a reference to a vector that will be cleared and filled with one * entry for each peer connected to this torrent, given the handle is * valid. If the torrent_handle is invalid, it will return an empty list. * <p/> * Each entry in the vector contains * information about that particular peer. See peer_info. * * @return */ public List<PeerInfo> getPeerInfo() { if (!th.is_valid()) { return Collections.emptyList(); } peer_info_vector v = new peer_info_vector(); th.get_peer_info(v); int size = (int) v.size(); List<PeerInfo> l = new ArrayList<PeerInfo>(size); for (int i = 0; i < size; i++) { l.add(new PeerInfo(v.get(i))); } return l; } /** * Returns a pointer to the torrent_info object associated with this * torrent. The {@link com.frostwire.jlibtorrent.TorrentInfo} object * may be a copy of the internal object. * <p/> * If the torrent doesn't have metadata, the pointer will not be * initialized (i.e. a NULL pointer). The torrent may be in a state * without metadata only if it was started without a .torrent file, e.g. * by using the libtorrent extension of just supplying a tracker and * info-hash. * * @return */ public TorrentInfo getTorrentInfo() { torrent_info ti = th.get_torrent_copy(); return ti != null ? new TorrentInfo(ti) : null; } /** * `status()`` will return a structure with information about the status * of this torrent. If the torrent_handle is invalid, it will throw * libtorrent_exception exception. See torrent_status. The ``flags`` * argument filters what information is returned in the torrent_status. * Some information in there is relatively expensive to calculate, and if * you're not interested in it (and see performance issues), you can * filter them out. * <p/> * By default everything is included. The flags you can use to decide * what to *include* are defined in the status_flags_t enum. * <p/> * It is important not to call this method for each field in the status * for performance reasons. * * @return */ public TorrentStatus getStatus(boolean force) { long now = System.currentTimeMillis(); if (force || (now - lastStatusRequestTime) >= REQUEST_STATUS_RESOLUTION_MILLIS) { lastStatusRequestTime = now; lastStatus = new TorrentStatus(th.status()); } return lastStatus; } /** * `status()`` will return a structure with information about the status * of this torrent. If the torrent_handle is invalid, it will throw * libtorrent_exception exception. See torrent_status. The ``flags`` * argument filters what information is returned in the torrent_status. * Some information in there is relatively expensive to calculate, and if * you're not interested in it (and see performance issues), you can * filter them out. * * @return */ public TorrentStatus getStatus() { return this.getStatus(false); } /** * Returns the info-hash for the torrent. * <p/> * If this handle is to a torrent that hasn't loaded yet (for instance by being added) * by a URL, the returned value is undefined. * * @return */ public Sha1Hash getInfoHash() { return new Sha1Hash(th.info_hash()); } /** * ``pause()`` will disconnect all peers. * <p/> * When a torrent is paused, it will however * remember all share ratios to all peers and remember all potential (not * connected) peers. Torrents may be paused automatically if there is a * file error (e.g. disk full) or something similar. See * file_error_alert. * <p/> * To know if a torrent is paused or not, call * ``torrent_handle::status()`` and inspect ``torrent_status::paused``. * <p/> * The ``flags`` argument to pause can be set to * ``torrent_handle::graceful_pause`` which will delay the disconnect of * peers that we're still downloading outstanding requests from. The * torrent will not accept any more requests and will disconnect all idle * peers. As soon as a peer is done transferring the blocks that were * requested from it, it is disconnected. This is a graceful shut down of * the torrent in the sense that no downloaded bytes are wasted. * <p/> * torrents that are auto-managed may be automatically resumed again. It * does not make sense to pause an auto-managed torrent without making it * not automanaged first. * <p/> * The current {@link Session} add torrent implementations add the torrent * in no-auto-managed mode. */ public void pause() { th.pause(); } /** * Will reconnect all peers. * <p/> * Torrents that are auto-managed may be automatically resumed again. */ public void resume() { th.resume(); } /** * Set or clear the stop-when-ready flag. When this flag is set, the * torrent will *force stop* whenever it transitions from a * non-data-transferring state into a data-transferring state (referred to * as being ready to download or seed). This is useful for torrents that * should not start downloading or seeding yet, but what to be made ready * to do so. A torrent may need to have its files checked for instance, so * it needs to be started and possibly queued for checking (auto-managed * and started) but as soon as it's done, it should be stopped. * <p/> * *Force stopped* means auto-managed is set to false and it's paused. As * if auto_manage(false) and pause() were called on the torrent. * * @param value */ public void stopWhenReady(boolean value) { th.stop_when_ready(value); } /** * Explicitly sets the upload mode of the torrent. In upload mode, the * torrent will not request any pieces. If the torrent is auto managed, * it will automatically be taken out of upload mode periodically (see * ``session_settings::optimistic_disk_retry``). Torrents are * automatically put in upload mode whenever they encounter a disk write * error. * <p/> * {@code value} should be true to enter upload mode, and false to leave it. * <p/> * To test if a torrent is in upload mode, call * ``torrent_handle::status()`` and inspect * ``torrent_status::upload_mode``. * * @param value */ public void setUploadMode(boolean value) { th.set_upload_mode(value); } /** * Enable or disable share mode for this torrent. When in share mode, the * torrent will not necessarily be downloaded, especially not the whole * of it. Only parts that are likely to be distributed to more than 2 * other peers are downloaded, and only if the previous prediction was * correct. * * @param value */ public void setShareMode(boolean value) { th.set_share_mode(value); } /** * Instructs libtorrent to flush all the disk caches for this torrent and * close all file handles. This is done asynchronously and you will be * notified that it's complete through {@link com.frostwire.jlibtorrent.alerts.CacheFlushedAlert}. * <p/> * Note that by the time you get the alert, libtorrent may have cached * more data for the torrent, but you are guaranteed that whatever cached * data libtorrent had by the time you called * {@link #flushCache()} has been written to disk. */ public void flushCache() { th.flush_cache(); } /** * This function returns true if any whole chunk has been downloaded * since the torrent was first loaded or since the last time the resume * data was saved. When saving resume data periodically, it makes sense * to skip any torrent which hasn't downloaded anything since the last * time. * <p/> * .. note:: * A torrent's resume data is considered saved as soon as the alert is * posted. It is important to make sure this alert is received and * handled in order for this function to be meaningful. * * @return */ public boolean needSaveResumeData() { return th.need_save_resume_data(); } /** * changes whether the torrent is auto managed or not. For more info, * see queuing_. * * @param value */ public void setAutoManaged(boolean value) { th.auto_managed(value); } /** * Every torrent that is added is assigned a queue position exactly one * greater than the greatest queue position of all existing torrents. * Torrents that are being seeded have -1 as their queue position, since * they're no longer in line to be downloaded. * <p/> * When a torrent is removed or turns into a seed, all torrents with * greater queue positions have their positions decreased to fill in the * space in the sequence. * <p/> * This function returns the torrent's position in the download * queue. The torrents with the smallest numbers are the ones that are * being downloaded. The smaller number, the closer the torrent is to the * front of the line to be started. * <p/> * The queue position is also available in the torrent_status. * * @return */ public int getQueuePosition() { return th.queue_position(); } /** * The ``queue_position_*()`` functions adjust the torrents position in * the queue. Up means closer to the front and down means closer to the * back of the queue. Top and bottom refers to the front and the back of * the queue respectively. */ public void queuePositionUp() { th.queue_position_up(); } /** * The ``queue_position_*()`` functions adjust the torrents position in * the queue. Up means closer to the front and down means closer to the * back of the queue. Top and bottom refers to the front and the back of * the queue respectively. */ public void queuePositionDown() { th.queue_position_down(); } /** * The ``queue_position_*()`` functions adjust the torrents position in * the queue. Up means closer to the front and down means closer to the * back of the queue. Top and bottom refers to the front and the back of * the queue respectively. */ public void queuePositionTop() { th.queue_position_top(); } /** * The ``queue_position_*()`` functions adjust the torrents position in * the queue. Up means closer to the front and down means closer to the * back of the queue. Top and bottom refers to the front and the back of * the queue respectively. */ public void queuePositionBottom() { th.queue_position_bottom(); } /** * ``save_resume_data()`` generates fast-resume data and returns it as an * entry. This entry is suitable for being bencoded. For more information * about how fast-resume works, see fast-resume_. * <p/> * The ``flags`` argument is a bitmask of flags ORed together. see * save_resume_flags_t * <p/> * This operation is asynchronous, ``save_resume_data`` will return * immediately. The resume data is delivered when it's done through an * save_resume_data_alert. * <p/> * The fast resume data will be empty in the following cases: * <p/> * 1. The torrent handle is invalid. * 2. The torrent is checking (or is queued for checking) its storage, it * will obviously not be ready to write resume data. * 3. The torrent hasn't received valid metadata and was started without * metadata (see libtorrent's metadata-from-peers_ extension) * <p/> * Note that by the time you receive the fast resume data, it may already * be invalid if the torrent is still downloading! The recommended * practice is to first pause the session, then generate the fast resume * data, and then close it down. Make sure to not remove_torrent() before * you receive the save_resume_data_alert though. There's no need to * pause when saving intermittent resume data. * <p/> * .. warning:: * If you pause every torrent individually instead of pausing the * session, every torrent will have its paused state saved in the * resume data! * <p/> * .. warning:: * The resume data contains the modification timestamps for all files. * If one file has been modified when the torrent is added again, the * will be rechecked. When shutting down, make sure to flush the disk * cache before saving the resume data. This will make sure that the * file timestamps are up to date and won't be modified after saving * the resume data. The recommended way to do this is to pause the * torrent, which will flush the cache and disconnect all peers. * <p/> * .. note:: * It is typically a good idea to save resume data whenever a torrent * is completed or paused. In those cases you don't need to pause the * torrent or the session, since the torrent will do no more writing to * its files. If you save resume data for torrents when they are * paused, you can accelerate the shutdown process by not saving resume * data again for paused torrents. Completed torrents should have their * resume data saved when they complete and on exit, since their * statistics might be updated. * <p/> * In full allocation mode the reume data is never invalidated by * subsequent writes to the files, since pieces won't move around. This * means that you don't need to pause before writing resume data in full * or sparse mode. If you don't, however, any data written to disk after * you saved resume data and before the session closed is lost. * <p/> * It also means that if the resume data is out dated, libtorrent will * not re-check the files, but assume that it is fairly recent. The * assumption is that it's better to loose a little bit than to re-check * the entire file. * <p/> * It is still a good idea to save resume data periodically during * download as well as when closing down. * <p/> * Example code to pause and save resume data for all torrents and wait * for the alerts: * <p/> * .. code:: c++ * <p/> * extern int outstanding_resume_data; // global counter of outstanding resume data * std::vector<torrent_handle> handles = ses.get_torrents(); * ses.pause(); * for (std::vector<torrent_handle>::iterator i = handles.begin(); * i != handles.end(); ++i) * { * torrent_handle& h = *i; * if (!h.is_valid()) continue; * torrent_status s = h.status(); * if (!s.has_metadata) continue; * if (!s.need_save_resume_data()) continue; * <p/> * h.save_resume_data(); * ++outstanding_resume_data; * } * <p/> * while (outstanding_resume_data > 0) * { * alert const* a = ses.wait_for_alert(seconds(10)); * <p/> * // if we don't get an alert within 10 seconds, abort * if (a == 0) break; * <p/> * std::auto_ptr<alert> holder = ses.pop_alert(); * <p/> * if (alert_cast<save_resume_data_failed_alert>(a)) * { * process_alert(a); * --outstanding_resume_data; * continue; * } * <p/> * save_resume_data_alert const* rd = alert_cast<save_resume_data_alert>(a); * if (rd == 0) * { * process_alert(a); * continue; * } * <p/> * torrent_handle h = rd->handle; * torrent_status st = h.status(torrent_handle::query_save_path | torrent_handle::query_name); * std::ofstream out((st.save_path * + "/" + st.name + ".fastresume").c_str() * , std::ios_base::binary); * out.unsetf(std::ios_base::skipws); * bencode(std::ostream_iterator<char>(out), *rd->resume_data); * --outstanding_resume_data; * } * <p/> * .. note:: * Note how ``outstanding_resume_data`` is a global counter in this * example. This is deliberate, otherwise there is a race condition for * torrents that was just asked to save their resume data, they posted * the alert, but it has not been received yet. Those torrents would * report that they don't need to save resume data again, and skipped by * the initial loop, and thwart the counter otherwise. */ public void saveResumeData() { th.save_resume_data(torrent_handle.save_resume_flags_t.save_info_dict.swigValue()); } /** * Returns true if this handle refers to a valid torrent and false if it * hasn't been initialized or if the torrent it refers to has been * aborted. Note that a handle may become invalid after it has been added * to the session. Usually this is because the storage for the torrent is * somehow invalid or if the filenames are not allowed (and hence cannot * be opened/created) on your filesystem. If such an error occurs, a * file_error_alert is generated and all handles that refers to that * torrent will become invalid. * * @return */ public boolean isValid() { return th.is_valid(); } /** * Generates a magnet URI from the specified torrent. If the torrent * handle is invalid, null is returned. * * @return */ public String makeMagnetUri() { return th.is_valid() ? libtorrent.make_magnet_uri(th) : null; } // ``set_upload_limit`` will limit the upload bandwidth used by this // particular torrent to the limit you set. It is given as the number of // bytes per second the torrent is allowed to upload. // ``set_download_limit`` works the same way but for download bandwidth // instead of upload bandwidth. Note that setting a higher limit on a // torrent then the global limit // (``session_settings::upload_rate_limit``) will not override the global // rate limit. The torrent can never upload more than the global rate // limit. // ``upload_limit`` and ``download_limit`` will return the current limit // setting, for upload and download, respectively. public int getUploadLimit() { return th.upload_limit(); } // ``set_upload_limit`` will limit the upload bandwidth used by this // particular torrent to the limit you set. It is given as the number of // bytes per second the torrent is allowed to upload. // ``set_download_limit`` works the same way but for download bandwidth // instead of upload bandwidth. Note that setting a higher limit on a // torrent then the global limit // (``session_settings::upload_rate_limit``) will not override the global // rate limit. The torrent can never upload more than the global rate // limit. // ``upload_limit`` and ``download_limit`` will return the current limit // setting, for upload and download, respectively. public void setUploadLimit(int limit) { th.set_upload_limit(limit); } // ``set_upload_limit`` will limit the upload bandwidth used by this // particular torrent to the limit you set. It is given as the number of // bytes per second the torrent is allowed to upload. // ``set_download_limit`` works the same way but for download bandwidth // instead of upload bandwidth. Note that setting a higher limit on a // torrent then the global limit // (``session_settings::upload_rate_limit``) will not override the global // rate limit. The torrent can never upload more than the global rate // limit. // ``upload_limit`` and ``download_limit`` will return the current limit // setting, for upload and download, respectively. public int getDownloadLimit() { return th.download_limit(); } // ``set_upload_limit`` will limit the upload bandwidth used by this // particular torrent to the limit you set. It is given as the number of // bytes per second the torrent is allowed to upload. // ``set_download_limit`` works the same way but for download bandwidth // instead of upload bandwidth. Note that setting a higher limit on a // torrent then the global limit // (``session_settings::upload_rate_limit``) will not override the global // rate limit. The torrent can never upload more than the global rate // limit. // ``upload_limit`` and ``download_limit`` will return the current limit // setting, for upload and download, respectively. public void setDownloadLimit(int limit) { th.set_download_limit(limit); } /** * Enables or disables *sequential download*. * <p/> * When enabled, the piece picker will pick pieces in sequence * instead of rarest first. In this mode, piece priorities are ignored, * with the exception of priority 7, which are still preferred over the * sequential piece order. * <p/> * Enabling sequential download will affect the piece distribution * negatively in the swarm. It should be used sparingly. * * @param sequential */ public void setSequentialDownload(boolean sequential) { th.set_sequential_download(sequential); } // ``force_recheck`` puts the torrent back in a state where it assumes to // have no resume data. All peers will be disconnected and the torrent // will stop announcing to the tracker. The torrent will be added to the // checking queue, and will be checked (all the files will be read and // compared to the piece hashes). Once the check is complete, the torrent // will start connecting to peers again, as normal. public void forceRecheck() { th.force_recheck(); } // ``force_reannounce()`` will force this torrent to do another tracker // request, to receive new peers. The ``seconds`` argument specifies how // many seconds from now to issue the tracker announces. // If the tracker's ``min_interval`` has not passed since the last // announce, the forced announce will be scheduled to happen immediately // as the ``min_interval`` expires. This is to honor trackers minimum // re-announce interval settings. // The ``tracker_index`` argument specifies which tracker to re-announce. // If set to -1 (which is the default), all trackers are re-announce. public void forceReannounce(int seconds, int tracker_index) { th.force_reannounce(seconds, tracker_index); } // ``force_reannounce()`` will force this torrent to do another tracker // request, to receive new peers. The ``seconds`` argument specifies how // many seconds from now to issue the tracker announces. // If the tracker's ``min_interval`` has not passed since the last // announce, the forced announce will be scheduled to happen immediately // as the ``min_interval`` expires. This is to honor trackers minimum // re-announce interval settings. // The ``tracker_index`` argument specifies which tracker to re-announce. // If set to -1 (which is the default), all trackers are re-announce. public void forceReannounce(int seconds) { th.force_reannounce(seconds); } /** * Force this torrent to do another tracker * request, to receive new peers. The ``seconds`` argument specifies how * many seconds from now to issue the tracker announces. * <p/> * If the tracker's ``min_interval`` has not passed since the last * announce, the forced announce will be scheduled to happen immediately * as the ``min_interval`` expires. This is to honor trackers minimum * re-announce interval settings. * <p/> * The ``tracker_index`` argument specifies which tracker to re-announce. * If set to -1 (which is the default), all trackers are re-announce. */ public void forceReannounce() { th.force_reannounce(); } /** * Announce the torrent to the DHT immediately. */ public void forceDHTAnnounce() { th.force_dht_announce(); } /** * Will return the list of trackers for this torrent. The * announce entry contains both a string ``url`` which specify the * announce url for the tracker as well as an int ``tier``, which is * specifies the order in which this tracker is tried. * * @return */ public List<AnnounceEntry> getTrackers() { announce_entry_vector v = th.trackers(); int size = (int) v.size(); List<AnnounceEntry> list = new ArrayList<AnnounceEntry>(size); for (int i = 0; i < size; i++) { list.add(new AnnounceEntry(v.get(i))); } return list; } /** * Will send a scrape request to the tracker. A * scrape request queries the tracker for statistics such as total number * of incomplete peers, complete peers, number of downloads etc. * <p/> * This request will specifically update the ``num_complete`` and * ``num_incomplete`` fields in the torrent_status struct once it * completes. When it completes, it will generate a scrape_reply_alert. * If it fails, it will generate a scrape_failed_alert. */ public void scrapeTracker() { th.scrape_tracker(); } // If you want // libtorrent to use another list of trackers for this torrent, you can // use ``replace_trackers()`` which takes a list of the same form as the // one returned from ``trackers()`` and will replace it. If you want an // immediate effect, you have to call force_reannounce(). See // announce_entry. // The updated set of trackers will be saved in the resume data, and when // a torrent is started with resume data, the trackers from the resume // data will replace the original ones. public void replaceTrackers(List<AnnounceEntry> trackers) { announce_entry_vector v = new announce_entry_vector(); for (AnnounceEntry e : trackers) { v.add(e.getSwig()); } th.replace_trackers(v); } // ``add_tracker()`` will look if the specified tracker is already in the // set. If it is, it doesn't do anything. If it's not in the current set // of trackers, it will insert it in the tier specified in the // announce_entry. // The updated set of trackers will be saved in the resume data, and when // a torrent is started with resume data, the trackers from the resume // data will replace the original ones. public void addTracker(AnnounceEntry tracker) { th.add_tracker(tracker.getSwig()); } // ``add_url_seed()`` adds another url to the torrent's list of url // seeds. If the given url already exists in that list, the call has no // effect. The torrent will connect to the server and try to download // pieces from it, unless it's paused, queued, checking or seeding. // ``remove_url_seed()`` removes the given url if it exists already. // ``url_seeds()`` return a set of the url seeds currently in this // torrent. Note that urls that fails may be removed automatically from // the list. // See http-seeding_ for more information. public void addUrlSeed(String url) { th.add_url_seed(url); } // ``add_url_seed()`` adds another url to the torrent's list of url // seeds. If the given url already exists in that list, the call has no // effect. The torrent will connect to the server and try to download // pieces from it, unless it's paused, queued, checking or seeding. // ``remove_url_seed()`` removes the given url if it exists already. // ``url_seeds()`` return a set of the url seeds currently in this // torrent. Note that urls that fails may be removed automatically from // the list. // See http-seeding_ for more information. public void removeUrlSeed(String url) { th.remove_url_seed(url); } // These functions are identical as the ``*_url_seed()`` variants, but // they operate on `BEP 17`_ web seeds instead of `BEP 19`_. // See http-seeding_ for more information. public void addHttpSeed(String url) { th.add_url_seed(url); } // These functions are identical as the ``*_url_seed()`` variants, but // they operate on `BEP 17`_ web seeds instead of `BEP 19`_. // See http-seeding_ for more information. public void removeHttpSeed(String url) { th.remove_http_seed(url); } // ``use_interface()`` sets the network interface this torrent will use // when it opens outgoing connections. By default, it uses the same // interface as the session uses to listen on. The parameter must be a // string containing one or more, comma separated, ip-address (either an // IPv4 or IPv6 address). When specifying multiple interfaces, the // torrent will round-robin which interface to use for each outgoing // conneciton. This is useful for clients that are multi-homed. // public void useInterface(String netInterface) { // th.use_interface(netInterface); // Fills the specified ``std::vector<int>`` with the availability for // each piece in this torrent. libtorrent does not keep track of // availability for seeds, so if the torrent is seeding the availability // for all pieces is reported as 0. // The piece availability is the number of peers that we are connected // that has advertized having a particular piece. This is the information // that libtorrent uses in order to prefer picking rare pieces. public int[] getPieceAvailability() { int_vector v = new int_vector(); th.piece_availability(v); return Vectors.int_vector2ints(v); } // These functions are used to set and get the prioritiy of individual // pieces. By default all pieces have priority 1. That means that the // random rarest first algorithm is effectively active for all pieces. // You may however change the priority of individual pieces. There are 8 // different priority levels: // 0. piece is not downloaded at all // 1. normal priority. Download order is dependent on availability // 2. higher than normal priority. Pieces are preferred over pieces with // the same availability, but not over pieces with lower availability // 3. pieces are as likely to be picked as partial pieces. // 4. pieces are preferred over partial pieces, but not over pieces with // lower availability // 5. *currently the same as 4* // 6. piece is as likely to be picked as any piece with availability 1 // 7. maximum priority, availability is disregarded, the piece is // preferred over any other piece with lower priority // The exact definitions of these priorities are implementation details, // and subject to change. The interface guarantees that higher number // means higher priority, and that 0 means do not download. // ``piece_priority`` sets or gets the priority for an individual piece, // specified by ``index``. // ``prioritize_pieces`` takes a vector of integers, one integer per // piece in the torrent. All the piece priorities will be updated with // the priorities in the vector. // ``piece_priorities`` returns a vector with one element for each piece // in the torrent. Each element is the current priority of that piece. public void setPiecePriority(int index, Priority priority) { th.piece_priority(index, priority.getSwig()); } public Priority getPiecePriority(int index) { return Priority.fromSwig(th.piece_priority(index)); } public void prioritizePieces(Priority[] priorities) { int[] arr = new int[priorities.length]; for (int i = 0; i < arr.length; i++) { arr[i] = priorities[i] != Priority.UNKNOWN ? priorities[i].getSwig() : Priority.IGNORE.getSwig(); } th.prioritize_pieces(Vectors.ints2int_vector(arr)); } public Priority[] getPiecePriorities() { int_vector v = th.piece_priorities(); int size = (int) v.size(); Priority[] arr = new Priority[size]; for (int i = 0; i < size; i++) { arr[i] = Priority.fromSwig(v.get(i)); } return arr; } /** * index must be in the range [0, number_of_files). * <p/> * The priority values are the same as for piece_priority(). * <p/> * Whenever a file priority is changed, all other piece priorities are * reset to match the file priorities. In order to maintain sepcial * priorities for particular pieces, piece_priority() has to be called * again for those pieces. * <p/> * You cannot set the file priorities on a torrent that does not yet have * metadata or a torrent that is a seed. ``file_priority(int, int)`` and * prioritize_files() are both no-ops for such torrents. * * @param index * @param priority */ public void setFilePriority(int index, Priority priority) { th.file_priority(index, priority.getSwig()); } /** * index must be in the range [0, number_of_files). * <p/> * queries or sets the priority of file index. * * @param index * @return */ public Priority getFilePriority(int index) { return Priority.fromSwig(th.file_priority(index)); } /** * Takes a vector that has at as many elements as * there are files in the torrent. Each entry is the priority of that * file. The function sets the priorities of all the pieces in the * torrent based on the vector. * * @param priorities */ public void prioritizeFiles(Priority[] priorities) { int[] arr = new int[priorities.length]; for (int i = 0; i < arr.length; i++) { arr[i] = priorities[i] != Priority.UNKNOWN ? priorities[i].getSwig() : Priority.IGNORE.getSwig(); } th.prioritize_files(Vectors.ints2int_vector(arr)); } /** * Returns a vector with the priorities of all files. * * @return */ public Priority[] getFilePriorities() { int_vector v = th.file_priorities(); int size = (int) v.size(); Priority[] arr = new Priority[size]; for (int i = 0; i < size; i++) { arr[i] = Priority.fromSwig(v.get(i)); } return arr; } /** * This function sets or resets the deadline associated with a specific * piece index (``index``). libtorrent will attempt to download this * entire piece before the deadline expires. This is not necessarily * possible, but pieces with a more recent deadline will always be * prioritized over pieces with a deadline further ahead in time. The * deadline (and flags) of a piece can be changed by calling this * function again. * <p/> * If the piece is already downloaded when this call is made, nothing * happens, unless the alert_when_available flag is set, in which case it * will do the same thing as calling read_piece() for ``index``. * * @param index * @param deadline */ public void setPieceDeadline(int index, int deadline) { th.set_piece_deadline(index, deadline); } /** * This function sets or resets the deadline associated with a specific * piece index (``index``). libtorrent will attempt to download this * entire piece before the deadline expires. This is not necessarily * possible, but pieces with a more recent deadline will always be * prioritized over pieces with a deadline further ahead in time. The * deadline (and flags) of a piece can be changed by calling this * function again. * <p/> * The ``flags`` parameter can be used to ask libtorrent to send an alert * once the piece has been downloaded, by passing alert_when_available. * When set, the read_piece_alert alert will be delivered, with the piece * data, when it's downloaded. * <p/> * If the piece is already downloaded when this call is made, nothing * happens, unless the alert_when_available flag is set, in which case it * will do the same thing as calling read_piece() for ``index``. * * @param index * @param deadline * @param flags */ public void setPieceDeadline(int index, int deadline, DeadlineFlags flags) { th.set_piece_deadline(index, deadline, flags.getSwig()); } /** * Removes the deadline from the piece. If it * hasn't already been downloaded, it will no longer be considered a * priority. * * @param index */ public void resetPieceDeadline(int index) { th.reset_piece_deadline(index); } /** * Removes deadlines on all pieces in the torrent. * As if {@link #resetPieceDeadline(int)} was called on all pieces. */ public void clearPieceDeadlines() { th.clear_piece_deadlines(); } /** * This sets the bandwidth priority of this torrent. The priority of a * torrent determines how much bandwidth its peers are assigned when * distributing upload and download rate quotas. A high number gives more * bandwidth. The priority must be within the range [0, 255]. * <p/> * The default priority is 0, which is the lowest priority. * <p/> * To query the priority of a torrent, use the * ``torrent_handle::status()`` call. * <p/> * Torrents with higher priority will not nececcarily get as much * bandwidth as they can consume, even if there's is more quota. Other * peers will still be weighed in when bandwidth is being distributed. * With other words, bandwidth is not distributed strictly in order of * priority, but the priority is used as a weight. * <p/> * Peers whose Torrent has a higher priority will take precedence when * distributing unchoke slots. This is a strict prioritization where * every interested peer on a high priority torrent will be unchoked * before any other, lower priority, torrents have any peers unchoked. * * @param priority */ public void setPriority(int priority) { if (priority < 0 || 255 < priority) { throw new IllegalArgumentException("The priority must be within the range [0, 255]"); } th.set_priority(priority); } /** * This function fills in the supplied vector with the number of * bytes downloaded of each file in this torrent. The progress values are * ordered the same as the files in the torrent_info. This operation is * not very cheap. Its complexity is *O(n + mj)*. Where *n* is the number * of files, *m* is the number of downloading pieces and *j* is the * number of blocks in a piece. * <p/> * The ``flags`` parameter can be used to specify the granularity of the * file progress. If left at the default value of 0, the progress will be * as accurate as possible, but also more expensive to calculate. If * ``torrent_handle::piece_granularity`` is specified, the progress will * be specified in piece granularity. i.e. only pieces that have been * fully downloaded and passed the hash check count. When specifying * piece granularity, the operation is a lot cheaper, since libtorrent * already keeps track of this internally and no calculation is required. * * @param flags * @return */ public long[] getFileProgress(FileProgressFlags flags) { int64_vector v = new int64_vector(); th.file_progress(v, flags.getSwig()); return Vectors.int64_vector2longs(v); } /** * This function fills in the supplied vector with the number of * bytes downloaded of each file in this torrent. The progress values are * ordered the same as the files in the torrent_info. This operation is * not very cheap. Its complexity is *O(n + mj)*. Where *n* is the number * of files, *m* is the number of downloading pieces and *j* is the * number of blocks in a piece. * * @return */ public long[] getFileProgress() { int64_vector v = new int64_vector(); th.file_progress(v); return Vectors.int64_vector2longs(v); } /** * The path to the directory where this torrent's files are stored. * It's typically the path as was given to async_add_torrent() or * add_torrent() when this torrent was started. * * @return */ public String getSavePath() { torrent_status ts = th.status(status_flags_t.query_save_path.swigValue()); return ts.getSave_path(); } /** * The name of the torrent. Typically this is derived from the * .torrent file. In case the torrent was started without metadata, * and hasn't completely received it yet, it returns the name given * to it when added to the session. * * @return */ public String getName() { torrent_status ts = th.status(status_flags_t.query_name.swigValue()); return ts.getName(); } // Moves the file(s) that this torrent are currently seeding from or // downloading to. If the given ``save_path`` is not located on the same // drive as the original save path, the files will be copied to the new // drive and removed from their original location. This will block all // other disk IO, and other torrents download and upload rates may drop // while copying the file. // Since disk IO is performed in a separate thread, this operation is // also asynchronous. Once the operation completes, the // ``storage_moved_alert`` is generated, with the new path as the // message. If the move fails for some reason, // ``storage_moved_failed_alert`` is generated instead, containing the // error message. // The ``flags`` argument determines the behavior of the copying/moving // of the files in the torrent. see move_flags_t. // * always_replace_files = 0 // * fail_if_exist = 1 // * dont_replace = 2 // ``always_replace_files`` is the default and replaces any file that // exist in both the source directory and the target directory. // ``fail_if_exist`` first check to see that none of the copy operations // would cause an overwrite. If it would, it will fail. Otherwise it will // proceed as if it was in ``always_replace_files`` mode. Note that there // is an inherent race condition here. If the files in the target // directory appear after the check but before the copy or move // completes, they will be overwritten. When failing because of files // already existing in the target path, the ``error`` of // ``move_storage_failed_alert`` is set to // ``boost::system::errc::file_exists``. // The intention is that a client may use this as a probe, and if it // fails, ask the user which mode to use. The client may then re-issue // the ``move_storage`` call with one of the other modes. // ``dont_replace`` always takes the existing file in the target // directory, if there is one. The source files will still be removed in // that case. // Files that have been renamed to have absolute pahts are not moved by // this function. Keep in mind that files that don't belong to the // torrent but are stored in the torrent's directory may be moved as // well. This goes for files that have been renamed to absolute paths // that still end up inside the save path. public void moveStorage(String savePath, int flags) { th.move_storage(savePath, flags); } // Moves the file(s) that this torrent are currently seeding from or // downloading to. If the given ``save_path`` is not located on the same // drive as the original save path, the files will be copied to the new // drive and removed from their original location. This will block all // other disk IO, and other torrents download and upload rates may drop // while copying the file. // Since disk IO is performed in a separate thread, this operation is // also asynchronous. Once the operation completes, the // ``storage_moved_alert`` is generated, with the new path as the // message. If the move fails for some reason, // ``storage_moved_failed_alert`` is generated instead, containing the // error message. // The ``flags`` argument determines the behavior of the copying/moving // of the files in the torrent. see move_flags_t. // * always_replace_files = 0 // * fail_if_exist = 1 // * dont_replace = 2 // ``always_replace_files`` is the default and replaces any file that // exist in both the source directory and the target directory. // ``fail_if_exist`` first check to see that none of the copy operations // would cause an overwrite. If it would, it will fail. Otherwise it will // proceed as if it was in ``always_replace_files`` mode. Note that there // is an inherent race condition here. If the files in the target // directory appear after the check but before the copy or move // completes, they will be overwritten. When failing because of files // already existing in the target path, the ``error`` of // ``move_storage_failed_alert`` is set to // ``boost::system::errc::file_exists``. // The intention is that a client may use this as a probe, and if it // fails, ask the user which mode to use. The client may then re-issue // the ``move_storage`` call with one of the other modes. // ``dont_replace`` always takes the existing file in the target // directory, if there is one. The source files will still be removed in // that case. // Files that have been renamed to have absolute pahts are not moved by // this function. Keep in mind that files that don't belong to the // torrent but are stored in the torrent's directory may be moved as // well. This goes for files that have been renamed to absolute paths // that still end up inside the save path. public void moveStorage(String savePath) { th.move_storage(savePath); } /** * Renames the file with the given index asynchronously. The rename * operation is complete when either a {@link com.frostwire.jlibtorrent.alerts.FileRenamedAlert} or * {@link com.frostwire.jlibtorrent.alerts.FileRenameFailedAlert} is posted. * * @param index * @param newName */ public void renameFile(int index, String newName) { th.rename_file(index, newName); } /** * Flags to pass in to status() to specify which properties of the * torrent to query for. By default all flags are set. */ public enum StatusFlags { /** * calculates ``distributed_copies``, ``distributed_full_copies`` and * ``distributed_fraction``. */ QUERY_DISTRIBUTED_COPIES(status_flags_t.query_distributed_copies.swigValue()), /** * includes partial downloaded blocks in ``total_done`` and * ``total_wanted_done``. */ QUERY_ACCURATE_DOWNLOAD_COUNTERS(status_flags_t.query_accurate_download_counters.swigValue()), /** * includes ``last_seen_complete``. */ QUERY_LAST_SEEN_COMPLETE(status_flags_t.query_last_seen_complete.swigValue()), /** * includes ``pieces``. */ QUERY_PIECES(status_flags_t.query_pieces.swigValue()), /** * includes ``verified_pieces`` (only applies to torrents in *seed mode*). */ QUERY_VERIFIED_PIECES(status_flags_t.query_verified_pieces.swigValue()), /** * includes ``torrent_file``, which is all the static information from the .torrent file. */ QUERY_TORRENT_FILE(status_flags_t.query_torrent_file.swigValue()), /** * includes ``name``, the name of the torrent. This is either derived * from the .torrent file, or from the ``&dn=`` magnet link argument * or possibly some other source. If the name of the torrent is not * known, this is an empty string. */ QUERY_NAME(status_flags_t.query_name.swigValue()), /** * includes ``save_path``, the path to the directory the files of the * torrent are saved to. */ QUERY_SAVE_PATH(status_flags_t.query_save_path.swigValue()); private StatusFlags(int swigValue) { this.swigValue = swigValue; } private final int swigValue; public int getSwig() { return swigValue; } } /** * Flags for {@link #setPieceDeadline(int, int, com.frostwire.jlibtorrent.TorrentHandle.DeadlineFlags)}. */ public enum DeadlineFlags { ALERT_WHEN_AVAILABLE(torrent_handle.deadline_flags.alert_when_available.swigValue()); private DeadlineFlags(int swigValue) { this.swigValue = swigValue; } private final int swigValue; public int getSwig() { return swigValue; } } /** * Flags to be passed in {@link #getFileProgress(com.frostwire.jlibtorrent.TorrentHandle.FileProgressFlags)}. */ public enum FileProgressFlags { DEFAULT(0), /** * only calculate file progress at piece granularity. This makes * the file_progress() call cheaper and also only takes bytes that * have passed the hash check into account, so progress cannot * regress in this mode. */ PIECE_GRANULARITY(torrent_handle.file_progress_flags_t.piece_granularity.swigValue()); private FileProgressFlags(int swigValue) { this.swigValue = swigValue; } private final int swigValue; public int getSwig() { return swigValue; } } }
package com.github.andriell.gui; import com.github.andriell.processor.Manager; import com.github.andriell.processor.ManagerInterface; import javax.swing.*; public class ProcessWorkArea implements WorkArea { private JPanel rootPanel; private JLabel processCountLabel; private JLabel processRunningLabel; private JTextField processLimitLabel; private ManagerInterface manager; public ProcessWorkArea() { new Thread(new Runnable() { public void run() { String s; while (true) { try { s = Integer.toString(manager.getProcessInQueue()); if (s.equals(processCountLabel.getText())) { processCountLabel.setText(s); } s = Integer.toString(manager.getRunningProcesses()); if (s.equals(processRunningLabel.getText())) { processRunningLabel.setText(s); } s = Integer.toString(manager.getLimitProcess()); if (!s.equals(processLimitLabel.getText())) { processLimitLabel.setText(s); } Thread.sleep(1000); } catch (Exception e) {} } } }).start(); } public void setManager(ManagerInterface manager) { this.manager = manager; } public JPanel getRootPanel() { return rootPanel; } @Override public String toString() { return "Процессы"; } }
package com.messagebird; import com.messagebird.exceptions.GeneralException; import com.messagebird.exceptions.NotFoundException; import com.messagebird.exceptions.UnauthorizedException; import com.messagebird.objects.Balance; import com.messagebird.objects.Contact; import com.messagebird.objects.ContactList; import com.messagebird.objects.ContactRequest; import com.messagebird.objects.ErrorReport; import com.messagebird.objects.Group; import com.messagebird.objects.GroupList; import com.messagebird.objects.GroupRequest; import com.messagebird.objects.Hlr; import com.messagebird.objects.Lookup; import com.messagebird.objects.LookupHlr; import com.messagebird.objects.Message; import com.messagebird.objects.MessageList; import com.messagebird.objects.MessageResponse; import com.messagebird.objects.MsgType; import com.messagebird.objects.PagedPaging; import com.messagebird.objects.PhoneNumbersLookup; import com.messagebird.objects.PhoneNumbersResponse; import com.messagebird.objects.PurchasedNumber; import com.messagebird.objects.PurchasedNumberCreatedResponse; import com.messagebird.objects.PurchasedNumbersResponse; import com.messagebird.objects.PurchasedNumbersFilter; import com.messagebird.objects.Verify; import com.messagebird.objects.VerifyRequest; import com.messagebird.objects.VoiceMessage; import com.messagebird.objects.VoiceMessageList; import com.messagebird.objects.VoiceMessageResponse; import com.messagebird.objects.conversations.Conversation; import com.messagebird.objects.conversations.ConversationList; import com.messagebird.objects.conversations.ConversationMessage; import com.messagebird.objects.conversations.ConversationMessageList; import com.messagebird.objects.conversations.ConversationMessageRequest; import com.messagebird.objects.conversations.ConversationStartRequest; import com.messagebird.objects.conversations.ConversationStatus; import com.messagebird.objects.conversations.ConversationWebhook; import com.messagebird.objects.conversations.ConversationWebhookCreateRequest; import com.messagebird.objects.conversations.ConversationWebhookList; import com.messagebird.objects.conversations.ConversationWebhookUpdateRequest; import com.messagebird.objects.voicecalls.RecordingResponse; import com.messagebird.objects.voicecalls.TranscriptionResponse; import com.messagebird.objects.voicecalls.VoiceCall; import com.messagebird.objects.voicecalls.VoiceCallFlowList; import com.messagebird.objects.voicecalls.VoiceCallFlowRequest; import com.messagebird.objects.voicecalls.VoiceCallFlowResponse; import com.messagebird.objects.voicecalls.VoiceCallLeg; import com.messagebird.objects.voicecalls.VoiceCallLegResponse; import com.messagebird.objects.voicecalls.VoiceCallResponse; import com.messagebird.objects.voicecalls.VoiceCallResponseList; import com.messagebird.objects.voicecalls.Webhook; import com.messagebird.objects.voicecalls.WebhookList; import com.messagebird.objects.voicecalls.WebhookResponseData; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.HashSet; public class MessageBirdClient { /** * The Conversations API has a different URL scheme from the other * APIs/endpoints. By default, the service prefixes paths with that URL. We * can, however, override this behaviour by providing absolute URLs * ourselves. */ private static final String BASE_URL_CONVERSATIONS = "https://conversations.messagebird.com/v1"; private static final String BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX = "https://whatsapp-sandbox.messagebird.com/v1"; static final String VOICE_CALLS_BASE_URL = "https://voice.messagebird.com"; static final String NUMBERS_CALLS_BASE_URL = "https://numbers.messagebird.com/v1"; private static String[] supportedLanguages = {"de-DE", "en-AU", "en-UK", "en-US", "es-ES", "es-LA", "fr-FR", "it-IT", "nl-NL", "pt-BR"}; private static final String BALANCEPATH = "/balance"; private static final String CONTACTPATH = "/contacts"; private static final String GROUPPATH = "/groups"; private static final String HLRPATH = "/hlr"; private static final String LOOKUPHLRPATH = "/lookup/%s/hlr"; private static final String LOOKUPPATH = "/lookup"; private static final String MESSAGESPATH = "/messages"; private static final String VERIFYPATH = "/verify"; private static final String VOICEMESSAGESPATH = "/voicemessages"; private static final String CONVERSATION_PATH = "/conversations"; private static final String CONVERSATION_MESSAGE_PATH = "/messages"; private static final String CONVERSATION_WEBHOOK_PATH = "/webhooks"; static final String VOICECALLSPATH = "/calls"; static final String LEGSPATH = "/legs"; static final String RECORDINGPATH = "/recordings"; static final String TRANSCRIPTIONPATH = "/transcriptions"; static final String WEBHOOKS = "/webhooks"; static final String VOICECALLFLOWPATH = "/call-flows"; private static final String VOICELEGS_SUFFIX_PATH = "/legs"; static final String RECORDING_DOWNLOAD_FORMAT = ".wav"; static final String TRANSCRIPTION_DOWNLOAD_FORMAT = ".txt"; private static final int DEFAULT_MACHINE_TIMEOUT_VALUE = 7000; private static final int MIN_MACHINE_TIMEOUT_VALUE = 400; private static final int MAX_MACHINE_TIMEOUT_VALUE = 10000; private static final String[] MESSAGE_LIST_FILTERS_VALS = {"originator", "recipient", "direction", "searchterm", "type", "contact_id", "status", "from", "until"}; private static final Set<String> MESSAGE_LIST_FILTERS = new HashSet<>(Arrays.asList(MESSAGE_LIST_FILTERS_VALS)); private final String DOWNLOADS = "Downloads"; private MessageBirdService messageBirdService; private String conversationsBaseUrl; public enum Feature { ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX } public MessageBirdClient(final MessageBirdService messageBirdService) { this.messageBirdService = messageBirdService; this.conversationsBaseUrl = BASE_URL_CONVERSATIONS; } public MessageBirdClient(final MessageBirdService messageBirdService, List<Feature> features) { this(messageBirdService); if(features.indexOf(Feature.ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX) >= 0) { this.conversationsBaseUrl = BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX; } } /** Balance and HRL methods **/ /** * MessageBird provides an API to get the balance information of your account. * * @return Balance object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Balance getBalance() throws GeneralException, UnauthorizedException, NotFoundException { return messageBirdService.requestByID(BALANCEPATH, "", Balance.class); } /** * MessageBird provides an API to send Network Queries to any mobile number across the world. * An HLR allows you to view which mobile number (MSISDN) belongs to what operator in real time and see whether the number is active. * * @param msisdn The telephone number. * @param reference A client reference * @return Hlr Object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Hlr getRequestHlr(final BigInteger msisdn, final String reference) throws GeneralException, UnauthorizedException { if (msisdn == null) { throw new IllegalArgumentException("msisdn must be specified."); } if (reference == null) { throw new IllegalArgumentException("Reference must be specified."); } final Map<String, Object> payload = new LinkedHashMap<String, Object>(); payload.put("msisdn", msisdn); payload.put("reference", reference); return messageBirdService.sendPayLoad(HLRPATH, payload, Hlr.class); } /** * Retrieves the information of an existing HLR. You only need to supply the unique message id that was returned upon creation or receiving. * * @param hlrId ID as returned by getRequestHlr in the id variable * @return Hlr Object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Hlr getViewHlr(final String hlrId) throws GeneralException, UnauthorizedException, NotFoundException { if (hlrId == null) { throw new IllegalArgumentException("Hrl ID must be specified."); } return messageBirdService.requestByID(HLRPATH, hlrId, Hlr.class); } /** Messaging **/ /** * Send a message through the messagebird platform * * @param message Message object to be send * @return Message Response * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendMessage(final Message message) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(MESSAGESPATH, new Message(originator, body, recipients), MessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @param reference your reference * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException { final Message message = new Message(originator, body, recipients); message.setReference(reference); return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } /** * Convenient function to send a simple flash message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { final Message message = new Message(originator, body, recipients); message.setType(MsgType.flash); return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } /** * Convenient function to send a simple flash message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @param reference your reference * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException { final Message message = new Message(originator, body, recipients); message.setType(MsgType.flash); message.setReference(reference); return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } public MessageList listMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException { verifyOffsetAndLimit(offset, limit); return messageBirdService.requestList(MESSAGESPATH, offset, limit, MessageList.class); } public MessageList listMessagesFiltered(final Integer offset, final Integer limit, final Map<String, Object> filters) throws UnauthorizedException, GeneralException { verifyOffsetAndLimit(offset, limit); for (String filter : filters.keySet()) { if (!MESSAGE_LIST_FILTERS.contains(filter)) { throw new IllegalArgumentException("Invalid filter name: " + filter); } } return messageBirdService.requestList(MESSAGESPATH, filters, offset, limit, MessageList.class); } public void deleteMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Message ID must be specified."); } messageBirdService.deleteByID(MESSAGESPATH, id); } public MessageResponse viewMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Message ID must be specified."); } return messageBirdService.requestByID(MESSAGESPATH, id, MessageResponse.class); } /** Voice Messaging **/ /** * Convenient function to send a simple message to a list of recipients * * @param voiceMessage Voice message object * @return VoiceMessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageResponse sendVoiceMessage(final VoiceMessage voiceMessage) throws UnauthorizedException, GeneralException { addDefaultMachineTimeoutValueIfNotExists(voiceMessage); checkMachineTimeoutValueIsInRange(voiceMessage); return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, voiceMessage, VoiceMessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param body Body of the message * @param recipients List of recipients * @return VoiceMessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { final VoiceMessage message = new VoiceMessage(body, recipients); addDefaultMachineTimeoutValueIfNotExists(message); checkMachineTimeoutValueIsInRange(message); return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param body Body of the message * @param recipients List of recipients * @param reference your reference * @return VoiceMessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException { final VoiceMessage message = new VoiceMessage(body, recipients); message.setReference(reference); addDefaultMachineTimeoutValueIfNotExists(message); checkMachineTimeoutValueIsInRange(message); return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class); } private void addDefaultMachineTimeoutValueIfNotExists(final VoiceMessage voiceMessage){ if (voiceMessage.getMachineTimeout() == 0){ voiceMessage.setMachineTimeout(DEFAULT_MACHINE_TIMEOUT_VALUE); //default machine timeout value } } private void checkMachineTimeoutValueIsInRange(final VoiceMessage voiceMessage){ if (voiceMessage.getMachineTimeout() < MIN_MACHINE_TIMEOUT_VALUE || voiceMessage.getMachineTimeout() > MAX_MACHINE_TIMEOUT_VALUE){ throw new IllegalArgumentException("Please define machine timeout value between " + MIN_MACHINE_TIMEOUT_VALUE + " and " + MAX_MACHINE_TIMEOUT_VALUE); } } public void deleteVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Message ID must be specified."); } messageBirdService.deleteByID(VOICEMESSAGESPATH, id); } public VoiceMessageResponse viewVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Voice Message ID must be specified."); } return messageBirdService.requestByID(VOICEMESSAGESPATH, id, VoiceMessageResponse.class); } /** * List voice messages * * @param offset offset for result list * @param limit limit for result list * @return VoiceMessageList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException { verifyOffsetAndLimit(offset, limit); return messageBirdService.requestList(VOICEMESSAGESPATH, offset, limit, VoiceMessageList.class); } /** * @param verifyRequest includes recipient, originator, reference, type, datacoding, template, timeout, tokenLenght, voice, language * @return Verify object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Verify sendVerifyToken(VerifyRequest verifyRequest) throws UnauthorizedException, GeneralException { if (verifyRequest == null) { throw new IllegalArgumentException("Verify request cannot be null"); } else if (verifyRequest.getRecipient() == null || verifyRequest.getRecipient().isEmpty()) { throw new IllegalArgumentException("Recipient cannot be empty for verify"); } return messageBirdService.sendPayLoad(VERIFYPATH, verifyRequest, Verify.class); } /** * @param recipient The telephone number that you want to verify. * @return Verify object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Verify sendVerifyToken(String recipient) throws UnauthorizedException, GeneralException { if (recipient == null || recipient.isEmpty()) { throw new IllegalArgumentException("Recipient cannot be empty for verify"); } VerifyRequest verifyRequest = new VerifyRequest(recipient); return this.sendVerifyToken(verifyRequest); } public Verify verifyToken(String id, String token) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } else if (token == null || token.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } final Map<String, Object> params = new LinkedHashMap<String, Object>(); params.put("token", token); return messageBirdService.requestByID(VERIFYPATH, id, params, Verify.class); } /** * @param id id is for getting verify object * @return Verify object * @throws NotFoundException if id is not found * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ Verify getVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } return messageBirdService.requestByID(VERIFYPATH, id, Verify.class); } /** * @param id id for deleting verify object * @throws NotFoundException if id is not found * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public void deleteVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } messageBirdService.deleteByID(VERIFYPATH, id); } /** * Send a Lookup request * * @param lookup including with country code, country prefix, phone number, type, formats, country code * @return Lookup * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException if lookup not found */ public Lookup viewLookup(final Lookup lookup) throws UnauthorizedException, GeneralException, NotFoundException { if (lookup.getPhoneNumber() == null) { throw new IllegalArgumentException("PhoneNumber must be specified."); } final Map<String, Object> params = new LinkedHashMap<String, Object>(); if (lookup.getCountryCode() != null) { params.put("countryCode", lookup.getCountryCode()); } return messageBirdService.requestByID(LOOKUPPATH, String.valueOf(lookup.getPhoneNumber()), params, Lookup.class); } /** * Send a Lookup request * * @param phoneNumber phone number is for viewing lookup * @return Lookup * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Lookup viewLookup(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException { if (phoneNumber == null) { throw new IllegalArgumentException("PhoneNumber must be specified."); } final Lookup lookup = new Lookup(phoneNumber); return this.viewLookup(lookup); } /** * Request a Lookup HLR (lookup) * * @param lookupHlr country code for request lookup hlr * @return lookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public LookupHlr requestLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException { if (lookupHlr.getPhoneNumber() == null) { throw new IllegalArgumentException("PhoneNumber must be specified."); } if (lookupHlr.getReference() == null) { throw new IllegalArgumentException("Reference must be specified."); } final Map<String, Object> payload = new LinkedHashMap<String, Object>(); payload.put("phoneNumber", lookupHlr.getPhoneNumber()); payload.put("reference", lookupHlr.getReference()); if (lookupHlr.getCountryCode() != null) { payload.put("countryCode", lookupHlr.getCountryCode()); } return messageBirdService.sendPayLoad(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), payload, LookupHlr.class); } /** * Request a Lookup HLR (lookup) * * @param phoneNumber phone number is for request hlr * @param reference reference for request hlr * @return lookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public LookupHlr requestLookupHlr(final BigInteger phoneNumber, final String reference) throws UnauthorizedException, GeneralException { if (phoneNumber == null) { throw new IllegalArgumentException("Phonenumber must be specified."); } if (reference == null) { throw new IllegalArgumentException("Reference must be specified."); } final LookupHlr lookupHlr = new LookupHlr(); lookupHlr.setPhoneNumber(phoneNumber); lookupHlr.setReference(reference); return this.requestLookupHlr(lookupHlr); } /** * View a Lookup HLR (lookup) * * @param lookupHlr search with country code * @return LookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException if there is no lookup hlr with given country code */ public LookupHlr viewLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException, NotFoundException { if (lookupHlr.getPhoneNumber() == null) { throw new IllegalArgumentException("Phonenumber must be specified"); } final Map<String, Object> params = new LinkedHashMap<String, Object>(); if (lookupHlr.getCountryCode() != null) { params.put("countryCode", lookupHlr.getCountryCode()); } return messageBirdService.requestByID(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), "", params, LookupHlr.class); } /** * View a Lookup HLR (lookup) * * @param phoneNumber phone number for searching on hlr * @return LookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException phone number not found on hlr */ public LookupHlr viewLookupHlr(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException { if (phoneNumber == null) { throw new IllegalArgumentException("phoneNumber must be specified"); } final LookupHlr lookupHlr = new LookupHlr(); lookupHlr.setPhoneNumber(phoneNumber); return this.viewLookupHlr(lookupHlr); } /** * Convenient function to list all call flows * * @param offset * @param limit * @return VoiceCallFlowList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallFlowList listVoiceCallFlows(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException { verifyOffsetAndLimit(offset, limit); String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH); return messageBirdService.requestList(url, offset, limit, VoiceCallFlowList.class); } /** * Retrieves the information of an existing Call Flow. You only need to supply * the unique call flow ID that was returned upon creation or receiving. * @param id String * @return VoiceCallFlowResponse * @throws NotFoundException * @throws GeneralException * @throws UnauthorizedException */ public VoiceCallFlowResponse viewVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Call Flow ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH); return messageBirdService.requestByID(url, id, VoiceCallFlowResponse.class); } /** * Convenient function to create a call flow * * @param voiceCallFlowRequest VoiceCallFlowRequest * @return VoiceCallFlowResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallFlowResponse sendVoiceCallFlow(final VoiceCallFlowRequest voiceCallFlowRequest) throws UnauthorizedException, GeneralException { String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH); return messageBirdService.sendPayLoad(url, voiceCallFlowRequest, VoiceCallFlowResponse.class); } /** * Updates an existing Call Flow. You only need to supply the unique id that * was returned upon creation. * @param id String * @param voiceCallFlowRequest VoiceCallFlowRequest * @return VoiceCallFlowResponse * @throws UnauthorizedException * @throws GeneralException */ public VoiceCallFlowResponse updateVoiceCallFlow(String id, VoiceCallFlowRequest voiceCallFlowRequest) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Call Flow ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH); String request = url + "/" + id; return messageBirdService.sendPayLoad("PUT", request, voiceCallFlowRequest, VoiceCallFlowResponse.class); } /** * Convenient function to delete call flow * * @param id String * @return void * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public void deleteVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Voice Call Flow ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH); messageBirdService.deleteByID(url, id); } /** * Deletes an existing contact. You only need to supply the unique id that * was returned upon creation. */ void deleteContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Contact ID must be specified."); } messageBirdService.deleteByID(CONTACTPATH, id); } /** * Gets a contact listing with specified pagination options. * * @return Listing of Contact objects. */ public ContactList listContacts(int offset, int limit) throws UnauthorizedException, GeneralException { return messageBirdService.requestList(CONTACTPATH, offset, limit, ContactList.class); } /** * Gets a contact listing with default pagination options. */ public ContactList listContacts() throws UnauthorizedException, GeneralException { final int limit = 20; final int offset = 0; return listContacts(offset, limit); } /** * Creates a new contact object. MessageBird returns the created contact * object with each request. */ public Contact sendContact(final ContactRequest contactRequest) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(CONTACTPATH, contactRequest, Contact.class); } /** * Updates an existing contact. You only need to supply the unique id that * was returned upon creation. */ public Contact updateContact(final String id, ContactRequest contactRequest) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Contact ID must be specified."); } String request = CONTACTPATH + "/" + id; return messageBirdService.sendPayLoad("PATCH", request, contactRequest, Contact.class); } /** * Retrieves the information of an existing contact. You only need to supply * the unique contact ID that was returned upon creation or receiving. */ public Contact viewContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Contact ID must be specified."); } return messageBirdService.requestByID(CONTACTPATH, id, Contact.class); } /** * Deletes an existing group. You only need to supply the unique id that * was returned upon creation. */ public void deleteGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Group ID must be specified."); } messageBirdService.deleteByID(GROUPPATH, id); } /** * Removes a contact from group. You need to supply the IDs of the group * and contact. Does not delete the contact. */ public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException { if (groupId == null) { throw new IllegalArgumentException("Group ID must be specified."); } if (contactId == null) { throw new IllegalArgumentException("Contact ID must be specified."); } String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId); messageBirdService.deleteByID(GROUPPATH, id); } /** * Gets a contact listing with specified pagination options. */ public GroupList listGroups(final int offset, final int limit) throws UnauthorizedException, GeneralException { return messageBirdService.requestList(GROUPPATH, offset, limit, GroupList.class); } /** * Gets a contact listing with default pagination options. */ public GroupList listGroups() throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 20; return listGroups(offset, limit); } /** * Creates a new group object. MessageBird returns the created group object * with each request. */ public Group sendGroup(final GroupRequest groupRequest) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(GROUPPATH, groupRequest, Group.class); } /** * Adds contact to group. You need to supply the IDs of the group and * contact. */ public void sendGroupContact(final String groupId, final String[] contactIds) throws NotFoundException, GeneralException, UnauthorizedException { // reuestByID appends the "ID" to the base path, so this workaround // lets us add a query string. String path = String.format("%s%s?%s", groupId, CONTACTPATH, getQueryString(contactIds)); messageBirdService.requestByID(GROUPPATH, path, null); } private String getQueryString(final String[] contactIds) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("_method=PUT"); for (String groupId : contactIds) { stringBuilder.append("&ids[]=").append(groupId); } return stringBuilder.toString(); } /** * Updates an existing group. You only need to supply the unique ID that * was returned upon creation. */ public Group updateGroup(final String id, final GroupRequest groupRequest) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Group ID must be specified."); } String path = String.format("%s/%s", GROUPPATH, id); return messageBirdService.sendPayLoad("PATCH", path, groupRequest, Group.class); } /** * Retrieves the information of an existing group. You only need to supply * the unique group ID that was returned upon creation or receiving. */ public Group viewGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Group ID must be specified."); } return messageBirdService.requestByID(GROUPPATH, id, Group.class); } /** * Gets a single conversation. * * @param id Conversation to retrieved. * @return The retrieved conversation. */ public Conversation viewConversation(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Id must be specified"); } String url = this.conversationsBaseUrl + CONVERSATION_PATH; return messageBirdService.requestByID(url, id, Conversation.class); } /** * Updates a conversation. * * @param id Conversation to update. * @param status New status for the conversation. * @return The updated Conversation. */ public Conversation updateConversation(final String id, final ConversationStatus status) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Id must be specified."); } String url = String.format("%s%s/%s", this.conversationsBaseUrl, CONVERSATION_PATH, id); return messageBirdService.sendPayLoad("PATCH", url, status, Conversation.class); } /** * Gets a Conversation listing with specified pagination options. * * @param offset Number of objects to skip. * @param limit Number of objects to take. * @return List of conversations. */ public ConversationList listConversations(final int offset, final int limit) throws UnauthorizedException, GeneralException { String url = this.conversationsBaseUrl + CONVERSATION_PATH; return messageBirdService.requestList(url, offset, limit, ConversationList.class); } /** * Gets a contact listing with default pagination options. * * @return List of conversations. */ public ConversationList listConversations() throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 10; return listConversations(offset, limit); } /** * Starts a conversation by sending an initial message. * * @param request Data for this request. * @return The created Conversation. */ public Conversation startConversation(ConversationStartRequest request) throws UnauthorizedException, GeneralException { String url = String.format("%s%s/start", this.conversationsBaseUrl, CONVERSATION_PATH); return messageBirdService.sendPayLoad(url, request, Conversation.class); } /** * Gets a ConversationMessage listing with specified pagination options. * * @param conversationId Conversation to get messages for. * @param offset Number of objects to skip. * @param limit Number of objects to take. * @return List of messages. */ public ConversationMessageList listConversationMessages( final String conversationId, final int offset, final int limit ) throws UnauthorizedException, GeneralException { String url = String.format( "%s%s/%s%s", this.conversationsBaseUrl, CONVERSATION_PATH, conversationId, CONVERSATION_MESSAGE_PATH ); return messageBirdService.requestList(url, offset, limit, ConversationMessageList.class); } /** * Gets a ConversationMessage listing with default pagination options. * * @param conversationId Conversation to get messages for. * @return List of messages. */ public ConversationMessageList listConversationMessages( final String conversationId ) throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 10; return listConversationMessages(conversationId, offset, limit); } /** * Gets a single message. * * @param messageId Message to retrieve. * @return The retrieved message. */ public ConversationMessage viewConversationMessage(final String messageId) throws NotFoundException, GeneralException, UnauthorizedException { String url = this.conversationsBaseUrl + CONVERSATION_MESSAGE_PATH; return messageBirdService.requestByID(url, messageId, ConversationMessage.class); } /** * Sends a message to an existing Conversation. * * @param conversationId Conversation to send message to. * @param request Message to send. * @return The newly created message. */ public ConversationMessage sendConversationMessage( final String conversationId, final ConversationMessageRequest request ) throws UnauthorizedException, GeneralException { String url = String.format( "%s%s/%s%s", this.conversationsBaseUrl, CONVERSATION_PATH, conversationId, CONVERSATION_MESSAGE_PATH ); return messageBirdService.sendPayLoad(url, request, ConversationMessage.class); } /** * Deletes a webhook. * * @param webhookId Webhook to delete. */ public void deleteConversationWebhook(final String webhookId) throws NotFoundException, GeneralException, UnauthorizedException { String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH; messageBirdService.deleteByID(url, webhookId); } /** * Creates a new webhook. * * @param request Webhook to create. * @return Newly created webhook. */ public ConversationWebhook sendConversationWebhook(final ConversationWebhookCreateRequest request) throws UnauthorizedException, GeneralException { String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH; return messageBirdService.sendPayLoad(url, request, ConversationWebhook.class); } /** * Update an existing webhook. * * @param request update request. * @return Updated webhook. */ public ConversationWebhook updateConversationWebhook(final String id, final ConversationWebhookUpdateRequest request) throws UnauthorizedException, GeneralException { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("Conversation webhook ID must be specified."); } String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH + "/" + id; return messageBirdService.sendPayLoad("PATCH", url, request, ConversationWebhook.class); } /** * Gets a single webhook. * * @param webhookId Webhook to retrieve. * @return The retrieved webhook. */ public ConversationWebhook viewConversationWebhook(final String webhookId) throws NotFoundException, GeneralException, UnauthorizedException { String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH; return messageBirdService.requestByID(url, webhookId, ConversationWebhook.class); } /** * Gets a ConversationWebhook listing with the specified pagination options. * * @param offset Number of objects to skip. * @param limit Number of objects to skip. * @return List of webhooks. */ public ConversationWebhookList listConversationWebhooks(final int offset, final int limit) throws UnauthorizedException, GeneralException { String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH; return messageBirdService.requestList(url, offset, limit, ConversationWebhookList.class); } /** * Gets a ConversationWebhook listing with default pagination options. * * @return List of webhooks. */ public ConversationWebhookList listConversationWebhooks() throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 10; return listConversationWebhooks(offset, limit); } /** * Function for voice call to a number * * @param voiceCall Voice call object * @return VoiceCallResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallResponse sendVoiceCall(final VoiceCall voiceCall) throws UnauthorizedException, GeneralException { if (voiceCall.getSource() == null) { throw new IllegalArgumentException("Source of voice call must be specified."); } if (voiceCall.getDestination() == null) { throw new IllegalArgumentException("Destination of voice call must be specified."); } if (voiceCall.getCallFlow() == null) { throw new IllegalArgumentException("Call flow of voice call must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); return messageBirdService.sendPayLoad(url, voiceCall, VoiceCallResponse.class); } /** * Function to list all voice calls * * @return VoiceCallResponseList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallResponseList listAllVoiceCalls(Integer page, Integer pageSize) throws GeneralException, UnauthorizedException { String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallResponseList.class); } /** * Function to view voice call by id * * @param id Voice call ID * @return VoiceCallResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallResponse viewVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Voice Message ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); return messageBirdService.requestByID(url, id, VoiceCallResponse.class); } /** * Function to delete voice call by id * * @param id Voice call ID * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public void deleteVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Voice Message ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); messageBirdService.deleteByID(url, id); } /** * Retrieves a listing of all legs. * * @param callId Voice call ID * @param page page to fetch (can be null - will return first page), number of first page is 1 * @param pageSize page size * @return VoiceCallLegResponse * @throws UnsupportedEncodingException no UTF8 supported url * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallLegResponse viewCallLegsByCallId(String callId, Integer page, Integer pageSize) throws UnsupportedEncodingException, UnauthorizedException, GeneralException { if (callId == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } String url = String.format( "%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, urlEncode(callId), VOICELEGS_SUFFIX_PATH); return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallLegResponse.class); } /** * Retrieves a leg resource. * The parameters are the unique ID of the call and of the leg that were returned upon their respective creation. * * @param callId Voice call ID * @param legId ID of leg of specified call {callId} * @return VoiceCallLeg * @throws UnsupportedEncodingException no UTF8 supported url * @throws NotFoundException not found with callId and legId * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallLeg viewCallLegByCallIdAndLegId(final String callId, String legId) throws UnsupportedEncodingException, NotFoundException, GeneralException, UnauthorizedException { if (callId == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } String url = String.format( "%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, urlEncode(callId), VOICELEGS_SUFFIX_PATH); VoiceCallLegResponse response = messageBirdService.requestByID(url, legId, VoiceCallLegResponse.class); if (response.getData().size() == 1) { return response.getData().get(0); } else { throw new NotFoundException("No such leg", new LinkedList<ErrorReport>()); } } private String urlEncode(String s) throws UnsupportedEncodingException { return URLEncoder.encode(s, String.valueOf(StandardCharsets.UTF_8)); } /** * Function to view recording by call id , leg id and recording id * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @return Recording * @throws NotFoundException not found with callId and legId * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public RecordingResponse viewRecording(String callID, String legId, String recordingId) throws NotFoundException, GeneralException, UnauthorizedException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); Map<String, Object> params = new LinkedHashMap<>(); params.put("legs", legId); params.put("recordings", recordingId); return messageBirdService.requestByID(url, callID, params, RecordingResponse.class); } /** * Downloads the record in .wav format by using callId, legId and recordId and stores to basePath. basePath is not mandatory to set. * If basePath is not set, default download will be the /Download folder in user group. * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @param basePath store location. It should be directory. Property is Optional if $HOME is accessible * @return the path that file is stored * @throws NotFoundException if the recording does not found * @throws GeneralException general exception * @throws UnauthorizedException if client is unauthorized */ public String downloadRecording(String callID, String legId, String recordingId, String basePath) throws NotFoundException, GeneralException, UnauthorizedException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } String url = String.format( "%s%s/%s%s/%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH, recordingId, RECORDING_DOWNLOAD_FORMAT ); String fileName = String.format("%s%s",recordingId, RECORDING_DOWNLOAD_FORMAT); return messageBirdService.getBinaryData(url, basePath, fileName); } /** * List the all recordings related to CallID and LegId * * @param callID Voice call ID * @param legId Leg ID * @param offset Number of objects to skip. * @param limit Number of objects to take. * @return Recordings for CallID and LegID * @throws GeneralException if client is unauthorized * @throws UnauthorizedException general exception */ public RecordingResponse listRecordings(String callID, String legId, final Integer offset, final Integer limit) throws GeneralException, UnauthorizedException { verifyOffsetAndLimit(offset, limit); if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } String url = String.format( "%s%s/%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH); return messageBirdService.requestList(url, offset, limit, RecordingResponse.class); } /** * Function to view recording by call id , leg id and recording id * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @param language Language * @return TranscriptionResponseList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public TranscriptionResponse createTranscription(String callID, String legId, String recordingId, String language) throws UnauthorizedException, GeneralException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } if (language == null) { throw new IllegalArgumentException("Language must be specified."); } if (!Arrays.asList(supportedLanguages).contains(language)) { throw new IllegalArgumentException("Your language is not allowed."); } String url = String.format( "%s%s/%s%s/%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH, recordingId, TRANSCRIPTIONPATH); return messageBirdService.sendPayLoad(url, language, TranscriptionResponse.class); } /** * Function to view recording by call id, leg id and recording id * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @param transcriptionId Transcription ID * @return Transcription * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException If transcription is not found */ public TranscriptionResponse viewTranscription(String callID, String legId, String recordingId, String transcriptionId) throws UnauthorizedException, GeneralException, NotFoundException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } if(transcriptionId == null) { throw new IllegalArgumentException("Transcription ID must be specified."); } String url = String.format( "%s%s/%s%s/%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH, recordingId, TRANSCRIPTIONPATH); return messageBirdService.requestByID(url, transcriptionId, TranscriptionResponse.class); } /** * Lists the Transcription of callId, legId and recordId * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @param page page to fetch (can be null - will return first page), number of first page is 1 * @param pageSize page size * @return List of Transcription * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public TranscriptionResponse listTranscriptions(String callID, String legId, String recordingId, Integer page, Integer pageSize) throws UnauthorizedException, GeneralException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } String url = String.format( "%s%s/%s%s/%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH, recordingId, TRANSCRIPTIONPATH); return messageBirdService.requestList(url, new PagedPaging(page, pageSize), TranscriptionResponse.class); } /** * Downloads the transcription in .txt format by using callId, legId, recordId and transcriptionId and stores to basePath. basePath is not mandatory to set. * If basePath is not set, default download will be the /Download folder in user group. * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @param transcriptionId Transcription ID * @param basePath store location. It should be directory. Property is Optional if $HOME is accessible * @return the path that file is stored * @throws NotFoundException if the recording does not found * @throws GeneralException general exception * @throws UnauthorizedException if client is unauthorized */ public String downloadTranscription(String callID, String legId, String recordingId, String transcriptionId, String basePath) throws UnauthorizedException, GeneralException, NotFoundException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } if (transcriptionId == null) { throw new IllegalArgumentException("Transcription ID must be specified."); } String fileName = String.format("%s%s", transcriptionId, TRANSCRIPTION_DOWNLOAD_FORMAT); String url = String.format( "%s%s/%s%s/%s%s/%s%s/%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH, recordingId, TRANSCRIPTIONPATH, fileName); return messageBirdService.getBinaryData(url, basePath, fileName); } /** * Function to create a webhook * * @param webhook webhook to create * @return WebhookResponseData created webhook * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public WebhookResponseData createWebhook(Webhook webhook) throws UnauthorizedException, GeneralException { if (webhook.getUrl() == null) { throw new IllegalArgumentException("URL of webhook must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS); return messageBirdService.sendPayLoad(url, webhook, WebhookResponseData.class); } /** * Function to update a webhook * * @param webhook webhook fields to update * @return WebhookResponseData updated webhook * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public WebhookResponseData updateWebhook(String id, Webhook webhook) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Id of webhook must be specified."); } String url = String.format("%s%s/%s", VOICE_CALLS_BASE_URL, WEBHOOKS, id); return messageBirdService.sendPayLoad("PUT", url, webhook, WebhookResponseData.class); } /** * Function to view a webhook * * @param id id of a webhook * @return WebhookResponseData * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public WebhookResponseData viewWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Id of webhook must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS); return messageBirdService.requestByID(url, id, WebhookResponseData.class); } /** * Function to list webhooks * * @param offset offset for result list * @param limit limit for result list * @return WebhookList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public WebhookList listWebhooks(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException { verifyOffsetAndLimit(offset, limit); String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS); return messageBirdService.requestList(url, offset, limit, WebhookList.class); } public void deleteWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Webhook ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS); messageBirdService.deleteByID(url, id); } private void verifyOffsetAndLimit(Integer offset, Integer limit) { if (offset != null && offset < 0) { throw new IllegalArgumentException("Offset must be > 0"); } if (limit != null && limit < 0) { throw new IllegalArgumentException("Limit must be > 0"); } } private void countryCodeIsValid(String countryCode) throws IllegalArgumentException { final boolean isValid = Arrays.asList(Locale.getISOCountries()).contains(countryCode); if (!isValid) { throw new IllegalArgumentException("Invalid Country Code Provided."); } } public PhoneNumbersResponse listNumbersForPurchase(String countryCode) throws GeneralException, UnauthorizedException, NotFoundException, IllegalArgumentException { countryCodeIsValid(countryCode); final String url = String.format("%s/available-phone-numbers", NUMBERS_CALLS_BASE_URL); return messageBirdService.requestByID(url, countryCode, PhoneNumbersResponse.class); } public PhoneNumbersResponse listNumbersForPurchase(String countryCode, PhoneNumbersLookup params) throws GeneralException, UnauthorizedException, NotFoundException, IllegalArgumentException { countryCodeIsValid(countryCode); final String url = String.format("%s/available-phone-numbers", NUMBERS_CALLS_BASE_URL); return messageBirdService.requestByID(url, countryCode, params.toHashMap(), PhoneNumbersResponse.class); } public PurchasedNumberCreatedResponse purchaseNumber(String number, String countryCode, int billingIntervalMonths) throws UnauthorizedException, GeneralException, IllegalArgumentException { countryCodeIsValid(countryCode); final String url = String.format("%s/phone-numbers", NUMBERS_CALLS_BASE_URL); final Map<String, Object> payload = new LinkedHashMap<String, Object>(); payload.put("number", number); payload.put("countryCode", countryCode); if (!Arrays.asList(1, 3, 6, 9).contains(billingIntervalMonths)) { throw new IllegalArgumentException("Billing Interval Must Be Either 1, 3, 6, or 9."); } payload.put("billingIntervalMonths", billingIntervalMonths); return messageBirdService.sendPayLoad(url, payload, PurchasedNumberCreatedResponse.class); } /** * Lists Numbers that were purchased using the account credentials that the client was initialized with. * * @param filter Filters the list of purchased numbers according to search criteria. * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException if the resource is missing */ public PurchasedNumbersResponse listPurchasedNumbers(PurchasedNumbersFilter filter) throws UnauthorizedException, GeneralException, NotFoundException { final String url = String.format("%s/phone-numbers", NUMBERS_CALLS_BASE_URL); return messageBirdService.requestByID(url, null, filter.toHashMap(), PurchasedNumbersResponse.class); } /** * Returns a Number that has already been purchased on the initialized account. * * @param number The number whose data should be returned. * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException if the Number is missing */ public PurchasedNumber viewPurchasedNumber(String number) throws UnauthorizedException, GeneralException, NotFoundException { final String url = String.format("%s/phone-numbers", NUMBERS_CALLS_BASE_URL); return messageBirdService.requestByID(url, number, PurchasedNumber.class); } /** * Updates tags on a particular existing Number. Any number of parameters after the number can be given to apply multiple tags. * * @param number The number to update. * @param tags A tag to apply to the number. * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public PurchasedNumber updateNumber(String number, String... tags) throws UnauthorizedException, GeneralException { final String url = String.format("%s/phone-numbers/%s", NUMBERS_CALLS_BASE_URL, number); final Map<String, List<String>> payload = new HashMap<String, List<String>>(); payload.put("tags", Arrays.asList(tags)); return messageBirdService.sendPayLoad("PATCH", url, payload, PurchasedNumber.class); } /** * Cancels a particular number. * * @param number The number to cancel. * @throws GeneralException general exception * @throws UnauthorizedException if client is unauthorized * @throws NotFoundException if the resource is missing */ public void cancelNumber(String number) throws UnauthorizedException, GeneralException, NotFoundException { final String url = String.format("%s/phone-numbers", NUMBERS_CALLS_BASE_URL); messageBirdService.deleteByID(url, number); } }
package com.github.ferstl.depgraph; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.maven.artifact.resolver.filter.AndArtifactFilter; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.artifact.filter.ScopeArtifactFilter; import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilter; import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException; import org.apache.maven.shared.dependency.graph.DependencyNode; import com.github.ferstl.depgraph.dot.DotBuilder; import com.google.common.base.Charsets; import com.google.common.io.Files; @Mojo( name = "aggregate", aggregator = true, defaultPhase = LifecyclePhase.NONE, inheritByDefault = false, requiresDependencyCollection = ResolutionScope.TEST, requiresDirectInvocation = true, threadSafe = true) public class DepGraphMojo extends AbstractMojo { @Parameter(property = "scope") private String scope; @Parameter(property = "includes", defaultValue = "") private List<String> includes; @Parameter(property = "excludes", defaultValue = "") private List<String> excludes; @Parameter(property = "outputFile", defaultValue = "${project.build.directory}/dependency-graph.dot") private File outputFile; @Component private MavenProject project; @Component( hint = "default" ) private DependencyGraphBuilder dependencyGraphBuilder; @Override public void execute() throws MojoExecutionException { ArtifactFilter filter = createArtifactFilters(); try { DotBuilder dotBuilder = new DotBuilder(ArtifactIdRenderer.VERSIONLESS_ID, ArtifactIdRenderer.ARTIFACT_ID); @SuppressWarnings("unchecked") List<MavenProject> collectedProjects = this.project.getCollectedProjects(); buildModuleTree(collectedProjects, dotBuilder); for (MavenProject collectedProject : collectedProjects) { DependencyNode root = this.dependencyGraphBuilder.buildDependencyGraph(collectedProject, filter); DotBuildingVisitor visitor = new DotBuildingVisitor(dotBuilder); root.accept(visitor); } writeDotFile(dotBuilder); System.err.println(dotBuilder); } catch (DependencyGraphBuilderException | IOException e) { throw new MojoExecutionException("Unable to create dependency graph.", e); } } private void writeDotFile(DotBuilder dotBuilder) throws IOException { Files.createParentDirs(this.outputFile); try(Writer writer = Files.newWriter(this.outputFile, Charsets.UTF_8)) { writer.write(dotBuilder.toString()); } } private ArtifactFilter createArtifactFilters() { List<ArtifactFilter> filters = new ArrayList<>(3); if (this.scope != null) { filters.add(new ScopeArtifactFilter(this.scope)); } if (!this.includes.isEmpty()) { filters.add(new StrictPatternIncludesArtifactFilter(this.includes)); } if (!this.excludes.isEmpty()) { filters.add(new StrictPatternExcludesArtifactFilter(this.excludes)); } return new AndArtifactFilter(filters); } private void buildModuleTree(Collection<MavenProject> collectedProjects, DotBuilder dotBuilder) { // FIXME apply filters here for (MavenProject collectedProject : collectedProjects) { MavenProject child = collectedProject; MavenProject parent = collectedProject.getParent(); while (parent != null) { ArtifactNode parentNode = new ArtifactNode(parent.getArtifact()); ArtifactNode childNode = new ArtifactNode(child.getArtifact()); dotBuilder.addEdge(parentNode, childNode); child = parent; parent = parent.getParent(); } } } }
package com.gocardless.resources; import com.google.gson.annotations.SerializedName; import java.util.List; import java.util.Map; /** * Represents a billing request resource returned from the API. * * Billing Requests */ public class BillingRequest { private BillingRequest() { // blank to prevent instantiation } private List<Action> actions; private String createdAt; private String id; private Links links; private MandateRequest mandateRequest; private Map<String, String> metadata; private PaymentRequest paymentRequest; private Resources resources; private Status status; /** * List of actions that can be performed before this billing request can be fulfilled. */ public List<Action> getActions() { return actions; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was created. */ public String getCreatedAt() { return createdAt; } /** * Unique identifier, beginning with "BRQ". */ public String getId() { return id; } public Links getLinks() { return links; } /** * Request for a mandate */ public MandateRequest getMandateRequest() { return mandateRequest; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } /** * Request for a one-off strongly authorised payment */ public PaymentRequest getPaymentRequest() { return paymentRequest; } public Resources getResources() { return resources; } /** * One of: * <ul> * <li>`pending`: the billing_request is pending and can be used</li> * <li>`ready_to_fulfil`: the billing_request is ready to fulfil</li> * <li>`fulfilled`: the billing_request has been fulfilled and a payment created</li> * <li>`cancelled`: the billing_request has been cancelled and cannot be used</li> * </ul> */ public Status getStatus() { return status; } public enum Status { @SerializedName("pending") PENDING, @SerializedName("ready_to_fulfil") READY_TO_FULFIL, @SerializedName("fulfilled") FULFILLED, @SerializedName("cancelled") CANCELLED, @SerializedName("unknown") UNKNOWN } public static class Action { private Action() { // blank to prevent instantiation } private List<String> completesActions; private Boolean required; private List<String> requiresActions; private Status status; private Type type; /** * Which other action types this action can complete. */ public List<String> getCompletesActions() { return completesActions; } /** * Informs you whether the action is required to fulfil the billing request or not. */ public Boolean getRequired() { return required; } /** * Requires completing these actions before this action can be completed. */ public List<String> getRequiresActions() { return requiresActions; } /** * Status of the action */ public Status getStatus() { return status; } /** * Unique identifier for the action. */ public Type getType() { return type; } public enum Status { @SerializedName("pending") PENDING, @SerializedName("completed") COMPLETED, @SerializedName("unknown") UNKNOWN } public enum Type { @SerializedName("choose_currency") CHOOSE_CURRENCY, @SerializedName("collect_customer_details") COLLECT_CUSTOMER_DETAILS, @SerializedName("collect_bank_account") COLLECT_BANK_ACCOUNT, @SerializedName("bank_authorisation") BANK_AUTHORISATION, @SerializedName("unknown") UNKNOWN } } public static class Links { private Links() { // blank to prevent instantiation } private String bankAuthorisation; private String creditor; private String customer; private String customerBankAccount; private String customerBillingDetail; private String mandateRequest; private String mandateRequestMandate; private String paymentRequest; private String paymentRequestPayment; /** * (Optional) ID of the [bank authorisation](#billing-requests-bank-authorisations) that was * used to verify this request. */ public String getBankAuthorisation() { return bankAuthorisation; } /** * ID of the associated [creditor](#core-endpoints-creditors). */ public String getCreditor() { return creditor; } /** * ID of the [customer](#core-endpoints-customers) that will be used for this request */ public String getCustomer() { return customer; } /** * (Optional) ID of the [customer_bank_account](#core-endpoints-customer-bank-accounts) that * will be used for this request */ public String getCustomerBankAccount() { return customerBankAccount; } /** * ID of the customer billing detail that will be used for this request */ public String getCustomerBillingDetail() { return customerBillingDetail; } /** * (Optional) ID of the associated mandate request */ public String getMandateRequest() { return mandateRequest; } /** * (Optional) ID of the [mandate](#core-endpoints-mandates) that was created from this * mandate request. this mandate request. */ public String getMandateRequestMandate() { return mandateRequestMandate; } /** * (Optional) ID of the associated payment request */ public String getPaymentRequest() { return paymentRequest; } /** * (Optional) ID of the [payment](#core-endpoints-payments) that was created from this * payment request. */ public String getPaymentRequestPayment() { return paymentRequestPayment; } } /** * Represents a mandate request resource returned from the API. * * Request for a mandate */ public static class MandateRequest { private MandateRequest() { // blank to prevent instantiation } private String currency; private Links links; private String scheme; public String getCurrency() { return currency; } public Links getLinks() { return links; } /** * A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs", "becs_nz", * "betalingsservice", "pad" and "sepa_core" are supported. */ public String getScheme() { return scheme; } public static class Links { private Links() { // blank to prevent instantiation } private String mandate; /** * (Optional) ID of the [mandate](#core-endpoints-mandates) that was created from this * mandate request. this mandate request. * */ public String getMandate() { return mandate; } } } /** * Represents a payment request resource returned from the API. * * Request for a one-off strongly authorised payment */ public static class PaymentRequest { private PaymentRequest() { // blank to prevent instantiation } private Integer amount; private Integer appFee; private String currency; private String description; private Links links; private String scheme; /** * Amount in minor unit (e.g. pence in GBP, cents in EUR). */ public Integer getAmount() { return amount; } /** * The amount to be deducted from the payment as an app fee, to be paid to the partner * integration which created the billing request, in the lowest denomination for the * currency (e.g. pence in GBP, cents in EUR). */ public Integer getAppFee() { return appFee; } public String getCurrency() { return currency; } /** * A human-readable description of the payment. This will be displayed to the payer when * authorising the billing request. * */ public String getDescription() { return description; } public Links getLinks() { return links; } /** * A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs", "becs_nz", * "betalingsservice", "pad" and "sepa_core" are supported. */ public String getScheme() { return scheme; } public static class Links { private Links() { // blank to prevent instantiation } private String payment; /** * (Optional) ID of the [payment](#core-endpoints-payments) that was created from this * payment request. */ public String getPayment() { return payment; } } } public static class Resources { private Resources() { // blank to prevent instantiation } private Customer customer; private CustomerBankAccount customerBankAccount; private CustomerBillingDetail customerBillingDetail; /** * Embedded customer */ public Customer getCustomer() { return customer; } /** * Embedded customer bank account, only if a bank account is linked */ public CustomerBankAccount getCustomerBankAccount() { return customerBankAccount; } /** * Embedded customer billing detail */ public CustomerBillingDetail getCustomerBillingDetail() { return customerBillingDetail; } /** * Represents a customer resource returned from the API. * * Embedded customer */ public static class Customer { private Customer() { // blank to prevent instantiation } private String companyName; private String createdAt; private String email; private String familyName; private String givenName; private String id; private String language; private Map<String, String> metadata; private String phoneNumber; /** * Customer's company name. Required unless a `given_name` and `family_name` are * provided. For Canadian customers, the use of a `company_name` value will mean that * any mandate created from this customer will be considered to be a "Business PAD" * (otherwise, any mandate will be considered to be a "Personal PAD"). */ public String getCompanyName() { return companyName; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * created. */ public String getCreatedAt() { return createdAt; } /** * Customer's email address. Required in most cases, as this allows GoCardless to send * notifications to this customer. */ public String getEmail() { return email; } /** * Customer's surname. Required unless a `company_name` is provided. */ public String getFamilyName() { return familyName; } /** * Customer's first name. Required unless a `company_name` is provided. */ public String getGivenName() { return givenName; } /** * Unique identifier, beginning with "CU". */ public String getId() { return id; } public String getLanguage() { return language; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } public String getPhoneNumber() { return phoneNumber; } } /** * Represents a customer bank account resource returned from the API. * * Embedded customer bank account, only if a bank account is linked */ public static class CustomerBankAccount { private CustomerBankAccount() { // blank to prevent instantiation } private String accountHolderName; private String accountNumberEnding; private AccountType accountType; private String bankName; private String countryCode; private String createdAt; private String currency; private Boolean enabled; private String id; private Links links; private Map<String, String> metadata; /** * Name of the account holder, as known by the bank. Usually this is the same as the * name stored with the linked [creditor](#core-endpoints-creditors). This field will be * transliterated, upcased and truncated to 18 characters. This field is required unless * the request includes a [customer bank account * token](#javascript-flow-customer-bank-account-tokens). */ public String getAccountHolderName() { return accountHolderName; } /** * The last few digits of the account number. Currently 4 digits for NZD bank accounts * and 2 digits for other currencies. */ public String getAccountNumberEnding() { return accountNumberEnding; } /** * Bank account type. Required for USD-denominated bank accounts. Must not be provided * for bank accounts in other currencies. See [local * details](#local-bank-details-united-states) for more information. */ public AccountType getAccountType() { return accountType; } /** * Name of bank, taken from the bank details. */ public String getBankName() { return bankName; } public String getCountryCode() { return countryCode; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * created. */ public String getCreatedAt() { return createdAt; } public String getCurrency() { return currency; } /** * Boolean value showing whether the bank account is enabled or disabled. */ public Boolean getEnabled() { return enabled; } /** * Unique identifier, beginning with "BA". */ public String getId() { return id; } public Links getLinks() { return links; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } public enum AccountType { @SerializedName("savings") SAVINGS, @SerializedName("checking") CHECKING, @SerializedName("unknown") UNKNOWN } public static class Links { private Links() { // blank to prevent instantiation } private String customer; /** * ID of the [customer](#core-endpoints-customers) that owns this bank account. */ public String getCustomer() { return customer; } } } /** * Represents a customer billing detail resource returned from the API. * * Embedded customer billing detail */ public static class CustomerBillingDetail { private CustomerBillingDetail() { // blank to prevent instantiation } private String addressLine1; private String addressLine2; private String addressLine3; private String city; private String countryCode; private String createdAt; private String danishIdentityNumber; private String id; private String postalCode; private String region; private List<String> schemes; private String swedishIdentityNumber; /** * The first line of the customer's address. */ public String getAddressLine1() { return addressLine1; } /** * The second line of the customer's address. */ public String getAddressLine2() { return addressLine2; } /** * The third line of the customer's address. */ public String getAddressLine3() { return addressLine3; } /** * The city of the customer's address. */ public String getCity() { return city; } public String getCountryCode() { return countryCode; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * created. */ public String getCreatedAt() { return createdAt; } /** * For Danish customers only. The civic/company number (CPR or CVR) of the customer. * Must be supplied if the customer's bank account is denominated in Danish krone (DKK). */ public String getDanishIdentityNumber() { return danishIdentityNumber; } /** * Unique identifier, beginning with "CU". */ public String getId() { return id; } /** * The customer's postal code. */ public String getPostalCode() { return postalCode; } public String getRegion() { return region; } /** * The schemes associated with this customer billing detail */ public List<String> getSchemes() { return schemes; } /** * For Swedish customers only. The civic/company number (personnummer, * samordningsnummer, or organisationsnummer) of the customer. Must be supplied if the * customer's bank account is denominated in Swedish krona (SEK). This field cannot be * changed once it has been set. */ public String getSwedishIdentityNumber() { return swedishIdentityNumber; } } } }
package com.google.research.bleth.utils; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; /** A utility class providing method for db related operations, such as join and group by. */ public class Queries { /** * Given a primary entity kind, a secondary entity kind, a foreign key and a filter, return a list of all entities * of the secondary entity matching an entity of the primary entity kind. * * Equivalent SQL syntax: * * SELECT secondaryEntityKind.a_1, ... secondaryEntityKind.a_n * FROM primaryEntityKind INNER JOIN secondaryEntityKind * ON primaryEntityKind.__key__ = secondaryEntityKind.foreignKey * WHERE primaryEntityFilter * * @param primaryEntityKind is the primary entity kind. * @param secondaryEntityKind is the secondary entity kind. * @param foreignKey is the join property of secondaryEntityKind (the join property of primaryEntityKind is the key). * @param primaryEntityFilter is a simple or composed filter to apply on primaryEntityKind prior to the join operation (optional). * @return a list of secondary entities matching the primary entities retrieved. */ public static List<Entity> Join(String primaryEntityKind, String secondaryEntityKind, String foreignKey, Optional<Query.Filter> primaryEntityFilter) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); List<Entity> result = new ArrayList<>(); // Retrieve all primaryEntity keys ordered by their key, filtered by primaryEntityFilter (if provided). Query primaryMatchingFilterCondition = new Query(primaryEntityKind); primaryEntityFilter.ifPresent(primaryMatchingFilterCondition::setFilter); Iterator<String> primaryKeyIterator = datastore.prepare(primaryMatchingFilterCondition) .asList(FetchOptions.Builder.withDefaults()) .stream() .map(entity -> KeyFactory.keyToString(entity.getKey())) .sorted() .iterator(); // Retrieve all secondaryEntity ordered by their foreignKey. Query secondary = new Query(secondaryEntityKind) .addSort(foreignKey, Query.SortDirection.ASCENDING); Iterator<Entity> secondaryEntityIterator = datastore.prepare(secondary).asIterator(); // If one of these queries is empty, return an empty list. if (!(primaryKeyIterator.hasNext() && secondaryEntityIterator.hasNext())) { return result; } // Iterate over two queries results and add secondary entities with a matching foreign key. String primaryKey = primaryKeyIterator.next(); Entity secondaryEntity = secondaryEntityIterator.next(); String secondaryKey = String.valueOf(secondaryEntity.getProperty(foreignKey)); while (primaryKeyIterator.hasNext() && secondaryEntityIterator.hasNext()) { if (primaryKey.compareTo(secondaryKey) > 0) { secondaryEntity = secondaryEntityIterator.next(); secondaryKey = (String) secondaryEntity.getProperty(foreignKey); } else if (primaryKey.compareTo(secondaryKey) < 0) { primaryKey = primaryKeyIterator.next(); } else { result.add(secondaryEntity); primaryKey = primaryKeyIterator.next(); secondaryEntity = secondaryEntityIterator.next(); secondaryKey = (String) secondaryEntity.getProperty(foreignKey); } } // Add last entity to result (if matching). if (primaryKey.compareTo(secondaryKey) == 0) { result.add(secondaryEntity); } return result; } }
package com.imsweb.seerapi.client.ndc; import java.util.HashMap; import java.util.Map; public class NdcSearch { private String _query; private Boolean _includeRemoved; private String _addedSince; private String _modifiedSince; private String _removedSince; private Integer _page; private Integer _perPage; private String _order; public String getQuery() { return _query; } public void setQuery(String query) { _query = query; } public Boolean getIncludeRemoved() { return _includeRemoved; } public void setIncludeRemoved(Boolean includeRemoved) { this._includeRemoved = includeRemoved; } public String getAddedSince() { return _addedSince; } public void setAddedSince(String addedSince) { _addedSince = addedSince; } public String getModifiedSince() { return _modifiedSince; } public void setModifiedSince(String modifiedSince) { _modifiedSince = modifiedSince; } public String getRemovedSince() { return _removedSince; } public void setRemovedSince(String removedSince) { _removedSince = removedSince; } public Integer getPage() { return _page; } public void setPage(Integer page) { _page = page; } public Integer getPerPage() { return _perPage; } public void setPerPage(Integer perPage) { _perPage = perPage; } public String getOrder() { return _order; } public void setOrder(String orderBy) { _order = orderBy; } /** * Return a map of parameters to be used in the API calls * @return a Map of parameters */ public Map<String, String> paramMap() { Map<String, String> params = new HashMap<>(); if (getQuery() != null) params.put("q", getQuery()); if (getIncludeRemoved() != null) params.put("include_removed", getIncludeRemoved() ? "true" : "false"); if (getAddedSince() != null) params.put("added_since", getAddedSince()); if (getModifiedSince() != null) params.put("modified_since", getModifiedSince()); if (getRemovedSince() != null) params.put("removed_since", getRemovedSince()); if (getPage() != null) params.put("page", getPage().toString()); if (getPerPage() != null) params.put("per_page", getPerPage().toString()); if (getOrder() != null) params.put("order", getOrder()); return params; } }
package com.j256.ormlite.stmt; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import com.j256.ormlite.dao.BaseDaoImpl; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.dao.ObjectCache; import com.j256.ormlite.dao.RawRowMapper; import com.j256.ormlite.dao.RawRowObjectMapper; import com.j256.ormlite.db.DatabaseType; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.field.SqlType; import com.j256.ormlite.logger.Logger; import com.j256.ormlite.logger.LoggerFactory; import com.j256.ormlite.misc.IOUtils; import com.j256.ormlite.misc.SqlExceptionUtil; import com.j256.ormlite.misc.TransactionManager; import com.j256.ormlite.stmt.StatementBuilder.StatementType; import com.j256.ormlite.stmt.mapped.MappedCreate; import com.j256.ormlite.stmt.mapped.MappedDelete; import com.j256.ormlite.stmt.mapped.MappedDeleteCollection; import com.j256.ormlite.stmt.mapped.MappedQueryForId; import com.j256.ormlite.stmt.mapped.MappedRefresh; import com.j256.ormlite.stmt.mapped.MappedUpdate; import com.j256.ormlite.stmt.mapped.MappedUpdateId; import com.j256.ormlite.support.CompiledStatement; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.support.DatabaseConnection; import com.j256.ormlite.support.DatabaseResults; import com.j256.ormlite.table.TableInfo; /** * Executes SQL statements for a particular table in a particular database. Basically a call through to various mapped * statement methods. * * @param <T> * The class that the code will be operating on. * @param <ID> * The class of the ID column associated with the class. The T class does not require an ID field. The class * needs an ID parameter however so you can use Void or Object to satisfy the compiler. * @author graywatson */ public class StatementExecutor<T, ID> implements GenericRowMapper<String[]> { private static Logger logger = LoggerFactory.getLogger(StatementExecutor.class); private static final FieldType[] noFieldTypes = new FieldType[0]; private final DatabaseType databaseType; private final TableInfo<T, ID> tableInfo; private final Dao<T, ID> dao; private MappedQueryForId<T, ID> mappedQueryForId; private PreparedQuery<T> preparedQueryForAll; private MappedCreate<T, ID> mappedInsert; private MappedUpdate<T, ID> mappedUpdate; private MappedUpdateId<T, ID> mappedUpdateId; private MappedDelete<T, ID> mappedDelete; private MappedRefresh<T, ID> mappedRefresh; private String countStarQuery; private String ifExistsQuery; private FieldType[] ifExistsFieldTypes; private RawRowMapper<T> rawRowMapper; /** * Provides statements for various SQL operations. */ public StatementExecutor(DatabaseType databaseType, TableInfo<T, ID> tableInfo, Dao<T, ID> dao) { this.databaseType = databaseType; this.tableInfo = tableInfo; this.dao = dao; } /** * Return the object associated with the id or null if none. This does a SQL * {@code SELECT col1,col2,... FROM ... WHERE ... = id} type query. */ public T queryForId(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException { if (mappedQueryForId == null) { mappedQueryForId = MappedQueryForId.build(databaseType, tableInfo, null); } return mappedQueryForId.execute(databaseConnection, id, objectCache); } /** * Return the first object that matches the {@link PreparedStmt} or null if none. */ public T queryForFirst(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt, ObjectCache objectCache) throws SQLException { CompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT); DatabaseResults results = null; try { results = compiledStatement.runQuery(objectCache); if (results.first()) { logger.debug("query-for-first of '{}' returned at least 1 result", preparedStmt.getStatement()); return preparedStmt.mapRow(results); } else { logger.debug("query-for-first of '{}' returned at 0 results", preparedStmt.getStatement()); return null; } } finally { IOUtils.closeThrowSqlException(results, "results"); IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } } /** * Return a list of all of the data in the table. Should be used carefully if the table is large. Consider using the * {@link Dao#iterator} if this is the case. */ public List<T> queryForAll(ConnectionSource connectionSource, ObjectCache objectCache) throws SQLException { prepareQueryForAll(); return query(connectionSource, preparedQueryForAll, objectCache); } /** * Return a long value which is the number of rows in the table. */ public long queryForCountStar(DatabaseConnection databaseConnection) throws SQLException { if (countStarQuery == null) { StringBuilder sb = new StringBuilder(64); sb.append("SELECT COUNT(*) FROM "); databaseType.appendEscapedEntityName(sb, tableInfo.getTableName()); countStarQuery = sb.toString(); } long count = databaseConnection.queryForLong(countStarQuery); logger.debug("query of '{}' returned {}", countStarQuery, count); return count; } /** * Return a long value from a prepared query. */ public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException { CompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG); DatabaseResults results = null; try { results = compiledStatement.runQuery(null); if (results.first()) { return results.getLong(0); } else { throw new SQLException("No result found in queryForLong: " + preparedStmt.getStatement()); } } finally { IOUtils.closeThrowSqlException(results, "results"); IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } } /** * Return a long from a raw query with String[] arguments. */ public long queryForLong(DatabaseConnection databaseConnection, String query, String[] arguments) throws SQLException { logger.debug("executing raw query for long: {}", query); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("query arguments: {}", (Object) arguments); } CompiledStatement compiledStatement = null; DatabaseResults results = null; try { compiledStatement = databaseConnection.compileStatement(query, StatementType.SELECT, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS); assignStatementArguments(compiledStatement, arguments); results = compiledStatement.runQuery(null); if (results.first()) { return results.getLong(0); } else { throw new SQLException("No result found in queryForLong: " + query); } } finally { IOUtils.closeThrowSqlException(results, "results"); IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } } /** * Return a list of all of the data in the table that matches the {@link PreparedStmt}. Should be used carefully if * the table is large. Consider using the {@link Dao#iterator} if this is the case. */ public List<T> query(ConnectionSource connectionSource, PreparedStmt<T> preparedStmt, ObjectCache objectCache) throws SQLException { SelectIterator<T, ID> iterator = buildIterator(/* no dao specified because no removes */null, connectionSource, preparedStmt, objectCache, DatabaseConnection.DEFAULT_RESULT_FLAGS); try { List<T> results = new ArrayList<T>(); while (iterator.hasNextThrow()) { results.add(iterator.nextThrow()); } logger.debug("query of '{}' returned {} results", preparedStmt.getStatement(), results.size()); return results; } finally { IOUtils.closeThrowSqlException(iterator, "iterator"); } } /** * Create and return a SelectIterator for the class using the default mapped query for all statement. */ public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource, int resultFlags, ObjectCache objectCache) throws SQLException { prepareQueryForAll(); return buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags); } /** * Return a row mapper suitable for mapping 'select *' queries. */ public GenericRowMapper<T> getSelectStarRowMapper() throws SQLException { prepareQueryForAll(); return preparedQueryForAll; } /** * Return a raw row mapper suitable for use with {@link Dao#queryRaw(String, RawRowMapper, String...)}. */ public RawRowMapper<T> getRawRowMapper() { if (rawRowMapper == null) { rawRowMapper = new RawRowMapperImpl<T, ID>(tableInfo); } return rawRowMapper; } /** * Create and return an {@link SelectIterator} for the class using a prepared statement. */ public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource, PreparedStmt<T> preparedStmt, ObjectCache objectCache, int resultFlags) throws SQLException { DatabaseConnection connection = connectionSource.getReadOnlyConnection(); CompiledStatement compiledStatement = null; try { compiledStatement = preparedStmt.compile(connection, StatementType.SELECT, resultFlags); SelectIterator<T, ID> iterator = new SelectIterator<T, ID>(tableInfo.getDataClass(), classDao, preparedStmt, connectionSource, connection, compiledStatement, preparedStmt.getStatement(), objectCache); connection = null; compiledStatement = null; return iterator; } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); if (connection != null) { connectionSource.releaseConnection(connection); } } } /** * Return a results object associated with an internal iterator that returns String[] results. */ public GenericRawResults<String[]> queryRaw(ConnectionSource connectionSource, String query, String[] arguments, ObjectCache objectCache) throws SQLException { logger.debug("executing raw query for: {}", query); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("query arguments: {}", (Object) arguments); } DatabaseConnection connection = connectionSource.getReadOnlyConnection(); CompiledStatement compiledStatement = null; try { compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS); assignStatementArguments(compiledStatement, arguments); GenericRawResults<String[]> rawResults = new RawResultsImpl<String[]>(connectionSource, connection, query, String[].class, compiledStatement, this, objectCache); compiledStatement = null; connection = null; return rawResults; } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); if (connection != null) { connectionSource.releaseConnection(connection); } } } /** * Return a results object associated with an internal iterator is mapped by the user's rowMapper. */ public <UO> GenericRawResults<UO> queryRaw(ConnectionSource connectionSource, String query, RawRowMapper<UO> rowMapper, String[] arguments, ObjectCache objectCache) throws SQLException { logger.debug("executing raw query for: {}", query); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("query arguments: {}", (Object) arguments); } DatabaseConnection connection = connectionSource.getReadOnlyConnection(); CompiledStatement compiledStatement = null; try { compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS); assignStatementArguments(compiledStatement, arguments); RawResultsImpl<UO> rawResults = new RawResultsImpl<UO>(connectionSource, connection, query, String[].class, compiledStatement, new UserRawRowMapper<UO>(rowMapper, this), objectCache); compiledStatement = null; connection = null; return rawResults; } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); if (connection != null) { connectionSource.releaseConnection(connection); } } } /** * Return a results object associated with an internal iterator is mapped by the user's rowMapper. */ public <UO> GenericRawResults<UO> queryRaw(ConnectionSource connectionSource, String query, DataType[] columnTypes, RawRowObjectMapper<UO> rowMapper, String[] arguments, ObjectCache objectCache) throws SQLException { logger.debug("executing raw query for: {}", query); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("query arguments: {}", (Object) arguments); } DatabaseConnection connection = connectionSource.getReadOnlyConnection(); CompiledStatement compiledStatement = null; try { compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS); assignStatementArguments(compiledStatement, arguments); RawResultsImpl<UO> rawResults = new RawResultsImpl<UO>(connectionSource, connection, query, String[].class, compiledStatement, new UserRawRowObjectMapper<UO>(rowMapper, columnTypes), objectCache); compiledStatement = null; connection = null; return rawResults; } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); if (connection != null) { connectionSource.releaseConnection(connection); } } } /** * Return a results object associated with an internal iterator that returns Object[] results. */ public GenericRawResults<Object[]> queryRaw(ConnectionSource connectionSource, String query, DataType[] columnTypes, String[] arguments, ObjectCache objectCache) throws SQLException { logger.debug("executing raw query for: {}", query); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("query arguments: {}", (Object) arguments); } DatabaseConnection connection = connectionSource.getReadOnlyConnection(); CompiledStatement compiledStatement = null; try { compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS); assignStatementArguments(compiledStatement, arguments); RawResultsImpl<Object[]> rawResults = new RawResultsImpl<Object[]>(connectionSource, connection, query, Object[].class, compiledStatement, new ObjectArrayRowMapper(columnTypes), objectCache); compiledStatement = null; connection = null; return rawResults; } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); if (connection != null) { connectionSource.releaseConnection(connection); } } } /** * Return the number of rows affected. */ public int updateRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException { logger.debug("running raw update statement: {}", statement); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("update arguments: {}", (Object) arguments); } CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.UPDATE, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS); try { assignStatementArguments(compiledStatement, arguments); return compiledStatement.runUpdate(); } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } } /** * Return true if it worked else false. */ public int executeRawNoArgs(DatabaseConnection connection, String statement) throws SQLException { logger.debug("running raw execute statement: {}", statement); return connection.executeStatement(statement, DatabaseConnection.DEFAULT_RESULT_FLAGS); } /** * Return true if it worked else false. */ public int executeRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException { logger.debug("running raw execute statement: {}", statement); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("execute arguments: {}", (Object) arguments); } CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.EXECUTE, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS); try { assignStatementArguments(compiledStatement, arguments); return compiledStatement.runExecute(); } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } } /** * Create a new entry in the database from an object. */ public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { if (mappedInsert == null) { mappedInsert = MappedCreate.build(databaseType, tableInfo); } return mappedInsert.insert(databaseType, databaseConnection, data, objectCache); } /** * Update an object in the database. */ public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { if (mappedUpdate == null) { mappedUpdate = MappedUpdate.build(databaseType, tableInfo); } return mappedUpdate.update(databaseConnection, data, objectCache); } /** * Update an object in the database to change its id to the newId parameter. */ public int updateId(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache) throws SQLException { if (mappedUpdateId == null) { mappedUpdateId = MappedUpdateId.build(databaseType, tableInfo); } return mappedUpdateId.execute(databaseConnection, data, newId, objectCache); } /** * Update rows in the database. */ public int update(DatabaseConnection databaseConnection, PreparedUpdate<T> preparedUpdate) throws SQLException { CompiledStatement compiledStatement = preparedUpdate.compile(databaseConnection, StatementType.UPDATE); try { return compiledStatement.runUpdate(); } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } } /** * Does a query for the object's Id and copies in each of the field values from the database to refresh the data * parameter. */ public int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { if (mappedRefresh == null) { mappedRefresh = MappedRefresh.build(databaseType, tableInfo); } return mappedRefresh.executeRefresh(databaseConnection, data, objectCache); } /** * Delete an object from the database. */ public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { if (mappedDelete == null) { mappedDelete = MappedDelete.build(databaseType, tableInfo); } return mappedDelete.delete(databaseConnection, data, objectCache); } /** * Delete an object from the database by id. */ public int deleteById(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException { if (mappedDelete == null) { mappedDelete = MappedDelete.build(databaseType, tableInfo); } return mappedDelete.deleteById(databaseConnection, id, objectCache); } /** * Delete a collection of objects from the database. */ public int deleteObjects(DatabaseConnection databaseConnection, Collection<T> datas, ObjectCache objectCache) throws SQLException { // have to build this on the fly because the collection has variable number of args return MappedDeleteCollection.deleteObjects(databaseType, tableInfo, databaseConnection, datas, objectCache); } /** * Delete a collection of objects from the database. */ public int deleteIds(DatabaseConnection databaseConnection, Collection<ID> ids, ObjectCache objectCache) throws SQLException { // have to build this on the fly because the collection has variable number of args return MappedDeleteCollection.deleteIds(databaseType, tableInfo, databaseConnection, ids, objectCache); } /** * Delete rows that match the prepared statement. */ public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException { CompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE); try { return compiledStatement.runUpdate(); } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } } /** * Call batch tasks inside of a connection which may, or may not, have been "saved". */ public <CT> CT callBatchTasks(DatabaseConnection connection, boolean saved, Callable<CT> callable) throws SQLException { if (databaseType.isBatchUseTransaction()) { return TransactionManager.callInTransaction(connection, saved, databaseType, callable); } boolean autoCommitAtStart = false; try { if (connection.isAutoCommitSupported()) { autoCommitAtStart = connection.isAutoCommit(); if (autoCommitAtStart) { // disable auto-commit mode if supported and enabled at start connection.setAutoCommit(false); logger.debug("disabled auto-commit on table {} before batch tasks", tableInfo.getTableName()); } } try { return callable.call(); } catch (SQLException e) { throw e; } catch (Exception e) { throw SqlExceptionUtil.create("Batch tasks callable threw non-SQL exception", e); } } finally { if (autoCommitAtStart) { /** * Try to restore if we are in auto-commit mode. * * NOTE: we do _not_ have to do a commit here. According to {@link Connection#setAutoCommit(boolean)}, * this will start a transaction when auto-commit is turned off and it will be committed here. */ connection.setAutoCommit(true); logger.debug("re-enabled auto-commit on table {} after batch tasks", tableInfo.getTableName()); } } } public String[] mapRow(DatabaseResults results) throws SQLException { int columnN = results.getColumnCount(); String[] result = new String[columnN]; for (int colC = 0; colC < columnN; colC++) { result[colC] = results.getString(colC); } return result; } public boolean ifExists(DatabaseConnection connection, ID id) throws SQLException { if (ifExistsQuery == null) { QueryBuilder<T, ID> qb = new QueryBuilder<T, ID>(databaseType, tableInfo, dao); qb.selectRaw("COUNT(*)"); /* * NOTE: bit of a hack here because the select arg is never used but it _can't_ be a constant because we set * field-name and field-type on it. */ qb.where().eq(tableInfo.getIdField().getColumnName(), new SelectArg()); ifExistsQuery = qb.prepareStatementString(); ifExistsFieldTypes = new FieldType[] { tableInfo.getIdField() }; } long count = connection.queryForLong(ifExistsQuery, new Object[] { id }, ifExistsFieldTypes); logger.debug("query of '{}' returned {}", ifExistsQuery, count); return (count != 0); } private void assignStatementArguments(CompiledStatement compiledStatement, String[] arguments) throws SQLException { for (int i = 0; i < arguments.length; i++) { compiledStatement.setObject(i, arguments[i], SqlType.STRING); } } private void prepareQueryForAll() throws SQLException { if (preparedQueryForAll == null) { preparedQueryForAll = new QueryBuilder<T, ID>(databaseType, tableInfo, dao).prepare(); } } /** * Map raw results to return a user object from a String array. */ private static class UserRawRowMapper<UO> implements GenericRowMapper<UO> { private final RawRowMapper<UO> mapper; private final GenericRowMapper<String[]> stringRowMapper; private String[] columnNames; public UserRawRowMapper(RawRowMapper<UO> mapper, GenericRowMapper<String[]> stringMapper) { this.mapper = mapper; this.stringRowMapper = stringMapper; } public UO mapRow(DatabaseResults results) throws SQLException { String[] stringResults = stringRowMapper.mapRow(results); return mapper.mapRow(getColumnNames(results), stringResults); } private String[] getColumnNames(DatabaseResults results) throws SQLException { if (columnNames != null) { return columnNames; } columnNames = results.getColumnNames(); return columnNames; } } /** * Map raw results to return a user object from an Object array. */ private static class UserRawRowObjectMapper<UO> implements GenericRowMapper<UO> { private final RawRowObjectMapper<UO> mapper; private final DataType[] columnTypes; private String[] columnNames; public UserRawRowObjectMapper(RawRowObjectMapper<UO> mapper, DataType[] columnTypes) { this.mapper = mapper; this.columnTypes = columnTypes; } public UO mapRow(DatabaseResults results) throws SQLException { int columnN = results.getColumnCount(); Object[] objectResults = new Object[columnN]; for (int colC = 0; colC < columnN; colC++) { if (colC >= columnTypes.length) { objectResults[colC] = null; } else { objectResults[colC] = columnTypes[colC].getDataPersister().resultToJava(null, results, colC); } } return mapper.mapRow(getColumnNames(results), columnTypes, objectResults); } private String[] getColumnNames(DatabaseResults results) throws SQLException { if (columnNames != null) { return columnNames; } columnNames = results.getColumnNames(); return columnNames; } } /** * Map raw results to return Object[]. */ private static class ObjectArrayRowMapper implements GenericRowMapper<Object[]> { private final DataType[] columnTypes; public ObjectArrayRowMapper(DataType[] columnTypes) { this.columnTypes = columnTypes; } public Object[] mapRow(DatabaseResults results) throws SQLException { int columnN = results.getColumnCount(); Object[] result = new Object[columnN]; for (int colC = 0; colC < columnN; colC++) { DataType dataType; if (colC >= columnTypes.length) { dataType = DataType.STRING; } else { dataType = columnTypes[colC]; } result[colC] = dataType.getDataPersister().resultToJava(null, results, colC); } return result; } } }
package com.redoutevant.gitproject; public class ValidarLogin { private String username; /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } public static void main(String[] args) { } }
package com.remondis.remap; import static com.remondis.remap.Lang.denyNull; import static com.remondis.remap.MappingException.alreadyMappedProperty; import static com.remondis.remap.MappingException.multipleInteractions; import static com.remondis.remap.MappingException.notAProperty; import static com.remondis.remap.MappingException.zeroInteractions; import static com.remondis.remap.Properties.createUnmappedMessage; import static com.remondis.remap.ReflectionUtil.newInstance; import static java.util.Objects.nonNull; import java.beans.PropertyDescriptor; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * The {@link MappingConfiguration} object is used to specify the mapping of the fields from a source object/type * to a destination object/type. Only properties can be mapped. Properties are defined with the Java * Bean Convention: * <ul> * <li>A property is a field with any visibility</li> * <li>A property has a * public getter/setter pair exactly named as the field</li> * <li>Boolean values have is/setter * methods.</li> * <li>A bean has a default zero-args constructor.</li> * </ul> * For the mapping, * keywords like <code>transient</code> do not have any effect. * * <p> * The mapper always tries to map all properties with name from the source to the destination * object. To retrieve a valid mapper, all properties must be either mapped/reassigned or omitted. * If there are unmapped properties in source/destination type, the {@link MappingConfiguration#mapper()} throws * an error. If the mapping contains nested mappings of other complex types, a delegation mapper * must be registered using {@link #useMapper(Mapper)}, otherweise a {@link MappingException} is * thrown. * </p> * * @param <S> source type of the mapping * @param <D> destination type of the mapping * @author schuettec */ public class MappingConfiguration<S, D> { static final String OMIT_FIELD_DEST = "omit in destination"; static final String OMIT_FIELD_SOURCE = "omit in source"; private Class<S> source; private Class<D> destination; /** * Holds the list of mappers registered for hierarchical mapping. */ private Map<Projection<?, ?>, InternalMapper<?, ?>> mappers; /** * Holds the list of mapping operations. */ private Set<Transformation> mappings; /** * This set keeps track of the mapped source properties. */ private Set<PropertyDescriptor> mappedSourceProperties; /** * This set keeps track of the mapped destination properties. */ private Set<PropertyDescriptor> mappedDestinationProperties; /** * This flag indicates that all other source properties that are not part of the mapping should be omitted. Attention: * Do not omit implicit mappings. */ private boolean omitOtherSourceProperties; /** * This flag indicates that all other destination properties that are not part of the mapping should be omitted. * Attention: * Do not omit implicit mappings. */ private boolean omitOtherDestinationProperties; /** * This flag indicates that the creation of implicit mappings should be disabled. */ private boolean noImplicitMappings; MappingConfiguration(Class<S> source, Class<D> destination) { this.source = source; this.destination = destination; this.mappings = new HashSet<>(); this.mappedSourceProperties = new HashSet<>(); this.mappedDestinationProperties = new HashSet<>(); this.mappers = new Hashtable<>(); } /** * Marks a destination field as omitted. The mapping will not touch this field in the destination * object. * * @param destinationSelector The {@link FieldSelector} lambda that selects the field with invoking * the corresponding getter method. * @return Returns this object for method chaining. */ public MappingConfiguration<S, D> omitInDestination(FieldSelector<D> destinationSelector) { denyNull("destinationSelector", destinationSelector); PropertyDescriptor propertyDescriptor = getPropertyFromFieldSelector(Target.DESTINATION, OMIT_FIELD_DEST, destination, destinationSelector); OmitTransformation omitDestination = OmitTransformation.omitDestination(this, propertyDescriptor); omitMapping(mappedDestinationProperties, propertyDescriptor, omitDestination); return this; } private void omitMapping(Set<PropertyDescriptor> mappedDestinationProperties, PropertyDescriptor propertyDescriptor, OmitTransformation omitDestination) { // check if the property descriptor is already mapped denyAlreadyMappedProperty(mappedDestinationProperties, propertyDescriptor); // mark the property as mapped in destination mappedDestinationProperties.add(propertyDescriptor); // create omit transformation object mappings.add(omitDestination); } /** * Omits all unmapped source and destination fields. This method adds the necessary * {@link #omitInDestination(FieldSelector)} and {@link #omitInSource(FieldSelector)} declarations to the mapping as * if they were called specifically. * <p> * <b>Note: The use of {@link #omitOthers()} carries the risk of erroneously excluding fields from mapping. For * example: * If a field is added on the source type, a mapping configuration that does not use {@link #omitOthers()} will * complain * about a new unmapped field. This normally gives the developer a hint, to either specify a mapping or omit this * field intentionally. If this method is used, any unmapped field will be omitted without notification! * </b> * </p> * * @return Returns this object for method chaining. */ public MappingConfiguration<S, D> omitOthers() { omitOtherSourceProperties(); omitOtherDestinationProperties(); return this; } /** * Omits all unmapped destination fields. This method adds the necessary * {@link #omitInDestination(FieldSelector)} declarations to the mapping as * if they were called specifically. * <p> * <b>Note: The use of {@link #omitOtherDestinationProperties()} carries the risk of erroneously excluding fields from * mapping. For * example: * If a field is added on the destination type, a mapping configuration that does not use * {@link #omitOtherDestinationProperties()} will * complain * about a new unmapped field. This normally gives the developer a hint, to either specify a mapping or omit this * field intentionally. If this method is used, any unmapped field will be omitted without notification! * </b> * </p> * * @return Returns this object for method chaining. */ public MappingConfiguration<S, D> omitOtherDestinationProperties() { this.omitOtherDestinationProperties = true; return this; } /** * Omits all unmapped source fields. This method adds the necessary * {@link #omitInSource(FieldSelector)} declarations to the mapping as * if they were called specifically. * <p> * <b>Note: The use of {@link #omitOtherSourceProperties()} carries the risk of erroneously excluding fields from * mapping. For * example: * If a field is added on the source type, a mapping configuration that does not use * {@link #omitOtherSourceProperties()} will * complain * about a new unmapped field. This normally gives the developer a hint, to either specify a mapping or omit this * field intentionally. If this method is used, any unmapped field will be omitted without notification! * </b> * </p> * * @return Returns this object for method chaining. */ public MappingConfiguration<S, D> omitOtherSourceProperties() { this.omitOtherSourceProperties = true; return this; } /** * Marks a source field as omitted. The mapping will not touch this field in the source object. * * @param sourceSelector The {@link FieldSelector} lambda that selects the field with invoking the * corresponding getter method. * @return Returns this object for method chaining. */ public MappingConfiguration<S, D> omitInSource(FieldSelector<S> sourceSelector) { denyNull("sourceSelector", sourceSelector); // Omit in destination PropertyDescriptor propertyDescriptor = getPropertyFromFieldSelector(Target.SOURCE, OMIT_FIELD_SOURCE, this.source, sourceSelector); OmitTransformation omitSource = OmitTransformation.omitSource(this, propertyDescriptor); omitMapping(mappedSourceProperties, propertyDescriptor, omitSource); return this; } /** * Reassigns a property from the source to the specified property of the destination object. * * @param sourceSelector The {@link FieldSelector}s selecting the source property with get-method * invocation. * @return Returns a {@link ReassignBuilder} to specify the destination field. */ public <RS> ReassignBuilder<S, D> reassign(FieldSelector<S> sourceSelector) { denyNull("sourceSelector", sourceSelector); PropertyDescriptor typedSourceProperty = getPropertyFromFieldSelector(Target.SOURCE, ReassignBuilder.ASSIGN, this.source, sourceSelector); ReassignBuilder<S, D> reassignBuilder = new ReassignBuilder<>(typedSourceProperty, destination, this); return reassignBuilder; } /** * Maps a property from the source to the specified property of the destination object with * transforming the source value using the specified transform lambda. <b>Note: The mapping * library is designed to reduce the required client tests. Using this method requires the client * to test the transformation function!</b> * * @param sourceSelector The {@link FieldSelector}s selecting the source property with get-method * invocation. * @param destinationSelector The {@link FieldSelector}s selecting the destination property with * get-method invocation. * @return Returns {@link ReplaceBuilder} to specify the transform function and null-strategy. */ public <RD, RS> ReplaceBuilder<S, D, RD, RS> replace(TypedSelector<RS, S> sourceSelector, TypedSelector<RD, D> destinationSelector) { denyNull("sourceSelector", sourceSelector); denyNull("destinationSelector", destinationSelector); TypedPropertyDescriptor<RS> sourceProperty = getTypedPropertyFromFieldSelector(Target.SOURCE, ReplaceBuilder.TRANSFORM, this.source, sourceSelector); TypedPropertyDescriptor<RD> destProperty = getTypedPropertyFromFieldSelector(Target.DESTINATION, ReplaceBuilder.TRANSFORM, this.destination, destinationSelector); ReplaceBuilder<S, D, RD, RS> builder = new ReplaceBuilder<>(sourceProperty, destProperty, this); return builder; } /** * Defines a custom source of a value that should be mapped to the specified property of the destination object. * The custom source value is provided by a supplier lambda function. <b>Note: The mapping * library is designed to reduce the required client tests. Using this method requires the client * to test the supplier lambda function!</b> * * @param destinationSelector The {@link FieldSelector}s selecting the destination property with * get-method invocation. * @return Returns {@link ReplaceBuilder} to specify the transform function and null-strategy. */ public <RD> SetBuilder<S, D, RD> set(TypedSelector<RD, D> destinationSelector) { denyNull("destinationSelector", destinationSelector); TypedPropertyDescriptor<RD> destProperty = getTypedPropertyFromFieldSelector(Target.DESTINATION, ReplaceBuilder.TRANSFORM, this.destination, destinationSelector); SetBuilder<S, D, RD> builder = new SetBuilder<>(destProperty, this); return builder; } /** * Defines a restructuring operation to build an complex object to be assigned to the specified destination field by * mapping from fields of the source type. * * @param <RD> The destination type. * @param destinationSelector The {@link FieldSelector}s selecting the destination property with * get-method invocation. * @return Returns a {@link RestructureBuilder} for further configuration. */ public <RD> RestructureBuilder<S, D, RD> restructure(TypedSelector<RD, D> destinationSelector) { denyNull("destinationSelector", destinationSelector); TypedPropertyDescriptor<RD> destProperty = getTypedPropertyFromFieldSelector(Target.DESTINATION, ReplaceBuilder.TRANSFORM, this.destination, destinationSelector); return new RestructureBuilder<S, D, RD>(this, destProperty); } /** * Maps a property holding a collection from the source to the specified property holding a collection of the * destination object. The specified transform function will be applied on every item in the source value to convert * to the specified destination type. <b>Note: The mapping * library is designed to reduce the required client tests. Using this method requires the client * to test the transformation function!</b> * * @param sourceSelector The {@link FieldSelector}s selecting the source property holding a {@link Collection}. * @param destinationSelector The {@link FieldSelector}s selecting the destination property holding a * {@link Collection}. * @return Returns {@link ReplaceBuilder} to specify the transform function and null-strategy. */ public <RD, RS> ReplaceCollectionBuilder<S, D, RD, RS> replaceCollection( TypedSelector<Collection<RS>, S> sourceSelector, TypedSelector<Collection<RD>, D> destinationSelector) { denyNull("sourceSelector", sourceSelector); denyNull("destinationSelector", destinationSelector); TypedPropertyDescriptor<Collection<RS>> sourceProperty = getTypedPropertyFromFieldSelector(Target.SOURCE, ReplaceBuilder.TRANSFORM, this.source, sourceSelector); TypedPropertyDescriptor<Collection<RD>> destProperty = getTypedPropertyFromFieldSelector(Target.DESTINATION, ReplaceBuilder.TRANSFORM, this.destination, destinationSelector); ReplaceCollectionBuilder<S, D, RD, RS> builder = new ReplaceCollectionBuilder<>(sourceProperty, destProperty, this); return builder; } protected void addMapping(PropertyDescriptor sourceProperty, PropertyDescriptor destProperty, Transformation transformation) { // check if the property descriptor is already mapped denyAlreadyOmittedProperty(sourceProperty); denyAlreadyMappedProperty(mappedDestinationProperties, destProperty); // mark the property as mapped in destination mappedSourceProperties.add(sourceProperty); mappedDestinationProperties.add(destProperty); // create omit transformation object mappings.add(transformation); } protected void addDestinationMapping(PropertyDescriptor destProperty, Transformation setTransformation) { denyAlreadyMappedProperty(mappedDestinationProperties, destProperty); // mark the property as mapped in destination mappedDestinationProperties.add(destProperty); // create omit transformation object mappings.add(setTransformation); } private void denyAlreadyOmittedProperty(PropertyDescriptor sourceProperty) { if (mappedSourceProperties.contains(sourceProperty)) { // Search for omit-Operations mappings.stream() .forEach(t -> { PropertyDescriptor omitSourceProperty = t.getSourceProperty(); // If omitSourceProperty is null, then the mapping is an OmitInDestination-Operation. if (t instanceof OmitTransformation && nonNull(omitSourceProperty) && omitSourceProperty.equals(sourceProperty)) { throw alreadyMappedProperty(sourceProperty); } }); } } /** * Returns the mapper configured with this builder. * * @return The mapper instance. */ public Mapper<S, D> mapper() { if (!noImplicitMappings) { addStrictMapping(); } if (omitOtherSourceProperties) { addOmitForSource(); } if (omitOtherDestinationProperties) { addOmitForDestination(); } validateMapping(); return new Mapper<>(this); } private void addOmitForDestination() { Set<PropertyDescriptor> unmappedDestinationProperties = getUnmappedDestinationProperties(); for (PropertyDescriptor propertyDescriptor : unmappedDestinationProperties) { OmitTransformation omitDestination = OmitTransformation.omitDestination(this, propertyDescriptor); omitMapping(mappedDestinationProperties, propertyDescriptor, omitDestination); } } private void addOmitForSource() { // Get the set of property names Set<String> unmappedSourcePropertyNames = getUnmappedSourceProperties().stream() .map(PropertyDescriptor::getName) .collect(Collectors.toSet()); // Add a reassign for all properties of source that are unmapped properties in the destination getUnmappedSourceProperties().stream() .filter(pd -> unmappedSourcePropertyNames.contains(pd.getName())) .forEach(pd -> { OmitTransformation omitSource = OmitTransformation.omitSource(this, pd); omitMapping(mappedSourceProperties, pd, omitSource); }); } /** * This method adds a strict mapping for all unmapped properties of source that have a * corresponding property in the destination type. */ private void addStrictMapping() { // Get all unmapped properties from destination because this will be the only properties that can be mapped from // source. Set<PropertyDescriptor> unmappedDestinationProperties = getUnmappedDestinationProperties(); // Get the set of property names Set<String> unmappedDestinationPropertyNames = unmappedDestinationProperties.stream() .map(PropertyDescriptor::getName) .collect(Collectors.toSet()); // Add a reassign for all properties of source that are unmapped properties in the destination getUnmappedSourceProperties().stream() .filter(pd -> unmappedDestinationPropertyNames.contains(pd.getName())) .forEach(pd -> { // find the corresponding PropertyDescriptor in the unmapped // destination properties and add reassign // transformation PropertyDescriptor destinationProperty = getPropertyDescriptorByPropertyName(unmappedDestinationProperties, pd.getName()); MapTransformation transformation = new MapTransformation(this, pd, destinationProperty); addMapping(pd, destinationProperty, transformation); }); } private PropertyDescriptor getPropertyDescriptorByPropertyName(Set<PropertyDescriptor> descriptors, String propertyName) { Set<PropertyDescriptor> matchedPropertiesByName = descriptors.stream() .filter(pd -> pd.getName() .equals(propertyName)) .collect(Collectors.toSet()); if (matchedPropertiesByName.isEmpty() || matchedPropertiesByName.size() > 1) { throw new MappingException( String.format("Cannot assign source property '%s' to destination, but this was determined " + "to be possible - this is an implementation fault.", propertyName)); } else { return matchedPropertiesByName.iterator() .next(); } } private void validateMapping() { // check for unmapped properties Set<PropertyDescriptor> unmapped = getUnmappedProperties(); if (!unmapped.isEmpty()) { throw MappingException.unmappedProperties(unmapped); } // check if all mappers are available to perform nested mapping for (Transformation t : mappings) { t.validateTransformation(); } } private Set<PropertyDescriptor> getUnmappedProperties() { Set<PropertyDescriptor> unmapped = new HashSet<>(); // Check that there are no unmapped source fields unmapped.addAll(getUnmappedSourceProperties()); // Check that there are no unmapped destination fields unmapped.addAll(getUnmappedDestinationProperties()); return unmapped; } private Set<PropertyDescriptor> getUnmappedDestinationProperties() { return getUnmappedProperties(destination, mappedDestinationProperties, Target.DESTINATION); } private Set<PropertyDescriptor> getUnmappedSourceProperties() { return getUnmappedProperties(source, mappedSourceProperties, Target.SOURCE); } /** * Returns all properties from the specified type, that were unmapped in the specified {@link Set} * of {@link PropertyDescriptor}s. * * @param type The type to check for unmapped properties. * @param mappedSourceProperties The set of mapped properties. * @param target The type of mapping target. * @return Returns the {@link Set} of unmapped properties. */ private <T> Set<PropertyDescriptor> getUnmappedProperties(Class<T> type, Set<PropertyDescriptor> mappedSourceProperties, Target targetType) { Set<PropertyDescriptor> allSourceProperties = Properties.getProperties(type, targetType); allSourceProperties.removeAll(mappedSourceProperties); return allSourceProperties; } /** * Executes a {@link FieldSelector} lambda on a proxy object of the specified type and returns the * {@link PropertyDescriptor} of the property selected. * * @param target Defines if the properties are validated against source or target rules. * @param configurationMethod The configuration method this {@link PropertyDescriptor} is used for. Only needed for * exception messages. * @param sensorType The type of sensor object. * @param selector The selector lambda. * @return Returns the {@link PropertyDescriptor} selected by the lambda. * @throws MappingException if a property was specified for mapping but not invoked. */ static <R, T> TypedPropertyDescriptor<R> getTypedPropertyFromFieldSelector(Target target, String configurationMethod, Class<T> sensorType, TypedSelector<R, T> selector) { InvocationSensor<T> invocationSensor = new InvocationSensor<T>(sensorType); T sensor = invocationSensor.getSensor(); // perform the selector lambda on the sensor R returnValue = selector.selectField(sensor); // if any property interaction was tracked... if (invocationSensor.hasTrackedProperties()) { // ...make sure it was exactly one property interaction List<String> trackedPropertyNames = invocationSensor.getTrackedPropertyNames(); denyMultipleInteractions(configurationMethod, trackedPropertyNames); // get the property name String propertyName = trackedPropertyNames.get(0); // find the property descriptor or fail with an exception PropertyDescriptor property = getPropertyDescriptorOrFail(target, sensorType, propertyName); TypedPropertyDescriptor<R> tpd = new TypedPropertyDescriptor<R>(); tpd.returnValue = returnValue; tpd.property = property; return tpd; } else { throw zeroInteractions(configurationMethod); } } /** * Executes a {@link FieldSelector} lambda on a proxy object of the specified type and returns the * {@link PropertyDescriptor} of the property selected. * * @param target Defines if the properties are validated against source or target rules. * @param configurationMethod The configuration method this {@link PropertyDescriptor} is used * for. Only needed for exception messages. * @param sensorType The type of sensor object. * @param selector The selector lambda. * @return Returns the {@link PropertyDescriptor} selected with the lambda. * @throws MappingException if a property was specified for mapping but not invoked. */ static <T> PropertyDescriptor getPropertyFromFieldSelector(Target target, String configurationMethod, Class<T> sensorType, FieldSelector<T> selector) { InvocationSensor<T> invocationSensor = new InvocationSensor<T>(sensorType); T sensor = invocationSensor.getSensor(); // perform the selector lambda on the sensor selector.selectField(sensor); // if any property interaction was tracked... if (invocationSensor.hasTrackedProperties()) { // ...make sure it was exactly one property interaction List<String> trackedPropertyNames = invocationSensor.getTrackedPropertyNames(); denyMultipleInteractions(configurationMethod, trackedPropertyNames); // get the property name String propertyName = trackedPropertyNames.get(0); // find the property descriptor or fail with an exception return getPropertyDescriptorOrFail(target, sensorType, propertyName); } else { throw zeroInteractions(configurationMethod); } } /** * Ensures that the specified property name is a property in the specified {@link Set} of {@link * PropertyDescriptor}s. * * @param target Defines if the properties are validated against source or target rules. * @param type The inspected type. * @param propertyName The property name */ static PropertyDescriptor getPropertyDescriptorOrFail(Target target, Class<?> type, String propertyName) { Optional<PropertyDescriptor> property; property = Properties.getProperties(type, target) .stream() .filter(pd -> pd.getName() .equals(propertyName)) .findFirst(); if (property.isPresent()) { return property.get(); } else { throw notAProperty(type, propertyName); } } static void denyMultipleInteractions(String configurationMethod, List<String> trackedPropertyNames) { if (trackedPropertyNames.size() > 1) { throw multipleInteractions(configurationMethod, trackedPropertyNames); } } static void denyAlreadyMappedProperty(Set<PropertyDescriptor> mappedProperties, PropertyDescriptor propertyDescriptor) { if (mappedProperties.contains(propertyDescriptor)) { throw alreadyMappedProperty(propertyDescriptor); } } /** * Registers a configured mapper to this object that is to be used whenever a hierarchical mapping * tries to map the specified types. <b>Note: Only one mapper can be added for a combination of * source and destination type!</b> * * @param mapper A mapper * @return Returns this {@link MappingConfiguration} object for further configuration. */ public MappingConfiguration<S, D> useMapper(Mapper<?, ?> mapper) { denyNull("mapper", mapper); InternalMapper<?, ?> interalMapper = new MapperAdapter<>(mapper); useInternalMapper(interalMapper); return this; } /** * Registers a custom type conversion to this mapping that is to be used whenever a type mapping is required that is * not defined by a replace operation. * <b>Note: Only one mapper/type converter can be added for a combination of * source and destination type!</b> * * @param typeMapping A {@link TypeMapping}. * @return Returns this {@link MappingConfiguration} object for further configuration. */ public MappingConfiguration<S, D> useMapper(TypeMapping<?, ?> typeMapping) { denyNull("typeMapping", typeMapping); useInternalMapper(typeMapping); return this; } /** * Disables the creation of implicit mappings, so that fields with the same name and same type are not mapped * automatically any more. This requires the user to define the mappings explicitly using * {@link #reassign(FieldSelector)} or any other mapping operation. * * @return Returns this {@link MappingConfiguration} object for further configuration. */ public MappingConfiguration<S, D> noImplicitMappings() { this.noImplicitMappings = true; return this; } /** * Returns <code>true</code> if the mapper does not create implicit mappings. If <code>false</code> * is returned, the mapper creates implicit mappings for field that have the same name and type. */ boolean isNoImplicitMappings() { return noImplicitMappings; } protected void useInternalMapper(InternalMapper<?, ?> interalMapper) { Projection<?, ?> projection = interalMapper.getProjection(); if (mappers.containsKey(projection)) { throw MappingException.duplicateMapper(projection.getSource(), projection.getDestination()); } else { mappers.put(projection, interalMapper); } } /** * Returns a registered mapper for hierarchical mapping. If the desired mapper was not found a * {@link MappingException} is thrown. * * @param sourceType The source type * @param destinationType The destination type * @return Returns the registered mapper. */ @SuppressWarnings("unchecked") <S1, D1> InternalMapper<S1, D1> getMapperFor(PropertyDescriptor sourceProperty, Class<S1> sourceType, PropertyDescriptor destinationProperty, Class<D1> destinationType) { Projection<?, ?> projection = new Projection<>(sourceType, destinationType); if (mappers.containsKey(projection)) { return (InternalMapper<S1, D1>) mappers.get(projection); } else { throw MappingException.noMapperFound(sourceProperty, sourceType, destinationProperty, destinationType); } } /** * Checks if the specified mapper is registered. * * @param sourceType The source type * @param destinationType the destination type * @return Returns <code>true</code> if a mapper was registered for this type of conversion. Otherwise * <code>false</code> * is returned. */ public <S1, D1> boolean hasMapperFor(Class<S1> sourceType, Class<D1> destinationType) { Projection<?, ?> projection = new Projection<>(sourceType, destinationType); return mappers.containsKey(projection); } /** * Performs the actual mapping with iteration recursively through the object hierarchy. * * @param source The source object to map to a new destination object. * @return Returns a newly created destination object. */ D map(S source) { return map(source, null); } /** * Performs the actual mapping with iteration recursively through the object hierarchy. * Warning, this feature is not provided for nested Collections instances, only for instances and nested instances * * @param source The source object to map to a new destination object. * @param destination The destination object to populate * @return Returns a newly created destination object. */ D map(S source, D destination) { D destinationObject = destination; if (source == null) { throw MappingException.denyMappingOfNull(); } if (destination == null) { destinationObject = createDestination(); } for (Transformation t : mappings) { t.performTransformation(source, destinationObject); } return destinationObject; } private D createDestination() { return newInstance(destination); } Class<S> getSource() { return source; } Class<D> getDestination() { return destination; } Set<Transformation> getMappings() { return new HashSet<>(mappings); } @Override public String toString() { return toString(false); } /** * Returns a string representation of this mapper. * * @param detailed If <code>true</code> the string will be more detailed. * @return Returns a string representation of this mapper. */ public String toString(boolean detailed) { StringBuilder b = new StringBuilder("Mapping from ").append(detailed ? source.getName() : source.getSimpleName()) .append("\n\t to ") .append(detailed ? destination.getName() : destination.getSimpleName()) .append("\n with transformation:\n"); mappings.stream() .sorted(Comparator.comparing(t -> t.getClass() .getName())) .forEach(t -> { b.append("- ") .append(t.toString(detailed)) .append("\n"); }); Set<PropertyDescriptor> unmappedProperties = getUnmappedProperties(); if (unmappedProperties.isEmpty()) { b.append("All properties are mapped!"); } else { b.append(createUnmappedMessage(unmappedProperties)); } return b.toString(); } /** * @return Returns the registered {@link Mapper}s. */ protected Map<Projection<?, ?>, InternalMapper<?, ?>> getMappers() { return new Hashtable<>(this.mappers); } }
package com.royalrangers.service; import com.dropbox.core.DbxException; import com.dropbox.core.DbxRequestConfig; import com.dropbox.core.v2.DbxClientV2; import com.dropbox.core.v2.files.FileMetadata; import com.dropbox.core.v2.sharing.SharedLinkMetadata; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import java.util.UUID; @Service public class DropboxService { @Value("${dropbox.appName}") private String appName; @Value("${dropbox.accessToken}") private String accessToken; public DbxClientV2 getClient() { DbxRequestConfig config = DbxRequestConfig.newBuilder(appName) .withUserLocale(Locale.getDefault().toString()) .build(); DbxClientV2 client = new DbxClientV2(config, accessToken); return client; } public void fileUpload(MultipartFile file) throws IOException, DbxException { byte[] bytes = file.getBytes(); InputStream in = new ByteArrayInputStream(bytes); FileMetadata metadata = getClient().files().uploadBuilder("/" + file.getOriginalFilename()) .uploadAndFinish(in); } public String avatarUpload(MultipartFile file) throws IOException, DbxException { String path = "/avatar/"; String extension = getFilenameExtension(file.getOriginalFilename()); String filename = UUID.randomUUID().toString() + extension; InputStream in = file.getInputStream(); DbxClientV2 client = getClient(); FileMetadata metadata = client.files().uploadBuilder(path + filename).uploadAndFinish(in); SharedLinkMetadata shared = client.sharing().createSharedLinkWithSettings(path +filename); return shared.getUrl(); } private String getFilenameExtension (String filename) { return filename.substring(filename.lastIndexOf(".")); } }
package com.sciul.cloud_configurator.dsl; import com.sciul.cloud_configurator.Provider; import javax.json.JsonObject; import java.util.HashMap; import java.util.Map; public class Subnet extends Resource { private String cidrBlock, availabilityZone; private VPC vpc; public Subnet(String name, String cidrBlock, String availabilityZone, VPC vpc) { setCidrBlock(cidrBlock); setAvailabilityZone(availabilityZone); setVPC(vpc); setName("SUBNET-" + name + "-" + availabilityZone); resourceList.add(new RouteTable("RTB-" + name, vpc.getName(), resourceList)); resourceList.add(new SubnetNetworkAclAssociation(getName() + "-ACL", getName(), "SCI-QA-ACL", resourceList)); } @Override public JsonObject toJson(Provider provider) { return provider.createSubnet(this); } @Override public Subnet tag(String name, String value) { tags.put(name, value); return this; } public String getAvailabilityZone() { return availabilityZone; } public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; } public VPC getVPC() { return vpc; } public void setVPC(VPC vpc) { this.vpc = vpc; resourceList = vpc.resourceList; } public String getCidrBlock() { return cidrBlock; } public void setCidrBlock(String cidrBlock) { this.cidrBlock = cidrBlock; } }
package com.shape.web.controller; import com.shape.web.entity.Alarm; import com.shape.web.entity.FileDB; import com.shape.web.entity.Project; import com.shape.web.entity.User; import com.shape.web.service.AlarmService; import com.shape.web.service.FileDBService; import com.shape.web.service.ProjectService; import com.shape.web.service.UserService; import com.shape.web.util.CommonUtils; import com.shape.web.util.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Controller; 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.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; @Controller public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired AlarmService as; @Autowired UserService us; @Autowired ProjectService pjs; @Autowired FileDBService fs; @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String Upload(@RequestParam(value = "idx") String projectIdx, @RequestParam(value = "userIdx") String userIdx, HttpServletRequest HSrequest, HttpSession session) throws Exception { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) HSrequest; Iterator<String> iterator = multipartHttpServletRequest.getFileNames(); Project project = pjs.get(Integer.parseInt(projectIdx)); User user = us.get(Integer.parseInt(userIdx)); String filePath = FileUtil.getFoldername(Integer.parseInt(projectIdx), null); MultipartFile multipartFile = null; String originalFileName = null; String originalFileExtension = null; String storedFileName = null; String type = null; Pattern pattern = Pattern.compile("\\.(jpg|jpeg|png|gif)$", Pattern.CASE_INSENSITIVE); File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } while (iterator.hasNext()) { multipartFile = multipartHttpServletRequest.getFile(iterator.next()); if (!multipartFile.isEmpty()) { originalFileName = multipartFile.getOriginalFilename(); originalFileExtension = originalFileName.substring(originalFileName.lastIndexOf(".")); storedFileName = CommonUtils.getRandomString() + originalFileExtension; Matcher m = pattern.matcher(originalFileExtension); if (m.matches()) type = "img"; else type = "file"; file = new File(filePath + "/" + originalFileName); multipartFile.transferTo(file); FileDB fd = new FileDB(storedFileName, originalFileName, filePath, type, new Date()); fd.setUser(user); fd.setProject(project); fs.save(fd); for (User u : project.getUsers()) { Alarm alarm = new Alarm(2, originalFileName, "download?name=" + storedFileName, new Date()); alarm.setUser(u); alarm.setActor(user); project.addAlarms(alarm); as.save(alarm); } logger.info(filePath + "/" + originalFileName + " UPLOAD FINISHED!"); return storedFileName; } } return "redirect:/chat?projectIdx=" + projectIdx; } @RequestMapping(value = "/download", method = RequestMethod.GET) public void Download(@RequestParam(value = "filename", required = true) String name, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream in = null; OutputStream os = null; String client = ""; FileDB fd=fs.getByStoredname(name); name=fd.getOriginalname(); String folder=fd.getPath(); File file = new File(folder + "/" + name); response.reset(); response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"" + ";"); if (client.contains("MSIE")) { response.setHeader("Content-Disposition", "attachment; filename=" + new String(name.getBytes("KSC5601"), "ISO8859_1")); } else { response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(name, "UTF-8") + "\""); response.setHeader("Content-Type", "application/octet-stream; charset=utf-8"); //octet-stream-> } //response response.setHeader("Content-Length", "" + file.length()); in = new FileInputStream(file); os = response.getOutputStream(); byte b[] = new byte[(int) file.length()]; int leng = 0; logger.info(" " + name); while ((leng = in.read(b)) > 0) { os.write(b, 0, leng); } in.close(); os.close(); } }
package com.testdroid.jenkins; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.testdroid.api.APIException; import com.testdroid.api.model.*; import com.testdroid.api.model.APITestRunConfig.Scheduler; import com.testdroid.jenkins.remotesupport.MachineIndependentFileUploader; import com.testdroid.jenkins.remotesupport.MachineIndependentResultsDownloader; import com.testdroid.jenkins.scheduler.TestRunFinishCheckScheduler; import com.testdroid.jenkins.scheduler.TestRunFinishCheckSchedulerFactory; import com.testdroid.jenkins.utils.ApiClientAdapter; import com.testdroid.jenkins.utils.LocaleUtil; import com.testdroid.jenkins.utils.TestdroidApiUtil; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.URI; import java.util.*; import java.util.concurrent.Semaphore; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import static com.testdroid.api.model.APIDevice.OsType; import static com.testdroid.api.model.APIDevice.OsType.UNDEFINED; import static com.testdroid.jenkins.Messages.*; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; public class RunInCloudBuilder extends AbstractBuilder { private static final Logger LOGGER = Logger.getLogger(RunInCloudBuilder.class.getSimpleName()); private static final String POST_HOOK_URL = "/plugin/testdroid-run-in-cloud/api/json/cloud-webhook"; private static final String DEFAULT_TEST_TIMEOUT = "600"; // 10 minutes private static final Semaphore semaphore = new Semaphore(1); private String appPath; //Backward compatibility, for those who has clusterId in config.xml private String clusterId; private String deviceGroupId; private String dataPath; private boolean failBuildIfThisStepFailed; private String keyValuePairs; private String language; private String projectId; private String scheduler; private String screenshotsDirectory; private String testCasesSelect; private String testCasesValue; private String testPath; private String testRunName; private String testRunner; private WaitForResultsBlock waitForResultsBlock; private String withAnnotation; private String withoutAnnotation; private String testTimeout; private String credentialsId; private String cloudUrl; private Long frameworkId; private APIDevice.OsType osType; private String cloudUIUrl; public String getCloudUIUrl() { return cloudUIUrl; } public void setCloudUIUrl(String cloudUIUrl) { this.cloudUIUrl = cloudUIUrl; } // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public RunInCloudBuilder( String projectId, String appPath, String testPath, String dataPath, String testRunName, String scheduler, String testRunner, String deviceGroupId, String language, String screenshotsDirectory, String keyValuePairs, String withAnnotation, String withoutAnnotation, String testCasesSelect, String testCasesValue, Boolean failBuildIfThisStepFailed, WaitForResultsBlock waitForResultsBlock, String testTimeout, String credentialsId, String cloudUrl, String cloudUIUrl, Long frameworkId, APIDevice.OsType osType) { this.projectId = projectId; this.appPath = appPath; this.dataPath = dataPath; this.testPath = testPath; this.testRunName = testRunName; this.scheduler = scheduler; this.testRunner = testRunner; this.screenshotsDirectory = screenshotsDirectory; this.keyValuePairs = keyValuePairs; this.withAnnotation = withAnnotation; this.withoutAnnotation = withoutAnnotation; this.testCasesSelect = testCasesSelect; this.testCasesValue = testCasesValue; this.deviceGroupId = deviceGroupId; this.language = language; this.failBuildIfThisStepFailed = failBuildIfThisStepFailed; this.testTimeout = testTimeout; this.credentialsId = credentialsId; this.cloudUrl = cloudUrl; this.frameworkId = frameworkId; this.osType = osType; this.waitForResultsBlock = waitForResultsBlock; this.cloudUIUrl = cloudUIUrl; } public String getTestRunName() { return testRunName; } public void setTestRunName(String testRunName) { this.testRunName = testRunName; } public String getAppPath() { return appPath; } public void setAppPath(String appPath) { this.appPath = appPath; } public String getTestPath() { return testPath; } public void setTestPath(String testPath) { this.testPath = testPath; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getDeviceGroupId() { //Backward compatibility, for those who has clusterId in config.xml if (isBlank(deviceGroupId) && isNotBlank(clusterId)) { return clusterId; } else { return deviceGroupId; } } public void setDeviceGroupId(String deviceGroupId) { this.deviceGroupId = deviceGroupId; } public String getTestRunner() { return testRunner; } public void setTestRunner(String testRunner) { this.testRunner = testRunner; } public String getScreenshotsDirectory() { return screenshotsDirectory; } public void setScreenshotsDirectory(String screenshotsDirectory) { this.screenshotsDirectory = screenshotsDirectory; } public String getKeyValuePairs() { return keyValuePairs; } public void setKeyValuePairs(String keyValuePairs) { this.keyValuePairs = keyValuePairs; } public String getWithAnnotation() { return withAnnotation; } public void setWithAnnotation(String withAnnotation) { this.withAnnotation = withAnnotation; } public String getWithoutAnnotation() { return withoutAnnotation; } public void setWithoutAnnotation(String withoutAnnotation) { this.withoutAnnotation = withoutAnnotation; } public String getTestCasesSelect() { if (StringUtils.isBlank(testCasesSelect)) { return APITestRunConfig.LimitationType.PACKAGE.name(); } return testCasesSelect; } public void setTestCasesSelect(String testCasesSelect) { this.testCasesSelect = testCasesSelect; } public String getTestCasesValue() { return testCasesValue; } public void setTestCasesValue(String testCasesValue) { this.testCasesValue = testCasesValue; } public String getDataPath() { return dataPath; } public void setDataPath(String dataPath) { this.dataPath = dataPath; } public String getLanguage() { if (StringUtils.isBlank(language)) { language = LocaleUtil.formatLangCode(Locale.US); } // handle old versions' configs with wrongly formatted language codes if (language.contains("-")) { language = language.replace('-', '_'); } return language; } public void setLanguage(String language) { this.language = language; } public String getScheduler() { if (StringUtils.isBlank(scheduler)) { scheduler = Scheduler.PARALLEL.name(); } return scheduler; } public void setScheduler(String scheduler) { this.scheduler = scheduler.toLowerCase(); } public String getTestTimeout() { if (StringUtils.isBlank(testTimeout)) { return DEFAULT_TEST_TIMEOUT; } return testTimeout; } public void setTestTimeout(String testTimeout) { this.testTimeout = testTimeout; } public String getCredentialsId() { return credentialsId; } public void setCredentialsId(String credentialsId) { this.credentialsId = credentialsId; } public String getCloudUrl() { return cloudUrl; } public void setCloudUrl(String cloudUrl) { this.cloudUrl = cloudUrl; } public WaitForResultsBlock getWaitForResultsBlock() { return waitForResultsBlock; } public void setWaitForResultsBlock(WaitForResultsBlock waitForResultsBlock) { this.waitForResultsBlock = waitForResultsBlock; } public boolean isFailBuildIfThisStepFailed() { return failBuildIfThisStepFailed; } public void setFailBuildIfThisStepFailed(boolean failBuildIfThisStepFailed) { this.failBuildIfThisStepFailed = failBuildIfThisStepFailed; } public boolean isFullTest() { return StringUtils.isNotBlank(testPath); } public boolean isDataFile() { return StringUtils.isNotBlank(dataPath); } private boolean verifyParameters(TaskListener listener) { boolean result = true; if (StringUtils.isBlank(projectId)) { listener.getLogger().println(EMPTY_PROJECT() + "\n"); result = false; } return result; } public boolean isWaitForResults() { return waitForResultsBlock != null; } public Long getFrameworkId() { return frameworkId; } public void setFrameworkId(Long frameworkId) { this.frameworkId = frameworkId; } public OsType getOsType() { if (osType == null) { osType = UNDEFINED; } return osType; } public void setOsType(OsType osType) { this.osType = osType; } @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") private String evaluateHookUrl() { return isWaitForResults() ? StringUtils.isNotBlank(waitForResultsBlock.getHookURL()) ? waitForResultsBlock.getHookURL() : String.format("%s%s", Jenkins.getInstance().getRootUrl(), POST_HOOK_URL) : null; } private String evaluateResultsPath(FilePath workspace) { if (isWaitForResults()) { String resultsPath = waitForResultsBlock.getResultsPath(); if (StringUtils.isNotBlank(resultsPath)) { try { return getAbsolutePath(workspace, resultsPath); } catch (Exception exception) { LOGGER.log(Level.WARNING, "Couldn't get absolute path for results. Using workspace..."); } } return workspace.getRemote(); } return null; } /** * Perform build step, as required by AbstractBuilder */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { return completeRun(build, build.getWorkspace(), launcher, listener); } /** * Wrapper around runTest to be used elsewhere, and sensibly log steps of the build procedure */ public boolean completeRun(Run<?, ?> build, FilePath workspace, Launcher launcher, final TaskListener listener) { listener.getLogger().println(Messages.RUN_TEST_IN_CLOUD_STARTED()); boolean result = runTest(build, workspace, launcher, listener); if (result) { listener.getLogger().println(Messages.RUN_TEST_IN_CLOUD_SUCCEEDED()); } else { listener.getLogger().println(Messages.RUN_TEST_IN_CLOUD_FAILED()); } return result || !failBuildIfThisStepFailed; } /** * Actually run tests against Bitbar Cloud, and perhaps wait for results */ private boolean runTest(Run<?, ?> build, FilePath workspace, Launcher launcher, final TaskListener listener) { // rewrite paths to take variables into consideration String appPathFinal = applyMacro(build, listener, appPath); String testPathFinal = applyMacro(build, listener, testPath); String dataPathFinal = applyMacro(build, listener, dataPath); String withAnnotationFinal = applyMacro(build, listener, withAnnotation); String testRunnerFinal = applyMacro(build, listener, testRunner); String withoutAnnotationFinal = applyMacro(build, listener, withoutAnnotation); // cloudSettings will load the global settings in constructor..! TestdroidCloudSettings.DescriptorImpl cloudSettings = new TestdroidCloudSettings.DescriptorImpl(); // override default cloud settings if credentials/cloud URL specified on build level if (StringUtils.isNotBlank(getCredentialsId())) { StandardUsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById( getCredentialsId(), StandardUsernamePasswordCredentials.class, build, Collections.emptyList() ); if (credentials != null) { listener.getLogger().println(Messages.BUILD_STEP_USING_CREDENTIALS()); cloudSettings = new TestdroidCloudSettings.DescriptorImpl( credentials.getUsername(), credentials.getPassword().getPlainText() ); if (StringUtils.isNotBlank(getCloudUrl())) { cloudSettings.setCloudUrl(getCloudUrl()); if( StringUtils.isNotBlank(getCloudUIUrl())) { cloudSettings.setNewCloudUrl(getCloudUIUrl()); } } } else { listener.getLogger().println(String.format(Messages.COULDNT_FIND_CREDENTIALS(), getCredentialsId())); } } else if (StringUtils.isNotBlank(this.cloudUrl)) { // cloud URL always goes 1-to-1 with credentials, so it can't be used if credentials aren't specified..! listener.getLogger().println(String.format(Messages.CLOUD_URL_SET_BUT_NO_CREDENTIALS(), cloudUrl, cloudSettings.getCloudUrl())); } boolean releaseDone = false; try { // make part update and run project "transactional" // so that a different job can't overwrite project settings just after the first one set it RunInCloudBuilder.semaphore.acquire(); ApiClientAdapter api = TestdroidApiUtil.createApiClient(cloudSettings); if (!api.isAuthenticated()) { listener.getLogger().println("Couldn't connect to the cloud!"); return false; } if (!verifyParameters(listener)) { return false; } APIUser user = api.getUser(); String cloudVersion = api.getCloudVersion(); final APIProject project = user.getProject(Long.parseLong(getProjectId().trim())); if (project == null) { listener.getLogger().println(Messages.CHECK_PROJECT_NAME()); return false; } APITestRunConfig config = project.getTestRunConfig(); config.setDeviceLanguageCode(getLanguage()); config.setScheduler(Scheduler.valueOf(getScheduler().toUpperCase())); config.setUsedDeviceGroupId(Long.parseLong(getDeviceGroupId())); //Reset as in RiC we use only deviceGroups config.setDeviceIds(null); config.setHookURL(evaluateHookUrl()); config.setScreenshotDir(getScreenshotsDirectory()); config.setInstrumentationRunner(testRunnerFinal); config.setWithoutAnnotation(withoutAnnotationFinal); config.setWithAnnotation(withAnnotationFinal); config.setFrameworkId(Optional.ofNullable(frameworkId).orElse(config.getFrameworkId())); config.setOsType(Optional.ofNullable(osType).orElse(config.getOsType())); //clear files, otherwise use case fail: // 1. userA share project userB // 2. userB run project config.setFiles(null); // default test timeout is 10 minutes config.setTimeout(Long.parseLong(DEFAULT_TEST_TIMEOUT)); if (ApiClientAdapter.isPaidUser(user)) { try { long runTimeout = Long.parseLong(getTestTimeout()); config.setTimeout(runTimeout); } catch (NumberFormatException e) { listener.getLogger().println(TEST_TIMEOUT_NOT_NUMERIC_VALUE(getTestTimeout())); LOGGER.log(Level.WARNING, "NumberFormatException when parsing timeout.", e); } } else { listener.getLogger().println(String.format(Messages.FREE_USERS_MAX_10_MINS(), user.getEmail())); } setLimitations(build, listener, config); createProvidedParameters(config); config = user.validateTestRunConfig(config); printTestJob(project, config, cloudSettings, cloudVersion, listener); getDescriptor().save(); Long testFileId; Long dataFileId; Long appFileId; List<APIFileConfig> files = new ArrayList<>(); if (StringUtils.isNotBlank(getAppPath())) { final FilePath appFile = new FilePath(launcher.getChannel(), getAbsolutePath(workspace, appPathFinal)); listener.getLogger().println(String.format(Messages.UPLOADING_NEW_APPLICATION_S(), appPathFinal)); appFileId = appFile.act(new MachineIndependentFileUploader(cloudSettings, listener)); if (appFileId == null) { return false; } else { files.add(new APIFileConfig(appFileId, APIFileConfig.Action.INSTALL)); } } else { listener.getLogger().println("App path was blank. Using latest app in project."); } if (isFullTest()) { FilePath testFile = new FilePath(launcher.getChannel(), getAbsolutePath(workspace, testPathFinal)); listener.getLogger().println(String.format(Messages.UPLOADING_NEW_INSTRUMENTATION_S(), testPathFinal)); testFileId = testFile.act(new MachineIndependentFileUploader(cloudSettings, listener)); if (testFileId == null) { return false; } else { files.add(new APIFileConfig(testFileId, APIFileConfig.Action.RUN_TEST)); } } if (isDataFile()) { FilePath dataFile = new FilePath(launcher.getChannel(), getAbsolutePath(workspace, dataPathFinal)); listener.getLogger().println(String.format(Messages.UPLOADING_DATA_FILE_S(), dataPathFinal)); dataFileId = dataFile.act(new MachineIndependentFileUploader(cloudSettings, listener)); if (dataFileId == null) { return false; } else { files.add(new APIFileConfig(dataFileId, APIFileConfig.Action.COPY_TO_DEVICE)); } } listener.getLogger().println(Messages.RUNNING_TESTS()); // run project with proper name set in jenkins if it's set String finalTestRunName = applyMacro(build, listener, getTestRunName()); if (StringUtils.isBlank(finalTestRunName) || finalTestRunName.trim().startsWith("$")) { finalTestRunName = null; } config.setFiles(files); config.setTestRunName(finalTestRunName); config = user.validateTestRunConfig(config); // start the test run itself APITestRun testRun = user.startTestRun(config); // add the Bitbar Cloud link to the left-hand-side menu in Jenkins BuildBadgeAction cloudLinkAction = new CloudLink(cloudSettings.resolveCloudUiUrl(), project.getId(), testRun.getId(), cloudVersion); build.addAction(cloudLinkAction); RunInCloudEnvInject variable = new RunInCloudEnvInject("CLOUD_LINK", cloudLinkAction.getUrlName()); build.addAction(variable); listener.getLogger().println(String.format("Started new Bitbar Cloud run at: %s (id: %s)", cloudLinkAction.getUrlName(), testRun.getId())); RunInCloudBuilder.semaphore.release(); releaseDone = true; return waitForResults(user, project, testRun, workspace, launcher, listener, cloudSettings); } catch (APIException e) { listener.getLogger().println(String.format("%s: %s", Messages.ERROR_API(), e.getMessage())); LOGGER.log(Level.WARNING, Messages.ERROR_API(), e); } catch (IOException e) { listener.getLogger().println(String.format("%s: %s", Messages.ERROR_CONNECTION(), e.getLocalizedMessage())); LOGGER.log(Level.WARNING, Messages.ERROR_CONNECTION(), e); } catch (InterruptedException e) { listener.getLogger().println(String.format("%s: %s", Messages.ERROR_TESTDROID(), e.getLocalizedMessage())); LOGGER.log(Level.WARNING, Messages.ERROR_TESTDROID(), e); } catch (NumberFormatException e) { listener.getLogger().println(Messages.NO_DEVICE_GROUP_CHOSEN()); LOGGER.log(Level.WARNING, Messages.NO_DEVICE_GROUP_CHOSEN()); } finally { if (!releaseDone) { RunInCloudBuilder.semaphore.release(); } } return false; } @SuppressFBWarnings(value="NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") private boolean waitForResults( final APIUser user, final APIProject project, final APITestRun testRun, FilePath workspace, Launcher launcher, TaskListener listener, TestdroidCloudSettings.DescriptorImpl cloudSettings) { if (isWaitForResults()) { boolean isDownloadOk = false; TestRunFinishCheckScheduler scheduler = TestRunFinishCheckSchedulerFactory.createTestRunFinishScheduler( waitForResultsBlock.getTestRunStateCheckMethod(), listener ); try { boolean testRunToAbort = false; listener.getLogger().println("Waiting for results..."); scheduler.schedule(this, testRun); try { synchronized (this) { wait(waitForResultsBlock.getWaitForResultsTimeout() * 1000); } scheduler.cancel(testRun); testRun.refresh(); if (testRun.getState() == APITestRun.State.FINISHED) { isDownloadOk = launcher.getChannel().call( new MachineIndependentResultsDownloader( cloudSettings, listener, project.getId(), testRun.getId(), evaluateResultsPath(workspace), waitForResultsBlock.isDownloadScreenshots())); if (!isDownloadOk) { listener.getLogger().println(Messages.DOWNLOAD_RESULTS_FAILED()); LOGGER.log(Level.WARNING, Messages.DOWNLOAD_RESULTS_FAILED()); } } else { testRunToAbort = true; String msg = String.format(Messages.DOWNLOAD_RESULTS_FAILED_WITH_REASON_S(), "Test run is not finished yet!"); listener.getLogger().println(msg); LOGGER.log(Level.WARNING, msg); } } catch (InterruptedException e) { testRunToAbort = true; listener.getLogger().println(e.getMessage()); LOGGER.log(Level.WARNING, e.getMessage(), e); } if (testRunToAbort && waitForResultsBlock.isForceFinishAfterBreak()) { String msg = "Force finish test in Cloud"; listener.getLogger().println(msg); LOGGER.log(Level.WARNING, msg); testRun.abort(); } } catch (APIException e) { listener.getLogger().println( String.format("%s: %s", Messages.ERROR_API(), e.getMessage())); LOGGER.log(Level.WARNING, Messages.ERROR_API(), e); } catch (IOException e) { listener.getLogger().println( String.format("%s: %s", Messages.ERROR_CONNECTION(), e.getLocalizedMessage())); LOGGER.log(Level.WARNING, Messages.ERROR_CONNECTION(), e); } finally { scheduler.cancel(testRun); } return isDownloadOk; } else { return true; } } private void setLimitations(Run<?, ?> build, final TaskListener listener, APITestRunConfig config) { if (StringUtils.isNotBlank(getTestCasesValue())) { config.setLimitationType(APITestRunConfig.LimitationType.valueOf(getTestCasesSelect().toUpperCase())); config.setLimitationValue(applyMacro(build, listener, getTestCasesValue())); } else { config.setLimitationType(null); config.setLimitationValue(""); } } private void createProvidedParameters(APITestRunConfig config) { List<APITestRunParameter> apiTestRunParameters = new ArrayList<>(); if (keyValuePairs != null) { String[] splitKeyValuePairs = keyValuePairs.split(";"); apiTestRunParameters.addAll(Arrays.stream(splitKeyValuePairs).filter(StringUtils::isNotEmpty).map(s -> { String[] pair = s.split(":"); return pair.length == 2 ? new APITestRunParameter(pair[0], pair[1]) : null; }).filter(Objects::nonNull).collect(Collectors.toList())); } config.setTestRunParameters(apiTestRunParameters); } private void printTestJob(APIProject project, APITestRunConfig config, TestdroidCloudSettings.DescriptorImpl cloudSettings, String cloudVersion, TaskListener listener) { listener.getLogger().println(Messages.TEST_RUN_CONFIGURATION()); listener.getLogger().println(String.format("%s: %s (version %s)", Messages.CLOUD_URL(), cloudSettings.getCloudUrl(), cloudVersion)); listener.getLogger().println(String.format("%s: %s", Messages.USER_EMAIL(), cloudSettings.getEmail())); listener.getLogger().println(String.format("%s: %s", Messages.PROJECT(), project.getName())); listener.getLogger().println(OS_TYPE_VALUE(config.getOsType())); listener.getLogger().println(FRAMEWORK_ID_VALUE(config.getFrameworkId())); listener.getLogger().println(String.format("%s: %s", Messages.LOCALE(), config.getDeviceLanguageCode())); listener.getLogger().println(String.format("%s: %s", Messages.SCHEDULER(), config.getScheduler())); listener.getLogger().println(String.format("%s: %s", Messages.TIMEOUT(), config.getTimeout())); } private String getAbsolutePath(FilePath workspace, String path) throws IOException, InterruptedException { if (StringUtils.isBlank(path)) { return StringUtils.EMPTY; } String trimmed = StringUtils.trim(path); if (trimmed.startsWith(File.separator)) { // absolute return trimmed; } else { URI workspaceURI = workspace.toURI(); return workspaceURI.getPath() + trimmed; } } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> implements Serializable, RunInCloudDescriptorHelper { private static final long serialVersionUID = 1L; public DescriptorImpl() { super(RunInCloudBuilder.class); load(); } @Override public String getDisplayName() { return Messages.TESTDROID_RUN_TESTS_IN_CLOUD(); } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { save(); return super.configure(req, formData); } @Override public boolean isApplicable(Class<? extends AbstractProject> arg0) { return true; } } }
package com.treetank.io.berkeley; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.Environment; import com.sleepycat.je.LockMode; import com.sleepycat.je.OperationStatus; import com.sleepycat.je.Transaction; import com.treetank.exception.TreetankIOException; import com.treetank.io.IReader; import com.treetank.io.StorageProperties; import com.treetank.page.AbstractPage; import com.treetank.page.PageReference; import com.treetank.page.UberPage; /** * This class represents an reading instance of the Treetank-Application * implementing the {@link IReader}-interface. * * @author Sebastian Graf, University of Konstanz * */ public class BerkeleyReader implements IReader { /** Link to the {@link Database} */ private transient final Database mDatabase; /** Link to the {@link Transaction} */ private transient final Transaction mTxn; /** * Constructor. * * @param database * to be connected to * @param txn * transaction to be used */ public BerkeleyReader(final Database database, final Transaction txn) { mTxn = txn; mDatabase = database; } /** * Constructor * * @param env * to be used * @param database * to be connected to * @throws DatabaseException * if something weird happens */ public BerkeleyReader(final Environment env, final Database database) throws DatabaseException { this(database, env.beginTransaction(null, null)); } /** * {@inheritDoc} */ public StorageProperties getProps() throws TreetankIOException { try { final DatabaseEntry keyEntry = new DatabaseEntry(); BerkeleyFactory.KEY.objectToEntry(BerkeleyKey.getPropsKey(), keyEntry); final DatabaseEntry valueEntry = new DatabaseEntry(); mDatabase.get(mTxn, keyEntry, valueEntry, LockMode.DEFAULT); final StorageProperties props = BerkeleyFactory.PROPS_VAL_B .entryToObject(valueEntry); return props; } catch (final DatabaseException exc) { throw new TreetankIOException(exc); } } /** * {@inheritDoc} */ public AbstractPage read(final PageReference pageReference) throws TreetankIOException { final DatabaseEntry valueEntry = new DatabaseEntry(); final DatabaseEntry keyEntry = new DatabaseEntry(); BerkeleyFactory.KEY.objectToEntry(pageReference.getKey(), keyEntry); AbstractPage page = null; try { final OperationStatus status = mDatabase.get(mTxn, keyEntry, valueEntry, LockMode.DEFAULT); if (status == OperationStatus.SUCCESS) { page = BerkeleyFactory.PAGE_VAL_B.entryToObject(valueEntry); } return page; } catch (final DatabaseException exc) { throw new TreetankIOException(exc); } } /** * {@inheritDoc} */ public PageReference readFirstReference() throws TreetankIOException { final DatabaseEntry valueEntry = new DatabaseEntry(); final DatabaseEntry keyEntry = new DatabaseEntry(); BerkeleyFactory.KEY.objectToEntry(BerkeleyKey.getFirstRevKey(), keyEntry); try { final OperationStatus status = mDatabase.get(mTxn, keyEntry, valueEntry, LockMode.DEFAULT); PageReference uberPageReference = null; if (status == OperationStatus.SUCCESS) { uberPageReference = BerkeleyFactory.FIRST_REV_VAL_B .entryToObject(valueEntry); } final UberPage page = (UberPage) read(uberPageReference); uberPageReference.setPage(page); return uberPageReference; } catch (final DatabaseException e) { throw new TreetankIOException(e); } } /** * {@inheritDoc} */ public void close() throws TreetankIOException { try { mTxn.abort(); } catch (final DatabaseException e) { throw new TreetankIOException(e); } } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((mDatabase == null) ? 0 : mDatabase.hashCode()); result = prime * result + ((mTxn == null) ? 0 : mTxn.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { boolean returnVal = true; if (obj == null) { returnVal = false; } if (getClass() != obj.getClass()) { returnVal = false; } final BerkeleyReader other = (BerkeleyReader) obj; if (mDatabase == null) { if (other.mDatabase != null) { returnVal = false; } } else if (!mDatabase.equals(other.mDatabase)) { returnVal = false; } if (mTxn == null) { if (other.mTxn != null) { returnVal = false; } } else if (!mTxn.equals(other.mTxn)) { returnVal = false; } return returnVal; } }
package com.visenze.visearch; import java.util.List; import java.util.Map; public class ObjectSearchResult { private String type; private Float score; private List<Integer> box; private Map<String, List<String>> attributes; private Map<String, List<String>> attributesList; private int total; private List<ImageResult> result; private List<Facet> facets; public ObjectSearchResult() { } public String getType() { return type; } public Float getScore() { return score; } public List<Integer> getBox() { return box; } public Map<String, List<String>> getAttributes() { return attributes; } public Map<String, List<String>> getAttributesList() { return attributesList; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<ImageResult> getResult() { return result; } public void setResult(List<ImageResult> result) { this.result = result; } public void setType(String type) { this.type = type; } public void setScore(Float score) { this.score = score; } public void setBox(List<Integer> box) { this.box = box; } public void setAttributes(Map<String, List<String>> attributes) { this.attributes = attributes; } public void setAttributesList(Map<String, List<String>> attributesList) { this.attributesList = attributesList; } public List<Facet> getFacets() { return facets; } public void setFacets(List<Facet> facets) { this.facets = facets; } }
package de.tblsoft.solr.pipeline; import com.google.common.base.Strings; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.pipeline.bean.Filter; import de.tblsoft.solr.util.DateUtils; import org.apache.commons.lang3.text.StrSubstitutor; import java.util.*; public abstract class AbstractFilter implements FilterIF { protected FilterIF nextFilter; protected Filter filter; private String baseDir; protected Map<String,String> variables = new HashMap<String, String>(); protected PipelineExecuter pipelineExecuter; @Override public void setVariables(Map<String,String> variables) { if(variables == null) { return; } for(Map.Entry<String,String> entry: variables.entrySet()) { this.variables.put("variables." + entry.getKey(), entry.getValue()); } } @Override public void init() { nextFilter.init(); } @Override public void setFilterConfig(Filter filter) { this.filter = filter; } @Override public void document(Document document) { nextFilter.document(document); } @Override public void end() { nextFilter.end(); } @Override public void setNextFilter(FilterIF filter){ this.nextFilter=filter; } public String getProperty(String name, String defaultValue) { if(filter.getProperty() == null) { return defaultValue; } String value = (String) filter.getProperty().get(name); if(value != null) { StrSubstitutor strSubstitutor = new StrSubstitutor(variables); value = strSubstitutor.replace(value); return value; } return defaultValue; } public Boolean getPropertyAsBoolean(String name, Boolean defaultValue) { String value = getProperty(name,null); if(value == null) { return defaultValue; } return Boolean.valueOf(value); } public List<String> getPropertyAsList(String name, List<String> defaultValue) { if(filter.getProperty() == null) { return defaultValue; } List<String> value = (List<String>) filter.getProperty().get(name); if(value != null) { StrSubstitutor strSubstitutor = new StrSubstitutor(variables); for(int i = 0; i < value.size(); i++) { value.set(i, strSubstitutor.replace(value.get(i))); } return value; } return defaultValue; } public Map<String, String> getPropertyAsMapping(String name) { return getPropertyAsMapping(name, new HashMap<>(), "->"); } public Map<String, String> getPropertyAsMapping(String name, Map<String, String> defaultValue) { return getPropertyAsMapping(name,defaultValue, "->"); } public Map<String, String> getPropertyAsMapping(String name, Map<String, String> defaultValue, String splitter) { if(filter.getProperty() == null) { return defaultValue; } Map<String, String> mapping = new HashMap<>(); List<String> rawValues = getPropertyAsList(name, new ArrayList<>()); for (String rawValue : rawValues) { String[] splittedValue = rawValue.split(splitter); if(splittedValue.length < 2) { throw new RuntimeException("The mapping is not correct configured: " + rawValue); } mapping.put(splittedValue[0], splittedValue[1]); } return mapping; } public int getPropertyAsInt(String name, int defaultValue) { String value = getProperty(name,null); if(value != null) { return Integer.valueOf(value).intValue(); } return defaultValue; } public float getPropertyAsFloat(String name, float defaultValue) { String value = getProperty(name,null); if(value != null) { return Float.valueOf(value); } return defaultValue; } public Date getPropertyAsDate(String name, Date defaultValue) { String value = getProperty(name,null); if(value != null) { return DateUtils.getDate(value); } return defaultValue; } public void verify(String value, String message) { if(Strings.isNullOrEmpty(value)) { throw new RuntimeException(message); } } public void verify(List<String> value, String message) { if(value == null) { throw new RuntimeException(message); } } public String[] getPropertyAsArray(String name, String[] defaultValue) { List<String> list = getPropertyAsList(name, null); if(list == null) { return defaultValue; } return list.toArray(new String[list.size()]); } public String getBaseDir() { return baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } public String getId() { return this.filter.getId(); } @Override public void setPipelineExecuter(PipelineExecuter pipelineExecuter) { this.pipelineExecuter = pipelineExecuter; } public PipelineExecuter getPipelineExecuter() { return pipelineExecuter; } }
package de.timoh.brainfuck; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author Timo Hanisch (timohanisch@gmail.com) */ public class BrainfuckInterpreter { public static final char INC_POINTER = '>'; public static final char DEC_POINTER = '<'; public static final char INC_CELL = '+'; public static final char DEC_CELL = '-'; public static final char PRINT_CELL = '.'; public static final char READ_INPUT = ','; public static final char LOOP_OPEN = '['; public static final char LOOP_CLOSE = ']'; public static final int DEFAULT_CELL_COUNT = 1024; private char[] cells; private char[] input; private int currentCell = 0; private int currentInterpretingCharacter = 0; private final DataInputStream in; private boolean debug = false; public BrainfuckInterpreter() { this(DEFAULT_CELL_COUNT); } public BrainfuckInterpreter(boolean debug) { this(DEFAULT_CELL_COUNT, debug); } public BrainfuckInterpreter(int cellCount) { this.cells = new char[cellCount]; this.in = new DataInputStream(System.in); } public BrainfuckInterpreter(int cellCount, boolean debug) { this.cells = new char[cellCount]; this.in = new DataInputStream(System.in); this.debug = debug; } public void interpret(String input) { prepareInterpret(input); doInterpretation(); } private void prepareInterpret(String input) { if (this.debug) { System.out.println("Converting input"); } inputToCharArray(input); if (this.debug) { System.out.println("Interpreting input"); } } private void doInterpretation() { while (this.currentInterpretingCharacter < this.input.length) { interpretChar(this.input[this.currentInterpretingCharacter]); ++this.currentInterpretingCharacter; } } private void inputToCharArray(String input) { List<Character> inputList = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(input); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); String[] chars = token.split(""); for (String s : chars) { if (!s.isEmpty()) { inputList.add(s.charAt(0)); } } } this.input = new char[inputList.size()]; for (int i = 0; i < inputList.size(); i++) { this.input[i] = inputList.get(i); } } private void interpretChar(char c) { switch (c) { case INC_POINTER: if (this.currentCell + 1 < this.cells.length) { ++this.currentCell; } else { throw new RuntimeException("Segmentation fault"); } break; case DEC_POINTER: if (this.currentCell - 1 >= 0) { --this.currentCell; } else { throw new RuntimeException("Segmentation fault"); } break; case INC_CELL: ++this.cells[this.currentCell]; break; case DEC_CELL: --this.cells[this.currentCell]; break; case PRINT_CELL: System.out.print(this.cells[this.currentCell]); break; case READ_INPUT: try { char inputChar = (char) this.in.readByte(); this.cells[this.currentCell] = inputChar; } catch (IOException ex) { throw new RuntimeException(ex); } break; case LOOP_OPEN: if (this.cells[this.currentCell] == 0) { findMatchingCloseLoop(); } break; case LOOP_CLOSE: if (this.cells[this.currentCell] != 0) { findMatchingOpenLoop(); } break; default: // By default, all non language characters are used as comment strings. } } private void findMatchingCloseLoop() { ++this.currentInterpretingCharacter; int loopDepth = 0; while (true) { switch (this.input[this.currentInterpretingCharacter]) { case LOOP_OPEN: ++loopDepth; break; case LOOP_CLOSE: if (loopDepth <= 0) { return; } --loopDepth; break; default: break; } ++this.currentInterpretingCharacter; if (this.currentInterpretingCharacter >= this.input.length) { throw new RuntimeException("Loop error"); } } } private void findMatchingOpenLoop() { --this.currentInterpretingCharacter; int loopDepth = 0; while (true) { switch (this.input[this.currentInterpretingCharacter]) { case LOOP_OPEN: if (loopDepth == 0) { return; } --loopDepth; break; case LOOP_CLOSE: loopDepth++; break; default: break; } --this.currentInterpretingCharacter; if (this.currentInterpretingCharacter < 0) { throw new RuntimeException("Loop error"); } } } }
package de.tu_dortmund.ub.data.dswarm; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Callable; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonValue; import javax.json.stream.JsonGenerator; import de.tu_dortmund.ub.data.util.TPUUtil; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Export Task for Task Processing Unit for d:swarm * * @author Jan Polowinski (SLUB Dresden) * @version 2015-04-20 * */ public class Transform implements Callable<String> { private static final Logger LOG = LoggerFactory.getLogger(Transform.class); public static final String CHUNKED_TRANSFER_ENCODING = "chunked"; private final Properties config; private final String inputDataModelID; private final String outputDataModelID; private final Collection<String> projectIDs; private final Optional<Boolean> optionalDoIngestOnTheFly; private final Optional<Boolean> optionalDoExportOnTheFly; private final int cnt; public Transform(final Properties config, final String inputDataModelID, final String outputDataModelID, final Optional<Boolean> optionalDoIngestOnTheFly, final Optional<Boolean> optionalDoExportOnTheFly, final int cnt) { this.config = config; this.optionalDoIngestOnTheFly = optionalDoIngestOnTheFly; this.optionalDoExportOnTheFly = optionalDoExportOnTheFly; this.cnt = cnt; // init IDs of the prototype project if (inputDataModelID != null && !inputDataModelID.trim().isEmpty()) { this.inputDataModelID = inputDataModelID; } else { this.inputDataModelID = config.getProperty(TPUStatics.PROTOTYPE_INPUT_DATA_MODEL_ID_IDENTIFIER); } this.projectIDs = determineProjectIDs(); this.outputDataModelID = outputDataModelID; } // @Override public String call() { final String serviceName = config.getProperty(TPUStatics.SERVICE_NAME_IDENTIFIER); final String engineDswarmAPI = config.getProperty(TPUStatics.ENGINE_DSWARM_API_IDENTIFIER); LOG.info(String.format("[%s][%d] Starting 'Transform (Task)' ...", serviceName, cnt)); try { // export and save to results folder final String response = executeTask(inputDataModelID, projectIDs, outputDataModelID, serviceName, engineDswarmAPI, optionalDoIngestOnTheFly, optionalDoExportOnTheFly); LOG.debug(String.format("[%s][%d] task execution result = '%s'", serviceName, cnt, response)); return response; } catch (final Exception e) { LOG.error(String.format("[%s][%d] Transforming datamodel '%s' to '%s' failed with a %s", serviceName, cnt, inputDataModelID, outputDataModelID, e.getClass().getSimpleName()), e); } return null; } /** * configuration and processing of the task * * @param inputDataModelID * @param projectIDs * @param outputDataModelID * @return */ private String executeTask(final String inputDataModelID, final Collection<String> projectIDs, final String outputDataModelID, final String serviceName, final String engineDswarmAPI, final Optional<Boolean> optionalDoIngestOnTheFly, final Optional<Boolean> optionalDoExportOnTheFly) throws Exception { final JsonArray mappings = getMappingsFromProjects(projectIDs, serviceName, engineDswarmAPI); final JsonObject inputDataModel = getDataModel(inputDataModelID, serviceName, engineDswarmAPI); final JsonObject outputDataModel = getDataModel(outputDataModelID, serviceName, engineDswarmAPI); // erzeuge Task-JSON final String persistString = config.getProperty(TPUStatics.PERSIST_IN_DMP_IDENTIFIER); final boolean persist; if (persistString != null && !persistString.trim().isEmpty()) { persist = Boolean.valueOf(persistString); } else { // default is false persist = false; } final StringWriter stringWriter = new StringWriter(); final JsonGenerator jp = Json.createGenerator(stringWriter); jp.writeStartObject(); jp.write(DswarmBackendStatics.PERSIST_IDENTIFIER, persist); // default for now: true, i.e., no content will be returned jp.write(DswarmBackendStatics.DO_NOT_RETURN_DATA_IDENTIFIER, true); if (optionalDoIngestOnTheFly.isPresent()) { LOG.info(String.format("[%s][%d] do ingest on-the-fly", serviceName, cnt)); jp.write(DswarmBackendStatics.DO_INGEST_ON_THE_FLY, optionalDoIngestOnTheFly.get()); } if (optionalDoExportOnTheFly.isPresent()) { LOG.info(String.format("[%s][%d] do export on-the-fly", serviceName, cnt)); jp.write(DswarmBackendStatics.DO_EXPORT_ON_THE_FLY, optionalDoExportOnTheFly.get()); } jp.write(DswarmBackendStatics.DO_VERSIONING_ON_RESULT_IDENTIFIER, false); // task jp.writeStartObject(DswarmBackendStatics.TASK_IDENTIFIER); jp.write(DswarmBackendStatics.NAME_IDENTIFIER, "Task Batch-Prozess 'CrossRef'"); jp.write(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, "Task Batch-Prozess 'CrossRef' zum InputDataModel 'inputDataModelID '"); // job jp.writeStartObject(DswarmBackendStatics.JOB_IDENTIFIER); jp.write(DswarmBackendStatics.UUID_IDENTIFIER, UUID.randomUUID().toString()); jp.write(DswarmBackendStatics.MAPPINGS_IDENTIFIER, mappings); jp.writeEnd(); jp.write(DswarmBackendStatics.INPUT_DATA_MODEL_IDENTIFIER, inputDataModel); jp.write(DswarmBackendStatics.OUTPUT_DATA_MODEL_IDENTIFIER, outputDataModel); // end task jp.writeEnd(); // end request jp.writeEnd(); jp.flush(); jp.close(); final String task = stringWriter.toString(); stringWriter.flush(); stringWriter.close(); LOG.debug(String.format("[%s][%d] task : %s", serviceName, cnt, task)); try (CloseableHttpClient httpclient = HttpClients.createDefault()) { // POST /dmp/tasks/ final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.TASKS_ENDPOINT); final StringEntity stringEntity = new StringEntity(task, ContentType.APPLICATION_JSON); final String mimetype; if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) { mimetype = APIStatics.APPLICATION_XML_MIMETYPE; } else { mimetype = APIStatics.APPLICATION_JSON_MIMETYPE; } httpPost.setHeader(HttpHeaders.ACCEPT, mimetype); httpPost.setHeader(HttpHeaders.TRANSFER_ENCODING, CHUNKED_TRANSFER_ENCODING); httpPost.setEntity(stringEntity); final Header[] headers = httpPost.getAllHeaders(); final StringBuilder sb = new StringBuilder(); for (final Header header : headers) { final String name = header.getName(); final String value = header.getValue(); sb.append("\t\'").append(name).append("\' = \'").append(value).append("\'\n"); } LOG.info(String.format("[%s][%d] request : %s :: headers : \n'%s' :: body : '%s'", serviceName, cnt, httpPost.getRequestLine(), sb.toString(), stringEntity)); try (CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 204: { LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); return "success"; } case 200: { if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) { LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); // write result to file TPUUtil.writeResultToFile(httpResponse, config, outputDataModelID); return "success - exported XML"; } } default: { LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); EntityUtils.consume(httpEntity); } } } } return null; } private JsonArray getMappingsFromProjects(final Collection<String> projectIDs, final String serviceName, final String engineDswarmAPI) throws Exception { final JsonArrayBuilder mappingArrayBuilder = Json.createArrayBuilder(); for (final String projectID : projectIDs) { final JsonArray projectMappings = getMappingsFromProject(projectID, serviceName, engineDswarmAPI); if (projectMappings == null) { LOG.error(String.format("[%s][%d] couldn't determine mappings from project '%s'", serviceName, cnt, projectID)); continue; } LOG.info(String.format("[%s][%d] retrieved '%d' mappings from project '%s'", serviceName, cnt, projectMappings.size(), projectID)); for (final JsonValue projectMapping : projectMappings) { mappingArrayBuilder.add(projectMapping); } } final JsonArray mappingsArray = mappingArrayBuilder.build(); LOG.info(String.format("[%s][%d] accumulated '%d' mappings from all projects", serviceName, cnt, mappingsArray.size())); return mappingsArray; } private JsonArray getMappingsFromProject(final String projectID, final String serviceName, final String engineDswarmAPI) throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { // Hole Mappings aus dem Projekt mit 'projectID' final String uri = engineDswarmAPI + DswarmBackendStatics.PROJECTS_ENDPOINT + APIStatics.SLASH + projectID; final HttpGet httpGet = new HttpGet(uri); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpGet.getRequestLine())); try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { final StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, APIStatics.UTF_8); final String responseJson = writer.toString(); writer.flush(); writer.close(); LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, responseJson)); final JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(responseJson, APIStatics.UTF_8)); final JsonObject jsonObject = jsonReader.readObject(); final JsonArray mappings = jsonObject.getJsonArray(DswarmBackendStatics.MAPPINGS_IDENTIFIER); LOG.debug(String.format("[%s][%d] mappings : %s", serviceName, cnt, mappings.toString())); return mappings; } default: { LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine() .getReasonPhrase())); } } EntityUtils.consume(httpEntity); } } return null; } private JsonObject getDataModel(final String dataModelID, final String serviceName, final String engineDswarmAPI) throws Exception { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { // Hole Mappings aus dem Projekt mit 'projectID' final String uri = engineDswarmAPI + DswarmBackendStatics.DATAMODELS_ENDPOINT + APIStatics.SLASH + dataModelID; final HttpGet httpGet = new HttpGet(uri); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpGet.getRequestLine())); try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { final InputStream content = httpEntity.getContent(); final JsonReader jsonReader = Json.createReader(content); final JsonObject jsonObject = jsonReader.readObject(); LOG.info(String.format("[%s][%d] inputDataModel : %s", serviceName, cnt, jsonObject.toString())); final JsonObject dataResourceJSON = jsonObject.getJsonObject(DswarmBackendStatics.DATA_RESOURCE_IDENTIFIER); if (dataResourceJSON != null) { final String inputResourceID = dataResourceJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] inout resource ID : %s", serviceName, cnt, inputResourceID)); } return jsonObject; } default: { LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine() .getReasonPhrase())); } } EntityUtils.consume(httpEntity); } } return null; } private Collection<String> determineProjectIDs() { final List<String> projectIDs = new ArrayList<>(); final String projectIDsString = config.getProperty(TPUStatics.PROTOTYPE_PROJECT_IDS_INDENTIFIER, null); if (projectIDsString != null && !projectIDsString.trim().isEmpty()) { if (projectIDsString.contains(",")) { // multiple project ids final String[] projectIDsArray = projectIDsString.split(","); Collections.addAll(projectIDs, projectIDsArray); } else { // only one project id projectIDs.add(projectIDsString); } } else { final String projectID = config.getProperty(TPUStatics.PROTOTYPE_PROJECT_ID_INDENTIFIER); projectIDs.add(projectID); } return projectIDs; } }
package edu.cmu.sv.ws.ssnoc.rest; import java.util.ArrayList; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlElementWrapper; import edu.cmu.sv.ws.ssnoc.common.logging.Log; import edu.cmu.sv.ws.ssnoc.common.utils.ConverterUtils; import edu.cmu.sv.ws.ssnoc.data.dao.DAOFactory; import edu.cmu.sv.ws.ssnoc.data.dao.ILocationCrumbDAO; import edu.cmu.sv.ws.ssnoc.data.dao.IMessageDAO; import edu.cmu.sv.ws.ssnoc.data.dao.IStatusCrumbDAO; import edu.cmu.sv.ws.ssnoc.data.dao.IUserDAO; import edu.cmu.sv.ws.ssnoc.data.po.LocationCrumbPO; import edu.cmu.sv.ws.ssnoc.data.po.MessagePO; import edu.cmu.sv.ws.ssnoc.data.po.StatusCrumbPO; import edu.cmu.sv.ws.ssnoc.data.po.UserPO; import edu.cmu.sv.ws.ssnoc.dto.Message; import edu.cmu.sv.ws.ssnoc.dto.StatusCrumb; import edu.cmu.sv.ws.ssnoc.dto.User; /** * This class contains the implementation of the RESTful API calls made with * respect to a message. * */ @Path("/message") public class MessageService extends BaseService { /* * This method posts a new message on wall * * @param user - An object of type User * * @return - An object of type Response with the message of the request */ @POST @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Path("/{userName}") public Response addMessage(Message message) { Log.enter(message); Message resp = new Message(); try { // Step 0: do some validations - check for null user name, null // status, null location // Step 1: Get the existing user id from user name IUserDAO uDao = DAOFactory.getInstance().getUserDAO(); UserPO existingUser = uDao.findByName(message.getUserName()); long userId = 0; if(existingUser != null) userId = existingUser.getUserId(); // Step 2: Insert a new location and get back the location id ILocationCrumbDAO lDao = DAOFactory.getInstance() .getLocationCrumbDAO(); LocationCrumbPO lcpo = new LocationCrumbPO(); lcpo.setUserId(userId); lcpo.setLocation(message.getLocation()); long locationId = lDao.save(lcpo); // Step 3: Insert a new wall message and get back the message IMessageDAO mDao = DAOFactory.getInstance() .getMessageDAO(); MessagePO mpo = new MessagePO(); mpo.setAuthorId(userId); mpo.setLocationId(locationId); mpo.setMessage(message.getMessage()); // long messageId = mDao.saveWallMessage(mpo); // Step 4: Update the user with the new message, location crumb id // and modified at time // UserPO upo = new UserPO(); // upo.setUserId(userId); // upo.setLastStatusCrumbId(statusId); // upo.setLastLocationCrumbId(locationId); // uDao.update(upo); // Step 5: send a response back resp = ConverterUtils.convert(mpo); } catch (Exception e) { handleException(e); } finally { Log.exit(); } return created(resp); } @Path("/wall") /** * This method loads all message in the system. * * @return - List of all messages. */ @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @XmlElementWrapper(name = "messages") public List<Message> loadMessage() { Log.enter(); List<Message> message = null; try { List<MessagePO> messagePO = DAOFactory.getInstance().getMessageDAO().loadMessage(); message = new ArrayList<Message>(); for (MessagePO po : messagePO) { Message dto = ConverterUtils.convert(po); message.add(dto); } } catch (Exception e) { handleException(e); } finally { Log.exit(message); } return message; } /* * This method fetches all message information by the given message ID if * present * * @param messageID - messageID to fetch * * @return - An object of type Response with the status of the request */ /*@GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @XmlElementWrapper(name = "message") public Message loadUser(@PathParam("messageID") Long messageID) { Log.enter(); Message message = null; try { //MessagePO msgPO = DAOFactory.getInstance().getMessageDAO().loadExistingMessage(messageID); MessagePO msgPO = new MessagePO(); msgPO.setContent("blah!"); msgPO.setLocation("somewhere"); message = ConverterUtils.convert(msgPO); } catch (Exception e) { handleException(e); } finally { Log.exit(message); } return message; } */ /** * This method fetches all message information by the given message ID if present * * @param messageID * - messageID to fetch * @return - An object of type Response with the status of the request */ @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @XmlElementWrapper(name = "message") public Message loadMessage(@PathParam("messageID") long messageID) { Log.enter(); Message message = null; try { IMessageDAO dao = DAOFactory.getInstance().getMessageDAO(); Log.enter(messageID); MessagePO msgPO = dao.loadMessageById(messageID); message = ConverterUtils.convert(msgPO); } catch (Exception e) { handleException(e); } finally { Log.exit(message); } return message; } }
package edu.harvard.iq.dataverse.api; import edu.harvard.iq.dataverse.DataFile; import edu.harvard.iq.dataverse.Dataset; import edu.harvard.iq.dataverse.DatasetFieldType; import edu.harvard.iq.dataverse.DatasetVersion; import edu.harvard.iq.dataverse.Dataverse; import edu.harvard.iq.dataverse.DataverseFacet; import edu.harvard.iq.dataverse.DataverseContact; import edu.harvard.iq.dataverse.authorization.DataverseRole; import edu.harvard.iq.dataverse.DvObject; import edu.harvard.iq.dataverse.MetadataBlock; import edu.harvard.iq.dataverse.RoleAssignment; import edu.harvard.iq.dataverse.api.dto.ExplicitGroupDTO; import edu.harvard.iq.dataverse.api.dto.RoleAssignmentDTO; import edu.harvard.iq.dataverse.api.dto.RoleDTO; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.RoleAssignee; import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroup; import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroupProvider; import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroupServiceBean; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.authorization.users.User; import edu.harvard.iq.dataverse.engine.command.DataverseRequest; import edu.harvard.iq.dataverse.engine.command.impl.AddRoleAssigneesToExplicitGroupCommand; import edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetCommand; import edu.harvard.iq.dataverse.engine.command.impl.CreateDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.CreateExplicitGroupCommand; import edu.harvard.iq.dataverse.engine.command.impl.CreateRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.DeleteDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.DeleteExplicitGroupCommand; import edu.harvard.iq.dataverse.engine.command.impl.GetDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.GetExplicitGroupCommand; import edu.harvard.iq.dataverse.engine.command.impl.ListDataverseContentCommand; import edu.harvard.iq.dataverse.engine.command.impl.ListExplicitGroupsCommand; import edu.harvard.iq.dataverse.engine.command.impl.ListFacetsCommand; import edu.harvard.iq.dataverse.engine.command.impl.ListMetadataBlocksCommand; import edu.harvard.iq.dataverse.engine.command.impl.ListRoleAssignments; import edu.harvard.iq.dataverse.engine.command.impl.ListRolesCommand; import edu.harvard.iq.dataverse.engine.command.impl.PublishDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.RemoveRoleAssigneesFromExplicitGroupCommand; import edu.harvard.iq.dataverse.engine.command.impl.RevokeRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseMetadataBlocksCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateExplicitGroupCommand; import edu.harvard.iq.dataverse.util.json.JsonParseException; import static edu.harvard.iq.dataverse.util.json.JsonPrinter.brief; import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.ejb.Stateless; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonString; import javax.json.JsonValue; import javax.json.JsonValue.ValueType; import javax.json.stream.JsonParsingException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import static edu.harvard.iq.dataverse.util.json.JsonPrinter.json; import static edu.harvard.iq.dataverse.util.json.JsonPrinter.toJsonArray; /** * A REST API for dataverses. * @author michael */ @Stateless @Path("dataverses") public class Dataverses extends AbstractApiBean { private static final Logger LOGGER = Logger.getLogger(Dataverses.class.getName()); @EJB ExplicitGroupServiceBean explicitGroupSvc; @POST public Response addRoot( String body ) { LOGGER.info("Creating root dataverse"); return addDataverse( body, ""); } @POST @Path("{identifier}") public Response addDataverse( String body, @PathParam("identifier") String parentIdtf ) { Dataverse d; JsonObject dvJson; try ( StringReader rdr = new StringReader(body) ) { dvJson = Json.createReader(rdr).readObject(); d = jsonParser().parseDataverse(dvJson); } catch ( JsonParsingException jpe ) { LOGGER.log(Level.SEVERE, "Json: {0}", body); return error( Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage() ); } catch (JsonParseException ex) { Logger.getLogger(Dataverses.class.getName()).log(Level.SEVERE, "Error parsing dataverse from json: " + ex.getMessage(), ex); return error( Response.Status.BAD_REQUEST, "Error parsing the POSTed json into a dataverse: " + ex.getMessage() ); } try { if ( ! parentIdtf.isEmpty() ) { Dataverse owner = findDataverseOrDie( parentIdtf ); d.setOwner(owner); } // set the dataverse - contact relationship in the contacts for (DataverseContact dc : d.getDataverseContacts()) { dc.setDataverse(d); } AuthenticatedUser u = findAuthenticatedUserOrDie(); d = execCommand( new CreateDataverseCommand(d, createDataverseRequest(u), null, null) ); return created( "/dataverses/"+d.getAlias(), json(d) ); } catch ( WrappedResponse ww ) { Throwable cause = ww.getCause(); StringBuilder sb = new StringBuilder(); while (cause.getCause() != null) { cause = cause.getCause(); if (cause instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause; for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) { sb.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ") .append(violation.getPropertyPath()).append(" at ") .append(violation.getLeafBean()).append(" - ") .append(violation.getMessage()); } } } String error = sb.toString(); if (!error.isEmpty()) { LOGGER.log(Level.INFO, error); return ww.refineResponse(error); } return ww.getResponse(); } catch (EJBException ex) { Throwable cause = ex; StringBuilder sb = new StringBuilder(); sb.append("Error creating dataverse."); while (cause.getCause() != null) { cause = cause.getCause(); if (cause instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause; for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) { sb.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ") .append(violation.getPropertyPath()).append(" at ") .append(violation.getLeafBean()).append(" - ") .append(violation.getMessage()); } } } LOGGER.log(Level.SEVERE, sb.toString()); return error( Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + sb.toString() ); } catch ( Exception ex ) { LOGGER.log(Level.SEVERE, "Error creating dataverse", ex); return error( Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + ex.getMessage() ); } } @POST @Path("{identifier}/datasets") public Response createDataset( String jsonBody, @PathParam("identifier") String parentIdtf ) { try { User u = findUserOrDie(); Dataverse owner = findDataverseOrDie(parentIdtf); JsonObject json; try ( StringReader rdr = new StringReader(jsonBody) ) { json = Json.createReader(rdr).readObject(); } catch ( JsonParsingException jpe ) { LOGGER.log(Level.SEVERE, "Json: {0}", jsonBody); return error( Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage() ); } Dataset ds = new Dataset(); ds.setOwner(owner); JsonObject jsonVersion = json.getJsonObject("datasetVersion"); if ( jsonVersion == null) { return error(Status.BAD_REQUEST, "Json POST data are missing datasetVersion object."); } try { try { DatasetVersion version = new DatasetVersion(); version.setDataset(ds); // Use the two argument version so that the version knows which dataset it's associated with. version = jsonParser().parseDatasetVersion(jsonVersion, version); // force "initial version" properties version.setMinorVersionNumber(null); version.setVersionNumber(null); version.setVersionState(DatasetVersion.VersionState.DRAFT); LinkedList<DatasetVersion> versions = new LinkedList<>(); versions.add(version); version.setDataset(ds); ds.setVersions( versions ); } catch ( javax.ejb.TransactionRolledbackLocalException rbe ) { throw rbe.getCausedByException(); } } catch (JsonParseException ex) { LOGGER.log( Level.INFO, "Error parsing dataset version from Json", ex); return error(Status.BAD_REQUEST, "Error parsing datasetVersion: " + ex.getMessage() ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Error parsing dataset version from Json", e); return error(Status.INTERNAL_SERVER_ERROR, "Error parsing datasetVersion: " + e.getMessage() ); } Dataset managedDs = execCommand(new CreateDatasetCommand(ds, createDataverseRequest(u))); return created( "/datasets/" + managedDs.getId(), Json.createObjectBuilder().add("id", managedDs.getId()) ); } catch ( WrappedResponse ex ) { return ex.getResponse(); } } @GET @Path("{identifier}") public Response viewDataverse( @PathParam("identifier") String idtf ) { return allowCors(response( req -> ok(json(execCommand( new GetDataverseCommand(req, findDataverseOrDie(idtf))))))); } @DELETE @Path("{identifier}") public Response deleteDataverse( @PathParam("identifier") String idtf ) { return response( req -> { execCommand( new DeleteDataverseCommand(req, findDataverseOrDie(idtf))); return ok( "Dataverse " + idtf +" deleted"); }); } @GET @Path("{identifier}/metadatablocks") public Response listMetadataBlocks( @PathParam("identifier") String dvIdtf ) { try { JsonArrayBuilder arr = Json.createArrayBuilder(); final List<MetadataBlock> blocks = execCommand( new ListMetadataBlocksCommand(createDataverseRequest(findUserOrDie()), findDataverseOrDie(dvIdtf))); for ( MetadataBlock mdb : blocks) { arr.add( brief.json(mdb) ); } return allowCors(ok(arr)); } catch (WrappedResponse we ){ return we.getResponse(); } } @POST @Path("{identifier}/metadatablocks") @Produces(MediaType.APPLICATION_JSON) public Response setMetadataBlocks( @PathParam("identifier")String dvIdtf, String blockIds ) { List<MetadataBlock> blocks = new LinkedList<>(); try { for ( JsonValue blockId : Util.asJsonArray(blockIds).getValuesAs(JsonValue.class) ) { MetadataBlock blk = (blockId.getValueType()==ValueType.NUMBER) ? findMetadataBlock( ((JsonNumber)blockId).longValue() ) : findMetadataBlock( ((JsonString)blockId).getString() ); if ( blk == null ) { return error(Response.Status.BAD_REQUEST, "Can't find metadata block '"+ blockId + "'"); } blocks.add( blk ); } } catch( Exception e ) { return error(Response.Status.BAD_REQUEST, e.getMessage()); } try { execCommand( new UpdateDataverseMetadataBlocksCommand.SetBlocks(createDataverseRequest(findUserOrDie()), findDataverseOrDie(dvIdtf), blocks)); return ok("Metadata blocks of dataverse " + dvIdtf + " updated."); } catch (WrappedResponse ex) { return ex.getResponse(); } } @GET @Path("{identifier}/metadatablocks/:isRoot") public Response getMetadataRoot_legacy( @PathParam("identifier")String dvIdtf ) { return getMetadataRoot(dvIdtf); } @GET @Path("{identifier}/metadatablocks/isRoot") @Produces(MediaType.APPLICATION_JSON) public Response getMetadataRoot( @PathParam("identifier")String dvIdtf ) { return response( req -> { final Dataverse dataverse = findDataverseOrDie(dvIdtf); if ( permissionSvc.request(req) .on(dataverse) .has(Permission.EditDataverse) ) { return ok( dataverse.isMetadataBlockRoot() ); } else { return error( Status.FORBIDDEN, "Not authorized" ); } }); } @POST @Path("{identifier}/metadatablocks/:isRoot") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.WILDCARD) public Response setMetadataRoot_legacy( @PathParam("identifier")String dvIdtf, String body ) { return setMetadataRoot(dvIdtf, body); } @PUT @Path("{identifier}/metadatablocks/isRoot") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.WILDCARD) public Response setMetadataRoot( @PathParam("identifier")String dvIdtf, String body ) { return response( req -> { final boolean root = parseBooleanOrDie(body); final Dataverse dataverse = findDataverseOrDie(dvIdtf); execCommand(new UpdateDataverseMetadataBlocksCommand.SetRoot(req, dataverse, root)); return ok("Dataverse " + dataverse.getName() + " is now a metadata " + (root? "" : "non-") + "root"); }); } @GET @Path("{identifier}/facets/") /** * return list of facets for the dataverse with alias `dvIdtf` */ public Response listFacets( @PathParam("identifier") String dvIdtf ) { try { Dataverse dataverse = findDataverseOrDie(dvIdtf); JsonArrayBuilder fs = Json.createArrayBuilder(); for( DataverseFacet f : dataverse.getDataverseFacets() ) { fs.add( f.getDatasetFieldType().getName() ); } return allowCors( ok( fs ) ); } catch( WrappedResponse e ) { return e.getResponse(); } } @POST @Path("{identifier}/facets") @Produces(MediaType.APPLICATION_JSON) public Response setFacets( @PathParam("identifier")String dvIdtf, String facetIds ) { List<DatasetFieldType> facets = new LinkedList<>(); for ( JsonString facetId : Util.asJsonArray(facetIds).getValuesAs(JsonString.class) ) { DatasetFieldType dsfType = findDatasetFieldType(facetId.getString()); if ( dsfType == null ) { return error(Response.Status.BAD_REQUEST, "Can't find dataset field type '"+ facetId + "'"); } else if (!dsfType.isFacetable()) { return error(Response.Status.BAD_REQUEST, "Dataset field type '"+ facetId + "' is not facetable"); } facets.add( dsfType ); } try { Dataverse dataverse = findDataverseOrDie(dvIdtf); // by passing null for Featured Dataverses and DataverseFieldTypeInputLevel, those are not changed execCommand( new UpdateDataverseCommand(dataverse, facets, null, createDataverseRequest(findUserOrDie()), null) ); return ok("Facets of dataverse " + dvIdtf + " updated."); } catch (WrappedResponse ex) { return ex.getResponse(); } } @GET @Path("{identifier}/contents") public Response listContent( @PathParam("identifier") String dvIdtf ) { DvObject.Visitor<JsonObjectBuilder> ser = new DvObject.Visitor<JsonObjectBuilder>() { @Override public JsonObjectBuilder visit(Dataverse dv) { return Json.createObjectBuilder().add("type", "dataverse") .add("id", dv.getId()) .add("title",dv.getName() ); } @Override public JsonObjectBuilder visit(Dataset ds) { return json(ds).add("type", "dataset"); } @Override public JsonObjectBuilder visit(DataFile df) { throw new UnsupportedOperationException("Files don't live directly in Dataverses"); } }; return allowCors(response( req -> ok( execCommand(new ListDataverseContentCommand(req, findDataverseOrDie(dvIdtf))) .stream() .map( dvo->(JsonObjectBuilder)dvo.accept(ser)) .collect(toJsonArray())) )); } @GET @Path("{identifier}/roles") public Response listRoles( @PathParam("identifier") String dvIdtf ) { return response( req -> ok( execCommand( new ListRolesCommand(req, findDataverseOrDie(dvIdtf)) ) .stream().map(r->json(r)) .collect( toJsonArray() ) )); } @POST @Path("{identifier}/roles") public Response createRole( RoleDTO roleDto, @PathParam("identifier") String dvIdtf ) { return response( req -> ok( json(execCommand(new CreateRoleCommand(roleDto.asRole(), req, findDataverseOrDie(dvIdtf)))))); } @GET @Path("{identifier}/assignments") public Response listAssignments( @PathParam("identifier") String dvIdtf) { return response( req -> ok( execCommand(new ListRoleAssignments(req, findDataverseOrDie(dvIdtf))) .stream() .map( a -> json(a) ) .collect(toJsonArray()) )); } @POST @Path("{identifier}/assignments") public Response createAssignment( RoleAssignmentDTO ra, @PathParam("identifier") String dvIdtf, @QueryParam("key") String apiKey ) { try { final DataverseRequest req = createDataverseRequest(findUserOrDie()); final Dataverse dataverse = findDataverseOrDie(dvIdtf); RoleAssignee assignee = findAssignee(ra.getAssignee()); if ( assignee==null ) { return error( Status.BAD_REQUEST, "Assignee not found" ); } DataverseRole theRole; Dataverse dv = dataverse; theRole = null; while ( (theRole==null) && (dv!=null) ) { for ( DataverseRole aRole : rolesSvc.availableRoles(dv.getId()) ) { if ( aRole.getAlias().equals(ra.getRole()) ) { theRole = aRole; break; } } dv = dv.getOwner(); } if ( theRole == null ) { return error( Status.BAD_REQUEST, "Can't find role named '" + ra.getRole() + "' in dataverse " + dataverse); } String privateUrlToken = null; return ok(json(execCommand(new AssignRoleCommand(assignee, theRole, dataverse, req, privateUrlToken)))); } catch (WrappedResponse ex) { LOGGER.log(Level.WARNING, "Can''t create assignment: {0}", ex.getMessage()); return ex.getResponse(); } } @DELETE @Path("{identifier}/assignments/{id}") public Response deleteAssignment( @PathParam("id") long assignmentId, @PathParam("identifier") String dvIdtf ) { RoleAssignment ra = em.find( RoleAssignment.class, assignmentId ); if ( ra != null ) { try { findDataverseOrDie(dvIdtf); execCommand( new RevokeRoleCommand(ra, createDataverseRequest(findUserOrDie()))); return ok("Role " + ra.getRole().getName() + " revoked for assignee " + ra.getAssigneeIdentifier() + " in " + ra.getDefinitionPoint().accept(DvObject.NamePrinter) ); } catch (WrappedResponse ex) { return ex.getResponse(); } } else { return error( Status.NOT_FOUND, "Role assignment " + assignmentId + " not found" ); } } @POST @Path("{identifier}/actions/:publish") public Response publishDataverse( @PathParam("identifier") String dvIdtf ) { try { Dataverse dv = findDataverseOrDie(dvIdtf); return ok( json(execCommand( new PublishDataverseCommand(createDataverseRequest(findAuthenticatedUserOrDie()), dv))) ); } catch (WrappedResponse wr) { return wr.getResponse(); } } @POST @Path("{identifier}/groups/") public Response createExplicitGroup( ExplicitGroupDTO dto, @PathParam("identifier") String dvIdtf) { return response( req ->{ ExplicitGroupProvider prv = explicitGroupSvc.getProvider(); ExplicitGroup newGroup = dto.apply(prv.makeGroup()); newGroup = execCommand( new CreateExplicitGroupCommand(req, findDataverseOrDie(dvIdtf), newGroup)); String groupUri = String.format("%s/groups/%s", dvIdtf, newGroup.getGroupAliasInOwner()); return created( groupUri, json(newGroup) ); }); } @GET @Path("{identifier}/groups/") public Response listGroups( @PathParam("identifier") String dvIdtf, @QueryParam("key") String apiKey ) { return response( req -> ok( execCommand(new ListExplicitGroupsCommand(req, findDataverseOrDie(dvIdtf))) .stream().map( eg->json(eg)) .collect( toJsonArray() ) )); } @GET @Path("{identifier}/groups/{aliasInOwner}") public Response getGroupByOwnerAndAliasInOwner( @PathParam("identifier") String dvIdtf, @PathParam("aliasInOwner") String grpAliasInOwner ){ return response( req -> ok(json(findExplicitGroupOrDie(findDataverseOrDie(dvIdtf), req, grpAliasInOwner)))); } @PUT @Path("{identifier}/groups/{aliasInOwner}") public Response updateGroup(ExplicitGroupDTO groupDto, @PathParam("identifier") String dvIdtf, @PathParam("aliasInOwner") String grpAliasInOwner ) { return response( req-> ok(json(execCommand( new UpdateExplicitGroupCommand(req, groupDto.apply( findExplicitGroupOrDie(findDataverseOrDie(dvIdtf), req, grpAliasInOwner))))))); } @DELETE @Path("{identifier}/groups/{aliasInOwner}") public Response deleteGroup(@PathParam("identifier") String dvIdtf, @PathParam("aliasInOwner") String grpAliasInOwner ) { return response( req -> { execCommand( new DeleteExplicitGroupCommand(req, findExplicitGroupOrDie(findDataverseOrDie(dvIdtf), req, grpAliasInOwner)) ); return ok( "Group " + dvIdtf + "/" + grpAliasInOwner + " deleted" ); }); } @POST @Path("{identifier}/groups/{aliasInOwner}/roleAssignees") @Consumes("application/json") public Response addRoleAssingees(List<String> roleAssingeeIdentifiers, @PathParam("identifier") String dvIdtf, @PathParam("aliasInOwner") String grpAliasInOwner) { return response( req -> ok( json( execCommand( new AddRoleAssigneesToExplicitGroupCommand(req, findExplicitGroupOrDie(findDataverseOrDie(dvIdtf), req, grpAliasInOwner), new TreeSet<>(roleAssingeeIdentifiers)))))); } @PUT @Path("{identifier}/groups/{aliasInOwner}/roleAssignees/{roleAssigneeIdentifier: .*}") public Response addRoleAssingee( @PathParam("identifier") String dvIdtf, @PathParam("aliasInOwner") String grpAliasInOwner, @PathParam("roleAssigneeIdentifier") String roleAssigneeIdentifier) { return addRoleAssingees(Collections.singletonList(roleAssigneeIdentifier), dvIdtf, grpAliasInOwner); } @DELETE @Path("{identifier}/groups/{aliasInOwner}/roleAssignees/{roleAssigneeIdentifier: .*}") public Response deleteRoleAssingee( @PathParam("identifier") String dvIdtf, @PathParam("aliasInOwner") String grpAliasInOwner, @PathParam("roleAssigneeIdentifier") String roleAssigneeIdentifier ) { return response( req ->ok(json(execCommand( new RemoveRoleAssigneesFromExplicitGroupCommand(req, findExplicitGroupOrDie(findDataverseOrDie(dvIdtf), req, grpAliasInOwner), Collections.singleton(roleAssigneeIdentifier)))))); } private ExplicitGroup findExplicitGroupOrDie( DvObject dv, DataverseRequest req, String groupIdtf ) throws WrappedResponse { ExplicitGroup eg = execCommand(new GetExplicitGroupCommand(req, dv, groupIdtf) ); if ( eg == null ) throw new WrappedResponse( notFound("Can't find " + groupIdtf + " in dataverse " + dv.getId())); return eg; } @GET @Path("{identifier}/links") public Response listLinks(@PathParam("identifier") String dvIdtf ) { try { User u = findUserOrDie(); Dataverse dv = findDataverseOrDie(dvIdtf); if (!u.isSuperuser()) { return error(Status.FORBIDDEN, "Not a superuser"); } List<Dataverse> dvsThisDvHasLinkedToList = dataverseSvc.findDataversesThisIdHasLinkedTo(dv.getId()); JsonArrayBuilder dvsThisDvHasLinkedToBuilder = Json.createArrayBuilder(); for (Dataverse dataverse : dvsThisDvHasLinkedToList) { dvsThisDvHasLinkedToBuilder.add(dataverse.getAlias()); } List<Dataverse> dvsThatLinkToThisDvList = dataverseSvc.findDataversesThatLinkToThisDvId(dv.getId()); JsonArrayBuilder dvsThatLinkToThisDvBuilder = Json.createArrayBuilder(); for (Dataverse dataverse : dvsThatLinkToThisDvList) { dvsThatLinkToThisDvBuilder.add(dataverse.getAlias()); } List<Dataset> datasetsThisDvHasLinkedToList = dataverseSvc.findDatasetsThisIdHasLinkedTo(dv.getId()); JsonArrayBuilder datasetsThisDvHasLinkedToBuilder = Json.createArrayBuilder(); for (Dataset dataset : datasetsThisDvHasLinkedToList) { datasetsThisDvHasLinkedToBuilder.add(dataset.getLatestVersion().getTitle()); } JsonObjectBuilder response = Json.createObjectBuilder(); response.add("dataverses that the " + dv.getAlias() + " dataverse has linked to", dvsThisDvHasLinkedToBuilder); response.add("dataverses that link to the " + dv.getAlias(), dvsThatLinkToThisDvBuilder); response.add("datasets that the " + dv.getAlias() + " has linked to", datasetsThisDvHasLinkedToBuilder); return ok(response); } catch (WrappedResponse wr) { return wr.getResponse(); } } }
package edu.hm.hafner.analysis; import java.util.Optional; import java.util.regex.Matcher; import edu.hm.hafner.util.LookaheadStream; /** * Parses a report file line by line for issues using a pre-defined regular expression. If the regular expression * matches then the abstract method {@link #createIssue(Matcher, IssueBuilder)} will be called. Sub classes need to * provide an implementation that transforms the {@link Matcher} instance into a new issue. This class basically * simplifies the parent class {@link LookaheadParser} so that sub classes are not allowed to consume additional lines * of the report anymore. * * @author Ullrich Hafner */ public abstract class RegexpLineParser extends LookaheadParser { private static final long serialVersionUID = 434000822024807289L; private static final int MAX_LINE_LENGTH = 4000; // see JENKINS-55805 /** * Creates a new instance of {@link RegexpLineParser}. * * @param pattern * pattern of compiler warnings */ protected RegexpLineParser(final String pattern) { super(pattern); } @Override protected boolean isLineInteresting(final String line) { return line.length() < MAX_LINE_LENGTH; // skip long lines, see JENKINS-55805 } @Override protected final Optional<Issue> createIssue(final Matcher matcher, final LookaheadStream lookahead, final IssueBuilder builder) throws ParsingException { return createIssue(matcher, builder); } /** * Creates a new issue for the specified pattern. This method is called for each matching line in the specified * file. If a match is a false positive, then return {@link Optional#empty()} to ignore this warning. * * @param matcher * the regular expression matcher * @param builder * the issue builder to use * * @return a new annotation for the specified pattern * @throws ParsingException * Signals that during parsing a non recoverable error has been occurred */ protected abstract Optional<Issue> createIssue(Matcher matcher, IssueBuilder builder); }
package edu.neu.ccs.pyramid.dataset; import edu.neu.ccs.pyramid.feature.FeatureMappers; import edu.neu.ccs.pyramid.util.Sampling; import org.apache.mahout.math.Vector; import java.io.*; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; public class DataSetUtil { /** * * @param dataSet * @param numClasses for new dataset * @return */ public static ClfDataSet changeLabels(ClfDataSet dataSet, int numClasses){ ClfDataSet dataSet1; int numDataPoints = dataSet.getNumDataPoints(); int numFeatures = dataSet.getNumFeatures(); if (dataSet.isDense()){ dataSet1 = new DenseClfDataSet(numDataPoints,numFeatures,numClasses); } else { dataSet1 = new SparseClfDataSet(numDataPoints,numFeatures,numClasses); } for (int i=0;i<numDataPoints;i++){ FeatureRow featureRow = dataSet.getFeatureRow(i); //only copy non-zero elements Vector vector = featureRow.getVector(); for (Vector.Element element: vector.nonZeroes()){ int featureIndex = element.index(); double value = element.get(); if (featureIndex<numFeatures){ dataSet1.setFeatureValue(i,featureIndex,value); } } } for (int i=0;i<numDataPoints;i++){ DataSetting dataSetting = dataSet.getFeatureRow(i).getSetting().copy(); dataSetting.setExtLabel("unknown"); dataSet1.getFeatureRow(i).putSetting(dataSetting); } for (int j=0;j<numFeatures;j++){ FeatureSetting featureSetting = dataSet.getFeatureColumn(j).getSetting().copy(); dataSet1.getFeatureColumn(j).putSetting(featureSetting); } return dataSet1; } /** * only keep the selected features * @param clfDataSet * @return */ public static ClfDataSet trim(ClfDataSet clfDataSet, List<Integer> columnsToKeep){ ClfDataSet trimmed ; int numClasses = clfDataSet.getNumClasses(); // keep density if (clfDataSet.isDense()) { trimmed = new DenseClfDataSet(clfDataSet.getNumDataPoints(), columnsToKeep.size(), numClasses); } else{ trimmed = new SparseClfDataSet(clfDataSet.getNumDataPoints(),columnsToKeep.size(), numClasses); } for (int j=0;j<trimmed.getNumFeatures();j++){ int oldColumnIndex = columnsToKeep.get(j); FeatureColumn featureColumn = clfDataSet.getFeatureColumn(oldColumnIndex); Vector vector = featureColumn.getVector(); for (Vector.Element element: vector.nonZeroes()){ int dataPointIndex = element.index(); double value = element.get(); trimmed.setFeatureValue(dataPointIndex,j,value); } } //copy labels int[] labels = clfDataSet.getLabels(); for (int i=0;i<trimmed.getNumDataPoints();i++){ trimmed.setLabel(i,labels[i]); } //just copy settings for (int i=0;i<trimmed.getNumDataPoints();i++){ trimmed.getFeatureRow(i).putSetting(clfDataSet.getFeatureRow(i).getSetting().copy()); } for (int j=0;j<trimmed.getNumFeatures();j++){ int oldColumnIndex = columnsToKeep.get(j); trimmed.getFeatureColumn(j).putSetting(clfDataSet.getFeatureColumn(oldColumnIndex).getSetting().copy()); } //todo double-check //todo: something like featuremappers DataSetSetting dataSetSetting = clfDataSet.getSetting().copy(); dataSetSetting.setFeatureMappers(null); trimmed.putSetting(dataSetSetting); return trimmed; } /** * only keep the selected features * @param dataSet * @return */ public static MultiLabelClfDataSet trim(MultiLabelClfDataSet dataSet, List<Integer> columnsToKeep){ MultiLabelClfDataSet trimmed ; int numClasses = dataSet.getNumClasses(); // keep density if (dataSet.isDense()) { trimmed = new DenseMLClfDataSet(dataSet.getNumDataPoints(), columnsToKeep.size(), numClasses); } else{ trimmed = new SparseMLClfDataSet(dataSet.getNumDataPoints(),columnsToKeep.size(), numClasses); } for (int j=0;j<trimmed.getNumFeatures();j++){ int oldColumnIndex = columnsToKeep.get(j); FeatureColumn featureColumn = dataSet.getFeatureColumn(oldColumnIndex); Vector vector = featureColumn.getVector(); for (Vector.Element element: vector.nonZeroes()){ int dataPointIndex = element.index(); double value = element.get(); trimmed.setFeatureValue(dataPointIndex,j,value); } } //copy labels MultiLabel[] multiLabels = dataSet.getMultiLabels(); for (int i=0;i<trimmed.getNumDataPoints();i++){ trimmed.addLabels(i,multiLabels[i].getMatchedLabels()); } //just copy settings for (int i=0;i<trimmed.getNumDataPoints();i++){ trimmed.getFeatureRow(i).putSetting(dataSet.getFeatureRow(i).getSetting().copy()); } for (int j=0;j<trimmed.getNumFeatures();j++){ int oldColumnIndex = columnsToKeep.get(j); trimmed.getFeatureColumn(j).putSetting(dataSet.getFeatureColumn(oldColumnIndex).getSetting().copy()); } //todo double-check //todo: something like featuremappers DataSetSetting dataSetSetting = dataSet.getSetting().copy(); dataSetSetting.setFeatureMappers(null); trimmed.putSetting(dataSetSetting); return trimmed; } /** * //todo change implementation * only keep the first numFeatures features * @param clfDataSet * @param numFeatures * @return */ public static ClfDataSet trim(ClfDataSet clfDataSet, int numFeatures){ if (numFeatures> clfDataSet.getNumFeatures()){ throw new IllegalArgumentException("numFeatures > clfDataSet.getNumFeatures()"); } ClfDataSet trimmed ; int numClasses = clfDataSet.getNumClasses(); // keep density if (clfDataSet.isDense()) { trimmed = new DenseClfDataSet(clfDataSet.getNumDataPoints(), numFeatures, numClasses); } else{ trimmed = new SparseClfDataSet(clfDataSet.getNumDataPoints(),numFeatures, numClasses); } for (int i=0;i<trimmed.getNumDataPoints();i++){ FeatureRow featureRow = clfDataSet.getFeatureRow(i); //only copy non-zero elements Vector vector = featureRow.getVector(); for (Vector.Element element: vector.nonZeroes()){ int featureIndex = element.index(); double value = element.get(); if (featureIndex<numFeatures){ trimmed.setFeatureValue(i,featureIndex,value); } } } //copy labels int[] labels = clfDataSet.getLabels(); for (int i=0;i<trimmed.getNumDataPoints();i++){ trimmed.setLabel(i,labels[i]); } //just copy settings for (int i=0;i<trimmed.getNumDataPoints();i++){ trimmed.getFeatureRow(i).putSetting(clfDataSet.getFeatureRow(i).getSetting().copy()); } for (int j=0;j<numFeatures;j++){ trimmed.getFeatureColumn(j).putSetting(clfDataSet.getFeatureColumn(j).getSetting().copy()); } //todo double-check //todo: something like featuremappers trimmed.putSetting(clfDataSet.getSetting()); return trimmed; } /** * * @param inputFile * @param outputFile * @param start inclusive, first column is 0 * @param end inclusive */ public static void extractColumns(String inputFile, String outputFile, int start, int end, String delimiter) throws IOException{ try(BufferedReader br = new BufferedReader(new FileReader(new File(inputFile))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outputFile))) ){ String line; while((line = br.readLine())!=null){ String[] split = line.split(Pattern.quote(delimiter)); System.out.println(Arrays.toString(split)); System.out.println(split.length); for (int i=start;i<=end;i++){ System.out.println(i); bw.write(split[i]); if (i<end){ bw.write(delimiter); } } bw.newLine(); } } } public static void extractColumns(String inputFile, String outputFile, int start, int end, Pattern pattern) throws IOException{ try(BufferedReader br = new BufferedReader(new FileReader(new File(inputFile))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outputFile))) ){ String line; while((line = br.readLine())!=null){ //remove leading spaces String[] split = line.trim().split(pattern.pattern()); for (int i=start;i<=end;i++){ bw.write(split[i]); if (i<end){ bw.write(","); } } bw.newLine(); } } } public static void setLabelTranslator(ClfDataSet dataSet, LabelTranslator labelTranslator){ int[] labels = dataSet.getLabels(); for (int i=0;i<dataSet.getNumDataPoints();i++){ dataSet.getFeatureRow(i).getSetting() .setExtLabel(labelTranslator.toExtLabel(labels[i])); } dataSet.getSetting().setLabelTranslator(labelTranslator); } // /** // * // * @param dataSet // * @param extLabels in order // */ // public static void setLabelTranslator(ClfDataSet dataSet, List<String> extLabels){ // int[] labels = dataSet.getLabels(); // for (int i=0;i<dataSet.getNumDataPoints();i++){ // dataSet.getFeatureRow(i).getSetting() // .setExtLabel(extLabels.get(labels[i])); // dataSet.getSetting().setLabelTranslator(new LabelTranslator(extLabels)); // /** // * // * @param dataSet // * @param extLabels in order // */ // public static void setLabelTranslator(ClfDataSet dataSet, String[] extLabels){ // int[] labels = dataSet.getLabels(); // for (int i=0;i<dataSet.getNumDataPoints();i++){ // dataSet.getFeatureRow(i).getSetting() // .setExtLabel(extLabels[labels[i]]); // dataSet.getSetting().setLabelTranslator(new LabelTranslator(extLabels)); // public static void setLabelTranslator(ClfDataSet dataSet, Map<Integer, String> intToExtLabel){ // int[] labels = dataSet.getLabels(); // for (int i=0;i<dataSet.getNumDataPoints();i++){ // dataSet.getFeatureRow(i).getSetting() // .setExtLabel(intToExtLabel.get(labels[i])); // dataSet.getSetting().setLabelTranslator(new LabelTranslator(intToExtLabel)); public static void setLabelTranslator(MultiLabelClfDataSet dataSet, LabelTranslator labelTranslator){ MultiLabel[] multiLabels= dataSet.getMultiLabels(); for (int i=0;i<dataSet.getNumDataPoints();i++){ MultiLabel multiLabel = multiLabels[i]; List<String> extLabels = multiLabel.getMatchedLabels().stream() .map(labelTranslator::toExtLabel) .collect(Collectors.toList()); dataSet.getFeatureRow(i).getSetting() .setExtLabels(extLabels); } dataSet.getSetting().setLabelTranslator(labelTranslator); } // public static void setLabelTranslator(MultiLabelClfDataSet dataSet, Map<Integer, String> intToExtLabel){ // MultiLabel[] multiLabels= dataSet.getMultiLabels(); // for (int i=0;i<dataSet.getNumDataPoints();i++){ // MultiLabel multiLabel = multiLabels[i]; // List<String> extLabels = multiLabel.getMatchedLabels().stream() // .map(intToExtLabel::get) // .collect(Collectors.toList()); // dataSet.getFeatureRow(i).getSetting() // .setExtLabels(extLabels); // dataSet.getSetting().setLabelTranslator(new LabelTranslator(intToExtLabel)); // public static void setLabelTranslator(MultiLabelClfDataSet dataSet, String[] extLabels){ // MultiLabel[] multiLabels= dataSet.getMultiLabels(); // for (int i=0;i<dataSet.getNumDataPoints();i++){ // MultiLabel multiLabel = multiLabels[i]; // List<String> matchedExtLabels = multiLabel.getMatchedLabels().stream() // .map(label -> extLabels[label]) // .collect(Collectors.toList()); // dataSet.getFeatureRow(i).getSetting() // .setExtLabels(matchedExtLabels); // dataSet.getSetting().setLabelTranslator(new LabelTranslator(extLabels)); public static void setFeatureNames(DataSet dataSet, List<String> featureNames){ if (featureNames.size()!=dataSet.getNumFeatures()){ throw new IllegalArgumentException("featureNames.size()!=dataSet.getNumFeatures()"); } for (int j=0;j<dataSet.getNumFeatures();j++){ dataSet.getFeatureColumn(j).getSetting().setFeatureName(featureNames.get(j)); } } public static void setFeatureNames(DataSet dataSet, String[] featureNames){ List<String> list = Arrays.stream(featureNames).collect(Collectors.toList()); setFeatureNames(dataSet,list); } /** * should use after featureMappers are finalized * @param dataSet * @param featureMappers */ public static void setFeatureMappers(DataSet dataSet, FeatureMappers featureMappers){ if (dataSet.getNumFeatures()!=featureMappers.getTotalDim()){ throw new IllegalArgumentException("dataSet.getNumFeatures()!=featureMappers.getTotalDim()"); } dataSet.getSetting().setFeatureMappers(featureMappers); setFeatureNames(dataSet,featureMappers.getAllNames()); } /** * keep both local intId->extIds and global extId <-> intId translations * may fail because the intIds in idTranslator may not correspond to [0,numDataPoints) * @param dataSet * @param idTranslator */ public static void setIdTranslator(DataSet dataSet, IdTranslator idTranslator){ for (int i=0;i<dataSet.getNumDataPoints();i++){ dataSet.getFeatureRow(i).getSetting().setExtId(idTranslator.toExtId(i)); } dataSet.getSetting().setIdTranslator(idTranslator); } /** * stratified bootstrap sample * each class has the same number of data points as in the original data set * @param clfDataSet * @return */ public static ClfDataSet bootstrap(ClfDataSet clfDataSet){ Map<Integer, List<Integer>> labelIndicesMap = new HashMap<>(); int[] labels = clfDataSet.getLabels(); for (int i=0;i<clfDataSet.getNumDataPoints();i++){ int label = labels[i]; if (!labelIndicesMap.containsKey(label)){ labelIndicesMap.put(label, new ArrayList<>()); } labelIndicesMap.get(label).add(i); } List<Integer> sampledIndices = new ArrayList<>(clfDataSet.getNumDataPoints()); //sample for each class for (Map.Entry<Integer,List<Integer>> entry: labelIndicesMap.entrySet()) { List<Integer> indices = entry.getValue(); int[] sampleForClass = Sampling.sampleWithReplacement(indices.size(), indices).toArray(); for (int index: sampleForClass){ sampledIndices.add(index); } } return subSet(clfDataSet,sampledIndices); } /** * create a subset with the indices * it's fine to have duplicate indices * idTranslator is not saved in subSet as we may have duplicate extIds * @param clfDataSet * @param indices * @return */ public static ClfDataSet subSet(ClfDataSet clfDataSet, List<Integer> indices){ ClfDataSet sample; int numClasses = clfDataSet.getNumClasses(); if (clfDataSet instanceof DenseClfDataSet){ sample = new DenseClfDataSet(indices.size(),clfDataSet.getNumFeatures(), numClasses); } else { sample = new SparseClfDataSet(indices.size(),clfDataSet.getNumFeatures(), numClasses); } int[] labels = clfDataSet.getLabels(); for (int i=0;i<indices.size();i++){ int indexInOld = indices.get(i); FeatureRow oldFeatureRow = clfDataSet.getFeatureRow(indexInOld); int label = labels[indexInOld]; //copy label sample.setLabel(i,label); //copy row feature values, optimized for sparse vector for (Vector.Element element: oldFeatureRow.getVector().nonZeroes()){ sample.setFeatureValue(i,element.index(),element.get()); } //copy data settings sample.getFeatureRow(i).putSetting(oldFeatureRow.getSetting()); } //copy feature settings for (int j=0;j<clfDataSet.getNumFeatures();j++){ sample.getFeatureColumn(j) .putSetting(clfDataSet.getFeatureColumn(j).getSetting()); } //safe to copy label map DataSetUtil.setLabelTranslator(sample, clfDataSet.getSetting().getLabelTranslator()); //safe to copy feature mappers DataSetUtil.setFeatureMappers(sample,clfDataSet.getSetting().getFeatureMappers()); //ignore idTranslator as we may have duplicate extIds return sample; } public static void dumpDataSettings(ClfDataSet dataSet, String file) throws IOException{ dumpDataSettings(dataSet,new File(file)); } /** * dump data settings to a plain text file * @param dataSet * @param file * @throws IOException */ public static void dumpDataSettings(ClfDataSet dataSet, File file) throws IOException { int numDataPoints = dataSet.getNumDataPoints(); int[] labels = dataSet.getLabels(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(file)) ) { for (int i = 0; i < numDataPoints; i++) { FeatureRow featureRow = dataSet.getFeatureRow(i); DataSetting dataSetting = featureRow.getSetting(); bw.write("intId="); bw.write("" + i); bw.write(","); bw.write("extId="); bw.write(dataSetting.getExtId()); bw.write(","); bw.write("intLabel="); bw.write("" + labels[i]); bw.write(","); bw.write("extLabel="); bw.write(dataSetting.getExtLabel()); bw.newLine(); } } } /** * dump feature settings to plain text file * @param dataSet * @param file * @throws IOException */ public static void dumpFeatureSettings(ClfDataSet dataSet, String file) throws IOException { dumpFeatureSettings(dataSet,new File(file)); } public static void dumpFeatureSettings(ClfDataSet dataSet, File file) throws IOException { int numFeatures = dataSet.getNumFeatures(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(file)) ) { for (int j=0;j<numFeatures;j++){ FeatureSetting featureSetting = dataSet.getFeatureColumn(j).getSetting(); bw.write("featureIndex="); bw.write(""+j); bw.write(","); bw.write("featureType="); if (featureSetting.getFeatureType()==FeatureType.NUMERICAL){ bw.write("numerical"); } else { bw.write("binary"); } bw.write(","); bw.write("featureName="); bw.write(featureSetting.getFeatureName()); bw.newLine(); } } } public static List<MultiLabel> gatherLabels(MultiLabelClfDataSet dataSet){ Set<MultiLabel> multiLabels = new HashSet<>(); MultiLabel[] multiLabelsArray = dataSet.getMultiLabels(); for (MultiLabel multiLabel: multiLabelsArray){ multiLabels.add(multiLabel); } return multiLabels.stream().collect(Collectors.toList()); } /** * merge to binary dataset * k=positive (1), others = negative(0) * @param dataSet * @param k * @return */ public static ClfDataSet toBinary(MultiLabelClfDataSet dataSet, int k){ int numDataPoints = dataSet.getNumDataPoints(); int numFeatures = dataSet.getNumFeatures(); ClfDataSet clfDataSet; if (dataSet.isDense()){ clfDataSet = new DenseClfDataSet(numDataPoints,numFeatures,2); } else { clfDataSet = new SparseClfDataSet(numDataPoints,numFeatures,2); } for (int i=0;i<numDataPoints;i++){ FeatureRow featureRow = dataSet.getFeatureRow(i); //only copy non-zero elements Vector vector = featureRow.getVector(); for (Vector.Element element: vector.nonZeroes()){ int featureIndex = element.index(); double value = element.get(); clfDataSet.setFeatureValue(i,featureIndex,value); } if (dataSet.getMultiLabels()[i].matchClass(k)){ clfDataSet.setLabel(i,1); } else { clfDataSet.setLabel(i,0); } } for (int i=0;i<numDataPoints;i++){ DataSetting dataSetting = dataSet.getFeatureRow(i).getSetting().copy(); LabelTranslator labelTranslator = dataSet.getSetting().getLabelTranslator(); int label = clfDataSet.getLabels()[i]; if (labelTranslator!=null){ if (label ==1){ dataSetting.setExtLabel(labelTranslator.toExtLabel(k)); } else { dataSetting.setExtLabel("NOT "+labelTranslator.toExtLabel(k)); } } else { dataSetting.setExtLabel("unknown"); } clfDataSet.getFeatureRow(i).putSetting(dataSetting); } for (int j=0;j<numFeatures;j++){ FeatureSetting featureSetting = dataSet.getFeatureColumn(j).getSetting().copy(); clfDataSet.getFeatureColumn(j).putSetting(featureSetting); } return clfDataSet; } }
package es.ucm.fdi.iw.controller; import java.security.Principal; import java.util.List; import java.util.ArrayList; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.NoResultException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import es.ucm.fdi.iw.model.Language; import es.ucm.fdi.iw.model.Message; import es.ucm.fdi.iw.model.Offer; import es.ucm.fdi.iw.model.Proyect; import es.ucm.fdi.iw.model.Tag; import es.ucm.fdi.iw.model.User; @Controller public class RootController { private static Logger log = Logger.getLogger(RootController.class); @Autowired private EntityManager entityManager; @ModelAttribute public void addAttributes(Model model) { model.addAttribute("s", "/static/"); } @GetMapping({"/", "/welcome"}) public String root(Model model,Principal principal) { //principal es NULL //log.info(principal.getName() + " de tipo " + principal.getClass()); // org.springframework.security.core.userdetails.User model.addAttribute("pageTitle", "¡Bienvenido a CVKARD!"); return "index"; } /** * Home - vista de entrada al loguear */ @GetMapping("/home") public String home(HttpSession session, Principal principal) { if (principal != null && principal.getName() != null && session.getAttribute("user")== null) { try { User u = entityManager.createQuery("from User where email = :email", User.class) .setParameter("email", principal.getName()) .getSingleResult(); session.setAttribute("user", u); List b = new ArrayList<User>(); b = entityManager.createQuery("select b from User b where roles = :roles") .setParameter("roles", "USER,BUSSINES").getResultList(); log.info("Coge bien la lista" + b.size()); session.setAttribute("bussines", b); } catch (Exception e) { // TODO: handle exception System.err.println(e); } } List<Offer> o = new ArrayList<Offer>(); o = entityManager.createQuery("select o from Offer o ORDER BY o.date") .setMaxResults(4) .getResultList(); List<User> b = new ArrayList<User>(); b = entityManager.createQuery("select b from User b where roles = :roles") .setParameter("roles", "USER,BUSSINES").getResultList(); log.info("Coge bien la lista" + b.size()); session.setAttribute("offerList", o); session.setAttribute("bussines", b); return "home"; } /** * curriculum - Vista de portfolio del usuario "Empleado" */ @GetMapping("/curriculum/{nick}") public String curriculum(@PathVariable("nick") String nick,HttpSession session, Model model) { String url = "index"; log.info("Buscando usuario con nick: '"+nick+"'\n"); try { if(session.getAttribute("user")==null){ User u = entityManager.createQuery("from User where nick = :nick", User.class) .setParameter("nick", nick) .getSingleResult(); model.addAttribute("user", u); } url = "curriculum"; } catch (Exception e) { // TODO: handle exception log.error(e); } return url; } /** ???????????????????????? * Contact - Vista formulario de contacto entre usuarios */ @GetMapping("/contacto") public String contacto() { return "contacto"; } /** * Empresas - vista del conjunto de negocios acreditados en la web */ @GetMapping("/empresas") public String empresas() { return "empresas"; } /** * Ofertas - vista del conjunto de ofertas lanzadas por los negocios */ @GetMapping("/ofertas") public String ofertas() { return "ofertas"; } /** * Registro - vista de formulario de registro de un usuario nuevo a la web */ @GetMapping("/registro") public String registro() { return "registro"; } /** * Buscador - ??????????????????????????????????????????????? */ @GetMapping("/buscador") public String buscador() { return "buscador"; } /** * Proyecto - vista sobre los detalles y referencias de un proyecto concreto */ @GetMapping("/proyecto/{id}") public String proyecto(Model model,@PathVariable("id") long id, HttpSession session) { User u = (User) session.getAttribute("user"); u= entityManager.find(User.class, u.getId()); Proyect p = entityManager.find(Proyect.class, id); log.info("refresh de proyecto."+ p.getId()); session.setAttribute("user", u); model.addAttribute("proyect", p); model.addAttribute("participante", p.getMembers()); model.addAttribute("tags",p.getTags()); model.addAttribute("languages",p.getLanguages()); return "proyecto"; } @GetMapping("/editProyect/{id}") @Transactional public String editProyect(Model model,@PathVariable("id") long id, HttpSession session) { String exit="home"; User u = (User) session.getAttribute("user"); u= entityManager.find(User.class, u.getId()); Proyect p = entityManager.find(Proyect.class, id); log.info("refresh de proyecto."+ p.getId()); session.setAttribute("user", u); model.addAttribute("proyect", p); model.addAttribute("tags",p.getTags()); model.addAttribute("lang",p.getLanguages()); exit="editProyect"; return exit; } /** * Proyecto - vista sobre los detalles y referencias de un proyecto concreto */ @GetMapping("/showmessage/{type}/{id}") @Transactional public String showmessage(HttpSession session,Model model, @PathVariable("type") String type, @PathVariable("id") long id) { String url = "home"; boolean correct=false; Message m = entityManager.find(Message.class, id);//refresh de la base de datos User u = (User) session.getAttribute("user"); if(type.equals("R")){ model.addAttribute("entry",true); if(m.getReceiver().getId() == u.getId()){//si existe dentro de los recibidos lo habilitamos correct = true; if(m.getSender() != null) model.addAttribute("correo",m.getSender().getEmail()); else model.addAttribute("correo","Usuario no registrado"); if(!m.getRead()){ log.info("Mensaje "+id+ " actualizado como 'leido'"); m.setRead(true); } } }else{//sino lo asignamos a enviados por lo que leido no nos incumbe model.addAttribute("entry",false); if(m.getSender().getId() == u.getId()){//si existe dentro de los enviados lo habilitamos correct = true; model.addAttribute("correo",m.getReceiver().getEmail()); } } if(correct){ model.addAttribute("mensaje", m); url = "showmessage"; } return url; } /** * Buzon - vista del correo de entrada/salida de un usuario registrado */ @GetMapping("/buzon/{type}/{pag}") @Transactional public String buzon(HttpSession session,HttpServletResponse response, @PathVariable("pag") String pag,@PathVariable("type") String type, Model model) { String exit = "home"; if(type.equals("N")){ model.addAttribute("type", type); exit = "buzon"; }else{ try { log.info("pagina de buzon : "+pag); if(pag.equals("1")){ User u = (User) session.getAttribute("user"); log.info("carga el usuario : "+u.getName()); u = entityManager.find(User.class, u.getId());//refresh de la base de datos log.info("refresh de usuario lanzado."); if(type.equals("R")){ model.addAttribute("size",u.getReceivedMessages().size()); log.info("numero de mensajes recibidos: "+u.getReceivedMessages().size()); }else if(type.equals("E")){ model.addAttribute("size",u.getSentMessages().size()); log.info("numero de mensajes enviados: "+u.getSentMessages().size()); }else{ throw new EntityNotFoundException("opcion no contemplada"); } session.setAttribute("user", u); model.addAttribute("pag",pag); model.addAttribute("type", type); } exit = "buzon"; } catch (NoResultException nre) { log.error("fallo al encontrar el usuario para actualizar"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); }catch (EntityNotFoundException nre) { log.error(nre+": "+type); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } return exit; } @GetMapping("/empresavista") public String empresavista() { return "empresavista"; } /** * PerfilEmpresa - vista sobre el perfil de un negocio en concreto con sus configuraciones */ @GetMapping("/perfilempresa") public String perfilempresa(HttpSession session) { User u = (User) session.getAttribute("user"); u = entityManager.find(User.class, u.getId());//refresh de la base de datos if(u.getAddress() != null){ log.info(" cargamos la direccion don id: "+u.getAddress().getId()); session.setAttribute("user", u); } return "perfilempresa"; } /** * PerfilUsuario - vista sobre el perfil de un aspirante a trabajador en concreto con sus configuraciones */ @GetMapping("/perfilusuario") public String perfilusuario() { return "perfilusuario"; } @GetMapping("/tablaproyectos/{type}/{pag}") @Transactional public String tablaproyectos(Model model,@PathVariable("pag") String pag,@PathVariable("type") String type, HttpSession session) { String exit="home"; if(type.equals("N")){ model.addAttribute("type",type); List<Tag> t = entityManager.createQuery("from Tag ", Tag.class).getResultList(); model.addAttribute("tags",t); List<Language> l = entityManager.createQuery("from Language ", Language.class).getResultList(); model.addAttribute("lang",l); exit="tablaproyectos"; } else{ User u = (User) session.getAttribute("user"); u= entityManager.find(User.class, u.getId()); log.info("refresh de usuario."+ u.getId()); model.addAttribute("size",u.getProyects().size()); model.addAttribute("pag",pag); model.addAttribute("proyects", u.getProyects()); session.setAttribute("user", u); exit="tablaproyectos"; } return exit; } @GetMapping("/editOffer/{id}") @Transactional public String editOffer(HttpSession session,Model model, @PathVariable("id") long id) { Offer f = entityManager.find(Offer.class, id);//refresh de la base de datos User u = (User) session.getAttribute("user"); model.addAttribute("offer", f); model.addAttribute("tags",f.getTags()); session.setAttribute("user", u); String url = "editOffer"; return url; } @GetMapping("/tablaofertas/{pag}") @Transactional public String tablaofertas(HttpSession session,HttpServletResponse response, @PathVariable("pag") String pag, Model model) { String exit = "home"; try { log.info("pagina de ofertas : "+pag); if(pag.equals("1")){ User u = (User) session.getAttribute("user"); log.info("carga el usuario : "+u.getName()); u = entityManager.find(User.class, u.getId());//refresh de la base de datos log.info("refresh de usuario lanzado."); model.addAttribute("size",u.getOffers().size()); log.info("Tamaño."+u.getOffers().size()); session.setAttribute("user", u); model.addAttribute("pag",pag); model.addAttribute("offers", u.getOffers()); } else if(pag.equals("N")) { List<Tag> t = entityManager.createQuery("from Tag ", Tag.class).getResultList(); model.addAttribute("tags",t); } exit = "tablaofertas"; } catch (NoResultException nre) { log.error("fallo al encontrar el usuario para actualizar"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); }catch (EntityNotFoundException nre) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } return exit; } @GetMapping("/ofertavista/{id}") @Transactional public String ofertavista(HttpSession session, Model model, @PathVariable("id") long id) { String url = "home"; try { Offer f = entityManager.find(Offer.class, id);// refresh de la base de // datos model.addAttribute("theOffer", f); log.info("oferta del usuario con email : " + f.getOfferer().getEmail()); log.info("numero te tags en la oferta : " + f.getTags().size()); url = "ofertavista"; } catch (NoResultException nre) { log.error("fallo al encontrar el usuario para actualizar"); } return url; } @GetMapping("/empresas/empresavista/{id}/{pag}") @Transactional public String empresavista(HttpSession session, Model model, @PathVariable("id") long id, @PathVariable("pag") String pag) { String url = "home"; User u; log.info("pagina de ofertas : " + pag); u = entityManager.find(User.class, id);// refresh de la // base de datos log.info("refresh de usuario lanzado."); model.addAttribute("size", u.getOffers().size()); log.info("Tamaño." + u.getOffers().size()); model.addAttribute("pag", pag); model.addAttribute("offers", u.getOffers()); model.addAttribute("TheBussines", u); url = "empresavista"; return url; } @GetMapping("/ofertas/{pag}") @Transactional public String ofertas(HttpSession session,HttpServletResponse response, @PathVariable("pag") String pag, Model model) { String exit = "home"; try { log.info("pagina de ofertas : "+pag); if(pag.equals("1")){ User u = (User) session.getAttribute("user"); log.info("carga el usuario : "+u.getName()); u = entityManager.find(User.class, u.getId());//refresh de la base de datos log.info("refresh de usuario lanzado."); model.addAttribute("size",u.getOffers().size()); log.info("Tamaño."+u.getOffers().size()); session.setAttribute("user", u); model.addAttribute("pag",pag); List<Offer> o = entityManager.createQuery("select o from Offer o order by o.id DESC ", Offer.class).getResultList(); model.addAttribute("offers", o); } exit = "ofertas"; } catch (NoResultException nre) { log.error("fallo al encontrar el usuario para actualizar"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); }catch (EntityNotFoundException nre) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } return exit; } @GetMapping("/empresas/{pag}") @Transactional public String empresas(HttpSession session, HttpServletResponse response, @PathVariable("pag") String pag, Model model) { String exit = "home"; try { log.info("pagina de empresas : " + pag); if (pag.equals("1")) { List u = new ArrayList<User>(); u = entityManager.createQuery("select u from User u where roles = :roles") .setParameter("roles", "USER,BUSSINES").getResultList(); log.info("Coge bien la lista" + u.size()); model.addAttribute("size", u.size()); model.addAttribute("bussines", u); model.addAttribute("pag", pag); } exit = "empresas"; } catch (NoResultException nre) { log.error("fallo al encontrar el usuario para actualizar"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } catch (EntityNotFoundException nre) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } return exit; } @GetMapping("/tag/{id}/{pag}") @Transactional public String tag(Model model,@PathVariable("id") Long id,@PathVariable("pag") String pag, HttpSession session) { String exit="home"; User u = (User) session.getAttribute("user"); u= entityManager.find(User.class, u.getId()); log.info("refresh de usuario."+ u.getId()); Tag t= entityManager.find(Tag.class, id); //Solo proyectos por ahora model.addAttribute("sizeProyect",t.getProyects().size()); model.addAttribute("pag",pag); model.addAttribute("tag",t); session.setAttribute("user", u); model.addAttribute("proyects", t.getProyects()); model.addAttribute("offers", t.getOffers()); model.addAttribute("sizeOffer",t.getOffers().size()); exit="tag"; return exit; } @GetMapping("/language/{id}/{pag}") @Transactional public String language(Model model,@PathVariable("id") Long id,@PathVariable("pag") String pag, HttpSession session) { String exit="home"; User u = (User) session.getAttribute("user"); u= entityManager.find(User.class, u.getId()); log.info("refresh de usuario."+ u.getId()); Language l= entityManager.find(Language.class, id); //Solo proyectos por ahora model.addAttribute("size",l.getProyects().size()); model.addAttribute("pag",pag); model.addAttribute("lang",l); session.setAttribute("user", u); model.addAttribute("proyects", l.getProyects()); exit="language"; return exit; } @GetMapping("/proyectos/{pag}") @Transactional public String proyectos(Model model,@PathVariable("pag") String pag, HttpSession session) { String exit="home"; User u = (User) session.getAttribute("user"); u= entityManager.find(User.class, u.getId()); log.info("refresh de usuario."+ u.getId()); //List<Proyect> p = entityManager.createQuery("select p, AVG(p.assessment.punctuation) as score from Proyect p inner join p.assessment order by score DESC ", Proyect.class).getResultList(); List<Proyect> p = entityManager.createQuery("select p from Proyect p order by p.id DESC ", Proyect.class).getResultList(); model.addAttribute("size",p.size()); model.addAttribute("pag",pag); model.addAttribute("proyects",p); session.setAttribute("user", u); exit="proyectos"; return exit; } }
package fi.csc.microarray.filebroker; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.sql.SQLException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.zip.ZipException; import javax.jms.JMSException; import org.apache.activemq.DestinationDoesNotExistException; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.h2.tools.Server; import fi.csc.microarray.config.Configuration; import fi.csc.microarray.config.DirectoryLayout; import fi.csc.microarray.constants.ApplicationConstants; import fi.csc.microarray.filebroker.FileBrokerClient.FileBrokerArea; import fi.csc.microarray.manager.ManagerClient; import fi.csc.microarray.messaging.DirectMessagingListener; import fi.csc.microarray.messaging.JMSMessagingEndpoint; import fi.csc.microarray.messaging.MessagingEndpoint; import fi.csc.microarray.messaging.MessagingListener; import fi.csc.microarray.messaging.MessagingTopic; import fi.csc.microarray.messaging.MessagingTopic.AccessMode; import fi.csc.microarray.messaging.NodeBase; import fi.csc.microarray.messaging.Topics; import fi.csc.microarray.messaging.message.BooleanMessage; import fi.csc.microarray.messaging.message.ChipsterMessage; import fi.csc.microarray.messaging.message.CommandMessage; import fi.csc.microarray.messaging.message.ParameterMessage; import fi.csc.microarray.messaging.message.SuccessMessage; import fi.csc.microarray.messaging.message.UrlListMessage; import fi.csc.microarray.messaging.message.UrlMessage; import fi.csc.microarray.service.KeepAliveShutdownHandler; import fi.csc.microarray.service.ShutdownCallback; import fi.csc.microarray.util.IOUtils; import fi.csc.microarray.util.Strings; import fi.csc.microarray.util.SystemMonitorUtil; public class FileServer extends NodeBase implements MessagingListener, DirectMessagingListener, ShutdownCallback { /** * Logger for this class */ private static Logger logger; public static final String ERROR_QUOTA_EXCEEDED = "quota-exceeded"; public static final String CACHE_PATH = "cache"; public static final String STORAGE_PATH = "storage"; private MessagingEndpoint jmsEndpoint; private ManagerClient managerClient; private AuthorisedUrlRepository urlRepository; private FileBrokerAreas filebrokerAreas; private DerbyMetadataServer metadataServer; private File cacheRoot; private File storageRoot; private File publicRoot; private String publicPath; private String host; private int port; private DiskCleanUp cacheCleanUp; private ExecutorService longRunningTaskExecutor = Executors.newCachedThreadPool(); private int metadataPort; private ExampleSessionUpdater exampleSessionUpdater; private long defaultUserQuota; private long quotaWarning; // percentage of the quota public static void main(String[] args) { new FileServer(null, null); } public FileServer(String configURL, MessagingEndpoint overriddenEndpoint) { this(configURL, overriddenEndpoint, null); } public FileServer(String configURL, MessagingEndpoint overriddenEndpoint, JettyFileServer externalFileServer) { try { // initialise dir and logging DirectoryLayout.initialiseServerLayout( Arrays.asList(new String[] {"frontend", "filebroker"}), configURL); Configuration configuration = DirectoryLayout.getInstance().getConfiguration(); logger = Logger.getLogger(FileServer.class); // get configurations File fileRepository = DirectoryLayout.getInstance().getFileRoot(); String exampleSessionPath = configuration.getString("filebroker", "example-session-path"); this.publicPath = configuration.getString("filebroker", "public-path"); this.host = configuration.getString("filebroker", "url"); this.port = configuration.getInt("filebroker", "port"); this.defaultUserQuota = configuration.getInt("filebroker", "default-user-quota"); this.quotaWarning = configuration.getInt("filebroker", "quota-warning"); // initialise filebroker areas this.filebrokerAreas = new FileBrokerAreas(fileRepository, CACHE_PATH, STORAGE_PATH); // initialise url repository this.urlRepository = new AuthorisedUrlRepository(host, port, CACHE_PATH, STORAGE_PATH); // initialise metadata database logger.info("starting derby metadata server"); this.metadataPort = configuration.getInt("filebroker", "metadata-port"); this.metadataServer = new DerbyMetadataServer(); if (metadataPort > 0) { Server h2WebConsoleServer; h2WebConsoleServer = Server.createWebServer(new String[] {"-webAllowOthers", "-webPort", String.valueOf(this.metadataPort)}); h2WebConsoleServer.start(); logger.info("started metadata server web interface: " + h2WebConsoleServer.getStatus()); } else { logger.info("not starting metadata server web interface"); } cacheRoot = new File(fileRepository, CACHE_PATH); storageRoot = new File(fileRepository, STORAGE_PATH); publicRoot = new File(fileRepository, publicPath); // cache clean up setup int cleanUpTriggerLimitPercentage = configuration.getInt("filebroker", "clean-up-trigger-limit-percentage"); int cleanUpTargetPercentage = configuration.getInt("filebroker", "clean-up-target-percentage"); int cleanUpMinimumFileAge = configuration.getInt("filebroker", "clean-up-minimum-file-age"); long minimumSpaceForAcceptUpload = 1024l*1024l*configuration.getInt("filebroker", "minimum-space-for-accept-upload"); cacheCleanUp = new DiskCleanUp(cacheRoot, cleanUpTriggerLimitPercentage, cleanUpTargetPercentage, cleanUpMinimumFileAge, minimumSpaceForAcceptUpload); // boot up file server URL hostURL = new URL(this.host); JettyFileServer jettyFileServer; if (externalFileServer != null) { jettyFileServer = externalFileServer; } else { jettyFileServer = new JettyFileServer(urlRepository, metadataServer, cacheCleanUp); } jettyFileServer.start(fileRepository.getPath(), port, hostURL.getProtocol()); // disable periodic clean up for now // int cutoff = 1000 * configuration.getInt("filebroker", "file-life-time"); // int cleanUpFrequency = 1000 * configuration.getInt("filebroker", "clean-up-frequency"); // int checkFrequency = 1000 * 5; // Timer t = new Timer("frontend-scheduled-tasks", true); // t.schedule(new FileCleanUpTimerTask(userDataRoot, cutoff), 0, cleanUpFrequency); // t.schedule(new JettyCheckTimerTask(fileServer), 0, checkFrequency); // initialise messaging, part 1 if (overriddenEndpoint != null) { this.jmsEndpoint = overriddenEndpoint; } else { this.jmsEndpoint = new JMSMessagingEndpoint(this); } this.managerClient = new ManagerClient(jmsEndpoint); addEndpoint(jmsEndpoint); MessagingTopic filebrokerAdminTopic = jmsEndpoint.createTopic(Topics.Name.FILEBROKER_ADMIN_TOPIC, AccessMode.READ); filebrokerAdminTopic.setListener(new FilebrokerAdminMessageListener()); // load new zip example sessions and store as server sessions if (exampleSessionPath != null && !exampleSessionPath.isEmpty()) { File exampleSessionDir = new File(fileRepository, exampleSessionPath); logger.info("importing example sessions from " + exampleSessionDir.getAbsolutePath()); this.exampleSessionUpdater = new ExampleSessionUpdater(this, metadataServer, exampleSessionDir); try { this.exampleSessionUpdater.importExampleSessions(); } catch(ZipException e) { //import failed because of the broken zip file. Probably something interrupted the session export //and the situation needs to be resolved manually logger.error("example session import failed", e); throw e; } } else { logger.info("the example sessions path is not configured, nothing to import"); } // create keep-alive thread and register shutdown hook KeepAliveShutdownHandler.init(this); logger.info("minimum required space after upload: " + FileUtils.byteCountToDisplaySize(minimumSpaceForAcceptUpload)); logger.info("fileserver is up and running [" + ApplicationConstants.VERSION + "]"); logger.info("[mem: " + SystemMonitorUtil.getMemInfo() + "]"); } catch (Exception e) { e.printStackTrace(); logger.error(e, e); } } protected void addEndpoint(MessagingEndpoint endpoint) throws JMSException { MessagingTopic filebrokerTopic = endpoint.createTopic(Topics.Name.AUTHORISED_FILEBROKER_TOPIC, AccessMode.READ); filebrokerTopic.setListener(this); } public String getName() { return "filebroker"; } public void onChipsterMessage(ChipsterMessage msg) { onChipsterMessage(msg, this.jmsEndpoint); } public void onChipsterMessage(ChipsterMessage msg, MessagingEndpoint endpoint) { try { if ((msg instanceof CommandMessage)) { CommandMessage cmdMsg = (CommandMessage) msg; logger.debug("received messaged " + cmdMsg.getCommand() + " from " + cmdMsg.getUsername() + ", checking that it's not " + DirectoryLayout.getInstance().getConfiguration().getString("security", "guest-username")); if (handleReadOnlyMessages(cmdMsg, endpoint)) { // it was a read only message } else if (cmdMsg.getUsername() != null && cmdMsg.getUsername().equals(DirectoryLayout.getInstance().getConfiguration().getString("security", "guest-username"))) { logger.error("only read-only messages are allowed for guest users: " + cmdMsg.getCommand()); // can't inform the client, because each command is expecting different response type } else if (handleReadWriteMessages(cmdMsg, endpoint)) { // it was a read-write message } else { logger.error("message " + msg.getMessageID() + " not understood"); } } else { logger.error("message " + msg.getMessageID() + " is not a command message, but " + msg.getClass().getSimpleName()); } } catch (Exception e) { logger.error(e, e); } } private boolean handleReadWriteMessages(CommandMessage msg, MessagingEndpoint endpoint) throws Exception { switch (msg.getCommand()) { case CommandMessage.COMMAND_STORE_SESSION: handleStoreSessionRequest(endpoint, (CommandMessage)msg); return true; case CommandMessage.COMMAND_REMOVE_SESSION: handleRemoveSessionRequest(endpoint, (CommandMessage)msg); return true; case CommandMessage.COMMAND_MOVE_FROM_CACHE_TO_STORAGE: handleMoveFromCacheToStorageRequest(endpoint, (CommandMessage)msg); return true; case CommandMessage.COMMAND_DISK_SPACE_REQUEST: handleSpaceRequest(endpoint, (CommandMessage)msg); return true; default: return false; } } @SuppressWarnings("deprecation") private boolean handleReadOnlyMessages(CommandMessage msg, MessagingEndpoint endpoint) throws Exception { switch (msg.getCommand()) { case CommandMessage.COMMAND_NEW_URL_REQUEST: handleNewURLRequest(endpoint, msg); return true; case CommandMessage.COMMAND_GET_URL: handleGetURL(endpoint, msg); return true; case CommandMessage.COMMAND_IS_AVAILABLE: handleIsAvailable(endpoint, msg); return true; case CommandMessage.COMMAND_PUBLIC_URL_REQUEST: handlePublicUrlRequest(endpoint, msg); return true; case CommandMessage.COMMAND_PUBLIC_FILES_REQUEST: handlePublicFilesRequest(endpoint, msg); return true; case CommandMessage.COMMAND_LIST_SESSIONS: handleListSessionsRequest(endpoint, (CommandMessage)msg); return true; case CommandMessage.COMMAND_LIST_STORAGE_USAGE_OF_SESSIONS: handleListStorageUsageOfSessionsRequest(endpoint, (CommandMessage)msg, msg.getUsername()); return true; default: return false; } } private void handleListStorageUsageOfSessionsRequest( MessagingEndpoint endpoint, CommandMessage msg, String username) throws SQLException, JMSException { CommandMessage requestMessage = (CommandMessage) msg; CommandMessage reply; List<String>[] sessions; sessions = metadataServer.getStorageUsageOfSessions(username); Long storageUsage = metadataServer.getStorageusageOfUser(username); reply = new CommandMessage(); reply.addNamedParameter(ParameterMessage.PARAMETER_USERNAME_LIST, Strings.delimit(sessions[0], "\t")); reply.addNamedParameter(ParameterMessage.PARAMETER_SESSION_NAME_LIST, Strings.delimit(sessions[1], "\t")); reply.addNamedParameter(ParameterMessage.PARAMETER_SIZE_LIST, Strings.delimit(sessions[2], "\t")); reply.addNamedParameter(ParameterMessage.PARAMETER_DATE_LIST, Strings.delimit(sessions[3], "\t")); reply.addNamedParameter(ParameterMessage.PARAMETER_SESSION_UUID_LIST, Strings.delimit(sessions[4], "\t")); long quota; if (defaultUserQuota > 0) { quota = defaultUserQuota * 1024 * 1024; } else { quota = storageUsage + storageRoot.getUsableSpace(); } long quotaWarningBytes = (long) (quota * quotaWarning / 100.0); reply.addNamedParameter(ParameterMessage.PARAMETER_QUOTA, "" + quota); reply.addNamedParameter(ParameterMessage.PARAMETER_QUOTA_WARNING, "" + quotaWarningBytes); reply.addNamedParameter(ParameterMessage.PARAMETER_SIZE, "" + storageUsage); jmsEndpoint.replyToMessage(requestMessage, reply); } @Deprecated private void handlePublicUrlRequest(MessagingEndpoint endpoint, ChipsterMessage msg) throws MalformedURLException, JMSException { URL url = getPublicUrl(); UrlMessage reply = new UrlMessage(url); endpoint.replyToMessage(msg, reply); managerClient.publicUrlRequest(msg.getUsername(), url); } private void handlePublicFilesRequest(MessagingEndpoint endpoint, ChipsterMessage msg) throws MalformedURLException, JMSException { List<URL> files = null; ChipsterMessage reply; try { files = getPublicFiles(); reply = new UrlListMessage(files); } catch (IOException e) { reply = null; } endpoint.replyToMessage(msg, reply); managerClient.publicFilesRequest(msg.getUsername(), files); } private void handleNewURLRequest(MessagingEndpoint endpoint, ChipsterMessage msg) throws Exception { // parse request CommandMessage requestMessage = (CommandMessage) msg; String fileId = requestMessage.getNamedParameter(ParameterMessage.PARAMETER_FILE_ID); boolean useCompression = requestMessage.getParameters().contains(ParameterMessage.PARAMETER_USE_COMPRESSION); FileBrokerArea area = FileBrokerArea.valueOf(requestMessage.getNamedParameter(ParameterMessage.PARAMETER_AREA)); String username = msg.getUsername(); long space = Long.parseLong(requestMessage.getNamedParameter(ParameterMessage.PARAMETER_DISK_SPACE)); logger.debug("New url request, dataId: " + fileId); // check quota, if needed ChipsterMessage reply = createNewURLReply(fileId, username, space, useCompression, area); // send reply endpoint.replyToMessage(msg, reply); } private ChipsterMessage createNewURLReply(String fileId, String username, long space, boolean useCompression, FileBrokerArea area) throws Exception { ChipsterMessage reply; if (!AuthorisedUrlRepository.checkFilenameSyntax(fileId)) { reply = new CommandMessage(CommandMessage.COMMAND_FILE_OPERATION_DENIED); } else if (area == FileBrokerArea.STORAGE && !checkQuota(username, space)) { reply = new SuccessMessage(false, ERROR_QUOTA_EXCEEDED); } else { URL url = urlRepository.createAuthorisedUrl(fileId, useCompression, area, space); reply = new UrlMessage(url); managerClient.urlRequest(username, url); } return reply; } private void handleGetURL(MessagingEndpoint endpoint, ChipsterMessage msg) throws MalformedURLException, JMSException { // parse request CommandMessage requestMessage = (CommandMessage) msg; String fileId = requestMessage.getNamedParameter(ParameterMessage.PARAMETER_FILE_ID); ChipsterMessage reply; URL url = null; // check fileId if (!AuthorisedUrlRepository.checkFilenameSyntax(fileId)) { reply = new CommandMessage(CommandMessage.COMMAND_FILE_OPERATION_DENIED); // find url } else if (filebrokerAreas.fileExists(fileId, FileBrokerArea.CACHE)) { url = urlRepository.constructCacheURL(fileId, ""); } else if (filebrokerAreas.fileExists(fileId, FileBrokerArea.STORAGE)) { url = urlRepository.constructStorageURL(fileId, ""); } // url may be null reply = new UrlMessage(url); // send reply endpoint.replyToMessage(msg, reply); } private void handleIsAvailable(MessagingEndpoint endpoint, ChipsterMessage msg) throws JMSException, SQLException, IOException { // parse request CommandMessage requestMessage = (CommandMessage) msg; String fileId = requestMessage.getNamedParameter(ParameterMessage.PARAMETER_FILE_ID); Long size = Long.parseLong(requestMessage.getNamedParameter(ParameterMessage.PARAMETER_SIZE)); String checksum = requestMessage.getNamedParameter(ParameterMessage.PARAMETER_CHECKSUM); FileBrokerArea area = FileBrokerArea.valueOf(requestMessage.getNamedParameter(ParameterMessage.PARAMETER_AREA)); ChipsterMessage reply; // check fileId if (!AuthorisedUrlRepository.checkFilenameSyntax(fileId)) { reply = new CommandMessage(CommandMessage.COMMAND_FILE_OPERATION_DENIED); } else { try { if (isAvailable(fileId, size, checksum, area)) { reply = new BooleanMessage(true); } else { reply = new BooleanMessage(false); } } catch ( ContentLengthException | ChecksumException e) { logger.info("corrupted data or data id collision (" + fileId + ", " + size + ", " + checksum + ")", e); reply = new CommandMessage(CommandMessage.COMMAND_FILE_OPERATION_FAILED); } catch (ChecksumParseException e) { throw new IOException(e); } catch (IOException e) { throw e; } } // send reply endpoint.replyToMessage(msg, reply); } private boolean isAvailable(String fileId, Long size, String checksum, FileBrokerArea area) throws SQLException, ChecksumParseException, IOException, ContentLengthException, ChecksumException { if (!filebrokerAreas.fileExists(fileId, area)) { return false; } Long sizeOnDisk = filebrokerAreas.getSize(fileId, area); Long sizeInDb = null; if (area == FileBrokerArea.STORAGE) { DbFile dbFile = metadataServer.fetchFile(fileId); if (dbFile == null) { return false; } sizeInDb = dbFile.getSize(); } Md5FileUtils.verify(size, sizeOnDisk, sizeInDb); String checksumOnDisk = filebrokerAreas.getChecksum(fileId, area); Md5FileUtils.verify(checksum, checksumOnDisk); return true; } private void handleSpaceRequest(final MessagingEndpoint endpoint, final CommandMessage requestMessage) throws JMSException { final long size = Long.parseLong(requestMessage.getNamedParameter(ParameterMessage.PARAMETER_DISK_SPACE)); logger.debug("disk space request for " + size + " bytes"); logger.debug("usable space is: " + cacheRoot.getUsableSpace()); longRunningTaskExecutor.execute(new Runnable() { @Override public void run() { try { // Schedule clean up if necessary. If the space request can't be // satisfied immediately, this will wait until the clean up is done, // which may take several minutes. boolean spaceAvailable = cacheCleanUp.spaceRequest(size, true, null); // send reply BooleanMessage reply = new BooleanMessage(spaceAvailable); endpoint.replyToMessage(requestMessage, reply); } catch (DestinationDoesNotExistException e) { // don't print stack trace logger.error("could not reply to space request, because client gave up during the clean-up"); } catch (JMSException e) { logger.error("could not reply to space request", e); } } }); } private void handleListSessionsRequest(MessagingEndpoint endpoint, final CommandMessage requestMessage) throws JMSException, MalformedURLException { String username = requestMessage.getUsername(); CommandMessage reply; try { List<DbSession> sessions = metadataServer.listSessions(username); reply = new CommandMessage(); LinkedList<String> sessionIds = new LinkedList<>(); LinkedList<String> names = new LinkedList<>(); for (DbSession session : sessions) { names.add(session.getName()); sessionIds.add(session.getDataId()); } reply.addNamedParameter(ParameterMessage.PARAMETER_SESSION_NAME_LIST, Strings.delimit(names, "\t")); reply.addNamedParameter(ParameterMessage.PARAMETER_SESSION_UUID_LIST, Strings.delimit(sessionIds, "\t")); } catch (Exception e) { reply = new CommandMessage(CommandMessage.COMMAND_FILE_OPERATION_FAILED); } endpoint.replyToMessage(requestMessage, reply); } private void handleStoreSessionRequest(MessagingEndpoint endpoint, final CommandMessage requestMessage) throws JMSException, MalformedURLException { String username = requestMessage.getUsername(); String name = requestMessage.getNamedParameter(ParameterMessage.PARAMETER_SESSION_NAME); String sessionId = AuthorisedUrlRepository.stripCompressionSuffix(requestMessage.getNamedParameter(ParameterMessage.PARAMETER_SESSION_UUID)); List<String> fileIds = Arrays.asList(requestMessage.getNamedParameterAsArray(ParameterMessage.PARAMETER_FILE_ID_LIST)); ChipsterMessage reply; try { storeSession(username, name, sessionId, fileIds); // everything went fine reply = new CommandMessage(CommandMessage.COMMAND_FILE_OPERATION_SUCCESSFUL); } catch (Exception e) { reply = new CommandMessage(CommandMessage.COMMAND_FILE_OPERATION_FAILED); } endpoint.replyToMessage(requestMessage, reply); } private void storeSession(String username, String name, String sessionId, List<String> fileIds) throws SQLException { // check if we are overwriting previous session String previousSessionUuid = metadataServer.fetchSession(username, name); if (previousSessionUuid != null) { // move it aside metadataServer.renameSession("_" + name, previousSessionUuid); } // store session metadataServer.addSession(username, name, sessionId); // link files (they have been added when uploaded) for (String fileId : fileIds) { // check if the file is stored in this file broker if (filebrokerAreas.fileExists(fileId, FileBrokerArea.STORAGE)) { metadataServer.linkFileToSession(fileId, sessionId); } } // remove previous if (previousSessionUuid != null) { removeSession(previousSessionUuid); } } private void handleRemoveSessionRequest(MessagingEndpoint endpoint, final CommandMessage requestMessage) throws JMSException { // parse request String sessionId = requestMessage.getNamedParameter(ParameterMessage.PARAMETER_SESSION_UUID); SuccessMessage reply; try { // if no uuid, try to get url, which was the old way if (sessionId == null) { URL url = new URL(requestMessage.getNamedParameter(ParameterMessage.PARAMETER_SESSION_URL)); sessionId = IOUtils.getFilenameWithoutPath(url); } if (metadataServer.isUsernameAllowedToRemoveSession(requestMessage.getUsername(), sessionId)) { removeSession(sessionId); reply = new SuccessMessage(true); } else { reply = new SuccessMessage(false, "user it not allowed to remove the session"); } } catch (Exception e) { reply = new SuccessMessage(false, e); } // send endpoint.replyToMessage(requestMessage, reply); } protected void removeSession(String sessionId) throws SQLException { // remove from database (including related data) List<String> removedFiles = metadataServer.removeSession(sessionId); // remove from filesystem for (String removedFile : removedFiles) { File dataFile = new File(storageRoot, removedFile); dataFile.delete(); Md5FileUtils.removeMd5(dataFile); } } private void handleMoveFromCacheToStorageRequest(final MessagingEndpoint endpoint, final CommandMessage requestMessage) throws JMSException, MalformedURLException { final String fileId = requestMessage.getNamedParameter(ParameterMessage.PARAMETER_FILE_ID); logger.debug("move request for: " + fileId); // check id and if in cache if (!(AuthorisedUrlRepository.checkFilenameSyntax(fileId) && filebrokerAreas.fileExists(fileId, FileBrokerArea.CACHE))) { endpoint.replyToMessage(requestMessage, new SuccessMessage(false)); } else { // move longRunningTaskExecutor.execute(new Runnable() { @Override public void run() { ChipsterMessage reply = null; try { // check quota here also if (!checkQuota(requestMessage.getUsername(), filebrokerAreas.getSize(fileId, FileBrokerArea.CACHE))) { reply = new SuccessMessage(false, ERROR_QUOTA_EXCEEDED); } else { // move the file boolean moveSuccess = filebrokerAreas.moveFromCacheToStorage(fileId); // add to db long size = filebrokerAreas.getSize(fileId, FileBrokerArea.STORAGE); metadataServer.addFile(fileId, size); if (moveSuccess) { reply = new SuccessMessage(true); } else { reply = new SuccessMessage(false); logger.warn("could not move from cache to storage: " + fileId); } } } catch (Exception e) { reply = new SuccessMessage(false); } // send reply try { endpoint.replyToMessage(requestMessage, reply); } catch (JMSException e) { logger.error("could not send reply message", e); } } }); } } private boolean checkQuota(String username, long additionalBytes) throws SQLException { if (defaultUserQuota == -1) { logger.debug("quota limit disabled"); return true; } else { Long usage = metadataServer.getStorageusageOfUser(username); boolean isAllowed = usage + additionalBytes <= defaultUserQuota*1024*1024; logger.debug("quota check passed: " + isAllowed); return isAllowed; } } public void shutdown() { logger.info("shutdown requested"); // close messaging endpoint try { this.jmsEndpoint.close(); } catch (JMSException e) { logger.error("closing messaging endpoint failed", e); } logger.info("shutting down"); } @Deprecated public URL getPublicUrl() throws MalformedURLException { return new URL(host + ":" + port + "/" + publicPath); } public List<URL> getPublicFiles() throws IOException { List<URL> urlList = new LinkedList<URL>(); addFilesRecursively(urlList, publicRoot); return urlList; } private void addFilesRecursively(List<URL> files, File path) throws IOException { for (File file : path.listFiles()) { if (file.isDirectory()) { addFilesRecursively(files, file); } else { String localPath = file.toURI().toString();//convert spaces to %20 etc. String publicRootString = publicRoot.toURI().toString();//convert spaces to %20 etc. String urlString = localPath.replace(publicRootString, host + ":" + port + "/" + publicPath + "/"); files.add(new URL(urlString)); } } } private class FilebrokerAdminMessageListener implements MessagingListener { /* (non-Javadoc) * @see fi.csc.microarray.messaging.MessagingListener#onChipsterMessage(fi.csc.microarray.messaging.message.ChipsterMessage) */ @Override public void onChipsterMessage(ChipsterMessage msg) { try { // get totals if (msg instanceof CommandMessage && CommandMessage.COMMAND_LIST_STORAGE_USAGE_OF_USERS.equals(((CommandMessage)msg).getCommand())) { CommandMessage requestMessage = (CommandMessage) msg; CommandMessage reply; List<String>[] users; users = metadataServer.getStorageusageOfUsers(); reply = new CommandMessage(); reply.addNamedParameter(ParameterMessage.PARAMETER_USERNAME_LIST, Strings.delimit(users[0], "\t")); reply.addNamedParameter(ParameterMessage.PARAMETER_SIZE_LIST, Strings.delimit(users[1], "\t")); jmsEndpoint.replyToMessage(requestMessage, reply); } // get sessions for user else if (msg instanceof CommandMessage && CommandMessage.COMMAND_LIST_STORAGE_USAGE_OF_SESSIONS.equals(((CommandMessage)msg).getCommand())) { String username = ((ParameterMessage)msg).getNamedParameter("username"); handleListStorageUsageOfSessionsRequest(jmsEndpoint, (CommandMessage)msg, username); } // get sessions for session name else if (msg instanceof CommandMessage && CommandMessage.COMMAND_GET_STORAGE_USAGE_TOTALS.equals(((CommandMessage)msg).getCommand())) { CommandMessage requestMessage = (CommandMessage) msg; CommandMessage reply; LinkedList<String> totals = new LinkedList<String>(); totals.add(metadataServer.getStorageUsageTotal()); totals.add("" + storageRoot.getUsableSpace()); reply = new CommandMessage(); reply.addNamedParameter(ParameterMessage.PARAMETER_SIZE_LIST, Strings.delimit(totals, "\t")); jmsEndpoint.replyToMessage(requestMessage, reply); } else if (msg instanceof CommandMessage && CommandMessage.COMMAND_REMOVE_SESSION.equals(((CommandMessage)msg).getCommand())) { handleRemoveSessionRequest(jmsEndpoint, (CommandMessage)msg); } else if (msg instanceof CommandMessage && CommandMessage.COMMAND_GET_STATUS_REPORT.equals(((CommandMessage)msg).getCommand())) { CommandMessage requestMessage = (CommandMessage) msg; CommandMessage reply = new CommandMessage(); FileServerAdminTools admin = getAdminTools(); String sysStats = SystemMonitorUtil.getSystemStats(cacheRoot).systemStatsToString(); String report = ""; report += "SYSTEM\n\n"; report += sysStats + "\n"; report += admin.getDataBaseStatusReport() + "\n"; reply.addNamedParameter(ParameterMessage.PARAMETER_STATUS_REPORT, report); jmsEndpoint.replyToMessage(requestMessage, reply); } else if (msg instanceof CommandMessage && CommandMessage.COMMAND_LOG_STATUS.equals(((CommandMessage)msg).getCommand())) { longRunningTaskExecutor.execute(new Runnable() { public void run() { try { logger.info("status report requested from the admin-web"); FileServerAdminTools admin = getAdminTools(); String sysStats = SystemMonitorUtil.getSystemStats(cacheRoot).systemStatsToString(); String report = ""; report += "SYSTEM\n\n"; report += sysStats + "\n"; logger.info("calculating database status report"); report += admin.getDataBaseStatusReport() + "\n"; logger.info("calculating storage status report"); String storageReport = admin.getStorageStatusReport(false); File reportFile = new File(DirectoryLayout.getInstance().getLogsDir(), "storage-status.txt"); logger.info("writing storage status report to " + reportFile.getAbsolutePath()); try (PrintWriter out = new PrintWriter(reportFile)) { out.println(storageReport); } logger.info("status report ready\n\n" + report); } catch (Exception e) { logger.error("failed to log status report", e); } } }); } } catch (Exception e) { logger.error("error in file-broker message handling", e); } } private FileServerAdminTools getAdminTools() { return new FileServerAdminTools(metadataServer, cacheRoot, storageRoot, false); } } }
package foodtruck.geolocation; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.name.Named; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; /** * @author aviolette@gmail.com * @since Jul 20, 2011 */ public class GeolocationModule extends AbstractModule { @Override protected void configure() { bind(GeoLocator.class).to(CacheAndStoreLocator.class); bind(GeoLocator.class).annotatedWith(SecondaryGeolocator.class).to(GoogleGeolocator.class); } @Provides @Named("yahoo.app.id") @Singleton public String provideYahooAppId() { return System.getProperty("yahoo.app.id"); } @GoogleEndPoint @Provides @Singleton public WebResource provideWebResource() { Client c = Client.create(); return c.resource("http://maps.googleapis.com/maps/api/geocode/json"); } @YahooEndPoint @Provides @Singleton public WebResource provideYahooWebResource() { Client c = Client.create(); return c.resource("http://where.yahooapis.com/geocode"); } }
package fr.liglab.lcm.internals.nomaps; import java.util.Arrays; import java.util.Iterator; import java.util.PriorityQueue; import java.util.concurrent.atomic.AtomicInteger; import fr.liglab.lcm.internals.FrequentsIterator; import fr.liglab.lcm.internals.TransactionReader; import fr.liglab.lcm.util.ItemAndSupport; import fr.liglab.lcm.util.ItemsetsFactory; import gnu.trove.iterator.TIntIntIterator; import gnu.trove.map.hash.TIntIntHashMap; /** * This class' constructor performs item counting over a transactions database, and then gives * access to various counters. It ignores items below the minimum support. During recursions this * allows the algorithm to choose what kind of projections and filtering should be done, before * instantiating the actual projected dataset. * * We're using arrays as Maps<Int,Int> , however they're not public as item identifiers may have * been renamed by dataset representation. By the way this class is able to generate renamings * (and applies them to itself by the way) if you need to rename items in a future representation. * You *MUST* handle renaming after instantiation. See field reverseRenaming. */ public final class Counters { /** * Items occuring less than minSup times will be considered infrequent */ public final int minSupport; /** * How many transactions are represented by the given dataset ? */ public final int transactionsCount; /** * How many transactions have been counted (equals transactionsCount when all transactions * have a weight of 1) */ public final int distinctTransactionsCount; /** * Sum of given *filtered* transactions' lengths, ignoring their weight */ public final int distinctTransactionLengthSum; /** * Support count, per item having a support count in [minSupport; 100% [ * Items having a support count below minSupport are considered infrequent, those at 100% belong * to closure, for both supportCounts[i] = 0 - except if renaming happened, in which case such * items no longer exists. * * Indexes above maxFrequent should be considered valid. */ final int[] supportCounts; /** * supportCounts, summed - FIXME is this useful ?? */ public final int supportCountsSum; /** * For each item having a support count in [minSupport; 100% [ , gives how many distinct * transactions contained this item. It's like supportCounts if all transactions have a * weight equal to 1 * * Indexes above maxFrequent should be considered valid. */ final int[] distinctTransactionsCounts; /** * Items found to have a support count equal to transactionsCount (using IDs from given transactions) * On renamed datasets you SHOULD NOT use getReverseRenaming to translate back these items, * rather use parent's reverseRenaming (or none for the initial dataset) */ final int[] closure; /** * Counts how many items have a support count in [minSupport; 100% [ */ public final int nbFrequents; /** * Biggest item ID having a support count in [minSupport; 100% [ */ protected int maxFrequent; /** * This array allows another class to output the discovered closure using original items' IDs. * * After instanciation this field *must* be set by one of these methods * - reuseRenaming * - the initial dataset's constructor (which also sets "renaming") * - compactRenaming (useful when recompacting dataset in recursions) */ protected int[] reverseRenaming; /** * This field will be null EXCEPT if you're using the initial dataset's constructor, in which * case it computes its absolute renaming by the way. * * It gives, for each original item ID, its new identifier. If it's negative it means the item * should be filtered. */ final int[] renaming; /** * will be set to true if arrays have been compacted, ie. if supportCounts and distinctTransactionsCounts * don't contain any zero. */ protected boolean compactedArrays = false; /** * Does item counting over a projected dataset * @param minimumSupport * @param transactions extension's support * @param extension the item on which we're projecting - it won't appear in *any* counter (not even 'closure') * @param ignoredItems may be null, if it's not contained items won't appear in any counter either * @param maxItem biggest index among items to be found in "transactions" */ Counters(int minimumSupport, Iterator<TransactionReader> transactions, int extension, int[] ignoredItems, final int maxItem) { this.renaming = null; this.minSupport = minimumSupport; this.supportCounts = new int[maxItem]; this.distinctTransactionsCounts = new int[maxItem]; // item support and transactions counting int weightsSum = 0; int transactionsCount = 0; while (transactions.hasNext()) { TransactionReader transaction = transactions.next(); int weight = transaction.getTransactionSupport(); if (weight > 0) { if (transaction.hasNext()) { weightsSum += weight; transactionsCount++; } while (transaction.hasNext()) { int item = transaction.next(); if (item < maxItem) { this.supportCounts[item] += weight; this.distinctTransactionsCounts[item]++; } } } } this.transactionsCount = weightsSum; this.distinctTransactionsCount = transactionsCount; // ignored items this.supportCounts[extension] = 0; this.distinctTransactionsCounts[extension] = 0; if (ignoredItems != null) { for (int item : ignoredItems) { if (item < maxItem) { this.supportCounts[item] = 0; this.distinctTransactionsCounts[item] = 0; } } } // item filtering and final computations : some are infrequent, some belong to closure ItemsetsFactory closureBuilder = new ItemsetsFactory(); int remainingSupportsSum = 0; int remainingDistinctTransLength = 0; int remainingFrequents = 0; int biggestItemID = 0; for (int i = 0; i < this.supportCounts.length; i++) { if (this.supportCounts[i] < minimumSupport) { this.supportCounts[i] = 0; this.distinctTransactionsCounts[i] = 0; } else if (this.supportCounts[i] == this.transactionsCount) { closureBuilder.add(i); this.supportCounts[i] = 0; this.distinctTransactionsCounts[i] = 0; } else { biggestItemID = Math.max(biggestItemID, i); remainingFrequents++; remainingSupportsSum += this.supportCounts[i]; remainingDistinctTransLength += this.distinctTransactionsCounts[i]; } } this.closure = closureBuilder.get(); this.supportCountsSum = remainingSupportsSum; this.distinctTransactionLengthSum = remainingDistinctTransLength; this.nbFrequents = remainingFrequents; this.maxFrequent = biggestItemID; } /** * Does item counting over an initial dataset : it will only ignore infrequent items, and it * doesn't know what's biggest item ID. * IT ALSO IGNORES TRANSACTIONS WEIGHTS ! (assuming it's 1 everywhere) * /!\ It will perform an absolute renaming : items are renamed (and, likely, re-ordered) by * decreasing support count. For instance 0 will be the most frequent item. * * Indexes in arrays will refer items' new names, except for closure. * * @param minimumSupport * @param transactions */ Counters(int minimumSupport, Iterator<TransactionReader> transactions) { this.minSupport = minimumSupport; TIntIntHashMap supportsMap = new TIntIntHashMap(); int biggestItemID = 0; // item support and transactions counting int transactionsCounter = 0; while (transactions.hasNext()) { TransactionReader transaction = transactions.next(); transactionsCounter++; while (transaction.hasNext()) { int item = transaction.next(); biggestItemID = Math.max(biggestItemID, item); supportsMap.adjustOrPutValue(item, 1, 1); } } this.transactionsCount = transactionsCounter; this.distinctTransactionsCount = transactionsCounter; this.renaming = new int[biggestItemID]; Arrays.fill(renaming, -1); // item filtering and final computations : some are infrequent, some belong to closure final PriorityQueue<ItemAndSupport> renamingHeap = new PriorityQueue<ItemAndSupport>(); ItemsetsFactory closureBuilder = new ItemsetsFactory(); TIntIntIterator iterator = supportsMap.iterator(); while (iterator.hasNext()) { final int item = iterator.key(); final int supportCount = iterator.value(); if (supportCount == this.transactionsCount) { closureBuilder.add(item); } else if (supportCount >= minimumSupport){ renamingHeap.add(new ItemAndSupport(item, supportCount)); } // otherwise item is infrequent : its renaming is already -1, ciao } this.closure = closureBuilder.get(); this.nbFrequents = renamingHeap.size(); this.maxFrequent = this.nbFrequents - 1; this.supportCounts = new int[this.nbFrequents]; this.distinctTransactionsCounts = new int[this.nbFrequents]; this.reverseRenaming = new int[this.nbFrequents]; int remainingSupportsSum = 0; ItemAndSupport entry = renamingHeap.poll(); int newItemID = 0; while (entry != null) { final int item = entry.item; final int support = entry.support; this.renaming[item] = newItemID; this.reverseRenaming[newItemID] = item; this.supportCounts[newItemID] = support; this.distinctTransactionsCounts[newItemID] = support; remainingSupportsSum += support; entry = renamingHeap.poll(); newItemID++; } this.compactedArrays = true; this.supportCountsSum = remainingSupportsSum; this.distinctTransactionLengthSum = remainingSupportsSum; } /** * @return greatest frequent item's ID, which is also the greatest valid index for arrays supportCounts and distinctTransactionsCounts */ int getMaxFrequent() { return this.maxFrequent; } /** * @return a translation from */ int[] getReverseRenaming() { return this.reverseRenaming; } void reuseRenaming(int[] olderReverseRenaming) { this.reverseRenaming = olderReverseRenaming; } /** * Will compress an older renaming, by removing infrequent items. * Contained arrays (except closure) will refer new item IDs * @param olderReverseRenaming reverseRenaming from the dataset that fed this Counter * @return the translation from the old renaming to the compressed one (gives -1 for removed items) */ int[] compressRenaming(int[] olderReverseRenaming) { int[] renaming = new int[olderReverseRenaming.length]; this.reverseRenaming = new int[this.nbFrequents]; // we will always have newItemID <= item int newItemID = 0; for (int item = 0; item < this.supportCounts.length; item++) { if (this.supportCounts[item] > 0) { renaming[item] = newItemID; this.reverseRenaming[newItemID] = olderReverseRenaming[item]; this.distinctTransactionsCounts[newItemID] = this.distinctTransactionsCounts[item]; this.supportCounts[newItemID] = this.supportCounts[item]; newItemID++; } else { renaming[item] = -1; } } for (int item = this.supportCounts.length; item < olderReverseRenaming.length; item++) { renaming[item] = -1; } this.maxFrequent = newItemID - 1; this.compactedArrays = true; return renaming; } FrequentsIterator getFrequentsIterator(final int to) { return new AllFrequentsIterator(to); } /** * Thread-safe iterator over frequent items (ie. those having a support count in [minSup, 100%[) */ protected class AllFrequentsIterator implements FrequentsIterator { private final AtomicInteger index; private final int max; /** * will provide an iterator on frequent items (in increasing order) in [0,to[ */ public AllFrequentsIterator(final int to) { this.index = new AtomicInteger(0); this.max = to; } /** * @return -1 if iterator is finished */ public int next() { if (compactedArrays) { final int nextIndex = this.index.getAndIncrement(); if (nextIndex < this.max) { return nextIndex; } else { return -1; } } else { while (true) { final int nextIndex = this.index.getAndIncrement(); if (nextIndex < this.max) { if (supportCounts[nextIndex] > 0) { return nextIndex; } } else { return -1; } } } } } }
package io.featureflow.client; import com.google.gson.JsonPrimitive; import io.featureflow.client.core.*; import io.featureflow.client.model.Event; import io.featureflow.client.model.Feature; import io.featureflow.client.model.FeatureControl; import io.featureflow.client.model.Variant; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.time.LocalTime; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class FeatureflowClient implements Closeable { private static final Logger logger = LoggerFactory.getLogger(FeatureflowClient.class); private final FeatureflowConfig config; private final FeatureControlStreamClient featureControlStreamClient; // manages pubsub events to update a feature control private final FeatureControlCache featureControlCache; //holds the featureControls private final RestClient restClient; //manages retrieving features and pushing updates private final EventsClient eventHandler; private final Map<String, Feature> featuresMap = new HashMap<>(); //this contains code registered features and failovers private final FeatureflowUserProvider userProvider; private final FeatureflowUserLookupProvider userLookupProvider; private final boolean offline; FeatureflowClient(String apiKey) { this(apiKey, null, new FeatureflowConfig.Builder().build(), null, null, null, false); } FeatureflowClient(String apiKey, List<Feature> features) { this(apiKey, features, new FeatureflowConfig.Builder().build(), null, null, null, false); } FeatureflowClient( String apiKey, List<Feature> features, FeatureflowConfig config, Map<CallbackEvent, List<FeatureControlCallbackHandler>> callbacks, FeatureflowUserProvider userProvider, FeatureflowUserLookupProvider userLookupProvider, boolean offline) { //set config, use a builder this.config = config; this.userProvider = userProvider; this.userLookupProvider = userLookupProvider; this.offline = offline; featureControlCache = new SimpleMemoryFeatureCache(); if (offline) { restClient = new RestClientMock(apiKey, config); eventHandler = new EventsClientMock(config, restClient); } else { restClient = new RestClientImpl(apiKey, config); eventHandler = new EventsClientImpl(config, restClient); } //Actively defining registrations helps alert if features are available in an environment if (features != null && features.size() > 0) { for (Feature feature : features) { featuresMap.put(feature.key, feature); } try { restClient.registerFeatureControls(features); } catch (IOException e) { logger.error("Problem registering feature controls", e); } } featureControlStreamClient = new FeatureControlStreamClient(apiKey, config, featureControlCache, callbacks); Future<Void> startFuture = featureControlStreamClient.start(); if (config.waitForStartup > 0L) { logger.info("Waiting for Featureflow to initialise"); try { startFuture.get(config.waitForStartup, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { logger.error("Timeout waiting for Featureflow client initialise"); } catch (Exception e) { logger.error("Exception waiting for Featureflow client to initialise", e); } } } /** * Evaluate with a specific user, this will override any userProvider or anonymous user * * @param featureKey * @param user * @return */ public Evaluate evaluate(String featureKey, FeatureflowUser user) { Evaluate e = new Evaluate(this, featureKey, user); return e; } public Evaluate evaluate(String featureKey, String userId) { FeatureflowUser user = userLookupProvider == null ? new FeatureflowUser(userId) : userLookupProvider.getUser(userId); Evaluate e = new Evaluate(this, featureKey, user); return e; } public Evaluate evaluate(String featureKey) { //create an anonymous user if no provider FeatureflowUser user = userProvider == null ? new FeatureflowUser() : userProvider.getUser(); return evaluate(featureKey, user); } public Map<String, String> evaluateAll(FeatureflowUser user) { Map<String, String> result = new HashMap<>(); for (String s : featureControlCache.getAll().keySet()) { result.put(s, eval(s, user)); } return result; } private String eval(String featureKey, FeatureflowUser user) { String failoverVariant = (featuresMap.get(featureKey) != null && featuresMap.get(featureKey).failoverVariant != null) ? featuresMap.get(featureKey).failoverVariant : Variant.off; FeatureControl control = featureControlCache.get(featureKey); if (!offline && !featureControlStreamClient.initialized()) { logger.warn("FeatureFlow is not initialized yet."); } if (control == null) { logger.warn("Feature " + featureKey + " does not exist, returning failover variant of " + failoverVariant); return failoverVariant; } //add featureflow.context addAdditionalAttributes(user); String variant = control.evaluate(user); return variant; } private void addAdditionalAttributes(FeatureflowUser user) { user.getAttributes().put(FeatureflowUser.FEATUREFLOW_USER_ID, new JsonPrimitive(user.getId())); //this will be removed (we use the id value) user.getSessionAttributes().put(FeatureflowUser.FEATUREFLOW_HOUROFDAY, new JsonPrimitive(LocalTime.now().getHour())); user.getSessionAttributes().put(FeatureflowUser.FEATUREFLOW_DATE, new JsonPrimitive(FeatureflowUser.toIso(new DateTime()))); } public void close() throws IOException { this.eventHandler.close(); } public static Builder builder(String apiKey) { return new FeatureflowClient.Builder(apiKey); } public void track(String goalKey, FeatureflowUser user) { eventHandler.queueEvent(new Event(goalKey, user, evaluateAll(user))); } public static class Builder { private FeatureflowConfig config = null; private String apiKey; private Map<CallbackEvent, List<FeatureControlCallbackHandler>> featureControlCallbackHandlers = new HashMap<>(); private FeatureflowUserProvider userProvider; private FeatureflowUserLookupProvider userLookupProvider; private List<Feature> features = new ArrayList<>(); private boolean offline = false; //put there rather than configuration for convenience public Builder(String apiKey) { this.apiKey = apiKey; } public Builder withOffline(boolean offline) { this.offline = offline; return this; } public Builder withUpdateCallback(FeatureControlCallbackHandler featureControlCallbackHandler) { this.withCallback(CallbackEvent.UPDATED_FEATURE, featureControlCallbackHandler); return this; } public Builder withDeleteCallback(FeatureControlCallbackHandler featureControlCallbackHandler) { this.withCallback(CallbackEvent.DELETED_FEATURE, featureControlCallbackHandler); return this; } public Builder withCallback(CallbackEvent event, FeatureControlCallbackHandler featureControlCallbackHandler) { if (featureControlCallbackHandlers.get(event) == null) { featureControlCallbackHandlers.put(event, new ArrayList<>()); } this.featureControlCallbackHandlers.get(event).add(featureControlCallbackHandler); return this; } public Builder withUserProvider(FeatureflowUserProvider userProvider) { this.userProvider = userProvider; return this; } public Builder withUserLookupProvider(FeatureflowUserLookupProvider userLookupProvider) { this.userLookupProvider = userLookupProvider; return this; } public Builder withConfig(FeatureflowConfig config) { this.config = config; return this; } public Builder withFeature(Feature feature) { this.features.add(feature); return this; } public Builder withFeatures(List<Feature> features) { this.features = features; return this; } public FeatureflowClient build() { if (config == null) { config = new FeatureflowConfig.Builder().build(); } return new FeatureflowClient(apiKey, features, config, featureControlCallbackHandlers, userProvider, userLookupProvider, offline); } } public class Evaluate { private final String evaluateResult; private final String featureKey; private final FeatureflowUser user; private final FeatureflowClient client; Evaluate(FeatureflowClient featureflowClient, String featureKey, FeatureflowUser user) { this.featureKey = featureKey; this.user = user; this.evaluateResult = featureflowClient.eval(featureKey, user); this.client = featureflowClient; } Evaluate(FeatureflowClient featureflowClient, String featureKey, String userId) { this.featureKey = featureKey; this.user = userProvider != null ? userProvider.getUser() : userLookupProvider != null && userId != null ? userLookupProvider.getUser(userId) : new FeatureflowUser(userId); this.client = featureflowClient; this.evaluateResult = featureflowClient.eval(featureKey, user); } public boolean isOn() { return is(Variant.on); } public boolean isOff() { return is(Variant.off); } public boolean is(String variant) { if (!client.offline) eventHandler.queueEvent(new Event(featureKey, Event.EVALUATE_EVENT, user, evaluateResult, variant)); return variant.equals(evaluateResult); } public String value() { if (!client.offline) eventHandler.queueEvent(new Event(featureKey, Event.EVALUATE_EVENT, user, evaluateResult, null)); return evaluateResult; } } }
package io.hops.kafka; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.Schedule; import javax.ejb.Singleton; import javax.ejb.Timer; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import kafka.admin.AdminUtils; import kafka.common.TopicAlreadyMarkedForDeletionException; import kafka.utils.ZKStringSerializer$; import kafka.utils.ZkUtils; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.ZkConnection; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import se.kth.hopsworks.rest.AppException; import se.kth.hopsworks.util.Settings; @Singleton public class ZookeeprTopicCleanerTimer { private final static Logger LOGGER = Logger.getLogger(KafkaFacade.class.getName()); public final int connectionTimeout = 30 * 1000;// 30 seconds public int sessionTimeoutMs = 30 * 1000;//30 seconds @PersistenceContext(unitName = "kthfsPU") private EntityManager em; @EJB Settings settings; @EJB KafkaFacade kafkaFacade; ZkClient zkClient = null; ZkConnection zkConnection; @Schedule(persistent = false, second = "*/10", minute = "*", hour = "*") public void execute(Timer timer) { Set<String> zkTopics = new HashSet<>(); try { ZooKeeper zk = new ZooKeeper(settings.getZkConnectStr(), sessionTimeoutMs, new ZookeeperWatcher()); List<String> topics = zk.getChildren("/brokers/topics", false); zkTopics.addAll(topics); zk.close(); }catch (IOException ex) { LOGGER.log(Level.SEVERE, "Unable to find the zookeeper server: ", ex.toString()); } catch (KeeperException | InterruptedException ex) { LOGGER.log(Level.SEVERE, "Cannot retrieve topic list from Zookeeper", ex.toString()); } List<ProjectTopics> dbProjectTopics = em.createNamedQuery( "ProjectTopics.findAll").getResultList(); Set<String> dbTopics = new HashSet<>(); for (ProjectTopics pt : dbProjectTopics) { try { dbTopics.add(pt.getProjectTopicsPK().getTopicName()); } catch (UnsupportedOperationException e) { LOGGER.log(Level.SEVERE, e.toString()); } } /* To remove topics from zookeeper which do not exist in database. This situation happens when a hopsworks project is deleted, because all the topics in the project will be deleted (casecade delete) without deleting them from the Kafka cluster. 1. get all topics from zookeeper 2. get the topics which exist in zookeeper, but not in database zkTopics.removeAll(dbTopics); 3. remove those topics */ if (!zkTopics.isEmpty()) { zkTopics.removeAll(dbTopics); for (String topicName : zkTopics) { try { if (zkClient == null) { zkClient = new ZkClient(kafkaFacade.getIp(settings.getZkConnectStr()).getHostName(), sessionTimeoutMs, connectionTimeout, ZKStringSerializer$.MODULE$); } } catch (AppException ex) { LOGGER.log(Level.SEVERE, "Unable to get zookeeper ip address ", ex.toString()); } if (zkConnection == null) { zkConnection = new ZkConnection(settings.getZkConnectStr()); } ZkUtils zkUtils = new ZkUtils(zkClient, zkConnection, false); try { AdminUtils.deleteTopic(zkUtils, topicName); LOGGER.log(Level.INFO, "{0} is removed from Zookeeper", new Object[]{topicName}); } catch (TopicAlreadyMarkedForDeletionException ex) { LOGGER.log(Level.INFO, "{0} is already marked for deletion", new Object[]{topicName}); } } } } private class ZookeeperWatcher implements Watcher{ @Override public void process(WatchedEvent we) { LOGGER.log(Level.INFO, ""); } } }
package io.vertx.lang.groovy; import io.vertx.codegen.ClassKind; import io.vertx.codegen.TypeInfo; import io.vertx.codetrans.CodeTranslator; import io.vertx.codetrans.lang.groovy.GroovyLang; import io.vertx.docgen.Coordinate; import io.vertx.docgen.DocGenerator; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeMirror; import java.util.List; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class GroovyDocGenerator implements DocGenerator { private TypeInfo.Factory factory; private CodeTranslator translator; private ProcessingEnvironment env; @Override public void init(ProcessingEnvironment processingEnv) { factory = new TypeInfo.Factory(processingEnv.getElementUtils(), processingEnv.getTypeUtils()); translator = new CodeTranslator(processingEnv); env = processingEnv; } @Override public String getName() { return "groovy"; } @Override public String renderSource(ExecutableElement elt, String source) { GroovyLang lang = new GroovyLang(); try { return translator.translate(elt, lang); } catch (Exception e) { System.out.println("Cannot generate " + elt.getEnclosingElement().getSimpleName() + "#" + elt.getSimpleName() + " : " + e.getMessage()); return "Code not translatable"; } } @Override public String resolveTypeLink(TypeElement elt, Coordinate coordinate) { TypeInfo type = null; try { type = factory.create(elt.asType()); } catch (Exception e) { System.out.println("Could not resolve doc link for type " + elt.getQualifiedName()); return null; } if (type.getKind() == ClassKind.DATA_OBJECT) { String baselink; if (coordinate == null) { baselink = "../"; } else { baselink = "../../" + coordinate.getArtifactId() + "/"; } return baselink + "cheatsheet/" + elt.getSimpleName().toString() + ".html"; } if (type.getKind() == ClassKind.API) { String baselink = ""; if (coordinate != null) { baselink = "../../" + coordinate.getArtifactId() + "/groovy/"; } TypeInfo.Class.Api api = (TypeInfo.Class.Api) type.getRaw(); return baselink + "groovydoc/" + api.translateName("groovy").replace('.', '/') + ".html"; } return null; } @Override public String resolveMethodLink(ExecutableElement elt, Coordinate coordinate) { TypeElement typeElt = (TypeElement) elt.getEnclosingElement(); String link = resolveTypeLink(typeElt, coordinate); if (link != null) { if (link.contains("cheatsheet")) { link = link + '#' + java.beans.Introspector.decapitalize(elt.getSimpleName().toString().substring(3)); } else { String anchor = '#' + elt.getSimpleName().toString() + "("; TypeMirror type = elt.asType(); ExecutableType methodType = (ExecutableType) env.getTypeUtils().erasure(type); List<? extends TypeMirror> parameterTypes = methodType.getParameterTypes(); for (int i = 0;i < parameterTypes.size();i++) { if (i > 0) { anchor += ",%20"; } anchor += parameterTypes.get(i).toString(); } anchor += ')'; link = link + anchor; } } return link; } @Override public String resolveLabel(Element elt, String defaultLabel) { if (elt.getKind() == ElementKind.METHOD) { TypeInfo type = factory.create(elt.getEnclosingElement().asType()); if (type.getKind() == ClassKind.DATA_OBJECT) { String name = elt.getSimpleName().toString(); if (name.startsWith("set") && name.length() > 3 && Character.isUpperCase(name.charAt(3))) { name = java.beans.Introspector.decapitalize(name.substring(3)); } return name; } } return defaultLabel; } @Override public String resolveConstructorLink(ExecutableElement elt, Coordinate coordinate) { return "todo"; } @Override public String resolveFieldLink(VariableElement elt, Coordinate coordinate) { return "todo"; } }
package me.coley.recaf.parse.bytecode; import me.coley.recaf.Recaf; import me.coley.recaf.parse.bytecode.ast.*; import me.coley.recaf.util.TypeUtil; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import org.objectweb.asm.tree.analysis.Frame; import java.util.*; import static org.objectweb.asm.Opcodes.*; /** * Variable analysis. * * @author Matt */ public class Variables { private final Map<String, Integer> nameToIndex = new HashMap<>(); private final Map<Integer, Integer> indexToSort = new HashMap<>(); private final Map<String, String> nameToDesc = new HashMap<>(); private final Map<String, String> nameToStart = new HashMap<>(); private final Map<String, String> nameToEnd = new HashMap<>(); private int lastArgIndex = -1; private int next; private int maxIndex; /** * @param isStatic * Is the method static or not. * @param currentType * Internal name of declaring class. */ Variables(boolean isStatic, String currentType) { // Add "this" for instance methods if(!isStatic) { nameToIndex.put("this", 0); nameToIndex.put("0", 0); nameToDesc.put("this", "L" + currentType + ";"); nameToDesc.put("0", "L" + currentType + ";"); indexToSort.put(0, Type.OBJECT); setNext(next + 1); } } /** * @param root * AST root. * * @return Map of variable names to the variable instances. * * @throws AssemblerException * When fetching type-information from an instruction fails.<br> * Or when variables cannot fetch label information. */ void visit(RootAST root) throws AssemblerException { // Method descriptor // - contains explicit types & names // - highest priority due to being part of the method definition for(DefinitionArgAST arg : root.search(DefinitionArgAST.class)) { String name = arg.getVariableName().getName(); Type type = Type.getType(arg.getDesc().getDesc()); // Populate int index = next; nameToIndex.put(name, index); indexToSort.put(index, type.getSort()); nameToDesc.put(name, type.getDescriptor()); lastArgIndex = index; // Update next index setNext(index + getNextVarIncrement(index, type.getSize())); } // Variable instructions (VarInsnNode/IincInsnNode) // Pass 1: Add data for raw-index variables for(VariableReference ast : root.search(VariableReference.class)) { String name = ast.getVariableName().getName(); if(!name.matches("\\d+") || nameToIndex.containsKey(name)) continue; int index = Integer.parseInt(name); addVariable(ast, root, index); // Ensure "next" accounts for any taken indices fitNext(); } // Pass 2: Add data for named variables for(VariableReference ast : root.search(VariableReference.class)) { String name = ast.getVariableName().getName(); if(nameToIndex.containsKey(name)) continue; int index = next; addVariable(ast, root, index); // Update next var position int size = TypeUtil.sortToSize(indexToSort.get(index)); setNext(index + getNextVarIncrement(index, size)); } // Figure out variable types that for local variables // Figure out the label ranges where variables apply findRanges(root); // Create the variable nodes } /** * Fills missing index-to-descriptor mappings. * * @param labels * Map of label names to instances. * @param frames * Stack-frame analysis data. * * @throws AssemblerException * When multiple types for a single variable have conflicting array-levels. */ void visitWithFrames(Frame<RValue>[] frames, Map<String, LabelNode> labels) throws AssemblerException { // TODO: Reuse variable slots of the same sort if the scope of the variables do not collide for(Map.Entry<String, Integer> entry : nameToIndex.entrySet()) { // Skip already visitied String name = entry.getKey(); String startName = nameToStart.get(name); String endName = nameToEnd.get(name); LabelNode start = labels.get(startName); LabelNode end = labels.get(endName); if (start == null || end == null) continue; // Collect the types stored in this index Set<Type> types = new HashSet<>(); int index = entry.getValue(); for(Frame<RValue> frame : frames) { if(frame == null) continue; RValue value = frame.getLocal(index); if(value != null && value.getType() != null) types.add(value.getType()); } Iterator<Type> it = types.iterator(); // If we don't have type information, abort for this index if (!it.hasNext()) continue; Type last = it.next(); int arrayLevel = TypeUtil.getArrayDepth(last); while (it.hasNext()) { int lastArrayLevel = TypeUtil.getArrayDepth(last); Type type1 = it.next(); if (lastArrayLevel != TypeUtil.getArrayDepth(type1)) { // TODO: See above TODO about variable index re-use // - The problem here is this logic assumes no index re-use... // - This should throw an exception later, but for now // we just pretend the variable is an object (since everything is) last = Type.getObjectType("java/lang/Object"); break; //throw new VerifierException("Stored multiple array sizes in same variable slot: " + index); } if (last.equals(type1)) continue; if(Recaf.getCurrentWorkspace() != null) last = Type.getObjectType(Recaf.getCurrentWorkspace().getHierarchyGraph() .getCommon(last.getElementType().getInternalName(), type1.getElementType().getInternalName())); else break; } // Save type StringBuilder arr = new StringBuilder(); for(int i = 0; i < arrayLevel; i++) arr.append('['); // TODO: Boolean is saved as int, which is technically correct but not expected by most users // - Sort is saved as INTEGER because we don't analyze difference between int/bool cases if (last.getSort() < Type.ARRAY) nameToDesc.put(name, arr.toString() + last.getDescriptor()); else nameToDesc.put(name, arr.toString() + "L" + last.getInternalName() + ";"); } } /** * @param labels * Map of label names to instances. * * @return Map of variable names to the variable instances. */ List<LocalVariableNode> getVariables(Map<String, LabelNode> labels) { // TODO: Reuse variable slots of the same sort if the scope of the variables do not collide List<LocalVariableNode> vars = new ArrayList<>(); boolean addedThis = false; // Variables of given indices can be reused (usually given different names per use) // And sometimes there are just portions of code that don't have debug info. // - This seems to be correct... for(Map.Entry<String, Integer> entry : nameToIndex.entrySet()) { String name = entry.getKey(); int index = entry.getValue(); if (index == 0 && nameToIndex.containsKey("this")) name = "this"; if(name.equals("this")) { if(addedThis) continue; addedThis = true; } String desc = nameToDesc.get(name); if(desc == null) continue; String startName = nameToStart.get(name); String endName = nameToEnd.get(name); LabelNode start = labels.get(startName); LabelNode end = labels.get(endName); if(start == null || end == null) continue; vars.add(new LocalVariableNode(name, desc, null, start, end, index)); } vars.sort(Comparator.comparingInt(lvn -> lvn.index)); return vars; } /** * Moves {@link #next} forward to the next unused spot. */ private void fitNext() { while(nameToIndex.containsValue(next)) { int size = TypeUtil.sortToSize(indexToSort.get(next)); next += size; } } /** * Find starting and ending labels for each variable. * * @param root * Root AST. * * @throws AssemblerException * When a variable could not find a label pair to associate its range with. */ private void findRanges(RootAST root) throws AssemblerException { List<LabelAST> labels = root.search(LabelAST.class); if (labels.isEmpty()) return; // Arguments: (index <= lastArgIndex) // - this - entire range // - args - entire range for(Integer index : indexToSort.keySet()) { if (index <= lastArgIndex) { Optional<String> x = nameToIndex.entrySet().stream() .filter(e -> e.getValue().equals(index)) .map(Map.Entry::getKey) .findFirst(); if (!x.isPresent()) throw new AssemblerException("Failed to find index->name map for: " + index); String name = x.get(); nameToStart.put(name, labels.get(0).getName().getName()); nameToEnd.put(name, labels.get(labels.size() - 1).getName().getName()); } } // Locals: // - Start = first label above reference // - End = first label after last reference for(VariableReference ast : root.search(VariableReference.class)) { // Skip non-instructions if(!(ast instanceof Instruction)) continue; String name = ast.getVariableName().getName(); int line = ((AST)ast).getLine(); // Skip already matched variables if(nameToEnd.containsKey(name)) continue; // Find start - first label before this declaration AST start = (AST) ast; do { start = start.getPrev(); } while(start != null && !(start instanceof LabelAST)); if(start == null) throw new AssemblerException("Failed to find start label for variable: " + name, line); // Find end - first label after the last time this variable is referenced AST end = (AST) ast; AST marker = end; do { marker = marker.getNext(); if(marker instanceof LabelAST) end = marker; else if(marker instanceof VariableReference) { // Nullify the "end" since the variable has been referenced again. // The next label will be the end. String markerVName = ((VariableReference) marker).getVariableName().getName(); if(markerVName.equals(name)) end = null; } } while(marker != null); if(end == null) throw new AssemblerException("Failed to find end label for variable: " + name, line); // Update maps nameToStart.put(name, ((LabelAST) start).getName().getName()); nameToEnd.put(name, ((LabelAST) end).getName().getName()); } } /** * Handle adding the variable to the maps. * * @param ast * AST containing variable. * @param root * Root of AST. * @param index * Index to add variable to. * * @throws AssemblerException * When fetching type information from the var-reference fails. */ private void addVariable(VariableReference ast, RootAST root, int index) throws AssemblerException { String name = ast.getVariableName().getName(); // Fetch type information int sort = -1; if(ast instanceof Instruction) sort = getType(((Instruction) ast).getOpcode().getOpcode()); else if(ast instanceof DefinitionArgAST) { String desc = ((DefinitionArgAST) ast).getDesc().getDesc(); sort = Type.getType(desc).getSort(); } if(sort == -1) { int line = ((AST)ast).getLine(); throw new AssemblerException("Unknown variable type: " + ast, line); } // Update maps int used = index + TypeUtil.sortToSize(sort); if (used > maxIndex) maxIndex = used; nameToIndex.put(name, index); indexToSort.put(index, sort); if (sort >= Type.BOOLEAN && sort <= Type.DOUBLE) nameToDesc.put(name, sortToDesc(sort)); } /** * Finds the increment needed to fit the next variable slot. Will skip already used values. * * @param current * Current variable index, without increment. * @param size * Size of variable just discovered. * * @return Variable increment amount. */ private int getNextVarIncrement(int current, int size) { int temp = current + size; // Prevent a named variable from taking the place of an existing indexed variable while (indexToSort.containsKey(temp)) { int sort = indexToSort.get(temp); temp += TypeUtil.sortToSize(sort); } return temp - current; } /** * @param name * Variable name. * * @return Index. * * @throws AssemblerException * When index lookup fails. */ public int getIndex(String name) throws AssemblerException { try { return nameToIndex.get(name); } catch(Exception ex) { throw new AssemblerException("Failed to fetch index of: " + name); } } /** * @return Max used locals. */ public int getMax() { return maxIndex; } private void setNext(int next) { this.next = next; if (next > maxIndex) maxIndex = next; } /** * @param opcode * Var opcode. * * @return Type derived from the opcode. * * @throws AssemblerException * When the opcode is not supported. */ private static int getType(int opcode) throws AssemblerException { int type = -1; switch(opcode) { case ALOAD: case ASTORE: type = Type.OBJECT; break; case IINC: case ILOAD: case ISTORE: type = Type.INT; break; case FLOAD: case FSTORE: type = Type.FLOAT; break; case DLOAD: case DSTORE: type = Type.DOUBLE; break; case LLOAD: case LSTORE: type = Type.LONG; break; default: throw new AssemblerException("Unsupported opcode for variable reference: " + opcode); } return type; } /** * @param sort * Type sort<i>(kind)</i> * * @return Descriptor of primitive type. * * @throws AssemblerException * When the type is not a primitive. */ private static String sortToDesc(int sort) throws AssemblerException { switch(sort) { case Type.INT: return "I"; case Type.SHORT: return "S"; case Type.CHAR: return "C"; case Type.BYTE: return "B"; case Type.LONG: return "J"; case Type.FLOAT: return "F"; case Type.DOUBLE: return "D"; case Type.BOOLEAN: return "Z"; default: throw new AssemblerException("Unsupported"); } } }
package me.newyith.fortress.main; import me.newyith.fortress.command.Commands; import me.newyith.fortress.event.EventListener; import me.newyith.fortress.event.TickTimer; import me.newyith.fortress.fix.PearlGlitchFix; import me.newyith.fortress.manual.ManualCraftManager; import me.newyith.fortress.sandbox.jackson.SandboxSaveLoadManager; import me.newyith.fortress.util.Debug; import me.newyith.fortress.util.Point; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.Random; public class FortressPlugin extends JavaPlugin { public static final boolean releaseBuild = false; //TODO: change this to true for release builds private static final double saveDelayMs = 60*1000; private static int saveWaitTicks = 0; private static FortressPlugin instance; private static SaveLoadManager saveLoadManager; private static SandboxSaveLoadManager sandboxSaveLoadManager; public static int config_glowstoneDustBurnTimeMs = 1000 * 60 * 60; public static int config_stuckDelayMs = 30 * 1000; public static int config_stuckCancelDistance = 4; public static int config_generationRangeLimit = 128; public static int config_generationBlockLimit = 40000; //roughly 125 empty 8x8x8 rooms (6x6x6 air inside) private void loadConfig() { FileConfiguration config = getConfig(); if (releaseBuild) { config_glowstoneDustBurnTimeMs = getConfigInt(config, "glowstoneDustBurnTimeMs", config_glowstoneDustBurnTimeMs); config_stuckDelayMs = getConfigInt(config, "stuckDelayMs", config_stuckDelayMs); config_stuckCancelDistance = getConfigInt(config, "stuckCancelDistance", config_stuckCancelDistance); config_generationRangeLimit = getConfigInt(config, "generationRangeLimit", config_generationRangeLimit); config_generationBlockLimit = getConfigInt(config, "generationBlockLimit", config_generationBlockLimit); } saveConfig(); } private int getConfigInt(FileConfiguration config, String key, int defaultValue) { if (!config.isInt(key)) { config.set(key, defaultValue); } return config.getInt(key); } @Override public void onEnable() { instance = this; loadConfig(); saveLoadManager = new SaveLoadManager(this); saveLoadManager.load(); if (!releaseBuild) { sandboxSaveLoadManager = new SandboxSaveLoadManager(this); // sandboxSaveLoadManager.load(); } EventListener.onEnable(this); TickTimer.onEnable(this); ManualCraftManager.onEnable(this); PearlGlitchFix.onEnable(this); sendToConsole("%%%%%%%%%%%%%%%%%%%%%%%%%%%%", ChatColor.RED); sendToConsole(">> Fortress Plugin <<", ChatColor.GOLD); sendToConsole(" >> ON << ", ChatColor.GREEN); sendToConsole("%%%%%%%%%%%%%%%%%%%%%%%%%%%%", ChatColor.RED); } @Override public void onDisable() { saveLoadManager.save(); if (!releaseBuild) { // sandboxSaveLoadManager.save(); } sendToConsole("%%%%%%%%%%%%%%%%%%%%%%%%%%%%", ChatColor.RED); sendToConsole(">> Fortress Plugin <<", ChatColor.GOLD); sendToConsole(" >> OFF << ", ChatColor.RED); sendToConsole("%%%%%%%%%%%%%%%%%%%%%%%%%%%%", ChatColor.RED); } private void sendToConsole(String s, ChatColor color) { ConsoleCommandSender console = this.getServer().getConsoleSender(); console.sendMessage(color + s); } public static void onTick() { if (saveWaitTicks == 0) { // saveLoadManager.save(); //TODO: uncomment out this line later (or decide not to save periodically) saveWaitTicks = (int) (saveDelayMs / TickTimer.msPerTick); } else { saveWaitTicks } } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { String commandName = cmd.getName(); boolean commandHandled = false; // /stuck if (commandName.equalsIgnoreCase("stuck") && sender instanceof Player) { Player player = (Player)sender; Commands.onStuckCommand(player); commandHandled = true; } // /fort [subCommand] if (commandName.equalsIgnoreCase("fort") && args.length > 0 && sender instanceof Player) { String subCommand = args[0]; // /fort stuck if (subCommand.equalsIgnoreCase("stuck")) { Player player = (Player)sender; Commands.onStuckCommand(player); commandHandled = true; } } if (!releaseBuild) { // /test if (cmd.getName().equalsIgnoreCase("test")) { if (sender instanceof Player) { Debug.msg("executing test command..."); /*/ //*/ /* /fort stuck /fort home /fort info [teamColor?] (display owner, teamColor, ally teamColors) /fort list (display team members starting with owner) /fort leave /fort join [teamColor?] (example: '/fort join green3') if (teamColor specified) try to join team (player must be on base white list of the generator claiming that team color) else display list of teamColors (if any teams have invited the player) Note: To kick, remove name from base sign TODO: remove home and key runes */ //TODO: make /stuck only work within generation range of a generator //TODO: change rune pattern to alternate 3x2x1 -ish rune pattern //TODO: make rune pattern ignore air points in pattern (maybe make '*' mean any block material?) //TODO: write manual book //TODO: add potentialAlteredPoints and update + re-save it before generation (to make it robust enough to handle server crashes) // then onEnable look through potentialAlteredPoints and unalter where point not found among generated points // then test killing the server (ctrl+c not "stop") and make sure plugin is robust enough to handle it //TODO: make generation display wave of particle to indicate generating wall blocks // onProtectBlock, show particles appearing for a few seconds at random points on all faces not touching solid block // maybe use nether particle but make the nether particle be drawn toward center of block (like the particles are drawn to nether portal) //TODO: allow chest / redstone to be swapped and have rune remain valid //TODO: instead of breaking generator when redstone is cycled too quickly, just ignore changes to redstone power for 1 second after a change? //TODO: add emergency key rune //TODO: add disruptor rune //low priority: //TODO: consider making Point immutable (final) //TODO: refactor to use the listener pattern? //TODO: in Wall class and other places its used: rename wallMaterials to traverseMaterials //TODO: consider making mossy cobblestone be generated but not transmit generation to anything except mossy //TODO: consider making rune activation require an empty hand //TODO: consider making creating rune require empty hand (again) //TODO: make glowstone blocks work as fuel for 4x the fuel value of glowstone dust (silk touch works on glowstone block and fortune III does not) //*/ /* pistonCores should respect even its parent generator's claims pistonCores should respect other pistonCores' claims other generatorCores' claimed points including their pistonCores' claims and also any other pistonCores belonging to parent generator pistonCore's wallMaterials should be based on parent generator's wallMaterials on piston added to claimedWallPoints: create new PistonCore on piston removed from claimedWallPoints: break pistonCore on generator broken: break all its pistonCores pistonCore: onExtend: if (parent generator is running) if (piston protected || piston extended to touch protected) tell pistonCore to generate onRetract: tell pistonCore to degenerate generatorCore: onProtectPiston, onProtectPistonExtensionTouchPoint: set pistonCore.layerIndex if (extended) tell pistonCore to generate onGenerate: for each pistonCore if (pistonCore is protected) tell pistonCore to generate onDegenerate: include child pistonCores' generated use pistonCore.layerIndex to merge piston's generated with generator's generated maybe instead of requiring piston be protected before it can work as a mini generator just require that a pistonCore has been created also create pistonCore if block piston is extended to touch is generated */ //for beginning for post on bukkit.org once I'm ready to release: //*/
package mil.nga.geopackage.io; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DecimalFormat; import java.util.logging.Level; import java.util.logging.Logger; /** * Input / Output utility methods * * @author osbornb */ public class GeoPackageIOUtils { /** * Logger */ private static final Logger logger = Logger .getLogger(GeoPackageIOUtils.class.getName()); /** * Get the file extension * * @param file * file * @return extension */ public static String getFileExtension(File file) { String fileName = file.getName(); String extension = null; int extensionIndex = fileName.lastIndexOf("."); if (extensionIndex > -1) { extension = fileName.substring(extensionIndex + 1); } return extension; } /** * Check if the file has an extension * * @param file * file * @return true if has extension * @since 3.0.2 */ public static boolean hasFileExtension(File file) { return getFileExtension(file) != null; } /** * Add a the file extension to the file * * @param file * file * @param extension * file extension * @return new file with extension * @since 3.0.2 */ public static File addFileExtension(File file, String extension) { return new File(file.getAbsolutePath() + "." + extension); } /** * Get the file name with the extension removed * * @param file * file * @return file name */ public static String getFileNameWithoutExtension(File file) { String name = file.getName(); int extensionIndex = name.lastIndexOf("."); if (extensionIndex > -1) { name = name.substring(0, extensionIndex); } return name; } /** * Copy a file to a file location * * @param copyFrom * from file * @param copyTo * to file * @throws IOException * upon failure */ public static void copyFile(File copyFrom, File copyTo) throws IOException { InputStream from = new FileInputStream(copyFrom); OutputStream to = new FileOutputStream(copyTo); copyStream(from, to); } /** * Copy an input stream to a file location * * @param copyFrom * from file * @param copyTo * to file * @throws IOException * upon failure */ public static void copyStream(InputStream copyFrom, File copyTo) throws IOException { copyStream(copyFrom, copyTo, null); } /** * Copy an input stream to a file location * * @param copyFrom * from file * @param copyTo * to file * @param progress * progress tracker * @throws IOException * upon failure */ public static void copyStream(InputStream copyFrom, File copyTo, GeoPackageProgress progress) throws IOException { OutputStream to = new FileOutputStream(copyTo); copyStream(copyFrom, to, progress); // Try to delete the file if progress was cancelled if (progress != null && !progress.isActive() && progress.cleanupOnCancel()) { copyTo.delete(); } } /** * Get the file bytes * * @param file * input file * @return file bytes * @throws IOException * upon failure */ public static byte[] fileBytes(File file) throws IOException { FileInputStream fis = new FileInputStream(file); return streamBytes(fis); } /** * Get the stream bytes * * @param stream * input stream * @return stream bytes * @throws IOException * upon failure */ public static byte[] streamBytes(InputStream stream) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); copyStream(stream, bytes); return bytes.toByteArray(); } /** * Copy an input stream to an output stream * * @param copyFrom * from stream * @param copyTo * to stream * @throws IOException * upon failure */ public static void copyStream(InputStream copyFrom, OutputStream copyTo) throws IOException { copyStream(copyFrom, copyTo, null); } /** * Copy an input stream to an output stream * * @param copyFrom * from stream * @param copyTo * to stream * @param progress * progress tracker * @throws IOException * upon failure */ public static void copyStream(InputStream copyFrom, OutputStream copyTo, GeoPackageProgress progress) throws IOException { try { byte[] buffer = new byte[1024]; int length; while ((progress == null || progress.isActive()) && (length = copyFrom.read(buffer)) > 0) { copyTo.write(buffer, 0, length); if (progress != null) { progress.addProgress(length); } } copyTo.flush(); } finally { closeQuietly(copyTo); closeQuietly(copyFrom); } } /** * Format the bytes into readable text * * @param bytes * bytes * @return bytes text */ public static String formatBytes(long bytes) { double value = bytes; String unit = "B"; if (bytes >= 1024) { int exponent = (int) (Math.log(bytes) / Math.log(1024)); exponent = Math.min(exponent, 4); switch (exponent) { case 1: unit = "KB"; break; case 2: unit = "MB"; break; case 3: unit = "GB"; break; case 4: unit = "TB"; break; } value = bytes / Math.pow(1024, exponent); } DecimalFormat df = new DecimalFormat(" return df.format(value) + " " + unit; } /** * Close the closeable quietly * * @param closeable * closeable (stream, etc) * @since 2.0.2 */ public static void closeQuietly(Closeable closeable) { try { closeable.close(); } catch (IOException e) { logger.log(Level.WARNING, "Failed to close closeable", e); } } }
package net.engio.mbassy.bus; import net.engio.mbassy.bus.common.DeadMessage; import net.engio.mbassy.bus.common.FilteredMessage; import net.engio.mbassy.subscription.Subscription; import java.util.Collection; public class MessagePublication implements IMessagePublication { private final Collection<Subscription> subscriptions; private final Object message; // message publications can be referenced by multiple threads to query publication progress private volatile State state = State.Initial; private volatile boolean delivered = false; private final BusRuntime runtime; protected MessagePublication(BusRuntime runtime, Collection<Subscription> subscriptions, Object message, State initialState) { this.runtime = runtime; this.subscriptions = subscriptions; this.message = message; this.state = initialState; } public boolean add(Subscription subscription) { return subscriptions.add(subscription); } /* TODO: document state transitions */ public void execute() { state = State.Running; for (Subscription sub : subscriptions) { sub.publish(this, message); } state = State.Finished; // if the message has not been marked delivered by the dispatcher if (!delivered) { if (!isFilteredEvent() && !isDeadEvent()) { runtime.getProvider().publish(new FilteredMessage(message)); } else if (!isDeadEvent()) { runtime.getProvider().publish(new DeadMessage(message)); } } } public boolean isFinished() { return state.equals(State.Finished); } public boolean isRunning() { return state.equals(State.Running); } public boolean isScheduled() { return state.equals(State.Scheduled); } public void markDelivered() { delivered = true; } public MessagePublication markScheduled() { if (state.equals(State.Initial)) { state = State.Scheduled; } return this; } public boolean isDeadEvent() { return DeadMessage.class.equals(message.getClass()); } public boolean isFilteredEvent() { return FilteredMessage.class.equals(message.getClass()); } public Object getMessage() { return message; } private enum State { Initial, Scheduled, Running, Finished, Error } public static class Factory { public IMessagePublication createPublication(BusRuntime runtime, Collection<Subscription> subscriptions, Object message) { return new MessagePublication(runtime, subscriptions, message, State.Initial); } } }
package net.openhft.chronicle.map; import net.openhft.chronicle.hash.impl.util.BuildVersion; import net.openhft.chronicle.hash.replication.ConnectionListener; import net.openhft.chronicle.hash.replication.RemoteNodeValidator; import net.openhft.chronicle.hash.replication.TcpTransportAndNetworkConfig; import net.openhft.chronicle.hash.replication.ThrottlingConfig; import net.openhft.lang.collection.ATSDirectBitSet; import net.openhft.lang.collection.DirectBitSet; import net.openhft.lang.io.ByteBufferBytes; import net.openhft.lang.io.Bytes; import net.openhft.lang.io.DirectStore; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.net.*; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.*; import java.util.BitSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import static java.nio.channels.SelectionKey.*; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static net.openhft.chronicle.hash.impl.util.BuildVersion.version; import static net.openhft.lang.MemoryUnit.*; interface Work { /** * @param in the buffer that we will fill up * @return true when all the work is complete */ boolean doWork(@NotNull Bytes in); } /** * Used with a {@link net.openhft.chronicle.map.ReplicatedChronicleMap} to send data between the * maps using a socket connection {@link net.openhft.chronicle.map.TcpReplicator} * * @author Rob Austin. */ public final class TcpReplicator<K, V> extends AbstractChannelReplicator implements Closeable { public static final long TIMESTAMP_FACTOR = 10000; private static final int STATELESS_CLIENT = -127; private static final byte HEARTBEAT = 0; private static final byte NOT_SET = 0;//(byte) HEARTBEAT.ordinal(); private static final Logger LOG = LoggerFactory.getLogger(TcpReplicator.class.getName()); private static final int BUFFER_SIZE = 0x100000; // 1MB public static final long SPIN_LOOP_TIME_IN_NONOSECONDS = TimeUnit.MICROSECONDS.toNanos(500); private final SelectionKey[] selectionKeysStore = new SelectionKey[Byte.MAX_VALUE + 1]; // used to instruct the selector thread to set OP_WRITE on a key correlated by the bit index // in the bitset private final KeyInterestUpdater opWriteUpdater = new KeyInterestUpdater(OP_WRITE, selectionKeysStore); private final BitSet activeKeys = new BitSet(selectionKeysStore.length); private final long heartBeatIntervalMillis; private final ConnectionListener connectionListener; private long largestEntrySoFar = 128; @NotNull private final Replica replica; private final byte localIdentifier; @NotNull private final Replica.EntryExternalizable externalizable; @NotNull private final TcpTransportAndNetworkConfig replicationConfig; private final @Nullable RemoteNodeValidator remoteNodeValidator; private final String name; private long selectorTimeout; enum State { CONNECTED, DISCONNECTED; } /** * @throws IOException on an io error. */ public TcpReplicator(@NotNull final Replica replica, @NotNull final Replica.EntryExternalizable externalizable, @NotNull final TcpTransportAndNetworkConfig replicationConfig, @Nullable final RemoteNodeValidator remoteNodeValidator, String name, @Nullable final ConnectionListener connectionListener) throws IOException { super("TcpSocketReplicator-" + replica.identifier(), replicationConfig.throttlingConfig()); final ThrottlingConfig throttlingConfig = replicationConfig.throttlingConfig(); long throttleBucketInterval = throttlingConfig.bucketInterval(MILLISECONDS); heartBeatIntervalMillis = replicationConfig.heartBeatInterval(MILLISECONDS); selectorTimeout = Math.min(heartBeatIntervalMillis / 4, throttleBucketInterval); this.replica = replica; this.localIdentifier = replica.identifier(); this.externalizable = externalizable; this.replicationConfig = replicationConfig; this.remoteNodeValidator = remoteNodeValidator; this.name = name; this.connectionListener = (connectionListener == null) ? null : new ConnectionListener() { private final Map<InetAddress, State> listenerStateMap = new ConcurrentHashMap<>(); @Override public void onConnect(InetAddress address, byte identifier, boolean isServer) { if (listenerStateMap.put(address, State.CONNECTED) == State.CONNECTED) return; connectionListener.onConnect(address, identifier, isServer); } @Override public void onDisconnect(InetAddress address, byte identifier) { if (listenerStateMap.put(address, State.DISCONNECTED) == State.DISCONNECTED) return; connectionListener.onDisconnect(address, identifier); } }; start(); } @Override void processEvent() throws IOException { try { final InetSocketAddress serverInetSocketAddress = new InetSocketAddress(replicationConfig.serverPort()); final Details serverDetails = new Details(serverInetSocketAddress, localIdentifier); new ServerConnector(serverDetails).connect(); for (InetSocketAddress client : replicationConfig.endpoints()) { final Details clientDetails = new Details(client, localIdentifier); new ClientConnector(clientDetails).connect(); } while (selector.isOpen()) { registerPendingRegistrations(); final int nSelectedKeys = select(); // its less resource intensive to set this less frequently and use an approximation final long approxTime = System.currentTimeMillis(); checkThrottleInterval(); // check that we have sent and received heartbeats heartBeatMonitor(approxTime); // set the OP_WRITE when data is ready to send opWriteUpdater.applyUpdates(); if (useJavaNIOSelectionKeys) { // use the standard java nio selector if (nSelectedKeys == 0) continue; // go back and check pendingRegistrations final Set<SelectionKey> selectionKeys = selector.selectedKeys(); for (final SelectionKey key : selectionKeys) { processKey(approxTime, key); } selectionKeys.clear(); } else { // use the netty like selector final SelectionKey[] keys = selectedKeys.flip(); try { for (int i = 0; i < keys.length && keys[i] != null; i++) { final SelectionKey key = keys[i]; try { processKey(approxTime, key); } catch (BufferUnderflowException e) { if (!isClosed) LOG.error("", e); } } } finally { for (int i = 0; i < keys.length && keys[i] != null; i++) { keys[i] = null; } } } } } catch (CancelledKeyException | ConnectException | ClosedChannelException | ClosedSelectorException e) { if (LOG.isDebugEnabled()) LOG.debug("", e); } catch (Exception e) { LOG.error("", e); } catch (Throwable e) { LOG.error("", e); throw e; } finally { if (LOG.isDebugEnabled()) LOG.debug("closing name=" + name); if (!isClosed) { closeResources(); } } } private void processKey(long approxTime, @NotNull SelectionKey key) { try { if (!key.isValid()) return; if (key.isAcceptable()) { if (LOG.isDebugEnabled()) LOG.debug("onAccept - " + name); onAccept(key); } if (key.isConnectable()) { if (LOG.isDebugEnabled()) LOG.debug("onConnect - " + name); onConnect(key); } if (key.isReadable()) { if (LOG.isDebugEnabled()) LOG.debug("onRead - " + name); onRead(key, approxTime); } if (key.isWritable()) { if (LOG.isDebugEnabled()) LOG.debug("onWrite - " + name); onWrite(key, approxTime); } } catch (InterruptedException e) { quietClose(key, e); } catch (BufferUnderflowException | IOException | ClosedSelectorException | CancelledKeyException e) { if (!isClosed) quietClose(key, e); } catch (Exception e) { LOG.info("", e); if (!isClosed) closeEarlyAndQuietly(key.channel()); } } /** * spin loops 100000 times first before calling the selector with timeout * * @return The number of keys, possibly zero, whose ready-operation sets were updated * @throws IOException */ private int select() throws IOException { long start = System.nanoTime(); while (System.nanoTime() < start + SPIN_LOOP_TIME_IN_NONOSECONDS) { final int keys = selector.selectNow(); if (keys != 0) return keys; } return selector.select(selectorTimeout); } /** * checks that we receive heartbeats and send out heart beats. * * @param approxTime the approximate time in milliseconds */ void heartBeatMonitor(long approxTime) { for (int i = activeKeys.nextSetBit(0); i >= 0; i = activeKeys.nextSetBit(i + 1)) { try { final SelectionKey key = selectionKeysStore[i]; if (!key.isValid() || !key.channel().isOpen()) { activeKeys.clear(i); continue; } final Attached attachment = (Attached) key.attachment(); if (attachment == null) continue; if (!attachment.hasRemoteHeartbeatInterval) continue; try { sendHeartbeatIfRequired(approxTime, key); } catch (Exception e) { if (LOG.isDebugEnabled()) LOG.debug("", e); } try { heartbeatCheckHasReceived(key, approxTime); } catch (Exception e) { if (LOG.isDebugEnabled()) LOG.debug("", e); } } catch (Exception e) { if (LOG.isDebugEnabled()) LOG.debug("", e); } } } /** * check to see if its time to send a heartbeat, and send one if required * * @param approxTime the current time ( approximately ) * @param key nio selection key */ private void sendHeartbeatIfRequired(final long approxTime, @NotNull final SelectionKey key) { final Attached attachment = (Attached) key.attachment(); if (attachment.isHandShakingComplete() && attachment.entryWriter.lastSentTime + heartBeatIntervalMillis < approxTime) { attachment.entryWriter.lastSentTime = approxTime; attachment.entryWriter.writeHeartbeatToBuffer(); enableOpWrite(key); if (LOG.isDebugEnabled()) LOG.debug("sending heartbeat"); } } private void enableOpWrite(@NotNull SelectionKey key) { int ops = key.interestOps(); if ((ops & (OP_CONNECT | OP_ACCEPT)) == 0) key.interestOps(ops | OP_WRITE); } /** * check to see if we have lost connection with the remote node and if we have attempts a * reconnect. * * @param key the key relating to the heartbeat that we are checking * @param approxTimeOutTime the approximate time in milliseconds * @throws ConnectException */ private void heartbeatCheckHasReceived(@NotNull final SelectionKey key, final long approxTimeOutTime) { final Attached attached = (Attached) key.attachment(); if (attached.isServer && !attached.isHandShakingComplete()) return; final SocketChannel channel = (SocketChannel) key.channel(); if (approxTimeOutTime > attached.entryReader.lastHeartBeatReceived + attached.remoteHeartbeatInterval) { if (LOG.isDebugEnabled()) LOG.debug("lost connection, attempting to reconnect. " + "missed heartbeat from identifier=" + attached.remoteIdentifier); activeKeys.clear(attached.remoteIdentifier); quietClose(key, null); closeables.closeQuietly(channel.socket()); // when node discovery is used ( by nodes broadcasting out their host:port over UDP ), // when new or restarted nodes are started up. they attempt to find the nodes // on the grid by listening to the host and ports of the other nodes, so these nodes // will establish the connection when they come back up, hence under these // circumstances, polling a dropped node to attempt to reconnect is no-longer // required as the remote node will establish the connection its self on startup. if (replicationConfig.autoReconnectedUponDroppedConnection()) attached.connector.connectLater(); } } /** * closes and only logs the exception at debug * * @param key the SelectionKey * @param e the Exception that caused the issue */ private void quietClose(@NotNull final SelectionKey key, @Nullable final Exception e) { if (LOG.isDebugEnabled() && e != null) LOG.debug("", e); if (key.channel() != null && key.attachment() != null && connectionListener != null) connectionListener.onDisconnect(((SocketChannel) key.channel()).socket().getInetAddress(), ((Attached) key.attachment()).remoteIdentifier); closeEarlyAndQuietly(key.channel()); } /** * called when the selector receives a OP_CONNECT message */ private void onConnect(@NotNull final SelectionKey key) throws IOException { SocketChannel channel = null; try { channel = (SocketChannel) key.channel(); } finally { closeables.add(channel); } final Attached attached = (Attached) key.attachment(); try { if (!channel.finishConnect()) { return; } } catch (SocketException e) { quietClose(key, e); // when node discovery is used ( by nodes broadcasting out their host:port over UDP ), // when new or restarted nodes are started up. they attempt to find the nodes // on the grid by listening to the host and ports of the other nodes, // so these nodes will establish the connection when they come back up, // hence under these circumstances, polling a dropped node to attempt to reconnect // is no-longer required as the remote node will establish the connection its self // on startup. attached.connector.connectLater(); throw e; } attached.connector.setSuccessfullyConnected(); if (LOG.isDebugEnabled()) LOG.debug("successfully connected to {}, local-id={}", channel.socket().getInetAddress(), localIdentifier); channel.configureBlocking(false); channel.socket().setTcpNoDelay(true); channel.socket().setSoTimeout(0); channel.socket().setSoLinger(false, 0); attached.entryReader = new TcpSocketChannelEntryReader(); attached.entryWriter = new TcpSocketChannelEntryWriter(); key.interestOps(OP_WRITE | OP_READ); throttle(channel); // register it with the selector and store the ModificationIterator for this key attached.entryWriter.identifierToBuffer(localIdentifier); } /** * called when the selector receives a OP_ACCEPT message */ private void onAccept(@NotNull final SelectionKey key) throws IOException { ServerSocketChannel server = null; try { server = (ServerSocketChannel) key.channel(); } finally { if (server != null) closeables.add(server); } SocketChannel channel = null; try { channel = server.accept(); } finally { if (channel != null) closeables.add(channel); } channel.configureBlocking(false); channel.socket().setReuseAddress(true); channel.socket().setTcpNoDelay(true); channel.socket().setSoTimeout(0); channel.socket().setSoLinger(false, 0); final Attached attached = new Attached(); attached.entryReader = new TcpSocketChannelEntryReader(); attached.entryWriter = new TcpSocketChannelEntryWriter(); attached.entryWriter.identifierToBuffer(localIdentifier); attached.isServer = true; channel.register(selector, OP_READ, attached); throttle(channel); } /** * check that the version number is valid text, * * @param versionNumber the version number to check * @return true, if the version number looks correct */ boolean isValidVersionNumber(String versionNumber) { if (versionNumber.length() <= 2) return false; for (char c : versionNumber.toCharArray()) { if (c >= '0' && c <= '9') continue; if (c == '.' || c == '-' || c == '_') continue; if (c >= 'A' && c <= 'Z') continue; if (c >= 'a' && c <= 'z') continue; return false; } return true; } private void checkVersions(final Attached<K, V> attached) { final String localVersion = BuildVersion.version(); final String remoteVersion = attached.serverVersion; if (!remoteVersion.equals(localVersion)) { byte remoteIdentifier = attached.remoteIdentifier; LOG.warn("DIFFERENT CHRONICLE-MAP VERSIONS : " + "local-map=" + localVersion + ", remote-map-id-" + remoteIdentifier + "=" + remoteVersion + ", The Remote Chronicle Map with " + "identifier=" + remoteIdentifier + " and this Chronicle Map are on different " + "versions, we suggest that you use the same version." ); } } /** * used to exchange identifiers and timestamps and heartbeat intervals between the server and * client * * @param key the SelectionKey relating to the this cha * @param socketChannel * @throws java.io.IOException * @throws InterruptedException */ private void doHandShaking(@NotNull final SelectionKey key, @NotNull SocketChannel socketChannel) throws IOException { final Attached attached = (Attached) key.attachment(); final TcpSocketChannelEntryWriter writer = attached.entryWriter; final TcpSocketChannelEntryReader reader = attached.entryReader; socketChannel.register(selector, OP_READ | OP_WRITE, attached); if (attached.remoteIdentifier == Byte.MIN_VALUE) { final byte remoteIdentifier = reader.identifierFromBuffer(); if (remoteIdentifier == STATELESS_CLIENT) { attached.handShakingComplete = true; attached.hasRemoteHeartbeatInterval = false; return; } if (remoteIdentifier == Byte.MIN_VALUE) return; attached.remoteIdentifier = remoteIdentifier; final SocketChannel channel = (SocketChannel) key.channel(); if (channel != null && channel.socket() != null && connectionListener != null) { connectionListener.onConnect( channel.socket().getInetAddress(), attached.remoteIdentifier, attached.isServer); } // we use the as iterating the activeKeys via the bitset wont create and Objects // but if we use the selector.keys() this will. selectionKeysStore[remoteIdentifier] = key; activeKeys.set(remoteIdentifier); if (LOG.isDebugEnabled()) { LOG.debug("server-connection id={}, remoteIdentifier={}", localIdentifier, remoteIdentifier); } // this can occur sometimes when if 2 or more remote node attempt to use node discovery // at the same time final SocketAddress remoteAddress = socketChannel.getRemoteAddress(); if ((remoteNodeValidator != null && !remoteNodeValidator.validate(remoteIdentifier, remoteAddress)) || remoteIdentifier == localIdentifier) // throwing this exception will cause us to disconnect, both the client and server // will be able to detect the the remote and local identifiers are the same, // as the identifier is send early on in the hand shaking via the connect(() // and accept() methods throw new IllegalStateException("dropping connection, " + "as the remote-identifier is already being used, identifier=" + remoteIdentifier); if (LOG.isDebugEnabled()) LOG.debug("handshaking for localIdentifier=" + localIdentifier + "," + "remoteIdentifier=" + remoteIdentifier); attached.remoteModificationIterator = replica.acquireModificationIterator(remoteIdentifier); attached.remoteModificationIterator.setModificationNotifier(attached); writer.writeRemoteBootstrapTimestamp(replica.lastModificationTime(remoteIdentifier)); writer.writeServerVersion(); // tell the remote node, what are heartbeat interval is writer.writeRemoteHeartbeatInterval(heartBeatIntervalMillis); } if (attached.remoteBootstrapTimestamp == Long.MIN_VALUE) { attached.remoteBootstrapTimestamp = reader.remoteBootstrapTimestamp(); if (attached.remoteBootstrapTimestamp == Long.MIN_VALUE) return; } if (attached.serverVersion == null) { try { attached.serverVersion = reader.readRemoteServerVersion(); } catch (IllegalStateException e1) { socketChannel.close(); return; } if (attached.serverVersion == null) return; if (!isValidVersionNumber(attached.serverVersion)) { LOG.warn("Closing the remote connection : Please check that you don't have " + "a third party system incorrectly connecting to ChronicleMap, " + "remoteAddress=" + socketChannel.getRemoteAddress() + ", " + "so closing the remote connection as Chronicle can not make sense " + "of the remote version number received from the external connection, " + "version=" + attached.serverVersion + ", " + "Chronicle is expecting the version number to only contain " + "'.','-', ,A-Z,a-z,0-9"); socketChannel.close(); return; } checkVersions(attached); } if (!attached.hasRemoteHeartbeatInterval) { final long value = reader.readRemoteHeartbeatIntervalFromBuffer(); if (value == Long.MIN_VALUE) return; if (value < 0) { LOG.error("value=" + value); } // we add a 10% safety margin to the timeout time due to latency fluctuations // on the network, in other words we wont consider a connection to have // timed out, unless the heartbeat interval has exceeded 25% of the expected time. attached.remoteHeartbeatInterval = (long) (value * 1.25); // we have to make our selector poll interval at least as short as the minimum selector // timeout selectorTimeout = Math.min(selectorTimeout, value); if (selectorTimeout < 0) LOG.info(""); attached.hasRemoteHeartbeatInterval = true; // now we're finished we can get on with reading the entries attached.remoteModificationIterator.dirtyEntries(attached.remoteBootstrapTimestamp); try { reader.entriesFromBuffer(attached, key); } finally { attached.handShakingComplete = true; } } } /** * called when the selector receives a OP_WRITE message */ private void onWrite(@NotNull final SelectionKey key, final long approxTime) throws IOException { final SocketChannel socketChannel = (SocketChannel) key.channel(); final Attached attached = (Attached) key.attachment(); if (attached == null) { LOG.info("Closing connection " + socketChannel + ", nothing attached"); socketChannel.close(); return; } TcpSocketChannelEntryWriter entryWriter = attached.entryWriter; if (entryWriter == null) throw new NullPointerException("No entryWriter"); if (entryWriter.isWorkIncomplete()) { final boolean completed = entryWriter.doWork(); if (completed) entryWriter.workCompleted(); } else if (attached.remoteModificationIterator != null) entryWriter.entriesToBuffer(attached.remoteModificationIterator); try { final int len = entryWriter.writeBufferToSocket(socketChannel, approxTime); if (len == -1) socketChannel.close(); if (len > 0) contemplateThrottleWrites(len); if (!entryWriter.hasBytesToWrite() && !entryWriter.isWorkIncomplete() && !hasNext(attached) && attached.isHandShakingComplete()) { // if we have no more data to write to the socket then we will // un-register OP_WRITE on the selector, until more data becomes available // The OP_WRITE will get added back in as soon as we have data to write if (LOG.isDebugEnabled()) LOG.debug("Disabling OP_WRITE to remoteIdentifier=" + attached.remoteIdentifier + ", localIdentifier=" + localIdentifier); key.interestOps(key.interestOps() & ~OP_WRITE); } } catch (IOException e) { quietClose(key, e); if (!attached.isServer) attached.connector.connectLater(); throw e; } } private boolean hasNext(Attached attached) { return attached.remoteModificationIterator != null && attached.remoteModificationIterator.hasNext(); } /** * called when the selector receives a OP_READ message */ private void onRead(@NotNull final SelectionKey key, final long approxTime) throws IOException, InterruptedException { final SocketChannel socketChannel = (SocketChannel) key.channel(); final Attached attached = (Attached) key.attachment(); if (attached == null) { LOG.info("Closing connection " + socketChannel + ", nothing attached"); socketChannel.close(); return; } try { int len = attached.entryReader.readSocketToBuffer(socketChannel); if (len == -1) { socketChannel.register(selector, 0, attached); if (replicationConfig.autoReconnectedUponDroppedConnection()) { AbstractConnector connector = attached.connector; if (connector != null) connector.connectLater(); } else socketChannel.close(); return; } if (len == 0) return; if (attached.entryWriter.isWorkIncomplete()) return; } catch (IOException e) { if (!attached.isServer) attached.connector.connectLater(); throw e; } if (LOG.isDebugEnabled()) LOG.debug("heartbeat or data received."); attached.entryReader.lastHeartBeatReceived = approxTime; if (attached.isHandShakingComplete()) { attached.entryReader.entriesFromBuffer(attached, key); } else { doHandShaking(key, socketChannel); } } @Nullable private ServerSocketChannel openServerSocketChannel() throws IOException { ServerSocketChannel result = null; try { result = ServerSocketChannel.open(); } finally { if (result != null) closeables.add(result); } return result; } /** * sets interestOps to "selector keys",The change to interestOps much be on the same thread as * the selector. This class, allows via {@link AbstractChannelReplicator * .KeyInterestUpdater#set(int)} to holds a pending change in interestOps ( via a bitset ), * this change is processed later on the same thread as the selector */ private static class KeyInterestUpdater { @NotNull private final DirectBitSet changeOfOpWriteRequired; @NotNull private final SelectionKey[] selectionKeys; private final int op; KeyInterestUpdater(int op, @NotNull final SelectionKey[] selectionKeys) { this.op = op; this.selectionKeys = selectionKeys; long bitSetSize = LONGS.align(BYTES.alignAndConvert(selectionKeys.length, BITS), BYTES); changeOfOpWriteRequired = new ATSDirectBitSet(DirectStore.allocate(bitSetSize).bytes()); } public void applyUpdates() { for (long i = changeOfOpWriteRequired.clearNextSetBit(0L); i >= 0; i = changeOfOpWriteRequired.clearNextSetBit(i + 1)) { final SelectionKey key = selectionKeys[((int) i)]; try { key.interestOps(key.interestOps() | op); } catch (Exception e) { LOG.debug("", e); } } } /** * @param keyIndex the index of the key that has changed, the list of keys is provided by * the constructor {@link KeyInterestUpdater(int, SelectionKey[])} */ public void set(int keyIndex) { changeOfOpWriteRequired.setIfClear(keyIndex); } } private class ServerConnector extends AbstractConnector { @NotNull private final Details details; private ServerConnector(@NotNull Details details) { super("TCP-ServerConnector-" + localIdentifier); this.details = details; } @NotNull @Override public String toString() { return "ServerConnector{" + "" + details + '}'; } @Nullable SelectableChannel doConnect() throws IOException, InterruptedException { final ServerSocketChannel serverChannel = openServerSocketChannel(); if (serverChannel == null) return null; serverChannel.socket().setReceiveBufferSize(BUFFER_SIZE); serverChannel.configureBlocking(false); serverChannel.register(TcpReplicator.this.selector, 0); ServerSocket serverSocket = null; try { serverSocket = serverChannel.socket(); } finally { if (serverSocket != null) closeables.add(serverSocket); } if (serverSocket == null) return null; serverSocket.setReuseAddress(true); serverSocket.bind(details.address()); // these can be run on this thread addPendingRegistration(() -> { final Attached attached = new Attached(); attached.connector = ServerConnector.this; try { serverChannel.register(TcpReplicator.this.selector, OP_ACCEPT, attached); } catch (ClosedChannelException e) { LOG.debug("", e); } }); selector.wakeup(); return serverChannel; } } private class ClientConnector extends AbstractConnector { @NotNull private final Details details; private ClientConnector(@NotNull Details details) { super("TCP-ClientConnector-" + details.localIdentifier()); this.details = details; } @NotNull @Override public String toString() { return "ClientConnector{" + details + '}'; } /** * blocks until connected */ @Override SelectableChannel doConnect() throws IOException, InterruptedException { boolean success = false; final SocketChannel socketChannel = openSocketChannel(TcpReplicator.this.closeables); try { socketChannel.configureBlocking(false); socketChannel.socket().setReuseAddress(true); socketChannel.socket().setSoLinger(false, 0); socketChannel.socket().setSoTimeout(0); socketChannel.connect(details.address()); // Under experiment, the concoction was found to be more successful if we // paused before registering the OP_CONNECT Thread.sleep(10); // the registration has be be run on the same thread as the selector addPendingRegistration(new Runnable() { @Override public void run() { final Attached attached = new Attached(); attached.connector = ClientConnector.this; try { socketChannel.register(selector, OP_CONNECT, attached); } catch (ClosedChannelException e) { if (socketChannel.isOpen()) LOG.error("", e); } } }); selector.wakeup(); success = true; return socketChannel; } finally { if (!success) { try { try { socketChannel.socket().close(); } catch (Exception e) { LOG.error("", e); } socketChannel.close(); } catch (IOException e) { LOG.error("", e); } this.connectLater(); } } } } /** * Attached to the NIO selection key via methods such as {@link SelectionKey#attach(Object)} */ class Attached<K, V> implements Replica.ModificationNotifier { public TcpSocketChannelEntryReader entryReader; public TcpSocketChannelEntryWriter entryWriter; @Nullable public Replica.ModificationIterator remoteModificationIterator; // used for connect later public AbstractConnector connector; public long remoteBootstrapTimestamp = Long.MIN_VALUE; public byte remoteIdentifier = Byte.MIN_VALUE; public boolean hasRemoteHeartbeatInterval; // true if its socket is a ServerSocket public boolean isServer; public boolean handShakingComplete; public String serverVersion; public long remoteHeartbeatInterval = heartBeatIntervalMillis; boolean isHandShakingComplete() { return handShakingComplete; } /** * called whenever there is a change to the modification iterator */ @Override public void onChange() { if (remoteIdentifier != Byte.MIN_VALUE) TcpReplicator.this.opWriteUpdater.set(remoteIdentifier); } } /** * @author Rob Austin. */ public class TcpSocketChannelEntryWriter { @NotNull private final EntryCallback entryCallback; // if uncompletedWork is set ( not null ) , this must be completed before any further work // is carried out @Nullable public Work uncompletedWork; private long lastSentTime; private TcpSocketChannelEntryWriter() { entryCallback = new EntryCallback(externalizable, replicationConfig.tcpBufferSize()); } public boolean isWorkIncomplete() { return uncompletedWork != null; } public void workCompleted() { uncompletedWork = null; } /** * writes the timestamp into the buffer * * @param localIdentifier the current nodes identifier */ void identifierToBuffer(final byte localIdentifier) { in().writeByte(localIdentifier); } public void ensureBufferSize(long size) { if (in().remaining() < size) { size += entryCallback.in().position(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException(); entryCallback.resizeBuffer((int) size); } } void resizeToMessage(@NotNull IllegalStateException e) { String message = e.getMessage(); if (message.startsWith("java.io.IOException: Not enough available space for writing ")) { String substring = message.substring("java.io.IOException: Not enough available space for writing ".length(), message.length()); int i = substring.indexOf(' '); if (i != -1) { int size = Integer.parseInt(substring.substring(0, i)); long requiresExtra = size - in().remaining(); ensureBufferSize((int) (in().capacity() + requiresExtra)); } else throw e; } else throw e; } public Bytes in() { return entryCallback.in(); } private ByteBuffer out() { return entryCallback.out(); } /** * sends the identity and timestamp of this node to a remote node * * @param timeStampOfLastMessage the last timestamp we received a message from that node */ void writeRemoteBootstrapTimestamp(final long timeStampOfLastMessage) { in().writeLong(timeStampOfLastMessage); } void writeServerVersion() { in().write(String.format("%1$" + 64 + "s", version()).toCharArray()); } /** * writes all the entries that have changed, to the buffer which will later be written to * TCP/IP * * @param modificationIterator a record of which entries have modification */ void entriesToBuffer(@NotNull final Replica.ModificationIterator modificationIterator) { int entriesWritten = 0; try { for (; ; entriesWritten++) { long start = in().position(); boolean success = modificationIterator.nextEntry(entryCallback, 0); // if not success this is most likely due to the next entry not fitting into // the buffer and the buffer can not be re-sized above Integer.max_value, in // this case success will return false, so we return so that we can send to // the socket what we have. if (!success) return; long entrySize = in().position() - start; if (entrySize > largestEntrySoFar) largestEntrySoFar = entrySize; // we've filled up the buffer lets give another channel a chance to send // some data if (in().remaining() <= largestEntrySoFar || in().position() > replicationConfig.tcpBufferSize()) return; // if we have space in the buffer to write more data and we just wrote data // into the buffer then let try and write some more } } finally { if (LOG.isDebugEnabled()) LOG.debug("Entries written: {}", entriesWritten); } } /** * writes the contents of the buffer to the socket * * @param socketChannel the socket to publish the buffer to * @param approxTime an approximation of the current time in millis * @throws IOException */ private int writeBufferToSocket(@NotNull final SocketChannel socketChannel, final long approxTime) throws IOException { final Bytes in = in(); final ByteBuffer out = out(); if (in.position() == 0) return 0; // if we still have some unwritten writer from last time lastSentTime = approxTime; assert in.position() <= Integer.MAX_VALUE; int size = (int) in.position(); out.limit(size); final int len = socketChannel.write(out); if (LOG.isDebugEnabled()) LOG.debug("bytes-written=" + len); if (len == size) { out.clear(); in.clear(); } else { out.compact(); in.position(out.position()); in.limit(in.capacity()); out.clear(); } return len; } /** * used to send an single zero byte if we have not send any data for up to the * localHeartbeatInterval */ private void writeHeartbeatToBuffer() { // denotes the state - 0 for a heartbeat in().writeByte(HEARTBEAT); // denotes the size in bytes in().writeInt(0); } private void writeRemoteHeartbeatInterval(long localHeartbeatInterval) { in().writeLong(localHeartbeatInterval); } public boolean doWork() { return uncompletedWork != null && uncompletedWork.doWork(in()); } public boolean hasBytesToWrite() { return in().position() > 0; } } /** * Reads map entries from a socket, this could be a client or server socket */ class TcpSocketChannelEntryReader { public static final int HEADROOM = 1024; public static final int SIZE_OF_BOOTSTRAP_TIMESTAMP = 8; public long lastHeartBeatReceived = System.currentTimeMillis(); ByteBuffer in; ByteBufferBytes out; private long sizeInBytes; private byte state; private TcpSocketChannelEntryReader() { in = ByteBuffer.allocateDirect(replicationConfig.tcpBufferSize()); out = new ByteBufferBytes(in.slice()); out.limit(0); in.clear(); } void resizeBuffer(long size) { assert size < Integer.MAX_VALUE; if (size < in.capacity()) throw new IllegalStateException("it not possible to resize the buffer smaller"); final ByteBuffer buffer = ByteBuffer.allocateDirect((int) size) .order(ByteOrder.nativeOrder()); final int inPosition = in.position(); long outPosition = out.position(); long outLimit = out.limit(); out = new ByteBufferBytes(buffer.slice()); // TODO why copy byte by byte?! in.position(0); for (int i = 0; i < inPosition; i++) { buffer.put(in.get()); } in = buffer; in.limit(in.capacity()); in.position(inPosition); out.limit(outLimit); out.position(outPosition); } /** * reads from the socket and writes them to the buffer * * @param socketChannel the socketChannel to read from * @return the number of bytes read * @throws IOException */ private int readSocketToBuffer(@NotNull final SocketChannel socketChannel) throws IOException { compactBuffer(); final int len = socketChannel.read(in); out.limit(in.position()); return len; } /** * reads entries from the buffer till empty * * @param attached * @param key * @throws InterruptedException */ void entriesFromBuffer(@NotNull Attached attached, @NotNull SelectionKey key) { int entriesRead = 0; try { for (; ; entriesRead++) { out.limit(in.position()); // its set to MIN_VALUE when it should be read again if (state == NOT_SET) { if (out.remaining() < SIZE_OF_SIZE + 1) return; // state is used for heartbeat state = out.readByte(); sizeInBytes = out.readInt(); assert sizeInBytes >= 0; // if the buffer is too small to read this payload we will have to grow the // size of the buffer long requiredSize = sizeInBytes + SIZE_OF_SIZE + 1 + SIZE_OF_BOOTSTRAP_TIMESTAMP; if (out.capacity() < requiredSize) { attached.entryReader.resizeBuffer(requiredSize + HEADROOM); } // means this is heartbeat if (state == NOT_SET) continue; } if (out.remaining() < sizeInBytes) { return; } final long nextEntryPos = out.position() + sizeInBytes; assert nextEntryPos > 0; final long limit = out.limit(); out.limit(nextEntryPos); externalizable.readExternalEntry(out); out.limit(limit); // skip onto the next entry out.position(nextEntryPos); state = NOT_SET; sizeInBytes = 0; } } finally { if (LOG.isDebugEnabled()) LOG.debug("Entries read: {}", entriesRead); } } /** * compacts the buffer and updates the {@code in} and {@code out} accordingly */ private void compactBuffer() { // the maxEntrySizeBytes used here may not be the maximum size of the entry in its // serialized form however, its only use as an indication that the buffer is becoming // full and should be compacted the buffer can be compacted at any time if (in.position() == 0 || in.remaining() > largestEntrySoFar) return; in.limit(in.position()); assert out.position() < Integer.MAX_VALUE; in.position((int) out.position()); in.compact(); out.position(0); } /** * @return the identifier or -1 if unsuccessful */ byte identifierFromBuffer() { return (out.remaining() >= 1) ? out.readByte() : Byte.MIN_VALUE; } /** * @return the timestamp or -1 if unsuccessful */ long remoteBootstrapTimestamp() { if (out.remaining() >= 8) return out.readLong(); else return Long.MIN_VALUE; } /** * @return the timestamp or -1 if unsuccessful */ String readRemoteServerVersion() { if (out.remaining() >= 64) { char[] chars = new char[64]; out.readFully(chars, 0, chars.length); return new String(chars).trim(); } else return null; } public long readRemoteHeartbeatIntervalFromBuffer() { return (out.remaining() >= 8) ? out.readLong() : Long.MIN_VALUE; } } }
package org.apdplat.word.recognition; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apdplat.word.segmentation.PartOfSpeech; import org.apdplat.word.segmentation.Word; import org.apdplat.word.tagging.PartOfSpeechTagging; import org.apdplat.word.util.AutoDetector; import org.apdplat.word.util.ResourceLoader; import org.apdplat.word.util.WordConfTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author */ public class PersonName { private static final Logger LOGGER = LoggerFactory.getLogger(PersonName.class); private static final Set<String> SURNAME_1 =new HashSet<>(); private static final Set<String> SURNAME_2 =new HashSet<>(); private static final Map<String, Integer> POS_SEQ=new HashMap<>(); static{ reload(); } public static void reload(){ AutoDetector.loadAndWatch(new ResourceLoader() { @Override public void clear() { SURNAME_1.clear(); SURNAME_2.clear(); POS_SEQ.clear(); } @Override public void load(List<String> lines) { LOGGER.info(""); for (String line : lines) { if (line.length() == 1) { SURNAME_1.add(line); } else if (line.length() == 2) { SURNAME_2.add(line); } else if(line.startsWith("pos_seq=")) { String[] attr = line.split("="); POS_SEQ.put(attr[1].trim().replaceAll("\\s", " "), Integer.parseInt(attr[2])); } else{ LOGGER.error("" + line); } } LOGGER.info("" + SURNAME_1.size() + "" + SURNAME_2.size()); } @Override public void add(String line) { if (line.length() == 1) { SURNAME_1.add(line); } else if (line.length() == 2) { SURNAME_2.add(line); } else if(line.startsWith("pos_seq=")) { String[] attr = line.split("="); POS_SEQ.put(attr[1].trim().replaceAll("\\s", " "), Integer.parseInt(attr[2])); } else { LOGGER.error("" + line); } } @Override public void remove(String line) { if (line.length() == 1) { SURNAME_1.remove(line); } else if (line.length() == 2) { SURNAME_2.remove(line); } else if(line.startsWith("pos_seq=")) { String[] attr = line.split("="); POS_SEQ.remove(attr[1].trim().replaceAll("\\s", " ")); } else { LOGGER.error("" + line); } } }, WordConfTools.get("surname.path", "classpath:surname.txt")); } /** * * @return */ public static List<String> getSurnames(){ List<String> result = new ArrayList<>(); result.addAll(SURNAME_1); result.addAll(SURNAME_2); Collections.sort(result); return result; } /** * * @param text * @return */ public static String getSurname(String text){ if(is(text)){ if(isSurname(text.substring(0, 2))){ return text.substring(0, 2); } if(isSurname(text.substring(0, 1))){ return text.substring(0, 1); } } return ""; } /** * * @param text * @return */ public static boolean isSurname(String text){ return SURNAME_1.contains(text) || SURNAME_2.contains(text); } /** * * @param text * @return */ public static boolean is(String text){ int len = text.length(); if(len < 2){ return false; } if(len == 2){ return SURNAME_1.contains(text.substring(0, 1)); } if(len == 3){ return SURNAME_1.contains(text.substring(0, 1)) || SURNAME_2.contains(text.substring(0, 2)); } if(len == 4){ return SURNAME_2.contains(text.substring(0, 2)); } return false; } /** * * @param words * @return */ public static List<Word> recognize(List<Word> words){ int len = words.size(); if(len < 2){ return words; } LOGGER.debug("" + words); List<List<Word>> select = new ArrayList<>(); List<Word> result = new ArrayList<>(); for(int i=0; i<len-1; i++){ String word = words.get(i).getText(); if(isSurname(word)){ result.addAll(recognizePersonName(words.subList(i, words.size()))); select.add(result); result = new ArrayList<>(words.subList(0, i+1)); }else{ result.add(new Word(word)); } } if(select.isEmpty()){ return words; } if(select.size()==1){ return select.get(0); } return selectBest(select); } /** * * @param candidateWords * @return */ private static List<Word> selectBest(List<List<Word>> candidateWords){ LOGGER.debug(":{}", candidateWords); Map<List<Word>, Integer> map = new ConcurrentHashMap<>(); AtomicInteger i = new AtomicInteger(); candidateWords.stream().forEach(candidateWord -> { LOGGER.debug(i.incrementAndGet()+""+candidateWord); PartOfSpeechTagging.process(candidateWord); StringBuilder seq = new StringBuilder(); candidateWord.forEach(word -> seq.append(word.getPartOfSpeech().getPos().charAt(0)).append(" ")); String seqStr = seq.toString(); AtomicInteger score = new AtomicInteger(); LOGGER.debug("{} {}", candidateWord, seqStr); POS_SEQ.keySet().parallelStream().forEach(pos_seq -> { if (seqStr.contains(pos_seq)) { int sc = POS_SEQ.get(pos_seq); LOGGER.debug(pos_seq+"" + sc); score.addAndGet(sc); } }); score.addAndGet(-candidateWord.size()); LOGGER.debug("" + (-candidateWord.size())); LOGGER.debug(""+score.get()); map.put(candidateWord, score.get()); }); List<Word> result = map.entrySet().parallelStream().sorted((a,b)->b.getValue().compareTo(a.getValue())).map(e->e.getKey()).collect(Collectors.toList()).get(0); LOGGER.debug(""+result); return result; } private static List<Word> recognizePersonName(List<Word> words){ int len = words.size(); if(len < 2){ return words; } List<Word> result = new ArrayList<>(); for(int i=0; i<len-1; i++){ String second = words.get(i+1).getText(); if(second.length() > 1){ result.add(new Word(words.get(i).getText())); result.add(new Word(words.get(i+1).getText())); i++; if(i == len-2){ result.add(new Word(words.get(i+1).getText())); } continue; } String first = words.get(i).getText(); if(isSurname(first)){ String third = ""; if(i+2 < len && words.get(i+2).getText().length()==1){ third = words.get(i+2).getText(); } String text = first+second+third; if(is(text)){ LOGGER.debug("" + text); Word word = new Word(text); //word.confpart.of.speech.des.path=classpath:part_of_speech_des.txt word.setPartOfSpeech(PartOfSpeech.valueOf("nr")); result.add(word); i++; if(!"".equals(third)){ i++; } }else{ result.add(new Word(first)); } }else{ result.add(new Word(first)); } if(i == len-2){ result.add(new Word(words.get(i+1).getText())); } } return result; } public static void main(String[] args){ int i=1; for(String str : SURNAME_1){ LOGGER.info((i++)+" : "+str); } for(String str : SURNAME_2){ LOGGER.info((i++)+" : "+str); } LOGGER.info(""+is("")); LOGGER.info(""+is("")); LOGGER.info(""+is("")); LOGGER.info(""+is("")); List<Word> test = new ArrayList<>(); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); LOGGER.info(recognize(test).toString()); test = new ArrayList<>(); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); LOGGER.info(recognize(test).toString()); test = new ArrayList<>(); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); test.add(new Word("")); LOGGER.info(recognize(test).toString()); test = new ArrayList<>(); test.add(new Word("")); test.add(new Word("")); LOGGER.info(recognize(test).toString()); LOGGER.info(getSurname("")); LOGGER.info(getSurname("")); } }
package org.beanplant.JavaText.io; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.beanplant.JavaText.handlers.CommandLockHandler; import org.beanplant.JavaText.handlers.EventHandler; import org.beanplant.JavaText.io.commands.CommandConfirm; import org.beanplant.JavaText.io.commands.CommandConnect; import org.beanplant.JavaText.io.commands.CommandDeny; import org.beanplant.JavaText.io.commands.CommandDisconnect; import org.beanplant.JavaText.io.commands.CommandDrop; import org.beanplant.JavaText.io.commands.CommandGo; import org.beanplant.JavaText.io.commands.CommandHealth; import org.beanplant.JavaText.io.commands.CommandHelp; import org.beanplant.JavaText.io.commands.CommandHit; import org.beanplant.JavaText.io.commands.CommandHost; import org.beanplant.JavaText.io.commands.CommandInspect; import org.beanplant.JavaText.io.commands.CommandInventory; import org.beanplant.JavaText.io.commands.CommandLoad; import org.beanplant.JavaText.io.commands.CommandLock; import org.beanplant.JavaText.io.commands.CommandLook; import org.beanplant.JavaText.io.commands.CommandQuit; import org.beanplant.JavaText.io.commands.CommandSave; import org.beanplant.JavaText.io.commands.CommandStop; import org.beanplant.JavaText.io.commands.CommandTake; import org.beanplant.JavaText.io.commands.CommandUnknown; import org.beanplant.JavaText.io.commands.CommandUnlock; import org.beanplant.JavaText.world.World; /** * Parses the commands, and executes activities performed in the game. * * @author the_DJDJ */ public final class CommandParser { /** The world that all commands are executed on. */ private World world; /** The previous world, used for when the user switches worlds. */ private World oldWorld; /** The String that stores the command the user entered. */ private String command = new String(); /** The String that stores the arguments for the user-entered command. */ private String arguments = new String(); /** A hashmap containing all of the currently registered commands. */ private HashMap<String, Command> commands = new HashMap<>(); /** A list of all of the lock handlers currently active. */ private final List<CommandLockHandler> commandHandlers = new ArrayList<>(); /** A list of all the EventHandlers currently active. */ private static final List<EventHandler> eventHandlers = new ArrayList<>(); /** * The default constructor. This creates the environment in which to * interpret commands, as well as gets the world to execute commands on. * * @param world The world to execute commands on */ public CommandParser(World world){ this.world = world; this.registerCommand(new CommandGo(), "GO", "MOVE"); this.registerCommand(new CommandTake(), "TAKE"); this.registerCommand(new CommandDrop(), "DROP"); this.registerCommand(new CommandInventory(), "LOOT", "INVENTORY"); this.registerCommand(new CommandHealth(), "HEALTH"); this.registerCommand(new CommandLook(), "LOOK"); this.registerCommand(new CommandInspect(), "INSPECT"); this.registerCommand(new CommandHit(), "HIT", "KILL"); this.registerCommand(new CommandLock(), "LOCK"); this.registerCommand(new CommandUnlock(), "LOCK", "CLEAR"); this.registerCommand(new CommandConfirm(), "YES", "CONFIRM"); this.registerCommand(new CommandDeny(), "NO", "DENY"); this.registerCommand(new CommandHelp(), "HELP"); this.registerCommand(new CommandSave(), "SAVE"); this.registerCommand(new CommandLoad(), "LOAD", "RESTORE"); this.registerCommand(new CommandHost(), "HOST", "START"); this.registerCommand(new CommandStop(), "STOP"); this.registerCommand(new CommandConnect(), "CONNECT"); this.registerCommand(new CommandDisconnect(), "DISCONNECT"); this.registerCommand(new CommandUnknown(), "UNKNOWN"); this.registerCommand(new CommandQuit(), "QUIT", "EXIT"); } /** * The method to register a command. This takes the command, as well as all * of it's aliases, as arguments, and then adds them to the appropriate * hashmap. * * @param command the command to add. * @param names the aliases of this command */ public void registerCommand(Command command, String... names) { for (String name : names) { this.commands.put(name, command); } } /** * The method to deregister a command. This removes the alias from the list * of aliases check when a command is entered. * * @param name the command to deregister */ public void deregisterCommand(String name) { this.commands.remove(name); } /** * The method that actually executes the command. This method gets the * command that the user entered, and splits it into the command and its * arguments. Once the command has been split up, this calls the appropriate * method to execute the instructions. * * @param input The command to execute */ public void parse(String input){ // Clear our output screen world.getOutputStream().initialisePrint(); if(input.length() <= 2 && !input.equals("NO")){ this.commands.get("GO").execute(input); triggerEvent("GO"); } else { try { command = input.substring(0, input.indexOf(" ")).trim(); } catch (StringIndexOutOfBoundsException ex){ command = input; } finally { try { arguments = input.substring(input.indexOf(" "), input.length()).trim(); } catch (StringIndexOutOfBoundsException ex){} } if(!command.equals("YES") && !command.equals("NO")) this.removeAllLockHandlers(); if(this.commands.containsKey(command)) { this.commands.get(command).execute(arguments); } else { this.commands.get("UNKNOWN").execute(arguments); } // Notify event listeners triggerEvent(command); } } /** * The method that adds a lock handler to the CommandParser, so that locked * commands do something * * @param handler the handler to add */ public void addLockHandler(CommandLockHandler handler){ this.commandHandlers.add(handler); } /** * The method that removes all lock handlers, essentially removing all locks * on commands */ public void removeAllLockHandlers(){ this.commandHandlers.clear(); } /** * A simple method that fetches all the lock handlers. * * @return a list of all lock handlers */ public List<CommandLockHandler> getAllLockHandlers() { return this.commandHandlers; } /** * The method that adds an event handler to the CommandParser, so that * events can be triggered * * @param handler the handler to add */ public static void addEventHandler(EventHandler handler){ eventHandlers.add(handler); } /** * The method that removes an event handler from the CommandParser, so that * events relying on that handler are no longer triggered. * * @param handler the handler to remove * @return whether or not the remove was successful */ public static boolean removeEventHandler(EventHandler handler){ return eventHandlers.remove(handler); } /** * The method that removes all event handlers from the CommandParser, so * that no new events will be trigger */ public static void removeAllEventHandlers(){ eventHandlers.clear(); } /** * The method used when an event is to be triggered. This goes through all * of the event handlers and fires the event to each one in turn. * * @param event the event to fire */ private void triggerEvent(String event){ for (EventHandler eventHandler : eventHandlers) { eventHandler.fireEvent(event); } } /** * A simple method to overwrite the current world. This is useful where a * command must overwrite the world, for instance, when loading one from a * file. * * @param world the new world */ public void updateWorld(World world) { this.world = world; } /** * Returns the current world in use. * * @return the world. */ public World getWorld() { return this.world; } }
package org.datetimepicker.ui.components; /** * @author Jagdeep Jain * */ public class XPaths { // date picker
package org.ethereum.net.message; import org.ethereum.core.Genesis; import org.ethereum.crypto.HashUtil; import org.spongycastle.util.encoders.Hex; public class StaticMessages { public static final byte[] PING = Hex.decode("2240089100000002C102"); public static final byte[] PONG = Hex.decode("2240089100000002C103"); public static final byte[] GET_PEERS = Hex.decode("2240089100000002C110"); public static final byte[] GET_TRANSACTIONS = Hex.decode("2240089100000002C116"); public static final byte[] DISCONNECT_08 = Hex.decode("2240089100000003C20108"); public static final byte[] GENESIS_HASH = Genesis.getInstance().getHash(); public static final byte[] MAGIC_PACKET = Hex.decode("22400891"); static { HELLO_MESSAGE = generateHelloMessage(); } public static HelloMessage HELLO_MESSAGE; public static HelloMessage generateHelloMessage() { byte[] peerIdBytes = HashUtil.randomPeerId(); return new HelloMessage((byte) 0x16, (byte) 0x00, "EthereumJ [v0.5.1] by RomanJ", Byte.parseByte("00000111", 2), (short) 30303, peerIdBytes); } }
package org.jfree.chart.block; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.Size2D; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.Range; /** * An arrangement manager that lays out blocks in a similar way to * Swing's BorderLayout class. */ public class BorderArrangement implements Arrangement, Serializable { /** For serialization. */ private static final long serialVersionUID = 506071142274883745L; /** The block (if any) at the center of the layout. */ private Block centerBlock; /** The block (if any) at the top of the layout. */ private Block topBlock; /** The block (if any) at the bottom of the layout. */ private Block bottomBlock; /** The block (if any) at the left of the layout. */ private Block leftBlock; /** The block (if any) at the right of the layout. */ private Block rightBlock; /** * Creates a new instance. */ public BorderArrangement() { } /** * Adds a block to the arrangement manager at the specified edge. * If the key is not an instance of {@link RectangleEdge} the block will * be added in the center. * * @param block the block (<code>null</code> permitted). * @param key the edge (an instance of {@link RectangleEdge}) or * <code>null</code> for the center block. */ @Override public void add(Block block, Object key) { if (!(key instanceof RectangleEdge)) { // catches null also this.centerBlock = block; } else { RectangleEdge edge = (RectangleEdge) key; if (edge == RectangleEdge.TOP) { this.topBlock = block; } else if (edge == RectangleEdge.BOTTOM) { this.bottomBlock = block; } else if (edge == RectangleEdge.LEFT) { this.leftBlock = block; } else if (edge == RectangleEdge.RIGHT) { this.rightBlock = block; } } } /** * Arranges the items in the specified container, subject to the given * constraint. * * @param container the container. * @param g2 the graphics device. * @param constraint the constraint. * * @return The block size. */ @Override public Size2D arrange(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { RectangleConstraint contentConstraint = container.toContentConstraint(constraint); Size2D contentSize = null; LengthConstraintType w = contentConstraint.getWidthConstraintType(); LengthConstraintType h = contentConstraint.getHeightConstraintType(); if (w == LengthConstraintType.NONE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeNN(container, g2); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not implemented."); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not implemented."); } } else if (w == LengthConstraintType.FIXED) { if (h == LengthConstraintType.NONE) { contentSize = arrangeFN(container, g2, constraint.getWidth()); } else if (h == LengthConstraintType.FIXED) { contentSize = arrangeFF(container, g2, constraint); } else if (h == LengthConstraintType.RANGE) { contentSize = arrangeFR(container, g2, constraint); } } else if (w == LengthConstraintType.RANGE) { if (h == LengthConstraintType.NONE) { throw new RuntimeException("Not implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not implemented."); } else if (h == LengthConstraintType.RANGE) { contentSize = arrangeRR(container, constraint.getWidthRange(), constraint.getHeightRange(), g2); } } return new Size2D(container.calculateTotalWidth(contentSize.getWidth()), container.calculateTotalHeight(contentSize.getHeight())); } /** * Performs an arrangement without constraints. * * @param container the container. * @param g2 the graphics device. * * @return The container size after the arrangement. */ protected Size2D arrangeNN(BlockContainer container, Graphics2D g2) { double[] w = new double[5]; double[] h = new double[5]; if (this.topBlock != null) { Size2D size = this.topBlock.arrange(g2, RectangleConstraint.NONE); w[0] = size.width; h[0] = size.height; } if (this.bottomBlock != null) { Size2D size = this.bottomBlock.arrange(g2, RectangleConstraint.NONE); w[1] = size.width; h[1] = size.height; } if (this.leftBlock != null) { Size2D size = this.leftBlock.arrange(g2, RectangleConstraint.NONE); w[2] = size.width; h[2] = size.height; } if (this.rightBlock != null) { Size2D size = this.rightBlock.arrange(g2, RectangleConstraint.NONE); w[3] = size.width; h[3] = size.height; } h[2] = Math.max(h[2], h[3]); h[3] = h[2]; if (this.centerBlock != null) { Size2D size = this.centerBlock.arrange(g2, RectangleConstraint.NONE); w[4] = size.width; h[4] = size.height; } double width = Math.max(w[0], Math.max(w[1], w[2] + w[4] + w[3])); double centerHeight = Math.max(h[2], Math.max(h[3], h[4])); double height = h[0] + h[1] + centerHeight; if (this.topBlock != null) { this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, width, h[0])); } if (this.bottomBlock != null) { this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, height - h[1], width, h[1])); } if (this.leftBlock != null) { this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2], centerHeight)); } if (this.rightBlock != null) { this.rightBlock.setBounds(new Rectangle2D.Double(width - w[3], h[0], w[3], centerHeight)); } if (this.centerBlock != null) { this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], width - w[2] - w[3], centerHeight)); } return new Size2D(width, height); } /** * Performs an arrangement with a fixed width and a range for the height. * * @param container the container. * @param g2 the graphics device. * @param constraint the constraint. * * @return The container size after the arrangement. */ protected Size2D arrangeFR(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { Size2D size1 = arrangeFN(container, g2, constraint.getWidth()); if (constraint.getHeightRange().contains(size1.getHeight())) { return size1; } else { double h = constraint.getHeightRange().constrain(size1.getHeight()); RectangleConstraint c2 = constraint.toFixedHeight(h); return arrange(container, g2, c2); } } /** * Arranges the container width a fixed width and no constraint on the * height. * * @param container the container. * @param g2 the graphics device. * @param width the fixed width. * * @return The container size after arranging the contents. */ protected Size2D arrangeFN(BlockContainer container, Graphics2D g2, double width) { double[] w = new double[5]; double[] h = new double[5]; RectangleConstraint c1 = new RectangleConstraint(width, null, LengthConstraintType.FIXED, 0.0, null, LengthConstraintType.NONE); if (this.topBlock != null) { Size2D size = this.topBlock.arrange(g2, c1); w[0] = size.width; h[0] = size.height; } if (this.bottomBlock != null) { Size2D size = this.bottomBlock.arrange(g2, c1); w[1] = size.width; h[1] = size.height; } RectangleConstraint c2 = new RectangleConstraint(0.0, new Range(0.0, width), LengthConstraintType.RANGE, 0.0, null, LengthConstraintType.NONE); if (this.leftBlock != null) { Size2D size = this.leftBlock.arrange(g2, c2); w[2] = size.width; h[2] = size.height; } if (this.rightBlock != null) { double maxW = Math.max(width - w[2], 0.0); RectangleConstraint c3 = new RectangleConstraint(0.0, new Range(Math.min(w[2], maxW), maxW), LengthConstraintType.RANGE, 0.0, null, LengthConstraintType.NONE); Size2D size = this.rightBlock.arrange(g2, c3); w[3] = size.width; h[3] = size.height; } h[2] = Math.max(h[2], h[3]); h[3] = h[2]; if (this.centerBlock != null) { RectangleConstraint c4 = new RectangleConstraint(width - w[2] - w[3], null, LengthConstraintType.FIXED, 0.0, null, LengthConstraintType.NONE); Size2D size = this.centerBlock.arrange(g2, c4); w[4] = size.width; h[4] = size.height; } double height = h[0] + h[1] + Math.max(h[2], Math.max(h[3], h[4])); return arrange(container, g2, new RectangleConstraint(width, height)); } /** * Performs an arrangement with range constraints on both the vertical * and horizontal sides. * * @param container the container. * @param widthRange the allowable range for the container width. * @param heightRange the allowable range for the container height. * @param g2 the graphics device. * * @return The container size. */ protected Size2D arrangeRR(BlockContainer container, Range widthRange, Range heightRange, Graphics2D g2) { double[] w = new double[5]; double[] h = new double[5]; if (this.topBlock != null) { RectangleConstraint c1 = new RectangleConstraint(widthRange, heightRange); Size2D size = this.topBlock.arrange(g2, c1); w[0] = size.width; h[0] = size.height; } if (this.bottomBlock != null) { Range heightRange2 = Range.shift(heightRange, -h[0], false); RectangleConstraint c2 = new RectangleConstraint(widthRange, heightRange2); Size2D size = this.bottomBlock.arrange(g2, c2); w[1] = size.width; h[1] = size.height; } Range heightRange3 = Range.shift(heightRange, -(h[0] + h[1])); if (this.leftBlock != null) { RectangleConstraint c3 = new RectangleConstraint(widthRange, heightRange3); Size2D size = this.leftBlock.arrange(g2, c3); w[2] = size.width; h[2] = size.height; } Range widthRange2 = Range.shift(widthRange, -w[2], false); if (this.rightBlock != null) { RectangleConstraint c4 = new RectangleConstraint(widthRange2, heightRange3); Size2D size = this.rightBlock.arrange(g2, c4); w[3] = size.width; h[3] = size.height; } h[2] = Math.max(h[2], h[3]); h[3] = h[2]; Range widthRange3 = Range.shift(widthRange, -(w[2] + w[3]), false); if (this.centerBlock != null) { RectangleConstraint c5 = new RectangleConstraint(widthRange3, heightRange3); Size2D size = this.centerBlock.arrange(g2, c5); w[4] = size.width; h[4] = size.height; } double width = Math.max(w[0], Math.max(w[1], w[2] + w[4] + w[3])); double height = h[0] + h[1] + Math.max(h[2], Math.max(h[3], h[4])); if (this.topBlock != null) { this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, width, h[0])); } if (this.bottomBlock != null) { this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, height - h[1], width, h[1])); } if (this.leftBlock != null) { this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2], h[2])); } if (this.rightBlock != null) { this.rightBlock.setBounds(new Rectangle2D.Double(width - w[3], h[0], w[3], h[3])); } if (this.centerBlock != null) { this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], width - w[2] - w[3], height - h[0] - h[1])); } return new Size2D(width, height); } /** * Arranges the items within a container. * * @param container the container. * @param constraint the constraint. * @param g2 the graphics device. * * @return The container size after the arrangement. */ protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { double[] w = new double[5]; double[] h = new double[5]; w[0] = constraint.getWidth(); if (this.topBlock != null) { RectangleConstraint c1 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight()), LengthConstraintType.RANGE); Size2D size = this.topBlock.arrange(g2, c1); h[0] = size.height; } w[1] = w[0]; if (this.bottomBlock != null) { RectangleConstraint c2 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight() - h[0]), LengthConstraintType.RANGE); Size2D size = this.bottomBlock.arrange(g2, c2); h[1] = size.height; } h[2] = constraint.getHeight() - h[1] - h[0]; if (this.leftBlock != null) { RectangleConstraint c3 = new RectangleConstraint(0.0, new Range(0.0, constraint.getWidth()), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.leftBlock.arrange(g2, c3); w[2] = size.width; } h[3] = h[2]; if (this.rightBlock != null) { RectangleConstraint c4 = new RectangleConstraint(0.0, new Range(0.0, Math.max(constraint.getWidth() - w[2], 0.0)), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.rightBlock.arrange(g2, c4); w[3] = size.width; } h[4] = h[2]; w[4] = constraint.getWidth() - w[3] - w[2]; RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]); if (this.centerBlock != null) { this.centerBlock.arrange(g2, c5); } if (this.topBlock != null) { this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0], h[0])); } if (this.bottomBlock != null) { this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2], w[1], h[1])); } if (this.leftBlock != null) { this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2], h[2])); } if (this.rightBlock != null) { this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0], w[3], h[3])); } if (this.centerBlock != null) { this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4], h[4])); } return new Size2D(constraint.getWidth(), constraint.getHeight()); } /** * Clears the layout. */ @Override public void clear() { this.centerBlock = null; this.topBlock = null; this.bottomBlock = null; this.leftBlock = null; this.rightBlock = null; } /** * Tests this arrangement for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BorderArrangement)) { return false; } BorderArrangement that = (BorderArrangement) obj; if (!ObjectUtilities.equal(this.topBlock, that.topBlock)) { return false; } if (!ObjectUtilities.equal(this.bottomBlock, that.bottomBlock)) { return false; } if (!ObjectUtilities.equal(this.leftBlock, that.leftBlock)) { return false; } if (!ObjectUtilities.equal(this.rightBlock, that.rightBlock)) { return false; } if (!ObjectUtilities.equal(this.centerBlock, that.centerBlock)) { return false; } return true; } }
package org.jfree.data.xy; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jfree.chart.util.ObjectUtils; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.DomainInfo; import org.jfree.data.Range; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.general.SeriesChangeEvent; /** * An {@link XYDataset} where every series shares the same x-values (required * for generating stacked area charts). */ public class DefaultTableXYDataset extends AbstractIntervalXYDataset implements TableXYDataset, IntervalXYDataset, DomainInfo, PublicCloneable { /** * Storage for the data - this list will contain zero, one or many * XYSeries objects. */ private List<XYSeries> data; /** Storage for the x values. */ private HashSet<Number> xPoints; /** A flag that controls whether or not events are propogated. */ private boolean propagateEvents = true; /** A flag that controls auto pruning. */ private boolean autoPrune = false; /** The delegate used to control the interval width. */ private IntervalXYDelegate intervalDelegate; /** * Creates a new empty dataset. */ public DefaultTableXYDataset() { this(false); } /** * Creates a new empty dataset. * * @param autoPrune a flag that controls whether or not x-values are * removed whenever the corresponding y-values are all * <code>null</code>. */ public DefaultTableXYDataset(boolean autoPrune) { this.autoPrune = autoPrune; this.data = new ArrayList<XYSeries>(); this.xPoints = new HashSet<Number>(); this.intervalDelegate = new IntervalXYDelegate(this, false); addChangeListener(this.intervalDelegate); } /** * Returns the flag that controls whether or not x-values are removed from * the dataset when the corresponding y-values are all <code>null</code>. * * @return A boolean. */ public boolean isAutoPrune() { return this.autoPrune; } /** * Adds a series to the collection and sends a {@link DatasetChangeEvent} * to all registered listeners. The series should be configured to NOT * allow duplicate x-values. * * @param series the series (<code>null</code> not permitted). */ public void addSeries(XYSeries series) { ParamChecks.nullNotPermitted(series, "series"); if (series.getAllowDuplicateXValues()) { throw new IllegalArgumentException( "Cannot accept XYSeries that allow duplicate values. " + "Use XYSeries(seriesName, <sort>, false) constructor."); } updateXPoints(series); this.data.add(series); series.addChangeListener(this); fireDatasetChanged(); } /** * Adds any unique x-values from 'series' to the dataset, and also adds any * x-values that are in the dataset but not in 'series' to the series. * * @param series the series (<code>null</code> not permitted). */ private void updateXPoints(XYSeries series) { ParamChecks.nullNotPermitted(series, "series"); Set<Number> seriesXPoints = new HashSet<Number>(); boolean savedState = this.propagateEvents; this.propagateEvents = false; for (int itemNo = 0; itemNo < series.getItemCount(); itemNo++) { Number xValue = series.getX(itemNo); seriesXPoints.add(xValue); if (!this.xPoints.contains(xValue)) { this.xPoints.add(xValue); for (XYSeries dataSeries : this.data) { if (!dataSeries.equals(series)) { dataSeries.add(xValue, null); } } } } for (Number xPoint : this.xPoints) { if (!seriesXPoints.contains(xPoint)) { series.add(xPoint, null); } } this.propagateEvents = savedState; } /** * Updates the x-values for all the series in the dataset. */ public void updateXPoints() { this.propagateEvents = false; for (XYSeries aData : this.data) { updateXPoints(aData); } if (this.autoPrune) { prune(); } this.propagateEvents = true; } /** * Returns the number of series in the collection. * * @return The series count. */ @Override public int getSeriesCount() { return this.data.size(); } /** * Returns the number of x values in the dataset. * * @return The number of x values in the dataset. */ @Override public int getItemCount() { if (this.xPoints == null) { return 0; } else { return this.xPoints.size(); } } /** * Returns a series. * * @param series the series (zero-based index). * * @return The series (never <code>null</code>). */ public XYSeries getSeries(int series) { if ((series < 0) || (series >= getSeriesCount())) { throw new IllegalArgumentException("Index outside valid range."); } return this.data.get(series); } /** * Returns the key for a series. * * @param series the series (zero-based index). * * @return The key for a series. */ @Override public Comparable getSeriesKey(int series) { // check arguments...delegated return getSeries(series).getKey(); } /** * Returns the number of items in the specified series. * * @param series the series (zero-based index). * * @return The number of items in the specified series. */ @Override public int getItemCount(int series) { // check arguments...delegated return getSeries(series).getItemCount(); } /** * Returns the x-value for the specified series and item. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The x-value for the specified series and item. */ @Override public Number getX(int series, int item) { XYSeries s = this.data.get(series); return s.getX(item); } /** * Returns the starting X value for the specified series and item. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The starting X value. */ @Override public Number getStartX(int series, int item) { return this.intervalDelegate.getStartX(series, item); } /** * Returns the ending X value for the specified series and item. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The ending X value. */ @Override public Number getEndX(int series, int item) { return this.intervalDelegate.getEndX(series, item); } /** * Returns the y-value for the specified series and item. * * @param series the series (zero-based index). * @param index the index of the item of interest (zero-based). * * @return The y-value for the specified series and item (possibly * <code>null</code>). */ @Override public Number getY(int series, int index) { XYSeries s = this.data.get(series); return s.getY(index); } /** * Returns the starting Y value for the specified series and item. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The starting Y value. */ @Override public Number getStartY(int series, int item) { return getY(series, item); } /** * Returns the ending Y value for the specified series and item. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The ending Y value. */ @Override public Number getEndY(int series, int item) { return getY(series, item); } /** * Removes all the series from the collection and sends a * {@link DatasetChangeEvent} to all registered listeners. */ public void removeAllSeries() { // Unregister the collection as a change listener to each series in // the collection. for (XYSeries series : this.data) { series.removeChangeListener(this); } // Remove all the series from the collection and notify listeners. this.data.clear(); this.xPoints.clear(); fireDatasetChanged(); } /** * Removes a series from the collection and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param series the series (<code>null</code> not permitted). */ public void removeSeries(XYSeries series) { ParamChecks.nullNotPermitted(series, "series"); if (this.data.contains(series)) { series.removeChangeListener(this); this.data.remove(series); if (this.data.isEmpty()) { this.xPoints.clear(); } fireDatasetChanged(); } } /** * Removes a series from the collection and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param series the series (zero based index). */ public void removeSeries(int series) { if ((series < 0) || (series > getSeriesCount())) { throw new IllegalArgumentException("Index outside valid range."); } // fetch the series, remove the change listener, then remove the series. XYSeries s = this.data.get(series); s.removeChangeListener(this); this.data.remove(series); if (this.data.isEmpty()) { this.xPoints.clear(); } else if (this.autoPrune) { prune(); } fireDatasetChanged(); } /** * Removes the items from all series for a given x value. * * @param x the x-value. */ public void removeAllValuesForX(Number x) { ParamChecks.nullNotPermitted(x, "x"); boolean savedState = this.propagateEvents; this.propagateEvents = false; for (XYSeries series : this.data) { series.remove(x); } this.propagateEvents = savedState; this.xPoints.remove(x); fireDatasetChanged(); } /** * Returns <code>true</code> if all the y-values for the specified x-value * are <code>null</code> and <code>false</code> otherwise. * * @param x the x-value. * * @return A boolean. */ protected boolean canPrune(Number x) { for (XYSeries series : this.data) { if (series.getY(series.indexOf(x)) != null) { return false; } } return true; } /** * Removes all x-values for which all the y-values are <code>null</code>. */ public void prune() { Set<Number> hs = (HashSet<Number>) this.xPoints.clone(); for (Number x : hs) { if (canPrune(x)) { removeAllValuesForX(x); } } } /** * This method receives notification when a series belonging to the dataset * changes. It responds by updating the x-points for the entire dataset * and sending a {@link DatasetChangeEvent} to all registered listeners. * * @param event information about the change. */ @Override public void seriesChanged(SeriesChangeEvent event) { if (this.propagateEvents) { updateXPoints(); fireDatasetChanged(); } } /** * Tests this collection for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof DefaultTableXYDataset)) { return false; } DefaultTableXYDataset that = (DefaultTableXYDataset) obj; if (this.autoPrune != that.autoPrune) { return false; } if (this.propagateEvents != that.propagateEvents) { return false; } if (!this.intervalDelegate.equals(that.intervalDelegate)) { return false; } if (!ObjectUtils.equal(this.data, that.data)) { return false; } return true; } /** * Returns a hash code. * * @return A hash code. */ @Override public int hashCode() { int result; result = (this.data != null ? this.data.hashCode() : 0); result = 29 * result + (this.xPoints != null ? this.xPoints.hashCode() : 0); result = 29 * result + (this.propagateEvents ? 1 : 0); result = 29 * result + (this.autoPrune ? 1 : 0); return result; } /** * Returns an independent copy of this dataset. * * @return A clone. * * @throws CloneNotSupportedException if there is some reason that cloning * cannot be performed. */ @Override public Object clone() throws CloneNotSupportedException { DefaultTableXYDataset clone = (DefaultTableXYDataset) super.clone(); int seriesCount = this.data.size(); clone.data = new java.util.ArrayList<XYSeries>(seriesCount); for (int i = 0; i < seriesCount; i++) { XYSeries series = this.data.get(i); clone.data.add((XYSeries)series.clone()); } clone.intervalDelegate = new IntervalXYDelegate(clone); // need to configure the intervalDelegate to match the original clone.intervalDelegate.setFixedIntervalWidth(getIntervalWidth()); clone.intervalDelegate.setAutoWidth(isAutoWidth()); clone.intervalDelegate.setIntervalPositionFactor( getIntervalPositionFactor()); clone.updateXPoints(); return clone; } /** * Returns the minimum x-value in the dataset. * * @param includeInterval a flag that determines whether or not the * x-interval is taken into account. * * @return The minimum value. */ @Override public double getDomainLowerBound(boolean includeInterval) { return this.intervalDelegate.getDomainLowerBound(includeInterval); } /** * Returns the maximum x-value in the dataset. * * @param includeInterval a flag that determines whether or not the * x-interval is taken into account. * * @return The maximum value. */ @Override public double getDomainUpperBound(boolean includeInterval) { return this.intervalDelegate.getDomainUpperBound(includeInterval); } /** * Returns the range of the values in this dataset's domain. * * @param includeInterval a flag that determines whether or not the * x-interval is taken into account. * * @return The range. */ @Override public Range getDomainBounds(boolean includeInterval) { if (includeInterval) { return this.intervalDelegate.getDomainBounds(includeInterval); } else { return DatasetUtilities.iterateDomainBounds(this, includeInterval); } } /** * Returns the interval position factor. * * @return The interval position factor. */ public double getIntervalPositionFactor() { return this.intervalDelegate.getIntervalPositionFactor(); } /** * Sets the interval position factor. Must be between 0.0 and 1.0 inclusive. * If the factor is 0.5, the gap is in the middle of the x values. If it * is lesser than 0.5, the gap is farther to the left and if greater than * 0.5 it gets farther to the right. * * @param d the new interval position factor. */ public void setIntervalPositionFactor(double d) { this.intervalDelegate.setIntervalPositionFactor(d); fireDatasetChanged(); } /** * returns the full interval width. * * @return The interval width to use. */ public double getIntervalWidth() { return this.intervalDelegate.getIntervalWidth(); } /** * Sets the interval width to a fixed value, and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param d the new interval width (must be > 0). */ public void setIntervalWidth(double d) { this.intervalDelegate.setFixedIntervalWidth(d); fireDatasetChanged(); } /** * Returns whether the interval width is automatically calculated or not. * * @return A flag that determines whether or not the interval width is * automatically calculated. */ public boolean isAutoWidth() { return this.intervalDelegate.isAutoWidth(); } /** * Sets the flag that indicates whether the interval width is automatically * calculated or not. * * @param b a boolean. */ public void setAutoWidth(boolean b) { this.intervalDelegate.setAutoWidth(b); fireDatasetChanged(); } }
package org.lightmare.cache; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.lightmare.jndi.JndiManager; import org.lightmare.jpa.JpaManager; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.LogUtils; import org.lightmare.utils.NamingUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Container class to cache connections and connection types * * @author levan * @since 0.0.65-SNAPSHOT */ public class ConnectionContainer { // Keeps unique EntityManagerFactories builded by unit names private static final ConcurrentMap<String, ConnectionSemaphore> CONNECTIONS = new ConcurrentHashMap<String, ConnectionSemaphore>(); // Keeps unique PoolConfigs builded by unit names private static final ConcurrentMap<String, PoolProviderType> POOL_CONFIG_TYPES = new ConcurrentHashMap<String, PoolProviderType>(); private static final Logger LOG = Logger .getLogger(ConnectionContainer.class); /** * Checks if connection with passed unit name is cached * * @param unitName * @return <code>boolean</code> */ public static boolean checkForEmf(String unitName) { boolean check = StringUtils.valid(unitName); if (check) { check = CONNECTIONS.containsKey(unitName); } return check; } /** * Gets {@link ConnectionSemaphore} from cache without waiting for lock * * @param unitName * @return {@link ConnectionSemaphore} */ public static ConnectionSemaphore getSemaphore(String unitName) { return CONNECTIONS.get(unitName); } /** * Checks if deployed {@link ConnectionSemaphore} componnents * * @param semaphore * @return <code>boolean</code> */ private static boolean checkOnProgress(ConnectionSemaphore semaphore) { return semaphore.isInProgress() && ObjectUtils.notTrue(semaphore.isBound()); } /** * Creates and locks {@link ConnectionSemaphore} instance * * @param unitName * @return {@link ConnectionSemaphore} */ private static ConnectionSemaphore createSemaphore(String unitName) { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); ConnectionSemaphore current = null; if (semaphore == null) { semaphore = new ConnectionSemaphore(); semaphore.setUnitName(unitName); semaphore.setInProgress(Boolean.TRUE); semaphore.setCached(Boolean.TRUE); current = CONNECTIONS.putIfAbsent(unitName, semaphore); } if (current == null) { current = semaphore; } current.incrementUser(); return current; } /** * Caches {@link ConnectionSemaphore} with lock * * @param unitName * @param jndiName * @return {@link ConnectionSemaphore} */ public static ConnectionSemaphore cacheSemaphore(String unitName, String jndiName) { ConnectionSemaphore semaphore; if (StringUtils.valid(unitName)) { semaphore = createSemaphore(unitName); if (StringUtils.valid(jndiName)) { ConnectionSemaphore existent = CONNECTIONS.putIfAbsent( jndiName, semaphore); if (existent == null) { semaphore.setJndiName(jndiName); } } } else { semaphore = null; } return semaphore; } /** * Waits until {@link ConnectionSemaphore} is in progress (locked) * * @param semaphore */ private static void awaitConnection(ConnectionSemaphore semaphore) { synchronized (semaphore) { boolean inProgress = checkOnProgress(semaphore); while (inProgress) { try { semaphore.wait(); inProgress = checkOnProgress(semaphore); } catch (InterruptedException ex) { inProgress = Boolean.FALSE; LOG.error(ex.getMessage(), ex); } } } } /** * Checks if {@link ConnectionSemaphore} is in progress and if it is waits * while lock is released * * @param semaphore * @return <code>boolean</code> */ private static boolean isInProgress(ConnectionSemaphore semaphore) { boolean inProgress = ObjectUtils.notNull(semaphore); if (inProgress) { inProgress = checkOnProgress(semaphore); if (inProgress) { awaitConnection(semaphore); } } return inProgress; } /** * Checks if {@link ConnectionSemaphore#isInProgress()} for appropriated * unit name * * @param jndiName * @return <code>boolean</code> */ public static boolean isInProgress(String jndiName) { boolean inProgress; ConnectionSemaphore semaphore = CONNECTIONS.get(jndiName); inProgress = isInProgress(semaphore); return inProgress; } /** * Gets {@link ConnectionSemaphore} from cache, awaits if connection * instantiation is in progress * * @param unitName * @return {@link ConnectionSemaphore} * @throws IOException */ public static ConnectionSemaphore getConnection(String unitName) throws IOException { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); isInProgress(semaphore); return semaphore; } /** * Gets {@link EntityManagerFactory} from {@link ConnectionSemaphore}, * awaits if connection * * @param unitName * @return {@link EntityManagerFactory} * @throws IOException */ public static EntityManagerFactory getEntityManagerFactory(String unitName) throws IOException { EntityManagerFactory emf; ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); boolean inProgress = ObjectUtils.notNull(semaphore); if (inProgress) { inProgress = checkOnProgress(semaphore); if (inProgress) { awaitConnection(semaphore); } emf = semaphore.getEmf(); } else { emf = null; } return emf; } /** * Removes connection from {@link javax.naming.Context} cache * * @param semaphore */ private static void unbindConnection(ConnectionSemaphore semaphore) { String jndiName = semaphore.getJndiName(); if (ObjectUtils.notNull(jndiName) && semaphore.isBound()) { JndiManager jndiManager = new JndiManager(); try { String fullJndiName = NamingUtils.createJpaJndiName(jndiName); Object boundData = jndiManager.lookup(fullJndiName); if (ObjectUtils.notNull(boundData)) { jndiManager.unbind(fullJndiName); } } catch (IOException ex) { LogUtils.error(LOG, ex, NamingUtils.COULD_NOT_UNBIND_NAME_ERROR, jndiName, ex.getMessage()); } } } /** * Closes all existing {@link EntityManagerFactory} instances kept in cache */ public static void closeEntityManagerFactories() { Collection<ConnectionSemaphore> semaphores = CONNECTIONS.values(); EntityManagerFactory emf; for (ConnectionSemaphore semaphore : semaphores) { emf = semaphore.getEmf(); JpaManager.closeEntityManagerFactory(emf); } synchronized (CONNECTIONS) { CONNECTIONS.clear(); } } /** * Closes all {@link javax.persistence.EntityManagerFactory} cached * instances * * @throws IOException */ public static void closeConnections() throws IOException { ConnectionContainer.closeEntityManagerFactories(); Initializer.closeAll(); } /** * Closes connection ({@link EntityManagerFactory}) in passed * {@link ConnectionSemaphore} * * @param semaphore */ private static void closeConnection(ConnectionSemaphore semaphore) { int users = semaphore.decrementUser(); if (users < ConnectionSemaphore.MINIMAL_USERS) { EntityManagerFactory emf = semaphore.getEmf(); JpaManager.closeEntityManagerFactory(emf); unbindConnection(semaphore); synchronized (CONNECTIONS) { CONNECTIONS.remove(semaphore.getUnitName()); String jndiName = semaphore.getJndiName(); if (StringUtils.valid(jndiName)) { CONNECTIONS.remove(jndiName); semaphore.setBound(Boolean.FALSE); semaphore.setCached(Boolean.FALSE); } } } } /** * Removes {@link ConnectionSemaphore} from cache and unbinds name from * {@link javax.naming.Context} * * @param unitName */ public static void removeConnection(String unitName) { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); if (ObjectUtils.notNull(semaphore)) { awaitConnection(semaphore); closeConnection(semaphore); } } /** * Caches {@link PoolProviderType} to use for data source deployment * * @param jndiName * @param type */ public static void setPollProviderType(String jndiName, PoolProviderType type) { POOL_CONFIG_TYPES.put(jndiName, type); } /** * Gets configured {@link PoolProviderType} for data sources deployment * * @param jndiName * @return {@link PoolProviderType} */ public static PoolProviderType getAndRemovePoolProviderType(String jndiName) { PoolProviderType type = POOL_CONFIG_TYPES.get(jndiName); if (type == null) { type = new PoolConfig().getPoolProviderType(); POOL_CONFIG_TYPES.put(jndiName, type); } POOL_CONFIG_TYPES.remove(jndiName); return type; } /** * Closes all connections and data sources and clears all cached data * * @throws IOException */ public static void clear() throws IOException { closeConnections(); CONNECTIONS.clear(); POOL_CONFIG_TYPES.clear(); } }
package org.openhab.binding.fems.tools; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.util.Date; import java.util.List; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.types.State; import org.openhab.binding.fems.Constants; import org.openhab.binding.fems.agents.ess.message.ESSAgentListener; import org.openhab.binding.fems.exceptions.FEMSException; import org.openhab.binding.fems.exceptions.IPException; import org.openhab.binding.fems.exceptions.InternetException; import org.openhab.binding.fems.exceptions.RS485Exception; import org.openhab.binding.fems.internal.FEMSHandlerFactory; import org.openhab.binding.fems.internal.essprotocol.modbus.ModbusElement; import org.openhab.binding.fems.internal.essprotocol.modbus.ModbusElementRange; import org.openhab.binding.fems.internal.essprotocol.modbus.ModbusItem; public class FEMSInit implements ESSAgentListener { private volatile List<ModbusElementRange> wordRanges = null; public void init(String ess, boolean debug) { int returnCode = 0; Log log = new Log(FEMSHandlerFactory.class); try { log.info("FEMS Initialization"); // init LCD display Constants.IO_AGENT.setLcdText(true, "FEMS Selbsttest"); // Init runtime variables Runtime rt = Runtime.getRuntime(); Process proc; InitStatus initStatus = new InitStatus(); try { // check for valid ip address InetAddress ip = Tools.getIPaddress(); if(ip == null) { try { proc = rt.exec("/sbin/dhclient eth0"); proc.waitFor(); ip = Tools.getIPaddress(); /* try again */ if(ip == null) { /* still no IP */ throw new IPException(); } } catch (IOException | InterruptedException e) { throw new IPException(e.getMessage()); } } log.info("IP: " + ip.getHostAddress()); initStatus.setIp(true); Constants.IO_AGENT.setLcdText(initStatus + " IP ok "); Constants.IO_AGENT.handleCommand(Constants.UserLED_1, OnOffType.ON); // check time if(Tools.isDateValid()) { /* date is valid, so we check internet access only */ log.info("Date ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); try { URL url = new URL("https://fenecon.de"); URLConnection con = url.openConnection(); con.setConnectTimeout(5000); con.getContent(); } catch (IOException e) { throw new InternetException(e.getMessage()); } } else { log.info("Date not ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); try { proc = rt.exec("/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org"); proc.waitFor(); if(!Tools.isDateValid()) { // try one more time proc = rt.exec("/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org"); proc.waitFor(); if(!Tools.isDateValid()) { throw new InternetException("Wrong Date: " + Constants.LONG_DATE_FORMAT.format(new Date())); } } log.info("Date now ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); } catch (IOException | InterruptedException e) { throw new InternetException(e.getMessage()); } } log.info("Internet access is available"); initStatus.setInternet(true); Constants.IO_AGENT.setLcdText(initStatus + " Internet ok"); Constants.IO_AGENT.handleCommand(Constants.UserLED_2, OnOffType.ON); // start system update log.info("Start system update"); try { proc = rt.exec("/usr/bin/fems-autoupdate"); } catch (IOException e) { log.error(e.getMessage()); } // test modbus String searchString = "BSMU_Battery_Stack_Overall_SOC"; if(ess.equals("cess")) { searchString = "Battery_string_1_SOC"; } if(!debug) { State soc = null; for(int i=0; i<20; i++) { if(wordRanges != null) { outerloop: for (ModbusElementRange wordRange : wordRanges) { for (ModbusElement word : wordRange.getWords()) { if(word instanceof ModbusItem) { ModbusItem item = (ModbusItem)word; if(item.getName().equals(searchString)) { soc = item.getState(); break outerloop; } } } } } else { log.info("No modbus data received yet - waiting"); Thread.sleep(5000); } } if(soc != null) { log.info("Modbus OK - SOC: " + soc.toString()); initStatus.setModbus(true); Constants.IO_AGENT.setLcdText(initStatus + " RS485 ok "); Constants.IO_AGENT.handleCommand(Constants.UserLED_3, OnOffType.ON); } else { throw new RS485Exception(); } } else { // if we are in debug mode: ignore RS485-errors log.info("Debug mode: ignore RS485-Error"); } // Exit message log.info("Finished without error"); Constants.IO_AGENT.setLcdText(initStatus + " erfolgreich"); //TODO: remove; not necessary anymore; announce systemd finished /*log.info("Announce systemd: ready"); try { proc = rt.exec("/bin/systemd-notify --ready"); proc.waitFor(); } catch (IOException | InterruptedException e) { log.error(e.getMessage()); }*/ } catch (FEMSException e) { log.error(e.getMessage()); log.error("Finished with error"); Constants.IO_AGENT.setLcdText(initStatus + " " + e.getMessage()); returnCode = 1; } // Check if Yaler is active if(FEMSYaler.getFEMSYaler().isActive()) { log.info("Yaler is activated"); } else { log.info("Yaler is deactivated"); } log.info("openHAB started"); // Send message Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog()); Constants.IO_AGENT.handleCommand(Constants.UserLED_4, OnOffType.ON); } catch (Throwable e) { // Catch everything else returnCode = 2; StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("Critical error: " + sw.toString()); e.printStackTrace(); Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog()); // try to send log } if(returnCode != 0) { log.error("Waiting..."); try { Thread.sleep(5000); } catch (InterruptedException e) { } System.exit(returnCode); } } @Override public void essUpdate(List<ModbusElementRange> wordRanges) { this.wordRanges = wordRanges; } }
package org.opentripplanner.streets; import com.conveyal.gtfs.model.Stop; import com.conveyal.osmlib.Node; import com.conveyal.osmlib.OSM; import com.conveyal.osmlib.Way; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TLongIntMap; import gnu.trove.map.hash.TLongIntHashMap; import org.opentripplanner.common.geometry.SphericalDistanceLibrary; import org.opentripplanner.transit.TransitLayer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; public class StreetLayer implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(StreetLayer.class); private static final int SNAP_RADIUS_MM = 5 * 1000; // Edge lists should be constructed after the fact from edges. This minimizes serialized size too. transient List<TIntList> outgoingEdges; transient List<TIntList> incomingEdges; transient IntHashGrid spatialIndex = new IntHashGrid(); TLongIntMap vertexIndexForOsmNode = new TLongIntHashMap(100_000, 0.75f, -1, -1); // TIntLongMap osmWayForEdgeIndex; // TODO use negative IDs for temp vertices and edges. // This is only used when loading from OSM, and is then nulled to save memory. transient OSM osm; // Initialize these when we have an estimate of the number of expected edges. public VertexStore vertexStore = new VertexStore(100_000); public EdgeStore edgeStore = new EdgeStore(vertexStore, 200_000); transient Histogram edgesPerWayHistogram = new Histogram("Number of edges per way per direction"); transient Histogram pointsPerEdgeHistogram = new Histogram("Number of geometry points per edge"); public TransitLayer linkedTransitLayer = null; public void loadFromOsm (OSM osm) { LOG.info("Making street edges from OSM ways..."); this.osm = osm; for (Map.Entry<Long, Way> entry : osm.ways.entrySet()) { Way way = entry.getValue(); if ( ! (way.hasTag("highway") || way.hasTag("area", "yes") || way.hasTag("public_transport", "platform"))) { continue; } int nEdgesCreated = 0; int beginIdx = 0; // Break each OSM way into topological segments between intersections, and make one edge per segment. for (int n = 1; n < way.nodes.length; n++) { if (osm.intersectionNodes.contains(way.nodes[n]) || n == (way.nodes.length - 1)) { makeEdge(way, beginIdx, n); nEdgesCreated += 1; beginIdx = n; } } edgesPerWayHistogram.add(nEdgesCreated); } LOG.info("Done making street edges."); LOG.info("Made {} vertices and {} edges.", vertexStore.nVertices, edgeStore.nEdges); edgesPerWayHistogram.display(); pointsPerEdgeHistogram.display(); // Clear unneeded indexes vertexIndexForOsmNode = null; osm = null; } /** * Get or create mapping from a global long OSM ID to an internal street vertex ID, creating the vertex as needed. */ private int getVertexIndexForOsmNode(long osmNodeId) { int vertexIndex = vertexIndexForOsmNode.get(osmNodeId); if (vertexIndex == -1) { // Register a new vertex, incrementing the index starting from zero. // Store node coordinates for this new street vertex Node node = osm.nodes.get(osmNodeId); vertexIndex = vertexStore.addVertex(node.getLat(), node.getLon()); vertexIndexForOsmNode.put(osmNodeId, vertexIndex); } return vertexIndex; } /** * Calculate length from a list of nodes. This is done in advance of creating an edge pair because we need to catch * potential length overflows before we ever reserve space for the edges. */ private int getEdgeLengthMillimeters (List<Node> nodes) { double lengthMeters = 0; Node prevNode = nodes.get(0); for (Node node : nodes.subList(1, nodes.size())) { lengthMeters += SphericalDistanceLibrary .fastDistance(prevNode.getLat(), prevNode.getLon(), node.getLat(), node.getLon()); prevNode = node; } if (lengthMeters * 1000 > Integer.MAX_VALUE) { return -1; } return (int)(lengthMeters * 1000); } /** * Make an edge for a sub-section of an OSM way, typically between two intersections or dead ends. */ private void makeEdge (Way way, int beginIdx, int endIdx) { long beginOsmNodeId = way.nodes[beginIdx]; long endOsmNodeId = way.nodes[endIdx]; // Will create mapping if it doesn't exist yet. int beginVertexIndex = getVertexIndexForOsmNode(beginOsmNodeId); int endVertexIndex = getVertexIndexForOsmNode(endOsmNodeId); // Fetch the OSM node objects for this subsection of the OSM way. int nNodes = endIdx - beginIdx + 1; List<Node> nodes = new ArrayList<>(nNodes); for (int n = beginIdx; n <= endIdx; n++) { long nodeId = way.nodes[n]; Node node = osm.nodes.get(nodeId); nodes.add(node); } // Compute edge length and check that it can be properly represented. int edgeLengthMillimeters = getEdgeLengthMillimeters(nodes); if (edgeLengthMillimeters < 0) { LOG.warn("Street segment was too long to be represented, skipping."); return; } // Create and store the forward and backward edge EdgeStore.Edge newForwardEdge = edgeStore.addStreetPair(beginVertexIndex, endVertexIndex, edgeLengthMillimeters); newForwardEdge.setGeometry(nodes); pointsPerEdgeHistogram.add(nNodes); } public void indexStreets () { LOG.info("Indexing streets..."); spatialIndex = new IntHashGrid(); // Skip by twos, we only need to index forward (even) edges. Their odd companions have the same geometry. EdgeStore.Edge edge = edgeStore.getCursor(); for (int e = 0; e < edgeStore.nEdges; e += 2) { edge.seek(e); // FIXME for now we are skipping edges over 1km because they can have huge envelopes. TODO Rasterize them. if (edge.getLengthMm() < 1 * 1000 * 1000) { spatialIndex.insert(edge.getEnvelope(), e); } } LOG.info("Done indexing streets."); } /** After JIT this appears to scale almost linearly with number of cores. */ public void testRouting (boolean withDestinations, TransitLayer transitLayer) { LOG.info("Routing from random vertices in the graph..."); LOG.info("{} goal direction.", withDestinations ? "Using" : "Not using"); StreetRouter router = new StreetRouter(this); long startTime = System.currentTimeMillis(); final int N = 1_000; final int nVertices = outgoingEdges.size(); Random random = new Random(); for (int n = 0; n < N; n++) { int from = random.nextInt(nVertices); VertexStore.Vertex vertex = vertexStore.getCursor(from); // LOG.info("Routing from ({}, {}).", vertex.getLat(), vertex.getLon()); router.setOrigin(from); router.toVertex = withDestinations ? random.nextInt(nVertices) : StreetRouter.ALL_VERTICES; if (n != 0 && n % 100 == 0) { LOG.info(" {}/{} searches", n, N); } } double eTime = System.currentTimeMillis() - startTime; LOG.info("average response time {} msec", eTime / N); } public void buildEdgeLists() { LOG.info("Building edge lists from edges..."); outgoingEdges = new ArrayList<>(vertexStore.nVertices); incomingEdges = new ArrayList<>(vertexStore.nVertices); for (int v = 0; v < vertexStore.nVertices; v++) { outgoingEdges.add(new TIntArrayList(4)); incomingEdges.add(new TIntArrayList(4)); } EdgeStore.Edge edge = edgeStore.getCursor(); while (edge.advance()) { outgoingEdges.get(edge.getFromVertex()).add(edge.edgeIndex); incomingEdges.get(edge.getToVertex()).add(edge.edgeIndex); } LOG.info("Done building edge lists."); // Display histogram of edge list sizes Histogram edgesPerListHistogram = new Histogram("Number of edges per edge list"); for (TIntList edgeList : outgoingEdges) { edgesPerListHistogram.add(edgeList.size()); } for (TIntList edgeList : incomingEdges) { edgesPerListHistogram.add(edgeList.size()); } edgesPerListHistogram.display(); } /** * Create a street-layer vertex representing a transit stop. * Connect that new vertex to the street network if possible. * The vertex will be created and assigned an index whether or not it is successfully linked. * * TODO maybe use X and Y everywhere for fixed point, and lat/lon for double precision degrees. * TODO move this into Split.perform(), store streetLayer ref in Split * * @return the index of a street vertex very close to this stop, or -1 if no such vertex could be found or created. */ public int getOrCreateVertexNear (double lat, double lon, double radiusMeters) { Split split = findSplit(lat, lon, radiusMeters); if (split == null) { // If no linking site was found within range. return -1; } // We have a linking site. Find or make a suitable vertex at that site. // Retaining the original Edge cursor object inside findSplit is not necessary, one object creation is harmless. EdgeStore.Edge edge = edgeStore.getCursor(split.edge); // Check for cases where we don't need to create a new vertex (the edge is reached end-wise) if (split.distance0_mm < SNAP_RADIUS_MM || split.distance1_mm < SNAP_RADIUS_MM) { if (split.distance0_mm < split.distance1_mm) { // Very close to the beginning of the edge. return edge.getFromVertex(); } else { // Very close to the end of the edge. return edge.getToVertex(); } } // The split is somewhere away from an existing intersection vertex. Make a new vertex. int newVertexIndex = vertexStore.addVertexFixed((int)split.fLat, (int)split.fLon); // Modify the existing bidirectional edge pair to lead up to the split. // Its spatial index entry is still valid, its envelope has only shrunk. int oldToVertex = edge.getToVertex(); edge.setLengthMm(split.distance0_mm); edge.setToVertex(newVertexIndex); edge.setGeometry(Collections.EMPTY_LIST); // Turn it into a straight line for now. // Make a second, new bidirectional edge pair after the split and add it to the spatial index. // New edges will be added to edge lists later (the edge list is a transient index). EdgeStore.Edge newEdge = edgeStore.addStreetPair(newVertexIndex, oldToVertex, split.distance1_mm); spatialIndex.insert(newEdge.getEnvelope(), newEdge.edgeIndex); // TODO newEdge.copyFlagsFrom(edge) to match the existing edge... return newVertexIndex; // TODO store street-to-stop distance in a table in TransitLayer. This also allows adjusting for subway entrances etc. } /** * Non-destructively find a location on an existing street near the given point. * PARAMETERS ARE FLOATING POINT GEOGRAPHIC (not fixed point ints) * @return a Split object representing a point along a sub-segment of a specific edge, or null if there are no streets nearby. */ public Split findSplit (double lat, double lon, double radiusMeters) { return Split.find (lat, lon, radiusMeters, this); } /** * For every stop in a TransitLayer, find or create a nearby vertex in the street layer and record the connection * between the two. * It only makes sense to link one TransitLayer to one StreetLayer, otherwise the bi-mapping between transit stops * and street vertices would be ambiguous. */ public void associateStops (TransitLayer transitLayer, int radiusMeters) { for (Stop stop : transitLayer.stopForIndex) { int streetVertexIndex = getOrCreateVertexNear(stop.stop_lat, stop.stop_lon, radiusMeters); transitLayer.streetVertexForStop.add(streetVertexIndex); // -1 means no link // The inverse stopForStreetVertex map is a transient, derived index and will be built later. } // Bidirectional reference between the StreetLayer and the TransitLayer transitLayer.linkedStreetLayer = this; this.linkedTransitLayer = transitLayer; } public void splitStreet(int fixedLon, int fixedLat, boolean transit, boolean out) { } public int getVertexCount() { return vertexStore.nVertices; } }
package org.quickmail.transport; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Date; import java.util.List; import java.util.Objects; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import javax.mail.util.ByteArrayDataSource; import org.quickmail.Attachment; import org.quickmail.HtmlMessageBody; import org.quickmail.Inline; import org.quickmail.Mail; import org.quickmail.TextMessageBody; class MessageComposer { private static final String DEFAULT_MIME_TYPE = "application/octet-stream"; private MimeMessage msg; public MessageComposer(Session session) { this.msg = new MimeMessage(Objects.requireNonNull(session, "session must not be null")); } public Message compose(Mail mail) throws MessagingException, IOException { Objects.requireNonNull(mail, "mail must not be null"); if (mail.getFrom() != null) { msg.setFrom(new InternetAddress(mail.getFrom())); } if (mail.getTo() != null) { msg.setRecipients(RecipientType.TO, convertToAddresses(mail.getTo())); } if (mail.getCc() != null) { msg.setRecipients(RecipientType.CC, convertToAddresses(mail.getCc())); } if (mail.getBcc() != null) { msg.setRecipients(RecipientType.BCC, convertToAddresses(mail.getBcc())); } if (mail.getReplyTo() != null) { msg.setReplyTo(convertToAddresses(mail.getReplyTo())); } msg.setSentDate((mail.getSentDate() != null) ? mail.getSentDate() : new Date()); msg.setSubject(mail.getSubject(), mail.getSubjectCharset().name()); setMessageContent(mail); return msg; } private Address[] convertToAddresses(List<String> strs) throws AddressException { return strs.stream() .map(str -> { try { return new InternetAddress(str); } catch (AddressException e) { return null; } }) .filter(Objects::nonNull) .toArray(Address[]::new); } private void setMessageContent(Mail mail) throws MessagingException, IOException { if (mail.hasAttachment()) { msg.setContent(composeMultipartMixed(mail)); } else if (mail.hasTextMessage() && mail.hasHtmlMessage()) { msg.setContent(composeMultipartAlternative(mail)); } else if (mail.hasHtmlMessage() && mail.getHtmlMessage().hasInline()){ msg.setContent(composeMultipartRelated(mail)); } else if (mail.hasTextMessage()) { TextMessageBody textMsg = mail.getTextMessage(); msg.setText(textMsg.getContent(), getMimeCharset(textMsg.getCharset()), TextMessageBody.getSubType()); if (textMsg.getEncoding() != null) { msg.setHeader("Content-Transfer-Encoding", textMsg.getEncoding()); } } else if (mail.hasHtmlMessage()) { HtmlMessageBody htmlMsg = mail.getHtmlMessage(); msg.setText(htmlMsg.getContent(), getMimeCharset(htmlMsg.getCharset()), HtmlMessageBody.getSubType()); if (htmlMsg.getEncoding() != null) { msg.setHeader("Content-Transfer-Encoding", htmlMsg.getEncoding()); } } else { // empty message msg.setText("", TextMessageBody.getSubType()); } } private String getMimeCharset(Charset charset) { if (charset == null) { return null; } return MimeUtility.mimeCharset(charset.name()); } /** * <pre> * multipart/mixed * | * |--mulpart/alternative * | | * | |--text/plain * | | * | |--multipart/related * | | * | |--text/html * | | * | |--image/xxxx (inline) * | * |--application/xxxx (attachment) * </pre> */ private Multipart composeMultipartMixed(Mail mail) throws MessagingException, IOException { Multipart mixed = new MimeMultipart("mixed"); if (mail.hasTextMessage() && mail.hasHtmlMessage()) { addMultipart(mixed, composeMultipartAlternative(mail)); } else if (mail.hasHtmlMessage() && mail.getHtmlMessage().hasInline()) { addMultipart(mixed, composeMultipartRelated(mail)); } else if (mail.hasTextMessage()) { mixed.addBodyPart(composeTextMessage(mail)); } else if (mail.hasHtmlMessage()) { mixed.addBodyPart(composeHtmlMessage(mail)); } for (Attachment attachment : mail.getAttachments()) { mixed.addBodyPart(composeAttachment(attachment)); } return mixed; } private Multipart composeMultipartAlternative(Mail mail) throws MessagingException, IOException { Multipart alternative = new MimeMultipart("alternative"); alternative.addBodyPart(composeTextMessage(mail)); if (mail.getHtmlMessage().hasInline()) { addMultipart(alternative, composeMultipartRelated(mail)); } else { alternative.addBodyPart(composeHtmlMessage(mail)); } return alternative; } private Multipart composeMultipartRelated(Mail mail) throws MessagingException, IOException { Multipart related = new MimeMultipart("related"); related.addBodyPart(composeHtmlMessage(mail)); for (Inline inline : mail.getHtmlMessage().getInlines()) { related.addBodyPart(composeInline(inline)); } return related; } private void addMultipart(Multipart dst, Multipart src) throws MessagingException { BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(src); dst.addBodyPart(bodyPart); } private BodyPart composeTextMessage(Mail mail) throws MessagingException { TextMessageBody textMsg = mail.getTextMessage(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(textMsg.getContent(), getMimeCharset(textMsg.getCharset()), TextMessageBody.getSubType()); if (textMsg.getEncoding() != null) { bodyPart.setHeader("Content-Transfer-Encoding", textMsg.getEncoding()); } return bodyPart; } private BodyPart composeHtmlMessage(Mail mail) throws MessagingException { HtmlMessageBody htmlMsg = mail.getHtmlMessage(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(htmlMsg.getContent(), getMimeCharset(htmlMsg.getCharset()), HtmlMessageBody.getSubType()); if (htmlMsg.getEncoding() != null) { bodyPart.setHeader("Content-Transfer-Encoding", htmlMsg.getEncoding()); } return bodyPart; } private BodyPart composeAttachment(Attachment attachment) throws MessagingException, IOException { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setDisposition("attachment"); String mimeCharset = getMimeCharset(attachment.getCharset()); if (attachment.getFile() != null) { bodyPart.attachFile(attachment.getFile()); setContentType(bodyPart, attachment.getMimeType(), mimeCharset); } else { String mimeType = (attachment.getMimeType() != null) ? attachment.getMimeType() : DEFAULT_MIME_TYPE; DataSource dataSource = new ByteArrayDataSource(attachment.getInputStream(), mimeType); bodyPart.setDataHandler(new DataHandler(dataSource)); setContentType(bodyPart, mimeType, mimeCharset); } if (attachment.getEncoding() != null) { bodyPart.setHeader("Content-Transfer-Encoding", attachment.getEncoding()); } try { String filename = MimeUtility.encodeWord(attachment.getName(), mimeCharset, "B"); bodyPart.setFileName(filename); } catch (UnsupportedEncodingException e) { bodyPart.setFileName(attachment.getName()); } return bodyPart; } private MimeBodyPart composeInline(Inline inline) throws MessagingException, IOException { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setDisposition("inline"); if (inline.getFile() != null) { bodyPart.attachFile(inline.getFile()); setContentType(bodyPart, inline.getMimeType(), null); } else { String mimeType = (inline.getMimeType() != null) ? inline.getMimeType() : DEFAULT_MIME_TYPE; DataSource dataSource = new ByteArrayDataSource(inline.getInputStream(), mimeType); bodyPart.setDataHandler(new DataHandler(dataSource)); } if (inline.getId() != null) { bodyPart.setHeader("Content-Id", inline.getId()); } if (inline.getEncoding() != null) { bodyPart.setHeader("Content-Transfer-Encoding", inline.getEncoding()); } return bodyPart; } private void setContentType(BodyPart bodyPart, String mimeType, String mimeCharset) throws MessagingException { if (mimeType == null) { return; } if (mimeCharset != null) { bodyPart.setHeader("Content-Type", mimeType + "; charset=" + mimeCharset); } else { bodyPart.setHeader("Content-Type", mimeType); } } }
package org.threadly.concurrent; import java.util.concurrent.Callable; import org.threadly.concurrent.lock.LockFactory; import org.threadly.concurrent.lock.NativeLock; import org.threadly.concurrent.lock.VirtualLock; /** * <p>This class helps assist in making concurrent code testable. * This class is not strictly required, but it makes the TestablePriorityScheduler * a drop in replacement instead of having to pass a LockFactory into your code.</p> * * <p>The alternative to using this class would be to pass a LockFactory into your code. * But in addition if the runnable needs to sleep, it must do it on the scheduler or locks.</p> * * @author jent - Mike Jensen * @param <T> type to be returned from .call() */ public abstract class VirtualCallable<T> implements Callable<T> { protected LockFactory factory = null; /** * This is the run call that will be called for schedulers aware of * VirtualRunnable (currently only TestablePriorityScheduler). This * lets us inject a lock factory that works for the given scheduler. * * @param factory factory to use while running this runnable * @return result from .call() * @throws Exception possible thrown from .call() */ public T call(LockFactory factory) throws Exception { this.factory = factory; try { return call(); } finally { this.factory = null; } } /** * Returns a virtual lock for the runnable that makes sense for the * processing thread pool. * * @return {@link VirtualLock} to synchronize on and use with pleasure */ protected VirtualLock makeLock() { if (factory == null) { return new NativeLock(); } else { return factory.makeLock(); } } /** * Alternative to Thread.sleep(). This call defaults to the native * version or uses a method that makes sense for the running thread pool. * * You have to use this instead of Thread.sleep() or you will block the * TestablePriorityScheduler. * * @param sleepTime Time to pause thread * @throws InterruptedException */ protected void sleep(long sleepTime) throws InterruptedException { if (factory == null) { Thread.sleep(sleepTime); } else { factory.makeLock().sleep(sleepTime); } } /** * Constructs a VirtualCallable for a given runnable and result. This is very similar to * Executors.callable(Runnable, Result). The difference is this callable implementation is * able to handle when {@link VirtualRunnable} are being provided. * * @param task runnable or {@link VirtualRunnable} implementation to call * @param result result to be provided from the callable after the runnable has run * @return {@link VirtualCallable} object which will run the provided task */ public static <T> VirtualCallable<T> fromRunnable(Runnable task, T result) { if (task == null) { throw new IllegalArgumentException("Must provide a task to be run within the callable"); } return new RunnableCallable<T>(task, result); } /** * Callable implementation which uses a runnable and result to handle * the actual run. * * @author jent - Mike Jensen * @param <T> type of result to be returned from callable */ private static class RunnableCallable<T> extends VirtualCallable<T> implements RunnableContainerInterface { private final Runnable task; private final T result; private RunnableCallable(Runnable task, T result) { this.task = task; this.result = result; } @Override public T call() throws Exception { if (factory != null && task instanceof VirtualRunnable) { ((VirtualRunnable)task).run(factory); } else { task.run(); } return result; } @Override public Runnable getContainedRunnable() { return task; } } }
package org.xelasov.ejdbc.base; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; public class ResultSetWrapper { private final ResultSet rs; public ResultSetWrapper(final ResultSet rs) { Assert.argumentNotNull(rs); this.rs = rs; } public boolean getBool(final int pos) throws SQLException { return rs.getBoolean(pos); } public Boolean getBoolOrNull(final int pos) throws SQLException { final boolean rv = rs.getBoolean(pos); return rs.wasNull() ? null : new Boolean(rv); } public BigDecimal getBigDecimal(final int pos) throws SQLException { return rs.getBigDecimal(pos); } public BigDecimal getBigDecimalOrNull(final int pos) throws SQLException { final BigDecimal rv = rs.getBigDecimal(pos); return rs.wasNull() ? null : rv; } public byte getByte(final int pos) throws SQLException { return rs.getByte(pos); } public Byte getByteOrNull(final int pos) throws SQLException { final byte rv = rs.getByte(pos); return rs.wasNull() ? null : new Byte(rv); } public boolean getByteBool(final int pos) throws SQLException { final byte b = getByte(pos); return 1 == b; } public Boolean getByteBoolOrNull(final int pos) throws SQLException { final Byte b = getByteOrNull(pos); if (b == null) return null; else return new Boolean(1 == b.byteValue()); } public LocalDate getDate(final int pos) throws SQLException { final java.sql.Date rv = rs.getDate(pos); return rs.wasNull() || rv == null ? LocalDate.from(Instant.EPOCH) : rv.toLocalDate(); } public LocalDate getDateOrNull(final int pos) throws SQLException { final java.sql.Date rv = rs.getDate(pos); return rs.wasNull() || rv == null ? null : rv.toLocalDate(); } public LocalDateTime getDateTime(final int pos) throws SQLException { final java.sql.Timestamp rv = rs.getTimestamp(pos); return rs.wasNull() || rv == null ? LocalDateTime.from(Instant.EPOCH) : rv.toLocalDateTime(); } public LocalDateTime getDateTimeOrNull(final int pos) throws SQLException { final java.sql.Timestamp rv = rs.getTimestamp(pos); return rs.wasNull() || rv == null ? null : rv.toLocalDateTime(); } public double getDouble(final int pos) throws SQLException { return rs.getDouble(pos); } public Double getDoubleOrNull(final int pos) throws SQLException { final double rv = rs.getDouble(pos); return rs.wasNull() ? null : new Double(rv); } public float getFloat(final int pos) throws SQLException { return rs.getFloat(pos); } public Float getFloatOrNull(final int pos) throws SQLException { final float rv = rs.getFloat(pos); return rs.wasNull() ? null : new Float(rv); } public int getInteger(final int pos) throws SQLException { return rs.getInt(pos); } public Integer getIntegerOrNull(final int pos) throws SQLException { final int rv = rs.getInt(pos); return rs.wasNull() ? null : new Integer(rv); } public long getLong(final int pos) throws SQLException { return rs.getLong(pos); } public Long getLongOrNull(final int pos) throws SQLException { final long rv = rs.getLong(pos); return rs.wasNull() ? null : new Long(rv); } public ResultSet getResultSet() { return rs; } public boolean next() throws SQLException { return rs.next(); } public short getShort(final int pos) throws SQLException { return rs.getShort(pos); } public Short getShortOrNull(final int pos) throws SQLException { final short rv = rs.getShort(pos); return rs.wasNull() ? null : new Short(rv); } public String getString(final int pos) throws SQLException { final String rv = rs.getString(pos); return rs.wasNull() || rv == null ? "" : rv; } public String getStringOrNull(final int pos) throws SQLException { return rs.getString(pos); } public LocalTime getTime(final int pos) throws SQLException { final java.sql.Time rv = rs.getTime(pos); return rs.wasNull() || rv == null ? LocalTime.from(Instant.EPOCH): rv.toLocalTime(); } public LocalTime getTimeOrNull(final int pos) throws SQLException { final java.sql.Time rv = rs.getTime(pos); return rs.wasNull() || rv == null ? null : rv.toLocalTime(); } }
package pitt.search.semanticvectors; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.standard.StandardTokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.TermAttribute; import org.apache.lucene.util.Version; import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.ZeroVectorException; import pitt.search.semanticvectors.viz.PathFinder; /** * Command line term vector search utility. */ public class SearchBatch { private static final Logger logger = Logger.getLogger(SearchBatch.class.getCanonicalName()); /** * Different types of searches that can be performed, set using {@link FlagConfig#searchtype()}. * * <p>Most involve processing combinations of vectors in different ways, in * building a query expression, scoring candidates against these query * expressions, or both. Most options here correspond directly to a particular * subclass of {@link VectorSearcher}. * * <p>Names may be passed as command-line arguments, so underscores are avoided. * */ public enum SearchType { /** * Build a query by adding together (weighted) vectors for each of the query * terms, and search using cosine similarity. * See {@link VectorSearcher.VectorSearcherCosine}. * This is the default search option. */ SUM, /** * "Quantum disjunction" - get vectors for each query term, create a * representation for the subspace spanned by these vectors, and score by * measuring cosine similarity with this subspace. * Uses {@link VectorSearcher.VectorSearcherSubspaceSim}. */ SUBSPACE, /** * "Closest disjunction" - get vectors for each query term, score by measuring * distance to each term and taking the minimum. * Uses {@link VectorSearcher.VectorSearcherMaxSim}. */ MAXSIM, /** * "Farthest conjunction" - get vectors for each query term, score by measuring * distance to each term and taking the maximum. * Uses {@link VectorSearcher.VectorSearcherMaxSim}. */ MINSIM, /** * Uses permutation of coordinates to model typed relationships, as * introduced by Sahlgren at al. (2008). * * <p>Searches for the term that best matches the position of a "?" in a sequence of terms. * For example <code>martin ? king</code> should retrieve <code>luther</code> as the top ranked match. * * <p>Requires {@link FlagConfig#queryvectorfile()} to contain * unpermuted vectors, either random vectors or previously learned term vectors, * and {@link FlagConfig#searchvectorfile()} must contain permuted learned vectors. * * <p>Uses {@link VectorSearcher.VectorSearcherPerm}. */ PERMUTATION, /** * This is a variant of the {@link SearchType#PERMUTATION} method which * takes the mean of the two possible search directions (search * with index vectors for permuted vectors, or vice versa). * Uses {@link VectorSearcher.VectorSearcherPerm}. */ BALANCEDPERMUTATION, /** * Used for Predication Semantic Indexing, see {@link PSI}. * Uses {@link VectorSearcher.VectorSearcherBoundProduct}. */ BOUNDPRODUCT, /** * Lucene document search, for comparison. * */ LUCENE, /** * Used for Predication Semantic Indexing, see {@link PSI}. * Finds minimum similarity across query terms to seek middle terms */ BOUNDMINIMUM, /** * Binds vectors to facilitate search across multiple relationship paths. * Uses {@link VectorSearcher.VectorSearcherBoundProductSubSpace} */ BOUNDPRODUCTSUBSPACE, /** * Intended to support searches of the form A is to B as C is to ?, but * hasn't worked well thus far. (dwiddows, 2013-02-03). */ ANALOGY, /** * Builds an additive query vector (as with {@link SearchType#SUM} and prints out the query * vector for debugging). */ PRINTQUERY } private static LuceneUtils luceneUtils; public static String usageMessage = "\nSearch class in package pitt.search.semanticvectors" + "\nUsage: java pitt.search.semanticvectors.Search [-queryvectorfile query_vector_file]" + "\n [-searchvectorfile search_vector_file]" + "\n [-luceneindexpath path_to_lucene_index]" + "\n [-searchtype TYPE]" + "\n <QUERYTERMS>" + "\nIf no query or search file is given, default will be" + "\n termvectors.bin in local directory." + "\n-luceneindexpath argument is needed if to get term weights from" + "\n term frequency, doc frequency, etc. in lucene index." + "\n-searchtype can be one of SUM, SUBSPACE, MAXSIM, MINSIM" + "\n BALANCEDPERMUTATION, PERMUTATION, PRINTQUERY" + "\n<QUERYTERMS> should be a list of words, separated by spaces." + "\n If the term NOT is used, terms after that will be negated."; /** * Takes a user's query, creates a query vector, and searches a vector store. * @param flagConfig configuration object for controlling the search * @return list containing search results. */ public static void runSearch(FlagConfig flagConfig) throws IllegalArgumentException { /** * The runSearch function has four main stages: * i. Check flagConfig for null (but so far fails to check other dependencies). * ii. Open corresponding vector and lucene indexes. * iii. Based on search type, build query vector and perform search. * iv. Return LinkedList of results, usually for main() to print out. */ // Stage i. Check flagConfig for null, and there being at least some remaining query terms. if (flagConfig == null) { throw new NullPointerException("flagConfig cannot be null"); } if (flagConfig.remainingArgs == null) { throw new IllegalArgumentException("No query terms left after flag parsing!"); } String[] queryArgs = flagConfig.remainingArgs; /** Principal vector store for finding query vectors. */ VectorStore queryVecReader = null; /** Auxiliary vector store used when searching for boundproducts. Used only in some searchtypes. */ VectorStore boundVecReader = null; /** Auxiliary vector stores used when searching for boundproducts. Used only in some searchtypes. */ VectorStore elementalVecReader = null, semanticVecReader = null, predicateVecReader = null; /** * Vector store for searching. Defaults to being the same as queryVecReader. * May be different from queryVecReader, e.g., when using terms to search for documents. */ VectorStore searchVecReader = null; // Stage ii. Open vector stores, and Lucene utils. try { // Default VectorStore implementation is (Lucene) VectorStoreReader. if (!flagConfig.elementalvectorfile().equals("elementalvectors") && !flagConfig.semanticvectorfile().equals("semanticvectors") && !flagConfig.predicatevectorfile().equals("predicatevectors")) { //for PSI search VerbatimLogger.info("Opening elemental query vector store from file: " + flagConfig.elementalvectorfile() + "\n"); VerbatimLogger.info("Opening semantic query vector store from file: " + flagConfig.semanticvectorfile() + "\n"); VerbatimLogger.info("Opening predicate query vector store from file: " + flagConfig.predicatevectorfile() + "\n"); if (flagConfig.elementalvectorfile().equals("deterministic")) { if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.ORTHOGRAPHIC)) elementalVecReader = new VectorStoreOrthographical(flagConfig); else if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH)) elementalVecReader = new VectorStoreDeterministic(flagConfig); else VerbatimLogger.info("Please select either -elementalmethod orthographic OR -elementalmethod contenthash depending upon the deterministic approach you would like used."); } else {elementalVecReader = new VectorStoreRAM(flagConfig); ((VectorStoreRAM) elementalVecReader).initFromFile(flagConfig.elementalvectorfile());} semanticVecReader = new VectorStoreRAM(flagConfig); ((VectorStoreRAM) semanticVecReader).initFromFile(flagConfig.semanticvectorfile()); predicateVecReader = new VectorStoreRAM(flagConfig); ((VectorStoreRAM) predicateVecReader).initFromFile(flagConfig.predicatevectorfile()); } else { VerbatimLogger.info("Opening query vector store from file: " + flagConfig.queryvectorfile() + "\n"); if (flagConfig.queryvectorfile().equals("deterministic")) { if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.ORTHOGRAPHIC)) queryVecReader = new VectorStoreOrthographical(flagConfig); else if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH)) queryVecReader = new VectorStoreDeterministic(flagConfig); else VerbatimLogger.info("Please select either -elementalmethod orthographic OR -elementalmethod contenthash depending upon the deterministic approach you would like used."); } else {queryVecReader = new VectorStoreRAM(flagConfig); ((VectorStoreRAM) queryVecReader).initFromFile(flagConfig.queryvectorfile()); } } if (flagConfig.boundvectorfile().length() > 0) { VerbatimLogger.info("Opening second query vector store from file: " + flagConfig.boundvectorfile() + "\n"); boundVecReader = new VectorStoreRAM(flagConfig); ((VectorStoreRAM) boundVecReader).initFromFile(flagConfig.boundvectorfile()); } // Open second vector store if search vectors are different from query vectors. if (flagConfig.queryvectorfile().equals(flagConfig.searchvectorfile()) || flagConfig.searchvectorfile().isEmpty()) { searchVecReader = queryVecReader; } else { VerbatimLogger.info("Opening search vector store from file: " + flagConfig.searchvectorfile() + "\n"); searchVecReader = new VectorStoreRAM(flagConfig); ((VectorStoreRAM) searchVecReader).initFromFile(flagConfig.searchvectorfile()); } if (!flagConfig.luceneindexpath().isEmpty()) { try { luceneUtils = new LuceneUtils(flagConfig); } catch (IOException e) { logger.warning("Couldn't open Lucene index at " + flagConfig.luceneindexpath() + ". Will continue without term weighting."); } } } catch (IOException e) { e.printStackTrace(); } try { BufferedReader queryReader = new BufferedReader(new FileReader(new File(queryArgs[0]))); String queryString = queryReader.readLine(); int qcnt = 0; while (queryString != null) { ArrayList<String> queryTerms = new ArrayList<String>(); qcnt++; //have Lucene parse the query string, for consistency StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46); TokenStream stream = analyzer.tokenStream(null, new StringReader(queryString)); CharTermAttribute cattr = stream.addAttribute(CharTermAttribute.class); stream.reset(); //for each token in the query string while (stream.incrementToken()) { String term = cattr.toString(); if (!luceneUtils.stoplistContains(term)) { if (! flagConfig.matchcase()) term = term.toLowerCase(); queryTerms.add(term); } } stream.end(); stream.close(); analyzer.close(); //transform to String[] array queryArgs = queryTerms.toArray(new String[0]); // Stage iii. Perform search according to which searchType was selected. // Most options have corresponding dedicated VectorSearcher subclasses. VectorSearcher vecSearcher = null; LinkedList<SearchResult> results; VerbatimLogger.info("Searching term vectors, searchtype " + flagConfig.searchtype() + "\n"); try { switch (flagConfig.searchtype()) { case SUM: vecSearcher = new VectorSearcher.VectorSearcherCosine( queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs); break; case SUBSPACE: vecSearcher = new VectorSearcher.VectorSearcherSubspaceSim( queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs); break; case MAXSIM: vecSearcher = new VectorSearcher.VectorSearcherMaxSim( queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs); break; case MINSIM: vecSearcher = new VectorSearcher.VectorSearcherMinSim( queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs); break; case BOUNDPRODUCT: if (queryArgs.length == 2) { vecSearcher = new VectorSearcher.VectorSearcherBoundProduct( queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0],queryArgs[1]); } else { vecSearcher = new VectorSearcher.VectorSearcherBoundProduct( elementalVecReader, semanticVecReader, predicateVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0]); } break; case BOUNDPRODUCTSUBSPACE: if (queryArgs.length == 2) { vecSearcher = new VectorSearcher.VectorSearcherBoundProductSubSpace( queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0], queryArgs[1]); } else { vecSearcher = new VectorSearcher.VectorSearcherBoundProductSubSpace( elementalVecReader, semanticVecReader, predicateVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0]); } break; case BOUNDMINIMUM: if (queryArgs.length == 2) { vecSearcher = new VectorSearcher.VectorSearcherBoundMinimum( queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0], queryArgs[1]); } else { vecSearcher = new VectorSearcher.VectorSearcherBoundMinimum( elementalVecReader, semanticVecReader, predicateVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0]); } break; case PERMUTATION: vecSearcher = new VectorSearcher.VectorSearcherPerm( queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs); break; case BALANCEDPERMUTATION: vecSearcher = new VectorSearcher.BalancedVectorSearcherPerm( queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs); break; case ANALOGY: vecSearcher = new VectorSearcher.AnalogySearcher( queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs); break; case LUCENE: vecSearcher = new VectorSearcher.VectorSearcherLucene( luceneUtils, flagConfig, queryArgs); break; case PRINTQUERY: Vector queryVector = CompoundVectorBuilder.getQueryVector( queryVecReader, luceneUtils, flagConfig, queryArgs); System.out.println(queryVector.toString()); default: throw new IllegalArgumentException("Unknown search type: " + flagConfig.searchtype()); } } catch (ZeroVectorException zve) { logger.info(zve.getMessage()); } results = new LinkedList<SearchResult>(); try { results = vecSearcher.getNearestNeighbors(flagConfig.numsearchresults()); } catch (Exception e) { //no search results returned } int cnt = 0; // Print out results. if (results.size() > 0) { VerbatimLogger.info("Search output follows ...\n"); for (SearchResult result: results) { if (flagConfig.treceval() != -1) //results in trec_eval format { System.out.println( String.format("%s\t%s\t%s\t%s\t%f\t%s", qcnt, "Q0", result.getObjectVector().getObject().toString(), ++cnt, result.getScore(), "DEFAULT") ); } else System.out.println( //results in cosine:object format String.format("%f:%s", result.getScore(), result.getObjectVector().getObject().toString())); } } queryString = queryReader.readLine(); } queryReader.close(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main (String[] args) throws IllegalArgumentException, IOException { FlagConfig flagConfig; try { flagConfig = FlagConfig.getFlagConfig(args); runSearch(flagConfig); } catch (IllegalArgumentException e) { System.err.println(usageMessage); throw e; } } }
package redis.clients.jedis; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisMovedDataException; import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; import redis.clients.jedis.exceptions.JedisRedirectionException; import redis.clients.util.JedisClusterCRC16; public abstract class JedisClusterCommand<T> { private static final String NO_DISPATCH_MESSAGE = "No way to dispatch this command to Redis Cluster."; private final JedisClusterConnectionHandler connectionHandler; private final int maxAttempts; private final ThreadLocal<Jedis> askConnection = new ThreadLocal<Jedis>(); public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int maxAttempts) { this.connectionHandler = connectionHandler; this.maxAttempts = maxAttempts; } public abstract T execute(Jedis connection); public T run(String key) { if (key == null) { throw new JedisClusterException(NO_DISPATCH_MESSAGE); } return runWithRetries(JedisClusterCRC16.getSlot(key), this.maxAttempts, false, false); } public T run(int keyCount, String... keys) { if (keys == null || keys.length == 0) { throw new JedisClusterException(NO_DISPATCH_MESSAGE); } // For multiple keys, only execute if they all share the same connection slot. int slot = JedisClusterCRC16.getSlot(keys[0]); if (keys.length > 1) { for (int i = 1; i < keyCount; i++) { int nextSlot = JedisClusterCRC16.getSlot(keys[i]); if (slot != nextSlot) { throw new JedisClusterException("No way to dispatch this command to Redis Cluster " + "because keys have different slots."); } } } return runWithRetries(slot, this.maxAttempts, false, false); } public T runBinary(byte[] key) { if (key == null) { throw new JedisClusterException(NO_DISPATCH_MESSAGE); } return runWithRetries(JedisClusterCRC16.getSlot(key), this.maxAttempts, false, false); } public T runBinary(int keyCount, byte[]... keys) { if (keys == null || keys.length == 0) { throw new JedisClusterException(NO_DISPATCH_MESSAGE); } // For multiple keys, only execute if they all share the same connection slot. int slot = JedisClusterCRC16.getSlot(keys[0]); if (keys.length > 1) { for (int i = 1; i < keyCount; i++) { int nextSlot = JedisClusterCRC16.getSlot(keys[i]); if (slot != nextSlot) { throw new JedisClusterException("No way to dispatch this command to Redis Cluster " + "because keys have different slots."); } } } return runWithRetries(slot, this.maxAttempts, false, false); } public T runWithAnyNode() { Jedis connection = null; try { connection = connectionHandler.getConnection(); return execute(connection); } catch (JedisConnectionException e) { throw e; } finally { releaseConnection(connection); } } private T runWithRetries(final int slot, int attempts, boolean tryRandomNode, boolean asking) { if (attempts <= 0) { throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?"); } Jedis connection = null; try { if (asking) { // TODO: Pipeline asking with the original command to make it // faster.... connection = askConnection.get(); connection.asking(); // if asking success, reset asking flag asking = false; } else { if (tryRandomNode) { connection = connectionHandler.getConnection(); } else { connection = connectionHandler.getConnectionFromSlot(slot); } } return execute(connection); } catch (JedisNoReachableClusterNodeException jnrcne) { throw jnrcne; } catch (JedisConnectionException jce) { // release current connection before recursion releaseConnection(connection); connection = null; if (attempts <= 1) { //We need this because if node is not reachable anymore - we need to finally initiate slots renewing, //or we can stuck with cluster state without one node in opposite case. //But now if maxAttempts = 1 or 2 we will do it too often. For each time-outed request. //TODO make tracking of successful/unsuccessful operations for node - do renewing only //if there were no successful responses from this node last few seconds this.connectionHandler.renewSlotCache(); //no more redirections left, throw original exception, not JedisClusterMaxRedirectionsException, because it's not MOVED situation throw jce; } return runWithRetries(slot, attempts - 1, tryRandomNode, asking); } catch (JedisRedirectionException jre) { // if MOVED redirection occurred, if (jre instanceof JedisMovedDataException) { // it rebuilds cluster's slot cache // recommended by Redis cluster specification this.connectionHandler.renewSlotCache(connection); } // release current connection before recursion or renewing releaseConnection(connection); connection = null; if (jre instanceof JedisAskDataException) { asking = true; askConnection.set(this.connectionHandler.getConnectionFromNode(jre.getTargetNode())); } else if (jre instanceof JedisMovedDataException) { } else { throw new JedisClusterException(jre); } return runWithRetries(slot, attempts - 1, false, asking); } finally { releaseConnection(connection); } } private void releaseConnection(Jedis connection) { if (connection != null) { connection.close(); } } }
package refinedstorage.tile; import io.netty.buffer.ByteBuf; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.items.IItemHandler; import powercrystals.minefactoryreloaded.api.IDeepStorageUnit; import refinedstorage.RefinedStorage; import refinedstorage.RefinedStorageUtils; import refinedstorage.container.ContainerStorage; import refinedstorage.inventory.InventorySimple; import refinedstorage.network.MessagePriorityUpdate; import refinedstorage.storage.IStorage; import refinedstorage.storage.IStorageGui; import refinedstorage.storage.IStorageProvider; import refinedstorage.storage.ItemGroup; import refinedstorage.tile.config.ICompareConfig; import refinedstorage.tile.config.IModeConfig; import refinedstorage.tile.config.IRedstoneModeConfig; import refinedstorage.tile.config.ModeConfigUtils; import java.util.List; public class TileExternalStorage extends TileMachine implements IStorageProvider, IStorage, IStorageGui, ICompareConfig, IModeConfig { public static final String NBT_PRIORITY = "Priority"; public static final String NBT_COMPARE = "Compare"; public static final String NBT_MODE = "Mode"; private InventorySimple inventory = new InventorySimple("external_storage", 9, this); private int priority = 0; private int compare = 0; private int mode = 0; private int stored = 0; @Override public int getEnergyUsage() { return 2; } @Override public void updateMachine() { } @Override public void addItems(List<ItemGroup> items) { IDeepStorageUnit storageUnit = getStorageUnit(); if (storageUnit != null) { if (storageUnit.getStoredItemType() != null) { items.add(new ItemGroup(storageUnit.getStoredItemType().copy())); } } else { IItemHandler handler = getItemHandler(); if (handler != null) { for (int i = 0; i < handler.getSlots(); ++i) { if (handler.getStackInSlot(i) != null) { items.add(new ItemGroup(handler.getStackInSlot(i).copy())); } } } } } @Override public void push(ItemStack stack) { IDeepStorageUnit storageUnit = getStorageUnit(); if (storageUnit != null) { if (storageUnit.getStoredItemType() == null) { storageUnit.setStoredItemType(stack, stack.stackSize); } else { storageUnit.setStoredItemCount(storageUnit.getStoredItemType().stackSize + stack.stackSize); } } else { IItemHandler handler = getItemHandler(); if (handler != null) { for (int i = 0; i < handler.getSlots(); ++i) { if (handler.insertItem(i, stack, false) == null) { break; } } } } } @Override public ItemStack take(ItemStack stack, int flags) { int quantity = stack.stackSize; IDeepStorageUnit storageUnit = getStorageUnit(); if (storageUnit != null) { if (storageUnit.getStoredItemType() != null && RefinedStorageUtils.compareStackNoQuantity(storageUnit.getStoredItemType(), stack)) { if (quantity > storageUnit.getStoredItemType().stackSize) { quantity = storageUnit.getStoredItemType().stackSize; } ItemStack took = storageUnit.getStoredItemType().copy(); took.stackSize = quantity; storageUnit.setStoredItemCount(storageUnit.getStoredItemType().stackSize - quantity); return took; } } else { IItemHandler handler = getItemHandler(); if (handler != null) { for (int i = 0; i < handler.getSlots(); ++i) { ItemStack slot = handler.getStackInSlot(i); if (slot != null && RefinedStorageUtils.compareStack(slot, stack, flags)) { if (quantity > slot.stackSize) { quantity = slot.stackSize; } handler.extractItem(i, quantity, false); ItemStack took = slot.copy(); took.stackSize = quantity; return took; } } } } return null; } @Override public boolean mayPush(ItemStack stack) { if (ModeConfigUtils.doesNotViolateMode(inventory, this, compare, stack)) { IDeepStorageUnit storageUnit = getStorageUnit(); if (storageUnit != null) { if (storageUnit.getStoredItemType() == null) { return stack.stackSize < storageUnit.getMaxStoredCount(); } return RefinedStorageUtils.compareStackNoQuantity(storageUnit.getStoredItemType(), stack) && (storageUnit.getStoredItemType().stackSize + stack.stackSize) < storageUnit.getMaxStoredCount(); } else { IItemHandler handler = getItemHandler(); if (handler != null) { for (int i = 0; i < handler.getSlots(); ++i) { if (handler.insertItem(i, stack, true) == null) { return true; } } } } } return false; } public TileEntity getFront() { return worldObj.getTileEntity(pos.offset(getDirection())); } public IDeepStorageUnit getStorageUnit() { return getFront() instanceof IDeepStorageUnit ? (IDeepStorageUnit) getFront() : null; } public IItemHandler getItemHandler() { return RefinedStorageUtils.getItemHandler(getFront(), getDirection().getOpposite()); } @Override public void sendContainerData(ByteBuf buf) { super.sendContainerData(buf); buf.writeInt(priority); IDeepStorageUnit storageUnit = getStorageUnit(); if (storageUnit != null) { buf.writeInt(storageUnit.getStoredItemType() == null ? 0 : storageUnit.getStoredItemType().stackSize); } else { IItemHandler handler = getItemHandler(); if (handler != null) { int amount = 0; for (int i = 0; i < handler.getSlots(); ++i) { if (handler.getStackInSlot(i) != null) { amount += handler.getStackInSlot(i).stackSize; } } buf.writeInt(amount); } else { buf.writeInt(0); } } buf.writeInt(compare); buf.writeInt(mode); } @Override public void receiveContainerData(ByteBuf buf) { super.receiveContainerData(buf); priority = buf.readInt(); stored = buf.readInt(); compare = buf.readInt(); mode = buf.readInt(); } @Override public Class<? extends Container> getContainer() { return ContainerStorage.class; } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); RefinedStorageUtils.restoreInventory(inventory, 0, nbt); if (nbt.hasKey(NBT_PRIORITY)) { priority = nbt.getInteger(NBT_PRIORITY); } if (nbt.hasKey(NBT_COMPARE)) { compare = nbt.getInteger(NBT_COMPARE); } if (nbt.hasKey(NBT_MODE)) { mode = nbt.getInteger(NBT_MODE); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); RefinedStorageUtils.saveInventory(inventory, 0, nbt); nbt.setInteger(NBT_PRIORITY, priority); nbt.setInteger(NBT_COMPARE, compare); nbt.setInteger(NBT_MODE, mode); } @Override public int getCompare() { return compare; } @Override public void setCompare(int compare) { markDirty(); this.compare = compare; } @Override public boolean isWhitelist() { return mode == 0; } @Override public boolean isBlacklist() { return mode == 1; } @Override public void setToWhitelist() { markDirty(); this.mode = 0; } @Override public void setToBlacklist() { markDirty(); this.mode = 1; } @Override public int getPriority() { return priority; } public void setPriority(int priority) { markDirty(); this.priority = priority; } @Override public void provide(List<IStorage> storages) { storages.add(this); } @Override public String getGuiTitle() { return "gui.refinedstorage:external_storage"; } @Override public IRedstoneModeConfig getRedstoneModeConfig() { return this; } @Override public ICompareConfig getCompareConfig() { return this; } @Override public IModeConfig getModeConfig() { return this; } @Override public int getStored() { return stored; } @Override public int getCapacity() { IDeepStorageUnit storageUnit = getStorageUnit(); if (storageUnit != null) { return storageUnit.getMaxStoredCount(); } else { IItemHandler handler = getItemHandler(); if (handler != null) { return handler.getSlots() * 64; } } return 0; } @Override public void onPriorityChanged(int priority) { RefinedStorage.NETWORK.sendToServer(new MessagePriorityUpdate(pos, priority)); } @Override public IInventory getInventory() { return inventory; } }
package ru.r2cloud.jradio.demod; import java.io.IOException; import ru.r2cloud.jradio.ByteInput; import ru.r2cloud.jradio.Context; import ru.r2cloud.jradio.FloatInput; import ru.r2cloud.jradio.blocks.ComplexToReal; import ru.r2cloud.jradio.blocks.CostasLoop; import ru.r2cloud.jradio.blocks.DelayOne; import ru.r2cloud.jradio.blocks.FLLBandEdge; import ru.r2cloud.jradio.blocks.Firdes; import ru.r2cloud.jradio.blocks.FloatToChar; import ru.r2cloud.jradio.blocks.FrequencyXlatingFIRFilter; import ru.r2cloud.jradio.blocks.LowPassFilterComplex; import ru.r2cloud.jradio.blocks.PolyphaseClockSyncComplex; import ru.r2cloud.jradio.blocks.RmsAgcComplex; import ru.r2cloud.jradio.blocks.Window; public class BpskDemodulator implements ByteInput { private final FloatToChar f2char; // produces soft stream of bytes public BpskDemodulator(FloatInput source, int baudRate, int decimation, double centerFrequency, boolean differential) { FloatInput next = source; if (centerFrequency != 0.0 || decimation != 1) { float[] taps = Firdes.lowPass(1.0, next.getContext().getSampleRate(), baudRate * 2.0, baudRate * 0.2, Window.WIN_HAMMING, 6.76); next = new FrequencyXlatingFIRFilter(next, taps, decimation, centerFrequency); } float samplesPerSymbol = next.getContext().getSampleRate() / baudRate; next = new RmsAgcComplex(next, 2e-2f / samplesPerSymbol, 1.0f); next = new FLLBandEdge(next, samplesPerSymbol, 0.35f, 100, (float) (3 * Math.PI / next.getContext().getSampleRate() * 20)); next = new LowPassFilterComplex(next, 1.0, baudRate, baudRate * 0.1, Window.WIN_HAMMING, 6.76); int nfilts = 16; float[] rrcTaps = Firdes.rootRaisedCosine(nfilts, nfilts, 1.0f / samplesPerSymbol, 0.35f, (int) (11 * samplesPerSymbol * nfilts)); next = new PolyphaseClockSyncComplex(next, samplesPerSymbol, 0.1f, rrcTaps, nfilts, nfilts / 2, 1.5f, 1); next = new CostasLoop(next, (float) (2 * Math.PI / baudRate * 50), 2, false); if (differential) { next = new DelayOne(next); } next = new ComplexToReal(next); f2char = new FloatToChar(next, 127.0f); } @Override public byte readByte() throws IOException { return f2char.readByte(); } @Override public Context getContext() { return f2char.getContext(); } @Override public void close() throws IOException { f2char.close(); } }
package se.hiflyer.fettle.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class GuavaReplacement { private GuavaReplacement() {} public static <T> List<T> newArrayList() { return new ArrayList<T>(); } public static <T> List<T> newArrayList(T... elements) { List<T> list = new ArrayList<T>(); Collections.addAll(list, elements); return list; } public static <K, V> Map<K, V> newHashMap() { return new HashMap<K, V>(); } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; import seedu.todo.commons.EphemeralDB; import seedu.todo.commons.exceptions.InvalidNaturalDateException; import seedu.todo.commons.exceptions.ParseException; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.DateParser; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.controllers.concerns.Tokenizer; import seedu.todo.models.CalendarItem; import seedu.todo.models.Event; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; /** * @@author A0093907W * * Controller to update a CalendarItem. */ public class UpdateController implements Controller { private static final String NAME = "Update"; private static final String DESCRIPTION = "Updates a task by listed index."; private static final String COMMAND_SYNTAX = "update <index> <task> by <deadline>"; private static final String MESSAGE_UPDATE_SUCCESS = "Item successfully updated!"; private static final String STRING_WHITESPACE = ""; private static final String UPDATE_EVENT_TEMPLATE = "update \"%s\" [name \"%s\"] [from \"%s\" to \"%s\"]"; private static final String UPDATE_TASK_TEMPLATE = "update \"%s\" [name \"%s\"] [by \"%s\"]"; private static final String START_TIME_FIELD = "<start time>"; private static final String END_TIME_FIELD = "<end time>"; private static final String DEADLINE_FIELD = "<deadline>"; private static final String NAME_FIELD = "<name>"; private static final String INDEX_FIELD = "<index>"; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { // TODO return (input.toLowerCase().startsWith("update")) ? 1 : 0; } /** * Get the token definitions for use with <code>tokenizer</code>.<br> * This method exists primarily because Java does not support HashMap * literals... * * @return tokenDefinitions */ private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("default", new String[] {"update"}); tokenDefinitions.put("name", new String[] {"name"}); tokenDefinitions.put("time", new String[] { "at", "by", "on", "before", "time" }); tokenDefinitions.put("timeFrom", new String[] { "from" }); tokenDefinitions.put("timeTo", new String[] { "to" }); return tokenDefinitions; } @Override public void process(String input) throws ParseException { // TODO: Example of last minute work Map<String, String[]> parsedResult; parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input); // Name String name = parseName(parsedResult); // Time String[] naturalDates = DateParser.extractDatePair(parsedResult); String naturalFrom = naturalDates[0]; String naturalTo = naturalDates[1]; // Parse natural date using Natty. LocalDateTime dateFrom; LocalDateTime dateTo; try { dateFrom = naturalFrom == null ? null : DateParser.parseNatural(naturalFrom); dateTo = naturalTo == null ? null : DateParser.parseNatural(naturalTo); } catch (InvalidNaturalDateException e) { System.out.println("Disambiguate!"); return; } // Record index Integer recordIndex = null; try { recordIndex = parseIndex(parsedResult); } catch (NumberFormatException e) { recordIndex = null; // Later then disambiguate } // Retrieve record and check if task or event EphemeralDB edb = EphemeralDB.getInstance(); CalendarItem calendarItem = null; boolean isTask; try { calendarItem = edb.getCalendarItemsByDisplayedId(recordIndex); isTask = calendarItem.getClass() == Task.class; } catch (NullPointerException e) { // Assume task for disambiguation purposes since we can't tell renderDisambiguation(true, recordIndex, name, naturalFrom, naturalTo); return; } // Validate isTask, name and times. if (!validateParams(isTask, calendarItem, name, dateFrom, dateTo)) { renderDisambiguation(isTask, (int) recordIndex, name, naturalFrom, naturalTo); return; } // Update and persist task / event. TodoListDB db = TodoListDB.getInstance(); updateCalendarItem(db, calendarItem, isTask, name, dateFrom, dateTo); // Re-render Renderer.renderIndex(db, MESSAGE_UPDATE_SUCCESS); } /** * Extracts the record index from parsedResult. * * @param parsedResult * @return Integer index if parse was successful, null otherwise. */ private Integer parseIndex(Map<String, String[]> parsedResult) { String indexStr = null; if (parsedResult.get("default") != null && parsedResult.get("default")[1] != null) { indexStr = parsedResult.get("default")[1].trim(); return Integer.decode(indexStr); } else { return null; } } /** * Extracts the name to be updated from parsedResult. * * @param parsedResult * @return String name if found, null otherwise. */ private String parseName(Map<String, String[]> parsedResult) { if (parsedResult.get("name") != null && parsedResult.get("name")[1] != null) { return parsedResult.get("name")[1]; } return null; } /** * Updates and persists a CalendarItem to the DB. * * @param db * TodoListDB instance * @param record * Record to update * @param isTask * true if CalendarItem is a Task, false if Event * @param name * Display name of CalendarItem object * @param dateFrom * Due date for Task or start date for Event * @param dateTo * End date for Event */ private void updateCalendarItem(TodoListDB db, CalendarItem record, boolean isTask, String name, LocalDateTime dateFrom, LocalDateTime dateTo) { // Update name if not null if (name != null) { record.setName(name); } // Update time if (isTask) { Task task = (Task) record; if (dateFrom != null) { task.setDueDate(dateFrom); } } else { Event event = (Event) record; if (dateFrom != null) { event.setStartDate(dateFrom); } if (dateTo != null) { event.setEndDate(dateTo); } } // Persist db.save(); } /** * Validate that applying the update changes to the record will not result in an inconsistency. * * <ul> * <li>Fail if name is invalid</li> * <li>Fail if no update changes</li> * </ul> * * Tasks: * <ul> * <li>Fail if task has a dateTo</li> * </ul> * * Events: * <ul> * <li>Fail if event does not have both dateFrom and dateTo</li> * <li>Fail if event has a dateTo that is before dateFrom</li> * </ul> * * @param isTask * @param name * @param dateFrom * @param dateTo * @return */ private boolean validateParams(boolean isTask, CalendarItem record, String name, LocalDateTime dateFrom, LocalDateTime dateTo) { // TODO: Not enough sleep // We really need proper ActiveRecord validation and rollback, sigh... if (name == null && dateFrom == null && dateTo == null) { return false; } if (isTask) { // Fail if task has a dateTo if (dateTo != null) { return false; } } else { Event event = (Event) record; // Take union of existing fields and update params LocalDateTime newDateFrom = (dateFrom == null) ? event.getStartDate() : dateFrom; LocalDateTime newDateTo = (dateTo == null) ? event.getEndDate() : dateTo; if (newDateFrom == null || newDateTo == null) { return false; } if (newDateTo.isBefore(newDateFrom)) { return false; } } return true; } /** * Renders disambiguation with best-effort input matching to template. * * @param isTask * @param name * @param naturalFrom * @param naturalTo */ private void renderDisambiguation(boolean isTask, Integer recordIndex, String name, String naturalFrom, String naturalTo) { name = StringUtil.replaceEmpty(name, NAME_FIELD); String disambiguationString; String errorMessage = STRING_WHITESPACE; // TODO String indexStr = (recordIndex == null) ? INDEX_FIELD : recordIndex.toString(); if (isTask) { naturalFrom = StringUtil.replaceEmpty(naturalFrom, DEADLINE_FIELD); disambiguationString = String.format(UPDATE_TASK_TEMPLATE, indexStr, name, naturalFrom); } else { naturalFrom = StringUtil.replaceEmpty(naturalFrom, START_TIME_FIELD); naturalTo = StringUtil.replaceEmpty(naturalTo, END_TIME_FIELD); disambiguationString = String.format(UPDATE_EVENT_TEMPLATE, indexStr, name, naturalFrom, naturalTo); } // Show an error in the console Renderer.renderDisambiguation(disambiguationString, errorMessage); } }
package studentcapture.submission; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import studentcapture.model.Grade; import studentcapture.submission.Submission; import java.util.*; @Repository public class SubmissionDAO { // This template should be used to send queries to the database @Autowired protected JdbcTemplate databaseConnection; /** * Add a new submission for an assignment * * @param assignmentID Unique identifier for the assignment we're submitting to * @param studentID Unique identifier for the student submitting * @return True if everything went well, otherwise false * * @author tfy12hsm */ public boolean addSubmission(String assignmentID, String studentID, Boolean studentConsent) { String sql = "INSERT INTO Submission (assignmentId, studentId, SubmissionDate, studentConsent) VALUES (?,?,?,?)"; java.util.Date date = new java.util.Date(System.currentTimeMillis()); java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime()); timestamp.setNanos(0); int rowsAffected = databaseConnection.update(sql, Integer.parseInt(assignmentID), Integer.parseInt(studentID), timestamp, studentConsent); return rowsAffected == 1; } /** * Make the feedback visible for the student * @param submission * @return */ public boolean publishFeedback(Submission submission, boolean publish) { /* Publishing feedback without a grade is not possible, returns false */ Grade grade = submission.getGrade(); System.out.println("GRADE: " + grade); if (grade == null) return false; /* If a person that is not a teacher tries to set a grade, return false */ String checkIfTeacherExist = "SELECT COUNT(*) FROM Participant WHERE (UserID = ?) AND (CourseID = ?) AND (Function = 'Teacher')"; int rows = databaseConnection.queryForInt(checkIfTeacherExist, grade.getTeacherID(), submission.getCourseID()); if(rows != 1) return false; String publishFeedback = "UPDATE Submission SET publishFeedback = ? WHERE (AssignmentID = ?) AND (StudentID = ?);"; int updatedRows = databaseConnection.update(publishFeedback, publish, submission.getAssignmentID(), submission.getStudentID()); return updatedRows == 1; } /** * Add a grade for a subsmission * * @param submission Object containing assignmentID, studentID * @return True if a row was changed, otherwise false */ public boolean setGrade(Submission submission) { Grade grade = submission.getGrade(); /* If a person that is not a teacher tries to set a grade, return false */ String checkIfTeacherExist = "SELECT COUNT(*) FROM Participant WHERE" + " (UserID = ?) AND (CourseID = ?) AND (Function = 'Teacher')"; int rows = databaseConnection.queryForInt(checkIfTeacherExist, grade.getTeacherID(), submission.getCourseID()); if(rows != 1) return false; String setGrade = "UPDATE Submission SET Grade = ?, TeacherID = ?, PublishStudentSubmission = ?" + " WHERE (AssignmentID = ?) AND (StudentID = ?);"; int updatedRows = databaseConnection.update(setGrade, grade.getGrade(), grade.getTeacherID(), grade.getPublishStudentSubmission(), submission.getAssignmentID(), submission.getStudentID()); return updatedRows == 1; } /** * Remove a submission * * @param assID Unique identifier for the assignment with the submission being removed * @param studentID Unique identifier for the student whose submission is removed * @return True if everything went well, otherwise false * * @author tfy12hsm */ public boolean removeSubmission(String assID, String studentID) { String removeSubmissionStatement = "DELETE FROM " + "Submission WHERE (AssignmentId=? AND StudentId=?)"; boolean result; int assignmentId = Integer.parseInt(assID); int studentId = Integer.parseInt(studentID); try { int rowsAffected = databaseConnection.update(removeSubmissionStatement, assignmentId, studentId); result = rowsAffected == 1; } catch (IncorrectResultSizeDataAccessException e) { result = false; } catch (DataAccessException e1) { result = false; } return result; } /** * Get all ungraded submissions for an assignment * * @param assId The assignment to get submissions for * @return A list of ungraded submissions for the assignment * * @author tfy12hsm */ public Optional<List<Submission>> getAllUngraded(String assId) { String getAllUngradedStatement = "SELECT " + "sub.AssignmentId,sub.StudentId,stu.FirstName,stu.LastName," + "sub.SubmissionDate,sub.Grade,sub.TeacherId," + "sub.StudentPublishConsent,sub.PublishStudentSubmission FROM" + " Submission AS sub LEFT JOIN Users AS stu ON " + "sub.studentId=stu.userId WHERE (AssignmentId=?) AND " + "(Grade IS NULL)"; int assignmentId = Integer.parseInt(assId); return getSubmissionsFromStatement(getAllUngradedStatement, assignmentId); } /** * Will return the result of a query to the DB. * @param statement the string containing the sql statement * @param assignmentID ID to specify assignment to get submissions for. * @return a list of submissions. */ private Optional<List<Submission>> getSubmissionsFromStatement(String statement, int assignmentID){ List<Submission> submissions = new ArrayList<>(); //TODO exceptions should maybe be handled in a better way? try { List<Map<String, Object>> rows = databaseConnection.queryForList( statement, assignmentID); for (Map<String, Object> row : rows) { Submission submission = new Submission(row); submissions.add(submission); } } catch (IncorrectResultSizeDataAccessException e) { return Optional.empty(); } catch (DataAccessException e1) { return Optional.empty(); } return Optional.of(submissions); } /** * Get all submissions for an assignment * @param assId The assignment to get submissions for * @return A list of submissions for the assignment * * @author tfy12hsm */ public Optional<List<Submission>> getAllSubmissions(int assignmentID) { String getAllSubmissionsStatement = "SELECT " + "sub.AssignmentId,sub.StudentId,stu.FirstName,stu.LastName," + "sub.SubmissionDate,sub.Grade,sub.TeacherId," + "sub.StudentPublishConsent,sub.PublishStudentSubmission FROM" + " Submission AS sub LEFT JOIN Users AS stu ON " + "sub.studentId=stu.userId WHERE (AssignmentId=?)"; return getSubmissionsFromStatement(getAllSubmissionsStatement, assignmentID); } /** * * Get all submissions for an assignment, including students that have not * yet made a submission. * * @param assId The assignment to get submissions for * @return A list of submissions for the assignment * * @author tfy12hsm */ public Optional<List<Submission>> getAllSubmissionsWithStudents (String assId) { List<Submission> submissions = new ArrayList<>(); int assignmentId = Integer.parseInt(assId); String getAllSubmissionsWithStudentsStatement = "SELECT ass.AssignmentId,par.UserId AS StudentId,sub.SubmissionDate" + ",sub.Grade,sub.TeacherId,sub.StudentPublishConsent" + ",sub.PublishStudentSubmission FROM Assignment" + " AS ass RIGHT JOIN " + "Participant AS par ON ass.CourseId=par.CourseId LEFT JOIN " + "Submission AS sub ON par.userId=sub.studentId WHERE " + "(par.function='Student') AND (ass.AssignmentId=?)"; return getSubmissionsFromStatement(getAllSubmissionsWithStudentsStatement, assignmentId); } /** * Returns a sought submission from the database. * * @param assignmentId assignment identifier * @param userId user identifier * @return sought submission * * @author tfy12hsm */ public Optional<Submission> getSubmission(int assignmentId, int userId) { Submission result = null; String getStudentSubmissionStatement = "SELECT * FROM Submission WHERE AssignmentId=? AND StudentId=?"; try { Map<String, Object> map = databaseConnection.queryForMap( getStudentSubmissionStatement, assignmentId, userId); result = new Submission(map); } catch (IncorrectResultSizeDataAccessException e){ //TODO return Optional.empty(); } catch (DataAccessException e1){ //TODO return Optional.empty(); } return Optional.of(result); } }
package top.zbeboy.isy.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.cache.CacheManager; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import javax.inject.Inject; import java.io.*; import java.util.Map; /** * . * * @author zbeboy * @version 1.0 * @since 1.0 */ @Component public class InitConfiguration implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(InitConfiguration.class); private final CacheManager cacheManager; @Autowired private RequestMappingHandlerMapping handlerMapping; @Inject private Environment env; @Autowired public InitConfiguration(CacheManager cacheManager) { this.cacheManager = cacheManager; } @Override public void run(String... strings) throws Exception { logger.info("\n\n" + "=========================================================\n" + "Using cache manager: " + this.cacheManager.getClass().getName() + "\n" + "=========================================================\n\n"); initUrlMapping(); } /** * url mapping */ public void initUrlMapping() { try { String filePath = Workbook.URL_MAPPING_FILE_PATH; String resourcesPath = Workbook.SETTINGS_PATH; File file = new File(resourcesPath); if(!file.exists()){ if(file.mkdirs()){ PrintWriter printWriter = new PrintWriter(filePath); final String[] url = {""}; Map<RequestMappingInfo, HandlerMethod> map = this.handlerMapping.getHandlerMethods(); map.forEach((key, value) -> { url[0] = key.toString(); url[0] = url[0].split(",")[0]; int i1 = url[0].indexOf("[") + 1; int i2 = url[0].lastIndexOf("]"); url[0] = url[0].substring(i1, i2); printWriter.println(url[0]); }); printWriter.close(); logger.info("Init url mapping to {} finish!",filePath); } } } catch (IOException e) { logger.error("Init url mapping error : {}",e); } } }
package valandur.webapi.permissions; import ninja.leaping.configurate.ConfigurationNode; import valandur.webapi.misc.TreeNode; import java.util.*; public class Permissions { public static TreeNode<String, Boolean> permissionTreeFromConfig(ConfigurationNode config) { if (config == null || config.getValue() == null) { return new TreeNode<>(false); } if (!config.hasMapChildren()) { if (config.getValue().getClass() == Boolean.class) return new TreeNode<>(config.getKey().toString(), config.getBoolean()); else { TreeNode<String, Boolean> node = new TreeNode<>(config.getKey().toString(), true); node.addChild(new TreeNode<>("*", true)); return node; } } TreeNode<String, Boolean> root = new TreeNode<>(config.getKey().toString(), true); for (Map.Entry<Object, ? extends ConfigurationNode> entry : config.getChildrenMap().entrySet()) { if (entry.getKey().toString().equalsIgnoreCase(".")) { root.setValue(entry.getValue().getBoolean()); continue; } root.addChild(permissionTreeFromConfig(entry.getValue())); } return root; } public static void permissionTreeToConfig(ConfigurationNode config, TreeNode<String, Boolean> perms) { if (perms == null) { return; } Collection<TreeNode<String, Boolean>> children = perms.getChildren(); if (children.size() == 0) { config.setValue(perms.getValue()); return; } TreeNode<String, Boolean> first = children.iterator().next(); if (children.size() == 1 && perms.getValue() && first.getKey().equalsIgnoreCase("*") && first.getValue()) { config.setValue("*"); return; } if (!perms.getValue()) { config.getNode(".").setValue(false); } for (TreeNode<String, Boolean> child : children) { permissionTreeToConfig(config.getNode(child.getKey()), child); } } public static boolean permits(TreeNode<String, Boolean> perms, String[] reqPerms) { return permits(perms, Arrays.asList(reqPerms)); } public static boolean permits(TreeNode<String, Boolean> perms, List<String> reqPerms) { return subPermissions(perms, reqPerms).getValue(); } public static TreeNode<String, Boolean> subPermissions(TreeNode<String, Boolean> perms, String[] path) { return subPermissions(perms, Arrays.asList(path)); } public static TreeNode<String, Boolean> subPermissions(TreeNode<String, Boolean> perms, List<String> path) { if (perms.getKey() != null && perms.getKey().equalsIgnoreCase("*") && perms.getValue()) { return perms; } for (String perm : path) { Optional<TreeNode<String, Boolean>> subPerm = perms.getChild(perm); if (subPerm.isPresent()) { perms = subPerm.get(); continue; } Optional<TreeNode<String, Boolean>> allChild = perms.getChild("*"); return allChild.orElseGet(Permissions::emptyNode); } // or the path had no elements return perms; } public static TreeNode<String, Boolean> emptyNode() { return new TreeNode<>(false); } /** * Constructs a node which permits all operations * @return A node that allowed all operations */ public static TreeNode<String, Boolean> permitAllNode() { TreeNode<String, Boolean> node = new TreeNode<>(true); node.addChild(new TreeNode<>("*", true)); return node; } }
package aj.hadoop.monitor.mapreduce; import java.io.*; import java.net.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.management.*; import java.util.StringTokenizer; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.Mapper.Context; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import aj.hadoop.monitor.util.PickerClient; import java.util.logging.Logger; import java.util.logging.Level; import java.util.logging.FileHandler; @Aspect public abstract class MapperMonitor { private String HOST = "localhost"; private int PORT = 9999; /** log file */ public static final String LOGFILE = "Hanoi-MethodTraceMonitor.log"; /** logger */ private Logger logger = null; /** file handler */ private FileHandler fh = null; /** * initialize */ public MapperMonitor() { logger = Logger.getLogger(this.getClass().getName()); try { fh = new FileHandler(this.LOGFILE, true); logger.addHandler(fh); } catch (IOException e) { e.printStackTrace(); } logger.log(Level.INFO, "Start trace..."); } @Pointcut ("call(void org.apache.hadoop.mapreduce.Mapper.Context.write" + "(" + "java.lang.Object, " + "java.lang.Object" + "))" + "&& cflow(execution(public void org.apache.hadoop.examples.**.map(..)))" + "&& args(key, value)") public void pointcut_mapper_out(Object key, Object value){} @Before ("pointcut_mapper_out( key, value )") public void logging( JoinPoint thisJoinPoint, Object key, Object value) { PickerClient client = new PickerClient(); client.setHost(this.HOST); client.setPORT(this.PORT); client.send((String)key); System.err.println("** [POINTCUT]" + (String)key); } }
package net.acomputerdog.RealisticStone; import net.acomputerdog.BlazeLoader.api.block.ApiBlock; import net.acomputerdog.BlazeLoader.main.Version; import net.acomputerdog.BlazeLoader.mod.Mod; import net.acomputerdog.BlazeLoader.util.logger.BLLogger; public class ModRealisticStone extends Mod { public static final BLLogger logger = new BLLogger("Realistic_Stone", false, false); /** * Returns ID used to identify this mod internally, even among different versions of the same mod. Mods should override. * --This should never be changed after the mod has been released!-- * * @return Returns the id of the mod. */ @Override public String getModId() { return "acomputerdog.realisticstone"; } /** * Returns the user-friendly name of the mod. Mods should override. * --Can be changed among versions, so this should not be used to ID mods!-- * * @return Returns user-friendly name of the mod. */ @Override public String getModName() { return "Realistic Stone"; } /** * Gets the version of the mod as an integer for choosing the newer version. * * @return Return the version of the mod as an integer. */ @Override public int getIntModVersion() { return 0; } /** * Gets the version of the mod as a String for display. * * @return Returns the version of the mod as an integer. */ @Override public String getStringModVersion() { return "0.0"; } /** * Returns true if this mod is compatible with the installed version of BlazeLoader. This should be checked using Version.class. * -Called before mod is loaded! Do not depend on Mod.load()!- * * @return Returns true if the mod is compatible with the installed version of BlazeLoader. */ @Override public boolean isCompatibleWithBLVersion() { if(!Version.getMinecraftVersion().equals("1.7.2")){ System.out.println("TerrainEdit - Incorrect Minecraft version, aborting launch!"); return false; }else if(Version.getGlobalVersion() == 2 && Version.getApiVersion() > 9){ System.out.println("TerrainEdit - Unknown BL version, bad things may happen!"); return true; }else if(Version.getGlobalVersion() != 2 || Version.getApiVersion() <= -1){ System.out.println("TerrainEdit - Incompatible BL version, aborting launch!"); return false; }else{ System.out.println("TerrainEdit - Valid BL and MC versions."); return true; } } /** * Gets a user-friendly description of the mod. * * @return Return a String representing a user-friendly description of the mod. */ @Override public String getModDescription() { return "Makes stone harder at deeper depths"; } /** * Called when mod is started. Game is fully loaded and can be interacted with. */ @Override public void start() { ApiBlock.registerBlock(new BlockRealisticStone(ApiBlock.getBlockByName("stone")), "stone", 1); } /** * Called when mod is loaded. Called before game is loaded. */ @Override public void load() { logger.logInfo("Realistic Stone is starting."); } /** * Called when mod is stopped. Game is about to begin shutting down, so mod should release system resources, close streams, etc. */ @Override public void stop() { logger.logInfo("Realistic Stone is stopping."); } }
/* * Thibaut Colar Nov 18, 2009 */ package net.colar.netbeans.fan.completion; import fan.sys.Type; import java.util.Collections; import net.colar.netbeans.fan.indexer.FanIndexer; import net.colar.netbeans.fan.structure.FanBasicElementHandle; import org.netbeans.modules.csl.api.ElementKind; import org.netbeans.modules.csl.api.HtmlFormatter; import org.openide.util.ImageUtilities; import net.colar.netbeans.fan.indexer.model.FanType; /** * Propose a Type such as Str or Int * ForcedName is used for using with a "As" clause, if null just use type.name() * @author thibautc */ public class FanTypeProposal extends FanCompletionProposal { private final String pod; public FanTypeProposal(FanType type, int anchor, String forcedName) { Boolean isJava=false; this.pod = type.getPod(); this.name = type.getSimpleName(); if (forcedName != null) { this.name = forcedName; } this.anchor = anchor; this.modifiers = Collections.emptySet(); this.kind = ElementKind.CLASS; icon = ImageUtilities.loadImageIcon("net/colar/netbeans/fan/fan.png", false); if (isJava) { icon = ImageUtilities.loadImageIcon("net/colar/netbeans/fan/project/resources/java.png", false); } FanBasicElementHandle handle = new FanBasicElementHandle(name, kind); handle.setDoc(FanIndexer.getDoc(type)); element = handle; } public FanTypeProposal(Type type, int anchor, String forcedName) { if (type.isJava()) { String qname = type.qname(); this.pod = qname.substring(0, qname.lastIndexOf("::")); } else { // for java type pod() return null; this.pod = type.pod().name(); } this.name = type.name(); if (forcedName != null) { this.name = forcedName; } this.anchor = anchor; this.modifiers = Collections.emptySet(); this.kind = ElementKind.CLASS; icon = ImageUtilities.loadImageIcon("net/colar/netbeans/fan/fan.png", false); if (type.isJava()) { icon = ImageUtilities.loadImageIcon("net/colar/netbeans/fan/project/resources/java.png", false); } FanBasicElementHandle handle = new FanBasicElementHandle(name, kind); handle.setDoc(FanIndexer.fanDocToHtml(type.doc())); element = handle; } @Override public String getInsertPrefix() { return name; } @Override public String getRhsHtml(HtmlFormatter formater) { return "[" + (pod == null ? "??" : pod) + "]"; } }
package net.ssehub.kernel_haven.analysis; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import net.ssehub.kernel_haven.SetUpException; import net.ssehub.kernel_haven.build_model.BuildModel; import net.ssehub.kernel_haven.code_model.SourceFile; import net.ssehub.kernel_haven.config.Configuration; import net.ssehub.kernel_haven.config.DefaultSettings; import net.ssehub.kernel_haven.provider.AbstractProvider; import net.ssehub.kernel_haven.util.ExtractorException; import net.ssehub.kernel_haven.util.Timestamp; import net.ssehub.kernel_haven.util.io.ITableCollection; import net.ssehub.kernel_haven.util.io.ITableWriter; import net.ssehub.kernel_haven.util.io.csv.CsvFileCollection; import net.ssehub.kernel_haven.variability_model.VariabilityModel; /** * An analysis that is a pipeline consisting of {@link AnalysisComponent}s. * * @author Adam */ public abstract class PipelineAnalysis extends AbstractAnalysis { private static PipelineAnalysis instance; private ITableCollection resultCollection; private ExtractorDataDuplicator<VariabilityModel> vmStarter; private ExtractorDataDuplicator<BuildModel> bmStarter; private ExtractorDataDuplicator<SourceFile> cmStarter; /** * Creates a new {@link PipelineAnalysis}. * * @param config The global configuration. */ public PipelineAnalysis(Configuration config) { super(config); } /** * The {@link PipelineAnalysis} that is the current main analysis in this execution. May be null if no * {@link PipelineAnalysis} is the main analysis component. * * @return The current {@link PipelineAnalysis} instance. */ static PipelineAnalysis getInstance() { return instance; } /** * Returns the {@link AnalysisComponent} that provides the variability model from the extractors. * * @return The {@link AnalysisComponent} that provides the variability model. */ protected AnalysisComponent<VariabilityModel> getVmComponent() { return vmStarter.createNewStartingComponent(config); } /** * Returns the {@link AnalysisComponent} that provides the build model from the extractors. * * @return The {@link AnalysisComponent} that provides the build model. */ protected AnalysisComponent<BuildModel> getBmComponent() { return bmStarter.createNewStartingComponent(config); } /** * Returns the {@link AnalysisComponent} that provides the code model from the extractors. * * @return The {@link AnalysisComponent} that provides the code model. */ protected AnalysisComponent<SourceFile> getCmComponent() { return cmStarter.createNewStartingComponent(config); } /** * The collection that {@link AnalysisComponent}s should write their intermediate output to. * * @return The {@link ITableCollection} to write output to. */ ITableCollection getResultCollection() { return resultCollection; } /** * Creates the result collection from the user settings. * * @return The result collection to store files in. * * @throws SetUpException If creating the result collection fails. */ private ITableCollection createResultCollection() throws SetUpException { String className = config.getValue(DefaultSettings.ANALYSIS_RESULT); if (className == null) { throw new SetUpException(); } try { @SuppressWarnings("unchecked") Class<? extends ITableCollection> clazz = (Class<? extends ITableCollection>) Class.forName(className); // TODO: find a proper way to call the constructor; we currently always call it with one File parameter return clazz.getConstructor(File.class).newInstance(new File(getOutputDir(), Timestamp.INSTANCE.getFilename("Analysis", "xlsx"))); } catch (ReflectiveOperationException | IllegalArgumentException | ClassCastException e) { throw new SetUpException(e); } } /** * Creates the pipeline. * * @return The "main" (i.e. the last) component of the pipeline. * * @throws SetUpException If setting up the pipeline fails. */ protected abstract AnalysisComponent<?> createPipeline() throws SetUpException; @Override public void run() { Thread.currentThread().setName("AnalysisPipelineController"); try { vmStarter = new ExtractorDataDuplicator<>(vmProvider, false); bmStarter = new ExtractorDataDuplicator<>(bmProvider, false); cmStarter = new ExtractorDataDuplicator<>(cmProvider, true); try { resultCollection = createResultCollection(); } catch (SetUpException e) { resultCollection = new CsvFileCollection(new File(getOutputDir(), "Analysis_" + Timestamp.INSTANCE.getFileTimestamp())); } instance = this; AnalysisComponent<?> mainComponent = createPipeline(); vmProvider.start(); bmProvider.start(); cmProvider.start(); vmStarter.start(); bmStarter.start(); cmStarter.start(); try (ITableWriter writer = resultCollection.getWriter(mainComponent.getResultName())) { Object result; while ((result = mainComponent.getNextResult()) != null) { LOGGER.logInfo("Got analysis result: " + result.toString()); writer.writeRow(result); } for (File file : resultCollection.getFiles()) { addOutputFile(file); } } catch (IOException e) { LOGGER.logException("Exception while writing output file", e); } try { resultCollection.close(); } catch (IOException e) { LOGGER.logException("Exception while closing output file", e); } } catch (SetUpException e) { LOGGER.logException("Exception while setting up", e); } } /** * A class for duplicating the extractor data. This way, multiple analysis components can have the same models * as their input data. * * @param <T> The type of model to duplicate. */ private static class ExtractorDataDuplicator<T> implements Runnable { private AbstractProvider<T> provider; private boolean multiple; private List<StartingComponent<T>> startingComponents; /** * Creates a new ExtractorDataDuplicator. * * @param provider The provider to get the data from. * @param multiple Whether the provider should be polled multiple times or just onece. */ public ExtractorDataDuplicator(AbstractProvider<T> provider, boolean multiple) { this.provider = provider; this.multiple = multiple; startingComponents = new LinkedList<>(); } /** * Creates a new starting component that will get its own copy of the data from us. * * @param config The configuration to create the component with. * * @return The starting component that can be used as input data for other analysis components. */ public StartingComponent<T> createNewStartingComponent(Configuration config) { StartingComponent<T> component = new StartingComponent<>(config); startingComponents.add(component); return component; } /** * Adds the given data element to all starting components. * * @param data The data to add. */ private void addToAllComponents(T data) { for (StartingComponent<T> component : startingComponents) { component.addResult(data); } } /** * Starts a new thread that copies the extractor data to all stating components created up until now. */ public void start() { new Thread(this, "ExtractorDataDuplicator").start(); } @Override public void run() { if (multiple) { T data; while ((data = provider.getNextResult()) != null) { addToAllComponents(data); } ExtractorException exc; while ((exc = provider.getNextException()) != null) { LOGGER.logException("Got extractor exception", exc); } } else { T data = provider.getResult(); if (data != null) { addToAllComponents(data); } ExtractorException exc = provider.getException(); if (exc != null) { LOGGER.logException("Got extractor exception", exc); } } for (StartingComponent<T> component : startingComponents) { synchronized (component) { component.done = true; component.notifyAll(); } } } } /** * A starting component for the analysis pipeline. This is used to pass the extractor data to the analysis * components. This class does nothing; it is only used by {@link ExtractorDataDuplicator}. * * @param <T> The type of result data that this produces. */ private static class StartingComponent<T> extends AnalysisComponent<T> { private boolean done = false; /** * Creates a new starting component. * * @param config The global configuration. */ public StartingComponent(Configuration config) { super(config); } @Override protected void execute() { // wait until the duplicator tells us that we are done synchronized (this) { while (!done) { try { wait(); } catch (InterruptedException e) { } } } } @Override public String getResultName() { return "StartingComponent"; } } }
package org.aikodi.chameleon.core.reference; import org.aikodi.chameleon.core.declaration.Declaration; import org.aikodi.chameleon.core.declaration.TargetDeclaration; import org.aikodi.chameleon.core.lookup.DeclarationSelector; import org.aikodi.chameleon.core.lookup.NameSelector; import org.aikodi.chameleon.util.Util; /** * A default implementation for cross-reference that consist of only a name. * * @author Marko van Dooren * * @param <D> * The type of the declaration that is referenced. */ public class NameReference<D extends Declaration> extends ElementReference<D> { /** * The class object for the type of declaration that is referenced. */ private Class<D> _specificClass; /** * Initialize a new simple reference given a qualified name. The name * is split at every dot, and multiple objects are created to form a chain of * references. * * The prefixes are all references to {@link Declaration}s. If the * given type must be used for all prefixes, use constructor * {@link #NameReference(String, Class, boolean)} with true as the last * argument. * * @param qualifiedName * The qualified name of the referenced declaration. The exact * meaning of the name is determined by the lookup rules of the * language. If the name contains dots, the last part will be the * name of this name reference, and the prefix will be used * to create another NameReference that will be the {@link #getTarget()} * of this NameReference. * @param type * The type of declaration that is referenced. */ public NameReference(String qualifiedName, Class<D> type) { this(qualifiedName, type, false); } /** * Initialize a new simple reference given a qualified name. The name * is split at every dot, and multiple objects are created to form a chain of * references. * * If recusriveLimit is true, the prefixes are all references to elements of * the given type. If recursiveLimit is false, the prefixes are all * references to {@link Declaration}s. * * @param qualifiedName * The qualified name of the referenced declaration. * @param type * The type of declaration that is referenced. * @param recursiveLimit * Indicate whether the type restriction must be applied to the * prefixes. */ public NameReference(String qualifiedName, Class<D> type, boolean recursiveLimit) { this(null, Util.getLastPart(qualifiedName), type); setTarget(createTarget(qualifiedName, type, recursiveLimit)); } /** * Initialize a new simple reference given a qualified name. The name * is split at every dot, and multiple objects are created to form a chain of * references. * * @param target * A cross-reference to the target declaration in which this * name reference must be resolved. * @param qualifiedName * The qualified name of the element referenced by this name reference. * @param type * The type of declaration that is referenced. */ public NameReference(CrossReferenceTarget target, String qualifiedName, Class<D> type) { super(qualifiedName); setTarget(target); _specificClass = type; } /** * YOU MUST OVERRIDE THIS METHOD IF YOU SUBCLASS THIS CLASS! */ @Override protected NameReference<D> cloneSelf() { return new NameReference<D>(null, name(), referencedType()); } private DeclarationSelector<D> _selector; @Override public DeclarationSelector<D> selector() { if (_selector == null) { _selector = new NameSelector<D>(_specificClass) { @Override public String name() { return NameReference.this.name(); } }; } return _selector; } /** * Return the {@link Class} object of the kind of elements that this * reference can point at. * * @return */ public Class<D> referencedType() { return _specificClass; } protected NameReference createTarget(String fqn, Class specificClass, boolean recursiveLimit) { String allButLastPart = Util.getAllButLastPart(fqn); if (allButLastPart == null) { return null; } else { return createSimpleReference(allButLastPart, recursiveLimit ? specificClass : Declaration.class, recursiveLimit); } } /** * Subclasses must override this method and return an object of the type of * the subclass. * * @param qualifiedName * The qualified name of the referenced declaration. * @param type * The type of declaration that is referenced. * @param recursiveLimit * Indicate whether the type restriction must be applied to the * prefixes. * @return */ protected <D extends Declaration> NameReference<D> createSimpleReference(String qualifiedName, Class<D> kind, boolean recursiveLimit) { return new NameReference(qualifiedName, recursiveLimit ? kind : Declaration.class, recursiveLimit); } }
package com.armandgray.seeme; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.ColorStateList; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.armandgray.seeme.models.User; import com.armandgray.seeme.services.HttpService; import com.armandgray.seeme.utils.BroadcastObserver; import com.armandgray.seeme.utils.NetworkHelper; import com.armandgray.seeme.utils.UserRVAdapter; import java.util.Arrays; import java.util.List; import java.util.Observable; import java.util.Observer; public class MainActivity extends AppCompatActivity implements Observer { public static final String JSON_URI = "http://52.39.178.132:8080/discoverable/localusers?networkId="; private static final String DEBUG_TAG = "DEBUG_TAG"; private boolean networkOK; private boolean isWifiConnected; private FloatingActionButton fab; private String ssid; private String networkId; private String other; private BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.e("BroadcastReceiver: ", "http Broadcast Received"); User[] userList = (User[]) intent.getParcelableArrayExtra(HttpService.HTTP_SERVICE_PAYLOAD); if (userList != null) { setupRvUsers(Arrays.asList(userList)); } else { Log.i("USER_LIST", "LIST IS NULL"); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setupFAB(); LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getApplicationContext()); broadcastManager.registerReceiver(httpBroadcastReceiver, new IntentFilter(HttpService.HTTP_SERVICE_MESSAGE)); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); isWifiConnected = networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI; if (isWifiConnected) { getWifiNetworkId(); } BroadcastObserver.getInstance().addObserver(this); networkOK = NetworkHelper.hasNetworkAccess(this); updateFAB(); } private void setupFAB() { fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (networkOK && isWifiConnected) { Intent intent = new Intent(MainActivity.this, HttpService.class); intent.setData(Uri.parse(JSON_URI + networkId)); startService(intent); } else { Toast.makeText(MainActivity.this, "WiFi Connection Unsuccessful!", Toast.LENGTH_SHORT).show(); } } }); } private void updateFAB() { if (isWifiConnected) { fab.setBackgroundTintList(ColorStateList.valueOf( ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null))); } else { fab.setBackgroundTintList(ColorStateList.valueOf( ResourcesCompat.getColor(getResources(), R.color.fabNoWifiColor, null))); } } private void getWifiNetworkId() { WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService (Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); ssid = wifiInfo.getSSID(); networkId = wifiInfo.getBSSID(); if (ssid.equals("<unknown ssid>")) { Log.i("ActiveNetInfo", "Wifi Network Not Found: " + String.valueOf(ssid)); } else { Log.i("ActiveNetInfo", "Wifi Network " + String.valueOf(ssid) + ": " + networkId); } } @Override public void update(Observable o, Object data) { NetworkInfo info = (NetworkInfo) data; isWifiConnected = info != null; updateFAB(); if (info != null) { getWifiNetworkId(); } } private void setupRvUsers(List<User> list) { RecyclerView rvUsers = (RecyclerView) findViewById(R.id.rvUsers); rvUsers.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); rvUsers.setAdapter(new UserRVAdapter(this, list)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @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. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { super.onDestroy(); LocalBroadcastManager.getInstance(getApplicationContext()) .unregisterReceiver(httpBroadcastReceiver); } }
package org.bouncycastle.cms; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.cms.IssuerAndSerialNumber; import org.bouncycastle.asn1.cms.KeyAgreeRecipientIdentifier; import org.bouncycastle.asn1.cms.KeyAgreeRecipientInfo; import org.bouncycastle.asn1.cms.OriginatorIdentifierOrKey; import org.bouncycastle.asn1.cms.OriginatorPublicKey; import org.bouncycastle.asn1.cms.RecipientEncryptedKey; import org.bouncycastle.asn1.cms.RecipientKeyIdentifier; import org.bouncycastle.asn1.cms.ecc.MQVuserKeyingMaterial; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.jce.spec.MQVPrivateKeySpec; import org.bouncycastle.jce.spec.MQVPublicKeySpec; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import javax.crypto.KeyAgreement; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; /** * the RecipientInfo class for a recipient who has been sent a message * encrypted using key agreement. */ public class KeyAgreeRecipientInformation extends RecipientInformation { private KeyAgreeRecipientInfo info; private ASN1OctetString encryptedKey; /** * @deprecated */ public KeyAgreeRecipientInformation( KeyAgreeRecipientInfo info, AlgorithmIdentifier encAlg, InputStream data) { this(info, encAlg, null, null, data); } /** * @deprecated */ public KeyAgreeRecipientInformation( KeyAgreeRecipientInfo info, AlgorithmIdentifier encAlg, AlgorithmIdentifier macAlg, InputStream data) { this(info, encAlg, macAlg, null, data); } KeyAgreeRecipientInformation( KeyAgreeRecipientInfo info, AlgorithmIdentifier encAlg, AlgorithmIdentifier macAlg, AlgorithmIdentifier authEncAlg, InputStream data) { super(encAlg, macAlg, authEncAlg, info.getKeyEncryptionAlgorithm(), data); this.info = info; this.rid = new RecipientId(); try { ASN1Sequence s = this.info.getRecipientEncryptedKeys(); // TODO Handle the case of more than one encrypted key RecipientEncryptedKey id = RecipientEncryptedKey.getInstance( s.getObjectAt(0)); KeyAgreeRecipientIdentifier karid = id.getIdentifier(); IssuerAndSerialNumber iAndSN = karid.getIssuerAndSerialNumber(); if (iAndSN != null) { rid.setIssuer(iAndSN.getName().getEncoded()); rid.setSerialNumber(iAndSN.getSerialNumber().getValue()); } else { RecipientKeyIdentifier rKeyID = karid.getRKeyID(); // Note: 'date' and 'other' fields of RecipientKeyIdentifier appear to be only informational rid.setSubjectKeyIdentifier(rKeyID.getSubjectKeyIdentifier().getOctets()); } encryptedKey = id.getEncryptedKey(); } catch (IOException e) { throw new IllegalArgumentException("invalid rid in KeyAgreeRecipientInformation"); } } private PublicKey getSenderPublicKey(Key receiverPrivateKey, OriginatorIdentifierOrKey originator, Provider prov) throws CMSException, GeneralSecurityException, IOException { OriginatorPublicKey opk = originator.getOriginatorKey(); if (opk != null) { return getPublicKeyFromOriginatorPublicKey(receiverPrivateKey, originator.getOriginatorKey(), prov); } OriginatorId origID = new OriginatorId(); IssuerAndSerialNumber iAndSN = originator.getIssuerAndSerialNumber(); if (iAndSN != null) { origID.setIssuer(iAndSN.getName().getEncoded()); origID.setSerialNumber(iAndSN.getSerialNumber().getValue()); } else { SubjectKeyIdentifier ski = originator.getSubjectKeyIdentifier(); origID.setSubjectKeyIdentifier(ski.getKeyIdentifier()); } return getPublicKeyFromOriginatorId(origID, prov); } private PublicKey getPublicKeyFromOriginatorPublicKey(Key receiverPrivateKey, OriginatorPublicKey originatorPublicKey, Provider prov) throws CMSException, GeneralSecurityException, IOException { PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance( ASN1Object.fromByteArray(receiverPrivateKey.getEncoded())); SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo( privInfo.getAlgorithmId(), originatorPublicKey.getPublicKey().getBytes()); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubInfo.getEncoded()); KeyFactory fact = KeyFactory.getInstance(keyEncAlg.getObjectId().getId(), prov); return fact.generatePublic(pubSpec); } private PublicKey getPublicKeyFromOriginatorId(OriginatorId origID, Provider prov) throws CMSException { // TODO Support all alternatives for OriginatorIdentifierOrKey // see RFC 3852 6.2.2 throw new CMSException("No support for 'originator' as IssuerAndSerialNumber or SubjectKeyIdentifier"); } private SecretKey calculateAgreedWrapKey(String wrapAlg, PublicKey senderPublicKey, PrivateKey receiverPrivateKey, Provider prov) throws CMSException, GeneralSecurityException, IOException { String agreeAlg = keyEncAlg.getObjectId().getId(); if (agreeAlg.equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) { byte[] ukmEncoding = info.getUserKeyingMaterial().getOctets(); MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.getInstance( ASN1Object.fromByteArray(ukmEncoding)); PublicKey ephemeralKey = getPublicKeyFromOriginatorPublicKey(receiverPrivateKey, ukm.getEphemeralPublicKey(), prov); senderPublicKey = new MQVPublicKeySpec(senderPublicKey, ephemeralKey); receiverPrivateKey = new MQVPrivateKeySpec(receiverPrivateKey, receiverPrivateKey); } KeyAgreement agreement = KeyAgreement.getInstance(agreeAlg, prov); agreement.init(receiverPrivateKey); agreement.doPhase(senderPublicKey, true); return agreement.generateSecret(wrapAlg); } private Key unwrapSessionKey(String wrapAlg, SecretKey agreedKey, Provider prov) throws GeneralSecurityException { AlgorithmIdentifier aid = getActiveAlgID(); String alg = aid.getObjectId().getId(); byte[] encKeyOctets = encryptedKey.getOctets(); // TODO Should we try alternate ways of unwrapping? // (see KeyTransRecipientInformation.getSessionKey) Cipher keyCipher = Cipher.getInstance(wrapAlg, prov); keyCipher.init(Cipher.UNWRAP_MODE, agreedKey); return keyCipher.unwrap(encKeyOctets, alg, Cipher.SECRET_KEY); } protected Key getSessionKey(Key receiverPrivateKey, Provider prov) throws CMSException { try { String wrapAlg = DERObjectIdentifier.getInstance( ASN1Sequence.getInstance(keyEncAlg.getParameters()).getObjectAt(0)).getId(); PublicKey senderPublicKey = getSenderPublicKey(receiverPrivateKey, info.getOriginator(), prov); SecretKey agreedWrapKey = calculateAgreedWrapKey(wrapAlg, senderPublicKey, (PrivateKey)receiverPrivateKey, prov); return unwrapSessionKey(wrapAlg, agreedWrapKey, prov); } catch (NoSuchAlgorithmException e) { throw new CMSException("can't find algorithm.", e); } catch (InvalidKeyException e) { throw new CMSException("key invalid in message.", e); } catch (InvalidKeySpecException e) { throw new CMSException("originator key spec invalid.", e); } catch (NoSuchPaddingException e) { throw new CMSException("required padding not supported.", e); } catch (Exception e) { throw new CMSException("originator key invalid.", e); } } /** * decrypt the content and return it */ public CMSTypedStream getContentStream( Key key, String prov) throws CMSException, NoSuchProviderException { return getContentStream(key, CMSUtils.getProvider(prov)); } public CMSTypedStream getContentStream( Key key, Provider prov) throws CMSException { Key sKey = getSessionKey(key, prov); return getContentFromSessionKey(sKey, prov); } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.servlets; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.PersistenceManagerRdbms; import org.gridlab.gridsphere.core.persistence.hibernate.DBTask; import org.gridlab.gridsphere.layout.PortletLayoutEngine; import org.gridlab.gridsphere.layout.PortletPageFactory; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.portletcontainer.*; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.security.auth.AuthenticationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import org.gridlab.gridsphere.services.core.request.RequestService; import org.gridlab.gridsphere.services.core.request.GenericRequest; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.net.SocketException; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); /* creates cookie requests */ private RequestService requestService = null; private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); //private static PortletRegistry registry = PortletRegistry.getInstance(); private static final String COOKIE_REQUEST = "cookie-request"; private int COOKIE_EXPIRATION_TIME = 60 * 60 * 24 * 7; // 1 week (in secs) private PortletGroup coreGroup = null; private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); SportletLog.setConfigureURL(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties")); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); layoutEngine = PortletLayoutEngine.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { requestService = (RequestService) factory.createPortletService(RequestService.class, getServletConfig().getServletContext(), true); log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createPortletService(AccessControlManagerService.class, getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createPortletService(UserManagerService.class, getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createPortletService(LoginService.class, getServletConfig().getServletContext(), true); log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createPortletService(PortletManagerService.class, getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void setHeaders(HttpServletResponse res) { res.setContentType("text/html; charset=utf-8"); // Necessary to display UTF-8 encoded characters res.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server res.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance res.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale" res.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { setHeaders(res); GridSphereEvent event = new GridSphereEventImpl(context, req, res); PortletRequest portletReq = event.getPortletRequest(); // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { firstDoGet = Boolean.FALSE; log.debug("Testing Database"); // checking if database setup is correct DBTask dt = new DBTask(); dt.setAction(DBTask.ACTION_CHECKDB); dt.setConfigDir(GridSphereConfig.getServletContext().getRealPath("")); try { dt.execute(); } catch (Exception e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/database_error.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize portlet service factory factory.init(); // initialize needed services initializeServices(); // create a root user if none available userManagerService.initRootUser(); // initialize all portlets PortletResponse portletRes = event.getPortletResponse(); PortletInvoker.initAllPortlets(portletReq, portletRes); // deep inside a service is used which is why this must follow the factory.init layoutEngine.init(); } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } coreGroup = aclService.getCoreGroup(); } } setUserAndGroups(portletReq); checkUserHasCookie(event); setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); setTCKUser(portletReq); layoutEngine.service(event); //log.debug("Session stats"); //userSessionManager.dumpSessions(); //log.debug("Portlet service factory stats"); //factory.logStatistics(); /* log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } */ } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { log.info("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); u.setID("500"); Map l = new HashMap(); l.put(coreGroup, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(coreGroup, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup) it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // req.getPortletRole returns the role user has in core gridsphere group role = aclService.getRoleInGroup(user, coreGroup); // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_GROUP, coreGroup); req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } protected void checkUserHasCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); User user = req.getUser(); if (user instanceof GuestUser) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; System.err.println("found a cookie:"); System.err.println("name=" + c.getName()); System.err.println("value=" + c.getValue()); if (c.getName().equals("gsuid")) { String cookieVal = c.getValue(); int hashidx = cookieVal.indexOf(" if (hashidx > 0) { String uid = cookieVal.substring(0, hashidx); System.err.println("uid = " + uid); String reqid = cookieVal.substring(hashidx+1); System.err.println("reqid = " + reqid); GenericRequest genreq = requestService.getRequest(reqid, COOKIE_REQUEST); if (genreq != null) { if (genreq.getUserID().equals(uid)) { User newuser = userManagerService.getUser(uid); if (newuser != null) { setUserSettings(event, newuser); } } } } } } } } } protected void setUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); User user = req.getUser(); GenericRequest request = requestService.createRequest(COOKIE_REQUEST); Cookie cookie = new Cookie("gsuid", user.getID() + "#" + request.getOid()); request.setUserID(user.getID()); long time = Calendar.getInstance().getTime().getTime() + COOKIE_EXPIRATION_TIME * 1000; request.setLifetime(new Date(time)); requestService.saveRequest(request); // COOKIE_EXPIRATION_TIME is specified in secs cookie.setMaxAge(COOKIE_EXPIRATION_TIME); res.addCookie(cookie); System.err.println("adding a cookie"); } protected void removeUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("gsuid")) { int idx = c.getValue().indexOf(" if (idx > 0) { String reqid = c.getValue().substring(idx+1); System.err.println("reqid= " + reqid); GenericRequest request = requestService.getRequest(reqid, COOKIE_REQUEST); if (request != null) requestService.deleteRequest(request); } c.setMaxAge(0); res.addCookie(c); } } } } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); String username = req.getParameter("username"); String password = req.getParameter("password"); try { User user = loginService.login(username, password); // null out passwd password = null; setUserSettings(event, user); String remme = req.getParameter("remlogin"); if (remme != null) { setUserCookie(event); } else { removeUserCookie(event); } } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } catch (AuthenticationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } public void setUserSettings(GridSphereEvent event, User user) { PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (user.getAttribute(User.LOCALE) != null) { session.setAttribute(User.LOCALE, new Locale((String)user.getAttribute(User.LOCALE), "", "")); } if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); removeUserCookie(event); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); res.setHeader("Content-Length", String.valueOf(f.length())); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (SocketException e) { log.error("Caught SocketException: " + e.getMessage()); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 2.0.1"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { log.debug("contextInitialized()"); ServletContext ctx = event.getServletContext(); GridSphereConfig.setServletContext(ctx); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
package org.helioviewer.jhv.gui.dialogs; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Objects; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import org.helioviewer.jhv.Settings; import org.helioviewer.jhv.gui.JHVFrame; import org.helioviewer.jhv.gui.interfaces.ShowableDialog; import org.helioviewer.jhv.io.DataSources; import org.helioviewer.jhv.log.Log; import org.helioviewer.jhv.plugins.PluginContainer; import org.helioviewer.jhv.plugins.PluginManager; import org.helioviewer.jhv.view.j2k.io.jpip.JPIPCacheManager; import com.jidesoft.dialog.ButtonPanel; import com.jidesoft.dialog.StandardDialog; @SuppressWarnings("serial") public class PreferencesDialog extends StandardDialog implements ShowableDialog { private final JLabel labelCache = new JLabel("The image cache currently uses 0.0GB on disk.", JLabel.RIGHT); private void setLabelCache() { labelCache.setText(String.format("The image cache currently uses %.1fGB on disk.", JPIPCacheManager.getSize() / (1024 * 1024 * 1024.))); } private DefaultsSelectionPanel defaultsPanel; public PreferencesDialog() { super(JHVFrame.getFrame(), "Preferences", true); setResizable(false); } @Override public ButtonPanel createButtonPanel() { AbstractAction close = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { defaultsPanel.saveSettings(); setVisible(false); } }; setDefaultAction(close); setDefaultCancelAction(close); JButton closeBtn = new JButton(close); closeBtn.setText("Close"); setInitFocusedComponent(closeBtn); ButtonPanel panel = new ButtonPanel(); panel.add(closeBtn, ButtonPanel.AFFIRMATIVE_BUTTON); return panel; } @Override public JComponent createContentPanel() { defaultsPanel = new DefaultsSelectionPanel(); defaultsPanel.setBorder(BorderFactory.createEmptyBorder(3, 9, 3, 9)); return defaultsPanel; } @Override public JComponent createBannerPanel() { JPanel panel = createParametersPanel(); panel.setBorder(BorderFactory.createEmptyBorder(3, 9, 3, 9)); return panel; } @Override public void showDialog() { setLabelCache(); pack(); setLocationRelativeTo(JHVFrame.getFrame()); setVisible(true); } private JPanel createParametersPanel() { JPanel settings = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(0, 2, 0, 2); c.gridx = 0; c.gridy = 0; settings.add(new JLabel("Preferred server:", JLabel.RIGHT), c); c.gridx = 1; c.gridy = 0; JComboBox<String> combo = new JComboBox<>(DataSources.getServers().toArray(new String[0])); combo.setSelectedItem(Settings.getProperty("default.server")); combo.addActionListener(e -> Settings.setProperty("default.server", (String) Objects.requireNonNull(combo.getSelectedItem()))); settings.add(combo, c); c.gridx = 0; c.gridy = 1; settings.add(new JLabel("At start-up:", JLabel.RIGHT), c); c.gridx = 1; c.gridy = 1; JCheckBox defaultMovie = new JCheckBox("Load default movie", Boolean.parseBoolean(Settings.getProperty("startup.loadmovie"))); defaultMovie.addActionListener(e -> Settings.setProperty("startup.loadmovie", Boolean.toString(defaultMovie.isSelected()))); settings.add(defaultMovie, c); c.gridx = 1; c.gridy = 2; JCheckBox sampHub = new JCheckBox("Load SAMP hub", Boolean.parseBoolean(Settings.getProperty("startup.sampHub"))); sampHub.addActionListener(e -> Settings.setProperty("startup.sampHub", Boolean.toString(sampHub.isSelected()))); settings.add(sampHub, c); c.gridx = 0; c.gridy = 3; settings.add(new JLabel("Normalize (after restart):", JLabel.RIGHT), c); c.gridx = 1; c.gridy = 3; JCheckBox normalizeRadius = new JCheckBox("Solar radius", Boolean.parseBoolean(Settings.getProperty("display.normalize"))); normalizeRadius.addActionListener(e -> Settings.setProperty("display.normalize", Boolean.toString(normalizeRadius.isSelected()))); settings.add(normalizeRadius, c); c.gridx = 1; c.gridy = 4; JCheckBox normalizeAIA = new JCheckBox("SDO/AIA brightness", Boolean.parseBoolean(Settings.getProperty("display.normalizeAIA"))); normalizeAIA.addActionListener(e -> Settings.setProperty("display.normalizeAIA", Boolean.toString(normalizeAIA.isSelected()))); settings.add(normalizeAIA, c); c.gridx = 0; c.gridy = 5; settings.add(new JLabel("Plugins:", JLabel.RIGHT), c); c.gridx = 1; for (PluginContainer plugin : PluginManager.getPlugins()) { JCheckBox plugCheck = new JCheckBox("<html>" + plugin.getName() + "<br/><small>" + plugin.getDescription(), plugin.isActive()); plugCheck.addActionListener(e -> plugin.toggleActive()); settings.add(plugCheck, c); c.gridy++; } JPanel cache = new JPanel(new FlowLayout(FlowLayout.LEADING)); JButton clearCache = new JButton("Clear Cache"); clearCache.addActionListener(e -> { try { JPIPCacheManager.clear(); setLabelCache(); } catch (Exception ex) { Log.error("JPIP cache clear error", ex); } }); cache.add(labelCache); cache.add(clearCache); JPanel paramsPanel = new JPanel(new BorderLayout()); paramsPanel.add(settings, BorderLayout.PAGE_START); paramsPanel.add(cache, BorderLayout.PAGE_END); return paramsPanel; } private static class DefaultsSelectionPanel extends JPanel { final JTable grid; final TableModel model; DefaultsSelectionPanel() { super(new BorderLayout()); setPreferredSize(new Dimension(-1, 150)); String pass = Settings.getProperty("proxy.password"); try { pass = new String(Base64.getDecoder().decode(pass), StandardCharsets.UTF_8); } catch (Exception e) { pass = null; } String[][] tableData = { {"Proxy username", Settings.getProperty("proxy.username")}, {"Proxy password", pass}, }; model = new DefaultTableModel(tableData, new String[]{"Description", "Value"}) { @Override public boolean isCellEditable(int row, int column) { return column == 1; } }; JPasswordField passField = new JPasswordField(); DefaultCellEditor passEditor = new DefaultCellEditor(passField); grid = new JTable(model) { @Override public TableCellEditor getCellEditor(int row, int column) { if (row == 1 && column == 1) { Object val = getValueAt(1, 1); if (val instanceof String) passField.setText((String) val); return passEditor; } else return super.getCellEditor(row, column); } }; grid.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (row == 1 && column == 1) { if (value instanceof String) passField.setText((String) value); return passField; } return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } }); grid.setRowHeight(20); JScrollPane scrollPane = new JScrollPane(grid); grid.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // grid.setFillsViewportHeight(true); TableColumn col = grid.getColumnModel().getColumn(0); col.setMaxWidth(150); col.setMinWidth(150); add(scrollPane, BorderLayout.CENTER); } void saveSettings() { Object val0 = model.getValueAt(0, 1); if (val0 instanceof String) Settings.setProperty("proxy.username", (String) val0); Object val1 = model.getValueAt(1, 1); if (val1 instanceof String) { String s = Base64.getEncoder().withoutPadding().encodeToString(((String) val1).getBytes(StandardCharsets.UTF_8)); Settings.setProperty("proxy.password", s); } } } }
package org.jetbrains.plugins.scala.util; import scala.tools.ant.Scalac; public class AntScalaCompiler extends Scalac { public void execute() { setAddparams("-Xgenerics"); setAddparams("-target:jvm-1.5"); // setAddparams("-Xexperimental"); super.execute(); } }
package org.mockito.internal.invocation; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.*; import org.hamcrest.Matcher; import org.mockito.internal.matchers.CapturesArguments; import org.mockito.internal.matchers.MatcherDecorator; import org.mockito.internal.reporting.PrintSettings; import org.mockito.invocation.DescribedInvocation; import org.mockito.invocation.Invocation; import org.mockito.invocation.Location; @SuppressWarnings("unchecked") public class InvocationMatcher implements DescribedInvocation, CapturesArgumensFromInvocation, Serializable { private static final long serialVersionUID = -3047126096857467610L; private final Invocation invocation; private final List<Matcher> matchers; public InvocationMatcher(Invocation invocation, List<Matcher> matchers) { this.invocation = invocation; if (matchers.isEmpty()) { this.matchers = ArgumentsProcessor.argumentsToMatchers(invocation.getArguments()); } else { this.matchers = matchers; } } public InvocationMatcher(Invocation invocation) { this(invocation, Collections.<Matcher>emptyList()); } public Method getMethod() { return invocation.getMethod(); } public Invocation getInvocation() { return this.invocation; } public List<Matcher> getMatchers() { return this.matchers; } public String toString() { return new PrintSettings().print(matchers, invocation); } public boolean matches(Invocation actual) { return invocation.getMock().equals(actual.getMock()) && hasSameMethod(actual) && new ArgumentsComparator().argumentsMatch(this, actual); } private boolean safelyArgumentsMatch(Object[] actualArgs) { try { return new ArgumentsComparator().argumentsMatch(this, actualArgs); } catch (Throwable t) { return false; } } /** * similar means the same method name, same mock, unverified * and: if arguments are the same cannot be overloaded */ public boolean hasSimilarMethod(Invocation candidate) { String wantedMethodName = getMethod().getName(); String currentMethodName = candidate.getMethod().getName(); final boolean methodNameEquals = wantedMethodName.equals(currentMethodName); final boolean isUnverified = !candidate.isVerified(); final boolean mockIsTheSame = getInvocation().getMock() == candidate.getMock(); final boolean methodEquals = hasSameMethod(candidate); if (!methodNameEquals || !isUnverified || !mockIsTheSame) { return false; } final boolean overloadedButSameArgs = !methodEquals && safelyArgumentsMatch(candidate.getArguments()); return !overloadedButSameArgs; } public boolean hasSameMethod(Invocation candidate) { //not using method.equals() for 1 good reason: //sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest Method m1 = invocation.getMethod(); Method m2 = candidate.getMethod(); if (m1.getName() != null && m1.getName().equals(m2.getName())) { /* Avoid unnecessary cloning */ Class[] params1 = m1.getParameterTypes(); Class[] params2 = m2.getParameterTypes(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) return false; } return true; } } return false; } public Location getLocation() { return invocation.getLocation(); } public void captureArgumentsFrom(Invocation invocation) { if (invocation.getMethod().isVarArgs()) { int indexOfVararg = invocation.getRawArguments().length - 1; for (int position = 0; position < indexOfVararg; position++) { Matcher m = matchers.get(position); if (m instanceof CapturesArguments) { ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class)); } } for (Matcher m : uniqueMatcherSet(indexOfVararg)) { if (m instanceof CapturesArguments) { Object rawArgument = invocation.getRawArguments()[indexOfVararg]; for (int i = 0; i < Array.getLength(rawArgument); i++) { ((CapturesArguments) m).captureFrom(Array.get(rawArgument, i)); } } } } else { for (int position = 0; position < matchers.size(); position++) { Matcher m = matchers.get(position); if (m instanceof CapturesArguments) { ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class)); } } } } private Set<Matcher> uniqueMatcherSet(int indexOfVararg) { HashSet<Matcher> set = new HashSet<Matcher>(); for (int position = indexOfVararg; position < matchers.size(); position++) { Matcher matcher = matchers.get(position); if(matcher instanceof MatcherDecorator) { set.add(((MatcherDecorator) matcher).getActualMatcher()); } else { set.add(matcher); } } return set; } public static List<InvocationMatcher> createFrom(List<Invocation> invocations) { LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>(); for (Invocation i : invocations) { out.add(new InvocationMatcher(i)); } return out; } }
package org.usfirst.frc157.ProtoBot2017.subsystems; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.RotatedRect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.opencv.utils.Converters; import edu.wpi.cscore.CvSink; import edu.wpi.cscore.CvSource; import edu.wpi.cscore.UsbCamera; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc157.ProtoBot2017.visionPipeLines.*; public class Vision extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. public static final int CAM_WIDTH = 640; public static final int CAM_HEIGHT = 480; private static final int CAM_EXPOSURE = 25; // B, G, R private static final Scalar RED = new Scalar(new double[] {0, 0, 255}); private static final Scalar YELLOW = new Scalar(new double[] {0, 255, 255}); private static final Scalar GREEN = new Scalar(new double[] {0, 255, 0}); private static final Scalar BLUE = new Scalar(new double[] {255, 0, 0}); private static final Scalar MAGENTA = new Scalar(new double[] {255, 0, 255}); private static final Scalar BLACK = new Scalar(new double[] {0, 0, 0}); private static final Scalar CYAN = new Scalar(new double[] {255, 255, 0}); private static final double BOILER_UPPER_TARGET_AR = 0; private static final double BOILER_LOWER_TARGET_AR = 0; private static final double GEAR_TARGET_AR = 0; private static final double ANGLE_TOLERANCE = 20; private static final int BOILER_NEAR_TARGET_CENTER_X = 320; private static final int BOILER_NEAR_TARGET_CENTER_Y = 120; private static final int BOILER_FAR_TARGET_CENTER_X = 320; private static final int BOILER_FAR_TARGET_CENTER_Y = 60; private static final int BOILER_TARGET_WIDTH = 120; private static final int BOILER_TARGET_HEIGHT = 40; private static final int GEAR_TARGET_CENTER_X = 440; private static final int GEAR_TARGET_CENTER_Y = 440; private static final int GEAR_TARGET_WIDTH = 80; private static final int GEAR_TARGET_HEIGHT = 80; private static final Rect NEAR_BOILER_TARGET = new Rect(BOILER_NEAR_TARGET_CENTER_X, BOILER_NEAR_TARGET_CENTER_Y, BOILER_TARGET_WIDTH, BOILER_TARGET_HEIGHT); private static final Rect FAR_BOILER_TARGET = new Rect(BOILER_FAR_TARGET_CENTER_X, BOILER_FAR_TARGET_CENTER_Y, BOILER_TARGET_WIDTH, BOILER_TARGET_HEIGHT); private static final Rect GEAR_TARGET = new Rect(new Point(GEAR_TARGET_CENTER_X - GEAR_TARGET_WIDTH/2, GEAR_TARGET_CENTER_Y - GEAR_TARGET_HEIGHT/2), new Point(GEAR_TARGET_CENTER_X + GEAR_TARGET_WIDTH/2, GEAR_TARGET_CENTER_Y + GEAR_TARGET_HEIGHT/2)); private Object pictureSync = new Object(); private boolean takePicture = false; int loopCount = 0; public enum BoilerRange { NEAR, FAR } public enum VisionMode { PASSTHROUGH, FIND_BOILER, FIND_GEAR } public enum TargetID { BOILER, GEAR, NONE } public enum CameraSelection { SHOT_CAMERA, GEAR_CAMERA } private Object VisionSetup = new Object(); private Object syncLoopCount = new Object(); private VisionMode visionMode = VisionMode.PASSTHROUGH; private BoilerRange boilerRange = BoilerRange.NEAR; private CameraSelection cameraSelection = CameraSelection.SHOT_CAMERA; public Rect getBoilerTargetRect(BoilerRange range) { switch(range) { case NEAR: return NEAR_BOILER_TARGET; case FAR: return FAR_BOILER_TARGET; default: return NEAR_BOILER_TARGET; } } public Point getBoilerTargetCenter(BoilerRange range) { switch(range) { case NEAR: return new Point(BOILER_NEAR_TARGET_CENTER_X, BOILER_NEAR_TARGET_CENTER_Y); case FAR: return new Point(BOILER_FAR_TARGET_CENTER_X, BOILER_FAR_TARGET_CENTER_Y); default: return new Point(BOILER_NEAR_TARGET_CENTER_X, BOILER_NEAR_TARGET_CENTER_Y); } } public Point getGearTargetCenter() { return new Point(GEAR_TARGET_CENTER_X, GEAR_TARGET_CENTER_Y); } public void setVisionMode(VisionMode newMode, BoilerRange newRange) { synchronized(VisionSetup) { visionMode = newMode; boilerRange = newRange; } SmartDashboard.putString("VisionMode", visionMode.name()); synchronized(syncLoopCount) { SmartDashboard.putDouble("VisionLoopCount", loopCount); } } public BoilerRange getBoilerTargetRange() { synchronized(VisionSetup) { return boilerRange; } } public VisionMode getVisionMode() { return visionMode; } public void StorePictures() { synchronized(pictureSync) { takePicture = true; } } public void setCamera(CameraSelection newCamera) { synchronized(VisionSetup) { cameraSelection = newCamera; } SmartDashboard.putString("Camera", cameraSelection.name()); synchronized(syncLoopCount) { SmartDashboard.putDouble("VisionLoopCount", loopCount); } } public CameraSelection getCamera() { return cameraSelection; } public class VisionTarget { public double x; public double y; public int loopCount; public boolean recentTarget; public TargetID target; public double crossTrack; public boolean inRange; VisionTarget(){ x = 0; y = 0; crossTrack = 0; inRange = false; loopCount = 0; recentTarget = false; target = TargetID.NONE; } } VisionTarget visionResults = new VisionTarget(); public VisionTarget getTarget() { VisionTarget result = new VisionTarget(); synchronized(visionResults) { result.x = visionResults.x; result.y = visionResults.y; result.crossTrack = visionResults.crossTrack; result.target = visionResults.target; result.loopCount = visionResults.loopCount; result.inRange = visionResults.inRange; result.recentTarget = false; } synchronized(syncLoopCount) { if (Math.abs(loopCount - result.loopCount) < 3) { result.recentTarget = true; } } return result; } boolean visionInitialized = false; Thread visionThread; private static final LocateBoiler findBoiler = new LocateBoiler(); private static final LocateGear findGear = new LocateGear(); private static final String SHOT_CAM_NAME = new String("cam1"); private static final String GEAR_CAM_NAME = new String("cam2"); //cam2 private UsbCamera shotCamera = new UsbCamera(SHOT_CAM_NAME, 0); // Shot Camera // private UsbCamera gearCamera = new UsbCamera(GEAR_CAM_NAME, 0); // Gear Camera private String NameBase = "NoTime"; public Vision() { setCamera(CameraSelection.SHOT_CAMERA); setVisionMode(VisionMode.FIND_GEAR, BoilerRange.NEAR); shotCamera.setResolution(CAM_WIDTH, CAM_HEIGHT); // gearCamera.setResolution(CAM_WIDTH, CAM_HEIGHT); InitializeVision(); System.out.println("Starting Vision"); } private void InitializeVision() { Point targetCenter = new Point(CAM_WIDTH/2, CAM_HEIGHT/2); NameBase = "/home/lvuser/images/"+ LocalDateTime.now() + "-"; if(visionInitialized == false) { visionInitialized = true; visionThread = new Thread(() -> { System.out.println("Starting Vision Thread"); shotCamera.setResolution(CAM_WIDTH, CAM_HEIGHT); shotCamera.setExposureManual(CAM_EXPOSURE); CvSink shotSink = null; try { // getting video will throw an exception if the camera has not been added System.out.println("Getting USB Cam - " + SHOT_CAM_NAME); shotSink = CameraServer.getInstance().getVideo(SHOT_CAM_NAME); } catch(Exception e) { // so if the camera has not been added, add it. System.out.println("Needed to add camera before using - " + SHOT_CAM_NAME + " all set"); CameraServer.getInstance().addCamera(shotCamera); shotSink = CameraServer.getInstance().getVideo(SHOT_CAM_NAME); } // Setup the Shot Cam // CameraServer.getInstance().addCamera(shotCamera); // shotCamera.setResolution(CAM_WIDTH, CAM_HEIGHT); // shotCamera.setExposureManual(CAM_EXPOSURE); // CvSink shotSink = CameraServer.getInstance().getVideo(SHOT_CAM_NAME); // Setup the Gear Cam // CameraServer.getInstance().addCamera(gearCamera); // gearCamera.setResolution(CAM_WIDTH, CAM_HEIGHT); // CvSink gearSink = CameraServer.getInstance().getVideo(GEAR_CAM_NAME); CvSink gearSink = shotSink; // set up a variable to hold the selected sink CvSink theSink = shotSink; // initialize to something, we will be set before use // Setup a CvSource. This will send images back to the Dashboard CvSource outputStream = CameraServer.getInstance().putVideo("Processed", CAM_WIDTH, CAM_HEIGHT); // Mats are very memory expensive. Lets reuse this Mat. Mat mat = new Mat(); // This cannot be 'true'. The program will never exit if it is. This // lets the robot stop this thread when restarting robot code or // deploying. // Beginning of vision thread loop while (!Thread.interrupted()) { boolean loopTakePicture = false; synchronized(syncLoopCount) { loopCount ++; } synchronized(pictureSync) { if(takePicture == true) { takePicture = false; loopTakePicture = true; } } // local copies of the vision mode and camera selection CameraSelection threadCameraSelection; VisionMode threadVisionMode; synchronized(VisionSetup) { threadCameraSelection = cameraSelection; threadVisionMode = visionMode; } // Tell the CvSink to grab a frame from the camera and put it // in the source mat. If there is an error notify the output. if(threadCameraSelection == CameraSelection.SHOT_CAMERA) { SmartDashboard.putString("Camera In Use", "Shot"); theSink = shotSink; } else { SmartDashboard.putString("Camera In Use", "Gear"); theSink = gearSink; } if (theSink.grabFrame(mat) == 0) { // Send the output the error. outputStream.notifyError(theSink.getError()); // skip the rest of the current iteration continue; } if(loopTakePicture == true) { Imgcodecs.imwrite(NameBase + loopCount + "_base.jpg", mat); System.out.println("Saved Base Image"); } // LOOK FOR BOILER TARGET // BOILER BOILER BOILER BOILER BOILER BOILER BOILER BOILER BOILER BOILER BOILER BOILER if(threadVisionMode == VisionMode.FIND_BOILER) { targetCenter.x= CAM_WIDTH/2; targetCenter.y= CAM_HEIGHT/2; findBoiler.process(mat); ArrayList<MatOfPoint> targetList = findBoiler.convexHullsOutput(); drawTargetCrosshair(mat, getBoilerTargetRect(boilerRange), Vision.MAGENTA); if(targetList.isEmpty()) { //drawBoilerTargetReticle(mat, targetCenter, CAM_HEIGHT, CAM_WIDTH, Vision.RED); } else { // Show the detected contours Imgproc.drawContours(mat, targetList, -1, Vision.BLACK, 1); ArrayList<RotatedRect> candidateList = new ArrayList<RotatedRect>(); // Preprocess the contours targetList.forEach(contour -> { // convert contour to rect compatible change MatOfPoint2f contourMat = new MatOfPoint2f(); contour.convertTo(contourMat, CvType.CV_32F); candidateList.add(Imgproc.minAreaRect(contourMat)); }); // Walk the candidate rectangles and sort out if they are nice CandidateLoop: for(RotatedRect candidate : candidateList) { // candidateList.forEach(candidate -> { // show candidate target aligined rectangle info drawRotRectangle(mat, candidate, Vision.MAGENTA); // figure out which target is the Boiler Upper Stripe double aspectRatio = candidate.size.width / candidate.size.height; if(aspectRatio < 1) {aspectRatio = 1/aspectRatio;} double fixedCAngle = 0; if(candidate.size.width < candidate.size.height){ fixedCAngle = (90 - candidate.angle) - 180; }else{ fixedCAngle = 0 - candidate.angle; } if( ((2 < aspectRatio) && (aspectRatio < 5)) && ((-ANGLE_TOLERANCE < fixedCAngle) && (fixedCAngle < ANGLE_TOLERANCE)) ) { // drawGearTargetReticle(mat, candidate.center, candidate.size.height, candidate.size.width, Vision.BLUE); // look at the targets and see if any are a good seconodary verification for the candidate for(RotatedRect secondary : candidateList) { // candidateList.forEach(secondary -> { // Check Aspect Ratio & Orientation double aspectRatioSecondary = secondary.size.width / secondary.size.height; if(aspectRatioSecondary < 1) {aspectRatioSecondary = 1/aspectRatioSecondary;} double fixedSAngle = 0; if(secondary.size.width < secondary.size.height){ fixedSAngle = (90 - secondary.angle) - 180; }else{ fixedSAngle = -secondary.angle; } // basic OKness of secondary if( ((3 < aspectRatioSecondary) && (aspectRatioSecondary < 12)) && ((-ANGLE_TOLERANCE < fixedSAngle) && (fixedSAngle < ANGLE_TOLERANCE)) ) { // draw a yellow box drawBoilerTargetReticle(mat, candidate.center, candidate.size.height, candidate.size.width, Vision.YELLOW); double candidateHeight = (candidate.size.height < candidate.size.width) ? candidate.size.height : candidate.size.width; double candidateWidth = (candidate.size.height < candidate.size.width) ? candidate.size.width : candidate.size.height; // OKness of secondary with respect to target if(((candidate.center.y - secondary.center.y) < (candidateHeight * 2.5)) && (secondary.center.x != candidate.center.x) && (secondary.center.y != candidate.center.y) && (candidate.center.x - secondary.center.x) < (candidateWidth * 1.5) ) { drawCandidateCrosshair(mat, candidate, Vision.YELLOW); Imgproc.line(mat, candidate.center, secondary.center, Vision.YELLOW, 2); // output target info to smart dashboard SmartDashboard.putDouble("TargetWidth", candidate.size.width); SmartDashboard.putDouble("TargetHeight", candidate.size.height); SmartDashboard.putDouble("TargetX", candidate.center.x); SmartDashboard.putDouble("TargetY", candidate.center.y); // save target info // x,y,loopCount synchronized(visionResults) { visionResults.x = candidate.center.x; visionResults.y = candidate.center.y; visionResults.inRange = true; visionResults.crossTrack = 0; visionResults.loopCount = loopCount; visionResults.target = TargetID.BOILER; } if(takePicture == true) { Imgcodecs.imwrite(NameBase + loopCount + "_boiler.jpg", mat); System.out.println("Saved Boiler Image"); } break CandidateLoop; } } } } // drawBoilerTargetReticle(mat, candidate.center, candidate.size.height, candidate.size.width, Vision.YELLOW); if(takePicture == true) { Imgcodecs.imwrite(NameBase + loopCount + "_boiler_final.jpg", mat); System.out.println("Saved Boiler final Image"); } } } // drawBoilerTargetReticle(mat, targetCenter, CAM_HEIGHT/3, CAM_WIDTH/3, Vision.MAGENTA); } // LOOK FOR GEAR TARGET // GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR GEAR else if(threadVisionMode == VisionMode.FIND_GEAR) { targetCenter.x= CAM_WIDTH/2; targetCenter.y= CAM_HEIGHT/2; findGear.process(mat); ArrayList<MatOfPoint> targetList = findGear.convexHullsOutput(); drawTargetCrosshair(mat, GEAR_TARGET, Vision.CYAN); if(targetList.isEmpty()) { // drawGearTargetReticle(mat, targetCenter, CAM_HEIGHT, CAM_WIDTH, Vision.RED); } else { boolean inRange = false; // Show the detected contours Imgproc.drawContours(mat, targetList, -1, Vision.BLACK, 1); ArrayList<RotatedRect> candidateList = new ArrayList<RotatedRect>(); // Preprocess the contours targetList.forEach(contour -> { // convert contour to rect compatible change MatOfPoint2f contourMat = new MatOfPoint2f(); contour.convertTo(contourMat, CvType.CV_32F); candidateList.add(Imgproc.minAreaRect(contourMat)); }); // Walk the candidate rectangles and sort out if they are nice CandidateLoop: for(RotatedRect candidate : candidateList) { // candidateList.forEach(candidate -> { // show candidate target aligined rectangle info drawRotRectangle(mat, candidate, Vision.CYAN); // figure out which target is the Boiler Upper Stripe double aspectRatio = candidate.size.width / candidate.size.height; if(aspectRatio < 1) {aspectRatio = 1/aspectRatio;} double fixedCAngle = 0; if(candidate.size.width < candidate.size.height){ fixedCAngle = (90 - candidate.angle); }else{ fixedCAngle = 0 - candidate.angle; } SmartDashboard.putDouble("TargetAngle", fixedCAngle); if( ((1 < aspectRatio) && (aspectRatio < 3)) && (((90-ANGLE_TOLERANCE) < fixedCAngle) && (fixedCAngle < (90+ANGLE_TOLERANCE))) ) { // drawGearTargetReticle(mat, candidate.center, candidate.size.height, candidate.size.width, Vision.BLUE); for(RotatedRect secondary : candidateList) { // candidateList.forEach(secondary -> { // Check Aspect Ratio & Orientation double aspectRatioSecondary = secondary.size.width / secondary.size.height; if(aspectRatioSecondary < 1) {aspectRatioSecondary = 1/aspectRatioSecondary;} double fixedSAngle = 0; if(secondary.size.width < secondary.size.height){ fixedSAngle = (90 - secondary.angle); }else{ fixedSAngle = 0 - secondary.angle; } // basic OKness of secondary if( //((1 < aspectRatioSecondary) && (aspectRatioSecondary < 4)) (((90-ANGLE_TOLERANCE) < fixedSAngle) && (fixedSAngle < (90+ANGLE_TOLERANCE))) ) { // draw a yellow box drawGearTargetReticle(mat, candidate.center, candidate.size.width, candidate.size.height, Vision.YELLOW); double candidateHeight = (candidate.size.height > candidate.size.width) ? candidate.size.height : candidate.size.width; double candidateWidth = (candidate.size.height > candidate.size.width) ? candidate.size.width : candidate.size.height; // OKness of secondary with respect to target if(((candidate.center.x - secondary.center.x) < (candidateWidth * 4)) && (secondary.center.x != candidate.center.x) && (Math.abs(candidate.center.y - secondary.center.y) < (Math.max(candidate.size.height, candidate.size.width) * 0.5)) ) { drawCandidateCrosshair(mat, candidate, secondary, Vision.YELLOW); // compute crosstrack & apect double secondaryHeight = (secondary.size.height > secondary.size.width) ? secondary.size.height : secondary.size.width; double secondaryWidth = (secondary.size.height > secondary.size.width) ? secondary.size.width : secondary.size.height; double hheight = Math.max(candidateHeight, secondaryHeight)/2; double left = Math.min(candidate.center.x - candidateWidth/2, secondary.center.x - secondaryWidth/2); double right = Math.max(candidate.center.x + candidateWidth/2, secondary.center.x + secondaryWidth/2); double aspect = (right-left)/hheight; double crossTrack = candidateHeight - secondaryHeight; if(candidate.center.x > secondary.center.x) { crossTrack = -crossTrack; } if(aspect > 3.8) { crossTrack = 0; } if(Math.max(candidateHeight, secondaryHeight) > 25) { inRange = true; } Imgproc.line(mat, candidate.center, secondary.center, Vision.YELLOW, 2); // output target info to smart dashboard SmartDashboard.putDouble("TargetWidth", candidateWidth); SmartDashboard.putDouble("TargetHeight", candidateHeight); SmartDashboard.putDouble("ConfirmWidth", secondaryWidth); SmartDashboard.putDouble("ConfirmHeight", secondaryHeight); SmartDashboard.putDouble("TargetX", candidate.center.x); SmartDashboard.putDouble("TargetY", candidate.center.y); SmartDashboard.putDouble("GTargetAspect", aspect); SmartDashboard.putDouble("GTargetCross", crossTrack); // save target info // x,y,loopCount synchronized(visionResults) { visionResults.x = candidate.center.x; visionResults.y = candidate.center.y; visionResults.crossTrack = crossTrack; visionResults.loopCount = loopCount; visionResults.target = TargetID.GEAR; visionResults.inRange = inRange; } if(takePicture == true) { Imgcodecs.imwrite(NameBase + loopCount + "_gear.jpg", mat); System.out.println("Saved Gear Image"); } break CandidateLoop; } } } } } if(takePicture == true) { Imgcodecs.imwrite(NameBase + loopCount + "_gear_final.jpg", mat); System.out.println("Saved Gear final Image"); } } } // PASSTHROUGH // PASSTHROUGH PASSTHROUGH PASSTHROUGH PASSTHROUGH PASSTHROUGH PASSTHROUGH PASSTHROUGH else // VisionMode.PASSTHROUGH { // do no image processing, // Circular Target, Centered in Blue targetCenter.x= CAM_WIDTH/2; targetCenter.y= CAM_HEIGHT/2; if(takePicture == true) { Imgcodecs.imwrite(NameBase + loopCount + "_passthru.jpg", mat); System.out.println("Saved Passthrough Image"); } drawPassthroughTargetReticle(mat, targetCenter, CAM_HEIGHT/3, CAM_WIDTH/3, Vision.BLUE); } // Put a rectangle on the image // // TODO - Put Rectangle on TARGET // Imgproc.rectangle(mat, new Point(100, 100), new Point(400, 400), // targetColor, 5); // Give the output stream a new image to display outputStream.putFrame(mat); if(loopTakePicture == true) { loopTakePicture = false; Imgcodecs.imwrite(NameBase + loopCount + "_passthru_final.jpg", mat); } } }); visionThread.setDaemon(true); visionThread.start(); } System.out.println("Vision Initialized & Started"); } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } private void drawRotRectangle(Mat mat, RotatedRect rect, Scalar color) { double width = (rect.size.width > rect.size.height) ? rect.size.width :rect.size.height; double height = (rect.size.width > rect.size.height) ? rect.size.height : rect.size.width; double hheight = height/2; double hwidth = width/2; // Vertical Extent Imgproc.line(mat, new Point(rect.center.x, rect.center.y - hheight), new Point(rect.center.x, rect.center.y + hheight), color, 2); // Horizontal Extent Imgproc.line(mat, new Point(rect.center.x - hwidth, rect.center.y), new Point(rect.center.x + hwidth, rect.center.y), color, 2); } private void drawGearTargetReticle(Mat mat, Point center, double in_height, double in_width, Scalar color) { double width = (in_width < in_height) ? in_width :in_height; double height = (in_width < in_height) ? in_height : in_width; double hheight = height/2; double hwidth = width/2; Imgproc.rectangle(mat, new Point(center.x-hwidth, center.y+hheight), new Point(center.x+hwidth, center.y-hheight), color, 5); Imgproc.line(mat, new Point(center.x-hwidth, center.y+hheight), new Point(center.x+hwidth, center.y-hheight), color, 3); Imgproc.line(mat, new Point(center.x+hwidth, center.y+hheight), new Point(center.x-hwidth, center.y-hheight), color, 3); } private void drawBoilerTargetReticle(Mat mat, Point center, double in_height, double in_width, Scalar color) { double width = (in_width > in_height) ? in_width :in_height; double height = (in_width > in_height) ? in_height : in_width; double hheight = height/2; double hwidth = width/2; Imgproc.rectangle(mat, new Point(center.x-hwidth, center.y+hheight), new Point(center.x+hwidth, center.y-hheight), color, 2); Imgproc.line(mat, new Point(center.x, center.y), new Point(center.x+hwidth, center.y-hheight), color, 2); Imgproc.line(mat, new Point(center.x, center.y), new Point(center.x-hwidth, center.y-hheight), color, 2); } private void drawPassthroughTargetReticle(Mat mat, Point center, double height, double width, Scalar color) { double hheight = height/2; double hwidth = width/2; int targetRadius = (int)(hheight/4); Imgproc.circle(mat, new Point(center.x, center.y), targetRadius, color); // Imgproc.rectangle(mat, new Point(center.x-hwidth, center.y+hheight), new Point(center.x+hwidth, center.y-hheight), // color, 10); } private void drawTargetCrosshair(Mat mat, Rect target, Scalar targetColor) { Imgproc.line(mat, new Point(target.x, 0), new Point(target.x, CAM_HEIGHT), targetColor, 3); Imgproc.line(mat, new Point(0, target.y ), new Point(CAM_WIDTH, target.y), targetColor, 3); // // Draw Target Lines // double hheight = target.height/2; // double hwidth = target.width/2; // if(hheight > hwidth) // hheight = target.width/2; // hwidth = target.height/2; // // Target Lines // // vertical lines // // left // Imgproc.line(mat, new Point(target.x - hwidth, 0), // new Point(target.x - hwidth, CAM_HEIGHT), // targetColor, 3); // // right // Imgproc.line(mat, new Point(target.x + hwidth, 0), // new Point(target.x + hwidth, CAM_HEIGHT), // targetColor, 3); // // horizontal lines // // upper // Imgproc.line(mat, new Point(0, target.y - hheight), // new Point(CAM_WIDTH, target.y - hheight), // targetColor, 3); // //lower // Imgproc.line(mat, new Point(0, target.y + hheight), // new Point(CAM_WIDTH, target.y + hheight), // targetColor, 3); } private void drawCandidateCrosshair(Mat mat, RotatedRect candidate, Scalar candidateColor) { Imgproc.line(mat, new Point(0, candidate.center.y), new Point(CAM_WIDTH, candidate.center.y), candidateColor, 2); Imgproc.line(mat, new Point(candidate.center.x, 0), new Point(candidate.center.x, CAM_HEIGHT), candidateColor, 2); // // Draw Candidate Lines // double hheight = candidate.size.height/2; // double hwidth = candidate.size.width/2; // if(hheight > hwidth) // hheight = candidate.size.width/2; // hwidth = candidate.size.height/2; // // Target Lines // // vertical lines // // left // Imgproc.line(mat, new Point(candidate.center.x - hwidth, 0), // new Point(candidate.center.x - hwidth, CAM_HEIGHT), // candidateColor, 2); // // right // Imgproc.line(mat, new Point(candidate.center.x + hwidth, 0), // new Point(candidate.center.x + hwidth, CAM_HEIGHT), // candidateColor, 2); // // horizontal lines // // upper // Imgproc.line(mat, new Point(0, candidate.center.y - hheight), // new Point(CAM_WIDTH, candidate.center.y - hheight), // candidateColor, 2); // //lower // Imgproc.line(mat, new Point(0, candidate.center.y + hheight), // new Point(CAM_WIDTH, candidate.center.y + hheight), // candidateColor, 2); } private void drawCandidateCrosshair(Mat mat, RotatedRect candidate, RotatedRect secondary, Scalar candidateColor) { // Draw Candidate Lines double candidateHeight = Math.max(candidate.size.width, candidate.size.height); double secondaryHeight = Math.max(secondary.size.width, secondary.size.height); double hheight = Math.max(candidateHeight, secondaryHeight)/2; double candidateWidth = Math.min(candidate.size.width, candidate.size.height); double secondaryWidth = Math.min(secondary.size.width, secondary.size.height); double left = Math.min(candidate.center.x - candidateWidth/2, secondary.center.x - secondaryWidth/2); double right = Math.max(candidate.center.x + candidateWidth/2, secondary.center.x + secondaryWidth/2); double hwidth = Math.abs(right-left)/2; Point center = new Point((candidate.center.x + secondary.center.x)/2,(candidate.center.y + secondary.center.y)/2); // Target Lines // vertical lines // left // Imgproc.line(mat, new Point(center.x - hwidth, 0), // new Point(center.x - hwidth, CAM_HEIGHT), // candidateColor, 2); // // right // Imgproc.line(mat, new Point(center.x + hwidth, 0), // new Point(center.x + hwidth, CAM_HEIGHT), // candidateColor, 2); // // horizontal lines // // upper // Imgproc.line(mat, new Point(0, center.y - hheight), // new Point(CAM_WIDTH, center.y - hheight), // candidateColor, 2); // //lower // Imgproc.line(mat, new Point(0, center.y + hheight), // new Point(CAM_WIDTH, center.y + hheight), // candidateColor, 2); Imgproc.line(mat, new Point(0, center.y), new Point(CAM_WIDTH, center.y), candidateColor, 2); Imgproc.line(mat, new Point(center.x, 0), new Point(center.x, CAM_HEIGHT), candidateColor, 2); } private double scoreBoilerTarget(MatOfPoint target) { double aspectRatio = target.height()/target.width(); return 1; } }
package parachute.scripts.pwoodcutter.strategies; import org.parabot.environment.api.utils.Time; import org.parabot.environment.scripts.framework.Strategy; import org.rev317.min.api.methods.GroundItems; import org.rev317.min.api.methods.Inventory; import org.rev317.min.api.methods.Players; import org.rev317.min.api.methods.SceneObjects; import org.rev317.min.api.wrappers.GroundItem; import org.rev317.min.api.wrappers.SceneObject; import parachute.scripts.pwoodcutter.main.Data; public class CutEvent implements Strategy { GroundItem[] nests; SceneObject[] chosen; @Override public boolean activate() { nests = GroundItems.getNearest(Data.nestids); chosen = SceneObjects.getNearest(Data.idchosen); return chosen.length > 0 && chosen[0] != null && !Inventory.isFull() && nestTrue() && Data.chosenRegion.isInRegion(); } @Override public void execute() { SceneObject[] chosen = SceneObjects.getNearest(Data.idchosen); if (chosen[0] != null) { if (chosen[0].getLocation().distanceTo() < 20) { chosen[0].interact(1); Time.sleep(2000); } while (Players.getMyPlayer().getAnimation() != -1 && !Inventory.isFull() && nestTrue() && chosen[0] != null && logErbij()) { nests = GroundItems.getNearest(Data.nestids); Time.sleep(10); } } } public boolean logErbij(){ int Inventory1 = Inventory.getCount(); Time.sleep(1500); int Inventory2 = Inventory.getCount(); return Inventory1 < Inventory2; } public boolean nestTrue(){ if(Data.Method == "Banking"){ if(nests.length <= 0){ return true; } } if(Data.Method == "Empty"){ return true; } return false; } }
package pl.polidea.treeview; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListAdapter; /** * Adapter used to feed the table view. * * @param <T> * class for ID of the tree */ public abstract class AbstractTreeViewAdapterSimple<T> extends BaseAdapter implements ListAdapter { private final TreeStateManager<T> treeStateManager; private final int numberOfLevels; private final LayoutInflater layoutInflater; private int indentWidth = 0; private final OnClickListener clickListener = new OnClickListener() { @Override public void onClick(final View v) { @SuppressWarnings("unchecked") final T id = (T) v.getTag(); expandCollapse(id); } }; private boolean collapsible; private final Activity activity; public Activity getActivity() { return activity; } protected TreeStateManager<T> getManager() { return treeStateManager; } protected void expandCollapse(final T id) { if(collapsible){ final TreeNodeInfo<T> info = treeStateManager.getNodeInfo(id); if (!info.isWithChildren()) { // ignore - no default action return; } if (info.isExpanded()) { treeStateManager.collapseChildren(id); } else { treeStateManager.expandDirectChildren(id); } } } public AbstractTreeViewAdapterSimple(final Activity activity, final TreeStateManager<T> treeStateManager, final int numberOfLevels) { this.activity = activity; this.treeStateManager = treeStateManager; this.layoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.numberOfLevels = numberOfLevels; } @Override public void registerDataSetObserver(final DataSetObserver observer) { treeStateManager.registerDataSetObserver(observer); } @Override public void unregisterDataSetObserver(final DataSetObserver observer) { treeStateManager.unregisterDataSetObserver(observer); } @Override public int getCount() { return treeStateManager.getVisibleCount(); } @Override public Object getItem(final int position) { return getTreeId(position); } public T getTreeId(final int position) { return treeStateManager.getVisibleList().get(position); } public TreeNodeInfo<T> getTreeNodeInfo(final int position) { return treeStateManager.getNodeInfo(getTreeId(position)); } @Override public boolean hasStableIds() { // NOPMD return true; } @Override public int getItemViewType(final int position) { return getTreeNodeInfo(position).getLevel(); } @Override public int getViewTypeCount() { return numberOfLevels; } @Override public boolean isEmpty() { return getCount() == 0; } @Override public boolean areAllItemsEnabled() { // NOPMD return true; } @Override public boolean isEnabled(final int position) { // NOPMD return true; } protected int getTreeListItemWrapperId() { return R.layout.tree_list_item_wrapper_bare; } @Override public final View getView(final int position, final View convertView, final ViewGroup parent) { final TreeNodeInfo<T> nodeInfo = getTreeNodeInfo(position); if (convertView == null) { final LinearLayout layout = (LinearLayout) layoutInflater.inflate( getTreeListItemWrapperId(), null); return populateTreeItem(layout, getNewChildView(nodeInfo), nodeInfo, true); } else { final LinearLayout linear = (LinearLayout) convertView; final FrameLayout frameLayout = (FrameLayout) linear .findViewById(R.id.treeview_list_item_frame); final View childView = frameLayout.getChildAt(0); updateView(childView, nodeInfo); return populateTreeItem(linear, childView, nodeInfo, false); } } /** * Called when new view is to be created. * * @param treeNodeInfo * node info * @return view that should be displayed as tree content */ public abstract View getNewChildView(TreeNodeInfo<T> treeNodeInfo); /** * Called when new view is going to be reused. You should update the view * and fill it in with the data required to display the new information. You * can also create a new view, which will mean that the old view will not be * reused. * * @param view * view that should be updated with the new values * @param treeNodeInfo * node info used to populate the view * @return view to used as row indented content */ public abstract View updateView(View view, TreeNodeInfo<T> treeNodeInfo); protected Drawable getBackgroundDrawable(TreeNodeInfo<T> nodeInfo){ return null; } protected int getBackgroundResourceId(TreeNodeInfo<T> nodeInfo){ return 0; } @SuppressWarnings("deprecation") @SuppressLint("NewApi") public final LinearLayout populateTreeItem(final LinearLayout layout, final View childView, final TreeNodeInfo<T> nodeInfo, final boolean newChildView) { if(getBackgroundDrawable(nodeInfo) != null){ int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { layout.setBackgroundDrawable(getBackgroundDrawable(nodeInfo)); } else { layout.setBackground(getBackgroundDrawable(nodeInfo)); } } else if (getBackgroundResourceId(nodeInfo) != 0){ layout.setBackgroundResource(getBackgroundResourceId(nodeInfo)); } layout.setPadding(calculateIndentation(nodeInfo), 0, 0, 0); layout.setTag(nodeInfo.getId()); //TODO is this used? final FrameLayout frameLayout = (FrameLayout) layout .findViewById(R.id.treeview_list_item_frame); if (newChildView) { frameLayout.addView(childView); } frameLayout.setTag(nodeInfo.getId()); //TODO is this used? return layout; } protected int calculateIndentation(final TreeNodeInfo<T> nodeInfo) { int width = getIndentWidth() * nodeInfo.getLevel(); return width; } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; } public void refresh() { treeStateManager.refresh(); } private int getIndentWidth() { return indentWidth; } @SuppressWarnings("unchecked") public void handleItemClick(final View view, final Object id) { expandCollapse((T) id); } }
package org.sirix.access; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sirix.JsonTestHelper; import org.sirix.exception.SirixException; public final class JsonDocumentTest { @Before public void setUp() throws SirixException { JsonTestHelper.deleteEverything(); } @After public void tearDown() throws SirixException { JsonTestHelper.closeEverything(); } @Test public void testJsonDocument() { // JsonTestHelper.createTestDocument(); } }
package ch.elexis.core.ui.preferences; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import ch.elexis.admin.AccessControlDefaults; import ch.elexis.core.constants.Preferences; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.constants.ExtensionPointConstantsData; import ch.elexis.core.data.util.Extensions; import ch.elexis.core.data.util.MultiplikatorList; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.constants.ExtensionPointConstantsUi; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.preferences.inputs.MultiplikatorEditor; import ch.elexis.core.ui.util.ListDisplay; import ch.elexis.core.ui.util.Log; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.data.Fall; import ch.elexis.data.PersistentObject; import ch.rgw.tools.JdbcLink; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; public class Leistungscodes extends PreferencePage implements IWorkbenchPreferencePage { private static final String DEFINITIONSDELIMITER = ";"; //$NON-NLS-1$ private static final String ARGUMENTSSDELIMITER = ":"; //$NON-NLS-1$ private static final String ITEMDELIMITER = "\t"; //$NON-NLS-1$ private static final String FOURLINESPLACEHOLDER = "\n\n\n\nd"; //$NON-NLS-1$ List<IConfigurationElement> lo = Extensions .getExtensions(ExtensionPointConstantsData.RECHNUNGS_MANAGER); //$NON-NLS-1$ List<IConfigurationElement> ll = Extensions .getExtensions(ExtensionPointConstantsUi.VERRECHNUNGSCODE); //$NON-NLS-1$ String[] systeme = CoreHub.globalCfg.nodes(Preferences.LEISTUNGSCODES_CFG_KEY); Table table; String[] tableCols = { Messages.Leistungscodes_nameOfBillingSystem, Messages.Leistungscodes_billingSystem, Messages.Leistungscodes_defaultOutput, Messages.Leistungscodes_multiplier }; int[] tableWidths = { 60, 120, 120, 70 }; Button bCheckZero; Button bStrictCheck; @Override protected Control createContents(final Composite parent){ Composite ret = new Composite(parent, SWT.NONE); ret.setLayout(new GridLayout(2, false)); Label l1 = new Label(ret, SWT.NONE); l1.setText(Messages.Leistungscodes_billingSystems); l1.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); SWTHelper.createHyperlink(ret, Messages.Leistungscodes_new, new HyperlinkAdapter() { @Override public void linkActivated(final HyperlinkEvent e){ AbrechnungsTypDialog at = new AbrechnungsTypDialog(getShell(), null); if (at.open() == Dialog.OK) { String[] result = at.getResult(); String key = Preferences.LEISTUNGSCODES_CFG_KEY + "/" + result[0]; //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/name", result[0]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/leistungscodes", result[1]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/standardausgabe", result[2]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/bedingungen", result[3]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/fakultativ", result[4]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/unused", result[5]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/disabled", result[6]); //$NON-NLS-1$ systeme = CoreHub.globalCfg.nodes(Preferences.LEISTUNGSCODES_CFG_KEY); reload(); } } }); SWTHelper.createHyperlink(ret, Messages.Leistungscodes_delete, new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e){ TableItem sel = table.getSelection()[0]; String bName = sel.getText(0); if (SWTHelper.askYesNo( MessageFormat.format(Messages.Leistungscodes_reallyDelete, bName), Messages.Leistungscodes_notUndoable)) { Fall.removeAbrechnungssystem(bName); systeme = CoreHub.globalCfg.nodes(Preferences.LEISTUNGSCODES_CFG_KEY); reload(); } } }); table = new Table(ret, SWT.FULL_SELECTION | SWT.SINGLE); for (int i = 0; i < tableCols.length; i++) { TableColumn tc = new TableColumn(table, SWT.NONE); tc.setText(tableCols[i]); tc.setWidth(tableWidths[i]); } table.setLinesVisible(true); table.setHeaderVisible(true); table.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(final MouseEvent e){ int idx = table.getSelectionIndex(); if (idx != -1) { TableItem sel = table.getItem(idx); String ssel = sel.getText(0); for (String s1 : systeme) { if (s1.equals(ssel)) { String[] pre = new String[7]; pre[0] = s1; pre[1] = Fall.getCodeSystem(s1); pre[2] = Fall.getDefaultPrintSystem(s1); pre[3] = Fall.getRequirements(s1); pre[4] = Fall.getOptionals(s1); pre[5] = Fall.getUnused(s1); pre[6] = "" + isBillingSystemDisabled(s1); //$NON-NLS-1$ AbrechnungsTypDialog at = new AbrechnungsTypDialog(getShell(), pre); if (at.open() == Dialog.OK) { String[] result = at.getResult(); String key = Preferences.LEISTUNGSCODES_CFG_KEY + "/" + result[0]; //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/name", result[0]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/leistungscodes", result[1]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/standardausgabe", result[2]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/bedingungen", result[3]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/fakultativ", result[4]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/unused", result[5]); //$NON-NLS-1$ CoreHub.globalCfg.set(key + "/disabled", result[6]); //$NON-NLS-1$ systeme = CoreHub.globalCfg.nodes(Preferences.LEISTUNGSCODES_CFG_KEY); reload(); } } } } } }); table.setLayoutData(SWTHelper.getFillGridData(2, true, 1, true)); bCheckZero = new Button(ret, SWT.CHECK); bCheckZero.setText(Messages.Leistungscodes_checkZero); bCheckZero.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ CoreHub.userCfg.set(Preferences.LEISTUNGSCODES_BILLING_ZERO_CHECK, bCheckZero.getSelection()); } }); bCheckZero.setSelection(CoreHub.userCfg.get(Preferences.LEISTUNGSCODES_BILLING_ZERO_CHECK, false)); bCheckZero.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); bStrictCheck = new Button(ret, SWT.CHECK); bStrictCheck.setText(Messages.Leistungscodes_strictValidityCheck); bStrictCheck.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ CoreHub.userCfg.set(Preferences.LEISTUNGSCODES_BILLING_STRICT, bStrictCheck.getSelection()); } }); bStrictCheck.setSelection(CoreHub.userCfg.get(Preferences.LEISTUNGSCODES_BILLING_STRICT, true)); bStrictCheck.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); final Button bOptify = new Button(ret, SWT.CHECK); bOptify.setText(Messages.Leistungscodes_checkPositions); bOptify.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ CoreHub.userCfg.set(Preferences.LEISTUNGSCODES_OPTIFY, bOptify.getSelection()); } }); bOptify.setSelection(CoreHub.userCfg.get(Preferences.LEISTUNGSCODES_OPTIFY, true)); bOptify.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); final Button bOptifyXray = new Button(ret, SWT.CHECK); bOptifyXray.setText(Messages.Leistungscodes_optifyXrayPositions); bOptifyXray.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ CoreHub.userCfg.set(Preferences.LEISTUNGSCODES_OPTIFY_XRAY, bOptifyXray.getSelection()); } }); bOptifyXray.setSelection(CoreHub.userCfg.get(Preferences.LEISTUNGSCODES_OPTIFY_XRAY, true)); bOptifyXray.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); final Button bObligation = new Button(ret, SWT.CHECK); bObligation.setText(Messages.Leistungscodes_separateObligations); bObligation.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ CoreHub.userCfg.set(Preferences.LEISTUNGSCODES_OBLIGATION, bObligation.getSelection()); } }); bObligation.setSelection(CoreHub.userCfg.get(Preferences.LEISTUNGSCODES_OBLIGATION, false)); bObligation.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); final Button bRemoveOpenReminders = new Button(ret, SWT.CHECK); bRemoveOpenReminders.setText(Messages.Leistungscodes_removeOpenReminders); bRemoveOpenReminders.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ CoreHub.globalCfg.set(Preferences.RNN_REMOVE_OPEN_REMINDER, bRemoveOpenReminders.getSelection()); } }); bRemoveOpenReminders .setSelection(CoreHub.globalCfg.get(Preferences.RNN_REMOVE_OPEN_REMINDER, false)); bRemoveOpenReminders.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); reload(); return ret; } /** * returns true if the billing system specified by the param is DISabled else returns false * * @param billingSystem * String, the name of the billing system to be tested */ public static boolean isBillingSystemDisabled(final String billingSystem){ String ret = CoreHub.globalCfg.get(Preferences.LEISTUNGSCODES_CFG_KEY + "/" //$NON-NLS-1$ + billingSystem + "/disabled", "0"); //$NON-NLS-1$ //$NON-NLS-2$ if (ret.equalsIgnoreCase("0")) //$NON-NLS-1$ return false; else return true; } /** * (re)build the table for the billing systems, populate the table with items */ public void reload(){ table.removeAll(); if (systeme != null) { for (String s : systeme) { String cfgkey = Preferences.LEISTUNGSCODES_CFG_KEY + "/" + s + "/"; //$NON-NLS-1$ //$NON-NLS-2$ TableItem it = new TableItem(table, SWT.NONE); String name = CoreHub.globalCfg.get(cfgkey + "name", "default"); //$NON-NLS-1$ //$NON-NLS-2$ it.setText(0, name); it.setText(1, CoreHub.globalCfg.get(cfgkey + "leistungscodes", "?")); //$NON-NLS-1$ //$NON-NLS-2$ it.setText(2, CoreHub.globalCfg.get(cfgkey + "standardausgabe", "?")); //$NON-NLS-1$ //$NON-NLS-2$ StringBuilder sql = new StringBuilder(); TimeTool actdat = new TimeTool(); MultiplikatorList multis = new MultiplikatorList("VK_PREISE", name); //$NON-NLS-1$ String tp = Double.toString(multis.getMultiplikator(actdat)); if (StringTool.isNothing(tp)) { if (CoreHub.getSystemLogLevel() > Log.INFOS) { SWTHelper.alert(Messages.Leistungscodes_didNotFindMulitplier, Messages.Leistungscodes_query + sql.toString()); } tp = "1.0"; //$NON-NLS-1$ } it.setText(3, tp); } } } public void init(final IWorkbench workbench){ } class AbrechnungsTypDialog_InputDialog extends Dialog { String cDialogTitle; String cDialogMessage; ListDisplay<String>[] cNoDuplicatesList; Text tName = null; String cInitialValue; Text tTextEditor = null; boolean cHasTextEditor; String cTextEditorValue; boolean cTextNeeded; Button chNumeric = null; boolean cHasNumericCheckbox; boolean cIsNumericChecked; Button chMultiline = null; boolean cHasStyledCheckbox; boolean cIsStyledChecked; Button chStyled = null; boolean cHasMultilineCheckbox; boolean cIsMultilineChecked; String[] result = null; Combo changeCombo; String[] cChangeTypeItems; String cCurrentFieldType; String cBilllingSystemDisabled; /** * * @param parentShell * Shell, the parentShell... * @param dialogTitle * String, the text displayed in the window bar * @param dialogMessage * String, the message displayed at the top of the window * @param initialValue * String, the value displayed for the name of the field * @param noDuplicatesList * ListDisplay<String>[], array of ListDisplay's containing item names which * should not be duplicated * @param text * String, the initial text value for the text editor field (for the item values) * @param isNumericChecked * Boolean, should the checkbox be checked * @param isStyledChecked * Boolean, should the checkbox be checked * @param isMultilineChecked * Boolean, should the checkbox be checked * @param changeTypeItems * String[], list of types to which this field can be changed to - if null, then * display no combo */ public AbrechnungsTypDialog_InputDialog(Shell parentShell, final String dialogTitle, final String dialogMessage, final String initialValue, ListDisplay<String>[] noDuplicatesList, String text, boolean isNumericChecked, boolean isStyledChecked, boolean isMultilineChecked, String[] changeTypeItems){ super(parentShell); cCurrentFieldType = dialogTitle.replaceAll("\\.\\.\\..*", StringTool.leer) + "..."; //$NON-NLS-1$ //$NON-NLS-2$; cDialogTitle = dialogTitle.replaceAll("\\.\\.\\.", StringTool.leer); //$NON-NLS-1$ cDialogMessage = dialogMessage; cInitialValue = initialValue; cNoDuplicatesList = noDuplicatesList; cTextEditorValue = text; cIsNumericChecked = isNumericChecked; cIsStyledChecked = isStyledChecked; cIsMultilineChecked = isMultilineChecked; if (changeTypeItems != null) { for (int i = 0; i < changeTypeItems.length; i++) { changeTypeItems[i] = changeTypeItems[i].replaceAll("\\.\\.\\.", StringTool.leer); //$NON-NLS-1$ } } cChangeTypeItems = changeTypeItems; calcFieldPresence(); } protected void calcFieldPresence(){ cHasTextEditor = false; cTextNeeded = true; cHasNumericCheckbox = false; cHasStyledCheckbox = false; cHasMultilineCheckbox = false; if (cCurrentFieldType.equalsIgnoreCase(Messages.Leistungscodes_contactHL)) {} else if (cCurrentFieldType .equalsIgnoreCase(Messages.Leistungscodes_textHL)) { cHasStyledCheckbox = true; cHasMultilineCheckbox = true; } else if (cCurrentFieldType.equalsIgnoreCase(Messages.Leistungscodes_dateHL)) {} else if (cCurrentFieldType .equalsIgnoreCase(Messages.Leistungscodes_comboHL)) { cHasTextEditor = true; cHasNumericCheckbox = true; } else if (cCurrentFieldType.equalsIgnoreCase(Messages.Leistungscodes_listHL)) { cHasTextEditor = true; cHasNumericCheckbox = true; } else if (cCurrentFieldType.equalsIgnoreCase(Messages.Leistungscodes_checkboxHL)) { cHasTextEditor = true; cTextNeeded = false; } else if (cCurrentFieldType.equalsIgnoreCase(Messages.Leistungscodes_radioHL)) { cHasTextEditor = true; cHasNumericCheckbox = true; } } /** * @parentShell the parent shell, or null to create a top-level shell * @dialogTitle the dialog title, or null if none * @dialogMessage the dialog message, or null if none * @initialValue the initial input value, or null if none (equivalent to the empty string) */ protected Control createDialogArea(final Composite parent){ // changing field type Control[] controls = parent.getChildren(); for (Control c : controls) { c.dispose(); } Composite ret = new Composite(parent, SWT.NONE); ret.setLayoutData(SWTHelper.getFillGridData(1, false, 1, true)); GridLayout gridLayout = new GridLayout(2, false); gridLayout.marginWidth = 5; gridLayout.marginTop = 7; gridLayout.marginBottom = 5; gridLayout.marginLeft = 5; gridLayout.marginRight = 5; ret.setLayout(gridLayout); Label label = new Label(ret, SWT.NONE); label.setText(cDialogMessage); label.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); tName = new Text(ret, SWT.BORDER); tName.setText(cInitialValue); tName.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); Label spacer = new Label(ret, SWT.NONE); spacer.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); if (cHasTextEditor) { Label teLabel = new Label(ret, SWT.NONE); teLabel.setText(Messages.Leistungscodes_EnterItems); teLabel.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); tTextEditor = new Text(ret, SWT.BORDER + SWT.MULTI + SWT.V_SCROLL); tTextEditor.setLayoutData(SWTHelper.getFillGridData(2, true, 1, true)); tTextEditor.setText(FOURLINESPLACEHOLDER); // force 4 lines // size... tTextEditor.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); } if (cHasNumericCheckbox) { chNumeric = new Button(ret, SWT.CHECK); chNumeric.setText(Messages.Leistungscodes_SaveAsNumeric); chNumeric.setSelection(cIsNumericChecked); chNumeric.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); } if (cHasMultilineCheckbox) { chMultiline = new Button(ret, SWT.CHECK); chMultiline.setText(Messages.Leistungscodes_SaveAsMultiplelinesText); chMultiline.setSelection(cIsMultilineChecked); chMultiline.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); } if (cHasStyledCheckbox & (CoreHub.actUser.getLabel().equalsIgnoreCase("a"))) { //$NON-NLS-1$ chStyled = new Button(ret, SWT.CHECK); chStyled.setText(Messages.Leistungscodes_SaveAsStyledText); chStyled.setSelection(cIsStyledChecked); chStyled.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); } if (cChangeTypeItems != null) { new Label(ret, SWT.SEPARATOR | SWT.HORIZONTAL).setLayoutData(SWTHelper .getFillGridData(2, true, 1, false)); Label currentTypeLabel = new Label(ret, SWT.NONE); currentTypeLabel.setText("Aktueller Feldtyp: "); //$NON-NLS-1$); Label currentType = new Label(ret, SWT.NONE); currentType.setText(cCurrentFieldType.replaceAll("\\.\\.\\.", StringTool.leer)); //$NON-NLS-1$); Label changeLabel = new Label(ret, SWT.NONE); changeLabel.setText(Messages.Leistungscodes_changeFieldTypeTo); changeCombo = new Combo(ret, SWT.NONE); changeCombo.setItems(cChangeTypeItems); changeCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e){ Combo selCombo = (Combo) e.widget; String selectedFieldType = selCombo.getText(); cCurrentFieldType = selectedFieldType + "..."; //$NON-NLS-1$ cDialogTitle = cCurrentFieldType.replaceAll("\\.\\.\\.", StringTool.leer); //$NON-NLS-1$ calcFieldPresence(); createDialogArea(parent); // again createButtonBar(parent); // again parent.layout(true); initializeBounds(); if (tTextEditor != null) tTextEditor.setText(cTextEditorValue); // force 4 // lines // end.. } @Override public void widgetDefaultSelected(SelectionEvent e){} }); } return ret; } @Override public void create(){ super.create(); getShell().setText(cDialogTitle); if (tTextEditor != null) tTextEditor.setText(cTextEditorValue); // force 4 lines end... } /** * validate input if not ok then display error message and return false, <br> * else create result as String[] containing: * <ul> * <li> * [0] fieldName</li> * <li> * [1] options for combo/list/checkboxes/radiogroup</li> * <li> * [2] boolean numeric</li> * <li> * [3] boolean multiline</li> * <li> * [4] boolean styled text</li> * <li> * [5] String new field type</li> * <li> * [6] boolean billing system disabled</li> */ @Override protected void okPressed(){ result = new String[7]; result[0] = tName.getText(); result[1] = (tTextEditor == null || tTextEditor.isDisposed()) ? StringTool.leer : tTextEditor .getText(); result[2] = (chNumeric == null || chNumeric.isDisposed()) ? "0" : ((chNumeric.getSelection()) ? "1" : "0"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ result[3] = (chMultiline == null || chMultiline.isDisposed()) ? "0" : ((chMultiline.getSelection()) ? "1" : "0"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ result[4] = (chStyled == null || chStyled.isDisposed()) ? "0" : ((chStyled.getSelection()) ? "1" : "0"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ result[5] = cCurrentFieldType; result[6] = cBilllingSystemDisabled; // allowed, no duplicates are allowed String errorString = StringTool.leer; if (result[0].isEmpty()) { errorString = errorString + Messages.Leistungscodes_ErrorNameMissing; } if ((result[0].indexOf(ARGUMENTSSDELIMITER) >= 0) || (result[0].indexOf(DEFINITIONSDELIMITER) >= 0) || (result[0].indexOf(ITEMDELIMITER) >= 0)) { errorString = errorString + Messages.Leistungscodes_ErrorNameNoSpecialChars; } if ((!cInitialValue.equalsIgnoreCase(result[0])) && (fieldExistsAlready(result[0], cNoDuplicatesList))) { errorString = errorString + Messages.Leistungscodes_ErrorFieldAlreadyExists; } if (cHasTextEditor) { if (cTextNeeded) { if ((result[1].length() > 4) && (result[1].substring(0, 4).equalsIgnoreCase("SQL:"))) { //$NON-NLS-1$ } else if ((result[1].length() > 7) && (result[1].substring(0, 7).equalsIgnoreCase("SCRIPT:"))) { //$NON-NLS-1$ } else { String tmp = result[1].replaceAll("\r\n", DEFINITIONSDELIMITER); //$NON-NLS-1$ tmp = tmp.replaceAll("\n", DEFINITIONSDELIMITER); //$NON-NLS-1$ tmp = tmp.replaceAll("\r", DEFINITIONSDELIMITER); //$NON-NLS-1$ if ((tmp.isEmpty()) || (tmp.split(DEFINITIONSDELIMITER).length < 2)) { errorString = errorString + Messages.Leistungscodes_ErrorAtLeast2Items; } if (!tmp.isEmpty()) { if ((tmp.substring(0, 1).equalsIgnoreCase(DEFINITIONSDELIMITER)) || (tmp.indexOf(DEFINITIONSDELIMITER + DEFINITIONSDELIMITER) >= 0)) { errorString = errorString + Messages.Leistungscodes_ErrorNoEmptyItemsAllowed; } } if ((result[1].indexOf(ARGUMENTSSDELIMITER) >= 0) || (result[1].indexOf(DEFINITIONSDELIMITER) >= 0) || (result[1].indexOf(ITEMDELIMITER) >= 0)) { errorString = errorString + Messages.Leistungscodes_ErrorItemsNoSpecialChars; } } } } if (errorString.isEmpty()) { super.okPressed(); } else { SWTHelper.alert(Messages.Leistungscodes_ErrorMessageTitlebar, errorString); } } public String[] getResult(){ return result; } } /** * class for entering billing systems * * @author G. Weirich / Harald Marlovits * */ class AbrechnungsTypDialog extends TitleAreaDialog { Text tName; Combo cbLstg; Combo cbRechn; Button cbDisabled; Label lbTaxp; String[] result; MultiplikatorEditor mke; ListDisplay<String> ldConstants; ListDisplay<String> ldRequirements; ListDisplay<String> ldOptional; ListDisplay<String> ldUnused; private Button bUseMultiForEigenleistung; /** * the constructor, * * @param shell * @param abrdef * String, the name of the billing system */ AbrechnungsTypDialog(final Shell shell, final String[] abrdef){ super(shell); result = abrdef; } @SuppressWarnings("unchecked") @Override protected Control createDialogArea(final Composite parent){ ScrolledComposite scroller = new ScrolledComposite(parent, SWT.V_SCROLL); Composite ret = new Composite(scroller, SWT.NONE); ret.setLayoutData(SWTHelper.getFillGridData(1, false, 1, true)); ret.setLayout(new GridLayout(1, false)); Composite upperPartComp = new Composite(ret, SWT.NONE); upperPartComp.setLayoutData(SWTHelper.getFillGridData(1, false, 1, false)); upperPartComp.setLayout(new GridLayout(2, false)); new Label(upperPartComp, SWT.NONE).setText(Messages.Leistungscodes_nameLabel); tName = new Text(upperPartComp, SWT.BORDER); tName.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); tName.addFocusListener(new FocusAdapter() { @Override public void focusLost(final FocusEvent e){ mke.reload(tName.getText()); super.focusLost(e); } }); new Label(upperPartComp, SWT.NONE).setText(Messages.Leistungscodes_billingSystemLabel); cbLstg = new Combo(upperPartComp, SWT.READ_ONLY); cbLstg.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); for (IConfigurationElement ic : ll) { cbLstg.add(ic.getAttribute("name")); //$NON-NLS-1$ } new Label(upperPartComp, SWT.NONE).setText(Messages.Leistungscodes_defaultOutputLabel); cbRechn = new Combo(upperPartComp, SWT.READ_ONLY); cbRechn.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); for (IConfigurationElement ic : lo) { cbRechn.add(ic.getAttribute("name")); //$NON-NLS-1$ } new Label(upperPartComp, SWT.NONE).setText(""); //$NON-NLS-1$ cbDisabled = new Button(upperPartComp, SWT.CHECK); cbDisabled.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); cbDisabled.setText(Messages.Leistungscodes_systemDisabled); new Label(ret, SWT.SEPARATOR | SWT.HORIZONTAL).setLayoutData(SWTHelper.getFillGridData( 2, true, 1, false)); String name = "default"; //$NON-NLS-1$ if (result != null) { tName.setText(result[0]); cbLstg.setText(result[1]); cbRechn.setText(result[2]); boolean checked = true; if ((result[6] == null) || (result[6].isEmpty()) || (result[6].equalsIgnoreCase("0")) || (result[6].equalsIgnoreCase("false"))) //$NON-NLS-1$ //$NON-NLS-2$ checked = false; cbDisabled.setSelection(checked); name = result[0]; } GridLayout grid1 = new GridLayout(1, false); grid1.marginWidth = 0; grid1.marginTop = 0; grid1.marginBottom = 0; grid1.marginRight = 5; // right column Composite middlePartComp = new Composite(ret, SWT.NONE); middlePartComp.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); middlePartComp.setLayout(new GridLayout(2, true)); Composite leftMiddlePart = new Composite(middlePartComp, SWT.NONE); leftMiddlePart.setLayout(grid1); leftMiddlePart.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); Composite rightMiddlePart = new Composite(middlePartComp, SWT.NONE); rightMiddlePart.setLayout(grid1); rightMiddlePart.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); lbTaxp = new Label(leftMiddlePart, SWT.NONE); lbTaxp.setText(Messages.Leistungscodes_multiplierLabel); mke = new MultiplikatorEditor(leftMiddlePart, name); mke.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); bUseMultiForEigenleistung = new Button(leftMiddlePart, SWT.CHECK); bUseMultiForEigenleistung.setText("Multiplikator bei Eigenleistungen anwenden."); bUseMultiForEigenleistung .setSelection(MultiplikatorList.isEigenleistungUseMulti(tName.getText())); new Label(rightMiddlePart, SWT.NONE).setText(Messages.Leistungscodes_caseConstants); ldConstants = new ListDisplay<String>(rightMiddlePart, SWT.NONE, new ListDisplay.LDListener() { public String getLabel(Object o){ return (String) o; } public void hyperlinkActivated(String l){ String msg = Messages.Leistungscodes_pleaseEnterNameAndValue; InputDialog inp = new InputDialog(getShell(), l + Messages.Leistungscodes_add, msg, StringTool.leer, null); //$NON-NLS-1$ if (inp.open() == Dialog.OK) { String[] req = inp.getValue().split("="); //$NON-NLS-1$ if (req.length != 2) { SWTHelper.showError(Messages.Leistungscodes_badEntry, Messages.Leistungscodes_explainEntry); } else { ldConstants.add(inp.getValue()); String bs = result[0]; if (bs == null) { bs = tName.getText(); } if (StringTool.isNothing(bs)) { SWTHelper.showError(Messages.Leistungscodes_badEntryCaptiob, Messages.Leistungscodes_badEntryText); } else { Fall.addBillingSystemConstant(bs, inp.getValue()); } } } } }); ldConstants.addHyperlinks(Messages.Leistungscodes_constantHL); if (result != null) { for (String con : Fall.getBillingSystemConstants(result[0])) { ldConstants.add(con); } } ldConstants.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); Action actionDel = new Action() { @Override public String getText(){ return Messages.Leistungscodes_delText; } @Override public ImageDescriptor getImageDescriptor(){ return null; } @Override public void run(){ String sel = ldConstants.getSelection(); ldConstants.remove(sel); Fall.removeBillingSystemConstant(result[0], sel); } }; ldConstants.setMenu(actionDel); Label separator = new Label(middlePartComp, SWT.SEPARATOR | SWT.HORIZONTAL); separator.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); Composite lowerPartComp = new Composite(ret, SWT.NONE); lowerPartComp.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); lowerPartComp.setLayout(new GridLayout(2, false)); String[] data = null; if ((result != null) && (result.length > 3) && (result[3] != null)) data = result[3].split(DEFINITIONSDELIMITER); FieldDefsDisplay fdReq = new FieldDefsDisplay(lowerPartComp, SWT.BORDER, data); fdReq.setLabel(Messages.Leistungscodes_necessaryData); ldRequirements = fdReq.getListDisplay(); data = null; if ((result != null) && (result.length > 4) && (result[4] != null)) data = result[4].split(DEFINITIONSDELIMITER); FieldDefsDisplay fdOpt = new FieldDefsDisplay(lowerPartComp, SWT.BORDER, data); fdOpt.setLabel(Messages.Leistungscodes_optionalData); ldOptional = fdOpt.getListDisplay(); if (CoreHub.acl.request(AccessControlDefaults.CASE_DEFINE_SPECIALS) == true) { data = null; if ((result != null) && (result.length > 5) && (result[5] != null)) data = result[5].split(DEFINITIONSDELIMITER); FieldDefsDisplay fdUnused = new FieldDefsDisplay(lowerPartComp, SWT.BORDER, data); fdUnused.setLabel(Messages.Leistungscodes_unusedData); ldUnused = fdUnused.getListDisplay(); fdUnused.addMoveToAction(ldRequirements, Messages.Leistungscodes_moveItemToRequiredData, Images.IMG_MOVETOUPPERLIST.getImageDescriptor(), true); fdUnused.addMoveToAction(ldOptional, Messages.Leistungscodes_moveItemToOptionalData, Images.IMG_MOVETOLOWERLIST.getImageDescriptor(), true); fdUnused.setNoDuplicatesList(ldRequirements, ldOptional); fdUnused.setNoDuplicatesCreateList(ldRequirements, ldOptional); } fdReq.addMoveToAction(ldRequirements, Messages.Leistungscodes_moveItemToRequiredData, Images.IMG_MOVETOUPPERLIST.getImageDescriptor(), false); fdReq.addMoveToAction(ldOptional, Messages.Leistungscodes_moveItemToOptionalData, Images.IMG_MOVETOLOWERLIST.getImageDescriptor(), true); fdReq.setDeletedList(ldUnused); fdReq.setNoDuplicatesList(ldOptional); fdReq.setNoDuplicatesCreateList(ldRequirements, ldOptional); fdOpt.addMoveToAction(ldRequirements, Messages.Leistungscodes_moveItemToRequiredData, Images.IMG_MOVETOUPPERLIST.getImageDescriptor(), true); fdOpt.addMoveToAction(ldOptional, Messages.Leistungscodes_moveItemToOptionalData, Images.IMG_MOVETOLOWERLIST.getImageDescriptor(), false); fdOpt.setDeletedList(ldUnused); fdOpt.setNoDuplicatesList(ldRequirements); fdOpt.setNoDuplicatesCreateList(ldRequirements, ldOptional); Point retSize = ret.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); ret.setSize(retSize.x, retSize.y); scroller.setContent(ret); scroller.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); ScrollBar sbY = scroller.getVerticalBar(); if (sbY != null) { sbY.setPageIncrement(ret.getSize().y); sbY.setIncrement(20); } return scroller; } @Override public void create(){ super.create(); setTitle(Messages.Leistungscodes_defineBillingSystem); setMessage(Messages.Leistungscodes_pleaseEnterDataForBillingSystem); getShell().setText(Messages.Leistungscodes_billingSystemCaption); } /** * create the result String array */ @Override protected void okPressed(){ result = new String[7]; result[0] = tName.getText(); result[1] = cbLstg.getText(); result[2] = cbRechn.getText(); result[3] = StringTool.join(ldRequirements.getAll(), DEFINITIONSDELIMITER); result[4] = StringTool.join(ldOptional.getAll(), DEFINITIONSDELIMITER); if (ldUnused != null) { result[5] = StringTool.join(ldUnused.getAll(), DEFINITIONSDELIMITER); } result[6] = (cbDisabled.getSelection() == true) ? "1" : "0"; //$NON-NLS-1$ //$NON-NLS-2$ if (bUseMultiForEigenleistung.getSelection()) { if (!MultiplikatorList.isEigenleistungUseMulti(tName.getText())) { MultiplikatorList.setEigenleistungUseMulti(tName.getText()); } } else { if (MultiplikatorList.isEigenleistungUseMulti(tName.getText())) { MultiplikatorList.removeEigenleistungUseMulti(tName.getText()); } } super.okPressed(); } public String[] getResult(){ return result; } } /** * test if a field already exists in the database table (faelle) or in any existing field * definitions * * @param fieldName * @param ldNoDuplicates * @return */ private boolean fieldExistsAlready(final String fieldName, ListDisplay<String>... ldNoDuplicates){ final String tempCaseID = "marlovits-14x@8w1"; //$NON-NLS-1$ JdbcLink j = PersistentObject.getConnection(); String minID = ""; //$NON-NLS-1$ try { minID = j.queryString("select id from faelle limit 1"); //$NON-NLS-1$ Fall fall = Fall.load(minID); if (!fall.exists()) { j.exec("insert into faelle (id) values(" + JdbcLink.wrap(tempCaseID) + ")"); //$NON-NLS-1$ //$NON-NLS-2$ minID = tempCaseID; fall = Fall.load(minID); } // (case-sensitive!!!) String mapped = fall.map(fieldName); if (mapped.equalsIgnoreCase(fieldName)) { return true; } if (!mapped.substring(0, 8).equalsIgnoreCase("**ERROR:")) { //$NON-NLS-1$ return true; } for (ListDisplay<String> ld : ldNoDuplicates) { for (String str : ld.getAll()) { if (str.split(ARGUMENTSSDELIMITER)[0].equalsIgnoreCase(fieldName)) { return true; } } } } finally { if (minID.equalsIgnoreCase(tempCaseID)) j.exec("delete from faelle where id = " + JdbcLink.wrap(tempCaseID)); //$NON-NLS-1$ } return false; } /** * creates a composite with a label on the top, <br> * below there is a ListDisplay on the left side and a navigator on the right side. <br> * in the navigator there are some items preconfigured: <br> * moveItemUp, moveItemDown, editItem * * @author Harald Marlovits * */ class FieldDefsDisplay extends Composite { final static int MOVEITEMUP = 0; final static int MOVEITEMDOWN = 1; final static int DELETEITEM = 3; final static int EDITITEM = 4; final static int LASTFIXEDITEM = 5; Label label; ListDisplay<String> listDisplay; org.eclipse.swt.widgets.List list; ToolBar toolBar; ListDisplay<String> deletedList = null; // they are moved to this list ListDisplay<String>[] noDuplicatesList = null; // list, this contains // the Lists containing // items not to be // duplicated ListDisplay<String>[] noDuplicatesListCreate = null; // new fields, // this contains // the Lists // containing // items not to // be duplicated Short additionalItemsCount = 0; List<ListDisplay<String>> moveTo_DestinationLists = new ArrayList<ListDisplay<String>>(30); IAction[] actions = new IAction[LASTFIXEDITEM + 1]; /** * set the noDuplicatesList value, which contains the Lists containing items not to be * duplicated for the "move to other list action" * * @param listArray */ public void setNoDuplicatesList(ListDisplay<String>... listArray){ noDuplicatesList = listArray; } /** * set the noDuplicatesList value, which contains the Lists containing items not to be * duplicated for the "create new field action" * * @param listArray */ public void setNoDuplicatesCreateList(ListDisplay<String>... listArray){ noDuplicatesListCreate = listArray; } /** * sets the label on top of this List * * @param labelText */ public void setLabel(String labelText){ label.setText(labelText); } /** * returns the ListDisplay of this composite * * @return */ public ListDisplay<String> getListDisplay(){ return listDisplay; } /** * sets the list to which items should be moved to when deleted * * @param unusedList */ public void setDeletedList(ListDisplay<String> unusedList){ deletedList = unusedList; } /** * adds an item at the bottom of the popupmenu and the toolbar * * @param destinationList * @param toolTipText * @param imageDescriptor */ public void addMoveToAction(ListDisplay<String> destinationList, String toolTipText, ImageDescriptor imageDescriptor, boolean enabled){ if (toolBar != null) { Short newItemIx = (short) (LASTFIXEDITEM + additionalItemsCount + 1); moveTo_DestinationLists.add(destinationList); addToolItem(toolBar, imageDescriptor.createImage(), toolTipText, newItemIx, enabled); ListPopUpMenuAction newAction = new ListPopUpMenuAction(toolTipText, imageDescriptor, toolTipText, newItemIx, destinationList, enabled); IAction[] extended = new IAction[LASTFIXEDITEM + additionalItemsCount + 1 + 1]; System.arraycopy(actions, 0, extended, 0, LASTFIXEDITEM + additionalItemsCount + 1); extended[LASTFIXEDITEM + additionalItemsCount + 1] = newAction; actions = extended; listDisplay.setMenu(actions); additionalItemsCount++; } } public FieldDefsDisplay(Composite parent, int style, String[] listItems){ super(parent, SWT.NONE); this.setLayoutData(SWTHelper.getFillGridData(2, true, 1, true)); GridLayout navGridMain = new GridLayout(2, false); navGridMain.marginWidth = 0; navGridMain.marginHeight = 0; this.setLayout(navGridMain); label = new Label(this, SWT.NONE); label.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false)); listDisplay = new ListDisplay<String>(this, SWT.NONE, new ListDisplay.LDListener() { public void hyperlinkActivated(final String l){ _FieldsHyperlinkActivated(l, StringTool.leer); } public String getLabel(final Object o){ return _FieldsGetLabel(o); } }); listDisplay.addHyperlinks(Messages.Leistungscodes_contactHL, Messages.Leistungscodes_textHL, Messages.Leistungscodes_dateHL, Messages.Leistungscodes_comboHL, Messages.Leistungscodes_listHL, Messages.Leistungscodes_checkboxHL, Messages.Leistungscodes_radioHL); listDisplay.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); if (listItems != null) { for (String item : listItems) { listDisplay.add(item); } } Composite navigator = new Composite(this, SWT.NONE); GridLayout navGrid = new GridLayout(1, false); navGrid.marginWidth = 0; navGrid.marginHeight = 0; navGrid.marginTop = 0; navigator.setLayout(navGrid); navigator.setLayoutData(SWTHelper.getFillGridData(1, false, 1, true)); toolBar = new ToolBar(navigator, SWT.BORDER | SWT.FLAT | SWT.VERTICAL); // toolBar = new ToolBar(navigator, SWT.BORDER | SWT.FLAT | // SWT.VERTICAL); toolBar.setData("listDisplay", listDisplay); //$NON-NLS-1$ listDisplay.setData("toolbar", toolBar); //$NON-NLS-1$ addToolItem(toolBar, Images.IMG_ARROWUP.getImage(), Messages.Leistungscodes_moveItemUp, MOVEITEMUP, true); addToolItem(toolBar, Images.IMG_ARROWDOWN.getImage(), Messages.Leistungscodes_moveItemDown, MOVEITEMDOWN, true); addToolItem(toolBar, null, Messages.Leistungscodes_moveItemDown, -1, false); addToolItem(toolBar, Images.IMG_REMOVEITEM.getImage(), Messages.Leistungscodes_deleteItem, DELETEITEM, true); addToolItem(toolBar, Images.IMG_EDIT.getImage(), Messages.Leistungscodes_editItem, EDITITEM, true); addToolItem(toolBar, null, Messages.Leistungscodes_moveItemDown, -1, false); ListPopUpMenuAction moveItemUpAction = new ListPopUpMenuAction(Messages.Leistungscodes_moveItemUp, Images.IMG_ARROWUP.getImageDescriptor(), Messages.Leistungscodes_moveItemUp, MOVEITEMUP, listDisplay, true); ListPopUpMenuAction moveItemDownAction = new ListPopUpMenuAction(Messages.Leistungscodes_moveItemDown, Images.IMG_ARROWDOWN.getImageDescriptor(), Messages.Leistungscodes_moveItemDown, MOVEITEMDOWN, listDisplay, true); ListPopUpMenuAction delItemAction = new ListPopUpMenuAction(Messages.Leistungscodes_deleteAction, Images.IMG_REMOVEITEM.getImageDescriptor(), Messages.Leistungscodes_removeConstraintTT, DELETEITEM, listDisplay, true); ListPopUpMenuAction changeItemAction = new ListPopUpMenuAction(Messages.Leistungscodes_editItem, Images.IMG_EDIT.getImageDescriptor(), Messages.Leistungscodes_editItem, EDITITEM, listDisplay, true); actions[MOVEITEMUP] = moveItemUpAction; actions[MOVEITEMDOWN] = moveItemDownAction; actions[2] = null; actions[DELETEITEM] = delItemAction; actions[EDITITEM] = changeItemAction; actions[LASTFIXEDITEM] = null; listDisplay.setMenu(actions); enableDisableItems(); final org.eclipse.swt.widgets.List child = getListPart(listDisplay); if (child != null) { child.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e){ enableDisableItems(); } @Override public void widgetDefaultSelected(SelectionEvent e){} }); child.addMouseListener(new MouseListener() { @Override public void mouseDoubleClick(MouseEvent e){ String sel = listDisplay.getSelection(); _FieldsHyperlinkActivated(StringTool.leer, sel); } @Override public void mouseDown(MouseEvent e){ if (e.button != 1) { int itemIx = e.y / child.getItemHeight() + child.getTopIndex(); if (itemIx >= child.getItemCount() - 1) itemIx = child.getItemCount() - 1; child.setSelection(itemIx); } enableDisableItems(); } @Override public void mouseUp(MouseEvent e){} }); } } /** * adds a button/toolItem to the bottom of the navigator * * @param parent * the toolBar/navigator * @param image * the image to be used * @param toolTipText * the tooltip to be shown * @param actionType * the action type (MOVEITEMUP, MOVEITEMDOWN, DELETEITEM, EDITITEM, * LASTFIXEDITEM, ...) * @param enabled * enabled or disabled... * @since 3.0.0 */ private void addToolItem(ToolBar parent, Image image, String toolTipText, int actionType, boolean enabled){ if (actionType == -1) { ToolItem toolItem = new ToolItem(parent, SWT.SEPARATOR); toolItem.setEnabled(false); } else { ImageRegistry imageRegistry = UiDesk.getImageRegistry(); ToolItem toolItem = new ToolItem(parent, SWT.PUSH); toolItem.setToolTipText(toolTipText); toolItem.setImage(image); toolItem.setData("type", actionType); //$NON-NLS-1$ toolItem.addSelectionListener(new toolBarSelectionListener()); toolItem.setEnabled(enabled); } } /** * enable or disable the items in the toolbar and in the popupmenu * * @param listDisplayToBeChanged */ private void enableDisableItems(){ ToolBar toolBar = (ToolBar) listDisplay.getData("toolbar"); //$NON-NLS-1$ org.eclipse.swt.widgets.List list = getListPart(listDisplay); Menu menu = list.getMenu(); boolean menuHasItems = menu.getItems().length > 0; int selIx = list.getSelectionIndex(); int maxIx = list.getItemCount(); boolean enabled = false; if (selIx > 0) enabled = true; toolBar.getItem(MOVEITEMUP).setEnabled(enabled); if (menuHasItems) menu.getItem(MOVEITEMUP).setEnabled(enabled); enabled = false; if (selIx < (maxIx - 1)) enabled = true; if (selIx == -1) enabled = false; toolBar.getItem(MOVEITEMDOWN).setEnabled(enabled); if (menuHasItems) menu.getItem(MOVEITEMDOWN).setEnabled(enabled); enabled = true; if (selIx == -1) enabled = false; toolBar.getItem(DELETEITEM).setEnabled(enabled); toolBar.getItem(EDITITEM).setEnabled(enabled); if (menuHasItems) menu.getItem(DELETEITEM).setEnabled(enabled); if (menuHasItems) menu.getItem(EDITITEM).setEnabled(enabled); } /** * find the list of ListDisplay composite - ugly but working find... * * @param listDisplay * @return */ private org.eclipse.swt.widgets.List getListPart(ListDisplay<String> listDisplay){ Control[] children = listDisplay.getChildren(); for (int li = 0; li < children.length; li++) { Control child = children[li]; if (child.getClass().toString() .equalsIgnoreCase("class org.eclipse.swt.widgets.List")) { //$NON-NLS-1$ return (org.eclipse.swt.widgets.List) child; } } return null; } /** * change the type of an item */ public void changeItemType(){ if (listDisplay.getSelection() == null) { SWTHelper.alert(StringTool.leer, Messages.Leistungscodes_mustSelectALine); } else {} } /** * move an item up or down in the list * * @param step * positive for moving down, negative for moving up */ public void moveListItem(int step){ if (listDisplay.getSelection() == null) { SWTHelper.alert(StringTool.leer, Messages.Leistungscodes_mustSelectALine); } else { if (step == 0) return; String sel = listDisplay.getSelection(); List<String> allRequirements = listDisplay.getAll(); int selIx = allRequirements.indexOf(sel); int listSize = allRequirements.size(); boolean conditionOk = false; if (step < 0) { if (selIx > (-step) - 1) conditionOk = true; } if (step > 0) { if (selIx <= listSize - step) conditionOk = true; } if (conditionOk) { allRequirements.set(selIx, allRequirements.get(selIx + step)); allRequirements.set(selIx + step, sel); Object[] tmp = allRequirements.toArray(); for (int i = 0; i < listSize; i++) { listDisplay.remove(allRequirements.get(0)); } for (int i = 0; i < tmp.length; i++) { listDisplay.add((String) tmp[i]); } listDisplay.setSelection(selIx + step); } } } /** * delete an item from the list, move to deletedList. <br> * if this IS the deletedList, then delete definitively */ public void deleteListItem(){ String sel = listDisplay.getSelection(); if (sel == null) { SWTHelper.alert(StringTool.leer, Messages.Leistungscodes_mustSelectALine); } else { if (SWTHelper.askYesNo(StringTool.leer, Messages.Leistungscodes_reallyWantToDeleteItem)) { if ((deletedList != null) && (!deletedList.equals(listDisplay))) { deletedList.add(sel); } listDisplay.remove(sel); } } } /** * selection listener for the toolbar/navigator * * @author Harald Marlovits * */ class toolBarSelectionListener implements SelectionListener { @Override public void widgetSelected(SelectionEvent e){ int type = (Integer) (((ToolItem) (e.getSource())).getData("type")); //$NON-NLS-1$ switch (type) { case MOVEITEMUP: moveListItem(-1); break; case MOVEITEMDOWN: moveListItem(+1); break; case DELETEITEM: deleteListItem(); break; case EDITITEM: String sel = listDisplay.getSelection(); _FieldsHyperlinkActivated(StringTool.leer, sel); break; default: if (type > LASTFIXEDITEM) { moveItemToOtherList(listDisplay, moveTo_DestinationLists.get(type - LASTFIXEDITEM - 1), noDuplicatesList); } break; } } @Override public void widgetDefaultSelected(SelectionEvent e){} } /** * selection listener for the popupmenu * * @author Harald Marlovits * */ class ListPopUpMenuAction extends Action { int actionType = 0; /** * * @param actionName * @param imageDescriptor * @param toolTipText * @param actionType * @param listDisplay * @param enabled * @since 3.0.0 constructor signature changed to ImageDescriptor */ public ListPopUpMenuAction(String actionName, ImageDescriptor imageDescriptor, String toolTipText, int actionType, ListDisplay<String> listDisplay, boolean enabled){ super(actionName); this.actionType = actionType; setImageDescriptor(imageDescriptor); setToolTipText(toolTipText); this.setEnabled(enabled); } @Override public void run(){ // this.setEnabled(false); switch (actionType) { case MOVEITEMUP: moveListItem(-1); break; case MOVEITEMDOWN: moveListItem(+1); break; case DELETEITEM: deleteListItem(); break; case EDITITEM: String sel = listDisplay.getSelection(); _FieldsHyperlinkActivated(StringTool.leer, sel); break; default: if (actionType > LASTFIXEDITEM) { moveItemToOtherList(listDisplay, moveTo_DestinationLists.get(actionType - LASTFIXEDITEM - 1), noDuplicatesList); } break; } } }; /** * return the label for the supplied object <br> * the object is the String in the form <fieldName>:<fieldType>:<itemsList> * * @param o * @return */ public String _FieldsGetLabel(final Object o){ String[] l = ((String) o).split(ARGUMENTSSDELIMITER); //$NON-NLS-1$ if (l.length > 1) { String type = Messages.Leistungscodes_date; if (l[1].equals("T")) { //$NON-NLS-1$ type = Messages.Leistungscodes_text; } else if (l[1].equals("K")) { //$NON-NLS-1$ type = Messages.Leistungscodes_contact; } else if (l[1].equals("D")) { //$NON-NLS-1$ type = Messages.Leistungscodes_date; } else if (l[1].equals("TM")) { //$NON-NLS-1$ type = Messages.Leistungscodes_textMultipleLines; } else if (l[1].equals("TS")) { //$NON-NLS-1$ type = Messages.Leistungscodes_textStyled; } else if (l[1].equals("CS")) { //$NON-NLS-1$ type = Messages.Leistungscodes_combo; } else if (l[1].equals("CN")) { //$NON-NLS-1$ type = Messages.Leistungscodes_comboNumeric; } else if (l[1].equals("LS")) { //$NON-NLS-1$ type = Messages.Leistungscodes_list; } else if (l[1].equals("LN")) { //$NON-NLS-1$ type = Messages.Leistungscodes_ListNumeric; } else if (l[1].equals("X")) { //$NON-NLS-1$ type = Messages.Leistungscodes_checkbox; } else if (l[1].equals("RS")) { //$NON-NLS-1$ type = Messages.Leistungscodes_radiogroup; } else if (l[1].equals("RN")) { //$NON-NLS-1$ type = Messages.Leistungscodes_radiogroupNumeric; } String opt = (l.length >= 3) ? " (" + l[2].replaceAll(ITEMDELIMITER, "; ") + ")" : StringTool.leer; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (opt.trim().equalsIgnoreCase("(SQL)")) { //$NON-NLS-1$ opt = (l.length >= 4) ? " (SQL: " + l[3].replaceAll(ITEMDELIMITER, "; ") + ")" : StringTool.leer; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return type + " " + l[0] + opt; //$NON-NLS-1$ } else { return type + " " + l[0] + opt; //$NON-NLS-1$ } } else { String opt = (l.length >= 3) ? " (" + l[2].replaceAll(ITEMDELIMITER, "; ") + ")" : StringTool.leer; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return "? " + " " + l[0] + opt; //$NON-NLS-1$ //$NON-NLS-2$ } } /** * * @param l * if creating a field, then this contains the field type name * @param fieldToBeChanged * if changing a field, then this contains the full definition for the field to * be changed [fieldName]:[fieldType]:[itemsList] */ public void _FieldsHyperlinkActivated(final String l, String fieldToBeChanged){ String ll = l; boolean isChanging = false; String fieldName = StringTool.leer; String fieldType = StringTool.leer; String optionsIn = StringTool.leer; boolean isNumericChecked = false; boolean isStyledChecked = false; boolean isMultilineChecked = false; if (ll.isEmpty()) { isChanging = true; String[] fields = fieldToBeChanged.split(ARGUMENTSSDELIMITER); fieldName = fields[0]; fieldType = fields[1]; optionsIn = fields.length > 2 ? fields[2] : StringTool.leer; optionsIn = optionsIn.replaceAll(ITEMDELIMITER, "\n"); //$NON-NLS-1$ if (fieldType.equalsIgnoreCase("K")) { //$NON-NLS-1$ ll = Messages.Leistungscodes_contactHL; } else if (fieldType.substring(0, 1).equalsIgnoreCase("T")) { //$NON-NLS-1$ ll = Messages.Leistungscodes_textHL; } else if (fieldType.substring(0, 1).equalsIgnoreCase("D")) { //$NON-NLS-1$ ll = Messages.Leistungscodes_dateHL; } else if (fieldType.substring(0, 1).equalsIgnoreCase("C")) { //$NON-NLS-1$ ll = Messages.Leistungscodes_comboHL; } else if (fieldType.substring(0, 1).equalsIgnoreCase("L")) { //$NON-NLS-1$ ll = Messages.Leistungscodes_listHL; } else if (fieldType.substring(0, 1).equalsIgnoreCase("X")) { //$NON-NLS-1$ ll = Messages.Leistungscodes_checkboxHL; } else if (fieldType.substring(0, 1).equalsIgnoreCase("R")) { //$NON-NLS-1$ ll = Messages.Leistungscodes_radioHL; } if (fieldType.length() >= 2) { if (fieldType.equalsIgnoreCase("TM")) { //$NON-NLS-1$ isMultilineChecked = true; } else if (fieldType.equalsIgnoreCase("TS")) { //$NON-NLS-1$ isStyledChecked = true; } else if (fieldType.substring(1, 2).equalsIgnoreCase("N")) { //$NON-NLS-1$ isNumericChecked = true; } } } String msg = Messages.Leistungscodes_pleaseEnterName; String[] changeItems = { Messages.Leistungscodes_contactHL, Messages.Leistungscodes_textHL, Messages.Leistungscodes_dateHL, Messages.Leistungscodes_comboHL, Messages.Leistungscodes_listHL, Messages.Leistungscodes_checkboxHL, Messages.Leistungscodes_radioHL }; AbrechnungsTypDialog_InputDialog inputDlg = new AbrechnungsTypDialog_InputDialog(getShell(), ll + (isChanging ? Messages.Leistungscodes_changeTextInTitleBar : Messages.Leistungscodes_add), msg, fieldName, noDuplicatesListCreate, optionsIn, isNumericChecked, isStyledChecked, isMultilineChecked, isChanging ? changeItems : null); if (inputDlg.open() == Dialog.OK) { String[] result = inputDlg.getResult(); String req = result[0]; String options = result[1]; ll = result[5]; if ((options.length() > 4) && (options.substring(0, 4).equalsIgnoreCase("SQL:"))) { //$NON-NLS-1$ // FallDetailBlatt2 } if ((options.length() > 4) && (options.substring(0, 4).equalsIgnoreCase("SCRIPT:"))) { //$NON-NLS-1$ // FallDetailBlatt2 } boolean hasNumeric = result[2].equalsIgnoreCase("0") ? false : true; //$NON-NLS-1$ boolean hasMultiline = result[3].equalsIgnoreCase("0") ? false : true; //$NON-NLS-1$ boolean hasStyled = result[4].equalsIgnoreCase("0") ? false : true; //$NON-NLS-1$ if (ll.equalsIgnoreCase(Messages.Leistungscodes_contactHL)) { req += ":K"; // Kontakt //$NON-NLS-1$ } else if (ll.equalsIgnoreCase(Messages.Leistungscodes_textHL)) { if (hasStyled) { req += ":TS"; // Styled Text //$NON-NLS-1$ } else if (hasMultiline) { req += ":TM"; // Multiline Text //$NON-NLS-1$ } else { req += ":T"; // normal Text //$NON-NLS-1$ } } else if (ll.equalsIgnoreCase(Messages.Leistungscodes_dateHL)) { req += ":D"; // Date //$NON-NLS-1$ } else if (ll.equalsIgnoreCase(Messages.Leistungscodes_comboHL)) { if (hasNumeric) { req += ":CN"; // Combo numeric //$NON-NLS-1$ } else { req += ":CS"; // Combo //$NON-NLS-1$ } } else if (ll.equalsIgnoreCase(Messages.Leistungscodes_listHL)) { if (hasNumeric) { req += ":LN"; // List numeric //$NON-NLS-1$ } else { req += ":LS"; // List //$NON-NLS-1$ } } else if (ll.equalsIgnoreCase(Messages.Leistungscodes_checkboxHL)) { req += ":X"; // Checkboxes //$NON-NLS-1$ } else if (ll.equalsIgnoreCase(Messages.Leistungscodes_radioHL)) { if (hasNumeric) { req += ":RN"; // Radiobuttons numeric //$NON-NLS-1$ } else { req += ":RS"; // Radiobuttons //$NON-NLS-1$ } } options = options.replaceAll("\r\n", ITEMDELIMITER); //$NON-NLS-1$ options = (options.replaceAll("\n", ITEMDELIMITER)).replaceAll("\r", ITEMDELIMITER); //$NON-NLS-1$ //$NON-NLS-2$ req = req + ARGUMENTSSDELIMITER + options; if (isChanging) { List<String> allRequirements = listDisplay.getAll(); int selIx = allRequirements.indexOf(fieldToBeChanged); if (selIx >= 0) { Object[] tmp = allRequirements.toArray(); int listSize = allRequirements.size(); List<String> currRequirements = listDisplay.getAll(); for (int i = 0; i < listSize; i++) { listDisplay.remove(currRequirements.get(0)); } for (int i = 0; i < tmp.length; i++) { String toBeAdded = (String) tmp[i]; if (i == selIx) toBeAdded = req; listDisplay.add(toBeAdded); } } } else { listDisplay.add(req); } } } /** * moving items from one list to another list the moved item MUST NOT be in the destination * list - will not be allowed the moved item MUST NOT be in one of the noDuplicatesDisplays * list - will not be allowed * * @param listDisplay * the current list from which the item should be moved away * @param destDisplay * the destination list to which the item should be moved to * @param noDuplicatesDisplays * an array of ListDisplay's which contain the values which should not be * duplicated */ @SuppressWarnings("unchecked") public void moveItemToOtherList(ListDisplay<String> listDisplay, ListDisplay<String> destDisplay, ListDisplay<String>... noDuplicatesDisplays){ // no duplicates allowed for destination list String sel = listDisplay.getSelection(); if (sel.isEmpty()) return; java.util.ArrayList<String> allItems = (ArrayList<String>) ((ArrayList<String>) destDisplay.getAll()).clone(); for (int li = 0; li < allItems.size(); li++) { allItems.set(li, allItems.get(li).split(ARGUMENTSSDELIMITER)[0]); } if (allItems.contains(sel.split(ARGUMENTSSDELIMITER)[0])) { SWTHelper.alert(StringTool.leer, Messages.Leistungscodes_definitionAlreadyExistsInDestination); return; } for (ListDisplay<String> noDuplicatesList : noDuplicatesDisplays) { java.util.ArrayList<String> allItems2 = (ArrayList<String>) ((ArrayList<String>) noDuplicatesList.getAll()).clone(); for (int li = 0; li < allItems2.size(); li++) { allItems2.set(li, allItems2.get(li).split(ARGUMENTSSDELIMITER)[0]); } if (allItems2.contains(sel.split(ARGUMENTSSDELIMITER)[0])) { SWTHelper.alert(StringTool.leer, Messages.Leistungscodes_definitionAlreadyExistsSomewhere); return; } } destDisplay.add(sel); listDisplay.remove(sel); } } }
package org.eclipse.hono.client.impl; import io.vertx.core.AsyncResult; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.proton.ProtonConnection; import io.vertx.proton.ProtonDelivery; import io.vertx.proton.ProtonQoS; import io.vertx.proton.ProtonReceiver; import org.apache.qpid.proton.message.Message; import org.eclipse.hono.client.MessageConsumer; import org.eclipse.hono.config.ClientConfigProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Objects; import java.util.function.BiConsumer; /** * Abstract client for consuming messages from a Hono server. */ abstract class AbstractConsumer extends AbstractHonoClient implements MessageConsumer { private static final Logger LOG = LoggerFactory.getLogger(AbstractConsumer.class); AbstractConsumer(final Context context, final ClientConfigProperties config, final ProtonReceiver receiver) { super(context, config); this.receiver = receiver; } @Override public void flow(final int credits) { receiver.flow(credits); } @Override public void close(final Handler<AsyncResult<Void>> closeHandler) { closeLinks(closeHandler); } static Future<ProtonReceiver> createConsumer( final Context context, final ClientConfigProperties clientConfig, final ProtonConnection con, final String tenantId, final String pathSeparator, final String address, final ProtonQoS qos, final BiConsumer<ProtonDelivery, Message> consumer) { Objects.requireNonNull(context); Objects.requireNonNull(clientConfig); Objects.requireNonNull(con); Objects.requireNonNull(tenantId); Objects.requireNonNull(pathSeparator); Objects.requireNonNull(address); Objects.requireNonNull(qos); final Future<ProtonReceiver> result = Future.future(); final String targetAddress = String.format(address, pathSeparator, tenantId); context.runOnContext(open -> { final ProtonReceiver receiver = con.createReceiver(targetAddress); receiver.setAutoAccept(true); receiver.setPrefetch(clientConfig.getInitialCredits()); receiver.setQoS(qos); receiver.handler((delivery, message) -> { if (consumer != null) { consumer.accept(delivery, message); } if (LOG.isTraceEnabled()) { int remainingCredits = receiver.getCredit() - receiver.getQueued(); LOG.trace("handling message [remotely settled: {}, queued messages: {}, remaining credit: {}]", delivery.remotelySettled(), receiver.getQueued(), remainingCredits); } }); receiver.openHandler(receiverOpen -> { if (receiverOpen.succeeded()) { LOG.debug("receiver [source: {}, qos: {}] open", receiver.getRemoteSource(), receiver.getRemoteQoS()); if (qos.equals(ProtonQoS.AT_LEAST_ONCE) && !qos.equals(receiver.getRemoteQoS())) { LOG.info("remote container uses other QoS than requested [requested: {}, in use: {}]", qos, receiver.getRemoteQoS()); } result.complete(receiver); } else { result.fail(receiverOpen.cause()); } }); receiver.open(); }); return result; } }
package org.zstack.compute.vm; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.cloudbus.CloudBusCallBack; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.gc.EventBasedGCPersistentContext; import org.zstack.core.gc.GCEventTrigger; import org.zstack.core.gc.GCFacade; import org.zstack.header.core.workflow.FlowTrigger; import org.zstack.header.core.workflow.NoRollbackFlow; import org.zstack.header.host.HostCanonicalEvents; import org.zstack.header.host.HostConstant; import org.zstack.header.host.HostErrors; import org.zstack.header.host.HostStatus; import org.zstack.header.message.MessageReply; import org.zstack.header.vm.*; import java.util.Map; import static org.zstack.utils.StringDSL.ln; @Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class VmStopOnHypervisorFlow extends NoRollbackFlow { @Autowired protected DatabaseFacade dbf; @Autowired protected CloudBus bus; @Autowired protected ErrorFacade errf; @Autowired protected GCFacade gcf; @Override public void run(final FlowTrigger chain, Map data) { final VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); StopVmOnHypervisorMsg msg = new StopVmOnHypervisorMsg(); msg.setVmInventory(spec.getVmInventory()); if (spec.getMessage() instanceof APIStopVmInstanceMsg) { msg.setType(((APIStopVmInstanceMsg)spec.getMessage()).getType()); } bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, spec.getVmInventory().getHostUuid()); bus.send(msg, new CloudBusCallBack(chain) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { chain.next(); } else { if (spec.isGcOnStopFailure() && reply.getError().isError(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE)) { setupGcJob(spec); chain.next(); } else { chain.fail(reply.getError()); } } } }); } private void setupGcJob(VmInstanceSpec spec) { GCStopVmContext c = new GCStopVmContext(); VmInstanceInventory vm = spec.getVmInventory(); c.setHostUuid(vm.getHostUuid()); c.setVmUuid(vm.getUuid()); c.setInventory(vm); c.setTriggerHostStatus(HostStatus.Connected.toString()); EventBasedGCPersistentContext<GCStopVmContext> ctx = new EventBasedGCPersistentContext<GCStopVmContext>(); ctx.setRunnerClass(GCStopVmRunner.class); ctx.setContextClass(GCStopVmContext.class); ctx.setName(String.format("stop-vm-%s", spec.getVmInventory().getUuid())); ctx.setContext(c); GCEventTrigger trigger = new GCEventTrigger(); trigger.setCodeName("gc-stop-vm-on-host-connected"); trigger.setEventPath(HostCanonicalEvents.HOST_STATUS_CHANGED_PATH); String code = ln( "import org.zstack.header.host.HostCanonicalEvents.HostStatusChangedData", "import org.zstack.compute.vm.GCStopVmContext", "HostStatusChangedData d = (HostStatusChangedData) data", "GCStopVmContext c = (GCStopVmContext) context", "return c.hostUuid == d.hostUuid && d.newStatus == c.triggerHostStatus" ).toString(); trigger.setCode(code); ctx.addTrigger(trigger); trigger = new GCEventTrigger(); trigger.setCodeName("gc-stop-vm-on-host-deleted"); trigger.setEventPath(HostCanonicalEvents.HOST_DELETED_PATH); code = ln( "import org.zstack.header.host.HostCanonicalEvents.HostDeletedData", "import org.zstack.compute.vm.GCStopVmContext", "HostDeletedData d = (HostDeletedData) data", "GCStopVmContext c = (GCStopVmContext) context", "return c.hostUuid == d.hostUuid" ).toString(); trigger.setCode(code); ctx.addTrigger(trigger); trigger = new GCEventTrigger(); trigger.setCodeName("gc-stop-vm-on-vm-deleted"); trigger.setEventPath(VmCanonicalEvents.VM_FULL_STATE_CHANGED_PATH); code = ln( "import org.zstack.header.vm.VmCanonicalEvents.VmStateChangedData", "import org.zstack.compute.vm.GCStopVmContext", "VmStateChangedData d = (VmStateChangedData) data", "GCStopVmContext c = (GCStopVmContext) context", "return c.vmUuid == d.vmUuid && d.newState == \"{0}\"" ).format(VmInstanceState.Destroyed.toString()); trigger.setCode(code); ctx.addTrigger(trigger); gcf.schedule(ctx); } }
package io.github.deathsbreedgames.spacerun.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.viewport.StretchViewport; import io.github.deathsbreedgames.spacerun.GlobalVars; public class OptionsScreen extends BaseScreen { private Preferences prefs; private OrthographicCamera camera; private SpriteBatch batch; private BitmapFont titleFont; private BitmapFont textFont; private Stage mainStage; private TextureAtlas buttonAtlas; private Skin buttonSkin; private BitmapFont buttonFont; private ImageButton soundControl, musicControl; public OptionsScreen() { super("MainMenu"); prefs = Gdx.app.getPreferences("SpaceRun"); camera = new OrthographicCamera(GlobalVars.width, GlobalVars.height); camera.position.set(GlobalVars.width / 2, GlobalVars.height / 2, 0); camera.update(); batch = new SpriteBatch(); titleFont = new BitmapFont(); titleFont.scale(0.75f); textFont = new BitmapFont(); textFont.scale(0.5f); mainStage = new Stage(new StretchViewport(GlobalVars.width, GlobalVars.height)); buttonAtlas = new TextureAtlas("gfx/ui/buttons.pack"); buttonSkin = new Skin(buttonAtlas); Gdx.input.setInputProcessor(mainStage); ImageButtonStyle imageButtonStyle = new ImageButtonStyle(); imageButtonStyle.imageUp = buttonSkin.getDrawable("Switch-on"); imageButtonStyle.imageChecked = buttonSkin.getDrawable("Switch-off"); ImageButtonStyle imageButtonStyleInv = new ImageButtonStyle(); imageButtonStyleInv.imageUp = buttonSkin.getDrawable("Switch-off"); imageButtonStyleInv.imageChecked = buttonSkin.getDrawable("Switch-on"); if(GlobalVars.soundOn) soundControl = new ImageButton(imageButtonStyle); else soundControl = new ImageButton(imageButtonStyleInv); soundControl.setPosition(10f, 350f); mainStage.addActor(soundControl); soundControl.addListener(new ChangeListener() { public void changed(ChangeEvent e, Actor a) { if(GlobalVars.soundOn) { GlobalVars.soundOn = false; } else { GlobalVars.soundOn = true; } prefs.putBoolean("SoundOff", !GlobalVars.soundOn); prefs.flush(); } }); if(GlobalVars.musicOn) musicControl = new ImageButton(imageButtonStyle); else musicControl = new ImageButton(imageButtonStyleInv); musicControl.setPosition(10f, 290f); mainStage.addActor(musicControl); musicControl.addListener(new ChangeListener() { public void changed(ChangeEvent e, Actor a) { if(GlobalVars.musicOn) { GlobalVars.musicOn = false; } else { GlobalVars.musicOn = true; } prefs.putBoolean("MusicOff", !GlobalVars.musicOn); prefs.flush(); } }); buttonFont = new BitmapFont(); buttonFont.scale(0.3f); TextButtonStyle buttonStyle = new TextButtonStyle(); buttonStyle.up = buttonSkin.getDrawable("MainMenu-normal"); buttonStyle.down = buttonSkin.getDrawable("MainMenu-down"); buttonStyle.over = buttonSkin.getDrawable("MainMenu-hover"); buttonStyle.font = buttonFont; TextButton clearButton = new TextButton("CLEAR DATA", buttonStyle); clearButton.setPosition(10f, 240f); mainStage.addActor(clearButton); clearButton.addListener(new ChangeListener() { public void changed(ChangeEvent e, Actor a) { prefs.putInteger("HighScore", 0); prefs.putBoolean("SoundOff", false); prefs.putBoolean("MusicOff", false); setNextScreen("Splash"); setDone(true); } }); TextButton backButton = new TextButton("BACK", buttonStyle); backButton.setPosition(GlobalVars.width / 2 - backButton.getWidth() / 2, 10f); mainStage.addActor(backButton); backButton.addListener(new ChangeListener() { public void changed(ChangeEvent e, Actor a) { setNextScreen("MainMenu"); setDone(true); } }); } @Override public void render(float delta) { super.render(delta); camera.update(); batch.setProjectionMatrix(camera.combined); batch.begin(); titleFont.setColor(1f, 0f, 0f, 1f); titleFont.draw(batch, "OPTIONS", 10f, 450f); textFont.draw(batch, "SOUND", 100f, 380f); textFont.draw(batch, "MUSIC", 100f, 320f); batch.end(); mainStage.act(); mainStage.draw(); } @Override public void dispose() { batch.dispose(); titleFont.dispose(); textFont.dispose(); mainStage.dispose(); buttonAtlas.dispose(); buttonSkin.dispose(); buttonFont.dispose(); } }
package org.lemurproject.galago.core.links; import java.io.IOException; import org.lemurproject.galago.core.parse.Document; import org.lemurproject.galago.core.types.DocumentUrl; import org.lemurproject.galago.tupleflow.InputClass; import org.lemurproject.galago.tupleflow.OutputClass; import org.lemurproject.galago.tupleflow.StandardStep; import org.lemurproject.galago.tupleflow.execution.Verified; /** * * @author sjh */ @Verified @InputClass(className = "org.lemurproject.galago.core.parse.Document") @OutputClass(className = "org.lemurproject.galago.core.types.DocumentUrl") public class UrlExtractor extends StandardStep<Document, DocumentUrl> { public String scrubUrl(String url) { // remove a leading pound sign if (url.charAt(url.length() - 1) == ' url = url.substring(0, url.length() - 1); // make it lowercase } url = url.toLowerCase(); // remove a port number, if it's the default number url = url.replace(":80/", "/"); if (url.endsWith(":80")) { url = url.replace(":80", ""); } // remove trailing slashes while (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 1); } return url.toLowerCase(); } @Override public void process(Document doc) throws IOException { processor.process(new DocumentUrl(doc.name, scrubUrl(doc.metadata.get("url")))); } }
package com.mmnaseri.cs.algorithm.common; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Comparator; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining; import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; import static org.hamcrest.collection.IsArrayWithSize.emptyArray; /** * @author Mohammad Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (7/9/15, 8:53 PM) */ public abstract class BaseSortTest { protected abstract Sorter<Integer> getAscendingSorter(); protected static final Comparator<Integer> NATURAL_COMPARATOR = new Comparator<Integer>() { @Override public int compare(Integer first, Integer second) { return first.compareTo(second); } }; @Test public void testSortingEmptyArray() throws Exception { final Integer[] items = {}; getAscendingSorter().sort(items); assertThat(items, emptyArray()); } @Test public void testSimpleAscendingSortWithNegativeItems() throws Exception { final Integer[] items = {-7, -9, -8, 7, 9, 8, 0}; final int length = items.length; getAscendingSorter().sort(items); assertThat(items, arrayWithSize(length)); assertThat(items, arrayContaining(-9, -8, -7, 0, 7, 8, 9)); } @Test public void testAscendingSortWithInfinity() throws Exception { final Integer[] items = {1, 2, 3, Integer.MIN_VALUE, 0, Integer.MAX_VALUE, 4, 5, 6}; final int length = items.length; getAscendingSorter().sort(items); assertThat(items, arrayWithSize(length)); assertThat(items, arrayContaining(Integer.MIN_VALUE, 0, 1, 2, 3, 4, 5, 6, Integer.MAX_VALUE)); } @DataProvider public Object[][] normalDataProvider() { return new Object[][]{ new Object[]{new Integer[]{10}, new Integer[]{10}}, //testSortingSingleItemList new Object[]{new Integer[]{1, 9, 3, 7, 3, 0}, new Integer[]{0, 1, 3, 3, 7, 9}}, //testSimpleAscendingSort new Object[]{new Integer[]{8, 8, 8, 7, 7, 7, 6, 6, 6}, new Integer[]{6, 6, 6, 7, 7, 7, 8, 8, 8}}, //testWithDuplicates new Object[]{new Integer[]{1, 2, 3, 4, 5, 6}, new Integer[]{1, 2, 3, 4, 5, 6}}, //testSortingAlreadySortedArray new Object[]{new Integer[]{6, 5, 4, 3, 2, 1}, new Integer[]{1, 2, 3, 4, 5, 6}}, //testSortingReversedArray }; } @Test(dataProvider = "normalDataProvider") public void testSortIntegrity(Integer[] items, Integer[] expected) throws Exception { final Integer[] target = new Integer[items.length]; System.arraycopy(items, 0, target, 0, target.length); getAscendingSorter().sort(target); assertThat(target, arrayWithSize(expected.length)); assertThat(target, arrayContaining(expected)); } }
package gov.nih.nci.caxchange.ctom.viewer.DAO; import gov.nih.nci.labhub.domain.CD; import gov.nih.nci.labhub.domain.HealthCareSite; import gov.nih.nci.labhub.domain.LaboratoryTest; import gov.nih.nci.labhub.domain.Specimen; import gov.nih.nci.labhub.domain.SpecimenCollection; import gov.nih.nci.labhub.domain.StudySite; import gov.nih.nci.labhub.domain.SubjectAssignment; import gov.nih.nci.system.applicationservice.ApplicationService; import gov.nih.nci.system.client.ApplicationServiceProvider; import gov.nih.nci.system.query.cql.CQLAssociation; import gov.nih.nci.system.query.cql.CQLAttribute; import gov.nih.nci.system.query.cql.CQLGroup; import gov.nih.nci.system.query.cql.CQLLogicalOperator; import gov.nih.nci.system.query.cql.CQLObject; import gov.nih.nci.system.query.cql.CQLPredicate; import gov.nih.nci.system.query.cql.CQLQuery; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * @author asharma * */ public class FiltersDAO extends HibernateDaoSupport{ private static final Logger logDB = Logger.getLogger(FiltersDAO.class); private static final String CONFIG_FILE = "/baseURL.properties"; /** * Retrieves the Site Filters * @param session * @return * @throws Exception */ public List getSiteFilterList (HttpSession session) throws Exception { List siteList = new ArrayList(); try { String studyId = (String)session.getAttribute("studyId")!=null?(String)session.getAttribute("studyId"):""; ApplicationService appService = ApplicationServiceProvider.getApplicationService(); // Create the query to get Study object CQLQuery query = new CQLQuery(); CQLObject target = new CQLObject(); target.setName("gov.nih.nci.labhub.domain.HealthCareSite"); // Now get to StudySite CQLAssociation subjectAssignmentAssociation2 = new CQLAssociation(); subjectAssignmentAssociation2.setName("gov.nih.nci.labhub.domain.StudySite"); subjectAssignmentAssociation2.setTargetRoleName("studySiteCollection"); // Now get to Study CQLAssociation studySiteAssociation1 = new CQLAssociation(); studySiteAssociation1.setName("gov.nih.nci.labhub.domain.Study"); studySiteAssociation1.setTargetRoleName("study"); // Now set the study identifier on the association to II CQLAssociation iiAssociation = new CQLAssociation(); iiAssociation.setName("gov.nih.nci.labhub.domain.II"); iiAssociation.setTargetRoleName("studyIdentifier"); iiAssociation.setAttribute(new CQLAttribute("extension", CQLPredicate.EQUAL_TO, studyId.trim())); studySiteAssociation1.setAssociation(iiAssociation); subjectAssignmentAssociation2.setAssociation(studySiteAssociation1); // Then put it all together target.setAssociation(subjectAssignmentAssociation2); query.setTarget(target); List resultList = appService.query(query); // Get a connection to the database using the hibernate configuration int i = 0; for (Iterator resultsIterator = resultList.iterator(); resultsIterator.hasNext();) { HealthCareSite hcs = (HealthCareSite) resultsIterator.next(); siteList = printRecordHealthCareSite(hcs); } } catch (Exception ex) { logDB.error(ex.getMessage()); } return siteList; } /** * printRecord creates the view object that will properly display the results * @param sa * @param beginDate2 * @param endDate2 * @param request * @return * @throws ParseException */ private ArrayList printRecordHealthCareSite(HealthCareSite hcs) throws ParseException { ArrayList list = new ArrayList(); list.add("All"); if (hcs == null) return null; if (hcs!= null) { // Set the study ID Collection siteCollection = hcs.getStudySiteCollection(); if (siteCollection != null && siteCollection.size() > 0) { for (Iterator ssIterator = siteCollection.iterator(); ssIterator.hasNext();) { StudySite ss = (StudySite) ssIterator.next(); list.add(ss.getHealthCareSite().getName()); } } } return list; } /** * Retrieves the Site Filters * @param session * @return * @throws Exception */ public List getLabTestFilterList (HttpSession session) throws Exception { List labTestList = new ArrayList(); try { String studyId = (String)session.getAttribute("studyId")!=null?(String)session.getAttribute("studyId"):""; String patientId = (String)session.getAttribute("patientId")!=null?(String)session.getAttribute("patientId"):""; ApplicationService appService = ApplicationServiceProvider.getApplicationService(); // Create the query to get SubjectAssignment object CQLQuery query = new CQLQuery(); CQLObject target = new CQLObject(); target.setName("gov.nih.nci.labhub.domain.SubjectAssignment"); // Set the subject Identifier on the association to II CQLAssociation subjectAssignmentAssociation1 = new CQLAssociation(); subjectAssignmentAssociation1.setName("gov.nih.nci.labhub.domain.II"); subjectAssignmentAssociation1.setTargetRoleName("studySubjectIdentifier"); subjectAssignmentAssociation1.setAttribute(new CQLAttribute("extension", CQLPredicate.EQUAL_TO, patientId.trim())); // Now get to StudySite CQLAssociation subjectAssignmentAssociation2 = new CQLAssociation(); subjectAssignmentAssociation2.setName("gov.nih.nci.labhub.domain.StudySite"); subjectAssignmentAssociation2.setTargetRoleName("studySite"); // Now get to Study CQLAssociation studySiteAssociation1 = new CQLAssociation(); studySiteAssociation1.setName("gov.nih.nci.labhub.domain.Study"); studySiteAssociation1.setTargetRoleName("study"); subjectAssignmentAssociation2.setAssociation(studySiteAssociation1); // Now set the study identifier on the association to II CQLAssociation studyAssociation1 = new CQLAssociation(); studyAssociation1.setName("gov.nih.nci.labhub.domain.II"); studyAssociation1.setTargetRoleName("studyIdentifier"); studyAssociation1.setAttribute(new CQLAttribute("extension", CQLPredicate.EQUAL_TO, studyId.trim())); studySiteAssociation1.setAssociation(studyAssociation1); // Now get the SpecimenCollection CQLAssociation subjectAssignmentAssociation3 = new CQLAssociation(); subjectAssignmentAssociation3.setName("gov.nih.nci.labhub.domain.SpecimenCollection"); subjectAssignmentAssociation3.setTargetRoleName("activityCollection"); // Then put it all together CQLGroup finalgroup = new CQLGroup(); finalgroup.addAssociation(subjectAssignmentAssociation1); finalgroup.addAssociation(subjectAssignmentAssociation2); finalgroup.addAssociation(subjectAssignmentAssociation3); finalgroup.setLogicOperator(CQLLogicalOperator.AND); target.setGroup(finalgroup); query.setTarget(target); List resultList = appService.query(query); // Get a connection to the database using the hibernate configuration int i = 0; for (Iterator resultsIterator = resultList.iterator(); resultsIterator.hasNext();) { SubjectAssignment sa = (SubjectAssignment) resultsIterator.next(); labTestList = printRecord(sa); } } catch (Exception ex) { logDB.error(ex.getMessage()); } return labTestList; } /** * printRecord creates the view object that will properly display the results * @param sa * @param beginDate2 * @param endDate2 * @param request * @return * @throws ParseException */ private ArrayList printRecord(SubjectAssignment sa) throws ParseException { ArrayList list = new ArrayList(); list.add("All"); SortedSet labSet = new TreeSet(); if (sa == null) return null; if (sa!= null) { // Now set the lab information Collection activityCollection = sa.getActivityCollection(); if (activityCollection != null && activityCollection.size() > 0) { for (Iterator activityIterator = activityCollection.iterator(); activityIterator.hasNext();) { SpecimenCollection activity = (SpecimenCollection) activityIterator.next(); Collection specimenCollection = activity.getSpecimenCollection(); if (specimenCollection != null && specimenCollection.size() > 0) { for (Iterator specimenIterator = specimenCollection .iterator(); specimenIterator.hasNext();) { Specimen specimen = (Specimen) specimenIterator.next(); Collection labTestCollection = specimen.getLaboratoryTestCollection(); if (labTestCollection != null && labTestCollection.size() > 0) { for (Iterator labTestIterator = labTestCollection .iterator(); labTestIterator.hasNext();) { LaboratoryTest labTest = (LaboratoryTest) labTestIterator.next(); if (labTest != null) { CD labTestIde = labTest.getLaboratoryTestId(); if (labTestIde != null) { String labTestId = labTestIde.getCode(); labSet.add(labTestId); } } } } } } } } } if(labSet!=null) list.addAll(labSet); return list; } }
package sqlancer.postgres.gen; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import sqlancer.IgnoreMeException; import sqlancer.Randomly; import sqlancer.common.gen.ExpressionGenerator; import sqlancer.postgres.PostgresCompoundDataType; import sqlancer.postgres.PostgresGlobalState; import sqlancer.postgres.PostgresProvider; import sqlancer.postgres.PostgresSchema.PostgresColumn; import sqlancer.postgres.PostgresSchema.PostgresDataType; import sqlancer.postgres.PostgresSchema.PostgresRowValue; import sqlancer.postgres.ast.PostgresAggregate; import sqlancer.postgres.ast.PostgresAggregate.PostgresAggregateFunction; import sqlancer.postgres.ast.PostgresBetweenOperation; import sqlancer.postgres.ast.PostgresBinaryArithmeticOperation; import sqlancer.postgres.ast.PostgresBinaryArithmeticOperation.PostgresBinaryOperator; import sqlancer.postgres.ast.PostgresBinaryBitOperation; import sqlancer.postgres.ast.PostgresBinaryBitOperation.PostgresBinaryBitOperator; import sqlancer.postgres.ast.PostgresBinaryComparisonOperation; import sqlancer.postgres.ast.PostgresBinaryLogicalOperation; import sqlancer.postgres.ast.PostgresBinaryLogicalOperation.BinaryLogicalOperator; import sqlancer.postgres.ast.PostgresBinaryRangeOperation; import sqlancer.postgres.ast.PostgresBinaryRangeOperation.PostgresBinaryRangeComparisonOperator; import sqlancer.postgres.ast.PostgresBinaryRangeOperation.PostgresBinaryRangeOperator; import sqlancer.postgres.ast.PostgresCastOperation; import sqlancer.postgres.ast.PostgresCollate; import sqlancer.postgres.ast.PostgresColumnValue; import sqlancer.postgres.ast.PostgresConcatOperation; import sqlancer.postgres.ast.PostgresConstant; import sqlancer.postgres.ast.PostgresExpression; import sqlancer.postgres.ast.PostgresFunction; import sqlancer.postgres.ast.PostgresFunction.PostgresFunctionWithResult; import sqlancer.postgres.ast.PostgresFunctionWithUnknownResult; import sqlancer.postgres.ast.PostgresInOperation; import sqlancer.postgres.ast.PostgresLikeOperation; import sqlancer.postgres.ast.PostgresOrderByTerm; import sqlancer.postgres.ast.PostgresOrderByTerm.PostgresOrder; import sqlancer.postgres.ast.PostgresPOSIXRegularExpression; import sqlancer.postgres.ast.PostgresPOSIXRegularExpression.POSIXRegex; import sqlancer.postgres.ast.PostgresPostfixOperation; import sqlancer.postgres.ast.PostgresPostfixOperation.PostfixOperator; import sqlancer.postgres.ast.PostgresPrefixOperation; import sqlancer.postgres.ast.PostgresPrefixOperation.PrefixOperator; import sqlancer.postgres.ast.PostgresSimilarTo; public class PostgresExpressionGenerator implements ExpressionGenerator<PostgresExpression> { private final int maxDepth; private final Randomly r; private List<PostgresColumn> columns; private PostgresRowValue rw; private boolean expectedResult; private PostgresGlobalState globalState; private boolean allowAggregateFunctions; private final Map<String, Character> functionsAndTypes; private final List<Character> allowedFunctionTypes; public PostgresExpressionGenerator(PostgresGlobalState globalState) { this.r = globalState.getRandomly(); this.maxDepth = globalState.getOptions().getMaxExpressionDepth(); this.globalState = globalState; this.functionsAndTypes = globalState.getFunctionsAndTypes(); this.allowedFunctionTypes = globalState.getAllowedFunctionTypes(); } public PostgresExpressionGenerator setColumns(List<PostgresColumn> columns) { this.columns = columns; return this; } public PostgresExpressionGenerator setRowValue(PostgresRowValue rw) { this.rw = rw; return this; } public PostgresExpressionGenerator expectedResult() { this.expectedResult = true; return this; } public static PostgresExpression generateExpression(PostgresGlobalState globalState) { return new PostgresExpressionGenerator(globalState).generateExpression(0); } public PostgresExpression generateExpression(int depth) { return generateExpression(depth, PostgresDataType.getRandomType()); } public List<PostgresExpression> generateOrderBy() { List<PostgresExpression> orderBys = new ArrayList<>(); for (int i = 0; i < Randomly.smallNumber(); i++) { orderBys.add(new PostgresOrderByTerm(PostgresColumnValue.create(Randomly.fromList(columns), null), PostgresOrder.getRandomOrder())); } return orderBys; } private enum BooleanExpression { POSTFIX_OPERATOR, NOT, BINARY_LOGICAL_OPERATOR, BINARY_COMPARISON, FUNCTION, CAST, LIKE, BETWEEN, IN_OPERATION, SIMILAR_TO, POSIX_REGEX, BINARY_RANGE_COMPARISON; } private PostgresExpression generateFunctionWithUnknownResult(int depth, PostgresDataType type) { List<PostgresFunctionWithUnknownResult> supportedFunctions = PostgresFunctionWithUnknownResult .getSupportedFunctions(type); // filters functions by allowed type (STABLE 's', IMMUTABLE 'i', VOLATILE 'v') supportedFunctions = supportedFunctions.stream() .filter(f -> allowedFunctionTypes.contains(functionsAndTypes.get(f.getName()))) .collect(Collectors.toList()); if (supportedFunctions.isEmpty()) { throw new IgnoreMeException(); } PostgresFunctionWithUnknownResult randomFunction = Randomly.fromList(supportedFunctions); return new PostgresFunction(randomFunction, type, randomFunction.getArguments(type, this, depth + 1)); } private PostgresExpression generateFunctionWithKnownResult(int depth, PostgresDataType type) { List<PostgresFunctionWithResult> functions = Stream.of(PostgresFunction.PostgresFunctionWithResult.values()) .filter(f -> f.supportsReturnType(type)).collect(Collectors.toList()); // filters functions by allowed type (STABLE 's', IMMUTABLE 'i', VOLATILE 'v') functions = functions.stream().filter(f -> allowedFunctionTypes.contains(functionsAndTypes.get(f.getName()))) .collect(Collectors.toList()); if (functions.isEmpty()) { throw new IgnoreMeException(); } PostgresFunctionWithResult randomFunction = Randomly.fromList(functions); int nrArgs = randomFunction.getNrArgs(); if (randomFunction.isVariadic()) { nrArgs += Randomly.smallNumber(); } PostgresDataType[] argTypes = randomFunction.getInputTypesForReturnType(type, nrArgs); PostgresExpression[] args = new PostgresExpression[nrArgs]; do { for (int i = 0; i < args.length; i++) { args[i] = generateExpression(depth + 1, argTypes[i]); } } while (!randomFunction.checkArguments(args)); return new PostgresFunction(randomFunction, type, args); } private PostgresExpression generateBooleanExpression(int depth) { List<BooleanExpression> validOptions = new ArrayList<>(Arrays.asList(BooleanExpression.values())); if (PostgresProvider.generateOnlyKnown) { validOptions.remove(BooleanExpression.SIMILAR_TO); validOptions.remove(BooleanExpression.POSIX_REGEX); validOptions.remove(BooleanExpression.BINARY_RANGE_COMPARISON); } BooleanExpression option = Randomly.fromList(validOptions); switch (option) { case POSTFIX_OPERATOR: PostfixOperator random = PostfixOperator.getRandom(); return PostgresPostfixOperation .create(generateExpression(depth + 1, Randomly.fromOptions(random.getInputDataTypes())), random); case IN_OPERATION: return inOperation(depth + 1); case NOT: return new PostgresPrefixOperation(generateExpression(depth + 1, PostgresDataType.BOOLEAN), PrefixOperator.NOT); case BINARY_LOGICAL_OPERATOR: PostgresExpression first = generateExpression(depth + 1, PostgresDataType.BOOLEAN); int nr = Randomly.smallNumber() + 1; for (int i = 0; i < nr; i++) { first = new PostgresBinaryLogicalOperation(first, generateExpression(depth + 1, PostgresDataType.BOOLEAN), BinaryLogicalOperator.getRandom()); } return first; case BINARY_COMPARISON: PostgresDataType dataType = getMeaningfulType(); return generateComparison(depth, dataType); case CAST: return new PostgresCastOperation(generateExpression(depth + 1), getCompoundDataType(PostgresDataType.BOOLEAN)); case FUNCTION: return generateFunction(depth + 1, PostgresDataType.BOOLEAN); case LIKE: return new PostgresLikeOperation(generateExpression(depth + 1, PostgresDataType.TEXT), generateExpression(depth + 1, PostgresDataType.TEXT)); case BETWEEN: PostgresDataType type = getMeaningfulType(); return new PostgresBetweenOperation(generateExpression(depth + 1, type), generateExpression(depth + 1, type), generateExpression(depth + 1, type), Randomly.getBoolean()); case SIMILAR_TO: assert !expectedResult; // TODO also generate the escape character return new PostgresSimilarTo(generateExpression(depth + 1, PostgresDataType.TEXT), generateExpression(depth + 1, PostgresDataType.TEXT), null); case POSIX_REGEX: assert !expectedResult; return new PostgresPOSIXRegularExpression(generateExpression(depth + 1, PostgresDataType.TEXT), generateExpression(depth + 1, PostgresDataType.TEXT), POSIXRegex.getRandom()); case BINARY_RANGE_COMPARISON: // TODO element check return new PostgresBinaryRangeOperation(PostgresBinaryRangeComparisonOperator.getRandom(), generateExpression(depth + 1, PostgresDataType.RANGE), generateExpression(depth + 1, PostgresDataType.RANGE)); default: throw new AssertionError(); } } private PostgresDataType getMeaningfulType() { // make it more likely that the expression does not only consist of constant // expressions if (Randomly.getBooleanWithSmallProbability() || columns == null || columns.isEmpty()) { return PostgresDataType.getRandomType(); } else { return Randomly.fromList(columns).getType(); } } private PostgresExpression generateFunction(int depth, PostgresDataType type) { if (PostgresProvider.generateOnlyKnown || Randomly.getBoolean()) { return generateFunctionWithKnownResult(depth, type); } else { return generateFunctionWithUnknownResult(depth, type); } } private PostgresExpression generateComparison(int depth, PostgresDataType dataType) { PostgresExpression leftExpr = generateExpression(depth + 1, dataType); PostgresExpression rightExpr = generateExpression(depth + 1, dataType); return getComparison(leftExpr, rightExpr); } private PostgresExpression getComparison(PostgresExpression leftExpr, PostgresExpression rightExpr) { PostgresBinaryComparisonOperation op = new PostgresBinaryComparisonOperation(leftExpr, rightExpr, PostgresBinaryComparisonOperation.PostgresBinaryComparisonOperator.getRandom()); if (PostgresProvider.generateOnlyKnown && op.getLeft().getExpressionType() == PostgresDataType.TEXT && op.getRight().getExpressionType() == PostgresDataType.TEXT) { return new PostgresCollate(op, "C"); } return op; } private PostgresExpression inOperation(int depth) { PostgresDataType type = PostgresDataType.getRandomType(); PostgresExpression leftExpr = generateExpression(depth + 1, type); List<PostgresExpression> rightExpr = new ArrayList<>(); for (int i = 0; i < Randomly.smallNumber() + 1; i++) { rightExpr.add(generateExpression(depth + 1, type)); } return new PostgresInOperation(leftExpr, rightExpr, Randomly.getBoolean()); } public static PostgresExpression generateExpression(PostgresGlobalState globalState, PostgresDataType type) { return new PostgresExpressionGenerator(globalState).generateExpression(0, type); } public PostgresExpression generateExpression(int depth, PostgresDataType originalType) { PostgresDataType dataType = originalType; if (dataType == PostgresDataType.REAL && Randomly.getBoolean()) { dataType = Randomly.fromOptions(PostgresDataType.INT, PostgresDataType.FLOAT); } if (dataType == PostgresDataType.FLOAT && Randomly.getBoolean()) { dataType = PostgresDataType.INT; } if (!filterColumns(dataType).isEmpty() && Randomly.getBoolean()) { return potentiallyWrapInCollate(dataType, createColumnOfType(dataType)); } PostgresExpression exprInternal = generateExpressionInternal(depth, dataType); return potentiallyWrapInCollate(dataType, exprInternal); } private PostgresExpression potentiallyWrapInCollate(PostgresDataType dataType, PostgresExpression exprInternal) { if (dataType == PostgresDataType.TEXT && PostgresProvider.generateOnlyKnown) { return new PostgresCollate(exprInternal, "C"); } else { return exprInternal; } } private PostgresExpression generateExpressionInternal(int depth, PostgresDataType dataType) throws AssertionError { if (allowAggregateFunctions && Randomly.getBoolean()) { allowAggregateFunctions = false; // aggregate function calls cannot be nested return getAggregate(dataType); } if (Randomly.getBooleanWithRatherLowProbability() || depth > maxDepth) { // generic expression if (Randomly.getBoolean() || depth > maxDepth) { if (Randomly.getBooleanWithRatherLowProbability()) { return generateConstant(r, dataType); } else { if (filterColumns(dataType).isEmpty()) { return generateConstant(r, dataType); } else { return createColumnOfType(dataType); } } } else { if (Randomly.getBoolean()) { return new PostgresCastOperation(generateExpression(depth + 1), getCompoundDataType(dataType)); } else { return generateFunctionWithUnknownResult(depth, dataType); } } } else { switch (dataType) { case BOOLEAN: return generateBooleanExpression(depth); case INT: return generateIntExpression(depth); case TEXT: return generateTextExpression(depth); case DECIMAL: case REAL: case FLOAT: case MONEY: case INET: return generateConstant(r, dataType); case BIT: return generateBitExpression(depth); case RANGE: return generateRangeExpression(depth); default: throw new AssertionError(dataType); } } } private static PostgresCompoundDataType getCompoundDataType(PostgresDataType type) { switch (type) { case BOOLEAN: case DECIMAL: // TODO case FLOAT: case INT: case MONEY: case RANGE: case REAL: case INET: return PostgresCompoundDataType.create(type); case TEXT: // TODO case BIT: if (Randomly.getBoolean() || PostgresProvider.generateOnlyKnown /* * The PQS implementation does not check for * size specifications */) { return PostgresCompoundDataType.create(type); } else { return PostgresCompoundDataType.create(type, (int) Randomly.getNotCachedInteger(1, 1000)); } default: throw new AssertionError(type); } } private enum RangeExpression { BINARY_OP; } private PostgresExpression generateRangeExpression(int depth) { RangeExpression option; List<RangeExpression> validOptions = new ArrayList<>(Arrays.asList(RangeExpression.values())); option = Randomly.fromList(validOptions); switch (option) { case BINARY_OP: return new PostgresBinaryRangeOperation(PostgresBinaryRangeOperator.getRandom(), generateExpression(depth + 1, PostgresDataType.RANGE), generateExpression(depth + 1, PostgresDataType.RANGE)); default: throw new AssertionError(option); } } private enum TextExpression { CAST, FUNCTION, CONCAT, COLLATE } private PostgresExpression generateTextExpression(int depth) { TextExpression option; List<TextExpression> validOptions = new ArrayList<>(Arrays.asList(TextExpression.values())); if (expectedResult) { validOptions.remove(TextExpression.COLLATE); } if (!globalState.getDmbsSpecificOptions().testCollations) { validOptions.remove(TextExpression.COLLATE); } option = Randomly.fromList(validOptions); switch (option) { case CAST: return new PostgresCastOperation(generateExpression(depth + 1), getCompoundDataType(PostgresDataType.TEXT)); case FUNCTION: return generateFunction(depth + 1, PostgresDataType.TEXT); case CONCAT: return generateConcat(depth); case COLLATE: assert !expectedResult; return new PostgresCollate(generateExpression(depth + 1, PostgresDataType.TEXT), globalState == null ? Randomly.fromOptions("C", "POSIX", "de_CH.utf8", "es_CR.utf8") : globalState.getRandomCollate()); default: throw new AssertionError(); } } private PostgresExpression generateConcat(int depth) { PostgresExpression left = generateExpression(depth + 1, PostgresDataType.TEXT); PostgresExpression right = generateExpression(depth + 1); return new PostgresConcatOperation(left, right); } private enum BitExpression { BINARY_OPERATION }; private PostgresExpression generateBitExpression(int depth) { BitExpression option; option = Randomly.fromOptions(BitExpression.values()); switch (option) { case BINARY_OPERATION: return new PostgresBinaryBitOperation(PostgresBinaryBitOperator.getRandom(), generateExpression(depth + 1, PostgresDataType.BIT), generateExpression(depth + 1, PostgresDataType.BIT)); default: throw new AssertionError(); } } private enum IntExpression { UNARY_OPERATION, FUNCTION, CAST, BINARY_ARITHMETIC_EXPRESSION } private PostgresExpression generateIntExpression(int depth) { IntExpression option; option = Randomly.fromOptions(IntExpression.values()); switch (option) { case CAST: return new PostgresCastOperation(generateExpression(depth + 1), getCompoundDataType(PostgresDataType.INT)); case UNARY_OPERATION: PostgresExpression intExpression = generateExpression(depth + 1, PostgresDataType.INT); return new PostgresPrefixOperation(intExpression, Randomly.getBoolean() ? PrefixOperator.UNARY_PLUS : PrefixOperator.UNARY_MINUS); case FUNCTION: return generateFunction(depth + 1, PostgresDataType.INT); case BINARY_ARITHMETIC_EXPRESSION: return new PostgresBinaryArithmeticOperation(generateExpression(depth + 1, PostgresDataType.INT), generateExpression(depth + 1, PostgresDataType.INT), PostgresBinaryOperator.getRandom()); default: throw new AssertionError(); } } private PostgresExpression createColumnOfType(PostgresDataType type) { List<PostgresColumn> columns = filterColumns(type); PostgresColumn fromList = Randomly.fromList(columns); PostgresConstant value = rw == null ? null : rw.getValues().get(fromList); return PostgresColumnValue.create(fromList, value); } final List<PostgresColumn> filterColumns(PostgresDataType type) { if (columns == null) { return Collections.emptyList(); } else { return columns.stream().filter(c -> c.getType() == type).collect(Collectors.toList()); } } public static PostgresExpression generateConstant(Randomly r) { return generateConstant(r, Randomly.fromOptions(PostgresDataType.values())); } public PostgresExpression generateExpressionWithExpectedResult(PostgresDataType type) { this.expectedResult = true; PostgresExpressionGenerator gen = new PostgresExpressionGenerator(globalState).setColumns(columns) .setRowValue(rw); PostgresExpression expr; do { expr = gen.generateExpression(type); } while (expr.getExpectedValue() == null); return expr; } public static PostgresExpression generateConstant(Randomly r, PostgresDataType type) { if (Randomly.getBooleanWithSmallProbability()) { return PostgresConstant.createNullConstant(); } // if (Randomly.getBooleanWithSmallProbability()) { // return PostgresConstant.createTextConstant(r.getString()); switch (type) { case INT: if (Randomly.getBooleanWithSmallProbability()) { return PostgresConstant.createTextConstant(String.valueOf(r.getInteger())); } else { return PostgresConstant.createIntConstant(r.getInteger()); } case BOOLEAN: if (Randomly.getBooleanWithSmallProbability() && !PostgresProvider.generateOnlyKnown) { return PostgresConstant .createTextConstant(Randomly.fromOptions("TR", "TRUE", "FA", "FALSE", "0", "1", "ON", "off")); } else { return PostgresConstant.createBooleanConstant(Randomly.getBoolean()); } case TEXT: return PostgresConstant.createTextConstant(r.getString()); case DECIMAL: return PostgresConstant.createDecimalConstant(r.getRandomBigDecimal()); case FLOAT: return PostgresConstant.createFloatConstant((float) r.getDouble()); case REAL: return PostgresConstant.createDoubleConstant(r.getDouble()); case RANGE: return PostgresConstant.createRange(r.getInteger(), Randomly.getBoolean(), r.getInteger(), Randomly.getBoolean()); case MONEY: return new PostgresCastOperation(generateConstant(r, PostgresDataType.FLOAT), getCompoundDataType(PostgresDataType.MONEY)); case INET: return PostgresConstant.createInetConstant(getRandomInet(r)); case BIT: return PostgresConstant.createBitConstant(r.getInteger()); default: throw new AssertionError(type); } } private static String getRandomInet(Randomly r) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { if (i != 0) { sb.append('.'); } sb.append(r.getInteger() & 255); } return sb.toString(); } public static PostgresExpression generateExpression(PostgresGlobalState globalState, List<PostgresColumn> columns, PostgresDataType type) { return new PostgresExpressionGenerator(globalState).setColumns(columns).generateExpression(0, type); } public static PostgresExpression generateExpression(PostgresGlobalState globalState, List<PostgresColumn> columns, PostgresDataType type, PostgresRowValue rw) { return new PostgresExpressionGenerator(globalState).setColumns(columns).setRowValue(rw).generateExpression(0, type); } public static PostgresExpression generateExpression(PostgresGlobalState globalState, List<PostgresColumn> columns) { return new PostgresExpressionGenerator(globalState).setColumns(columns).generateExpression(0); } public List<PostgresExpression> generateExpressions(int nr) { List<PostgresExpression> expressions = new ArrayList<>(); for (int i = 0; i < nr; i++) { expressions.add(generateExpression(0)); } return expressions; } public PostgresExpression generateExpression(PostgresDataType dataType) { return generateExpression(0, dataType); } public PostgresExpressionGenerator setGlobalState(PostgresGlobalState globalState) { this.globalState = globalState; return this; } public PostgresExpression generateHavingClause() { this.allowAggregateFunctions = true; PostgresExpression expression = generateExpression(PostgresDataType.BOOLEAN); this.allowAggregateFunctions = false; return expression; } public PostgresExpression generateAggregate() { return getAggregate(PostgresDataType.getRandomType()); } private PostgresExpression getAggregate(PostgresDataType dataType) { List<PostgresAggregateFunction> aggregates = PostgresAggregateFunction.getAggregates(dataType); PostgresAggregateFunction agg = Randomly.fromList(aggregates); return generateArgsForAggregate(dataType, agg); } public PostgresAggregate generateArgsForAggregate(PostgresDataType dataType, PostgresAggregateFunction agg) { List<PostgresDataType> types = agg.getTypes(dataType); List<PostgresExpression> args = new ArrayList<>(); for (PostgresDataType argType : types) { args.add(generateExpression(argType)); } return new PostgresAggregate(args, agg); } public PostgresExpressionGenerator allowAggregates(boolean value) { allowAggregateFunctions = value; return this; } @Override public PostgresExpression generatePredicate() { return generateExpression(PostgresDataType.BOOLEAN); } @Override public PostgresExpression negatePredicate(PostgresExpression predicate) { return new PostgresPrefixOperation(predicate, PostgresPrefixOperation.PrefixOperator.NOT); } @Override public PostgresExpression isNull(PostgresExpression expr) { return new PostgresPostfixOperation(expr, PostfixOperator.IS_NULL); } }
package com.alexrnl.jseries.request; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import org.junit.Before; import org.junit.Test; import com.alexrnl.jseries.request.parameters.Id; import com.alexrnl.jseries.request.parameters.Parameter; /** * Test suite for the {@link Request} class. * @author Alex */ public class RequestTest { /** The request to test */ private ConcreteRequest testRequest; /** * Concrete request class for tests. * @author Alex */ private static class ConcreteRequest extends Request { /** * Constructor #1.<br /> * @param verb * the verb of the request. * @param method * the method of the request. */ public ConcreteRequest (final Verb verb, final String method) { super(verb, method); } @Override public void addParameter (final Parameter<?> parameter) { super.addParameter(parameter); } } /** * Set up test attributes. */ @Before public void setUp () { testRequest = new ConcreteRequest(Verb.DELETE, "/test"); testRequest.addParameter(new Id(1)); } /** * Test method for {@link Request#hashCode()}. */ @Test public void testHashCode () { final ConcreteRequest comparing = new ConcreteRequest(Verb.PUT, "/test"); comparing.addParameter(new Id(1)); assertNotEquals(testRequest.hashCode(), comparing.hashCode()); assertEquals(comparing.hashCode(), comparing.hashCode()); assertEquals(testRequest.hashCode(), testRequest.hashCode()); final ConcreteRequest comparingOK = new ConcreteRequest(Verb.DELETE, "/test"); comparingOK.addParameter(new Id(1)); assertEquals(testRequest.hashCode(), comparingOK.hashCode()); } /** * Test method for {@link Request#equals(Object)}. */ @Test public void testEqualsObject () { final ConcreteRequest comparing = new ConcreteRequest(Verb.GET, "/test"); comparing.addParameter(new Id(1)); assertNotEquals(testRequest, comparing); assertEquals(comparing, comparing); assertEquals(testRequest, testRequest); assertNotEquals(testRequest, null); final ConcreteRequest comparingOK = new ConcreteRequest(Verb.DELETE, "/test"); comparingOK.addParameter(new Id(1)); assertEquals(testRequest, comparingOK); } /** * Test method for {@link Request#toString()}. */ @Test public void testToString () { assertEquals("ConcreteRequest [verb=DELETE, method=/test, parameters=[Version [name='v', value='2.1'], Id [name='id', value='1']]]", testRequest.toString()); } }
package com.notnoop.apns.internal; import org.junit.Assert; import org.junit.Test; public class UtilitiesTest { @Test public void testEncodeAndDecode() { String encodedHex = "a1b2d4"; byte[] decoded = Utilities.decodeHex(encodedHex); String encoded = Utilities.encodeHex(decoded); Assert.assertEquals(encodedHex.toLowerCase(), encoded.toLowerCase()); } @Test public void testParsingBytes() { Assert.assertEquals(0xFF00FF00, Utilities.parseBytes(0xFF, 0, 0xFF, 0)); Assert.assertEquals(0x00FF00FF, Utilities.parseBytes(0, 0xFF, 0, 0xFF)); Assert.assertEquals(0xDEADBEEF, Utilities.parseBytes(0xDE, 0xAD, 0xBE, 0xEF)); Assert.assertEquals(0x0EADBEEF, Utilities.parseBytes(0x0E, 0xAD, 0xBE, 0xEF)); Assert.assertTrue(Utilities.parseBytes(0xF0, 0,0,0) < 0); Assert.assertTrue(Utilities.parseBytes(0x80, 0,0,0) < 0); Assert.assertTrue(Utilities.parseBytes(0x70, 0,0,0) > 0); } }