answer
stringlengths
17
10.2M
package net.runelite.rs.api; import net.runelite.api.widgets.Widget; import net.runelite.mapping.Import; public interface RSWidget extends Widget { @Import("dynamicValues") int[][] getDynamicValues(); @Import("children") @Override RSWidget[] getChildren(); @Import("id") @Override int getId(); @Import("parentId") int getRSParentId(); @Import("clickMask") int setClickMask(); @Import("clickMask") void setClickMask(int mask); @Import("boundsIndex") int getBoundsIndex(); @Import("modelId") @Override int getModelId(); @Import("itemIds") int[] getItemIds(); @Import("itemQuantities") int[] getItemQuantities(); @Import("modelType") int getModelType(); @Import("actions") String[] getActions(); @Import("text") String getRSText(); @Import("opBase") String getRSName(); @Import("opBase") void setRSName(String name); @Import("text") @Override void setText(String text); @Import("textColor") @Override int getTextColor(); @Import("textColor") @Override void setTextColor(int textColor); @Import("opacity") int getOpacity(); @Import("relativeX") @Override int getRelativeX(); @Import("relativeX") @Override void setRelativeX(int x); @Import("relativeY") @Override int getRelativeY(); @Import("relativeY") @Override void setRelativeY(int y); @Import("width") @Override int getWidth(); @Import("width") @Override void setWidth(int width); @Import("height") @Override int getHeight(); @Import("height") @Override void setHeight(int height); @Import("isHidden") @Override boolean isSelfHidden(); @Import("isHidden") void setHidden(boolean hidden); @Import("index") int getIndex(); @Import("rotationX") int getRotationX(); @Import("rotationY") int getRotationY(); @Import("rotationZ") int getRotationZ(); @Import("contentType") @Override int getContentType(); @Import("contentType") @Override void setContentType(int contentType); @Import("type") @Override int getType(); @Import("type") @Override void setType(int type); @Import("scrollX") @Override int getScrollX(); @Import("scrollX") @Override void setScrollX(int scrollX); @Import("scrollY") @Override int getScrollY(); @Import("scrollY") @Override void setScrollY(int scrollY); @Import("spriteId") @Override int getSpriteId(); @Import("spriteId") @Override void setSpriteId(int spriteId); @Import("borderThickness") int getBorderThickness(); @Import("itemId") @Override int getItemId(); @Import("itemQuantity") @Override int getItemQuantity(); @Import("originalX") @Override int getOriginalX(); @Import("originalX") @Override void setOriginalX(int originalX); @Import("originalY") @Override int getOriginalY(); @Import("originalY") @Override void setOriginalY(int originalY); @Import("paddingX") @Override int getPaddingX(); @Import("paddingX") @Override void setPaddingX(int paddingX); @Import("paddingY") @Override int getPaddingY(); @Import("paddingY") @Override void setPaddingY(int paddingY); void broadcastHidden(boolean hidden); }
package com.exedio.cope; import java.sql.SQLException; import org.postgresql.Driver; import com.exedio.dsmf.PostgresqlDriver; /** * Still does not work. */ final class PostgresqlDatabase extends Database { static { try { Class.forName(Driver.class.getName()); } catch(ClassNotFoundException e) { throw new RuntimeException(e); } } protected PostgresqlDatabase(final Properties properties) { super(new PostgresqlDriver(), properties); } @Override public String getIntegerType(final long minimum, final long maximum) { return (minimum>=Integer.MIN_VALUE && maximum<=Integer.MAX_VALUE) ? "INTEGER" : "BIGINT"; // TODO: smallint } @Override public String getDoubleType() { return "DOUBLE PRECISION"; } @Override public String getStringType(final int maxLength) { return (maxLength>10485760) ? "TEXT" : "VARCHAR("+maxLength+')'; // in postgres varchar cannot be longer } @Override public String getDayType() { return "DATE"; } // TODO check if there is a suitable column type @Override public String getDateTimestampType() { return null; } // TODO check if there is a suitable column type @Override public String getBlobType(final long maximumLength) { return null; } @Override LimitSupport getLimitSupport() { // TODO support limit clause return LimitSupport.NONE; } @Override void appendLimitClause(final Statement bf, final int start, final int count) { throw new RuntimeException(); } @Override void appendLimitClause2(final Statement bf, final int start, final int count) { throw new RuntimeException(); } @Override protected void appendMatchClauseFullTextIndex(final Statement bf, final StringFunction function, final String value) { // TODO check for full text indexes appendMatchClauseByLike(bf, function, value); } private String extractConstraintName(final SQLException e, final String sqlState, final int vendorCode) { if(!sqlState.equals(e.getSQLState())) return null; if(e.getErrorCode()!=vendorCode) return null; final String m = e.getMessage(); final int end = m.lastIndexOf('\u00ab'); // left pointing double angle quotation mark if(end<0) return null; final int start = m.lastIndexOf('\u00bb', end); // right pointing double angle quotation mark if(start<0) return null; return m.substring(start+1, end); } @Override protected String extractUniqueConstraintName(final SQLException e) { return extractConstraintName(e, "23505", 0); } }
package org.jetel.graph.runtime; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.ThreadMXBean; import java.text.DateFormat; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.Defaults; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.Edge; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.Phase; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.graph.runtime.TrackingDetail.PortType; import org.jetel.util.primitive.DuplicateKeyMap; import org.jetel.util.string.StringUtils; /** * Description of the Class * * @author dpavlis * @since July 29, 2002 * @revision $Revision$ */ public class WatchDog implements Callable<Result>, CloverPost { private GraphExecutor graphExecutor; private int trackingInterval; private Result watchDogStatus; private TransformationGraph graph; private Phase currentPhase; private int currentPhaseNum; private Runtime javaRuntime; private MemoryMXBean memMXB; private ThreadMXBean threadMXB; private BlockingQueue <Message> inMsgQueue; private DuplicateKeyMap outMsgMap; private Throwable causeException; private String causeNodeID; private CloverJMX mbean; private volatile boolean runIt; private boolean threadCpuTimeIsSupported; private boolean provideJMX=true; private IGraphRuntimeContext runtimeContext; private PrintTracking printTracking; public final static String TRACKING_LOGGER_NAME = "Tracking"; public final static String MBEAN_NAME_PREFIX = "CLOVERJMX_"; public final static int WAITTIME_FOR_STOP_SIGNAL = 5000; //milliseconds private int[] _MSG_LOCK=new int[0]; static Log logger = LogFactory.getLog(WatchDog.class); static private MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); private ObjectName jmxObjectName; /** *Constructor for the WatchDog object * * @param graph Description of the Parameter * @param phases Description of the Parameter * @since September 02, 2003 */ public WatchDog(GraphExecutor graphExecutor, TransformationGraph graph, IGraphRuntimeContext runtimeContext) { this.graphExecutor = graphExecutor; graph.setWatchDog(this); this.graph = graph; this.runtimeContext = runtimeContext; currentPhase = null; watchDogStatus = Result.READY; javaRuntime = Runtime.getRuntime(); memMXB=ManagementFactory.getMemoryMXBean(); threadMXB= ManagementFactory.getThreadMXBean(); threadCpuTimeIsSupported = threadMXB.isThreadCpuTimeSupported(); inMsgQueue=new PriorityBlockingQueue<Message>(); outMsgMap=new DuplicateKeyMap(Collections.synchronizedMap(new HashMap())); trackingInterval=runtimeContext.getTrackingInterval(); //is JMX turned on? provideJMX = runtimeContext.useJMX(); } /** Main processing method for the WatchDog object */ public Result call() { watchDogStatus = Result.RUNNING; Result result=Result.N_A; runIt=true; logger.info("Thread started."); logger.info("Running on " + javaRuntime.availableProcessors() + " CPU(s)" + " max available memory for JVM " + javaRuntime.maxMemory() / 1024 + " KB"); // renice - lower the priority printTracking=new PrintTracking(true); mbean=registerTrackingMBean(provideJMX); mbean.graphStarted(); //disabled by Kokon // Thread trackingThread=new Thread(printTracking, TRACKING_LOGGER_NAME); // trackingThread.setPriority(Thread.MIN_PRIORITY); // trackingThread.start(); Phase[] phases = graph.getPhases(); for (currentPhaseNum = 0; currentPhaseNum < phases.length; currentPhaseNum++) { result=executePhase(phases[currentPhaseNum]); if(result == Result.ABORTED) { logger.error("!!! Phase execution aborted !!!"); break; } else if(result == Result.ERROR) { logger.error("!!! Phase finished with error - stopping graph run !!!"); break; } // force running of garbage collector logger.info("Forcing garbage collection ..."); javaRuntime.runFinalization(); javaRuntime.gc(); } mbean.graphFinished(result); // wait to get JMX chance to propagate the message if (mbean.hasClients()) { long timestamp = System.currentTimeMillis(); try { while (runIt && (System.currentTimeMillis() - timestamp) < WAITTIME_FOR_STOP_SIGNAL) Thread.sleep(250); } catch (InterruptedException ex) { // do nothing } } // disabled by Kokon // trackingThread.interrupt(); printPhasesSummary(); //should be in a free() method graph.setWatchDog(null); if(provideJMX) { try { mbs.unregisterMBean(jmxObjectName); } catch (Exception e) { logger.error("JMX error - ObjectName cannot be unregistered.", e); } } return result; } /** * * @since 17.1.2007 */ private CloverJMX registerTrackingMBean(boolean register) { mbean = new CloverJMX(this,register); // register MBean // shall we really register our MBEAN ? if (!register) return mbean; String mbeanId = graph.getId(); // Construct the ObjectName for the MBean we will register try { jmxObjectName = new ObjectName( createMBeanName(mbeanId != null ? mbeanId : graph.getName()) ); // Register the MBean mbs.registerMBean(mbean, jmxObjectName); } catch (MalformedObjectNameException ex) { logger.error(ex); } catch (InstanceAlreadyExistsException e) { logger.error(e); } catch (MBeanRegistrationException e) { logger.error(e); } catch (NotCompliantMBeanException e) { logger.error(e); } return mbean; } /** * Creates identifier for shared JMX mbean. * * @param defaultMBeanName * @return */ public static String createMBeanName(String mbeanIdentifier) { return "org.jetel.graph.runtime:type=" + MBEAN_NAME_PREFIX + (mbeanIdentifier != null ? mbeanIdentifier : ""); } // public void runPhase(int phaseNo){ // watchDogStatus = Result.RUNNING; // logger.info("Thread started."); // logger.info("Running on " + javaRuntime.availableProcessors() + " CPU(s)" // + " max available memory for JVM " + javaRuntime.freeMemory() / 1024 + " KB"); // // renice - lower the priority // currentPhaseNum=-1; // printTracking=new PrintTracking(true); // Thread trackingThread=new Thread(printTracking, TRACKING_LOGGER_NAME); // trackingThread.setPriority(Thread.MIN_PRIORITY); // trackingThread.start(); // for (int i = 0; i < phases.length; i++) { // if (phases[i].getPhaseNum()==phaseNo){ // currentPhaseNum=i; // break; // if (currentPhaseNum>=0){ // switch( executePhase(phases[currentPhaseNum]) ) { // case ABORTED: // watchDogStatus = Result.ABORTED; // logger.error("!!! Phase execution aborted !!!"); // return; // case ERROR: // watchDogStatus = Result.ERROR; // logger.error("!!! Phase finished with error - stopping graph run !!!"); // return; // }else{ // watchDogStatus = Result.ERROR; // logger.error("!!! No such phase: "+phaseNo); // return; // logger.info("Forcing garbage collection ..."); // javaRuntime.runFinalization(); // javaRuntime.gc(); // trackingThread.interrupt(); // watchDogStatus = Result.FINISHED_OK; // printPhasesSummary(); /** * Execute transformation - start-up all Nodes & watch them running * * @param phase Description of the Parameter * @param leafNodes Description of the Parameter * @return Description of the Return Value * @since July 29, 2002 */ public Result watch(Phase phase) throws InterruptedException { long phaseMemUtilizationMax; Iterator leafNodesIterator; Message message; int ticker = Defaults.WatchDog.NUMBER_OF_TICKS_BETWEEN_STATUS_CHECKS; long lastTimestamp; long currentTimestamp; long startTimestamp; long startTimeNano; Map<String, TrackingDetail> tracking = new LinkedHashMap<String, TrackingDetail>( phase.getNodes().size()); List<Node> leafNodes; // let's create a copy of leaf nodes - we will watch them leafNodes = new LinkedList<Node>(phase.getLeafNodes()); // assign tracking info phase.setTracking(tracking); // get current memory utilization phaseMemUtilizationMax = memMXB.getHeapMemoryUsage().getUsed(); // let's take timestamp so we can measure processing startTimestamp = lastTimestamp = System.currentTimeMillis(); // also let's take nanotime to measure how much CPU we spend processing startTimeNano = System.nanoTime(); printTracking.setTrackingInfo(tracking, phase.getPhaseNum()); mbean.setRuningPhase(phase.getPhaseNum()); mbean.setTrackingMap(tracking); mbean.updated(); // entering the loop awaiting completion of work by all leaf nodes while (true) { // wait on error message queue message = inMsgQueue.poll( Defaults.WatchDog.WATCHDOG_SLEEP_INTERVAL, TimeUnit.MILLISECONDS); if (message != null) { switch(message.getType()){ case ERROR: causeException = ((ErrorMsgBody) message.getBody()) .getSourceException(); causeNodeID = message.getSenderID(); logger .fatal("!!! Fatal Error !!! - graph execution is aborting"); logger.error("Node " + message.getSenderID() + " finished with status: " + ((ErrorMsgBody) message.getBody()) .getErrorMessage() + (causeException != null ? " caused by: " + causeException.getMessage() : "")); logger.debug("Node " + message.getSenderID() + " error details:", causeException); abort(); // printProcessingStatus(phase.getNodes().iterator(), // phase.getPhaseNum()); printTracking.execute(true); // print tracking return Result.ERROR; case MESSAGE: synchronized (_MSG_LOCK) { outMsgMap.put(message.getRecipientID(), message); } break; default: // do notfing, just wake up } } // is there any node running ? if (leafNodes.isEmpty()) { // gather tracking at nodes level phaseMemUtilizationMax = gatherNodeLevelTracking(phase, phaseMemUtilizationMax, startTimeNano, tracking); PhaseTrackingDetail phaseTracking = new PhaseTrackingDetail( phase.getPhaseNum(), (int) (System.currentTimeMillis() - startTimestamp), phaseMemUtilizationMax); phase.setPhaseTracking(phaseTracking); logger.info("Execution of phase [" + phase.getPhaseNum() + "] successfully finished - elapsed time(sec): " + phaseTracking.getExecTime() / 1000); // printProcessingStatus(phase.getNodes().iterator(), // phase.getPhaseNum()); printTracking.execute(true);// print tracking return Result.FINISHED_OK; // nothing else to do in this phase } // Check that we still have some nodes running leafNodesIterator = leafNodes.iterator(); while (leafNodesIterator.hasNext()) { Node node = (Node) leafNodesIterator.next(); // is this Node still alive - ? doing something if (!(node.getResultCode() == Result.RUNNING)) { leafNodesIterator.remove(); } } // from time to time perform some task if ((ticker // reinitialize ticker ticker = Defaults.WatchDog.NUMBER_OF_TICKS_BETWEEN_STATUS_CHECKS; // gather tracking at nodes level phaseMemUtilizationMax = gatherNodeLevelTracking(phase, phaseMemUtilizationMax, startTimeNano, tracking); // Display processing status, if it is time currentTimestamp = System.currentTimeMillis(); if (trackingInterval >= 0 && (currentTimestamp - lastTimestamp) >= trackingInterval) { // printProcessingStatus(phase.getNodes().iterator(), // phase.getPhaseNum()); printTracking.execute(false); // print tracking lastTimestamp = currentTimestamp; // update mbean & signal that it was updated mbean.setRunningNodes(leafNodes.size()); mbean.setRunTime(currentTimestamp - startTimestamp); mbean.updated(); } } if (!runIt) { // we were forced to stop execution, stop all Nodes logger.error("User has interrupted graph execution !!!"); abort(); causeNodeID = null; causeException = null; return Result.ABORTED; } } } private long gatherNodeLevelTracking(Phase phase, long phaseMemUtilizationMax, long startTimeNano, Map<String, TrackingDetail> tracking) { // get memory usage mark phaseMemUtilizationMax = Math.max( phaseMemUtilizationMax, memMXB.getHeapMemoryUsage().getUsed() ); long elapsedNano=System.nanoTime()-startTimeNano; // gather tracking information for (Node node : phase.getNodes().values()){ String nodeId=node.getId(); NodeTrackingDetail trackingDetail=(NodeTrackingDetail)tracking.get(nodeId); int inPortsNum=node.getInPorts().size(); int outPortsNum=node.getOutPorts().size(); if (trackingDetail==null){ trackingDetail=new NodeTrackingDetail(nodeId,node.getName(),phase.getPhaseNum(),inPortsNum,outPortsNum); tracking.put(nodeId, trackingDetail); } trackingDetail.timestamp(); trackingDetail.setResult(node.getResultCode()); long threadId=node.getNodeThread().getId(); // ThreadInfo tInfo=threadMXB.getThreadInfo(threadId); if (threadCpuTimeIsSupported) { trackingDetail.updateRunTime(threadMXB.getThreadCpuTime(threadId), threadMXB.getThreadUserTime(threadId), elapsedNano); } else { trackingDetail.updateRunTime(-1, -1, elapsedNano); } int i=0; for (InputPort port : node.getInPorts()){ trackingDetail.updateRows(PortType.IN_PORT, i, port.getInputRecordCounter()); trackingDetail.updateBytes(PortType.IN_PORT, i, port.getInputByteCounter()); i++; } i=0; for (OutputPort port : node.getOutPorts()){ trackingDetail.updateRows(PortType.OUT_PORT, i, port.getOutputRecordCounter()); trackingDetail.updateBytes(PortType.OUT_PORT, i, port.getOutputByteCounter()); if (port instanceof Edge){ trackingDetail.updateWaitingRows(i, ((Edge)port).getBufferedRecords()); } i++; } } return phaseMemUtilizationMax; } /** * Gets the Status of the WatchDog * * @return Result of WatchDog run-time * @since July 30, 2002 * @see org.jetel.graph.Result */ public Result getStatus() { return watchDogStatus; } /** Outputs summary info about executed phases */ void printPhasesSummary() { logger.info(" logger.info("Phase# Finished Status RunTime(sec) MemoryAllocation(KB)"); for (Phase phase : graph.getPhases()) { Object nodeInfo[] = {new Integer(phase.getPhaseNum()), phase.getResult().message(), phase.getPhaseTracking() != null ? new Integer(phase.getPhaseTracking().getExecTimeSec()) : "", phase.getPhaseTracking() != null ? new Integer(phase.getPhaseTracking().getMemUtilizationKB()) : ""}; int nodeSizes[] = {-18, -24, 12, 18}; logger.info(StringUtils.formatString(nodeInfo, nodeSizes)); } logger.info(" } /** * aborts execution of current phase * * @since July 29, 2002 */ public void abort() { watchDogStatus=Result.ABORTED; // iterate through all the nodes and stop them for(Node node : currentPhase.getNodes().values()) { node.abort(); logger.warn("Interrupted node: " + node.getId()); } } /** * Description of the Method * * @param nodesIterator Description of Parameter * @param leafNodesList Description of Parameter * @since July 31, 2002 */ private void startUpNodes(Phase phase) { for(Node node: phase.getNodes().values()) { // Thread nodeThread = new Thread(node, node.getId()); // // this thread is daemon - won't live if main thread ends // nodeThread.setDaemon(true); // node.setNodeThread(nodeThread); // nodeThread.start(); getGraphExecutor().executeNode(node); logger.debug(node.getId()+ " ... started"); } } /** * Description of the Method * * @param phase Description of the Parameter * @return Description of the Return Value */ private Result executePhase(Phase phase) { currentPhase = phase; logger.info("Initialization of phase [" + phase.getPhaseNum() + "]"); try { phase.init(); } catch (ComponentNotReadyException e) { logger.error("Phase initialization failed with reason: " + e.getMessage(), e); return Result.ERROR; } logger.info("Starting up all nodes in phase [" + phase.getPhaseNum() + "]"); startUpNodes(phase); logger.info("Sucessfully started all nodes in phase!"); // watch running nodes in phase try{ watchDogStatus = watch(phase); }catch(InterruptedException ex){ watchDogStatus = Result.ABORTED; } phase.setResult(watchDogStatus); return watchDogStatus; } /* * private void initialize(){ * } */ /** * @return Returns the currentPhaseNum - which phase is currently * beeing executed */ public int getCurrentPhaseNum() { return currentPhaseNum; } /** * @return Returns the trackingInterval - how frequently is the status printed (in ms). */ public int getTrackingInterval() { return trackingInterval; } /** * @param trackingInterval How frequently print the processing status (in ms). */ public void setTrackingInterval(int trackingInterval) { this.trackingInterval = trackingInterval; } static class PrintTracking implements Runnable{ private static int[] ARG_SIZES_WITH_CPU = {-6,-4,28, -5, 9,12,7,8}; private static int[] ARG_SIZES_WITHOUT_CPU = {38, -5, 9,12,7,8}; Map<String,TrackingDetail> tracking; int phaseNo; Log trackingLogger; volatile boolean run; Thread thisThread; boolean displayTracking; PrintTracking(boolean displayTracking){ trackingLogger= LogFactory.getLog(TRACKING_LOGGER_NAME); run=true; this.displayTracking=displayTracking; } void setTrackingInfo(Map<String,TrackingDetail> tracking, int phaseNo){ this.tracking=tracking; this.phaseNo=phaseNo; } public void run() { thisThread=Thread.currentThread(); while (run) { LockSupport.park(); if (displayTracking) printProcessingStatus(false); } } public void execute(boolean finalTracking){ LockSupport.unpark(thisThread); //added by Kokon if (displayTracking) printProcessingStatus(finalTracking); } public void stop(){ run=false; try{ thisThread.join(100); }catch(InterruptedException ex){ } if (thisThread.isAlive()){ thisThread.interrupt(); } } /** * Outputs basic LOG information about graph processing * * @param iterator Description of Parameter * @param phaseNo Description of the Parameter * @since July 30, 2002 */ private void printProcessingStatus(boolean finalTracking) { if (tracking==null) return; //StringBuilder strBuf=new StringBuilder(120); if (finalTracking) trackingLogger.info(" else trackingLogger.info(" // France is here just to get 24hour time format trackingLogger.info("Time: " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.FRANCE). format(Calendar.getInstance().getTime())); trackingLogger.info("Node Status Port #Records #KB Rec/s KB/s"); trackingLogger.info(" for (TrackingDetail nodeDetail : tracking.values()){ Object nodeInfo[] = {nodeDetail.getNodeId(), nodeDetail.getResult().message()}; int nodeSizes[] = {-23, -15}; trackingLogger.info(StringUtils.formatString(nodeInfo, nodeSizes)); //in ports Object portInfo[]; boolean cpuPrinted=false; for(int i=0;i<nodeDetail.getNumInputPorts();i++){ if (i==0){ cpuPrinted=true; final float cpuUsage= (finalTracking ? nodeDetail.getPeakUsageCPU() : nodeDetail.getUsageCPU()); portInfo = new Object[] {" %cpu:",cpuUsage>=0.01f ? Float.toString(cpuUsage) : "..", "In:", Integer.toString(i), Integer.toString(nodeDetail.getTotalRows(PortType.IN_PORT, i)), Long.toString(nodeDetail.getTotalBytes(PortType.IN_PORT, i)>>10), Integer.toString((nodeDetail.getAvgRows(PortType.IN_PORT, i))), Integer.toString(nodeDetail.getAvgBytes(PortType.IN_PORT, i)>>10)}; trackingLogger.info(StringUtils.formatString(portInfo, ARG_SIZES_WITH_CPU)); }else{ portInfo = new Object[] {"In:", Integer.toString(i), Integer.toString(nodeDetail.getTotalRows(PortType.IN_PORT, i)), Long.toString(nodeDetail.getTotalBytes(PortType.IN_PORT, i)>>10), Integer.toString(( nodeDetail.getAvgRows(PortType.IN_PORT, i))), Integer.toString(nodeDetail.getAvgBytes(PortType.IN_PORT, i)>>10)}; trackingLogger.info(StringUtils.formatString(portInfo, ARG_SIZES_WITHOUT_CPU)); } } //out ports for(int i=0;i<nodeDetail.getNumOutputPorts();i++){ if (i==0 && !cpuPrinted){ final float cpuUsage= (finalTracking ? nodeDetail.getPeakUsageCPU() : nodeDetail.getUsageCPU()); portInfo = new Object[] {" %cpu:",cpuUsage>0.01f ? Float.toString(cpuUsage) : "..", "Out:", Integer.toString(i), Integer.toString(nodeDetail.getTotalRows(PortType.OUT_PORT, i)), Long.toString(nodeDetail.getTotalBytes(PortType.OUT_PORT, i)>>10), Integer.toString((nodeDetail.getAvgRows(PortType.OUT_PORT, i))), Integer.toString(nodeDetail.getAvgBytes(PortType.OUT_PORT, i)>>10)}; trackingLogger.info(StringUtils.formatString(portInfo, ARG_SIZES_WITH_CPU)); }else{ portInfo = new Object[] {"Out:", Integer.toString(i), Integer.toString(nodeDetail.getTotalRows(PortType.OUT_PORT, i)), Long.toString(nodeDetail.getTotalBytes(PortType.OUT_PORT, i)>>10), Integer.toString((nodeDetail.getAvgRows(PortType.OUT_PORT, i))), Integer.toString(nodeDetail.getAvgBytes(PortType.OUT_PORT, i)>>10)}; trackingLogger.info(StringUtils.formatString(portInfo, ARG_SIZES_WITHOUT_CPU)); } } } trackingLogger.info(" } } public void sendMessage(Message msg) { inMsgQueue.add(msg); } public Message[] receiveMessage(String recipientNodeID, @SuppressWarnings("unused") final long wait) { Message[] msg = null; synchronized (_MSG_LOCK) { msg=(Message[])outMsgMap.getAll(recipientNodeID, new Message[0]); if (msg!=null) { outMsgMap.remove(recipientNodeID); } } return msg; } public boolean hasMessage(String recipientNodeID) { synchronized (_MSG_LOCK ){ return outMsgMap.containsKey(recipientNodeID); } } public long getUsedMemory(Node node) { return -1; } public long getCpuTime(Node node) { return -1; } /** * Returns exception (reported by Node) which caused * graph to stop processing.<br> * * @return the causeException * @since 7.1.2007 */ public Throwable getCauseException() { return causeException; } /** * Returns ID of Node which caused * graph to stop procesing. * * @return the causeNodeID * @since 7.1.2007 */ public String getCauseNodeID() { return causeNodeID; } /** * Stop execution of graph * * @since 29.1.2007 */ public void stopRun() { this.runIt = false; } /** * @return the graph * @since 26.2.2007 */ public TransformationGraph getTransformationGraph() { return graph; } public void setUseJMX(boolean useJMX) { this.provideJMX = useJMX; } /** * @return instance of graph executor, which was used to run this graph/watchdog */ public GraphExecutor getGraphExecutor() { return graphExecutor; } }
package edu.mit.csail.db.ml.main; import edu.mit.csail.db.ml.conf.ModelDbConfig; import edu.mit.csail.db.ml.server.ModelDbServer; import modeldb.ModelDBService; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TTransportFactory; /** * Main entry point of of the ModelDB Server. * * When you execute this file, you can include the following command line arguments: * (optional) --conf [path_to_conf_file] */ public class Main { public static void main(String[] args) throws Exception { // Read the configuration. This uses the default configuration if no configuration is given in the // command line arguments. ModelDbConfig config = ModelDbConfig.parse(args); // Attempt to launch the server. try { TServerTransport transport = new TServerSocket(config.thriftPort); // We use the binary protocol. TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); TTransportFactory transportFactory = new TFramedTransport.Factory(); // Create a multi-threaded server. Process requests with an instance of // ModelDbServer. TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(transport) .processor(new ModelDBService.Processor<ModelDbServer>(new ModelDbServer( config.dbUser, config.dbPassword, config.jbdcUrl, config.dbType ))) .protocolFactory(protocolFactory) .transportFactory(transportFactory) .minWorkerThreads(1) .maxWorkerThreads(100); TThreadPoolServer server = new TThreadPoolServer(serverArgs); // Launch the server. System.out.printf("Starting the simple server on port %d...\n", config.thriftPort); server.serve(); } catch (Exception e) { e.printStackTrace(); } } }
// BattleShip.java // LEGUP package edu.rpi.phil.legup.puzzles.battleship; import edu.rpi.phil.legup.*; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import javax.swing.ImageIcon; public class BattleShip extends PuzzleModule { static final long serialVersionUID = 532393951L; public static int NUM_SHIPS_SIZE4 = 1; public static int NUM_SHIPS_SIZE3 = 2; public static int NUM_SHIPS_SIZE2 = 3; public static int NUM_SHIPS_SIZE1 = 4; public static final int CELL_UNKNOWN = 0; public static final int CELL_WATER = 1; public static final int CELL_SHIP = 2; public static final int CELL_LEFT_CAP = 10; public static final int CELL_TOP_CAP = 11; public static final int CELL_BOTTOM_CAP = 12; public static final int CELL_RIGHT_CAP = 13; public static final int CELL_CENTER = 14; public static final int CELL_MIDDLE = 15; public static final int FIXED_LEFT_CAP = 20; public static final int FIXED_TOP_CAP = 21; public static final int FIXED_BOTTOM_CAP = 22; public static final int FIXED_RIGHT_CAP = 23; public static final int FIXED_CENTER = 24; public static final int FIXED_MIDDLE = 25; public static final int CELL_FIXED_UNKNOWN = 26; public Map<String, Integer> getSelectableCells() { Map<String, Integer> tmp = new LinkedHashMap<String, Integer>(); tmp.put("blank", CELL_UNKNOWN); tmp.put("water", CELL_WATER); tmp.put("ship", CELL_SHIP); tmp.put("left cap", CELL_LEFT_CAP); tmp.put("top cap", CELL_TOP_CAP); tmp.put("bottom cap", CELL_BOTTOM_CAP); tmp.put("right cap", CELL_RIGHT_CAP); tmp.put("center", CELL_CENTER); tmp.put("middle", CELL_MIDDLE); return tmp; } public Map<String, Integer> getUnselectableCells() { Map<String, Integer> tmp = new LinkedHashMap<String, Integer>(); tmp.put("FIXED_LEFT_CAP", FIXED_LEFT_CAP); tmp.put("FIXED_TOP_CAP", FIXED_TOP_CAP); tmp.put("FIXED_BOTTOM_CAP", FIXED_BOTTOM_CAP); tmp.put("FIXED_RIGHT_CAP", FIXED_RIGHT_CAP); tmp.put("FIXED_CENTER", FIXED_CENTER); tmp.put("FIXED_MIDDLE", FIXED_MIDDLE); tmp.put("CELL_FIXED_UNKNOWN", CELL_FIXED_UNKNOWN); return tmp; } public BattleShip() { } public void mousePressedEvent(BoardState state, Point where) { super.mousePressedEvent(state, where); if (!state.isModifiableCell(where.x, where.y) && Math.abs(state.getCellContents(where.x, where.y)) == CELL_FIXED_UNKNOWN) { state.setModifiableCell(where.x, where.y, true); state.setCellContents(where.x, where.y, FIXED_LEFT_CAP); } } public void labelPressedEvent(BoardState state, int index, int side) { ArrayList<Point> points = new ArrayList<Point>(); BoardState toModify = state.conditionalAddTransition(); if (side == Math.abs(BoardState.LABEL_LEFT) || side == Math.abs(BoardState.LABEL_RIGHT)) { side = BoardState.LABEL_RIGHT; for (int i = 0; i < state.getWidth(); i++) points.add(new Point(i, index)); } else { side = BoardState.LABEL_BOTTOM; for (int i = 0; i < state.getHeight(); i++) points.add(new Point(index, i)); } int numShips = 0, numUnknown = 0; for (Point p : points) { int val = Math.abs(state.getCellContents(p.x, p.y)); if (isShipPart(val)) numShips++; else numUnknown++; } if (numShips == toModify.getLabel(side, index)-40) { for (Point p : points) if (Math.abs(toModify.getCellContents(p.x, p.y)) == CELL_UNKNOWN) toModify.setCellContents(p.x, p.y, CELL_WATER); } else if (numShips+numUnknown == toModify.getLabel(side, index)-40) { for (Point p : points) if (Math.abs(toModify.getCellContents(p.x, p.y)) == CELL_UNKNOWN) toModify.setCellContents(p.x, p.y, CELL_SHIP); } } public boolean isShipPart(int value) { return (value != CELL_WATER && value != CELL_UNKNOWN); } public boolean isConcreteShipPart(int value) { return (isShipPart(value) && value != CELL_SHIP && value != CELL_FIXED_UNKNOWN); } public String getImageLocation(int cellValue) { if (cellValue <= 15) return "images/battleship/image["+cellValue+"].gif"; else if (cellValue >= 20 && cellValue <= 24) return "images/battleship/image["+(cellValue-10)+"].gif"; else if (cellValue == 25) return "images/battleship/image[0].gif"; else if (cellValue >= 30 && cellValue <= 39) return "images/treetent/" + (char)('a' + (cellValue-30)) + ".gif"; else if (cellValue >= 40 && cellValue < 60) return "images/treetent/" + (cellValue - 40) + ".gif"; else return "images/battleship/image[0].gif"; } public BoardImage[] getAllBorderImages() { BoardImage[] s = new BoardImage[30]; int count = 0; for (int x = 0; x < 20; ++x) { s[count++] = new BoardImage("images/treetent/" + (x)+ ".gif",40 + x); } for (int x = 0; x < 10; ++x) { s[count++] = new BoardImage("images/treetent/" + (char)('a' + (x)) + ".gif",30 + x); } return s; } public void drawLeftLabel(Graphics2D g, int val, int x, int y){ drawText( g, x, y, String.valueOf( (char)( 'A'-30 + val ) ) ); } public void drawRightLabel(Graphics2D g, int val, int x, int y){ drawText(g,x, y, String.valueOf(val - 40)); } public void drawTopLabel(Graphics2D g, int val, int x, int y){ drawText(g,x, y, String.valueOf(x + 1)); } public void drawBottomLabel(Graphics2D g, int val, int x, int y){ drawText(g,x, y, String.valueOf(val - 40)); } /*public int getNextCellValue(int x, int y, BoardState boardState) throws IndexOutOfBoundsException { int val = Math.abs(boardState.getCellContents(x,y)); if ((val >= 0 && val < 2) || (val >= 10 && val < 15) || (val >= 20 && val < 26)) return val + 1; else if (val == 2) return 10; else if (val == 15) return 0; else if (val == 26) return 20; else return 0; }*/ public Vector <PuzzleRule> getRules(){ Vector<PuzzleRule> ruleList = new Vector<PuzzleRule>(); ruleList.add(new WaterRowRule()); return ruleList; } public Vector<Contradiction> getContradictions() { Vector<Contradiction> result = new Vector<Contradiction>(); result.add(new Contradiction() { public String getImageName() { return "images/unknown.gif"; } static final long serialVersionUID = 532394123951L; public String checkContradictionRaw(BoardState state) { return null; } }); return result; } public Vector<CaseRule> getCaseRules() { Vector<CaseRule> result = new Vector<CaseRule>(); result.add(new CaseRule() { public String getImageName() { return "images/unknown.gif"; } static final long serialVersionUID = 594123951L; public String checkCaseRuleRaw(BoardState state) { return null; } }); return result; } public boolean checkValidBoardState(BoardState boardState){ /*int height = boardState.getHeight(); int width = boardState.getWidth(); BoardState identifiedShipSegments = identifyShipSegments(boardState); // Check if any two ships are adjacent for (int i=0;i<height;i++){ for (int j=0;j<width;j++){ try{ if (identifiedShipSegments.getCellContents(i,j) == -1){ return false; } } catch (Exception e){ return false; } } } // Check if any row or column value is violated for (int i=0;i<height;i++){ if (!checkRow(boardState, i)){ return false; } } for (int i=0;i<width;i++){ if (!checkCol(boardState, i)){ return false; } } // Check if the number and sizes of ships has not been exceeded if (!countShips(identifiedShipSegments)){ return false; } */ return true; } // As recommended, these are scratched /** public static int translateNumShipSegments(int cellValue){ return (cellValue - 10); } private boolean checkRow(BoardState boardState, int rowNum){ int width = boardState.getWidth(); int numShipSegments = 0; try{ numShipSegments = BattleShip.translateNumShipSegments(boardState.getLabel(BoardState.LABEL_RIGHT, rowNum)); } catch (Exception e){ } for (int i=0;i<width;i++){ try{ if (boardState.getCellContents(rowNum,i) == 2 || boardState.getCellContents(rowNum,i) == 3){ numShipSegments--; } } catch (Exception e){ } } if (numShipSegments < 0){ return false; } else{ return true; } } private boolean checkCol(BoardState boardState, int colNum){ int height = boardState.getHeight(); int numShipSegments = 0; try{ numShipSegments = BattleShip.translateNumShipSegments(boardState.getLabel(BoardState.LABEL_BOTTOM, colNum)); } catch (Exception e){ } for (int i=0;i<height;i++){ try{ if (boardState.getCellContents(i,colNum) == 2 || boardState.getCellContents(i,colNum) == 3){ numShipSegments--; } } catch (Exception e){ } } if (numShipSegments < 0){ return false; } else{ return true; } } private static BoardState identifyShipSegments(BoardState boardState){ int width = boardState.getWidth(); int height = boardState.getHeight(); int shipNumber = 2; // Copy the board state BoardState identifiedShipSegments = boardState.copy(); // Binarize it for (int i=0;i<height;i++){ for (int j=0;j<width;j++){ try{ if (identifiedShipSegments.getCellContents(i,j) == 2 || identifiedShipSegments.getCellContents(i,j) == 3){ identifiedShipSegments.setCellContents(i,j,1); } else{ identifiedShipSegments.setCellContents(i,j,0); } } catch (Exception e){ } } } // Find the segments for (int i=0;i<height;i++){ for (int j=0;j<width;j++){ try{ if (identifiedShipSegments.getCellContents(i,j) == 1){ labelShip(identifiedShipSegments,i,j,shipNumber); shipNumber++; } } catch (Exception e){ } } } // Return the identified board state return identifiedShipSegments; } private static void labelShip(BoardState identifiedBoardState,int row, int col,int shipNumber){ try{ identifiedBoardState.setCellContents(row,col,shipNumber); } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row-1, col) == 1){ labelShip(identifiedBoardState,row-1,col,shipNumber); } else if (identifiedBoardState.getCellContents(row-1, col) != shipNumber && identifiedBoardState.getCellContents(row-1, col) != 0){ identifiedBoardState.setCellContents(row-1,col,-1); } } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row+1, col) == 1){ labelShip(identifiedBoardState,row+1,col,shipNumber); } else if (identifiedBoardState.getCellContents(row+1, col) != shipNumber && identifiedBoardState.getCellContents(row+1, col) != 0){ identifiedBoardState.setCellContents(row+1,col,-1); } } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row, col-1) == 1){ labelShip(identifiedBoardState,row,col-1,shipNumber); } else if (identifiedBoardState.getCellContents(row, col-1) != shipNumber && identifiedBoardState.getCellContents(row, col-1) != 0){ identifiedBoardState.setCellContents(row,col-1,-1); } } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row, col+1) == 1){ labelShip(identifiedBoardState,row,col+1,shipNumber); } else if (identifiedBoardState.getCellContents(row, col+1) != shipNumber && identifiedBoardState.getCellContents(row, col+1) != 0){ identifiedBoardState.setCellContents(row,col+1,-1); } } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row-1, col-1) != 0){ identifiedBoardState.setCellContents(row-1, col-1, -1); } } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row+1, col-1) != 0){ identifiedBoardState.setCellContents(row+1, col-1, -1); } } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row-1, col+1) != 0){ identifiedBoardState.setCellContents(row-1, col+1, -1); } } catch (Exception e){ } try{ if (identifiedBoardState.getCellContents(row+1, col+1) != 0){ identifiedBoardState.setCellContents(row+1, col+1, -1); } } catch (Exception e){ } } public static boolean countShips(BoardState identifiedBoardState){ int num_size4 = BattleShip.NUM_SHIPS_SIZE4; int num_size3 = BattleShip.NUM_SHIPS_SIZE3; int num_size2 = BattleShip.NUM_SHIPS_SIZE2; int num_size1 = BattleShip.NUM_SHIPS_SIZE1; int shipNumber = 2; int size = -1; int width = identifiedBoardState.getWidth(); int height = identifiedBoardState.getHeight(); while(size != 0){ size = 0; for (int i=0;i<height;i++){ for (int j=0;j<width;j++){ try{ if (identifiedBoardState.getCellContents(i,j) == shipNumber){ size++; } } catch (Exception e){ } } } if (size == 4){ num_size4--; } else if (size == 3){ num_size3--; } else if (size == 2){ num_size2--; } else if (size == 1){ num_size1--; } else if (size != 0){ return false; } shipNumber++; } if (num_size4 < 0 || num_size3 < 0 || num_size2 < 0 || num_size1 <0){ return false; } else { return true; } } */ }
package ru.stqa.pft.sandbox; public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello, World!"); } }
package ru.stqa.pft.sandbox; public class MyFirstProgram { public static void main(String[] agrs) { hello("world"); hello("user"); hello("Nat"); Square s = new Square(5); System.out.println("Area of a square with a side " + s.l + " = " + s.area()); Rectangle r = new Rectangle(4, 6); System.out.println("Area of a rectangle with sides " + r.a + " and " + r.b + " = " + r.area()); double x1 = 2; double x2 = 9; double y1 = 2; double y2 = 7; System.out.println("Distance between the dots = " + distance(x1, x2, y1, y2)); } public static void hello(String somebody) { System.out.println("Hello, " + somebody + "!"); } public static double distance (double x1, double x2, double y1, double y2){ return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)); } }
package be.fedict.dcat.scrapers; import be.fedict.dcat.helpers.Storage; import be.fedict.dcat.vocab.MDR_LANG; import java.io.IOException; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentFactory; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.DCAT; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.VCARD4; import org.eclipse.rdf4j.repository.RepositoryException; public abstract class GeonetGmd extends Geonet { public final static String GMD = "http: public final static String API = "/eng/csw?service=CSW&version=2.0.2"; public final static int MAX_RECORDS = 200; public final static String API_RECORDS = API + "&request=GetRecords&resultType=results" + "&outputSchema=" + GMD + "&elementSetName=full&typeNames=gmd:MD_Metadata" + "&maxRecords=" + MAX_RECORDS; public final static String POSITION = "&startPosition="; private final SAXReader sax; private final static Map<String, String> NS = new HashMap<>(); static { NS.put("csw", "http: NS.put("gmd", "http: NS.put("gmx", "http: NS.put("gml", "http: NS.put("gco", "http: NS.put("srv", "http: NS.put("xlink", "http: } public final static String NUM_REC = "csw:GetRecordsResponse/csw:SearchResults/@numberOfRecordsMatched"; public final static String XP_DATASETS = "//gmd:MD_Metadata"; public final static String XP_ID = "gmd:fileIdentifier/gco:CharacterString"; public final static String XP_TSTAMP = "gmd:dateStamp/gco:DateTime"; public final static String XP_META = "gmd:identificationInfo/gmd:MD_DataIdentification"; public final static String XP_KEYWORDS = "gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:keyword"; public final static String XP_TOPIC = "gmd:topicCategory/gmd:MD_TopicCategoryCode"; public final static String XP_THESAURUS = "../gmd:thesaurusName/gmd:CI_Citation/gmd:title/gco:CharacterString"; public final static String XP_LICENSE = "gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:otherConstraints"; public final static String XP_LICENSE2 = "gmd:resourceConstraints/gmd:MD_Constraints/gmd:useLimitation"; public final static String XP_TYPE = "gmd:hierarchyLevel/gmd:MD_ScopeCode/@codeListValue"; public final static String XP_TITLE = "gmd:citation/gmd:CI_Citation/gmd:title"; public final static String XP_DESC = "gmd:abstract"; public final static String XP_PURP = "gmd:purpose"; public final static String XP_ANCHOR = "gmx:Anchor"; public final static String XP_CHAR = "gco:CharacterString"; public final static String XP_STR = "gco:CharacterString"; public final static String XP_STRLNG = "gmd:PT_FreeText/gmd:textGroup/gmd:LocalisedCharacterString"; public final static String XP_CONTACT = "gmd:contact/gmd:CI_ResponsibleParty"; public final static String XP_ORG_NAME = "gmd:organisationName"; public final static String XP_INDIVIDUAL = "gmd:individualName"; public final static String XP_EMAIL = "gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:electronicMailAddress/gco:CharacterString"; public final static String XP_TEMPORAL = "gmd:extent/gmd:EX_Extent/gmd:temporalElement"; public final static String XP_TEMP_EXT = "gmd:EX_TemporalExtent/gmd:extent/gml:TimePeriod/"; public final static String XP_TEMP_BEGIN = XP_TEMP_EXT + "gml:beginPosition"; public final static String XP_TEMP_END = XP_TEMP_EXT + "gml:endPosition"; public final static String XP_QUAL = "gmd:dataQualityInfo/gmd:DQ_DataQuality"; public final static String XP_QUAL_LIN = XP_QUAL + "/gmd:lineage/gmd:LI_Lineage/gmd:statement"; public final static String XP_QUAL_TYPE = XP_QUAL + "/gmd:scope/gmd:DQ_Scope/gmd:level/gmd:MD_ScopeCode/@codeListValue"; public final static String XP_DISTS = "gmd:distributionInfo/gmd:MD_Distribution"; public final static String XP_TRANSF = "/gmd:transferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource"; public final static String XP_DISTS2 = "gmd:distributionInfo/gmd:MD_Distribution/gmd:distributor/gmd:MD_Distributor"; public final static String XP_TRANSF2 = "/*/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource"; public final static String XP_FMT2 = "../../../../*/gmd:MD_Format/gmd:name/gco:CharacterString"; /** * Parse a temporal and store it in the RDF store. * * @param store RDF store * @param uri RDF subject URI * @param node * @throws RepositoryException * @throws MalformedURLException */ protected void parseTemporal(Storage store, IRI uri, Node node) throws RepositoryException, MalformedURLException { String start = node.valueOf(XP_TEMP_BEGIN); String end = node.valueOf(XP_TEMP_END); generateTemporal(store, uri, start, end); } /** * Parse a contact and store it in the RDF store * * @param store RDF store * @param uri RDF subject URI * @param contact contact DOM node * @throws RepositoryException */ protected void parseContact(Storage store, IRI uri, Node contact) throws RepositoryException { String v = ""; Node name = contact.selectSingleNode(XP_ORG_NAME); Node name2 = contact.selectSingleNode(XP_INDIVIDUAL); String email = contact.valueOf(XP_EMAIL); try { v = makeOrgURL(makeHashId(name + email)).toString(); } catch (MalformedURLException e) { logger.error("Could not generate hash url", e); } if (name != null || name2 != null || !email.isEmpty()) { IRI vcard = store.getURI(v); store.add(uri, DCAT.CONTACT_POINT, vcard); store.add(vcard, RDF.TYPE, VCARD4.ORGANIZATION); boolean found = false; for (String lang : getAllLangs()) { found |= parseMulti(store, vcard, name, VCARD4.FN, lang); } if (!found) { for (String lang : getAllLangs()) { parseMulti(store, vcard, name2, VCARD4.FN, lang); } } if (!email.isEmpty()) { store.add(vcard, VCARD4.HAS_EMAIL, store.getURI("mailto:" + email)); } } } /** * Map language code to geonet language string * * @param lang * @return */ protected String mapLanguage(String lang) { return lang.toUpperCase(); } /** * Parse and store multilingual string * * @param store RDF store * @param uri IRI of the dataset * @param node multilingual DOM node * @param property RDF property * @param lang language code * @return boolean * @throws RepositoryException */ protected boolean parseMulti(Storage store, IRI uri, Node node, IRI property, String lang) throws RepositoryException { if (node == null) { return false; } String txten = node.valueOf(XP_STR); String txt = node.valueOf(XP_STRLNG + "[@locale='#" + mapLanguage(lang) + "']"); if (txt == null || txt.isEmpty()) { store.add(uri, property, txten.strip(), "en"); return true; } store.add(uri, property, txt.strip(), lang); return true; } protected void generateDist(Storage store, IRI dataset, Node node, String format, List<String> license) throws MalformedURLException { String url = node.valueOf(XP_DIST_URL); if (url == null || url.isEmpty() || url.equals("undefined")) { logger.warn("No url for distribution"); return; } String id = makeHashId(dataset.toString()) + "/" + makeHashId(url); IRI dist = store.getURI(makeDistURL(id).toString()); logger.debug("Generating distribution {}", dist.toString()); store.add(dataset, DCAT.HAS_DISTRIBUTION, dist); store.add(dist, RDF.TYPE, DCAT.DISTRIBUTION); if (format != null) { store.add(dist, DCTERMS.FORMAT, format); } if (license != null) { for (String l: license) { store.add(dist, DCTERMS.LICENSE, l); } } try { IRI iri = store.getURI(url); store.add(dist, DCAT.DOWNLOAD_URL, store.getURI(url)); } catch (IllegalArgumentException e) { logger.debug("Cannot create download URL for {}", url); } Node title = node.selectSingleNode(XP_DIST_NAME); Node desc = node.selectSingleNode(XP_DIST_DESC); for (String lang : getAllLangs()) { parseMulti(store, dist, title, DCTERMS.TITLE, lang); parseMulti(store, dist, desc, DCTERMS.DESCRIPTION, lang); } } /** * Generate DCAT dataset * * @param dataset * @param id * @param store * @param node * @throws MalformedURLException */ protected void generateDataset(IRI dataset, String id, Storage store, Node node) throws MalformedURLException { logger.info("Generating dataset {}", dataset.toString()); Node metadata = node.selectSingleNode(XP_META); if (metadata == null) { logger.warn("No metadata for {}", id); return; } // try to filter out non-datasets String dtype = node.valueOf(XP_QUAL_TYPE); if (dtype == null || dtype.isEmpty()) { dtype = metadata.valueOf(XP_TYPE); } if (dtype != null && !dtype.isEmpty() && !dtype.equals("dataset")) { logger.warn("Not a dataset: {} is {}", id, dtype); return; } store.add(dataset, DCTERMS.TYPE, store.getURI(INSPIRE_TYPE + "dataset")); store.add(dataset, RDF.TYPE, DCAT.DATASET); store.add(dataset, DCTERMS.IDENTIFIER, id); String date = node.valueOf(XP_TSTAMP); if (date != null && !date.isEmpty()) { try { store.add(dataset, DCTERMS.MODIFIED, DATEFMT.parse(date)); } catch (ParseException ex) { logger.warn("Could not parse date {}", date, ex); } } Node title = metadata.selectSingleNode(XP_TITLE); Node desc = metadata.selectSingleNode(XP_DESC); List<Node> keywords = metadata.selectNodes(XP_KEYWORDS); for (String lang : getAllLangs()) { if (parseMulti(store, dataset, title, DCTERMS.TITLE, lang)) { store.add(dataset, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang)); } parseMulti(store, dataset, desc, DCTERMS.DESCRIPTION, lang); for (Node keyword : keywords) { Node thesaurus = keyword.selectSingleNode(XP_THESAURUS); if (thesaurus == null || !thesaurus.getText().equals("Theme")) { // full text keyword parseMulti(store, dataset, keyword, DCAT.KEYWORD, lang); } else { // actually a theme parseMulti(store, dataset, keyword, DCAT.THEME, lang); } } } // themes List<Node> topics = metadata.selectNodes(XP_TOPIC); for (Node topic: topics) { store.add(dataset, DCAT.THEME, topic.getText()); } // time range Node range = metadata.selectSingleNode(XP_TEMPORAL); if (range != null) { parseTemporal(store, dataset, range); } // frequency String freq = metadata.valueOf(XP_FREQ); if (freq != null) { store.add(dataset, DCTERMS.ACCRUAL_PERIODICITY, freq); } // contact point Node contact = node.selectSingleNode(XP_CONTACT); if (contact != null) { parseContact(store, dataset, contact); } // Distributions can be defined on several (hierarchical) levels List<Node> dists = node.selectNodes(XP_DISTS2 + XP_TRANSF2); // check higher level if no distributions could be found if (dists == null || dists.isEmpty()) { logger.warn("Checking for dists on higher level"); dists = node.selectNodes(XP_DISTS + XP_TRANSF); } if (dists == null || dists.isEmpty()) { logger.warn("No dists for {}", id); return; } List<Node> lic = metadata.selectNodes(XP_LICENSE); List<Node> lic2 = metadata.selectNodes(XP_LICENSE2); if (lic.isEmpty()) { lic = lic2; } else { if (!lic2.isEmpty()) { lic.addAll(lic2); } } List<String> licenses = new ArrayList<>(); for (Node n : lic) { String anchor = n.valueOf(XP_ANCHOR); if (anchor != null && !anchor.isEmpty()) { licenses.add(anchor); } String str = n.valueOf(XP_CHAR); if (str != null && !str.isEmpty()) { licenses.add(str); } } for (Node dist : dists) { // check proto first, in case of a OGC service Node fmt = dist.selectSingleNode(XP_PROTO); if (fmt == null || fmt.getText().startsWith("http") || fmt.getText().startsWith("WWW")) { fmt = dist.selectSingleNode(XP_MIME); if (fmt == null) { fmt = dist.selectSingleNode(XP_FMT2); } } String str = null; if (fmt != null) { str = fmt.getText(); } generateDist(store, dataset, dist, str, licenses); } } /** * Generate DCAT file * * @param cache * @param store * @throws RepositoryException * @throws MalformedURLException */ @Override public void generateDcat(Cache cache, Storage store) throws RepositoryException, MalformedURLException { Set<URL> urls = cache.retrievePageList(); try { for (URL url : urls) { Map<String, Page> map = cache.retrievePage(url); String xml = map.get("all").getContent(); Document doc = sax.read(new StringReader(xml)); List<Node> datasets = doc.selectNodes(XP_DATASETS); for (Node dataset : datasets) { String id = dataset.valueOf(XP_ID); IRI iri = store.getURI(makeDatasetURL(id).toString()); generateDataset(iri, id, store, dataset); } } } catch (DocumentException ex) { logger.error("Error parsing XML"); throw new RepositoryException(ex); } generateCatalog(store); } /** * Get total number of results from XML response * * @param doc * @return number of records */ private int getNumRecords(Document doc) { Node rec = doc.selectSingleNode(NUM_REC); if (rec != null) { String n = rec.getText(); logger.info(n + " records found"); return Integer.valueOf(n); } return MAX_RECORDS; } /** * Scrape DCAT catalog. * * @param cache * @throws IOException */ protected void scrapeCat(Cache cache) throws IOException { for (int pos = 1, recs = MAX_RECORDS; pos < recs; pos += MAX_RECORDS) { URL url = new URL(getBase() + API_RECORDS + POSITION + pos); String xml = makeRequest(url); try { Document doc = sax.read(new StringReader(xml)); if (pos == 1) { recs = getNumRecords(doc); } cache.storePage(url, "all", new Page(url, xml)); } catch (DocumentException ex) { logger.error("Error parsing XML " + url); } } } /** * Scrape DCAT catalog. * * @throws IOException */ @Override public void scrape() throws IOException { logger.info("Start scraping"); Cache cache = getCache(); Set<URL> urls = cache.retrievePageList(); if (urls.isEmpty()) { scrapeCat(cache); } logger.info("Done scraping"); } /** * Constructor * * @param prop * @throws java.io.IOException */ protected GeonetGmd(Properties prop) throws IOException { super(prop); DocumentFactory factory = DocumentFactory.getInstance(); factory.setXPathNamespaceURIs(NS); sax = new SAXReader(); sax.setDocumentFactory(factory); } }
package com.malhartech.dag; import com.malhartech.annotation.PortAnnotation; import com.malhartech.bufferserver.Buffer.Data.DataType; import com.malhartech.util.CircularBuffer; import java.nio.BufferOverflowException; import java.util.HashMap; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // write recoverable AIN /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public abstract class AbstractInputModule extends AbstractBaseModule { private static final Logger logger = LoggerFactory.getLogger(AbstractInputModule.class); private transient final Tuple NO_DATA = new Tuple(DataType.NO_DATA); private transient CircularBuffer<Tuple> controlTuples; private transient HashMap<String, CircularBuffer<Tuple>> afterEndWindows; // what if we did not allow user to emit control tuples. private boolean alive; public AbstractInputModule() { controlTuples = new CircularBuffer<Tuple>(1024); afterEndWindows = new HashMap<String, CircularBuffer<Tuple>>(); } @Override @SuppressWarnings("SleepWhileInLoop") public final void activate(ModuleContext context) { activateSinks(); alive = true; boolean inWindow = false; Tuple t = null; while (alive) { for (int size = controlTuples.size(); size t = controlTuples.get(); switch (t.getType()) { case BEGIN_WINDOW: for (int i = sinks.length; i sinks[i].process(t); } inWindow = true; NO_DATA.setWindowId(t.getWindowId()); beginWindow(); break; case END_WINDOW: endWindow(); inWindow = false; for (int i = sinks.length; i sinks[i].process(t); } /* * we prefer to cater to requests at the end of the window boundary. */ try { CircularBuffer<ModuleContext.ModuleRequest> requests = context.getRequests(); for (int i = requests.size(); i logger.debug("endwindow: " + t.getWindowId() + "lastprocessed: " + context.getLastProcessedWindowId()); requests.get().execute(this, context.getId(), t.getWindowId()); } } catch (Exception e) { logger.warn("Exception while catering to external request {}", e); } context.report(generatedTupleCount, 0L, t.getWindowId()); generatedTupleCount = 0; // i think there should be just one queue instead of one per port - lets defer till we find an example. for (Entry<String, CircularBuffer<Tuple>> e: afterEndWindows.entrySet()) { final Sink s = outputs.get(e.getKey()); if (s != null) { CircularBuffer<?> cb = e.getValue(); for (int i = cb.size(); i s.process(cb.get()); } } } break; default: for (int i = sinks.length; i sinks[i].process(t); } break; } } if (inWindow) { int oldg = generatedTupleCount; int oldp = processedTupleCount; process(NO_DATA); if (generatedTupleCount == oldg && processedTupleCount == oldp) { try { Thread.sleep(spinMillis); } catch (InterruptedException ex) { } } } } logger.debug("{} sending EndOfStream", this); if (inWindow) { EndWindowTuple ewt = new EndWindowTuple(); ewt.setWindowId(t.getWindowId()); for (final Sink output: outputs.values()) { output.process(ewt); } } /* * since we are going away, we should let all the downstream operators know that. */ // we need to think about this as well. EndStreamTuple est = new EndStreamTuple(); if (t != null) { est.setWindowId(t.getWindowId()); } for (final Sink output: outputs.values()) { output.process(est); } deactivateSinks(); } @Override public final void deactivate() { alive = false; } @Override public final Sink connect(String port, Sink component) { Sink retvalue; if (Component.INPUT.equals(port)) { retvalue = new Sink() { @Override @SuppressWarnings("SleepWhileInLoop") public void process(Object payload) { while (true) { try { controlTuples.add((Tuple)payload); break; } catch (BufferOverflowException boe) { try { Thread.sleep(spinMillis); } catch (InterruptedException ex) { break; } } } } }; } else { PortAnnotation pa = getPort(port); if (pa == null) { throw new IllegalArgumentException("Unrecognized Port " + port + " for " + this); } port = pa.name(); if (component == null) { outputs.remove(port); afterEndWindows.remove(port); } else { outputs.put(port, component); afterEndWindows.put(port, new CircularBuffer<Tuple>(bufferCapacity)); } if (sinks != NO_SINKS) { activateSinks(); } retvalue = null; } connected(port, component); return retvalue; } /** * Emit the payload to the specified output port. * * It's expected that the output port is active, otherwise NullPointerException is thrown. * * @param id * @param payload */ public final void emit(String id, Object payload) { if (payload instanceof Tuple) { CircularBuffer<Tuple> cb = afterEndWindows.get(id); if (cb != null) { try { cb.add((Tuple)payload); } catch (BufferOverflowException boe) { logger.error("Emitting too many control tuples within a window, please check your logic or increase the buffer size"); } } } else { final Sink s = outputs.get(id); if (s != null) { outputs.get(id).process(payload); } } generatedTupleCount++; } }
// $Id: FramedInputStream.java,v 1.9 2001/10/24 00:35:37 mdb Exp $ package com.threerings.presents.io; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; /** * The framed input stream reads input that was framed by a framing output * stream. Framing in this case simply means writing the length of the * frame followed by the data associated with the frame so that an entire * frame can be loaded from the network layer before any higher layer * attempts to process it. Additionally, any failure in decoding a frame * won't result in the entire stream being skewed due to the remainder of * the undecoded frame remaining in the input stream. * * <p>The framed input stream reads an entire frame worth of data into its * internal buffer when <code>readFrame()</code> is called. It then * behaves as if this is the only data available on the stream (meaning * that when the data in the frame is exhausted, it will behave as if the * end of the stream has been reached). The buffer can only contain a * single frame at a time, so any data left over from a previous frame * will disappear when <code>readFrame()</code> is called again. * * <p><em>Note:</em> The framing input stream does not synchronize reads * from its internal buffer. It is intended to only be accessed from a * single thread. * * <p>Implementation note: maybe this should derive from * <code>FilterInputStream</code> and be tied to a single * <code>InputStream</code> for its lifetime. */ public class FramedInputStream extends InputStream { public FramedInputStream () { _header = new byte[HEADER_SIZE]; _buffer = new byte[INITIAL_BUFFER_SIZE]; } /** * Reads a frame from the provided input stream, or appends to a * partially read frame. Appends the read data to the existing data * available via the framed input stream's read methods. If the entire * frame data is not yet available, <code>readFrame</code> will return * false, otherwise true. * * <p> The code assumes that it will be able to read the entire frame * header in a single read. The header is only four bytes and should * always arrive at the beginning of a packet, so unless something is * very funky with the networking layer, this should be a safe * assumption. * * @return true if the entire frame has been read, false if the buffer * contains only a partial frame. */ public boolean readFrame (InputStream source) throws IOException { // if the buffer currently contains a complete frame, that means // we're not halfway through reading a frame and that we can start // anew. if (_count == _length) { // read in the frame length int got = source.read(_header, 0, HEADER_SIZE); if (got < 0) { throw new EOFException(); } else if (got == 0) { // TBD: don't log this for now, but look into it later // Log.info("Woke up to read data, but there ain't none. Sigh."); return false; } else if (got < HEADER_SIZE) { String errmsg = "FramedInputStream does not support " + "partially reading the header. Needed " + HEADER_SIZE + " bytes, got " + got + " bytes."; throw new RuntimeException(errmsg); } // now that we've read our new frame length, we can clear out // any prior data _pos = 0; _count = 0; // decode the frame length _length = (_header[0] & 0xFF) << 24; _length += (_header[1] & 0xFF) << 16; _length += (_header[2] & 0xFF) << 8; _length += (_header[3] & 0xFF); // if necessary, expand our buffer to accomodate the frame if (_length > _buffer.length) { // increase the buffer size in large increments _buffer = new byte[Math.max(_buffer.length << 1, _length)]; } } // read the data into the buffer int got = source.read(_buffer, _count, _length-_count); if (got < 0) { throw new EOFException(); } _count += got; return (_count == _length); } /** * Reads the next byte of data from this input stream. The value byte * is returned as an <code>int</code> in the range <code>0</code> to * <code>255</code>. If no byte is available because the end of the * stream has been reached, the value <code>-1</code> is returned. * * <p>This <code>read</code> method cannot block. * * @return the next byte of data, or <code>-1</code> if the end of the * stream has been reached. */ public int read () { return (_pos < _count) ? (_buffer[_pos++] & 0xFF) : -1; } /** * Reads up to <code>len</code> bytes of data into an array of bytes * from this input stream. If <code>pos</code> equals * <code>count</code>, then <code>-1</code> is returned to indicate * end of file. Otherwise, the number <code>k</code> of bytes read is * equal to the smaller of <code>len</code> and * <code>count-pos</code>. If <code>k</code> is positive, then bytes * <code>buf[pos]</code> through <code>buf[pos+k-1]</code> are copied * into <code>b[off]</code> through <code>b[off+k-1]</code> in the * manner performed by <code>System.arraycopy</code>. The value * <code>k</code> is added into <code>pos</code> and <code>k</code> is * returned. * * <p>This <code>read</code> method cannot block. * * @param b the buffer into which the data is read. * @param off the start offset of the data. * @param len the maximum number of bytes read. * * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of the * stream has been reached. */ public int read (byte[] b, int off, int len) { // sanity check the arguments if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } // figure out how much data we'll return if (_pos >= _count) { return -1; } if (_pos + len > _count) { len = _count - _pos; } if (len <= 0) { return 0; } // copy and advance System.arraycopy(_buffer, _pos, b, off, len); _pos += len; return len; } /** * Skips <code>n</code> bytes of input from this input stream. Fewer * bytes might be skipped if the end of the input stream is reached. * The actual number <code>k</code> of bytes to be skipped is equal to * the smaller of <code>n</code> and <code>count-pos</code>. The value * <code>k</code> is added into <code>pos</code> and <code>k</code> is * returned. * * @param n the number of bytes to be skipped. * * @return the actual number of bytes skipped. */ public long skip (long n) { if (_pos + n > _count) { n = _count - _pos; } if (n <= 0) { return 0; } _pos += n; return n; } /** * Returns the number of bytes that can be read from this input stream * without blocking. The value returned is <code>count - pos</code>, * which is the number of bytes remaining to be read from the input * buffer. * * @return the number of bytes remaining to be read from the buffered * frames. */ public int available () { return _count - _pos; } /** * Always returns false as framed input streams do not support * marking. */ public boolean markSupported () { return false; } /** * Does nothing, as marking is not supported. */ public void mark (int readAheadLimit) { // not supported; do nothing } /** * Resets the buffer to the beginning of the buffered frames. */ public void reset () { _pos = 0; } protected byte[] _header; protected int _length; protected byte[] _buffer; protected int _pos; protected int _count; /** The size of the frame header (a 32-bit integer). */ protected static final int HEADER_SIZE = 4; /** The default initial size of the internal buffer. */ protected static final int INITIAL_BUFFER_SIZE = 32; }
// $Id: ClientManager.java,v 1.33 2003/08/20 19:30:52 mdb Exp $ package com.threerings.presents.server; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import com.samskivert.util.IntervalManager; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; import com.threerings.presents.data.ClientObject; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.net.AuthResponse; import com.threerings.presents.net.Credentials; import com.threerings.presents.server.net.*; import com.threerings.presents.server.util.SafeInterval; /** * The client manager is responsible for managing the clients (surprise, * surprise) which are slightly more than just connections. Clients * persist in the absence of connections in case a user goes bye bye * unintentionally and wants to reconnect and continue their session. * * <p> The client manager operates with thread safety because it is called * both from the conmgr thread (to notify of connections showing up or * going away) and from the dobjmgr thread (when clients are given the * boot for application-defined reasons). */ public class ClientManager implements ConnectionObserver, PresentsServer.Reporter, PresentsServer.Shutdowner { /** * Used by {@link #applyToClient}. */ public static interface ClientOp { /** * Called with the resolved client object. */ public void apply (ClientObject clobj); /** * Called if the client resolution fails. */ public void resolutionFailed (Exception e); } /** * Constructs a client manager that will interact with the supplied * connection manager. */ public ClientManager (ConnectionManager conmgr) { // register ourselves as a connection observer conmgr.addConnectionObserver(this); // start up an interval that will check for expired clients and // flush them from the bowels of the server IntervalManager.register(new SafeInterval(PresentsServer.omgr) { public void run () { flushClients(); } }, CLIENT_FLUSH_INTERVAL, null, true); // register as a "state of server" reporter and a shutdowner PresentsServer.registerReporter(this); PresentsServer.registerShutdowner(this); } // documentation inherited from interface public void shutdown () { Log.info("Client manager shutting down " + "[ccount=" + _usermap.size() + "]."); // inform all of our clients that they are being shut down for (Iterator iter = _usermap.values().iterator(); iter.hasNext(); ) { PresentsClient pc = (PresentsClient)iter.next(); try { pc.shutdown(); } catch (Exception e) { Log.warning("Client choked in shutdonw() [client=" + StringUtil.safeToString(pc) + "]."); Log.logStackTrace(e); } } } /** * Instructs the client manager to construct instances of this derived * class of {@link PresentsClient} to managed newly accepted client * connections. */ public void setClientClass (Class clientClass) { // sanity check if (!PresentsClient.class.isAssignableFrom(clientClass)) { Log.warning("Requested to use client class that does not " + "derive from PresentsClient " + "[class=" + clientClass.getName() + "]."); return; } // make a note of it _clientClass = clientClass; } /** * Instructs the client to use instances of this {@link * ClientResolver} derived class when resolving clients in preparation * for starting a client session. */ public void setClientResolverClass (Class clrClass) { // sanity check if (!ClientResolver.class.isAssignableFrom(clrClass)) { Log.warning("Requested to use client resolver class that does " + "not derive from ClientResolver " + "[class=" + clrClass.getName() + "]."); } else { // make a note of it _clrClass = clrClass; } } /** * Enumerates all active client objects. */ public Iterator enumerateClientObjects () { return _objmap.values().iterator(); } /** * Returns the client instance that manages the client session for the * specified authentication username or null if that client is not * currently connected to the server. */ public PresentsClient getClient (String authUsername) { return (PresentsClient)_usermap.get(authUsername.toLowerCase()); } /** * Returns the client object associated with the specified username. * This will return null unless the client object is resolved for some * reason (like they are logged on). */ public ClientObject getClientObject (String username) { return (ClientObject)_objmap.get(toKey(username)); } /** * We convert usernames to lower case in the username to client object * mapping so that we can pass arbitrarily cased usernames (like those * that might be typed in by a "user") straight on through. */ protected final String toKey (String username) { return username.toLowerCase(); } /** * Resolves the specified client, applies the supplied client * operation to them and releases the client. */ public void applyToClient (String username, ClientOp clop) { resolveClientObject(username, new ClientOpResolver(clop)); } /** * Requests that the client object for the specified user be resolved. * If the client object is already resolved, the request will be * processed immediately, otherwise the appropriate client object will * be instantiated and populated by the registered client resolver * (which may involve talking to databases). <em>Note:</em> this * <b>must</b> be paired with a call to {@link #releaseClientObject} * when the caller is finished with the client object. */ public synchronized void resolveClientObject ( String username, ClientResolutionListener listener) { // look to see if the client object is already resolved String key = toKey(username); ClientObject clobj = (ClientObject)_objmap.get(key); if (clobj != null) { clobj.reference(); listener.clientResolved(username, clobj); return; } // look to see if it's currently being resolved ClientResolver clr = (ClientResolver)_penders.get(key); if (clr != null) { // throw this guy onto the bandwagon clr.addResolutionListener(listener); return; } try { // create a client resolver instance which will create our // client object, populate it and notify the listeners clr = (ClientResolver)_clrClass.newInstance(); clr.init(username); clr.addResolutionListener(listener); // the dobject manager which starts the whole business off PresentsServer.omgr.createObject(clr.getClientObjectClass(), clr); } catch (Exception e) { // let the listener know that we're hosed listener.resolutionFailed(username, e); } } /** * Called by the {@link ClientResolver} once a client object has been * resolved. */ protected synchronized void mapClientObject ( String username, ClientObject clobj) { // stuff the object into the mapping table String key = toKey(username); _objmap.put(key, clobj); // and remove the resolution listener _penders.remove(key); } /** * Releases a client object that was obtained via a call to {@link * #resolveClientObject}. If this caller is the last reference, the * object will be flushed and destroyed. */ public void releaseClientObject (String username) { String key = toKey(username); ClientObject clobj = (ClientObject)_objmap.get(key); if (clobj == null) { Log.warning("Requested to release unmapped client object " + "[username=" + username + "]."); Thread.dumpStack(); return; } // decrement the reference count and stop here if there are // remaining references if (clobj.release()) { return; } Log.debug("Destroying client " + clobj.who() + "."); // we're all clear to go; remove the mapping _objmap.remove(key); // and destroy the object itself PresentsServer.omgr.destroyObject(clobj.getOid()); } // documentation inherited public synchronized void connectionEstablished ( Connection conn, AuthRequest req, AuthResponse rsp) { Credentials creds = req.getCredentials(); String username = creds.getUsername().toLowerCase(); // see if a client is already registered with these credentials PresentsClient client = getClient(username); if (client != null) { Log.info("Resuming session [username=" + username + ", conn=" + conn + "]."); client.resumeSession(conn); } else { Log.info("Session initiated [username=" + username + ", conn=" + conn + "]."); // create a new client and stick'em in the table try { // create a client and start up its session client = (PresentsClient)_clientClass.newInstance(); client.startSession(this, creds, conn); // map their client instance _usermap.put(username, client); } catch (Exception e) { Log.warning("Failed to instantiate client instance to " + "manage new client connection '" + conn + "'."); Log.logStackTrace(e); } } // map this connection to this client _conmap.put(conn, client); } // documentation inherited public synchronized void connectionFailed ( Connection conn, IOException fault) { // remove the client from the connection map PresentsClient client = (PresentsClient)_conmap.remove(conn); if (client != null) { Log.info("Unmapped failed client [client=" + client + ", conn=" + conn + ", fault=" + fault + "]."); // let the client know the connection went away client.wasUnmapped(); // and let the client know things went haywire client.connectionFailed(fault); } else if (!(conn instanceof AuthingConnection)) { Log.info("Unmapped connection failed? [conn=" + conn + ", fault=" + fault + "]."); Thread.dumpStack(); } } // documentation inherited public synchronized void connectionClosed (Connection conn) { // remove the client from the connection map PresentsClient client = (PresentsClient)_conmap.remove(conn); if (client != null) { Log.debug("Unmapped client [client=" + client + ", conn=" + conn + "]."); // let the client know the connection went away client.wasUnmapped(); } else { Log.info("Closed unmapped connection '" + conn + "'. " + "Client probably not yet authenticated."); } } /** * Returns the number of client sessions (some may be disconnected). */ public int getClientCount () { return _usermap.size(); } /** * Returns the number of connected clients. */ public int getConnectionCount () { return _conmap.size(); } // documentation inherited from interface PresentsServer.Reporter public void appendReport (StringBuffer report, long now, long sinceLast) { report.append("* presents.ClientManager:\n"); report.append("- Sessions: "); report.append(_usermap.size()).append(" total, "); report.append(_conmap.size()).append(" connected, "); report.append(_penders.size()).append(" pending\n"); report.append("- Mapped users: ").append(_objmap.size()).append("\n"); } /** * Called by the client instance when the client requests a logoff. * This is called from the conmgr thread. */ synchronized void clientDidEndSession (PresentsClient client) { Credentials creds = client.getCredentials(); String username = client.getUsername(); // remove the client from the username map PresentsClient rc = (PresentsClient) _usermap.remove(creds.getUsername().toLowerCase()); // sanity check just because we can if (rc == null) { Log.warning("Unregistered client ended session " + client + "."); Thread.dumpStack(); } else if (rc != client) { Log.warning("Different clients with same username!? " + "[c1=" + rc + ", c2=" + client + "]."); } else { Log.info("Ending session " + client + "."); } } /** * Called once per minute to check for clients that have been * disconnected too long and forcibly end their sessions. */ protected void flushClients () { ArrayList victims = null; long now = System.currentTimeMillis(); // first build a list of our victims (we can't flush clients // directly while iterating due to risk of a // ConcurrentModificationException) Iterator iter = _usermap.values().iterator(); while (iter.hasNext()) { PresentsClient client = (PresentsClient)iter.next(); if (client.checkExpired(now)) { if (victims == null) { victims = new ArrayList(); } victims.add(client); } } if (victims != null) { for (int ii = 0; ii < victims.size(); ii++) { PresentsClient client = (PresentsClient)victims.get(ii); Log.info("Client expired, ending session [client=" + client + ", dtime=" + (now-client.getNetworkStamp()) + "ms]."); client.endSession(); } } } /** Used by {@link #applyToClient}. */ protected class ClientOpResolver implements ClientResolutionListener { public ClientOpResolver (ClientOp clop) { _clop = clop; } // documentation inherited from interface public void clientResolved (String username, ClientObject clobj) { try { _clop.apply(clobj); } catch (Exception e) { Log.warning("Client op failed [username=" + username + ", clop=" + _clop + "]."); Log.logStackTrace(e); } finally { releaseClientObject(username); } } // documentation inherited from interface public void resolutionFailed (String username, Exception reason) { _clop.resolutionFailed(reason); } protected ClientOp _clop; } /** A mapping from auth username to client instances. */ protected HashMap _usermap = new HashMap(); /** A mapping from connections to client instances. */ protected HashMap _conmap = new HashMap(); /** A mapping from usernames to client object instances. */ protected HashMap _objmap = new HashMap(); /** A mapping of pending client resolvers. */ protected HashMap _penders = new HashMap(); /** A set containing the usernames of all locked clients. */ protected HashSet _locks = new HashSet(); /** The client class in use. */ protected Class _clientClass = PresentsClient.class; /** The client resolver class in use. */ protected Class _clrClass = ClientResolver.class; /** The frequency with which we check for expired clients. */ protected static final long CLIENT_FLUSH_INTERVAL = 60 * 1000L; }
package org.apache.zookeeper.server.quorum; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import javax.management.JMException; import org.apache.jute.BinaryOutputArchive; import org.apache.jute.OutputArchive; import org.apache.jute.Record; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooDefs.OpCode; import org.apache.zookeeper.jmx.ManagedUtil; import org.apache.zookeeper.server.DatadirCleanupManager; import org.apache.zookeeper.server.Request; import org.apache.zookeeper.server.ServerCnxnFactory; import org.apache.zookeeper.server.ZKDatabase; import org.apache.zookeeper.server.persistence.FileTxnSnapLog; import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException; import org.apache.zookeeper.server.util.ZxidUtils; import org.apache.zookeeper.txn.CreateTxn; import org.apache.zookeeper.txn.TxnHeader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZooQuorum implements ZooEmbedded, Runnable { private static final Logger LOG = LoggerFactory .getLogger(ZooStandalone.class); private static final String[] ZooArguments = { "./conf/zooConf/zooQuorum.cfg" }; public static QuorumPeer quorumPeer; public static ServerCnxnFactory cnxnFactory; @Override public void run() { init(); } @Override public void init() { LOG.info("Zoo Quorum init called!"); @SuppressWarnings("unused") ZooQuorum tmp = new ZooQuorum(); System.setProperty("jute.maxbuffer", "104857600"); String[] args = ZooArguments; QuorumPeerConfig config = new QuorumPeerConfig(); if (args.length == 1) { try { config.parse(args[0]); } catch (ConfigException e) { LOG.error("Error parsing configuration file!"); } } // Start and schedule the the purge task DatadirCleanupManager purgeMgr = new DatadirCleanupManager( config.getDataDir(), config.getDataLogDir(), config.getSnapRetainCount(), config.getPurgeInterval()); purgeMgr.start(); try { runFromConfig(config); } catch (IOException e) { LOG.error("Error Running from configuration file! " + config); } } @Override public void start() { run(); } @Override public void stop() { Thread.currentThread().stop(); } @Override public void insertPersistent(String blockname, byte[] data) { // String blockname = "/foo"; // String data = "pgaref"; LOG.info("pgaref: Create Internal Called from Cassandra add CommitLOG entry!"); int i = 0; // pgaref -> 23 is the byte len of ZooDefs.Ids.OPEN_ACL_UNSAFE int DataHeaderLength = 16 + blockname.length() + data.length + 23; // ByteBuffer Requestdata = ByteBuffer.allocate(DataHeaderLength); ByteBuffer Requestdata = ByteBuffer.wrap(new byte[DataHeaderLength]); try { Requestdata.clear(); // path name len Requestdata.putInt((blockname.length())); // path name Requestdata.put(blockname.getBytes()); // data len Requestdata.putInt(data.length); // data Requestdata.put(data); // acl null Requestdata.putInt(ZooDefs.Ids.OPEN_ACL_UNSAFE.size()); for (int index = 0; index < ZooDefs.Ids.OPEN_ACL_UNSAFE.size(); index++) { org.apache.zookeeper.data.ACL e1 = ZooDefs.Ids.OPEN_ACL_UNSAFE .get(index); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputArchive boa = BinaryOutputArchive.getArchive(baos); boa.writeRecord(e1, null); Requestdata.put(baos.toByteArray()); } // the flags Requestdata.putInt(CreateMode.PERSISTENT.toFlag()); Requestdata.flip(); } catch (IOException ex) { LOG.info("pgaref - Exception Serializing ACL List"); } catch (BufferOverflowException ex) { LOG.info("BufferOverflowException: " + ex); } /* DATA End here */ long zxid = ZxidUtils.makeZxid(1, i); TxnHeader hdr = new TxnHeader(1, 10 + i, zxid, 30 + i, ZooDefs.OpCode.create); Record txn = new CreateTxn(blockname, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1); Request req = new Request(null, 2285l, 1, OpCode.create, Requestdata, null); req.hdr = hdr; req.txn = txn; i++; // FOR QUORUM quorumPeer.getActiveServer().submitRequest(req); LOG.info("Fake-Request is going to process!!!"); } public void runFromConfig(QuorumPeerConfig config) throws IOException { try { ManagedUtil.registerLog4jMBeans(); } catch (JMException e) { LOG.warn("Unable to register log4j JMX control", e); } LOG.info("Starting quorum peer"); try { cnxnFactory = ServerCnxnFactory.createFactory(); cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns()); quorumPeer = new QuorumPeer(); quorumPeer.setClientPortAddress(config.getClientPortAddress()); quorumPeer.setTxnFactory(new FileTxnSnapLog(new File(config .getDataLogDir()), new File(config.getDataDir()))); quorumPeer.setQuorumPeers(config.getServers()); quorumPeer.setElectionType(config.getElectionAlg()); quorumPeer.setMyid(config.getServerId()); quorumPeer.setTickTime(config.getTickTime()); quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout()); quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout()); quorumPeer.setInitLimit(config.getInitLimit()); quorumPeer.setSyncLimit(config.getSyncLimit()); quorumPeer.setQuorumVerifier(config.getQuorumVerifier()); quorumPeer.setCnxnFactory(cnxnFactory); quorumPeer .setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory())); quorumPeer.setLearnerType(config.getPeerType()); quorumPeer.start(); quorumPeer.join(); } catch (InterruptedException e) { // warn, but generally this is ok LOG.warn("Quorum Peer interrupted", e); } } public static ServerCnxnFactory getConFactory() { return cnxnFactory; } @Override public void delete(String blockname) { // TODO Auto-generated method stub } @Override public void memoryCleanup() { // TODO Auto-generated method stub } //Leading OR Following @Override public String getServerState() { return quorumPeer.getServerState(); } }
package org.jdesktop.swingx.plaf.basic; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.LayoutManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import org.jdesktop.swingx.JXEditorPane; import org.jdesktop.swingx.JXHeader; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.painter.gradient.BasicGradientPainter; import org.jdesktop.swingx.plaf.HeaderUI; import org.jdesktop.swingx.plaf.PainterUIResource; /** * * @author rbair */ public class BasicHeaderUI extends HeaderUI { protected JLabel titleLabel; protected JXEditorPane descriptionPane; protected JLabel imagePanel; private PropertyChangeListener propListener; //this will not be actually put onto the component. Instead, it will //be used behind the scenes for painting the text and icon private LayoutManager layout; /** Creates a new instance of BasicHeaderUI */ public BasicHeaderUI() { } /** * Returns an instance of the UI delegate for the specified component. * Each subclass must provide its own static <code>createUI</code> * method that returns an instance of that UI delegate subclass. * If the UI delegate subclass is stateless, it may return an instance * that is shared by multiple components. If the UI delegate is * stateful, then it should return a new instance per component. * The default implementation of this method throws an error, as it * should never be invoked. */ public static ComponentUI createUI(JComponent c) { return new BasicHeaderUI(); } /** * Configures the specified component appropriate for the look and feel. * This method is invoked when the <code>ComponentUI</code> instance is being installed * as the UI delegate on the specified component. This method should * completely configure the component for the look and feel, * including the following: * <ol> * <li>Install any default property values for color, fonts, borders, * icons, opacity, etc. on the component. Whenever possible, * property values initialized by the client program should <i>not</i> * be overridden. * <li>Install a <code>LayoutManager</code> on the component if necessary. * <li>Create/add any required sub-components to the component. * <li>Create/install event listeners on the component. * <li>Create/install a <code>PropertyChangeListener</code> on the component in order * to detect and respond to component property changes appropriately. * <li>Install keyboard UI (mnemonics, traversal, etc.) on the component. * <li>Initialize any appropriate instance data. * </ol> * @param c the component where this UI delegate is being installed * * @see #uninstallUI * @see javax.swing.JComponent#setUI * @see javax.swing.JComponent#updateUI */ @Override public void installUI(JComponent c) { assert c instanceof JXHeader; JXHeader header = (JXHeader)c; installDefaults(header); titleLabel = new JLabel("Title For Header Goes Here"); titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD)); descriptionPane = new JXEditorPane(); // descriptionPane.setContentType("text/html"); descriptionPane.setEditable(false); descriptionPane.setOpaque(false); descriptionPane.setText("The description for the header goes here.\nExample: Click the Copy Code button to generate the corresponding Java code."); imagePanel = new JLabel(); imagePanel.setIcon(UIManager.getIcon("Header.defaultIcon")); installComponents(header); installListeners(header); } /** * Reverses configuration which was done on the specified component during * <code>installUI</code>. This method is invoked when this * <code>UIComponent</code> instance is being removed as the UI delegate * for the specified component. This method should undo the * configuration performed in <code>installUI</code>, being careful to * leave the <code>JComponent</code> instance in a clean state (no * extraneous listeners, look-and-feel-specific property objects, etc.). * This should include the following: * <ol> * <li>Remove any UI-set borders from the component. * <li>Remove any UI-set layout managers on the component. * <li>Remove any UI-added sub-components from the component. * <li>Remove any UI-added event/property listeners from the component. * <li>Remove any UI-installed keyboard UI from the component. * <li>Nullify any allocated instance data objects to allow for GC. * </ol> * @param c the component from which this UI delegate is being removed; * this argument is often ignored, * but might be used if the UI object is stateless * and shared by multiple components * * @see #installUI * @see javax.swing.JComponent#updateUI */ @Override public void uninstallUI(JComponent c) { assert c instanceof JXHeader; JXHeader header = (JXHeader)c; uninstallDefaults(header); uninstallListeners(header); uninstallComponents(header); titleLabel = null; descriptionPane = null; imagePanel = null; layout = null; } protected void installDefaults(JXHeader h) { Painter p = h.getBackgroundPainter(); if (p == null || p instanceof PainterUIResource) { h.setBackgroundPainter(createBackgroundPainter()); } } protected void uninstallDefaults(JXHeader h) { } protected void installListeners(final JXHeader h) { propListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { onPropertyChange(h, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } }; h.addPropertyChangeListener(propListener); } protected void uninstallListeners(JXHeader h) { h.removePropertyChangeListener(propListener); } protected void onPropertyChange(JXHeader h, String propertyName, Object oldValue, Object newValue) { if ("title".equals(propertyName) || propertyName == null) { titleLabel.setText(h.getTitle()); } else if ("description".equals(propertyName) || propertyName == null) { descriptionPane.setText(h.getDescription()); } else if ("icon".equals(propertyName) || propertyName == null) { imagePanel.setIcon(h.getIcon()); } else if ("enabled".equals(propertyName) || propertyName == null) { boolean enabled = h.isEnabled(); titleLabel.setEnabled(enabled); descriptionPane.setEnabled(enabled); imagePanel.setEnabled(enabled); } } protected void installComponents(JXHeader h) { h.setLayout(new GridBagLayout()); h.add(titleLabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 0, 11), 0, 0)); h.add(descriptionPane, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 0, 11), 0, 0)); h.add(imagePanel, new GridBagConstraints(1, 0, 1, 2, 0.0, 1.0, GridBagConstraints.FIRST_LINE_END, GridBagConstraints.NONE, new Insets(12, 0, 11, 11), 0, 0)); } protected void uninstallComponents(JXHeader h) { h.remove(titleLabel); h.remove(descriptionPane); h.remove(imagePanel); } protected Painter createBackgroundPainter() { return new PainterUIResource(new BasicGradientPainter(0, 0, Color.WHITE, 1, 0, UIManager.getColor("control"))); } @Override public void paint(Graphics g, JComponent c) { JPanel panel = new JPanel(); panel.setOpaque(false); panel.add(titleLabel); panel.add(descriptionPane); panel.add(imagePanel); panel.setSize(c.getSize()); layout.layoutContainer(panel); panel.paint(g); } }
package org.streamingpool.core.domain; import static io.reactivex.BackpressureStrategy.DROP; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import org.reactivestreams.Publisher; import io.reactivex.Flowable; import io.reactivex.subjects.PublishSubject; public final class ErrorDeflector { private final PublishSubject<Throwable> errorStream = PublishSubject.create(); public static final ErrorDeflector create() { return new ErrorDeflector(); } public <S, T> io.reactivex.functions.Function<S, Optional<T>> emptyOnError(Function<S, T> function) { return val -> { try { return Optional.of(function.apply(val)); } catch (Exception e) { deflectOperationIncomingError(function, val, e); return Optional.empty(); } }; } public <T> io.reactivex.functions.Predicate<T> falseOnError(Predicate<T> predicate) { return it -> { try { return predicate.test(it); } catch (Exception e) { deflectOperationIncomingError(predicate, it, e); return false; } }; } private <T> void deflectOperationIncomingError(Object operation, T incoming, Exception e) { ErrorStreamException exception = new ErrorStreamException( "Error in operation " + operation + ". Incoming value: " + incoming, e); errorStream.onNext(exception); } public <T> ErrorStreamPair<T> stream(Publisher<T> dataPublisher) { return ErrorStreamPair.ofDataError(dataPublisher, errorStream.toFlowable(DROP)); } public <T> ErrorStreamPair<T> streamNonEmpty(Publisher<Optional<T>> optionalPublisher) { return stream(Flowable.fromPublisher(optionalPublisher).filter(Optional::isPresent).map(Optional::get)); } }
package lapd.databases.neo4j; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.imp.pdb.facts.IMapWriter; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.io.IValueTextReader; import org.eclipse.imp.pdb.facts.io.StandardTextReader; import org.eclipse.imp.pdb.facts.type.ITypeVisitor; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; public class GraphDbValueRetrievalVisitor implements ITypeVisitor<IValue, GraphDbMappingException>{ private final Node node; private final IValueFactory valueFactory; private final TypeStore typeStore; public GraphDbValueRetrievalVisitor(Node node, IValueFactory valueFactory, TypeStore typeStore) { this.node = node; this.valueFactory = valueFactory; this.typeStore = typeStore; } @Override public IValue visitString(Type type) throws GraphDbMappingException { return valueFactory.string(node.getProperty(PropertyNames.STRING).toString()); } @Override public IValue visitInteger(Type type) throws GraphDbMappingException { return valueFactory.integer(node.getProperty(PropertyNames.INTEGER).toString()); } @Override public IValue visitReal(Type type) throws GraphDbMappingException { return valueFactory.real(node.getProperty(PropertyNames.REAL).toString()); } @Override public IValue visitBool(Type type) throws GraphDbMappingException { return valueFactory.bool((Boolean)node.getProperty(PropertyNames.BOOLEAN)); } @Override public IValue visitRational(Type type) throws GraphDbMappingException { String numerator = node.getProperty(PropertyNames.NUMERATOR).toString(); String denominator = node.getProperty(PropertyNames.DENOMINATOR).toString(); return valueFactory.rational(numerator + "r" + denominator); } @Override public IValue visitSourceLocation(Type type) throws GraphDbMappingException { String locString = node.getProperty(PropertyNames.SOURCE_LOCATION).toString(); IValueTextReader reader = new StandardTextReader(); try { return reader.read(valueFactory, TypeFactory.getInstance().sourceLocationType(), new StringReader(locString)); } catch (Exception e) { throw new GraphDbMappingException(e.getMessage()); } } @Override public IValue visitDateTime(Type type) throws GraphDbMappingException { // datetime deviates by one hour, hence the -3600000 return valueFactory.datetime((Long)node.getProperty(PropertyNames.DATE_TIME) - 3600000); } @Override public IValue visitList(Type type) throws GraphDbMappingException { if (!hasHead()) return valueFactory.list(TypeFactory.getInstance().voidType()); List<IValue> elementList = getElementValues(type); return valueFactory.list(elementList.toArray(new IValue[elementList.size()])); } @Override public IValue visitSet(Type type) throws GraphDbMappingException { if (!hasHead()) return valueFactory.set(TypeFactory.getInstance().voidType()); List<IValue> elementList = getElementValues(type); return valueFactory.set(elementList.toArray(new IValue[elementList.size()])); } @Override public IValue visitNode(Type type) throws GraphDbMappingException { String nodeName = node.getProperty(PropertyNames.NODE).toString(); if (!node.hasRelationship(Direction.OUTGOING, RelTypes.HEAD)) return valueFactory.node(nodeName); List<IValue> valueList = new ArrayList<IValue>(); Node currentNode = node.getSingleRelationship(RelTypes.HEAD, Direction.OUTGOING).getEndNode(); valueList.add(new TypeDeducer(currentNode, typeStore).getType().accept(new GraphDbValueRetrievalVisitor(currentNode, valueFactory, typeStore))); while (currentNode.hasRelationship(Direction.OUTGOING, RelTypes.NEXT_ELEMENT)) { currentNode = currentNode.getSingleRelationship(RelTypes.NEXT_ELEMENT, Direction.OUTGOING).getEndNode(); valueList.add(new TypeDeducer(currentNode, typeStore).getType().accept(new GraphDbValueRetrievalVisitor(currentNode, valueFactory, typeStore))); } if (!hasAnnotations()) return valueFactory.node(nodeName, valueList.toArray(new IValue[valueList.size()])); Map<String, IValue> annotations = getAnnotations(); return valueFactory.node(nodeName, annotations, valueList.toArray(new IValue[valueList.size()])); } @Override public IValue visitConstructor(Type type) throws GraphDbMappingException { if (!hasHead()) return valueFactory.constructor(type); List<IValue> valueList = getFields(type); if (!hasAnnotations()) return valueFactory.constructor(type, valueList.toArray(new IValue[valueList.size()])); Map<String, IValue> annotations = getAnnotations(); return valueFactory.constructor(type, annotations, valueList.toArray(new IValue[valueList.size()])); } @Override public IValue visitTuple(Type type) throws GraphDbMappingException { if (!hasHead()) return valueFactory.tuple(); List<IValue> valueList = getFields(type); return valueFactory.tuple(valueList.toArray(new IValue[valueList.size()])); } @Override public IValue visitMap(Type type) throws GraphDbMappingException { IMapWriter mapWriter = valueFactory.mapWriter(); if (!hasHead()) return mapWriter.done(); Node currentKeyNode = node.getSingleRelationship(RelTypes.HEAD, Direction.OUTGOING).getEndNode(); Node currentValueNode = currentKeyNode.getSingleRelationship(RelTypes.MAP_KEY_VALUE, Direction.OUTGOING).getEndNode(); mapWriter.put(type.getKeyType().accept(new GraphDbValueRetrievalVisitor(currentKeyNode, valueFactory, typeStore)), type.getValueType().accept(new GraphDbValueRetrievalVisitor(currentValueNode, valueFactory, typeStore))); while (currentKeyNode.hasRelationship(Direction.OUTGOING, RelTypes.NEXT_ELEMENT)) { currentKeyNode = currentKeyNode.getSingleRelationship(RelTypes.NEXT_ELEMENT, Direction.OUTGOING).getEndNode(); currentValueNode = currentKeyNode.getSingleRelationship(RelTypes.MAP_KEY_VALUE, Direction.OUTGOING).getEndNode(); mapWriter.put(type.getKeyType().accept(new GraphDbValueRetrievalVisitor(currentKeyNode, valueFactory, typeStore)), type.getValueType().accept(new GraphDbValueRetrievalVisitor(currentValueNode, valueFactory, typeStore))); } return mapWriter.done(); } @Override public IValue visitExternal(Type type) throws GraphDbMappingException { throw new GraphDbMappingException("Cannot handle external types."); } @Override public IValue visitNumber(Type type) throws GraphDbMappingException { return new TypeDeducer(node, typeStore).getType().accept(this); } @Override public IValue visitAlias(Type type) throws GraphDbMappingException { return type.getAliased().accept(this); } @Override public IValue visitAbstractData(Type type) throws GraphDbMappingException { String name = node.getProperty(PropertyNames.NODE).toString(); return visitConstructor(typeStore.lookupConstructor(type, name).iterator().next()); } @Override public IValue visitValue(Type type) throws GraphDbMappingException { return new TypeDeducer(node, typeStore).getType().accept(this); } @Override public IValue visitVoid(Type type) throws GraphDbMappingException { throw new GraphDbMappingException("Cannot handle void types."); } @Override public IValue visitParameter(Type type) throws GraphDbMappingException { return type.getBound().accept(this); } private List<IValue> getElementValues(Type type) throws GraphDbMappingException { List<IValue> valueList = new ArrayList<IValue>(); Type elementType = type.getElementType(); Node currentNode = node.getSingleRelationship(RelTypes.HEAD, Direction.OUTGOING).getEndNode(); valueList.add(elementType.accept(new GraphDbValueRetrievalVisitor(currentNode, valueFactory, typeStore))); while (currentNode.hasRelationship(Direction.OUTGOING, RelTypes.NEXT_ELEMENT)) { currentNode = currentNode.getSingleRelationship(RelTypes.NEXT_ELEMENT, Direction.OUTGOING).getEndNode(); valueList.add(elementType.accept(new GraphDbValueRetrievalVisitor(currentNode, valueFactory, typeStore))); } return valueList; } private boolean hasHead() { return node.hasRelationship(Direction.OUTGOING, RelTypes.HEAD); } private boolean hasAnnotations() { return node.hasRelationship(Direction.OUTGOING, RelTypes.ANNOTATION); } private Map<String, IValue> getAnnotations() throws GraphDbMappingException { Map<String, IValue> annotations = new HashMap<String, IValue>(); for (Relationship rel : node.getRelationships(Direction.OUTGOING, RelTypes.ANNOTATION)) { Node annotationNode = rel.getEndNode(); String annotationName = annotationNode.getProperty(PropertyNames.ANNOTATION).toString(); IValue annotationValue = new TypeDeducer(annotationNode, typeStore).getType().accept(new GraphDbValueRetrievalVisitor(annotationNode, valueFactory, typeStore)); annotations.put(annotationName, annotationValue); } return annotations; } private List<IValue> getFields(Type type) throws GraphDbMappingException { List<IValue> valueList = new ArrayList<IValue>(); Node currentNode = node.getSingleRelationship(RelTypes.HEAD, Direction.OUTGOING).getEndNode(); valueList.add(new TypeDeducer(currentNode, typeStore).getType().accept(new GraphDbValueRetrievalVisitor(currentNode, valueFactory, typeStore))); while (currentNode.hasRelationship(Direction.OUTGOING, RelTypes.NEXT_ELEMENT)) { currentNode = currentNode.getSingleRelationship(RelTypes.NEXT_ELEMENT, Direction.OUTGOING).getEndNode(); valueList.add(new TypeDeducer(currentNode, typeStore).getType().accept(new GraphDbValueRetrievalVisitor(currentNode, valueFactory, typeStore))); } return valueList; } }
/// 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; 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(); System.out.println("******************outer*****"); 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; atOrPastLastChange = false; 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(); if(symbol == null) break; continue; } } currentState = as.getState(); //normal transition if(as.getAction() == 0){ if(!second.next()) break; System.out.println("*********first " + second); System.out.println("*********second " + second); System.out.println("*********lastRepl " + lastRepl); 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(); } } 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() ) + ">"; } }
package magpie.optimization.rankers; import java.util.List; import magpie.data.BaseEntry; import magpie.data.MultiPropertyEntry; import expr.*; import java.util.LinkedList; import magpie.data.MultiPropertyDataset; /** * Use a formula of several properties. Requires that entries are instances of * {@linkplain MultiPropertyEntry}. * * <usage><p><b>Usage</b>: $&lt;data template&gt; &lt;formula...&gt; * <pr><br><i>data template</i>: Template used to determine whether properties exist in dataset * <pr><br><i>formula</i>: Formula to use as objective function. Property names must be surrounded by #{}'s. * <br>Example formula: #{volume_pa} * #{bandgap}</usage> * * @author Logan Ward */ public class PropertyFormulaRanker extends MultiObjectiveEntryRanker { /** Engine used to evaluate formula */ private Expr Evaluator = null; /** Holds links to the value of variables in the Expr formula */ final private List<Variable> Variables = new LinkedList<>(); /** Index of properties used in the formula */ private int[] PropertyIndex; @Override public PropertyFormulaRanker clone() { PropertyFormulaRanker x = (PropertyFormulaRanker) super.clone(); x.PropertyIndex = PropertyIndex.clone(); return x; } @Override public void setOptions(List<Object> Options) throws Exception { String formula; MultiPropertyDataset template; try { template = (MultiPropertyDataset) Options.get(0); formula = Options.get(1).toString(); for (int i=2; i<Options.size(); i++) { formula += " " + Options.get(i).toString(); } } catch (Exception e) { throw new Exception(printUsage()); } setFormula(template, formula); } @Override public String printUsage() { return "Usage: $<data template> <formula...>"; } @Override public void train(MultiPropertyDataset data) { // Nothing to do } @Override public String[] getObjectives() { String[] output = new String[Variables.size()]; for (int i=0; i < Variables.size(); i++) { output[i] = Variables.get(i).name(); } return output; } /** * Define the formula used by this class. Names of properties used in the * calculation should be surrounded #{}'s. * @param formula Formula to be used * @throws Exception If parsing failed or template does not contain */ public void setFormula(MultiPropertyDataset template, String formula) throws Exception { // Find variables in the formula formula = extractVariables(formula); // Ensure dataset contains those variables PropertyIndex = new int[Variables.size()]; for (int i=0; i < Variables.size(); i++) { PropertyIndex[i] = template.getPropertyIndex(Variables.get(i).name()); if (PropertyIndex[i] == -1) { throw new Exception("Dataset does not contain property: " + Variables.get(i).name()); } } // Generate the expression Parser Parser = new Parser(); // Define the variable set for (Variable var : Variables) { Parser.allow(var); } // Parse the expression Evaluator = Parser.parseString(formula); } /** * Parse a formula to find names of properties used as variables. They should * be surrounded by #{}'s. Stores result internally. * @param Formula Formula to be parsed * @return Formula in a form parsable by Expr */ protected String extractVariables(String Formula) throws Exception { // Prepare Variables.clear(); List<String> variableNames = new LinkedList<>(); // Parse formula int curPos = 0; // Current position of parser while (true) { // Find the next variable int varPos = Formula.indexOf("#{", curPos); if (varPos == -1) break; // No more variables int varEnd = Formula.indexOf("}", varPos); if (varEnd == -1) throw new Exception("Poorly formed expression - Can't find }"); curPos = varEnd; // Move up the serach String varName = Formula.substring(varPos + 2, varEnd); variableNames.add(varName); } // Create a list of variables with the following order // Also, remove the #{<...>} notation from the formula string for (String varName : variableNames) { Variable newVariable = Variable.make(varName); Formula = Formula.replace("#{" + varName + "}", varName); Variables.add(newVariable); } return Formula; } @Override public double objectiveFunction(BaseEntry Entry) { if (! (Entry instanceof MultiPropertyEntry)) { throw new Error("Entry must be a MultiPropertyEntry"); } MultiPropertyEntry e = (MultiPropertyEntry) Entry; for (int i=0; i<Variables.size(); i++) { double x = UseMeasured ? e.getMeasuredProperty(PropertyIndex[i]) : e.getPredictedProperty(PropertyIndex[i]); Variables.get(i).setValue(x); } return Evaluator.value(); } }
package ed.appserver.templates.djang10; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Set; import ed.appserver.JSFileLibrary; import ed.appserver.jxp.JxpSource; import ed.io.StreamUtil; import ed.js.JSArray; import ed.js.JSFunction; import ed.js.JSObject; import ed.js.engine.JSCompiledScript; import ed.js.engine.Scope; import ed.util.Dependency; import ed.util.Pair; public class Djang10Source extends JxpSource { public static final boolean DEBUG = Boolean.getBoolean("DEBUG.DJANG10"); private final Djang10Content content; private Djang10CompiledScript compiledScript; public Djang10Source(File f) { content = new Djang10File(f); compiledScript = null; } public Djang10Source(String content) { this.content = new DJang10String(content); compiledScript = null; } public synchronized JSFunction getFunction() throws IOException { if(_needsParsing() || compiledScript == null) { if(DEBUG) System.out.println("Parsing " + content.getDebugName()); compiledScript = null; _lastParse = lastUpdated(); _dependencies.clear(); NodeList nodes = null; Collection<Library> libraries; String contents = getContent(); Parser parser = new Parser(contents); JSHelper jsHelper = JSHelper.get(Scope.getThreadLocal()); for(Pair<JxpSource,Library> lib : jsHelper.getDefaultLibraries()) { parser.add_dependency(lib.first); parser.add_library(lib.second); } nodes = parser.parse(Scope.getThreadLocal(), new JSArray()); libraries = parser.getLoadedLibraries(); _dependencies.addAll(parser.get_dependencies()); compiledScript = new Djang10CompiledScript(nodes, libraries); compiledScript.set(JxpSource.JXP_SOURCE_PROP, this); if(DEBUG) System.out.println("Done Parsing " + content.getDebugName()); } return compiledScript; } public File getFile() { return (content instanceof Djang10File)? ((Djang10File)content).getFile() : null; } public long lastUpdated(Set<Dependency> visitedDeps) { visitedDeps.add(this); long lastUpdated = content.lastUpdated(); for(Dependency dep : _dependencies) if(!visitedDeps.contains(dep)) lastUpdated = Math.max(lastUpdated, dep.lastUpdated(visitedDeps)); return lastUpdated; } protected String getContent() throws IOException { return content.getContent(); } protected InputStream getInputStream() throws IOException { return content.getInputStream(); } public String getName() { return content.getName(); } public NodeList compile(Scope scope) { String contents; try { contents = getContent(); } catch (IOException e) { throw new TemplateException("Failed to read the template source from: " + getFile(), e); } Parser parser = new Parser(contents); JSHelper jsHelper = JSHelper.get(scope); for(Pair<JxpSource,Library> lib : jsHelper.getDefaultLibraries()) { parser.add_dependency(lib.first); parser.add_library(lib.second); } return parser.parse(scope, new JSArray()); } public static JSHelper install(Scope scope) { JSHelper jsHelper = JSHelper.install(scope); //FIXME: this whole injection is ugly, fix it! JSFileLibrary js = JSFileLibrary.loadLibraryFromEd("ed/appserver/templates/djang10/js", "djang10", scope); for(String jsFile : new String[] {"defaulttags", "loader_tags", "defaultfilters", "tengen_extras"}) { JSFunction jsFileFn = (JSFunction)js.get(jsFile); Library lib = (Library) jsHelper.evalLibrary.call(scope, jsFileFn); jsHelper.addDefaultLibrary((JxpSource)jsFileFn.get(JxpSource.JXP_SOURCE_PROP), lib); } JSFileLibrary defaultLoaders = (JSFileLibrary)js.get("loaders"); JSArray loaders = (JSArray)jsHelper.get("TEMPLATE_LOADERS"); for(String jsFile : new String[] { "filesystem", "absolute", "site_relative" }) { JSCompiledScript loaderFile = (JSCompiledScript)defaultLoaders.get(jsFile); Scope child = scope.child(); loaderFile.call(child); JSFunction loaderFunc = (JSFunction)((JSObject)((JSObject)jsHelper.get("loaders")).get(jsFile)).get("load_template_source"); loaders.add(loaderFunc); } return jsHelper; } private static interface Djang10Content { public String getContent() throws IOException; public InputStream getInputStream() throws IOException; public long lastUpdated(); public String getName(); public String getDebugName(); } private static class Djang10File implements Djang10Content { private final File file; public Djang10File(File file) { this.file = file; } public String getContent() throws IOException { return StreamUtil.readFully(file); } public InputStream getInputStream() throws IOException { return new FileInputStream(file); } public long lastUpdated() { return file.lastModified(); } public File getFile() { return file; } public String getName() { return file.toString(); } public String getDebugName() { return file.toString(); } } private static class DJang10String implements Djang10Content { private final String content; private final long timestamp; public DJang10String(String content) { this.content = content; timestamp = System.currentTimeMillis(); } public String getContent() throws IOException { return content; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(content.getBytes()); } public long lastUpdated() { return timestamp; } public String getName() { return "temp"+timestamp+".djang10"; } public String getDebugName() { return "String: " + content.replaceAll("\n", "\\n").replace("\t", "\\t"); } } }
package GameNationBackEnd.Filters; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class RoutingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; String uri = req.getRequestURI(); if (uri.startsWith("/api") || uri.startsWith("/oauth") || uri.endsWith(".html") || uri.endsWith(".css") || uri.endsWith(".jpg") || uri.endsWith(".png") || uri.endsWith(".ttf") || uri.endsWith(".js")) { chain.doFilter(request, response); } else { req.getRequestDispatcher("/index.html").forward(request, response); } } @Override public void destroy() {} }
package at.ngmpps.fjsstt.model.problem; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import at.ngmpps.fjsstt.model.problem.subproblem.Bid; /** * Datastructure representing a solution for a FJSSTT problem. * * @author ahaemm * */ public class Solution implements Serializable { private static final long serialVersionUID = -409137575428427517L; double objectiveValue; /** * The job bids, each one representing the solution of a job-level * subproblem. Indices are jobs. */ final Map<Integer, Bid> bids; /** * The begin times of job operations. */ final Map<Integer, int[]> operationsBeginTimes; /** * The machine assignments of job operations. */ final Map<Integer, int[]> operationsMachineAssignments; /** * The time at which the solution was found. */ int iteration; /** * The subgradient values resulting from mOperationsBeginTimes and * mOperationsMachineAssignments. */ final int[][] subgradients; /** * The vector of strictly positive Lagrange multipliers that led to the * solution. */ final double[][] multipliers; /** * Nr of Machines */ int machines; /** * Nr of timeslots */ int timeslots; /** * Max Nr of Operations per Job */ int maxOperationsPerJob; public Solution(final int machines, final int timeslots, final int maxOperationsPerJob) { this.machines = machines; this.timeslots = timeslots; this.maxOperationsPerJob = maxOperationsPerJob; operationsBeginTimes = new HashMap<Integer, int[]>(); operationsMachineAssignments = new HashMap<Integer, int[]>(); multipliers = new double[machines][timeslots]; subgradients = new int[0][]; bids = new HashMap<Integer,Bid>(); objectiveValue = Double.NEGATIVE_INFINITY; } public Solution(final double objectiveValue, final int machines, final int timeslots, final int maxOperationsPerJob) { this(objectiveValue, machines, timeslots, maxOperationsPerJob, null, 0, new int[machines][timeslots]); } public Solution(final double objectiveValue, final int machines, final int timeslots, final int maxOperationsPerJob, final Map<Integer,Bid> bids, final int iteration, final int[][] subgradients) { this(objectiveValue, machines, timeslots, maxOperationsPerJob, bids, iteration, subgradients, null); } public Solution(final double objectiveValue, final int machines, final int timeslots, final int maxOperationsPerJob, final Map<Integer,Bid> bids, final int iteration, final int[][] subgradients, final double[][] multipliers) { this.objectiveValue = objectiveValue; this.bids = bids; this.iteration = iteration; this.subgradients = subgradients; this.machines = machines; this.timeslots = timeslots; this.maxOperationsPerJob = maxOperationsPerJob; operationsBeginTimes = new HashMap<Integer, int[]>(); operationsMachineAssignments = new HashMap<Integer, int[]>(); this.multipliers = new double[machines][timeslots]; // for all jobs and operations: compile the arrays for optimal machine // assignments and completion times for operations if (this.bids != null) { for (final Bid bid : this.bids.values()) { final int job = bid.getJobID(); final int[] machineAssignments = bid.getOptimumMachines(); final int[] beginTimes = bid.getOptimumBeginTimes(); operationsMachineAssignments.put(job, new int[machineAssignments.length]); operationsBeginTimes.put(job, new int[beginTimes.length]); System.arraycopy(machineAssignments, 0, operationsMachineAssignments.get(job), 0, machineAssignments.length); System.arraycopy(beginTimes, 0, operationsBeginTimes.get(job), 0, beginTimes.length); } } if (multipliers != null) { for (int m = 0; m < machines; m++) { System.arraycopy(multipliers[m], 0, this.multipliers[m], 0, multipliers[m].length); } } } /** * Constructor used by ListScheduling, so that it can return a real Solution * and not just a String[][]. Problems: ListScheduling does not know in which * iteration it is called, so it cannot set mIteration. Both bids and * subgradients are not important for ListScheduling and - to my knowledge- * need not be set. */ public Solution(final double objectiveValue, final Map<Integer, int[]> begTimes, final Map<Integer, int[]> machAss) { this(objectiveValue, begTimes, machAss, 0); } public Solution(final double objectiveValue, final Map<Integer, int[]> begTimes, final Map<Integer, int[]> machAss, final int iteration) { this.objectiveValue = objectiveValue; this.bids = null; this.iteration = iteration; this.operationsBeginTimes = begTimes; this.operationsMachineAssignments = machAss; this.subgradients = null; this.multipliers = null; } /** * returns a new ID of a Job; need to add Operations, processTimes, dueDate and jobWeight for this individually * @return */ public Integer addJob() { Integer newID = 0; for(Integer key :operationsBeginTimes.keySet()) newID = key>=newID?key+1:newID; return newID; } public Integer addJob(int[] operationsBeginTimes, int[] operationsMachineAssignments) { Integer newID = addJob(); this.operationsBeginTimes.put(newID, operationsBeginTimes); if(operationsBeginTimes.length>this.maxOperationsPerJob) maxOperationsPerJob=operationsBeginTimes.length; this.operationsMachineAssignments.put(newID, operationsMachineAssignments); return newID; } public void removeJob(Integer jobID) { this.operationsBeginTimes.remove(jobID); this.operationsMachineAssignments.remove(jobID); // todo recalculate maxOperationsPerJob as the removed Job could have been the longest one. } public Solution clone() { return clone(0); } protected Solution clone(int reduce) { Solution result = null; if(reduce == 1) { result = new Solution(objectiveValue, machines, timeslots, maxOperationsPerJob, null, iteration, subgradients); } else if(reduce == 2) { result = new Solution(objectiveValue, machines, timeslots, maxOperationsPerJob, null, iteration, null); } else if(reduce == 3) { result = new Solution(objectiveValue, machines, timeslots, maxOperationsPerJob, null, iteration, null, null); } else //if (reduce == 0) result = new Solution(objectiveValue, machines, timeslots, maxOperationsPerJob, bids, iteration, subgradients); // if (operationsBeginTimes != null) // for (int i : operationsBeginTimes.keySet()) // for (int ii = 0; ii < operationsBeginTimes.get(i).length; ++ii) // result.setOperationsBeginTimes(i, ii, operationsBeginTimes.get(i)[ii]); // if (operationsMachineAssignments != null) // for (int i : operationsMachineAssignments.keySet()) // for (int ii = 0; ii < operationsMachineAssignments.get(i).length; ++ii) // result.setOperationsMachineAssignments(i, ii, operationsMachineAssignments.get(i)[ii]); if (operationsBeginTimes != null) { for (int i : operationsBeginTimes.keySet()) { result.getOperationsBeginTimes().put(i, Arrays.copyOf(operationsBeginTimes.get(i), operationsBeginTimes.get(i).length)); } } if (operationsMachineAssignments != null) { for (int i : operationsMachineAssignments.keySet()) { result.getOperationsMachineAssignments().put(i, Arrays.copyOf(operationsMachineAssignments.get(i), operationsMachineAssignments.get(i).length)); } } return result; } /** * clone without bids, subgradients, multipliers * @return */ public Solution cloneReducedSize() { return clone(3); } /** * Checks if two solutions are equal. The check only considers machine * assignments and begin times. * * @param sol * The solution to be compared to. * @return True if the solutions are equal. */ public boolean equals(Solution sol) { for (int i : operationsMachineAssignments.keySet()) { if (!sol.getOperationsMachineAssignments().containsKey(i)) return false; if (operationsMachineAssignments.get(i).length != sol.getOperationsBeginTimes().get(i).length) return false; for (int j = 0; j < operationsMachineAssignments.get(i).length; j++) { if (this.operationsMachineAssignments.get(i)[j] != sol.getOperationsMachineAssignments().get(i)[j]) return false; if (this.operationsBeginTimes.get(i)[j] != sol.getOperationsBeginTimes().get(i)[j]) return false; } } return true; } /** * @return the mBids */ public Map<Integer,Bid> getBids() { return bids; } /** * @return the mIteration */ public int getIteration() { return iteration; } public double[][] getMultipliers() { return multipliers; } /** * @return the mObjectiveValue */ public double getObjectiveValue() { return objectiveValue; } /** * @return the start time per Job per Operation */ public Map<Integer, int[]> getOperationsBeginTimes() { return operationsBeginTimes; } /** * @return the assigned Machine per Job per Operation */ public Map<Integer, int[]> getOperationsMachineAssignments() { return operationsMachineAssignments; } /** * @return the mSubgradients */ public int[][] getSubgradients() { return subgradients; } public void setIteration(int valuefoundAtIteration) { iteration = valuefoundAtIteration; } public void setObjectiveValue(double newvalue) { objectiveValue = newvalue; } public void setOperationsBeginTimes(final Integer job, final int op, final int time) { setArrayValueInMap(operationsBeginTimes, job, op, time); } public void setOperationsMachineAssignments(final Integer job, final int op, final int time) { setArrayValueInMap(operationsMachineAssignments, job, op, time); } protected void setArrayValueInMap(final Map<Integer, int[]> myMap, final Integer mapKey, final int arrayIdx, final int value) { if (!myMap.containsKey(mapKey)) { int[] x = new int[arrayIdx + 1]; x[arrayIdx] = value; myMap.put(mapKey, x); } else if (myMap.get(mapKey).length < (arrayIdx + 1)) { int[] x = Arrays.copyOf(myMap.get(mapKey), arrayIdx + 1); x[arrayIdx] = value; myMap.put(mapKey, x); } else myMap.get(mapKey)[arrayIdx] = value; } @Override public String toString() { return "Solution{" + ", objectiveValue=" + objectiveValue + ", bids=" + (bids!=null ? bids.toString() : "null") + ", operationsBeginTimes=" + (operationsBeginTimes!=null ? operationsBeginTimes.toString() : "null") + ", operationsMachineAssignments=" + (operationsMachineAssignments!=null ? operationsMachineAssignments.toString() : "null") + ", iteration=" + iteration + ", subgradients=" + (subgradients != null ? Arrays.toString(subgradients) : "null") + ", multipliers=" + (multipliers != null ? Arrays.toString(multipliers):"null") + '}'; } }
package biz.paluch.logging.gelf.jul; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.text.MessageFormat; import java.util.Collections; import java.util.IllegalFormatException; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.LogRecord; import biz.paluch.logging.gelf.*; import biz.paluch.logging.gelf.intern.GelfMessage; /** * @author Mark Paluch * @since 26.09.13 15:22 */ public class JulLogEvent implements LogEvent { private static Map<String, String> threadNameCache = new ConcurrentHashMap<>(); private LogRecord logRecord; public JulLogEvent(LogRecord logRecord) { this.logRecord = logRecord; } @Override public String getMessage() { return createMessage(logRecord); } @Override public Object[] getParameters() { return logRecord.getParameters(); } @Override public Throwable getThrowable() { return logRecord.getThrown(); } @Override public long getLogTimestamp() { return logRecord.getMillis(); } @Override public String getSyslogLevel() { return "" + levelToSyslogLevel(logRecord.getLevel()); } private String createMessage(LogRecord record) { String message = record.getMessage(); Object[] parameters = record.getParameters(); if (message == null) { message = ""; } if (record.getResourceBundle() != null && record.getResourceBundle().containsKey(message)) { message = record.getResourceBundle().getString(message); } if (parameters != null && parameters.length > 0) { String originalMessage = message; // by default, using {0}, {1}, etc. -> MessageFormat try { message = MessageFormat.format(message, parameters); } catch (IllegalArgumentException e) { // leaving message as it is to avoid compatibility problems message = record.getMessage(); } catch (NullPointerException e) { // ignore } if (message.equals(originalMessage)) { // if the text is the same, assuming this is String.format type log (%s, %d, etc.) try { message = String.format(message, parameters); } catch (IllegalFormatException e) { // leaving message as it is to avoid compatibility problems message = record.getMessage(); } catch (NullPointerException e) { // ignore } } } return message; } private String getThreadName(LogRecord record) { if (record.getThreadID() == Thread.currentThread().getId()) { return Thread.currentThread().getName(); } String cacheKey = "" + record.getThreadID(); if (threadNameCache.containsKey(cacheKey)) { return threadNameCache.get(cacheKey); } long threadId = record.getThreadID(); String threadName = "" + record.getThreadID(); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for (Thread thread : threadSet) { if (thread.getId() == threadId) { threadName = thread.getName(); break; } } threadNameCache.put(cacheKey, threadName); return threadName; } private int levelToSyslogLevel(final Level level) { if (level.intValue() <= Level.CONFIG.intValue()) { return GelfMessage.DEFAUL_LEVEL; } if (level.intValue() <= Level.INFO.intValue()) { return 6; } if (level.intValue() <= Level.WARNING.intValue()) { return 4; } if (level.intValue() <= Level.SEVERE.intValue()) { return 3; } if (level.intValue() > Level.SEVERE.intValue()) { return 2; } return GelfMessage.DEFAUL_LEVEL; } public Values getValues(MessageField field) { if (field instanceof LogMessageField) { return new Values(field.getName(), getValue((LogMessageField) field)); } throw new UnsupportedOperationException("Cannot provide value for " + field); } public String getValue(LogMessageField field) { switch (field.getNamedLogField()) { case Severity: return logRecord.getLevel().getName(); case ThreadName: return getThreadName(logRecord); case SourceClassName: return getSourceClassName(); case SourceMethodName: return getSourceMethodName(); case SourceSimpleClassName: return GelfUtil.getSimpleClassName(logRecord.getSourceClassName()); case LoggerName: return logRecord.getLoggerName(); } throw new UnsupportedOperationException("Cannot provide value for " + field); } private String getSourceMethodName() { String sourceMethodName = logRecord.getSourceMethodName(); if (sourceMethodName == null || "<unknown>".equals(sourceMethodName)) { return null; } return sourceMethodName; } private String getSourceClassName() { String sourceClassName = logRecord.getSourceClassName(); if (sourceClassName == null || "<unknown>".equals(sourceClassName)) { return null; } return sourceClassName; } @Override public String getMdcValue(String mdcName) { return null; } @Override public Set<String> getMdcNames() { return Collections.EMPTY_SET; } }
package by.post.control.ui; import by.post.control.db.DbControl; import by.post.control.db.DbController; import by.post.ui.ConfirmationDialog; import javafx.fxml.FXML; import javafx.scene.control.ButtonType; import javafx.scene.control.TextArea; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Optional; /** * @author Dmitriy V.Yefremov */ public class SqlConsoleController { @FXML private TextArea console; @FXML private TextArea consoleOut; private DbControl dbControl; private static final String SEP = "\n private static final Logger logger = LogManager.getLogger(SqlConsoleController.class); public SqlConsoleController() { } //TODO add icons for buttons and small query validation !!! /** * Actions for buttons */ @FXML public void onExecuteAction() { Optional<ButtonType> result = new ConfirmationDialog().showAndWait(); String query = console.getText(); if (result.get() == ButtonType.OK) { if (query.isEmpty()) { String info = "The query is empty. Please, repeat.\n"; logger.info(info); consoleOut.appendText(info); return; } try { consoleOut.appendText(executeQuery(query) + SEP); } catch (SQLException e) { logger.error("SqlConsoleController error in onExecuteAction:" + e); } logger.info("Execute query: \n" + query + SEP); console.clear(); } } @FXML public void onClearAction() { Optional<ButtonType> result = new ConfirmationDialog().showAndWait(); if (result.get() == ButtonType.OK) { console.clear(); consoleOut.clear(); } } @FXML private void initialize() { dbControl = DbController.getInstance(); } /** * @param query * @return result as string * @throws SQLException */ private String executeQuery(String query) throws SQLException { Statement statement = dbControl.execute(query); ResultSet resultSet = statement.getResultSet(); String result = getFormattedOut(resultSet); resultSet.close(); statement.close(); return result; } /** * @param resultSet * @return formatted output */ private String getFormattedOut(ResultSet resultSet) throws SQLException { StringBuilder stringBuilder = new StringBuilder(); String format = "%20s|"; if (resultSet == null) { return stringBuilder.append("No data! Please, check your request!").toString(); } ResultSetMetaData metaData = resultSet.getMetaData(); int columnsCounter = metaData.getColumnCount(); //TODO think about using for resolve data with TableBuilder class for (int i = 1; i < columnsCounter; i++) { stringBuilder.append(String.format(format, metaData.getColumnName(i))); } int len = stringBuilder.toString().length(); // Add separator for the header stringBuilder.append("\n" + String.format("%" + len + "s", " ").replace(' ', '-') + "\n"); while (resultSet.next()) { for (int i = 1; i < columnsCounter; i++) { stringBuilder.append(String.format(format, resultSet.getString(i))); } stringBuilder.append("\n"); } return stringBuilder.toString(); } }
package ca.krasnay.sqlbuilder; /** * Dialect for PostgreSQL. * * @author John Krasnay <john@krasnay.ca> */ public class PostgresqlDialect implements Dialect { public String createCountSelect(String sql) { return "select count(*) from (" + sql + ") a"; } public String createPageSelect(String sql, int limit, int offset) { return String.format("%s limit %d offset %d", sql, limit, offset); } }
package ch.hesso.master.utils; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.lang.Integer; import org.apache.hadoop.io.WritableComparable; public class StackoverflowPost implements WritableComparable<StackoverflowPost>, Iterable<String>, Comparable<StackoverflowPost> { private int id; private boolean question; private int acceptedAnswerId; // Only for question post, if one private int parentID; // Only for non-question post private Date creationDate; private int score; private int viewCount; // Only for question post private String body; private int ownerUserId; private String ownerDisplayName; private int lastEditorUserId; private String lastEditorDisplayName; private Date lastEditDate; private Date lastActivityDate; private Date closedDate; private Date communityOwnedDate; private String title; // Only for question post private List<String> tags; // Only for question post private int answerCount; // Only for question post private int commentCount; private int favoriteCount; public StackoverflowPost() { reset(); } public StackoverflowPost(boolean question) { this.question = question; if (question) { this.tags = new ArrayList<String>(); } } public StackoverflowPost(StackoverflowPost other) { this(other.question); id = other.id; creationDate = other.creationDate; score = other.score; body = other.body; ownerUserId = other.ownerUserId; lastEditorUserId = other.lastEditorUserId; lastEditorDisplayName = other.lastEditorDisplayName; lastEditDate = other.lastEditDate; lastActivityDate = other.lastActivityDate; commentCount = other.commentCount; favoriteCount = other.favoriteCount; if (question) { acceptedAnswerId = other.acceptedAnswerId; viewCount = other.viewCount; title = other.title; tags.addAll(other.tags); answerCount = other.answerCount; } else { parentID = other.parentID; } } public void reset() { id = -1; question = false; acceptedAnswerId = -1; parentID = -1; if (creationDate == null) { creationDate = new Date(0); } else { creationDate.setTime(0); ; } score = -1; viewCount = -1; body = ""; ownerUserId = -1; ownerDisplayName = ""; lastEditorUserId = -1; lastEditorDisplayName = ""; if (lastEditDate == null) { lastEditDate = new Date(0); } else { lastEditDate.setTime(0); ; } if (lastActivityDate == null) { lastActivityDate = new Date(0); } else { lastActivityDate.setTime(0); ; } if (closedDate == null) { closedDate = new Date(0); } else { closedDate.setTime(0); } if (communityOwnedDate == null) { communityOwnedDate = new Date(0); } else { communityOwnedDate.setTime(0); } title = ""; if (tags == null) { this.tags = new ArrayList<String>(); } else { tags.clear(); } answerCount = -1; commentCount = -1; favoriteCount = -1; } public void readFields(DataInput in) throws IOException { question = in.readBoolean(); id = in.readInt(); creationDate = new Date(in.readLong()); score = in.readInt(); body = in.readUTF(); ownerUserId = in.readInt(); ownerDisplayName = in.readUTF(); lastEditorUserId = in.readInt(); lastEditorDisplayName = in.readUTF(); lastEditDate = new Date(in.readLong()); lastActivityDate = new Date(in.readLong()); communityOwnedDate = new Date(in.readLong()); commentCount = in.readInt(); favoriteCount = in.readInt(); if (question) { acceptedAnswerId = in.readInt(); viewCount = in.readInt(); title = in.readUTF(); int nbTags = in.readInt(); tags = new ArrayList<String>(nbTags); for (int i = 0; i < nbTags; ++i) { tags.add(in.readUTF()); } answerCount = in.readInt(); closedDate = new Date(in.readLong()); } else { parentID = in.readInt(); } } public void write(DataOutput out) throws IOException { out.writeBoolean(question); out.writeInt(id); out.writeLong(creationDate.getTime()); out.writeInt(score); out.writeUTF(body); out.writeInt(ownerUserId); out.writeUTF(ownerDisplayName); out.writeInt(lastEditorUserId); out.writeUTF(lastEditorDisplayName); out.writeLong(lastEditDate.getTime()); out.writeLong(lastActivityDate.getTime()); out.writeLong(communityOwnedDate.getTime()); out.writeInt(commentCount); out.writeInt(favoriteCount); if (question) { out.writeInt(acceptedAnswerId); out.writeInt(viewCount); out.writeUTF(title); out.writeInt(tags.size()); for (String tag : tags) { out.writeUTF(tag); } out.writeInt(answerCount); out.writeLong(closedDate.getTime()); } else { out.writeInt(parentID); } } /** * Returns true iff <code>other</code> is a {@link StackoverflowPost} with * the same value. */ public boolean equals(Object other) { if (!(other instanceof StackoverflowPost)) return false; return this.id == ((StackoverflowPost) other).id; } public int hashCode() { return id; } @Override public int compareTo(StackoverflowPost o) { return Integer.compare(id, o.id); } @Override public String toString() { return "StackoverflowPost [id=" + id + ", question=" + question + ", acceptedAnswerId=" + acceptedAnswerId + ", parentID=" + parentID + ", creationDate=" + creationDate + ", score=" + score + ", viewCount=" + viewCount + ", body=" + body + ", ownerUserId=" + ownerUserId + ", lastEditorUserId=" + lastEditorUserId + ", lastEditorDisplayName=" + lastEditorDisplayName + ", lastEditDate=" + lastEditDate + ", lastActivityDate=" + lastActivityDate + ", title=" + title + ", tags=" + tags + ", answerCount=" + answerCount + ", commentCount=" + commentCount + ", favoriteCount=" + favoriteCount + "]"; } @Override public Iterator<String> iterator() { return tags.iterator(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isQuestion() { return question; } public void setQuestion(boolean question) { this.question = question; } public int getAcceptedAnswerId() { return acceptedAnswerId; } public void setAcceptedAnswerId(int acceptedAnswerId) { this.acceptedAnswerId = acceptedAnswerId; } public int getParentID() { return parentID; } public void setParentID(int parentID) { this.parentID = parentID; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getViewCount() { return viewCount; } public void setViewCount(int viewCount) { this.viewCount = viewCount; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public int getOwnerUserId() { return ownerUserId; } public void setOwnerUserId(int ownerUserId) { this.ownerUserId = ownerUserId; } public String getOwnerDisplayName() { return ownerDisplayName; } public void setOwnerDisplayName(String ownerDisplayName) { this.ownerDisplayName = ownerDisplayName; } public int getLastEditorUserId() { return lastEditorUserId; } public void setLastEditorUserId(int lastEditorUserId) { this.lastEditorUserId = lastEditorUserId; } public String getLastEditorDisplayName() { return lastEditorDisplayName; } public void setLastEditorDisplayName(String lastEditorDisplayName) { this.lastEditorDisplayName = lastEditorDisplayName; } public Date getLastEditDate() { return lastEditDate; } public void setLastEditDate(Date lastEditDate) { this.lastEditDate = lastEditDate; } public Date getLastActivityDate() { return lastActivityDate; } public void setLastActivityDate(Date lastActivityDate) { this.lastActivityDate = lastActivityDate; } public Date getClosedDate() { return closedDate; } public void setClosedDate(Date closedDate) { this.closedDate = closedDate; } public Date getCommunityOwnedDate() { return communityOwnedDate; } public void setCommunityOwnedDate(Date communityOwnedDate) { this.communityOwnedDate = communityOwnedDate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public void setTags(String tags) { this.tags.addAll(Arrays.asList(tags.split(" "))); } public void addTag(String tag) { tags.add(tag); } public int getAnswerCount() { return answerCount; } public void setAnswerCount(int answerCount) { this.answerCount = answerCount; } public int getCommentCount() { return commentCount; } public void setCommentCount(int commentCount) { this.commentCount = commentCount; } public int getFavoriteCount() { return favoriteCount; } public void setFavoriteCount(int favoriteCount) { this.favoriteCount = favoriteCount; } }
package cocktail.archive_handler; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import javax.xml.bind.JAXBException; import cocktail.db_access.DbAdapter; import cocktail.db_access.DbAdapterImpl; import cocktail.snippet.FileInfo; import cocktail.snippet.SnippetInfo; import cocktail.snippet.SnippetSet; import cocktail.sound_processing.SoundExtractor; import cocktail.sound_processing.SoundExtractorImpl; import cocktail.sound_processing.SoundProcess; import cocktail.sound_processing.SoundProcessImpl; import cocktail.stream_io.XmlStreamer; /** * This class handles archives to and from the frontend. Populating zip's and database with * information inside SnippetSets */ public class ArchiveHandler { private static final SoundExtractor convert = new SoundExtractorImpl(); private static final DbAdapter dbAdapter = new DbAdapterImpl(); private static final SoundProcess process = new SoundProcessImpl(); /** * creates a zip and populate it with snippets from the database. * Files are trimmed if needed before added to the archive. * * @param set SnippetSet to prepare * @return path to zip-archive */ public String zip(SnippetSet set) { File zipWorkspace = new File("./src/main/resources/zip/"); if (!zipWorkspace.exists()) { zipWorkspace.mkdir(); } File tempDir = new File(zipWorkspace + File.separator + set.getSetName()); String outputFile = tempDir + File.separator + set.getSetName() + ".zip"; final Path path = Paths.get(outputFile); final URI uri = URI.create("jar:file:" + path.toUri().getPath()); Map<String, String> env = new HashMap<>(); env.put("create", "true"); env.put("encoding", "UTF-8"); Path zipFilePath; File addNewFile; byte[] sourceFile = null; int currentFileID = -1; //set to -1 to ensure a file is getting loaded when working thru set. FileSystem fs = null; if (!tempDir.exists()) { tempDir.mkdir(); } try { fs = FileSystems.newFileSystem(uri, env); } catch (IOException e) { e.printStackTrace(); } //here the process of working thru the snippetset to collect clips and populating the archive. //trying to optimize it trying to avoid loading source files multiple times. for (SnippetInfo snippet : sortSetByFileID(set)) { if (fs != null) { //check if method needs to load a new clip from DB or not. if (currentFileID == -1 || currentFileID != snippet.getFileID()) { currentFileID = snippet.getFileID(); sourceFile = dbAdapter.readSnippet(snippet.getSnippetID()); System.out.println(" } //checks if the snippet is the same size as the source file. //addnewFile refers to the file that will be copied into the zip. if (!dbAdapter.isSnippetPartOfLongerFile(snippet.getSnippetID())) { addNewFile = byteArrayToFile(sourceFile, tempDir + File.separator + snippet.getFileName()); System.out.println(" //else it needs to be cut, using trimAudioClip. //addnewFile refers to the file that will be copied into the zip. } else { addNewFile = byteArrayToFile(process.trimAudioClip(sourceFile, snippet.getStartTime(), snippet.getLengthSec()), tempDir + File.separator + snippet.getFileName()); System.out.println(" } //parentDir is used to create destination subdirectories named from the first tagName. Path parentDir = fs.getPath("/snippets/" + snippet.getTagNames().get(0)); zipFilePath = fs.getPath( parentDir + File.separator + snippet.getFileName() + "_" + snippet.getSnippetID() + ".wav"); if (Files.notExists(parentDir)) { System.out.println("Creating directory " + parentDir); try { Files.createDirectories(parentDir); } catch (IOException e) { e.printStackTrace(); } } try { Files.copy(addNewFile.toPath(), zipFilePath); } catch (IOException e) { e.printStackTrace(); } snippet.setFileName(snippet.getFileName() + "_" + snippet.getSnippetID() + ".wav"); addNewFile.delete(); } } //creates and add the updated snippetset xml to the archive. File xmlFile = new File(tempDir + File.separator + "SnippetSet.xml"); try { if (fs != null) { set.toStream(new XmlStreamer<SnippetSet>(), xmlFile); Files.copy(xmlFile.toPath(), fs.getPath("SnippetSet.xml")); fs.close(); } } catch (IOException e) { e.printStackTrace(); try { fs.close(); } catch (IOException e1) { e1.printStackTrace(); } } xmlFile.delete(); return outputFile; } /** * Unpacking and processing of zip archive from the frontend. * populate the database with content. * * the method is basically split into two parts where the first part unpacks the files * and the second part process these files and upload/update the db with its content. * * @param inputFile path to zip archive to process * @return snippetSet of files added to database */ public SnippetSet unzip(String inputFile) { FileSystem fs = null; String tempZipDir = null; SnippetSet snippetSet = null; File unzipWorkspace = new File("./src/main/resources/unzip/"); if (!unzipWorkspace.exists()) { unzipWorkspace.mkdir(); } //trims the inputFile name to be used to name the temporary unzip workspace. int lastIndex = inputFile.lastIndexOf('/'); if (lastIndex >= 0) { System.out.println(lastIndex + " last index " + inputFile); tempZipDir = inputFile.substring(lastIndex + 1); tempZipDir = tempZipDir.substring(0, tempZipDir.lastIndexOf('.')); } File tempDir = new File("./src/main/resources/unzip/" + File.separator + tempZipDir); if (!tempDir.exists()) { tempDir.mkdir(); } //prepare and mount the zip archive as a zipFilesystem Map<String, String> env = new HashMap<>(); env.put("create", "false"); final Path path = Paths.get(inputFile); final URI uri = URI.create("jar:file:" + path.toUri().getPath()); try { fs = FileSystems.newFileSystem(uri, env); } catch (IOException e) { e.printStackTrace(); } //filewalk thru the zip to unpack and convert its content if (fs != null) { final Path zipRoot = fs.getPath("/"); try { Files.walkFileTree(zipRoot, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { File currentFile = new File(tempDir.toString(), file.toString()); final Path destFile = Paths.get(currentFile.toString()); Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); System.out.println(file.getFileName() + " unpacked."); //converting files to 16 bit 44khz mono wav's: String fileExtension = getFileExtension(currentFile.toString()); File workFile = destFile.toFile(); File tmpWorkFile = new File( destFile + "_tmp.wav"); try { if (vidCodec(fileExtension)) { convert.vidToWav(workFile, tmpWorkFile); tmpWorkFile.renameTo(workFile); } else if (soundCodec(fileExtension)) { convert.soundToWav(workFile, tmpWorkFile); tmpWorkFile.renameTo(workFile); } } catch (IOException e) { e.printStackTrace(); } //end of convert return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { final Path subDir = Paths.get(tempDir.toString(), dir.toString()); if (Files.notExists(subDir)) { Files.createDirectory(subDir); } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } //processing part: //here the procedure of going thru the snippetset inside the archive begins //set getting sorted by filename and processed one by one. ArrayList<Integer> snippetIDs = new ArrayList<>(); String fileName; String lastFileName = null; int lastFileID = 0; String snippetSetPath = tempDir.toString() + File.separator + "SnippetSet.xml"; SnippetSet currentSnippetSet = getSnippetSet(new File(snippetSetPath)); for (SnippetInfo snippet : sortSetBySourceFile(currentSnippetSet)) { System.out.println(" System.out.println("---file: " + snippet.getFileName()); System.out.println("---strt: " + snippet.getStartTime()); System.out.println("---lgth: " + snippet.getLengthSec()); System.out.println(" //fileExtension = getFileExtension(snippet.getFileName()); fileName = snippet.getFileName(); Path sourceFilePath = Paths.get(tempDir.toString(), "snippets/" + snippet.getTagNames().get(0) + File.separator + fileName); try { byte[] bArray = Files.readAllBytes(sourceFilePath); if (getSnippetLength(bArray) <= 0) { System.out.println("invalid file...."); System.out.println("skipping this to avoid fubar."); } else { ByteArrayInputStream bis = new ByteArrayInputStream(bArray); snippet.setFileName(trimFileName(fileName)); FileInfo fileInfo = new FileInfo(bis, trimFileName(fileName), bArray.length / 1024, getSnippetLength(bArray)); //check for which approach needed for current snippet //uploaded snippetsID's are then stored inside an array used to build a snippetSet //that is sent as return as validation of added files. //if snippet is already in database (it already has a snippetID) and only needs to be updated: if (snippet.getSnippetID() > 0) { fileInfo.setFileName(dbAdapter.getFileNameFromSnippetId(snippet.getSnippetID())); snippet.setFileName(dbAdapter.getFileNameFromSnippetId(snippet.getSnippetID())); System.out.println("edited file being updated in the database (" + dbAdapter .getFileNameFromSnippetId(snippet.getSnippetID()) + ")"); dbAdapter.editSnippet(snippet, fileInfo, snippet.getSnippetID()); snippetIDs.add(snippet.getSnippetID()); } else { //compares current file with last file to check if its a new file or not. // if (snippet's) source audio clip is the same as the last one, only snippetdata uploaded. if (fileName.equals(lastFileName)) { System.out.println( "----same source file as last snippet. not uploading clip again (" + fileName + ")."); snippetIDs.add(dbAdapter.writeSnippet(snippet, lastFileID)); System.out.println("lastFileID: " + lastFileID); //if (snippet's) is considered NEW and attempts to upload to the DB along with snippet data. //lastFileId is set to identify the sourceFile with the corresponding file inside the DB. } else { System.out.println("new file, uploading clip to database! (" + fileName + ")"); int tempSnippetID = dbAdapter.writeSnippet(fileInfo, snippet); snippetIDs.add(tempSnippetID); lastFileID = dbAdapter.getFileIdFromSnippetId(tempSnippetID); lastFileName = fileName; } } bis.close(); } } catch (IOException e) { e.printStackTrace(); try { fs.close(); } catch (IOException e1) { e1.printStackTrace(); } removeDirectory(tempDir); } } snippetSet = dbAdapter.createSnippetSetFromIds(snippetIDs); } try { assert fs != null; fs.close(); } catch (IOException e) { e.printStackTrace(); } removeDirectory(tempDir); System.out.println("snippetset: " + snippetSet); return snippetSet; } /** * remove files and delete directory * * @param dir directory to delete. */ private static void removeDirectory(File dir) { if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File theFile : files) { removeDirectory(theFile); } } dir.delete(); } else { dir.delete(); } } /** * get length of snippet (in secs) * * @param snippet snippet to check * @return length of snippet */ private static double getSnippetLength(byte[] snippet) { AudioFormat format; BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(snippet)); AudioInputStream ais = null; double output = 0; try { ais = AudioSystem.getAudioInputStream(bis); format = ais.getFormat(); long audioFileLength = ais.getFrameLength(); output = (audioFileLength + 0.0) / format.getFrameRate(); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); return -1; } try { bis.close(); ais.close(); } catch (IOException e) { e.printStackTrace(); return -1; } output = Math.round(output * 10000.0) / 10000.0; //4 decimals return output; } /** * compare extension of file to determine if its a video file using the file vidcodecs.txt * inside /resources * * @param extension file extension * @return bool */ private static boolean vidCodec(String extension) throws IOException { BufferedReader in = new BufferedReader(new FileReader("./src/main/resources/vidcodecs.txt")); String str; List<String> list = new ArrayList<>(); while ((str = in.readLine()) != null) { list.add(str); } for (String ext : list) { if (extension.equals(ext)) { return true; } } return false; } /** * compare extension of file to determine if its a sound file using the file soundCodecs.txt * inside /resources * * @param extension file extension * @return bool */ private static boolean soundCodec(String extension) throws IOException { BufferedReader in = new BufferedReader(new FileReader("./src/main/resources/soundcodecs.txt")); String str; List<String> list = new ArrayList<>(); while ((str = in.readLine()) != null) { list.add(str); } for (String ext : list) { if (extension.equals(ext)) { return true; } } return false; } /** * Collect/Fetch a snippetSet from an xmlFile * * @param xmlFile compatible xml file * @return SnippetSet */ private static SnippetSet getSnippetSet(File xmlFile) { XmlStreamer<SnippetSet> xmlStreamer = new XmlStreamer<>(); SnippetSet snippetSet = null; try { snippetSet = xmlStreamer.fromStream(SnippetSet.class, xmlFile); } catch (JAXBException | FileNotFoundException e) { e.printStackTrace(); } return snippetSet; } /** * Returns a File from a ByteArray (from database) * * @param byteIn audio data as byteArray * @param path location of output file. * @return clip as File */ private static File byteArrayToFile(byte[] byteIn, String path) { File output = new File(path); FileOutputStream fos = null; try { fos = new FileOutputStream(path); } catch (FileNotFoundException e) { e.printStackTrace(); } try { assert fos != null; fos.write(byteIn); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } return output; } /** * Sorts a SnippetSet according to FileID. * Used by zip to ensure files aren't loaded multiple times from database. * * @param set SnippetSet to sort * @return An ArrayList of SnippetInfo's. */ private static ArrayList<SnippetInfo> sortSetByFileID(SnippetSet set) { ArrayList<SnippetInfo> output = new ArrayList<>(); output.addAll(set.getSnippetCollection()); Collections .sort(output, (b1, b2) -> ((Integer) b1.getFileID()).compareTo(((Integer) b2.getFileID()))); return output; } /** * Sorts a SnippetSet according to FileNames. * * @param set SnippetSet to sort * @return An ArrayList of SnippetInfo's. */ private static ArrayList<SnippetInfo> sortSetBySourceFile(SnippetSet set) { ArrayList<SnippetInfo> output = new ArrayList<>(); output.addAll(set.getSnippetCollection()); Collections .sort(output, (b1, b2) -> (b1.getFileName()).compareTo(b2.getFileName())); return output; } /** * Delete a File (zip) when delivery to frontend is complete. * * @param setName path to zipFile. * @return bool */ public boolean deleteUsedZip(String setName) { File deadFile = new File(setName); if (!deadFile.isFile()) { System.out.println(setName + " is not found OR is not a file."); System.out.println("deleting directory: " + deadFile.toPath().getParent().toFile()); removeDirectory(deadFile.toPath().getParent().toFile()); return false; } System.out.println("deleting file: " + deadFile); deadFile.delete(); System.out.println("deleting directory: " + deadFile.toPath().getParent().toFile()); removeDirectory(deadFile.toPath().getParent().toFile()); return true; } /** * Collect/fetch all snippets related to a single file. * * @param fileID ID of file to fetch * @return SnippetSet of all related snippets attached to file. */ public SnippetSet getSingleFile(int fileID) { return dbAdapter.getAllSnippetFromFile(fileID); } /** * Get file extension from filename * * @param fileName Filename to trim * @return Extension as String */ private static String getFileExtension(String fileName) { String output = null; int lastIndex = fileName.lastIndexOf('.'); if (lastIndex >= 0) { output = fileName.substring(lastIndex + 1); } return output; } /** * Trims the Filename of any extensions, used by unzip to deliver clean names to DB. * * @param fileName Filename to trim * @return Filename as String */ private static String trimFileName(String fileName) { String output = null; int dotIndex = fileName.lastIndexOf('.'); if (dotIndex >= 0) { output = fileName.substring(0, dotIndex); } return output; } }
package com.amee.service.auth; import com.amee.domain.IAMEEEntity; import com.amee.domain.IAMEEEntityReference; import com.amee.domain.ObjectType; import com.amee.domain.auth.AuthorizationContext; import com.amee.domain.auth.Permission; import com.amee.domain.auth.PermissionEntry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service public class PermissionService { /** * Defines which 'principals' (keys) can relate to which 'entities' (values). */ public final static Map<ObjectType, Set<ObjectType>> PRINCIPAL_ENTITY = new HashMap<ObjectType, Set<ObjectType>>(); /** * Define which principals can relate to which entities. */ { // Users <--> Entities addPrincipalAndEntity(ObjectType.USR, ObjectType.ENV); addPrincipalAndEntity(ObjectType.USR, ObjectType.PR); addPrincipalAndEntity(ObjectType.USR, ObjectType.DC); addPrincipalAndEntity(ObjectType.USR, ObjectType.PI); addPrincipalAndEntity(ObjectType.USR, ObjectType.NPI); addPrincipalAndEntity(ObjectType.USR, ObjectType.DI); addPrincipalAndEntity(ObjectType.USR, ObjectType.NDI); addPrincipalAndEntity(ObjectType.USR, ObjectType.IV); addPrincipalAndEntity(ObjectType.USR, ObjectType.PINV); addPrincipalAndEntity(ObjectType.USR, ObjectType.PITV); addPrincipalAndEntity(ObjectType.USR, ObjectType.DINV); addPrincipalAndEntity(ObjectType.USR, ObjectType.DITV); addPrincipalAndEntity(ObjectType.USR, ObjectType.DINVH); addPrincipalAndEntity(ObjectType.USR, ObjectType.DITVH); addPrincipalAndEntity(ObjectType.USR, ObjectType.AL); addPrincipalAndEntity(ObjectType.USR, ObjectType.ID); addPrincipalAndEntity(ObjectType.USR, ObjectType.IVD); addPrincipalAndEntity(ObjectType.USR, ObjectType.RVD); addPrincipalAndEntity(ObjectType.USR, ObjectType.ALC); addPrincipalAndEntity(ObjectType.USR, ObjectType.USR); addPrincipalAndEntity(ObjectType.USR, ObjectType.GRP); addPrincipalAndEntity(ObjectType.USR, ObjectType.VD); addPrincipalAndEntity(ObjectType.USR, ObjectType.TA); // Groups <--> Entities addPrincipalAndEntity(ObjectType.GRP, ObjectType.ENV); addPrincipalAndEntity(ObjectType.GRP, ObjectType.PR); addPrincipalAndEntity(ObjectType.GRP, ObjectType.DC); addPrincipalAndEntity(ObjectType.GRP, ObjectType.PI); addPrincipalAndEntity(ObjectType.GRP, ObjectType.NPI); addPrincipalAndEntity(ObjectType.GRP, ObjectType.DI); addPrincipalAndEntity(ObjectType.GRP, ObjectType.NDI); addPrincipalAndEntity(ObjectType.GRP, ObjectType.IV); addPrincipalAndEntity(ObjectType.GRP, ObjectType.PINV); addPrincipalAndEntity(ObjectType.GRP, ObjectType.PITV); addPrincipalAndEntity(ObjectType.GRP, ObjectType.DINV); addPrincipalAndEntity(ObjectType.GRP, ObjectType.DITV); addPrincipalAndEntity(ObjectType.GRP, ObjectType.AL); addPrincipalAndEntity(ObjectType.GRP, ObjectType.ID); addPrincipalAndEntity(ObjectType.GRP, ObjectType.IVD); addPrincipalAndEntity(ObjectType.GRP, ObjectType.RVD); addPrincipalAndEntity(ObjectType.GRP, ObjectType.ALC); addPrincipalAndEntity(ObjectType.GRP, ObjectType.USR); addPrincipalAndEntity(ObjectType.GRP, ObjectType.GRP); addPrincipalAndEntity(ObjectType.GRP, ObjectType.VD); addPrincipalAndEntity(ObjectType.GRP, ObjectType.TA); } @Autowired private PermissionServiceDAO dao; public Permission getPermissionByUid(String uid) { return dao.getPermissionByUid(uid); } public void persist(Permission permission) { dao.persist(permission); } public void remove(Permission permission) { dao.remove(permission); } public List<Permission> getPermissionsForEntity(IAMEEEntityReference entity) { if ((entity == null) || !isValidEntity(entity)) { throw new IllegalArgumentException(); } return dao.getPermissionsForEntity(entity); } public Permission getPermissionForEntity(IAMEEEntityReference entity, PermissionEntry entry) { List<Permission> permissions = getPermissionsForEntity(entity); for (Permission permission : permissions) { if (permission.getEntries().contains(entry)) { return permission; } } return null; } public List<Permission> getPermissionsForPrincipals(Collection<IAMEEEntityReference> principals) { if ((principals == null) || principals.isEmpty()) { throw new IllegalArgumentException(); } List<Permission> permissions = new ArrayList<Permission>(); for (IAMEEEntityReference principal : principals) { permissions.addAll(getPermissionsForPrincipal(principal)); } return permissions; } public List<Permission> getPermissionsForPrincipal(IAMEEEntityReference principal) { if ((principal == null) || !isValidPrincipal(principal)) { throw new IllegalArgumentException(); } return dao.getPermissionsForPrincipal(principal, null); } public List<Permission> getPermissionsForEntity(AuthorizationContext authorizationContext, IAMEEEntityReference entityReference) { // Parameters must not be null. if ((authorizationContext == null) || (entityReference == null)) { throw new IllegalArgumentException("Either authorizationContext or entityReference is null."); } // Check principals are valid. for (IAMEEEntityReference principal : authorizationContext.getPrincipals()) { if (!isValidPrincipalToEntity(principal, entityReference)) { throw new IllegalArgumentException("A principal was not valid for the entity."); } } IAMEEEntity entity = getEntity(entityReference); List<Permission> permissions = new ArrayList<Permission>(); permissions.addAll(entity.handleAuthorizationContext(authorizationContext)); for (IAMEEEntityReference principal : authorizationContext.getPrincipals()) { permissions.addAll(dao.getPermissionsForEntity(principal, entity)); } return permissions; } public void trashPermissionsForEntity(IAMEEEntityReference entity) { dao.trashPermissionsForEntity(entity); } private void addPrincipalAndEntity(ObjectType principal, ObjectType entity) { Set<ObjectType> entities = PRINCIPAL_ENTITY.get(principal); if (entities == null) { entities = new HashSet<ObjectType>(); PRINCIPAL_ENTITY.put(principal, entities); } entities.add(entity); } public boolean isValidPrincipal(IAMEEEntityReference principal) { if (principal == null) throw new IllegalArgumentException(); return PRINCIPAL_ENTITY.keySet().contains(principal.getObjectType()); } public boolean isValidEntity(IAMEEEntityReference entity) { if (entity == null) throw new IllegalArgumentException(); for (Set<ObjectType> entities : PRINCIPAL_ENTITY.values()) { if (entities.contains(entity.getObjectType())) { return true; } } return false; } public boolean isValidPrincipalToEntity(IAMEEEntityReference principal, IAMEEEntityReference entity) { if ((principal == null) || (entity == null)) throw new IllegalArgumentException(); return isValidPrincipal(principal) && PRINCIPAL_ENTITY.get(principal.getObjectType()).contains(entity.getObjectType()); } /** * Fetch the entity referenced by the IAMEEEntityReference from the database. Copies the * AccessSpecification from the entityReference to the entity. * * @param entityReference to fetch * @return fetched entity */ public IAMEEEntity getEntity(IAMEEEntityReference entityReference) { IAMEEEntity entity = entityReference.getEntity(); if (entity == null) { entity = dao.getEntity(entityReference); if (entity == null) { throw new RuntimeException("An entity was not found for the entityReference."); } if (entity.getAccessSpecification() == null) { entity.setAccessSpecification(entityReference.getAccessSpecification()); } entityReference.setEntity(entity); } return entity; } }
package com.celements.model.util; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import org.xwiki.model.EntityType; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.ObjectPropertyReference; import org.xwiki.model.reference.ObjectReference; import org.xwiki.model.reference.SpaceReference; import org.xwiki.model.reference.WikiReference; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; public class EntityTypeUtil { private static final BiMap<Class<? extends EntityReference>, EntityType> ENTITY_TYPE_MAP; private static final Map<EntityType, String> REGEX_MAP; public static final String REGEX_WORD = "[a-zA-Z0-9_-]+"; public static final String REGEX_WIKINAME = "[a-zA-Z0-9]+"; public static final String REGEX_SPACE = "(" + REGEX_WIKINAME + "\\:)?" + REGEX_WORD; public static final String REGEX_DOC = REGEX_SPACE + "\\." + REGEX_WORD; public static final String REGEX_ATT = REGEX_DOC + "\\@" + ".+"; static { Map<Class<? extends EntityReference>, EntityType> map = new HashMap<>(); map.put(WikiReference.class, EntityType.WIKI); map.put(SpaceReference.class, EntityType.SPACE); map.put(DocumentReference.class, EntityType.DOCUMENT); map.put(AttachmentReference.class, EntityType.ATTACHMENT); map.put(ObjectReference.class, EntityType.OBJECT); map.put(ObjectPropertyReference.class, EntityType.OBJECT_PROPERTY); ENTITY_TYPE_MAP = ImmutableBiMap.copyOf(map); Map<EntityType, String> regexMap = new LinkedHashMap<>(); // keeps insertion order regexMap.put(EntityType.WIKI, REGEX_WIKINAME); regexMap.put(EntityType.SPACE, REGEX_SPACE); regexMap.put(EntityType.DOCUMENT, REGEX_DOC); regexMap.put(EntityType.ATTACHMENT, REGEX_ATT); REGEX_MAP = Collections.unmodifiableMap(regexMap); } @NotNull public static Optional<EntityType> getEntityTypeForClass( @NotNull Class<? extends EntityReference> token) { return Optional.fromNullable(ENTITY_TYPE_MAP.get(checkNotNull(token))); } @NotNull public static EntityType getEntityTypeForClassOrThrow( @NotNull Class<? extends EntityReference> token) { Optional<EntityType> type = getEntityTypeForClass(token); if (!type.isPresent()) { throw new IllegalArgumentException("No entity type for class: " + token); } return type.get(); } @NotNull public static Class<? extends EntityReference> getClassForEntityType(@NotNull EntityType type) { Class<? extends EntityReference> token = ENTITY_TYPE_MAP.inverse().get(checkNotNull(type)); if (token != null) { return token; } else { throw new IllegalStateException("No class for entity type: " + type); } } @NotNull public static EntityType getRootEntityType() { return EntityType.values()[0]; } @NotNull public static EntityType getLastEntityType() { return EntityType.values()[EntityType.values().length - 1]; } /** * @return the class for the root entity type */ @NotNull public static Class<? extends EntityReference> getRootClass() { return checkNotNull(ENTITY_TYPE_MAP.inverse().get(getRootEntityType())); } @NotNull public static Optional<EntityType> identifyEntityTypeFromName(@NotNull String name) { if (!checkNotNull(name).isEmpty()) { for (EntityType type : REGEX_MAP.keySet()) { if (name.matches(REGEX_MAP.get(type))) { return Optional.of(type); } } } return Optional.absent(); } @NotNull public static Iterator<EntityType> createIterator() { return createIteratorAt(null); } @NotNull public static Iterator<EntityType> createIteratorFrom(@Nullable final EntityType startType) { Iterator<EntityType> ret = createIteratorAt(checkNotNull(startType)); if ((startType != null) && ret.hasNext()) { ret.next(); } return ret; } @NotNull public static Iterator<EntityType> createIteratorAt(@Nullable final EntityType startType) { return new Iterator<EntityType>() { private int ordinal = MoreObjects.firstNonNull(startType, getLastEntityType()).ordinal(); @Override public boolean hasNext() { return ordinal >= 0; } @Override public EntityType next() { EntityType ret = EntityType.values()[ordinal]; decrease(); return ret; } private int decrease() { // skip type attachment for type OBJECT or OBJECT_PROPERTY return ordinal -= ((ordinal == EntityType.OBJECT.ordinal()) ? 2 : 1); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
package com.cjpowered.learn.inventory; import java.time.LocalDate; import java.util.Collection; import java.util.HashSet; import java.util.Set; import com.cjpowered.learn.marketing.MarketingInfo; public class StockItem implements Item { final int normalLevel; final boolean firstDayOfMonthOnly; final Set<StockCalculator> requiredStockCalculators; public StockItem(final int normalLevel, final Collection<StockCalculator> requiredStockCalculators) { this(normalLevel, requiredStockCalculators, false); } public StockItem(final int normalLevel, final Collection<StockCalculator> requiredStockCalculators, final boolean firstDayOfMonthOnly) { this.normalLevel = normalLevel; this.requiredStockCalculators = new HashSet<>(requiredStockCalculators); this.firstDayOfMonthOnly = firstDayOfMonthOnly; } @Override public int computeOrderQuantity(final InventoryDatabase database, final MarketingInfo marketingInfo, final LocalDate when) { if (this.firstDayOfMonthOnly && when.getDayOfMonth() != 1) return 0; int requiredLevel = 0; for (final StockCalculator calc : this.requiredStockCalculators) { requiredLevel = Math.max(requiredLevel, calc.requiredStock(this, this.normalLevel, database, marketingInfo, when)); } final int onHand = database.onHand(this); return Math.max(0, requiredLevel - onHand); } }
package com.continuuity.test; import com.continuuity.api.data.DataSet; /** * Instance of this class is for managing deployed application. * * @see AppFabricTestBase#deployApplication(Class) */ public interface ApplicationManager { /** * Starts a flow. * @param flowName Name of the flow to start. * @return A {@link FlowManager} for controlling the started flow. */ FlowManager startFlow(String flowName); /** * Starts a procedure. * @param procedureName Name of the procedure to start. * @return A {@link ProcedureManager} for controlling the started procedure. */ ProcedureManager startProcedure(String procedureName); /** * Gets a {@link StreamWriter} for writing data to the given stream. * @param streamName Name of the stream to write to. * @return A {@link StreamWriter}. */ StreamWriter getStreamWriter(String streamName); /** * Gets an instance of {@link DataSet} of the given dataset name. * Operations on the returned {@link DataSet} always perform synchronously, * i.e. no support on multi-operations transaction. * @param dataSetName Name of the dataset to retrieve. * @param <T> Type of the dataset. * @return A {@link DataSet} instance of the given dataset type. */ <T extends DataSet> T getDataSet(String dataSetName); /** * Stops all processors managed by this manager and clear all associated runtime metrics. */ void stopAll(); }
package com.coremedia.iso; import com.coremedia.iso.boxes.AbstractBox; import com.coremedia.iso.boxes.Box; import com.coremedia.iso.boxes.fragment.MovieFragmentBox; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.Enumeration; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A Property file based BoxFactory */ public class PropertyBoxParserImpl extends AbstractBoxParser { Properties mapping; public PropertyBoxParserImpl(String... customProperties) { InputStream is = getClass().getResourceAsStream("/isoparser-default.properties"); mapping = new Properties(); try { mapping.load(is); Enumeration<URL> enumeration = Thread.currentThread().getContextClassLoader().getResources("isoparser-custom.properties"); while (enumeration.hasMoreElements()) { URL url = enumeration.nextElement(); mapping.load(url.openStream()); } for (String customProperty : customProperties) { mapping.load(getClass().getResourceAsStream(customProperty)); } } catch (IOException e) { throw new RuntimeException(e); } } public PropertyBoxParserImpl(Properties mapping) { this.mapping = mapping; } Pattern p = Pattern.compile("(.*)\\((.*?)\\)"); @Override @SuppressWarnings("unchecked") public Class<? extends Box> getClassForFourCc(byte[] type, byte[] parent) { FourCcToBox fourCcToBox = new FourCcToBox(type, parent).invoke(); try { return (Class<? extends Box>) Class.forName(fourCcToBox.clazzName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @Override public AbstractBox createBox(byte[] type, byte[] userType, byte[] parent, Box lastMovieFragmentBox) { FourCcToBox fourCcToBox = new FourCcToBox(type, parent).invoke(); String[] param = fourCcToBox.getParam(); String clazzName = fourCcToBox.getClazzName(); try { if (param[0].trim().length() == 0) { param = new String[]{}; } Class clazz = Class.forName(clazzName); Class[] constructorArgsClazz = new Class[param.length]; Object[] constructorArgs = new Object[param.length]; for (int i = 0; i < param.length; i++) { if ("userType".equals(param[i])) { constructorArgs[i] = userType; constructorArgsClazz[i] = byte[].class; } else if ("type".equals(param[i])) { constructorArgs[i] = type; constructorArgsClazz[i] = byte[].class; } else if ("parent".equals(param[i])) { constructorArgs[i] = parent; constructorArgsClazz[i] = byte[].class; } else if ("lastMovieFragmentBox".equals(param[i])) { constructorArgs[i] = lastMovieFragmentBox; constructorArgsClazz[i] = MovieFragmentBox.class; } else { throw new InternalError("No such param: " + param[i]); } } Constructor<AbstractBox> constructorObject; try { if (param.length > 0) { constructorObject = clazz.getConstructor(constructorArgsClazz); } else { constructorObject = clazz.getConstructor(); } return constructorObject.newInstance(constructorArgs); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private class FourCcToBox { private byte[] type; private byte[] parent; private String clazzName; private String[] param; public FourCcToBox(byte[] type, byte... parent) { this.type = type; this.parent = parent; } public String getClazzName() { return clazzName; } public String[] getParam() { return param; } public FourCcToBox invoke() { String constructor = mapping.getProperty(IsoFile.bytesToFourCC(parent) + "-" + IsoFile.bytesToFourCC(type)); if (constructor == null) { constructor = mapping.getProperty(IsoFile.bytesToFourCC(type)); } if (constructor == null) { constructor = mapping.getProperty("default"); } if (constructor == null) { throw new RuntimeException("No box object found for " + IsoFile.bytesToFourCC(type)); } Matcher m = p.matcher(constructor); boolean matches = m.matches(); if (!matches) { throw new RuntimeException("Cannot work with that constructor: " + constructor); } clazzName = m.group(1); param = m.group(2).split(","); return this; } } }
package com.crystalcraftmc.crystalspace; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import java.io.*; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.*; /** * Tooling to post to metrics.griefcraft.com */ public class Metrics { /** * Interface used to collect custom data for a plugin */ public static abstract class Plotter { /** * Get the column name for the plotted point * * @return the plotted point's column name */ public abstract String getColumnName(); /** * Get the current value for the plotted point * * @return */ public abstract int getValue(); /** * Called after the website graphs have been updated */ public void reset() { } @Override public int hashCode() { return getColumnName().hashCode() + getValue(); } @Override public boolean equals(Object object) { if (!(object instanceof Plotter)) { return false; } Plotter plotter = (Plotter) object; return plotter.getColumnName().equals(getColumnName()) && plotter.getValue() == getValue(); } } /** * The metrics revision number */ private final static int REVISION = 4; /** * The base url of the metrics domain */ private static final String BASE_URL = "http://metrics.griefcraft.com"; /** * The url used to report a server's status */ private static final String REPORT_URL = "/report/%s"; /** * The file where guid and opt out is stored in */ private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml"; /** * Interval of time to ping in minutes */ private final static int PING_INTERVAL = 10; /** * A map of the custom data plotters for plugins */ private Map<Plugin, Set<Plotter>> customData = Collections.synchronizedMap(new HashMap<Plugin, Set<Plotter>>()); /** * The plugin configuration file */ private final YamlConfiguration configuration; /** * Unique server id */ private String guid; public Metrics() throws IOException { // load the config File file = new File(CONFIG_FILE); configuration = YamlConfiguration.loadConfiguration(file); // add some defaults configuration.addDefault("opt-out", false); configuration.addDefault("guid", UUID.randomUUID().toString()); // Do we need to create the file? if (configuration.get("guid", null) == null) { configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true); configuration.save(file); } // Load the guid then guid = configuration.getString("guid"); } /** * Adds a custom data plotter for a given plugin * * @param plugin * @param plotter */ public void addCustomData(Plugin plugin, Plotter plotter) { Set<Plotter> plotters = customData.get(plugin); if (plotters == null) { plotters = Collections.synchronizedSet(new LinkedHashSet<Plotter>()); customData.put(plugin, plotters); } plotters.add(plotter); } /** * Begin measuring a plugin * * @param plugin */ public void beginMeasuringPlugin(final Plugin plugin) throws IOException { // Did we opt out? if (configuration.getBoolean("opt-out", false)) { return; } // First tell the server about us postPlugin(plugin, false); // Ping the server in intervals plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { public void run() { try { postPlugin(plugin, true); } catch (IOException e) { System.out.println("[Metrics] " + e.getMessage()); } } }, PING_INTERVAL * 1200, PING_INTERVAL * 1200); } /** * Generic method that posts a plugin to the metrics website * * @param plugin */ private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + '=' + encode(guid) + '&' + encode("version") + '=' + encode(plugin.getDescription().getVersion()) + '&' + encode("server") + '=' + encode(Bukkit.getVersion()) //+ '&' + encode("players") + '=' + encode(String.valueOf(Bukkit.getServer().getOnlinePlayers().length)) + '&' + encode("revision") + '=' + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += '&' + encode("ping") + '=' + encode("true"); } // Add any custom data (if applicable) Set<Plotter> plotters = customData.get(plugin); if (plotters != null) { for (Plotter plotter : plotters) { data += "&" + encode("Custom" + plotter.getColumnName()) + "=" + encode(Integer.toString(plotter.getValue())); } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("ERR")) { throw new IOException(response); //Throw the exception } else { // Is this the first update this hour? if (response.contains("OK This is your first update this hour")) { if (plotters != null) { for (Plotter plotter : plotters) { plotter.reset(); } } } } //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right } /** * Check if mineshafter is present. If it is, we need to bypass it to send POST requests * * @return */ private boolean isMineshafterPresent() { try { Class.forName("mineshafter.MineServer"); return true; } catch (Exception e) { return false; } } /** * Encode text as UTF-8 * * @param text * @return */ private static String encode(String text) throws UnsupportedEncodingException { return URLEncoder.encode(text, "UTF-8"); } }
package com.dak.duty.controller; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.dak.duty.form.SetupForm; import com.dak.duty.model.Email; import com.dak.duty.repository.PersonRepository; import com.dak.duty.service.EmailService; import com.dak.duty.service.InitialisationService; @Controller @RequestMapping("/setup") public class SetupController { private static final Logger logger = LoggerFactory.getLogger(SetupController.class); @Autowired EmailService emailService; @Autowired InitialisationService initService; @Autowired PersonRepository personRepos; @Autowired @Qualifier("authenticationManager") AuthenticationManager authenticationManager; @RequestMapping(method = RequestMethod.GET) public String getSetup(Model model){ model.addAttribute("setupForm", new SetupForm()); return "setup/setup"; } @RequestMapping(method = RequestMethod.POST) public String postSetup(@Valid SetupForm form, BindingResult bindingResult, Model model, HttpServletRequest request){ logger.info("postSetup({})", form); if (bindingResult.hasErrors() || !form.getPassword().equals(form.getConfirmPassword())) { if(form.getPassword() == null || !form.getPassword().equals(form.getConfirmPassword())){ bindingResult.rejectValue("confirmPassword", null, "Passwords must match!"); } model.addAttribute("setupForm", form); return "setup/setup"; } // create admin user initService.createDefaultAdminUser(form.getEmailAddress().trim(), form.getPassword(), form.getNameLast().trim(), form.getNameFirst().trim()); // log in as newly created user doAutoLogin(form.getEmailAddress().trim(), form.getPassword(), request); // send welcome email try { emailService.send(new Email("admin@duty.dak.rocks", form.getEmailAddress().trim(), "Welcome to Duty Roster!", "We hope you like it!")); } catch (Exception e){ logger.error("error: {}", e); } return "redirect:/admin"; } private void doAutoLogin(String username, String password, HttpServletRequest request) { try { // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = authenticationManager.authenticate(token); logger.debug("Logging in with [{}]", authentication.getPrincipal()); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (Exception e) { SecurityContextHolder.getContext().setAuthentication(null); logger.error("Failure in autoLogin", e); } } }
package com.dedao.lints; import com.android.SdkConstants; import com.android.tools.lint.detector.api.Category; import com.android.tools.lint.detector.api.Context; import com.android.tools.lint.detector.api.Detector; import com.android.tools.lint.detector.api.Implementation; import com.android.tools.lint.detector.api.Issue; import com.android.tools.lint.detector.api.JavaContext; import com.android.tools.lint.detector.api.Location; import com.android.tools.lint.detector.api.Scope; import com.android.tools.lint.detector.api.Severity; import com.android.tools.lint.detector.api.TextFormat; import com.intellij.psi.PsiClass; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; /** * user liushuo * date 2017/4/27 */ public class AutoPointerFileDetector extends Detector implements Detector.JavaPsiScanner { private static final String CLASS_RECYCLERVIEW = "android.support.v7.widget.RecyclerView"; public static final Issue ISSUE_NO_FILE = Issue.create( "NoFile", "no file", "no file", Category.CORRECTNESS, 10, Severity.FATAL, new Implementation( AutoPointerFileDetector.class, Scope.JAVA_FILE_SCOPE)); public static final Issue ISSUE_UN_REGISTER_VIEW = Issue.create( "UnRegisterView", "unregister view", "unregister view", Category.CORRECTNESS, 10, Severity.FATAL, new Implementation( AutoPointerFileDetector.class, Scope.JAVA_FILE_SCOPE)); private Set<String> mSet = new HashSet<>(); @Override public List<String> applicableSuperClasses() { return Collections.singletonList(CLASS_RECYCLERVIEW); } @Override public void checkClass(JavaContext context, PsiClass node) { super.checkClass(context, node); String name = node.getName(); mSet.add(name); } @Override public void afterCheckProject(Context context) { super.afterCheckProject(context); File dir = context.getMainProject().getDir(); File parentDir = dir.getParentFile(); boolean gradleExists = new File(parentDir, SdkConstants.FN_BUILD_GRADLE).exists(); if (!gradleExists) { return; } File file = new File(parentDir, "file.properties"); if (!file.exists()) { context.report(ISSUE_NO_FILE, Location.create(context.file), "no file in project reference dir '" + parentDir.getAbsolutePath() + "'"); return; } try { FileInputStream fis = new FileInputStream(file); Properties properties = new Properties(); properties.load(fis); Iterator<String> itr = mSet.iterator(); while (itr.hasNext()) { String key = itr.next(); String value = properties.getProperty(key); if (value == null || value.isEmpty()) { context.report(ISSUE_UN_REGISTER_VIEW, Location.create(context.file), "unregister view(" + key + ") at project " + context.getProject().getName()); } } } catch (Exception e) { e.printStackTrace(); } } }
package com.elmakers.mine.bukkit.utility; import java.lang.ref.WeakReference; import com.elmakers.mine.bukkit.block.MaterialAndData; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.magic.Mage; public class Target implements Comparable<Target> { public static boolean DEBUG_TARGETING = false; protected int maxDistanceSquared = 128 * 128; protected int minDistanceSquared = 0; protected double maxAngle = 0.3; protected boolean useHitbox = false; protected double hitboxPadding = 0; protected float distanceWeight = 1; protected float fovWeight = 4; protected int npcWeight = -1; protected int playerWeight = 4; protected int livingEntityWeight = 3; protected int mageWeight = 5; protected double closeDistanceSquared = 1; protected double closeAngle = Math.PI / 2; private Location source; private Location location; private MaterialAndData locationMaterial; private WeakReference<Entity> _entity; private Mage mage; private boolean reverseDistance = false; private double distanceSquared = 100000; private double angle = 10000; private int score = 0; private Object extraData = null; public Target(Location sourceLocation) { this.source = sourceLocation; } public void setBlock(Block block) { if (block != null) { this.location = block.getLocation(); this.location.add(0.5, 0.5, 0.5); } } public Target(Location sourceLocation, Block block) { this.source = sourceLocation; this.locationMaterial = new MaterialAndData(block); this.setBlock(block); calculateScore(); } public Target(Location sourceLocation, Block block, boolean hitbox, double hitboxPadding) { this.source = sourceLocation; this.locationMaterial = new MaterialAndData(block); this.useHitbox = hitbox; this.hitboxPadding = hitboxPadding; this.setBlock(block); calculateScore(); } public Target(Location sourceLocation, Block block, int range) { this(sourceLocation, block, range, 0.3, false); } public Target(Location sourceLocation, Block block, int range, double angle) { this(sourceLocation, block, range, angle, false); } public Target(Location sourceLocation, Block block, int range, double angle, boolean reverseDistance) { this.maxDistanceSquared = range * range; this.maxAngle = angle; this.reverseDistance = reverseDistance; this.source = sourceLocation; this.setBlock(block); this.locationMaterial = new MaterialAndData(block); calculateScore(); } public Target(Location sourceLocation, Block block, int minRange, int maxRange, double angle, boolean reverseDistance) { this.maxDistanceSquared = maxRange * maxRange; this.minDistanceSquared = minRange * minRange; this.maxAngle = angle; this.reverseDistance = reverseDistance; this.source = sourceLocation; this.setBlock(block); this.locationMaterial = new MaterialAndData(block); calculateScore(); } public Target(Location sourceLocation, Entity entity, int range) { this.maxDistanceSquared = range * range; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); calculateScore(); } public Target(Location sourceLocation, Entity entity, int range, boolean hitbox, double hitboxPadding) { this.maxDistanceSquared = range * range; this.source = sourceLocation; this.useHitbox = hitbox; this.hitboxPadding = hitboxPadding; this._entity = new WeakReference<Entity>(entity); if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); calculateScore(); } public Target(Location sourceLocation, Entity entity, int range, double angle) { this.maxDistanceSquared = range * range; this.maxAngle = angle; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); calculateScore(); } public Target(Location sourceLocation, Entity entity, int range, double angle, double closeRange, double closeAngle, float distanceWeight, float fovWeight, int mageWeight, int npcWeight, int playerWeight, int livingEntityWeight) { this.closeDistanceSquared = closeRange * closeRange; this.closeAngle = closeAngle; this.maxDistanceSquared = range * range; this.maxAngle = angle; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); this.distanceWeight = distanceWeight; this.fovWeight = fovWeight; this.mageWeight = mageWeight; this.npcWeight = npcWeight; this.playerWeight = playerWeight; this.livingEntityWeight = livingEntityWeight; if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); calculateScore(); } public Target(Location sourceLocation, Entity entity, int range, double angle, double closeRange, double closeAngle) { this.closeDistanceSquared = closeRange * closeRange; this.closeAngle = closeAngle; this.maxDistanceSquared = range * range; this.maxAngle = angle; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); calculateScore(); } public Target(Location sourceLocation, Entity entity, int range, double angle, boolean reverseDistance) { this.maxDistanceSquared = range * range; this.maxAngle = angle; this.reverseDistance = reverseDistance; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); calculateScore(); } public Target(Location sourceLocation, Entity entity, int minRange, int maxRange, double angle, boolean reverseDistance) { this.maxDistanceSquared = maxRange * maxRange; this.minDistanceSquared = minRange * minRange; this.maxAngle = angle; this.reverseDistance = reverseDistance; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); calculateScore(); } public Target(Location sourceLocation, Mage mage, int minRange, int maxRange, double angle, boolean reverseDistance) { this.maxDistanceSquared = maxRange * maxRange; this.minDistanceSquared = minRange * minRange; this.maxAngle = angle; this.reverseDistance = reverseDistance; this.source = sourceLocation; this.mage = mage; if (mage != null) { this._entity = new WeakReference<Entity>(mage.getLivingEntity()); } if (mage != null) this.location = mage.getEyeLocation(); calculateScore(); } public Target(Location sourceLocation, Entity entity) { this.maxDistanceSquared = 0; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); if (entity != null) this.location = CompatibilityUtils.getEyeLocation(entity); } public Target(Location sourceLocation, Entity entity, Block block) { this.maxDistanceSquared = 0; this.source = sourceLocation; this._entity = new WeakReference<Entity>(entity); if (block != null) { this.setBlock(block); } else if (entity != null) { this.location = CompatibilityUtils.getEyeLocation(entity); } } public int getScore() { return score; } protected void calculateScore() { score = 0; if (source == null) return; Vector sourceDirection = source.getDirection(); Vector sourceLocation = new Vector(source.getX(), source.getY(), source.getZ()); Location targetLocation = getLocation(); if (targetLocation == null) return; Vector targetLoc = new Vector(targetLocation.getX(), targetLocation.getY(), targetLocation.getZ()); Vector targetDirection = new Vector(targetLoc.getX() - sourceLocation.getX(), targetLoc.getY() - sourceLocation.getY(), targetLoc.getZ() - sourceLocation.getZ()); distanceSquared = targetDirection.lengthSquared(); if (maxDistanceSquared > 0 && distanceSquared > maxDistanceSquared) return; if (distanceSquared < minDistanceSquared) return; Entity entity = getEntity(); if (useHitbox) { double checkDistance = Math.max(maxDistanceSquared, 2); Vector endPoint = sourceLocation.clone().add(sourceDirection.clone().multiply(checkDistance)); // Back up just a wee bit Vector startPoint = sourceLocation.clone().add(sourceDirection.multiply(-0.1)); BoundingBox hitbox = null; if (entity != null) { hitbox = CompatibilityUtils.getHitbox(entity); } if (hitbox == null) { // We make this a little smaller to ensure the coordinates stay inside the block hitbox = new BoundingBox(targetLoc, -0.499, 0.499, -0.499, 0.499, -0.499, 0.499); if (DEBUG_TARGETING) { if (entity != null) { org.bukkit.Bukkit.getLogger().info(" failed to get hitbox for " + entity.getType() + " : " + targetLoc); } else { org.bukkit.Bukkit.getLogger().info(" got hitbox for block " + getBlock() + " : " + hitbox); } } } if (hitboxPadding > 0) { hitbox.expand(hitboxPadding); } if (DEBUG_TARGETING && entity != null) { org.bukkit.Bukkit.getLogger().info("CHECKING " + entity.getType() + ": " + hitbox + ", " + startPoint + " - " + endPoint + ": " + hitbox.intersectsLine(sourceLocation, endPoint)); } if (!hitbox.intersectsLine(startPoint, endPoint)) { if (DEBUG_TARGETING && entity != null) { org.bukkit.Bukkit.getLogger().info(" block hitbox test failed from " + sourceLocation); } return; } Vector hit = hitbox.getIntersection(startPoint, endPoint); if (hit != null) { location.setX(hit.getX()); location.setY(hit.getY()); location.setZ(hit.getZ()); distanceSquared = location.distanceSquared(source); } if (DEBUG_TARGETING) { org.bukkit.Bukkit.getLogger().info("HIT: " + hit); } } else { angle = targetDirection.angle(sourceDirection); double checkAngle = maxAngle; if (closeDistanceSquared > 0 && maxDistanceSquared > closeDistanceSquared) { if (distanceSquared <= closeDistanceSquared) { checkAngle = closeAngle; } else { double ratio = (distanceSquared - closeDistanceSquared) / (maxDistanceSquared - closeDistanceSquared); checkAngle = closeAngle - ratio * (closeAngle - maxAngle); } } if (DEBUG_TARGETING && hasEntity()) { org.bukkit.Bukkit.getLogger().info("CHECKING " + getEntity().getType() + " (" + closeDistanceSquared + ") " + " angle = " + angle + " against " + checkAngle + " at distance " + distanceSquared + " rangeA = (" + closeAngle + " to " + maxAngle + "), rangeD = (" + closeDistanceSquared + " to " + maxDistanceSquared + ")" + " ... from " + sourceLocation + " to " + targetLoc); } if (checkAngle > 0 && angle > checkAngle) return; } if (reverseDistance) { distanceSquared = maxDistanceSquared - distanceSquared; } score = 1; // Apply scoring weights if (maxDistanceSquared > 0) score += (maxDistanceSquared - distanceSquared) * distanceWeight; if (!useHitbox && angle > 0) score += (3 - angle) * fovWeight; if (entity != null && mage != null && mage.getController().isNPC(entity)) { score = score + npcWeight; } else if (mage != null) { score = score + mageWeight; } else if (entity instanceof Player) { score = score + playerWeight; } else if (entity instanceof LivingEntity) { score = score + livingEntityWeight; } if (DEBUG_TARGETING && entity != null) { org.bukkit.Bukkit.getLogger().info("TARGETED " + entity.getType() + ": r2=" + distanceSquared + " (" + distanceWeight + "), a=" + angle + " (" + fovWeight + "), score: " + score); } } public int compareTo(Target other) { return other.score - this.score; } public boolean hasEntity() { return getEntity() != null; } public boolean isValid() { return location != null; } public boolean hasTarget() { return location != null; } public Entity getEntity() { return _entity == null ? null : _entity.get(); } public Block getBlock() { if (location == null) { return null; } return location.getBlock(); } public double getDistanceSquared() { return distanceSquared; } public Location getLocation() { return location; } public void add(Vector offset) { if (location != null) { location = location.add(offset); } } public void setDirection(Vector direction) { if (location != null) { location = location.setDirection(direction); } } public void setWorld(World world) { if (location != null) { location.setWorld(world); } } public Object getExtraData() { return extraData; } public void setExtraData(Object extraData) { this.extraData = extraData; } public void setEntity(Entity entity) { this._entity = new WeakReference<Entity>(entity); if (entity != null) { this.location = entity.getLocation(); } this.calculateScore(); } public MaterialAndData getTargetedMaterial() { return locationMaterial; } }
package com.fasterxml.jackson.databind; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.node.JsonNodeType; import com.fasterxml.jackson.databind.node.MissingNode; import com.fasterxml.jackson.databind.util.ClassUtil; /** * Base class for all JSON nodes, which form the basis of JSON * Tree Model that Jackson implements. * One way to think of these nodes is to consider them * similar to DOM nodes in XML DOM trees. *<p> * As a general design rule, most accessors ("getters") are included * in this base class, to allow for traversing structure without * type casts. Most mutators, however, need to be accessed through * specific sub-classes (such as <code>ObjectNode</code> * and <code>ArrayNode</code>). * This seems sensible because proper type * information is generally available when building or modifying * trees, but less often when reading a tree (newly built from * parsed JSON content). *<p> * Actual concrete sub-classes can be found from package * {@link com.fasterxml.jackson.databind.node}. *<p> * Note that it is possible to "read" from nodes, using * method {@link TreeNode#traverse(ObjectCodec)}, which will result in * a {@link JsonParser} being constructed. This can be used for (relatively) * efficient conversations between different representations; and it is what * core databind uses for methods like {@link ObjectMapper#treeToValue(TreeNode, Class)} * and {@link ObjectMapper#treeAsTokens(TreeNode)} */ public abstract class JsonNode extends JsonSerializable.Base // i.e. implements JsonSerializable implements TreeNode, Iterable<JsonNode> { protected JsonNode() { } /** * Method that can be called to get a node that is guaranteed * not to allow changing of this node through mutators on * this node or any of its children. * This means it can either make a copy of this node (and all * mutable children and grand children nodes), or node itself * if it is immutable. *<p> * Note: return type is guaranteed to have same type as the * node method is called on; which is why method is declared * with local generic type. * * @since 2.0 * * @return Node that is either a copy of this node (and all non-leaf * children); or, for immutable leaf nodes, node itself. */ public abstract <T extends JsonNode> T deepCopy(); // public abstract JsonToken asToken(); // public abstract JsonToken traverse(); // public abstract JsonToken traverse(ObjectCodec codec); // public abstract JsonParser.NumberType numberType(); @Override public int size() { return 0; } /** * Convenience method that is functionally same as: *<pre> * size() == 0 *</pre> * for all node types. * * @since 2.10 */ public boolean isEmpty() { return size() == 0; } @Override public final boolean isValueNode() { switch (getNodeType()) { case ARRAY: case OBJECT: case MISSING: return false; default: return true; } } @Override public final boolean isContainerNode() { final JsonNodeType type = getNodeType(); return type == JsonNodeType.OBJECT || type == JsonNodeType.ARRAY; } @Override public boolean isMissingNode() { return false; } @Override public boolean isArray() { return false; } @Override public boolean isObject() { return false; } /** * Method for accessing value of the specified element of * an array node. For other nodes, null is always returned. *<p> * For array nodes, index specifies * exact location within array and allows for efficient iteration * over child elements (underlying storage is guaranteed to * be efficiently indexable, i.e. has random-access to elements). * If index is less than 0, or equal-or-greater than * <code>node.size()</code>, null is returned; no exception is * thrown for any index. *<p> * NOTE: if the element value has been explicitly set as <code>null</code> * (which is different from removal!), * a {@link com.fasterxml.jackson.databind.node.NullNode} will be returned, * not null. * * @return Node that represent value of the specified element, * if this node is an array and has specified element. * Null otherwise. */ @Override public abstract JsonNode get(int index); /** * Method for accessing value of the specified field of * an object node. If this node is not an object (or it * does not have a value for specified field name), or * if there is no field with such name, null is returned. *<p> * NOTE: if the property value has been explicitly set as <code>null</code> * (which is different from removal!), * a {@link com.fasterxml.jackson.databind.node.NullNode} will be returned, * not null. * * @return Node that represent value of the specified field, * if this node is an object and has value for the specified * field. Null otherwise. */ @Override public JsonNode get(String fieldName) { return null; } /** * This method is similar to {@link #get(String)}, except * that instead of returning null if no such value exists (due * to this node not being an object, or object not having value * for the specified field), * a "missing node" (node that returns true for * {@link #isMissingNode}) will be returned. This allows for * convenient and safe chained access via path calls. */ @Override public abstract JsonNode path(String fieldName); /** * This method is similar to {@link #get(int)}, except * that instead of returning null if no such element exists (due * to index being out of range, or this node not being an array), * a "missing node" (node that returns true for * {@link #isMissingNode}) will be returned. This allows for * convenient and safe chained access via path calls. */ @Override public abstract JsonNode path(int index); @Override public Iterator<String> fieldNames() { return ClassUtil.emptyIterator(); } /** * Method for locating node specified by given JSON pointer instances. * Method will never return null; if no matching node exists, * will return a node for which {@link #isMissingNode()} returns true. * * @return Node that matches given JSON Pointer: if no match exists, * will return a node for which {@link #isMissingNode()} returns true. * * @since 2.3 */ @Override public final JsonNode at(JsonPointer ptr) { // Basically: value nodes only match if we have "empty" path left if (ptr.matches()) { return this; } JsonNode n = _at(ptr); if (n == null) { return MissingNode.getInstance(); } return n.at(ptr.tail()); } /** * Convenience method that is functionally equivalent to: *<pre> * return at(JsonPointer.valueOf(jsonPointerExpression)); *</pre> *<p> * Note that if the same expression is used often, it is preferable to construct * {@link JsonPointer} instance once and reuse it: this method will not perform * any caching of compiled expressions. * * @param jsonPtrExpr Expression to compile as a {@link JsonPointer} * instance * * @return Node that matches given JSON Pointer: if no match exists, * will return a node for which {@link TreeNode#isMissingNode()} returns true. * * @since 2.3 */ @Override public final JsonNode at(String jsonPtrExpr) { return at(JsonPointer.compile(jsonPtrExpr)); } /** * Helper method used by other methods for traversing the next step * of given path expression, and returning matching value node if any: * if no match, {@code null} is returned. * * @param ptr Path expression to use * * @return Either matching {@link JsonNode} for the first step of path or * {@code null} if no match (including case that this node is not a container) */ protected abstract JsonNode _at(JsonPointer ptr); // // First high-level division between values, containers and "missing" /** * Return the type of this node * * @return the node type as a {@link JsonNodeType} enum value * * @since 2.2 */ public abstract JsonNodeType getNodeType(); /** * Method that can be used to check if the node is a wrapper * for a POJO ("Plain Old Java Object" aka "bean". * Returns true only for * instances of <code>POJONode</code>. * * @return True if this node wraps a POJO */ public final boolean isPojo() { return getNodeType() == JsonNodeType.POJO; } /** * @return True if this node represents a numeric JSON value */ public final boolean isNumber() { return getNodeType() == JsonNodeType.NUMBER; } /** * * @return True if this node represents an integral (integer) * numeric JSON value */ public boolean isIntegralNumber() { return false; } /** * @return True if this node represents a non-integral * numeric JSON value */ public boolean isFloatingPointNumber() { return false; } /** * Method that can be used to check whether contained value * is a number represented as Java <code>short</code>. * Note, however, that even if this method returns false, it * is possible that conversion would be possible from other numeric * types -- to check if this is possible, use * {@link #canConvertToInt()} instead. * * @return True if the value contained by this node is stored as Java short */ public boolean isShort() { return false; } /** * Method that can be used to check whether contained value * is a number represented as Java <code>int</code>. * Note, however, that even if this method returns false, it * is possible that conversion would be possible from other numeric * types -- to check if this is possible, use * {@link #canConvertToInt()} instead. * * @return True if the value contained by this node is stored as Java int */ public boolean isInt() { return false; } /** * Method that can be used to check whether contained value * is a number represented as Java <code>long</code>. * Note, however, that even if this method returns false, it * is possible that conversion would be possible from other numeric * types -- to check if this is possible, use * {@link #canConvertToLong()} instead. * * @return True if the value contained by this node is stored as Java <code>long</code> */ public boolean isLong() { return false; } /** * @since 2.2 */ public boolean isFloat() { return false; } public boolean isDouble() { return false; } public boolean isBigDecimal() { return false; } public boolean isBigInteger() { return false; } /** * Method that checks whether this node represents basic JSON String * value. */ public final boolean isTextual() { return getNodeType() == JsonNodeType.STRING; } /** * Method that can be used to check if this node was created from * JSON boolean value (literals "true" and "false"). */ public final boolean isBoolean() { return getNodeType() == JsonNodeType.BOOLEAN; } /** * Method that can be used to check if this node was created from * JSON literal null value. */ public final boolean isNull() { return getNodeType() == JsonNodeType.NULL; } /** * Method that can be used to check if this node represents * binary data (Base64 encoded). Although this will be externally * written as JSON String value, {@link #isTextual} will * return false if this method returns true. * * @return True if this node represents base64 encoded binary data */ public final boolean isBinary() { return getNodeType() == JsonNodeType.BINARY; } /** * Method that can be used to check whether this node is a numeric * node ({@link #isNumber} would return true) AND its value fits * within Java's 32-bit signed integer type, <code>int</code>. * Note that floating-point numbers are convertible if the integral * part fits without overflow (as per standard Java coercion rules) *<p> * NOTE: this method does not consider possible value type conversion * from JSON String into Number; so even if this method returns false, * it is possible that {@link #asInt} could still succeed * if node is a JSON String representing integral number, or boolean. * * @since 2.0 */ public boolean canConvertToInt() { return false; } /** * Method that can be used to check whether this node is a numeric * node ({@link #isNumber} would return true) AND its value fits * within Java's 64-bit signed integer type, <code>long</code>. * Note that floating-point numbers are convertible if the integral * part fits without overflow (as per standard Java coercion rules) *<p> * NOTE: this method does not consider possible value type conversion * from JSON String into Number; so even if this method returns false, * it is possible that {@link #asLong} could still succeed * if node is a JSON String representing integral number, or boolean. * * @since 2.0 */ public boolean canConvertToLong() { return false; } /** * Method that can be used to check whether contained value * is numeric (returns true for {@link #isNumber()}) and * can be losslessly converted to integral number (specifically, * {@link BigInteger} but potentially others, see * {@link #canConvertToInt} and {@link #canConvertToInt}). * Latter part allows floating-point numbers * (for which {@link #isFloatingPointNumber()} returns {@code true}) * that do not have fractional part. * Note that "not-a-number" values of {@code double} and {@code float} * will return {@code false} as they can not be converted to matching * integral representations. * * @return True if the value is an actual number with no fractional * part; false for non-numeric types, NaN representations of floating-point * numbers, and floating-point numbers with fractional part. * * @since 2.12 */ public boolean canConvertToExactIntegral() { return isIntegralNumber(); } /** * Method to use for accessing String values. * Does <b>NOT</b> do any conversions for non-String value nodes; * for non-String values (ones for which {@link #isTextual} returns * false) null will be returned. * For String values, null is never returned (but empty Strings may be) * * @return Textual value this node contains, iff it is a textual * JSON node (comes from JSON String value entry) */ public String textValue() { return null; } /** * Method to use for accessing binary content of binary nodes (nodes * for which {@link #isBinary} returns true); or for Text Nodes * (ones for which {@link #textValue} returns non-null value), * to read decoded base64 data. * For other types of nodes, returns null. * * @return Binary data this node contains, iff it is a binary * node; null otherwise */ public byte[] binaryValue() throws IOException { return null; } /** * Method to use for accessing JSON boolean values (value * literals 'true' and 'false'). * For other types, always returns false. * * @return Textual value this node contains, iff it is a textual * json node (comes from JSON String value entry) */ public boolean booleanValue() { return false; } /** * Returns numeric value for this node, <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true); otherwise * returns null * * @return Number value this node contains, if any (null for non-number * nodes). */ public Number numberValue() { return null; } /** * Returns 16-bit short value for this node, <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true). For other * types returns 0. * For floating-point numbers, value is truncated using default * Java coercion, similar to how cast from double to short operates. * * @return Short value this node contains, if any; 0 for non-number * nodes. */ public short shortValue() { return 0; } /** * Returns integer value for this node, <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true). For other * types returns 0. * For floating-point numbers, value is truncated using default * Java coercion, similar to how cast from double to int operates. * * @return Integer value this node contains, if any; 0 for non-number * nodes. */ public int intValue() { return 0; } /** * Returns 64-bit long value for this node, <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true). For other * types returns 0. * For floating-point numbers, value is truncated using default * Java coercion, similar to how cast from double to long operates. * * @return Long value this node contains, if any; 0 for non-number * nodes. */ public long longValue() { return 0L; } /** * Returns 32-bit floating value for this node, <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true). For other * types returns 0.0. * For integer values, conversion is done using coercion; this means * that an overflow is possible for `long` values * * @return 32-bit float value this node contains, if any; 0.0 for non-number nodes. * * @since 2.2 */ public float floatValue() { return 0.0f; } /** * Returns 64-bit floating point (double) value for this node, <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true). For other * types returns 0.0. * For integer values, conversion is done using coercion; this may result * in overflows with {@link BigInteger} values. * * @return 64-bit double value this node contains, if any; 0.0 for non-number nodes. * * @since 2.2 */ public double doubleValue() { return 0.0; } /** * Returns floating point value for this node (as {@link BigDecimal}), <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true). For other * types returns <code>BigDecimal.ZERO</code>. * * @return {@link BigDecimal} value this node contains, if numeric node; <code>BigDecimal.ZERO</code> for non-number nodes. */ public BigDecimal decimalValue() { return BigDecimal.ZERO; } /** * Returns integer value for this node (as {@link BigInteger}), <b>if and only if</b> * this node is numeric ({@link #isNumber} returns true). For other * types returns <code>BigInteger.ZERO</code>. * * @return {@link BigInteger} value this node contains, if numeric node; <code>BigInteger.ZERO</code> for non-number nodes. */ public BigInteger bigIntegerValue() { return BigInteger.ZERO; } /** * Method that will return a valid String representation of * the container value, if the node is a value node * (method {@link #isValueNode} returns true), * otherwise empty String. */ public abstract String asText(); /** * Method similar to {@link #asText()}, except that it will return * <code>defaultValue</code> in cases where null value would be returned; * either for missing nodes (trying to access missing property, or element * at invalid item for array) or explicit nulls. * * @since 2.4 */ public String asText(String defaultValue) { String str = asText(); return (str == null) ? defaultValue : str; } /** * Method that will try to convert value of this node to a Java <b>int</b>. * Numbers are coerced using default Java rules; booleans convert to 0 (false) * and 1 (true), and Strings are parsed using default Java language integer * parsing rules. *<p> * If representation cannot be converted to an int (including structured types * like Objects and Arrays), * default value of <b>0</b> will be returned; no exceptions are thrown. */ public int asInt() { return asInt(0); } /** * Method that will try to convert value of this node to a Java <b>int</b>. * Numbers are coerced using default Java rules; booleans convert to 0 (false) * and 1 (true), and Strings are parsed using default Java language integer * parsing rules. *<p> * If representation cannot be converted to an int (including structured types * like Objects and Arrays), * specified <b>defaultValue</b> will be returned; no exceptions are thrown. */ public int asInt(int defaultValue) { return defaultValue; } /** * Method that will try to convert value of this node to a Java <b>long</b>. * Numbers are coerced using default Java rules; booleans convert to 0 (false) * and 1 (true), and Strings are parsed using default Java language integer * parsing rules. *<p> * If representation cannot be converted to a long (including structured types * like Objects and Arrays), * default value of <b>0</b> will be returned; no exceptions are thrown. */ public long asLong() { return asLong(0L); } /** * Method that will try to convert value of this node to a Java <b>long</b>. * Numbers are coerced using default Java rules; booleans convert to 0 (false) * and 1 (true), and Strings are parsed using default Java language integer * parsing rules. *<p> * If representation cannot be converted to a long (including structured types * like Objects and Arrays), * specified <b>defaultValue</b> will be returned; no exceptions are thrown. */ public long asLong(long defaultValue) { return defaultValue; } /** * Method that will try to convert value of this node to a Java <b>double</b>. * Numbers are coerced using default Java rules; booleans convert to 0.0 (false) * and 1.0 (true), and Strings are parsed using default Java language integer * parsing rules. *<p> * If representation cannot be converted to an int (including structured types * like Objects and Arrays), * default value of <b>0.0</b> will be returned; no exceptions are thrown. */ public double asDouble() { return asDouble(0.0); } /** * Method that will try to convert value of this node to a Java <b>double</b>. * Numbers are coerced using default Java rules; booleans convert to 0.0 (false) * and 1.0 (true), and Strings are parsed using default Java language integer * parsing rules. *<p> * If representation cannot be converted to an int (including structured types * like Objects and Arrays), * specified <b>defaultValue</b> will be returned; no exceptions are thrown. */ public double asDouble(double defaultValue) { return defaultValue; } /** * Method that will try to convert value of this node to a Java <b>boolean</b>. * JSON booleans map naturally; integer numbers other than 0 map to true, and * 0 maps to false * and Strings 'true' and 'false' map to corresponding values. *<p> * If representation cannot be converted to a boolean value (including structured types * like Objects and Arrays), * default value of <b>false</b> will be returned; no exceptions are thrown. */ public boolean asBoolean() { return asBoolean(false); } /** * Method that will try to convert value of this node to a Java <b>boolean</b>. * JSON booleans map naturally; integer numbers other than 0 map to true, and * 0 maps to false * and Strings 'true' and 'false' map to corresponding values. *<p> * If representation cannot be converted to a boolean value (including structured types * like Objects and Arrays), * specified <b>defaultValue</b> will be returned; no exceptions are thrown. */ public boolean asBoolean(boolean defaultValue) { return defaultValue; } public <T extends JsonNode> T require() throws IllegalArgumentException { return _this(); } public <T extends JsonNode> T requireNonNull() throws IllegalArgumentException { return _this(); } public JsonNode required(String propertyName) throws IllegalArgumentException { return _reportRequiredViolation("Node of type `%s` has no fields", getClass().getName()); } public JsonNode required(int index) throws IllegalArgumentException { return _reportRequiredViolation("Node of type `%s` has no indexed values", getClass().getName()); } public JsonNode requiredAt(String pathExpr) throws IllegalArgumentException { return requiredAt(JsonPointer.compile(pathExpr)); } public final JsonNode requiredAt(final JsonPointer path) throws IllegalArgumentException { JsonPointer currentExpr = path; JsonNode curr = this; // Note: copied from `at()` while (true) { if (currentExpr.matches()) { return curr; } curr = curr._at(currentExpr); // lgtm [java/dereferenced-value-may-be-null] if (curr == null) { _reportRequiredViolation("No node at '%s' (unmatched part: '%s')", path, currentExpr); } currentExpr = currentExpr.tail(); } } /** * Method that allows checking whether this node is JSON Object node * and contains value for specified property. If this is the case * (including properties with explicit null values), returns true; * otherwise returns false. *<p> * This method is equivalent to: *<pre> * node.get(fieldName) != null *</pre> * (since return value of get() is node, not value node contains) *<p> * NOTE: when explicit <code>null</code> values are added, this * method will return <code>true</code> for such properties. * * @param fieldName Name of element to check * * @return True if this node is a JSON Object node, and has a property * entry with specified name (with any value, including null value) */ public boolean has(String fieldName) { return get(fieldName) != null; } /** * Method that allows checking whether this node is JSON Array node * and contains a value for specified index * If this is the case * (including case of specified indexing having null as value), returns true; * otherwise returns false. *<p> * Note: array element indexes are 0-based. *<p> * This method is equivalent to: *<pre> * node.get(index) != null *</pre> *<p> * NOTE: this method will return <code>true</code> for explicitly added * null values. * * @param index Index to check * * @return True if this node is a JSON Object node, and has a property * entry with specified name (with any value, including null value) */ public boolean has(int index) { return get(index) != null; } /** * Method that is similar to {@link #has(String)}, but that will * return <code>false</code> for explicitly added nulls. *<p> * This method is functionally equivalent to: *<pre> * node.get(fieldName) != null &amp;&amp; !node.get(fieldName).isNull() *</pre> * * @since 2.1 */ public boolean hasNonNull(String fieldName) { JsonNode n = get(fieldName); return (n != null) && !n.isNull(); } /** * Method that is similar to {@link #has(int)}, but that will * return <code>false</code> for explicitly added nulls. *<p> * This method is equivalent to: *<pre> * node.get(index) != null &amp;&amp; !node.get(index).isNull() *</pre> * * @since 2.1 */ public boolean hasNonNull(int index) { JsonNode n = get(index); return (n != null) && !n.isNull(); } /** * Same as calling {@link #elements}; implemented so that * convenience "for-each" loop can be used for looping over elements * of JSON Array constructs. */ @Override public final Iterator<JsonNode> iterator() { return elements(); } /** * Method for accessing all value nodes of this Node, iff * this node is a JSON Array or Object node. In case of Object node, * field names (keys) are not included, only values. * For other types of nodes, returns empty iterator. */ public Iterator<JsonNode> elements() { return ClassUtil.emptyIterator(); } /** * @return Iterator that can be used to traverse all key/value pairs for * object nodes; empty iterator (no contents) for other types */ public Iterator<Map.Entry<String, JsonNode>> fields() { return ClassUtil.emptyIterator(); } /** * Method for finding a JSON Object field with specified name in this * node or its child nodes, and returning value it has. * If no matching field is found in this node or its descendants, returns null. * * @param fieldName Name of field to look for * * @return Value of first matching node found, if any; null if none */ public abstract JsonNode findValue(String fieldName); /** * Method for finding JSON Object fields with specified name, and returning * found ones as a List. Note that sub-tree search ends if a field is found, * so possible children of result nodes are <b>not</b> included. * If no matching fields are found in this node or its descendants, returns * an empty List. * * @param fieldName Name of field to look for */ public final List<JsonNode> findValues(String fieldName) { List<JsonNode> result = findValues(fieldName, null); if (result == null) { return Collections.emptyList(); } return result; } /** * Similar to {@link #findValues}, but will additionally convert * values into Strings, calling {@link #asText}. */ public final List<String> findValuesAsText(String fieldName) { List<String> result = findValuesAsText(fieldName, null); if (result == null) { return Collections.emptyList(); } return result; } /** * Method similar to {@link #findValue}, but that will return a * "missing node" instead of null if no field is found. Missing node * is a specific kind of node for which {@link #isMissingNode} * returns true; and all value access methods return empty or * missing value. * * @param fieldName Name of field to look for * * @return Value of first matching node found; or if not found, a * "missing node" (non-null instance that has no value) */ public abstract JsonNode findPath(String fieldName); /** * Method for finding a JSON Object that contains specified field, * within this node or its descendants. * If no matching field is found in this node or its descendants, returns null. * * @param fieldName Name of field to look for * * @return Value of first matching node found, if any; null if none */ public abstract JsonNode findParent(String fieldName); /** * Method for finding a JSON Object that contains specified field, * within this node or its descendants. * If no matching field is found in this node or its descendants, returns null. * * @param fieldName Name of field to look for * * @return Value of first matching node found, if any; null if none */ public final List<JsonNode> findParents(String fieldName) { List<JsonNode> result = findParents(fieldName, null); if (result == null) { return Collections.emptyList(); } return result; } public abstract List<JsonNode> findValues(String fieldName, List<JsonNode> foundSoFar); public abstract List<String> findValuesAsText(String fieldName, List<String> foundSoFar); public abstract List<JsonNode> findParents(String fieldName, List<JsonNode> foundSoFar); /** * Method that can be called on Object nodes, to access a property * that has Object value; or if no such property exists, to create, * add and return such Object node. * If the node method is called on is not Object node, * or if property exists and has value that is not Object node, * {@link UnsupportedOperationException} is thrown *<p> * NOTE: since 2.10 has had co-variant return type */ public <T extends JsonNode> T with(String propertyName) { throw new UnsupportedOperationException("JsonNode not of type ObjectNode (but " +getClass().getName()+"), cannot call with() on it"); } /** * Method that can be called on Object nodes, to access a property * that has <code>Array</code> value; or if no such property exists, to create, * add and return such Array node. * If the node method is called on is not Object node, * or if property exists and has value that is not Array node, * {@link UnsupportedOperationException} is thrown *<p> * NOTE: since 2.10 has had co-variant return type */ public <T extends JsonNode> T withArray(String propertyName) { throw new UnsupportedOperationException("JsonNode not of type ObjectNode (but " +getClass().getName()+"), cannot call withArray() on it"); } /** * Entry method for invoking customizable comparison, using passed-in * {@link Comparator} object. Nodes will handle traversal of structured * types (arrays, objects), but defer to comparator for scalar value * comparisons. If a "natural" {@link Comparator} is passed -- one that * simply calls <code>equals()</code> on one of arguments, passing the other * -- implementation is the same as directly calling <code>equals()</code> * on node. *<p> * Default implementation simply delegates to passed in <code>comparator</code>, * with <code>this</code> as the first argument, and <code>other</code> as * the second argument. * * @param comparator Object called to compare two scalar {@link JsonNode} * instances, and return either 0 (are equals) or non-zero (not equal) * * @since 2.6 */ public boolean equals(Comparator<JsonNode> comparator, JsonNode other) { return comparator.compare(this, other) == 0; } /** * Method that will produce (as of Jackson 2.10) valid JSON using * default settings of databind, as String. * If you want other kinds of JSON output (or output formatted using one of * other Jackson-supported data formats) make sure to use * {@link ObjectMapper} or {@link ObjectWriter} to serialize an * instance, for example: *<pre> * String json = objectMapper.writeValueAsString(rootNode); *</pre> *<p> * Note: method defined as abstract to ensure all implementation * classes explicitly implement method, instead of relying * on {@link Object#toString()} definition. */ @Override public abstract String toString(); /** * Alternative to {@link #toString} that will serialize this node using * Jackson default pretty-printer. * * @since 2.10 */ public String toPrettyString() { return toString(); } /** * Equality for node objects is defined as full (deep) value * equality. This means that it is possible to compare complete * JSON trees for equality by comparing equality of root nodes. *<p> * Note: marked as abstract to ensure all implementation * classes define it properly and not rely on definition * from {@link java.lang.Object}. */ @Override public abstract boolean equals(Object o); // @since 2.10 @SuppressWarnings("unchecked") protected <T extends JsonNode> T _this() { return (T) this; } protected <T> T _reportRequiredViolation(String msgTemplate, Object...args) { throw new IllegalArgumentException(String.format(msgTemplate, args)); } }
package com.forgeessentials.remote; import java.io.IOException; import java.security.GeneralSecurityException; import com.forgeessentials.core.ForgeEssentials; import com.forgeessentials.core.moduleLauncher.FEModule; import com.forgeessentials.core.moduleLauncher.config.IConfigLoader.ConfigLoaderBase; import com.forgeessentials.util.OutputHandler; import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerInitEvent; import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerStopEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.common.config.Configuration; @FEModule(name = "Remote", parentMod = ForgeEssentials.class, canDisable = true) public class ModuleRemote extends ConfigLoaderBase { private static final String CONFIG_CAT = "Remote"; private RemoteServer server; private int port = 27020; private String hostname = "localhost"; private boolean useSSL = false; @SubscribeEvent public void serverStarting(FEModuleServerInitEvent e) { try { if (useSSL) { SSLContextHelper sslCtxHelper = new SSLContextHelper(); sslCtxHelper.loadSSLCertificate("private.cert", "somepass", "someotherpass"); server = new RemoteServer(port, hostname, sslCtxHelper.getSSLCtx()); } else { server = new RemoteServer(port, hostname); } } catch (IOException | GeneralSecurityException e1) { OutputHandler.felog.severe("Unable to start remote-server: " + e1.getMessage()); } } @SubscribeEvent public void serverStopping(FEModuleServerStopEvent e) { if (server != null) { server.close(); server = null; } } @Override public void load(Configuration config, boolean isReload) { hostname = config.get(CONFIG_CAT, "hostname", "localhost", "Hostname of the minecraft server").getString(); port = config.get(CONFIG_CAT, "port", 27020, "Port to connect remotes to").getInt(); // useSSL = config.get(CONFIG_CAT, "useSSL", false, "Protect the communication with SSL").getBoolean(); } }
package com.github.andriell.gui.process; import com.github.andriell.gui.GuiHelper; import com.github.andriell.processor.ManagerInterface; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; public class Process extends JPanel { private static final Font fontTitle = new Font("Arial", Font.PLAIN, 16); private static final Border border = BorderFactory.createLineBorder(Color.black); private static final String timeZero = "00:00:00"; private static final String zero = "0"; private JLabel inQueue; private JLabel timeLeft; private JLabel runProcess; private JLabel pcSec; private JLabel total; private JSpinner limit; private ManagerInterface manager; private int startCount = 0; private long startTime = 0L; public Process(ManagerInterface m) { manager = m; setLayout(null); setPreferredSize(new Dimension(325, 105)); setBorder(border); JLabel title = new JLabel(manager.getProcessBeanId(), JLabel.CENTER); title.setSize(315, 20); title.setLocation(5, 5); title.setFont(fontTitle); add(title); GuiHelper.gridFormatter( this, new int[]{5, 30}, new int[]{90, 5, 60, 5, 90, 5, 60}, new int[]{20, 5, 20, 5, 20}, new Component[][]{ {new JLabel("Total process:"), null, total = new JLabel(zero), null, new JLabel("Run process:"), null, runProcess = new JLabel(zero)}, null, {new JLabel("In queue:"), null, inQueue = new JLabel(zero), null, new JLabel("Item/sec:"), null, pcSec = new JLabel(zero)}, null, {new JLabel("Limit process:"), null, limit = new JSpinner(new SpinnerNumberModel(2, 1, 999, 1)), null, new JLabel("Time left:"), null, timeLeft = new JLabel(timeZero)}, } ); limit.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { manager.setLimitProcess((Integer) limit.getValue()); } }); limit.setSize(40, 20); } private static String secToTime(int totalSecs) { int hours = totalSecs / 3600; int minutes = (totalSecs % 3600) / 60; int seconds = totalSecs % 60; return String.format("%02d:%02d:%02d", hours, minutes, seconds); } public void update() { int count = manager.getProcessInQueue(); long time = System.currentTimeMillis(); inQueue.setText(Integer.toString(count)); runProcess.setText(Integer.toString(manager.getRunningProcesses())); limit.setValue(manager.getLimitProcess()); if (count > 10 && startTime > 0 && count < startCount) { float inTime = (startCount - count) / ((time - startTime) / 1000); if (inTime > 0) { pcSec.setText(Float.toString(inTime)); timeLeft.setText(secToTime(Math.round((count / inTime)))); } } else { startTime = time; startCount = count; timeLeft.setText(timeZero); } } }
package com.github.kubode.rxeventbus; import rx.Scheduler; import rx.Subscription; import rx.functions.Action1; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; /** * <p>An implementation of event bus using {@link PublishSubject}.</p> * <p>MT-Safe.</p> * <p>Not support generics.</p> */ public class RxEventBus { private final Subject<Event, Event> subject = new SerializedSubject<>(PublishSubject.<Event>create()); /** * <p>Posts an {@link Event} to subscribed handlers.</p> * <p>If no handlers have been subscribed for event's class, unhandled will be called with unhandled event.</p> * * @param <E> Type of event. * @param event An event to post. * @param unhandled Will be called if event is not handled. * Note: If handler subscribed by using async {@link Scheduler}, it can't guarantee event is actually handled. */ public <E extends Event> void post(E event, Action1<E> unhandled) { subject.onNext(event); if (event.handledCount == 0) { unhandled.call(event); } } /** * <p>An overload method of {@link #post(Event, Action1)} that do nothing on unhandled.</p> * * @see #post(Event, Action1) */ public <E extends Event> void post(E event) { post(event, new Action1<E>() { @Override public void call(E e) { } }); } /** * <p>Subscribes handler to receive events type of specified class.</p> * <p>You should call {@link Subscription#unsubscribe()} if you want to stop receiving events.</p> * * @param <E> Type of event. * @param clazz Type of event that you want to receive. * @param handler An event handler function that called if an event is posted. * @param scheduler handler will dispatched on this. * @return A {@link Subscription} which can stop observing. */ public <E extends Event> Subscription subscribe(Class<E> clazz, Action1<E> handler, Scheduler scheduler) { return subject .ofType(clazz) .doOnNext(new Action1<E>() { @Override public void call(E e) { e.handledCount++; } }) .observeOn(scheduler) .subscribe(handler); } /** * An overload method of {@link #subscribe(Class, Action1, Scheduler)} that scheduler specified by {@link Schedulers#immediate()} * * @see #subscribe(Class, Action1, Scheduler) */ public <E extends Event> Subscription subscribe(Class<E> clazz, Action1<E> handler) { return subscribe(clazz, handler, Schedulers.immediate()); } }
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) { // primaryKey > secondaryKey secondaryEntity = secondaryEntityIterator.next(); secondaryKey = (String) secondaryEntity.getProperty(foreignKey); } else if (primaryKey.compareTo(secondaryKey) < 0) { // primaryKey < secondaryKey primaryKey = primaryKeyIterator.next(); } else { // primaryKey = secondaryKey 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.heroku.demo.mapping; import com.heroku.demo.domain.TimeTrack; import com.heroku.demo.service.TimeTrackDto; import org.dozer.Mapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component public class TimeTrackMapper { Mapper mapper; @Autowired public TimeTrackMapper(Mapper theMapper) { mapper = theMapper; } public TimeTrack fromDto(final TimeTrackDto dto) { return mapper.map(dto,TimeTrack.class); } public TimeTrackDto toDto(final TimeTrack entity) { return mapper.map(entity, TimeTrackDto.class); } public List<TimeTrackDto> toDtos(List<TimeTrack> timeTracks) { return timeTracks.stream().map(timeTrack -> toDto(timeTrack)).collect(Collectors.toList()); } }
package com.kryptnostic.api.v1.client; import java.util.List; import retrofit.http.Body; import retrofit.http.POST; import com.kryptnostic.api.v1.models.SearchResult; import com.kryptnostic.api.v1.models.request.SearchRequest; public interface SearchAPI { String SEARCH = "/search"; /** * Search on stored documents. * * @param SearchRequest request. * @return SearchResult */ @POST(SEARCH) SearchResult search(@Body SearchRequest request); /** * Search on stored documents. * * @param List<SearchRequest> requests. * @return SearchResult */ @POST(SEARCH) SearchResult search(@Body List<SearchRequest> requests); }
package com.mathtabolism.entity.account; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.mathtabolism.constants.AccountRole; import com.mathtabolism.constants.Gender; import com.mathtabolism.entity.GeneratedEntity; /** * * * @author mlaursen * */ @Entity @XmlRootElement @NamedQueries( @NamedQuery( name = Account.Q_findByUsername, query = "SELECT a FROM Account a WHERE a.username = :username" ) ) public class Account extends GeneratedEntity { public static final String Q_findByUsername = "Account.findByUsername"; @Column(unique = true) private String username; private String password; private String email; @Enumerated(EnumType.STRING) private AccountRole role; @Enumerated(EnumType.STRING) private Gender gender; @Temporal(TemporalType.DATE) private Date birthday; @Temporal(TemporalType.DATE) private Date lastLogin; @Temporal(TemporalType.DATE) private Date activeSince; @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "account_id") private List<AccountSetting> allSettings; @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "account_id") private List<AccountWeight> allWeights; @Transient private AccountSetting currentSettings; public Account() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @XmlTransient public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public AccountRole getRole() { return role; } public void setRole(AccountRole role) { this.role = role; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Date getLastLogin() { return lastLogin; } public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin; } public void setActiveSince(Date activeSince) { this.activeSince = activeSince; } public Date getActiveSince() { return activeSince; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("id", id) .append("username", username).append("password", password).append("email", email) .append("role", role).append("birthday", birthday).append("lastLogin", lastLogin) .append("activeSince", activeSince).toString(); } }
package com.mcjty.rftools.blocks.logic; import com.mcjty.container.GenericGuiContainer; import com.mcjty.gui.Window; import com.mcjty.gui.events.TextEvent; import com.mcjty.gui.layout.HorizontalLayout; import com.mcjty.gui.layout.VerticalLayout; import com.mcjty.gui.widgets.Label; import com.mcjty.gui.widgets.Panel; import com.mcjty.gui.widgets.TextField; import com.mcjty.gui.widgets.Widget; import com.mcjty.rftools.network.Argument; import net.minecraft.inventory.Container; import java.awt.*; public class GuiTimer extends GenericGuiContainer<TimerTileEntity> { public static final int TIMER_WIDTH = 160; public static final int TIMER_HEIGHT = 30; private TextField speedField; public GuiTimer(TimerTileEntity timerTileEntity, Container container) { super(timerTileEntity, container); } @Override public void initGui() { super.initGui(); int k = (this.width - TIMER_WIDTH) / 2; int l = (this.height - TIMER_HEIGHT) / 2; Panel toplevel = new Panel(mc, this).setFilledRectThickness(2).setLayout(new VerticalLayout()); Label label = new Label(mc, this).setText("Delay:"); speedField = new TextField(mc, this).setTooltips("Set the delay in ticks", "(20 ticks is one second)").addTextEvent(new TextEvent() { @Override public void textChanged(Widget parent, String newText) { setDelay(); } }); int delay = tileEntity.getDelay(); if (delay <= 0) { delay = 1; } speedField.setText(String.valueOf(delay)); Panel bottomPanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(label).addChild(speedField); toplevel.addChild(bottomPanel); toplevel.setBounds(new Rectangle(k, l, TIMER_WIDTH, TIMER_HEIGHT)); window = new Window(this, toplevel); } private void setDelay() { String d = speedField.getText(); int delay; try { delay = Integer.parseInt(d); } catch (NumberFormatException e) { delay = 1; } tileEntity.setDelay(delay); sendServerCommand(TimerTileEntity.CMD_SETDELAY, new Argument("delay", delay)); } @Override protected void drawGuiContainerBackgroundLayer(float v, int i, int i2) { window.draw(); } }
package com.paymill.services; import java.util.Date; import javax.ws.rs.core.MultivaluedMap; import org.apache.commons.lang3.StringUtils; import com.paymill.Paymill; import com.paymill.models.Fee; import com.paymill.models.Transaction; import com.paymill.utils.RestfulUtils; import com.paymill.utils.ValidationUtils; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; public class TransactionService implements PaymillService { private final static String PATH = "/transactions"; public void list( Integer count, Integer offset, Date created_at ) { WebResource webResource = Paymill.getHttpClient().resource( Paymill.ENDPOINT + PATH ); ClientResponse response = webResource.get( ClientResponse.class ); if( response.getStatus() != 200 ) { System.out.println( "Failed : HTTP error code : " + response.getStatus() ); } response.getEntity( String.class ); } public Transaction show( Transaction transaction ) { return RestfulUtils.show( TransactionService.PATH, transaction, Transaction.class ); } public Transaction createWithToken( String token, Integer amount, String currency ) { return this.createWithTokenAndFee( token, amount, currency, null, null ); } public Transaction createWithToken( String token, Integer amount, String currency, String description ) { return this.createWithTokenAndFee( token, amount, currency, description, null ); } public Transaction createWithTokenAndFee( String token, Integer amount, String currency, Fee fee ) { return this.createWithTokenAndFee( token, amount, currency, null, fee ); } public Transaction createWithTokenAndFee( String token, Integer amount, String currency, String description, Fee fee ) { ValidationUtils.validatesToken( token ); ValidationUtils.validatesAmount( amount ); ValidationUtils.validatesCurrency( currency ); ValidationUtils.validatesFee( fee ); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add( "token", token ); params.add( "amount", String.valueOf( amount ) ); params.add( "currency", currency ); if( StringUtils.isNotBlank( description ) ) params.add( "description", description ); if( fee != null && fee.getAmount() != null ) params.add( "fee_amount", String.valueOf( fee.getAmount() ) ); if( fee != null && StringUtils.isNotBlank( fee.getPayment() ) ) params.add( "fee_payment", fee.getPayment() ); return RestfulUtils.create( TransactionService.PATH, params, Transaction.class ); } public Transaction createWithPayment() { return null; } public Transaction createWithPreauthorization() { return null; } public Transaction update( Transaction transaction ) { return RestfulUtils.update( TransactionService.PATH, transaction, Transaction.class ); } }
package com.plaid.client; import java.util.HashMap; import java.util.Map; import com.plaid.client.response.MfaResponse; import org.apache.commons.lang.StringUtils; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.plaid.client.exception.PlaidClientsideException; import com.plaid.client.exception.PlaidMfaException; import com.plaid.client.http.HttpDelegate; import com.plaid.client.http.HttpResponseWrapper; import com.plaid.client.http.PlaidHttpRequest; import com.plaid.client.request.ConnectOptions; import com.plaid.client.request.Credentials; import com.plaid.client.request.GetOptions; import com.plaid.client.request.InfoOptions; import com.plaid.client.response.AccountsResponse; import com.plaid.client.response.InfoResponse; import com.plaid.client.response.MessageResponse; import com.plaid.client.response.PlaidUserResponse; import com.plaid.client.response.TransactionsResponse; public class DefaultPlaidUserClient implements PlaidUserClient { private String accessToken; private String clientId; private String secret; private ObjectMapper jsonMapper; private HttpDelegate httpDelegate; private Integer timeout; private DefaultPlaidUserClient() { ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.setSerializationInclusion(Include.NON_NULL); this.jsonMapper = jsonMapper; } @Override public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Override public String getAccessToken() { return this.accessToken; } @Override public PlaidUserResponse exchangeToken(String publicToken) { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("public_token", publicToken); return handlePost("/exchange_token", requestParams, PlaidUserResponse.class); } @Override public TransactionsResponse addUser(Credentials credentials, String type, String email, ConnectOptions connectOptions) throws PlaidMfaException { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("credentials", credentials); requestParams.put("type", type); requestParams.put("email", email); requestParams.put("options", connectOptions); return handlePost("/connect", requestParams, TransactionsResponse.class); } @Override public AccountsResponse achAuth(Credentials credentials, String type, ConnectOptions connectOptions) throws PlaidMfaException { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("credentials", credentials); requestParams.put("type", type); requestParams.put("options", connectOptions); return handlePost("/auth", requestParams, AccountsResponse.class); } @Override public AccountsResponse updateAchAuth(Credentials credentials, String accessToken) throws PlaidMfaException { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("credentials", credentials); requestParams.put("access_token", accessToken); return handlePatch("/auth", requestParams, AccountsResponse.class); } @Override public TransactionsResponse mfaConnectStep(String mfa, String type) throws PlaidMfaException { return handleMfa("/connect/step", mfa, type, TransactionsResponse.class); } @Override public AccountsResponse mfaAuthStep(String mfa, String type) throws PlaidMfaException { return handleMfa("/auth/step", mfa, type, AccountsResponse.class); } @Override public AccountsResponse updateMfaAuthStep(String mfa, String type) throws PlaidMfaException { return null; } @Override public AccountsResponse mfaAuthDeviceSelectionByDeviceType(String deviceType, String type) throws PlaidMfaException { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } if (StringUtils.isEmpty(deviceType)){ throw new PlaidClientsideException("No device selected"); } Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("type", type); HashMap<String, String> mask = new HashMap<String, String>(); mask.put("type", deviceType); HashMap<String, Object> sendMethod = new HashMap<String, Object>(); sendMethod.put("send_method", mask); requestParams.put("options", sendMethod); return handlePost("/auth/step", requestParams, AccountsResponse.class); } @Override public AccountsResponse mfaAuthDeviceSelectionByDeviceMask(String deviceMask, String type) throws PlaidMfaException { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } if (StringUtils.isEmpty(deviceMask)) { throw new PlaidClientsideException("No device selected"); } Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("type", type); HashMap<String, String> mask = new HashMap<String, String>(); mask.put("mask", deviceMask); HashMap<String, Object> sendMethod = new HashMap<String, Object>(); sendMethod.put("send_method", mask); requestParams.put("options", sendMethod); return handlePost("/auth/step", requestParams, AccountsResponse.class); } @Override public TransactionsResponse updateTransactions() { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect", authenticationParams(), timeout); HttpResponseWrapper<TransactionsResponse> response = httpDelegate.doGet(request, TransactionsResponse.class); TransactionsResponse body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } @Override public TransactionsResponse updateTransactions(GetOptions options) { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } Map<String, Object> requestParams = new HashMap<String, Object>(); if (options != null) { requestParams.put("options", options); } return handlePost("/connect/get", requestParams, TransactionsResponse.class); } @Override public AccountsResponse updateAuth() { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } Map<String, Object> requestParams = new HashMap<String, Object>(); return handlePost("/auth/get", requestParams, AccountsResponse.class); } @Override public TransactionsResponse updateCredentials(Credentials credentials, String type) { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect", authenticationParams(), timeout); request.addParameter("credentials", serialize(credentials)); request.addParameter("type", type); HttpResponseWrapper<TransactionsResponse> response = httpDelegate.doPatch(request, TransactionsResponse.class); TransactionsResponse body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } @Override public TransactionsResponse updateWebhook(String webhook) { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect", authenticationParams(), timeout); ConnectOptions connectOptions = new ConnectOptions(); connectOptions.setWebhook(webhook); request.addParameter("options", serialize(connectOptions)); HttpResponseWrapper<TransactionsResponse> response = httpDelegate.doPatch(request, TransactionsResponse.class); TransactionsResponse body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } @Override public MessageResponse deleteUser() { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } PlaidHttpRequest request = new PlaidHttpRequest("/connect", authenticationParams(), timeout); HttpResponseWrapper<MessageResponse> response = httpDelegate.doDelete(request, MessageResponse.class); return response.getResponseBody(); } @Override public AccountsResponse checkBalance() { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } Map<String, Object> requestParams = new HashMap<String, Object>(); return handlePost("/balance", requestParams, AccountsResponse.class); } @Override public TransactionsResponse addProduct(String product, ConnectOptions options) { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("upgrade_to", product); requestParams.put("login",true); if (options != null) { requestParams.put("options", options); } return handlePost("/upgrade", requestParams, TransactionsResponse.class); } @Override public InfoResponse info(Credentials credentials, String type, InfoOptions options) { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("credentials", credentials); requestParams.put("type", type); requestParams.put("options", options); return handlePost("/info", requestParams, InfoResponse.class); } private <T extends PlaidUserResponse> T handleMfa(String path, String mfa, String type, Class<T> returnTypeClass) throws PlaidMfaException { if (StringUtils.isEmpty(accessToken)) { throw new PlaidClientsideException("No accessToken set"); } Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("mfa", mfa); if (type != null) { requestParams.put("type", type); } return handlePost(path, requestParams, returnTypeClass); } private <T extends PlaidUserResponse> T handlePost(String path, Map<String, Object> requestParams, Class<T> returnTypeClass) throws PlaidMfaException { PlaidHttpRequest request = new PlaidHttpRequest(path, authenticationParams(), timeout); for (String param : requestParams.keySet()) { Object value = requestParams.get(param); if (value == null) { continue; } request.addParameter(param, serialize(value)); } try { HttpResponseWrapper<T> response = httpDelegate.doPost(request, returnTypeClass); T body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } catch (PlaidMfaException e) { setAccessToken(e.getMfaResponse().getAccessToken()); throw e; } } private <T extends PlaidUserResponse> T handlePatch(String path, Map<String, Object> requestParams, Class<T> returnTypeClass) throws PlaidMfaException { PlaidHttpRequest request = new PlaidHttpRequest(path, authenticationParams(), timeout); for (String param : requestParams.keySet()) { Object value = requestParams.get(param); if (value == null) { continue; } request.addParameter(param, serialize(value)); } try { HttpResponseWrapper<T> response = httpDelegate.doPatch(request, returnTypeClass); T body = response.getResponseBody(); setAccessToken(body.getAccessToken()); return body; } catch (PlaidMfaException e) { setAccessToken(e.getMfaResponse().getAccessToken()); throw e; } } private String serialize(Object value) { if (value instanceof String) { return (String) value; } else { try { return jsonMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new PlaidClientsideException(e); } } } private Map<String, String> authenticationParams() { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("client_id", clientId); parameters.put("secret", secret); if (!StringUtils.isEmpty(accessToken)) { parameters.put("access_token", accessToken); } return parameters; } @Override public HttpDelegate getHttpDelegate() { return httpDelegate; } public static class Builder { private String clientId; private String secret; private Integer timeout; private HttpDelegate httpDelegate; public Builder withClientId(String clientId) { this.clientId = clientId; return this; } public Builder withSecret(String secret) { this.secret = secret; return this; } public Builder withTimeout(Integer timeout) { this.timeout = timeout; return this; } public Builder withHttpDelegate(HttpDelegate httpDelegate) { this.httpDelegate = httpDelegate; return this; } public DefaultPlaidUserClient build() { DefaultPlaidUserClient client = new DefaultPlaidUserClient(); client.clientId = this.clientId; client.secret = this.secret; client.timeout = this.timeout; client.httpDelegate = this.httpDelegate; return client; } } }
package com.pturpin.quickcheck.test; import com.pturpin.quickcheck.generator.Generator; import com.pturpin.quickcheck.generator.ReflectiveGenerators; import com.pturpin.quickcheck.registry.Registry; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Optional; import java.util.Random; import java.util.function.Function; import java.util.function.Supplier; import static com.google.common.base.Preconditions.checkArgument; public final class TestRunners { private TestRunners() { /* Factory class */ } public static TestRunner randomRunner(Method method, Object instance, Registry registry, long nbRun, Supplier<Random> random) { Optional<Generator<Object[]>> optGenerator = ReflectiveGenerators.with(registry).parametersGen(method); return optGenerator .map(parametersGen -> randomRunner(method, instance, parametersGen, nbRun, random)) .orElseThrow(UnsupportedOperationException::new); } public static TestRunner randomRunner(Method method, Object instance, Generator<Object[]> parametersGen, long nbRun, Supplier<Random> random) { Function<Object[], TestRunner> runnerFactory = methodRunner(method, instance); return new RandomTestRunner(runnerFactory, nbRun, parametersGen, random); } public static TestRunner randomRunner(Function<Object[], TestRunner> runnerFactory, Generator<Object[]> parametersGen, long nbRun, Supplier<Random> random) { return new RandomTestRunner(runnerFactory, nbRun, parametersGen, random); } public static Function<Object[], TestRunner> staticMethodRunner(Method method) { return methodRunner(method, null); } public static Function<Object[], TestRunner> methodRunner(Method method, Object instance) { checkArgument(instance != null || Modifier.isStatic(method.getModifiers()), "Impossible to invoke a non-static method without instance : %s", method); Class<?> returnType = method.getReturnType(); boolean useReturn = TestResult.class.isAssignableFrom(returnType); return arguments -> () -> { try { Object result = method.invoke(instance, arguments); if (useReturn) { return (TestResult) result; } return TestResult.ok(); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { return TestResult.failure(e.getCause()); } }; } }
package com.questionanswer.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ClientApp {
package com.ragnarok.jparseutil.dataobject; public class Type { private static final String TAG = "JParserUtil.VariableType"; private String typeName; // fully qualified private boolean isPrimitive = false; private boolean isArray = false; private Type arrayElmentType = null; // not null if isArray is true public void setTypeName(String typeName) { this.typeName = typeName; } public String getTypeName() { return this.typeName; } public void setPrimitive(boolean isPrimitive) { this.isPrimitive = isPrimitive; } public boolean isPrimitive() { return this.isPrimitive; } public void setArray(boolean isArray) { this.isArray = isArray; } public boolean isArray() { return this.isArray; } public void setArrayElmentType(Type elemType) { this.arrayElmentType = elemType; } public Type getArrayElmentType() { return this.arrayElmentType; } @Override public String toString() { if (!isArray) { return String.format("{type: %s, isPrimitive: %b, isArray: %b}", typeName, isPrimitive, isArray); } else { return String.format("{type: %s, isPrimitive: %b, isArray: %b, arrayElemType: %s}", typeName, isPrimitive, isArray, arrayElmentType); } } }
package com.roch.fbyw.activity; import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import android.support.v4.view.ViewCompat; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import com.roch.fbyw.R; /** * BaseActivityonCreate * @author ZhaoDongShao * 2016812 */ public class MainBaseActivity extends BaseActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setMyStatusBarColor(); // if (Build.VERSION_CODES.LOLLIPOP > Build.VERSION.SDK_INT && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // CommonUtil.getInstance(this).getState(); } @SuppressLint({ "InlinedApi", "NewApi" }) private void setMyStatusBarColor() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); // , ContentView window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // flag setStatusBarColor window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { } else { } //ResourceUtil.getInstance().getColorById(R.color.color_145bba) window.setStatusBarColor(getResources().getColor(R.color.bule_155bbb)); ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT); View mChildView = mContentView.getChildAt(0); if (mChildView != null) { // ContentView FitsSystemWindows, ContentView // View . View . ViewCompat.setFitsSystemWindows(mChildView, true); } } } public int getStatusBarHeight() { int result = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; } }
package com.rox.emu.processor.mos6502; import com.rox.emu.env.RoxByte; import com.rox.emu.env.RoxWord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import static com.rox.emu.processor.mos6502.Registers.Register.*; /** * A representation of the MOS 6502 CPU registers * * @author Ross Drew */ public class Registers { private static final Logger log = LoggerFactory.getLogger(Registers.class); /** * A single registerValue for a MOS 6502 containing information on registerValue id and name */ public enum Register { ACCUMULATOR(0), Y_INDEX(1), X_INDEX(2), PROGRAM_COUNTER_HI(3), PROGRAM_COUNTER_LOW(4), STACK_POINTER_LOW(5), STACK_POINTER_HI(6), STATUS_FLAGS(7); private final String description; private final int index; Register(int index){ this.index = index; description = prettifyName(name()); } private static String prettifyName(String originalName){ String name = originalName.replaceAll("_"," ") .toLowerCase() .replace("hi","(High)") .replace("low","(Low)"); name = name.substring(0, 1).toUpperCase() + name.substring(1); int spaceIndex = name.indexOf(' '); if (spaceIndex > 0) name = name.substring(0, spaceIndex) + name.substring(spaceIndex, spaceIndex+2).toUpperCase() + name.substring(spaceIndex+2); return name; } public String getDescription(){ return description; } public int getIndex(){ return this.index; } } /** * A MOS 6502 status flag */ public enum Flag { CARRY(0), ZERO(1), IRQ_DISABLE(2), DECIMAL_MODE(3), BREAK(4), UNUSED(5), OVERFLOW(6), NEGATIVE(7); private final int index; private final int placeValue; private final String description; private static String prettifyName(String originalName){ String name = originalName.replaceAll("_"," ").toLowerCase(); name = name.substring(0, 1).toUpperCase() + name.substring(1); if (name.contains(" ")) { int spaceIndex = name.indexOf(' '); name = name.substring(0, spaceIndex) + name.substring(spaceIndex, spaceIndex + 2).toUpperCase() + name.substring(spaceIndex + 2); } return name; } Flag(int index) { this.index = index; this.placeValue = (1 << index); description = prettifyName(name()); } public String getDescription() { return description; } public int getIndex() { return index; } public int getPlaceValue() { return placeValue; } } private final RoxByte[] registerValue; public Registers(){ registerValue = new RoxByte[8]; Arrays.fill(registerValue, RoxByte.ZERO); setRegister(STACK_POINTER_LOW, RoxByte.fromLiteral(0b11111111)); setRegister(STATUS_FLAGS, RoxByte.fromLiteral(0b00000000)); } public Registers(final RoxByte[] registerValue){ this.registerValue = Arrays.copyOf(registerValue, 8); setRegister(STACK_POINTER_LOW, RoxByte.fromLiteral(0b11111111)); } /** * @param register the registerValue to set * @param value to set the registerValue to */ public void setRegister(Register register, RoxByte value){ log.debug("'R:{}' := {}", register.getDescription(), value); registerValue[register.getIndex()] = (value == null ? RoxByte.ZERO : value); } /** * @param register from which to get the value * @return the value of the desired registerValue */ public RoxByte getRegister(Register register){ return registerValue[register.getIndex()]; } /** * @param pcWordValue to set the Program Counter to */ public void setPC(RoxWord pcWordValue){ setRegister(PROGRAM_COUNTER_HI, pcWordValue.getHighByte()); setRegister(PROGRAM_COUNTER_LOW, pcWordValue.getLowByte()); log.debug("'R+:Program Counter' := {} [ {} | {} ]", pcWordValue, getRegister(PROGRAM_COUNTER_HI), getRegister(PROGRAM_COUNTER_LOW)); } /** * @return the two byte value of the Program Counter */ public RoxWord getPC(){ return (RoxWord.from(getRegister(PROGRAM_COUNTER_HI), getRegister(PROGRAM_COUNTER_LOW))); } /** * Increment the Program Counter then return it's value * * @return the new value of the Program Counter */ public RoxWord getNextProgramCounter(){ setPC(RoxWord.fromLiteral(getPC().getRawValue()+1)); return getPC(); } /** * Get the Program Counter value then increment * * @return the value of the Program Counter */ public RoxWord getAndStepProgramCounter(){ final RoxWord pc = getPC(); setPC(RoxWord.fromLiteral(getPC().getRawValue()+1)); return pc; } /** * @param flag flag to test * @return <code>true</code> if the specified flag is set, <code>false</code> otherwise */ public boolean getFlag(Flag flag) { return registerValue[STATUS_FLAGS.getIndex()].isBitSet(flag.getIndex()); } /** * @param flag for which to set the state * @param state to set the flag to */ public void setFlagTo(Flag flag, boolean state) { if (state) setFlag(flag); else clearFlag(flag); } /** * Set* the specified flag of the status register to 1 * * @param flag for which to set to true */ public void setFlag(Flag flag) { log.debug("'F:{}' -> SET", flag.description); registerValue[STATUS_FLAGS.getIndex()] = registerValue[STATUS_FLAGS.getIndex()].withBit(flag.getIndex()); } /** * Set/clear the specified flag of the status register to 0 * * @param flag to be cleared */ public void clearFlag(Flag flag){ log.debug("'F:{}' -> CLEARED", flag.getDescription()); registerValue[STATUS_FLAGS.getIndex()] = registerValue[STATUS_FLAGS.getIndex()].withoutBit(flag.getIndex()); } /** * @param value to set the status flags based on */ public void setFlagsBasedOn(RoxByte value){ setZeroFlagFor(value.getRawValue()); setNegativeFlagFor(value.getRawValue()); } /** * Set zero flag if given argument is 0 */ private void setZeroFlagFor(int value){ setFlagTo(Flag.ZERO, value == 0); } /** * Set negative flag if given argument is 0 */ private void setNegativeFlagFor(int value){ setFlagTo(Flag.NEGATIVE, isNegative(value)); } private boolean isNegative(int fakeByte){ return RoxByte.fromLiteral(fakeByte).isNegative(); } public Registers copy(){ return new Registers(registerValue); } }
package com.sequenceiq.ambari.shell; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.GenericApplicationContext; import org.springframework.shell.commands.ExitCommands; import org.springframework.shell.core.ExitShellRequest; import org.springframework.shell.core.JLineShellComponent; @Configuration @ComponentScan(basePackageClasses={AmbariShell.class,ExitCommands.class}) public class AmbariShell implements CommandLineRunner { @Autowired GenericApplicationContext ctx; public void run(String... arg0) throws Exception { JLineShellComponent shell = ctx.getBean("shell", JLineShellComponent.class); ExitShellRequest exitShellRequest; shell.start(); shell.promptLoop(); exitShellRequest = shell.getExitShellRequest(); if (exitShellRequest == null) { // shouldn't really happen, but we'll fallback to this anyway exitShellRequest = ExitShellRequest.NORMAL_EXIT; } shell.waitForComplete(); ctx.close(); } public static void main(String[] args) { new SpringApplicationBuilder(AmbariShell.class) .showBanner(false) .run(args); } }
package com.soebes.maven.extensions; import java.text.NumberFormat; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.artifact.Artifact; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeployTimer { private final Logger LOGGER = LoggerFactory.getLogger( getClass() ); private Map<String, TimePlusSize> timerEvents; public DeployTimer() { this.timerEvents = new ConcurrentHashMap<>(); } private String getArtifactId( Artifact artifact ) { StringBuilder sb = new StringBuilder( 128 ); sb.append( artifact.getGroupId() ); sb.append( ":" ).append( artifact.getArtifactId() ).append( ":" ).append( artifact.getVersion() ); if ( artifact.getClassifier() != null ) { sb.append( ':' ).append( artifact.getClassifier() ); } sb.append( ':' ).append( artifact.getExtension() ); return sb.toString(); } public void start( RepositoryEvent event ) { String artifactId = getArtifactId( event.getArtifact() ); TimePlusSize systemTime = new TimePlusSize(); systemTime.start(); timerEvents.put( artifactId, systemTime ); } public void stop( RepositoryEvent event ) { String artifactId = getArtifactId( event.getArtifact() ); if ( !timerEvents.containsKey( artifactId ) ) { throw new IllegalArgumentException( "Unknown artifactId (" + artifactId + ")" ); } timerEvents.get( artifactId ).stop(); timerEvents.get( artifactId ).setSize( event.getArtifact().getFile().length() ); } public void report() { LOGGER.info( "Deployment summary:" ); long totalInstallationTime = 0; long totalInstallationSize = 0; for ( Entry<String, TimePlusSize> item : this.timerEvents.entrySet() ) { totalInstallationTime += item.getValue().getElapsedTime(); totalInstallationSize += item.getValue().getSize(); LOGGER.info( "{} ms : {}", String.format( "%8d", item.getValue().getElapsedTime() ), item.getKey() ); } LOGGER.info( "{} ms {} bytes.", NumberFormat.getIntegerInstance().format( totalInstallationTime ), NumberFormat.getIntegerInstance().format( totalInstallationSize ) ); } }
package com.technogi.rdeb.client; public class EventBusClient { public void connect(Config config){} public void emit(Event event){} public void broadcast(Event event){} public void subscribe(String id){} }
package com.telekom.m2m.cot.restsdk.util; import com.telekom.m2m.cot.restsdk.devicecontrol.OperationStatus; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; /** * Filter to build as criteria for collection queries. * * @author Patrick Steinert * @since 0.2.0 */ public class Filter { @Nonnull private final HashMap<String, String> arguments = new HashMap<>(); private Filter() { } /** * Use to create a FilterBuilder. * * @return FilterBuilder. */ @Nonnull public static FilterBuilder build() { return new FilterBuilder(); } /** * Filter Builder for build collection queries. * <p><b>Usage:</b></p> * <pre> * {@code * measurementApi.getMeasurements( * Filter.build() * .byFragmentType("com_telekom_example_SampleTemperatureSensor") * .bySource("1122334455") * ); * } * </pre> */ public static class FilterBuilder { @Nonnull private final Filter instance = new Filter(); /** * Creates a parameter string. * * @return a string in pattern <code>arg1=val1&amp;arg2=val2</code> */ @Nonnull public String buildFilter() { String qs = ""; Set<Map.Entry<String, String>> set = instance.arguments.entrySet(); for (Map.Entry<String, String> entry : set) { qs += entry.getKey() + "=" + entry.getValue() + "&"; } return qs.substring(0, qs.length() - 1); } /** * Adds a build for source id. * * @param id ID of the source ({@link com.telekom.m2m.cot.restsdk.inventory.ManagedObject}) to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder bySource(String id) { instance.arguments.put("source", id); return this; } /** * Adds a build for type. * * @param type type to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byType(String type) { //instance.type = type; instance.arguments.put("type", type); return this; } /** * Adds a build for a time range. * * @param from start of the date range (more in the history). * @param to end of the date range (more in the future). * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byDate(Date from, Date to) { //instance.dateFrom = from; //instance.dateTo = to; instance.arguments.put("dateFrom", CotUtils.convertDateToTimestring(from)); instance.arguments.put("dateTo", CotUtils.convertDateToTimestring(to)); return this; } /** * Adds a build for a fragment. * * @param fragmentType to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byFragmentType(String fragmentType) { instance.arguments.put("fragmentType", fragmentType); return this; } /** * Adds a build for a deviceId. * * @param deviceId to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byDeviceId(String deviceId) { instance.arguments.put("deviceId", deviceId); return this; } /** * Adds a build for a status. * * @param operationStatus to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byStatus(OperationStatus operationStatus) { instance.arguments.put("status", operationStatus.toString()); return this; } /** * Adds a build for a text. * * @param text to build for. * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byText(String text) { instance.arguments.put("text", text); return this; } /** * Adds a build for a list of comma separated Ids. * * @param listOfIds to build for (comma separated). * @return an appropriate build Object. */ @Deprecated @Nonnull public FilterBuilder byListOfIds(String listOfIds) { instance.arguments.put("ids", listOfIds); return this; } /** * Adds a build for a Alarm status. * * @param status to build for. * @return an appropriate build Object. * @since 0.3.0 */ @Deprecated @Nonnull public FilterBuilder byStatus(String status) { instance.arguments.put("status", status); return this; } /** * Adds a build for an agentId. * * @param agentId to build for. * @return an appropriate build Object. * @since 0.3.1 */ @Deprecated @Nonnull public FilterBuilder byAgentId(String agentId) { instance.arguments.put("agentId", agentId); return this; } /** * Adds a build for a user. * * @param user to build for. * @return an appropriate build Object. * @since 0.6.0 */ @Deprecated @Nonnull public FilterBuilder byUser(String user) { instance.arguments.put("user", user); return this; } /** * Adds a build for an application. * * @param application to build for. * @return an appropriate build Object. * @since 0.6.0 */ @Deprecated @Nonnull public FilterBuilder byApplication(String application) { instance.arguments.put("application", application); return this; } /** * adds a build for a filter * * @param filterBy enum value, which filter should to be added * @param value value for filter, which should be added * @return an appropriate build Object */ @Nonnull public FilterBuilder setFilter(FilterBy filterBy, String value) { instance.arguments.put(filterBy.getFilterKey(), value); return this; } /** * adds a build for a hashmap of filters * * @param hashmap contains enum values and vaslues for filter builds * @return an appropriate build Object */ @Nonnull public FilterBuilder setFilters(@Nonnull HashMap<FilterBy, String> hashmap){ for (Map.Entry<FilterBy, String> e : hashmap.entrySet()){ instance.arguments.put(e.getKey().getFilterKey(), e.getValue()); } return this; } /** * validate all set filters allowed by the api * * @param acceptedFilters list of filters, which are allowed. Pass null if all filters are allowed. * @throws CotSdkException If a filter that is not allowed is detected. */ public void validateSupportedFilters(@Nullable final List acceptedFilters) { // Do nothing, when all filters are accepted. if (acceptedFilters != null) { for (final Map.Entry<String, String> definedFilter : instance.arguments.entrySet()) { if (!acceptedFilters.contains(FilterBy.getFilterBy(definedFilter.getKey()))) { throw new CotSdkException(String.format("This filter is not available in used api [%s]", definedFilter.getKey())); } } } } } }
package com.tumblr.jumblr.request; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.scribe.model.Token; import org.scribe.model.Verifier; import org.scribe.oauth.OAuthService; public class Authenticator { private final OAuthService service; private final Token request; private final String verifierParameter; private final URI callbackUrl; private CallbackServer s; private Token access; /** * Authenticates the current user. Note that this operation opens a browser window and blocks on user input. * @param service The OAuthService to authenticate * @param verifierParameter The name of the parameter that will have the OAuth verifier * @param callbackUrl The url given to the Scribe ServiceBuilder as the callback URL. * @return The newly created access token * @throws IOException */ public static Token autoAuthenticate(OAuthService service, String verifierParameter, URI callbackUrl) throws IOException { Authenticator a = new Authenticator(service, verifierParameter, callbackUrl); a.startServer(); a.openBrowser(); a.handleRequest(); return a.getAccessToken(); } public Authenticator(OAuthService service, String verifierParameter, URI callbackUrl) throws IOException { this.service = service; this.request = service.getRequestToken(); this.verifierParameter = verifierParameter; this.callbackUrl = callbackUrl; } public void startServer() throws IOException { this.s = new CallbackServer(callbackUrl); } public void openBrowser() { openBrowser(getAuthorizationUrl()); } public void handleRequest() { URI requestUrl = s.waitForNextRequest(); s.stop(); List<String> possibleVerifiers = Authenticator.getUrlParameters(requestUrl).get(verifierParameter); if (possibleVerifiers.size() != 1) { throw new RuntimeException(String.format("There were %d parameters with the given name," + " when exactly one was expected.", possibleVerifiers.size())); } String verifier = possibleVerifiers.get(0); access = service.getAccessToken(request, new Verifier(verifier)); } public Token getAccessToken() { return access; } public String getAuthorizationUrl() { return service.getAuthorizationUrl(request); } /** * Get all the parameters from a given URI. * @param url the url to get the parameters from * @return all the parameters and values */ private static ListMultimap<String, String> getUrlParameters(URI url) { ListMultimap<String, String> ret = ArrayListMultimap.create(); for (NameValuePair param : URLEncodedUtils.parse(url, "UTF-8")) { ret.put(param.getName(), param.getValue()); } return ret; } /** * Opens the browser to the given url * @param url url to open the browser to */ static void openBrowser(String url) { if(!Desktop.isDesktopSupported()) { throw new RuntimeException("Can't open browser: desktop not supported"); } Desktop d = Desktop.getDesktop(); URI uri; try { uri = new URI(url); d.browse(uri); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.uber.jenkins.phabricator.tasks; import com.uber.jenkins.phabricator.utils.Logger; /** * Base task for all operations in the phabricator-jenkins plugin. */ public abstract class Task { /** * Task results. */ public enum Result { SUCCESS, FAILURE, IGNORED, SKIPPED, UNKNWON }; protected Logger logger; protected Result result = Result.UNKNWON; /** * Task constructor. * @param logger The logger where logs go to. */ public Task(Logger logger) { this.logger = logger; } /** * Runs the task workflow. */ public Result run() { setUp(); execute(); tearDown(); return result; } /** * Logs the message. * @param message The message to log. */ protected void info(String message) { logger.info(getTag(), message); } /** * Gets the task's tag. * @return A string representation of this task's tag. */ protected abstract String getTag(); /** * Sets up the environment before task execution. */ protected abstract void setUp(); /** * Executes the task workflow. */ protected abstract void execute(); /** * Tears down after task execution. */ protected abstract void tearDown(); }
package com.Acrobot.ChestShop.Listeners.Block.Break; import com.Acrobot.Breeze.Utils.BlockUtil; import com.Acrobot.ChestShop.Config.Config; import com.Acrobot.ChestShop.Config.Property; import com.Acrobot.ChestShop.Events.ShopDestroyedEvent; import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Signs.ChestShopSign; import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uName; import com.google.common.collect.Lists; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Chest; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.material.Directional; import org.bukkit.material.PistonBaseMaterial; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import static com.Acrobot.Breeze.Utils.BlockUtil.getAttachedFace; import static com.Acrobot.Breeze.Utils.BlockUtil.isSign; import static com.Acrobot.ChestShop.Config.Property.TURN_OFF_SIGN_PROTECTION; import static com.Acrobot.ChestShop.Permission.ADMIN; import static com.Acrobot.ChestShop.Permission.MOD; import static com.Acrobot.ChestShop.Signs.ChestShopSign.NAME_LINE; /** * @author Acrobot */ public class SignBreak implements Listener { private static final BlockFace[] SIGN_CONNECTION_FACES = {BlockFace.SOUTH, BlockFace.NORTH, BlockFace.EAST, BlockFace.WEST}; @EventHandler(ignoreCancelled = true) public static void onSignBreak(BlockBreakEvent event) { if (!canBlockBeBroken(event.getBlock(), event.getPlayer())) { event.setCancelled(true); } } @EventHandler(ignoreCancelled = true) public static void onBlockPistonExtend(BlockPistonExtendEvent event) { for (Block block : getExtendBlocks(event)) { if (!canBlockBeBroken(block, null)) { event.setCancelled(true); return; } } } @EventHandler(ignoreCancelled = true) public static void onBlockPistonRetract(BlockPistonRetractEvent event) { if (!canBlockBeBroken(getRetractBlock(event), null)) { event.setCancelled(true); } } @EventHandler(ignoreCancelled = true) public static void onExplosion(EntityExplodeEvent event) { if (event.blockList() == null || !Config.getBoolean(Property.USE_BUILT_IN_PROTECTION)) { return; } for (Block block : event.blockList()) { if (!canBlockBeBroken(block, null)) { event.setCancelled(true); return; } } } public static boolean canBlockBeBroken(Block block, Player breaker) { List<Sign> attachedSigns = getAttachedSigns(block); List<Sign> brokenBlocks = new LinkedList<Sign>(); boolean canBeBroken = true; for (Sign sign : attachedSigns) { sign.update(); if (!canBeBroken || !ChestShopSign.isValid(sign)) { continue; } if (Config.getBoolean(TURN_OFF_SIGN_PROTECTION) || canDestroyShop(breaker, sign.getLine(NAME_LINE))) { brokenBlocks.add(sign); } else { canBeBroken = false; } } if (!canBeBroken) { return false; } for (Sign sign : brokenBlocks) { sendShopDestroyedEvent(sign, breaker); } return true; } private static boolean canDestroyShop(Player player, String name) { return player == null || hasShopBreakingPermission(player) || canUseName(player, name); } private static boolean canUseName(Player player, String name) { return uName.canUseName(player, name); } private static boolean hasShopBreakingPermission(Player player) { return Permission.has(player, ADMIN) || Permission.has(player, MOD); } private static void sendShopDestroyedEvent(Sign sign, Player player) { Chest connectedChest = null; if (!ChestShopSign.isAdminShop(sign)) { connectedChest = uBlock.findConnectedChest(sign.getBlock()); } Event event = new ShopDestroyedEvent(player, sign, connectedChest); Bukkit.getPluginManager().callEvent(event); } private static List<Sign> getAttachedSigns(Block block) { if (block == null) { return Lists.newArrayList(); } if (isSign(block)) { return Arrays.asList((Sign) block.getState()); } else { List<Sign> attachedSigns = new LinkedList<Sign>(); for (BlockFace face : SIGN_CONNECTION_FACES) { Block relative = block.getRelative(face); if (!isSign(relative)) { continue; } Sign sign = (Sign) relative.getState(); if (getAttachedFace(sign).equals(block)) { attachedSigns.add(sign); } } return attachedSigns; } } private static Block getRetractBlock(BlockPistonRetractEvent event) { Block block = getRetractLocationBlock(event); return (block != null && !BlockUtil.isSign(block) ? block : null); } //Those are fixes for CraftBukkit's piston bug, where piston appears not to be a piston. private static BlockFace getPistonDirection(Block block) { return block.getState().getData() instanceof PistonBaseMaterial ? ((Directional) block.getState().getData()).getFacing() : null; } private static Block getRetractLocationBlock(BlockPistonRetractEvent event) { BlockFace pistonDirection = getPistonDirection(event.getBlock()); return pistonDirection != null ? event.getBlock().getRelative((pistonDirection), 2).getLocation().getBlock() : null; } private static List<Block> getExtendBlocks(BlockPistonExtendEvent event) { BlockFace pistonDirection = getPistonDirection(event.getBlock()); if (pistonDirection == null) { return new ArrayList<Block>(); } Block piston = event.getBlock(); List<Block> pushedBlocks = new ArrayList<Block>(); for (int currentBlock = 1; currentBlock < event.getLength() + 1; currentBlock++) { Block block = piston.getRelative(pistonDirection, currentBlock); Material blockType = block.getType(); if (blockType == Material.AIR) { break; } pushedBlocks.add(block); } return pushedBlocks; } }
package com.whirvis.jraknet.client; import static com.whirvis.jraknet.protocol.MessageIdentifier.*; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.whirvis.jraknet.Packet; import com.whirvis.jraknet.RakNet; import com.whirvis.jraknet.RakNetException; import com.whirvis.jraknet.RakNetPacket; import com.whirvis.jraknet.client.discovery.DiscoveredServer; import com.whirvis.jraknet.client.discovery.DiscoveryMode; import com.whirvis.jraknet.client.discovery.DiscoveryThread; import com.whirvis.jraknet.protocol.MessageIdentifier; import com.whirvis.jraknet.protocol.Reliability; import com.whirvis.jraknet.protocol.login.ConnectionRequest; import com.whirvis.jraknet.protocol.login.OpenConnectionRequestOne; import com.whirvis.jraknet.protocol.login.OpenConnectionRequestTwo; import com.whirvis.jraknet.protocol.message.CustomPacket; import com.whirvis.jraknet.protocol.message.EncapsulatedPacket; import com.whirvis.jraknet.protocol.message.acknowledge.Acknowledge; import com.whirvis.jraknet.protocol.status.UnconnectedPing; import com.whirvis.jraknet.protocol.status.UnconnectedPingOpenConnections; import com.whirvis.jraknet.protocol.status.UnconnectedPong; import com.whirvis.jraknet.session.RakNetServerSession; import com.whirvis.jraknet.session.RakNetState; import com.whirvis.jraknet.session.UnumRakNetPeer; import com.whirvis.jraknet.util.RakNetUtils; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.nio.NioDatagramChannel; /** * Used to connect to servers using the RakNet protocol. * * @author Trent Summerlin */ public class RakNetClient implements UnumRakNetPeer, RakNetClientListener { private static final Logger log = LoggerFactory.getLogger(RakNetClient.class); // Used to discover systems without relying on the main thread private static DiscoveryThread discoverySystem = new DiscoveryThread(); private static final int[] DEFAULT_TRANSFER_UNITS = new int[] { RakNet.MAXIMUM_MTU_SIZE, 1200, 576, RakNet.MINIMUM_MTU_SIZE }; // Client data private final long guid; private final long pingId; private final long timestamp; private HashSet<Integer> discoveryPorts; private DiscoveryMode discoveryMode; /** Synchronize this first! (<code>externalServers</code> goes second!) */ private final ConcurrentHashMap<InetSocketAddress, DiscoveredServer> discovered; /** Synchronize this second! (<code>discovered</code> goes first!) */ private final ConcurrentHashMap<InetSocketAddress, DiscoveredServer> externalServers; private final ConcurrentLinkedQueue<RakNetClientListener> listeners; private Thread clientThread; // Networking data private final Bootstrap bootstrap; private final EventLoopGroup group; private final RakNetClientHandler handler; private MaximumTransferUnit[] maximumTransferUnits; // Session management private Channel channel; private SessionPreparation preparation; private volatile RakNetServerSession session; /** * Constructs a <code>RakNetClient</code> with the specified * <code>DiscoveryMode</code> and server discovery port. * * @param discoveryMode * how the client will discover servers. If this is set to * <code>null</code>, the client will enable set it to * <code>DiscoveryMode.ALL_CONNECTIONS</code> as long as the port * is greater than -1. * @param discoveryPorts * the ports the client will attempt to discover servers on. */ public RakNetClient(DiscoveryMode discoveryMode, int... discoveryPorts) { // Set client data UUID uuid = UUID.randomUUID(); this.guid = uuid.getMostSignificantBits(); this.pingId = uuid.getLeastSignificantBits(); this.timestamp = System.currentTimeMillis(); this.listeners = new ConcurrentLinkedQueue<RakNetClientListener>(); // Set discovery data this.discoveryPorts = new HashSet<Integer>(); this.discoveryMode = discoveryMode; this.setDiscoveryPorts(discoveryPorts); if (discoveryMode == null) { this.discoveryMode = (discoveryPorts.length > 0 ? DiscoveryMode.ALL_CONNECTIONS : DiscoveryMode.NONE); } this.discovered = new ConcurrentHashMap<InetSocketAddress, DiscoveredServer>(); this.externalServers = new ConcurrentHashMap<InetSocketAddress, DiscoveredServer>(); // Set networking data this.bootstrap = new Bootstrap(); this.group = new NioEventLoopGroup(); this.handler = new RakNetClientHandler(this); // Add maximum transfer units this.setMaximumTransferUnits(DEFAULT_TRANSFER_UNITS); // Initiate bootstrap data try { bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler); bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false); this.channel = bootstrap.bind(0).sync().channel(); log.debug("Created and bound bootstrap"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Constructs a <code>RakNetClient</code> with the specified server * discovery port with the <code>DiscoveryMode</code> set to * <code>DiscoveryMode.ALL_CONNECTIONS</code> or * <code>DiscoveryMode.NONE</code> if no discovery ports are specified. * * @param discoveryPorts * the ports the client will attempt to discover servers on. */ public RakNetClient(int... discoveryPorts) { this(null, discoveryPorts); } /** * @return the client's networking protocol version. */ public final int getProtocolVersion() { return RakNet.CLIENT_NETWORK_PROTOCOL; } /** * @return the client's globally unique ID. */ public final long getGloballyUniqueId() { return this.guid; } /** * @return the client's ping ID. */ public final long getPingId() { return this.pingId; } /** * @return the client's timestamp. */ public final long getTimestamp() { return (System.currentTimeMillis() - this.timestamp); } /** * @return the client's discovery ports. */ public final int[] getDiscoveryPorts() { return discoveryPorts.stream().mapToInt(Integer::intValue).toArray(); } /** * Sets the client's discovery ports. * * @param discoveryPorts * the new discovery ports. */ public final void setDiscoveryPorts(int... discoveryPorts) { // We make a new set to prevent duplicates HashSet<Integer> discoverySet = new HashSet<Integer>(); for (int discoveryPort : discoveryPorts) { if (discoveryPort < 0 || discoveryPort > 65535) { throw new IllegalArgumentException("Invalid port range for discovery port"); } discoverySet.add(discoveryPort); } // Set discovery ports this.discoveryPorts = discoverySet; String discoveryString = Arrays.toString(discoveryPorts); log.debug("Set discovery ports to " + (discoverySet.size() > 0 ? discoveryString.substring(1, discoveryString.length() - 1) : "nothing")); } /** * Adds a discovery port to start broadcasting to. * * @param discoveryPort * the discovery port to start broadcasting to. */ public final void addDiscoveryPort(int discoveryPort) { discoveryPorts.add(discoveryPort); log.debug("Added discovery port " + discoveryPort); } /** * Removes a discovery port to stop broadcasting from. * * @param discoveryPort * the discovery part to stop broadcasting from. */ public final void removeDiscoveryPort(int discoveryPort) { discoveryPorts.remove(discoveryPort); log.debug("Removed discovery port " + discoveryPort); } /** * @return the client's discovery mode. */ public final DiscoveryMode getDiscoveryMode() { return this.discoveryMode; } /** * Sets the client's discovery mode. * * @param mode * how the client will discover servers on the local network. */ public final void setDiscoveryMode(DiscoveryMode mode) { if (listeners.size() <= 0) { log.warn("Client has no listeners"); } this.discoveryMode = (mode != null ? mode : DiscoveryMode.NONE); if (this.discoveryMode == DiscoveryMode.NONE) { for (InetSocketAddress address : discovered.keySet()) { // Notify API for (RakNetClientListener listener : listeners) { listener.onServerForgotten(address); } } discovered.clear(); // We are not discovering servers anymore! log.debug("Cleared discovered servers due to discovery mode being set to " + DiscoveryMode.NONE); } log.debug("Set discovery mode to " + mode); } /** * @return the thread the server is running on if it was started using * <code>startThreaded()</code>. */ public final Thread getThread() { return this.clientThread; } /** * Adds a server to the client's external server discovery list. This * functions like the normal discovery system but is not affected by the * <code>DiscoveryMode</code> or discovery port set for the client. * * @param address * the server address. */ public final void addExternalServer(InetSocketAddress address) { if (!externalServers.containsKey(address)) { // Add newly discovered server externalServers.put(address, new DiscoveredServer(address, -1, null)); // Notify API log.debug("Added external server with address " + address); for (RakNetClientListener listener : listeners) { listener.onExternalServerAdded(address); } } } /** * Adds a server to the client's external server discovery list. This * functions like the normal discovery system but is not affected by the * <code>DiscoveryMode</code> or discovery port set for the client. * * @param address * the server address. * @param port * the server port. */ public final void addExternalServer(InetAddress address, int port) { this.addExternalServer(new InetSocketAddress(address, port)); } /** * Adds a server to the client's external server discovery list. This * functions like the normal discovery system but is not affected by the * <code>DiscoveryMode</code> or discovery port set for the client. * * @param address * the server address. * @param port * the server port. * @throws UnknownHostException * if the specified address is an unknown host. */ public final void addExternalServer(String address, int port) throws UnknownHostException { this.addExternalServer(InetAddress.getByName(address), port); } /** * Removes an external server from the client's external server discovery * list. * * @param address * the server address. */ public final void removeExternalServer(InetSocketAddress address) { if (externalServers.containsKey(address)) { // Remove now forgotten server externalServers.remove(address); // Notify API log.debug("Removed external server with address " + address); for (RakNetClientListener listener : listeners) { listener.onExternalServerRemoved(address); } } } /** * Removes an external server from the client's external server discovery * list. * * @param address * the server address. * @param port * the server port. */ public final void removeExternalServer(InetAddress address, int port) { this.removeExternalServer(new InetSocketAddress(address, port)); } /** * Removes an external server from the client's external server discovery * list. * * @param address * the server address. * @param port * the server port. * @throws UnknownHostException * if the specified address is an unknown host. */ public final void removeExternalServer(String address, int port) throws UnknownHostException { this.removeExternalServer(InetAddress.getByName(address), port); } /** * Removes an external server from the client's external server discovery * list. * * @param server * the discovered server. */ public final void removeExternalServer(DiscoveredServer server) { if (!externalServers.contains(server)) { throw new IllegalArgumentException("Discovered external server does not belong to client"); } this.removeExternalServer(server.getAddress()); } /** * @return the local servers as an array. */ public final DiscoveredServer[] getLocalServers() { return discovered.values().toArray(new DiscoveredServer[discovered.size()]); } /** * @return the external servers as an array. */ public final DiscoveredServer[] getExternalServers() { return externalServers.values().toArray(new DiscoveredServer[externalServers.size()]); } /** * Sets the size of the maximum transfer units that will be used by the * client during in. * * @param maximumTransferUnitSizes * the maximum transfer unit sizes. */ public final void setMaximumTransferUnits(int... maximumTransferUnitSizes) { boolean foundTransferUnit = false; ArrayList<MaximumTransferUnit> maximumTransferUnits = new ArrayList<MaximumTransferUnit>(); for (int i = 0; i < maximumTransferUnitSizes.length; i++) { int maximumTransferUnitSize = maximumTransferUnitSizes[i]; if (maximumTransferUnitSize > RakNet.MAXIMUM_MTU_SIZE || maximumTransferUnitSize < RakNet.MINIMUM_MTU_SIZE) { throw new IllegalArgumentException("Maximum transfer unit size must be between " + RakNet.MINIMUM_MTU_SIZE + "-" + RakNet.MAXIMUM_MTU_SIZE); } if (RakNetUtils.getMaximumTransferUnit() >= maximumTransferUnitSize) { maximumTransferUnits.add(new MaximumTransferUnit(maximumTransferUnitSize, (i * 2) + (i + 1 < maximumTransferUnitSizes.length ? 2 : 1))); foundTransferUnit = true; } else { log.warn("Valid maximum transfer unit " + maximumTransferUnitSize + " failed to register due to network card limitations"); } } this.maximumTransferUnits = maximumTransferUnits.toArray(new MaximumTransferUnit[maximumTransferUnits.size()]); if (foundTransferUnit == false) { throw new RuntimeException("No compatible maximum transfer unit found for machine network cards"); } } /** * @return the maximum transfer units the client will use during in. */ public final int[] getMaximumTransferUnits() { int[] maximumTransferUnitSizes = new int[maximumTransferUnits.length]; for (int i = 0; i < maximumTransferUnitSizes.length; i++) { maximumTransferUnitSizes[i] = maximumTransferUnits[i].getSize(); } return maximumTransferUnitSizes; } /** * @return the session the client is connected to. */ public final RakNetServerSession getSession() { return this.session; } /** * @return the client's listeners. */ public final RakNetClientListener[] getListeners() { return listeners.toArray(new RakNetClientListener[listeners.size()]); } /** * Adds a listener to the client. * * @param listener * the listener to add. * @return the client. */ public final RakNetClient addListener(RakNetClientListener listener) { // Validate listener if (listener == null) { throw new NullPointerException("Listener must not be null"); } if (listeners.contains(listener)) { throw new IllegalArgumentException("A listener cannot be added twice"); } if (listener instanceof RakNetClient && !listener.equals(this)) { throw new IllegalArgumentException("A client cannot be used as a listener except for itself"); } // Add listener listeners.add(listener); log.info("Added listener " + listener.getClass().getName()); // Initiate discovery system if it is not yet started if (discoverySystem.isRunning() == false) { discoverySystem.start(); } discoverySystem.addClient(this); return this; } /** * Adds the client to its own set of listeners, used when extending the * <code>RakNetClient</code> directly. * * @return the client. */ public final RakNetClient addSelfListener() { this.addListener(this); return this; } /** * Removes a listener from the client. * * @param listener * the listener to remove. * @return the client. */ public final RakNetClient removeListener(RakNetClientListener listener) { boolean hadListener = listeners.remove(listener); if (hadListener == true) { log.info("Removed listener " + listener.getClass().getName()); } else { log.warn("Attempted to removed unregistered listener " + listener.getClass().getName()); } return this; } /** * Removes the client from its own set of listeners, used when extending the * <code>RakNetClient</code> directly. * * @return the client. */ public final RakNetClient removeSelfListener() { this.removeListener(this); return this; } /** * @return <code>true</code> if the client is currently connected to a * server. */ public final boolean isConnected() { if (session == null) { return false; } return session.getState().equals(RakNetState.CONNECTED); } /** * Returns whether or not the client is doing something on a thread. This * can mean multiple things, with being connected to a server or looking for * servers on the local network to name a few. * * @return <code>true</code> if the client is running. */ public final boolean isRunning() { if (channel == null) { return false; } return channel.isOpen(); } /** * Called whenever the handler catches an exception in Netty. * * @param address * the address that caused the exception. * @param cause * the exception caught by the handler. */ protected final void handleHandlerException(InetSocketAddress address, Throwable cause) { // Handle exception based on connection state if (address.equals(preparation.address)) { if (preparation != null) { preparation.cancelReason = new NettyHandlerException(this, handler, cause); } else if (session != null) { this.disconnect(cause.getClass().getName() + ": " + cause.getLocalizedMessage()); } } // Notify API log.warn("Handled exception " + cause.getClass().getName() + " caused by address " + address); for (RakNetClientListener listener : listeners) { listener.onHandlerException(address, cause); } } /** * Handles a packet received by the handler. * * @param packet * the packet to handle. * @param sender * the address of the sender. */ public final void handleMessage(RakNetPacket packet, InetSocketAddress sender) { short packetId = packet.getId(); // This packet has to do with server discovery so it isn't handled here if (packetId == ID_UNCONNECTED_PONG) { UnconnectedPong pong = new UnconnectedPong(packet); pong.decode(); if (pong.identifier != null) { this.updateDiscoveryData(sender, pong); } } // Are we still ging in? if (preparation != null) { if (sender.equals(preparation.address)) { preparation.handleMessage(packet); return; } } // Only handle these from the server we're connected to! if (session != null) { if (sender.equals(session.getAddress())) { if (packetId >= ID_CUSTOM_0 && packetId <= ID_CUSTOM_F) { CustomPacket custom = new CustomPacket(packet); custom.decode(); session.handleCustom(custom); } else if (packetId == Acknowledge.ACKNOWLEDGED || packetId == Acknowledge.NOT_ACKNOWLEDGED) { Acknowledge acknowledge = new Acknowledge(packet); acknowledge.decode(); session.handleAcknowledge(acknowledge); } } } if (MessageIdentifier.hasPacket(packet.getId())) { log.debug("Handled internal packet with ID " + MessageIdentifier.getName(packet.getId()) + " (" + packet.getId() + ")"); } else { log.debug("Sent packet with ID " + packet.getId() + " to session handler"); } } /** * Sends a raw message to the specified address. Be careful when using this * method, because if it is used incorrectly it could break server sessions * entirely! If you are wanting to send a message to a session, you are * probably looking for the * {@link com.whirvis.jraknet.session.RakNetSession#sendMessage(com.whirvis.jraknet.protocol.Reliability, com.whirvis.jraknet.Packet) * sendMessage} method. * * @param buf * the buffer to send. * @param address * the address to send the buffer to. */ public final void sendNettyMessage(ByteBuf buf, InetSocketAddress address) { channel.writeAndFlush(new DatagramPacket(buf, address)); log.debug("Sent netty message with size of " + buf.capacity() + " bytes (" + (buf.capacity() * 8) + " bits) to " + address); } /** * Sends a raw message to the specified address. Be careful when using this * method, because if it is used incorrectly it could break server sessions * entirely! If you are wanting to send a message to a session, you are * probably looking for the * {@link com.whirvis.jraknet.session.RakNetSession#sendMessage(com.whirvis.jraknet.protocol.Reliability, com.whirvis.jraknet.Packet) * sendMessage} method. * * @param packet * the packet to send. * @param address * the address to send the packet to. */ public final void sendNettyMessage(Packet packet, InetSocketAddress address) { this.sendNettyMessage(packet.buffer(), address); } /** * Sends a raw message to the specified address. Be careful when using this * method, because if it is used incorrectly it could break server sessions * entirely! If you are wanting to send a message to a session, you are * probably looking for the * {@link com.whirvis.jraknet.session.RakNetSession#sendMessage(com.whirvis.jraknet.protocol.Reliability, int) * sendMessage} method. * * @param packetId * the ID of the packet to send. * @param address * the address to send the packet to. */ public final void sendNettyMessage(int packetId, InetSocketAddress address) { this.sendNettyMessage(new RakNetPacket(packetId), address); } /** * Updates the discovery data in the client by sending pings and removing * servers that have taken too long to respond to a ping. */ public final void updateDiscoveryData() { // Remove all servers that have timed out ArrayList<InetSocketAddress> forgottenServers = new ArrayList<InetSocketAddress>(); for (InetSocketAddress discoveredServerAddress : discovered.keySet()) { DiscoveredServer discoveredServer = discovered.get(discoveredServerAddress); if (System.currentTimeMillis() - discoveredServer.getDiscoveryTimestamp() >= DiscoveredServer.SERVER_TIMEOUT_MILLI) { forgottenServers.add(discoveredServerAddress); // Notify API for (RakNetClientListener listener : listeners) { listener.onServerForgotten(discoveredServerAddress); } } } discovered.keySet().removeAll(forgottenServers); if (forgottenServers.size() > 0) { log.debug("Forgot " + forgottenServers.size() + " servers"); } // Broadcast ping to local network if (discoveryMode != DiscoveryMode.NONE) { Iterator<Integer> discoveryIterator = discoveryPorts.iterator(); while (discoveryIterator.hasNext()) { int discoveryPort = discoveryIterator.next().intValue(); UnconnectedPing ping = new UnconnectedPing(); if (discoveryMode == DiscoveryMode.OPEN_CONNECTIONS) { ping = new UnconnectedPingOpenConnections(); } ping.timestamp = this.getTimestamp(); ping.pingId = this.pingId; ping.encode(); if (!ping.failed()) { this.sendNettyMessage(ping, new InetSocketAddress("255.255.255.255", discoveryPort)); log.debug("Broadcasted unconnected ping to port " + discoveryPort); } else { log.error(UnconnectedPing.class.getSimpleName() + " failed to encode"); } } } // Send ping to external servers if (!externalServers.isEmpty()) { UnconnectedPing ping = new UnconnectedPing(); ping.timestamp = this.getTimestamp(); ping.pingId = this.pingId; ping.encode(); if (!ping.failed()) { for (InetSocketAddress externalAddress : externalServers.keySet()) { this.sendNettyMessage(ping, externalAddress); log.debug("Broadcasting ping to server with address " + externalAddress); } } else { log.error(UnconnectedPing.class.getSimpleName() + " failed to encode"); } } } /** * This method handles the specified <code>UnconnectedPong</code> packet and * updates the discovery data accordingly. * * @param sender * the sender of the <code>UnconnectedPong</code> packet. * @param pong * the <code>UnconnectedPong</code> packet to handle. */ public final void updateDiscoveryData(InetSocketAddress sender, UnconnectedPong pong) { // Is this a local or an external server? if (RakNetUtils.isLocalAddress(sender) && !externalServers.containsKey(sender)) { // This is a local server if (!discovered.containsKey(sender)) { // Add newly discovered server discovered.put(sender, new DiscoveredServer(sender, System.currentTimeMillis(), pong.identifier)); // Notify API log.info("Discovered local server with address " + sender); for (RakNetClientListener listener : listeners) { listener.onServerDiscovered(sender, pong.identifier); } } else { // Server already discovered, but data has changed DiscoveredServer server = discovered.get(sender); server.setDiscoveryTimestamp(System.currentTimeMillis()); if (!pong.identifier.equals(server.getIdentifier())) { // Update server identifier server.setIdentifier(pong.identifier); // Notify API log.debug("Updated local server with address " + sender + " identifier to \"" + pong.identifier + "\""); for (RakNetClientListener listener : listeners) { listener.onServerIdentifierUpdate(sender, pong.identifier); } } } } else if (externalServers.containsKey(sender)) { DiscoveredServer server = externalServers.get(sender); server.setDiscoveryTimestamp(System.currentTimeMillis()); if (!pong.identifier.equals(server.getIdentifier())) { // Update server identifier server.setIdentifier(pong.identifier); // Notify API log.debug("Updated local server with address " + sender + " identifier to \"" + pong.identifier + "\""); for (RakNetClientListener listener : listeners) { listener.onExternalServerIdentifierUpdate(sender, pong.identifier); } } } } /** * Connects the client to a server with the specified address. * * @param address * the address of the server to connect to. * @throws RakNetException * if an error occurs during connection or in. */ public final void connect(InetSocketAddress address) throws RakNetException { // Make sure we have a listener if (listeners.size() <= 0) { log.warn("Client has no listeners"); } // Reset client data if (this.isConnected()) { this.disconnect("Disconnected"); } MaximumTransferUnit[] units = MaximumTransferUnit.sort(maximumTransferUnits); this.preparation = new SessionPreparation(this, units[0].getSize()); preparation.address = address; // Send OPEN_CONNECTION_REQUEST_ONE with a decreasing MTU int retriesLeft = 0; try { for (MaximumTransferUnit unit : units) { retriesLeft += unit.getRetries(); while (unit.retry() > 0 && preparation.loginPackets[0] == false && preparation.cancelReason == null) { OpenConnectionRequestOne connectionRequestOne = new OpenConnectionRequestOne(); connectionRequestOne.maximumTransferUnit = unit.getSize(); connectionRequestOne.protocolVersion = this.getProtocolVersion(); connectionRequestOne.encode(); this.sendNettyMessage(connectionRequestOne, address); Thread.sleep(500); } } } catch (InterruptedException e) { throw new RakNetException(e); } // Reset maximum transfer units so they can be used again for (MaximumTransferUnit unit : maximumTransferUnits) { unit.reset(); } // If the server didn't respond then it is offline if (preparation.loginPackets[0] == false && preparation.cancelReason == null) { preparation.cancelReason = new ServerOfflineException(this, preparation.address); } // Send OPEN_CONNECTION_REQUEST_TWO until a response is received try { while (retriesLeft > 0 && preparation.loginPackets[1] == false && preparation.cancelReason == null) { OpenConnectionRequestTwo connectionRequestTwo = new OpenConnectionRequestTwo(); connectionRequestTwo.clientGuid = this.guid; connectionRequestTwo.address = preparation.address; connectionRequestTwo.maximumTransferUnit = preparation.maximumTransferUnit; connectionRequestTwo.encode(); if (!connectionRequestTwo.failed()) { this.sendNettyMessage(connectionRequestTwo, address); Thread.sleep(500); } else { preparation.cancelReason = new PacketBufferException(this, connectionRequestTwo); } } } catch (InterruptedException e) { throw new RakNetException(e); } // If the server didn't respond then it is offline if (preparation.loginPackets[1] == false && preparation.cancelReason == null) { preparation.cancelReason = new ServerOfflineException(this, preparation.address); } // If the session was set we are connected if (preparation.readyForSession()) { // Set session and delete preparation data this.session = preparation.createSession(channel); this.preparation = null; // Send connection packet ConnectionRequest connectionRequest = new ConnectionRequest(); connectionRequest.clientGuid = this.guid; connectionRequest.timestamp = (System.currentTimeMillis() - this.timestamp); connectionRequest.encode(); session.sendMessage(Reliability.RELIABLE_ORDERED, connectionRequest); log.debug("Sent connection packet to server"); // Initiate connection loop required for the session to function this.initConnection(); } else { // Reset the connection data, it failed RakNetException cancelReason = preparation.cancelReason; this.preparation = null; this.session = null; throw cancelReason; } } /** * Connects the client to a server with the specified address. * * @param address * the address of the server to connect to. * @param port * the port of the server to connect to. * @throws RakNetException * if an error occurs during connection or in. */ public final void connect(InetAddress address, int port) throws RakNetException { this.connect(new InetSocketAddress(address, port)); } /** * Connects the client to a server with the specified address. * * @param address * the address of the server to connect to. * @param port * the port of the server to connect to. * @throws RakNetException * if an error occurs during connection or in. * @throws UnknownHostException * if the specified address is an unknown host. */ public final void connect(String address, int port) throws RakNetException, UnknownHostException { this.connect(InetAddress.getByName(address), port); } /** * Connects the the client to the specified discovered server. * * @param server * the discovered server to connect to. * @throws RakNetException * if an error occurs during connection or in. */ public final void connect(DiscoveredServer server) throws RakNetException { this.connect(server.getAddress()); } /** * Connects the client to a server with the specified address on its own * <code>Thread</code>. * * @param address * the address of the server to connect to. * @return the Thread the client is running on. */ public final Thread connectThreaded(InetSocketAddress address) { // Give the thread a reference RakNetClient client = this; // Create and start the thread Thread thread = new Thread() { @Override public void run() { try { client.connect(address); } catch (Throwable throwable) { if (client.getListeners().length > 0) { for (RakNetClientListener listener : client.getListeners()) { listener.onThreadException(throwable); } } else { throwable.printStackTrace(); } } } }; thread.setName("JRAKNET_CLIENT_" + Long.toHexString(client.getGloballyUniqueId()).toUpperCase()); thread.start(); this.clientThread = thread; log.info("Started on thread with name " + thread.getName()); // Return the thread so it can be modified return thread; } /** * Connects the client to a server with the specified address on its own * <code>Thread</code>. * * @param address * the address of the server to connect to. * @param port * the port of the server to connect to. * @return the Thread the client is running on. */ public final Thread connectThreaded(InetAddress address, int port) { return this.connectThreaded(new InetSocketAddress(address, port)); } /** * Connects the client to a server with the specified address on its own * <code>Thread</code>. * * @param address * the address of the server to connect to. * @param port * the port of the server to connect to. * @throws UnknownHostException * if the specified address is an unknown host. * @return the Thread the client is running on. */ public final Thread connectThreaded(String address, int port) throws UnknownHostException { return this.connectThreaded(InetAddress.getByName(address), port); } /** * Connects the the client to the specified discovered server on its own * <code>Thread</code>. * * @param server * the discovered server to connect to. * @return the Thread the client is running on. */ public final Thread connectThreaded(DiscoveredServer server) { return this.connectThreaded(server.getAddress()); } /** * Starts the loop needed for the client to stay connected to the server. * * @throws RakNetException * if any problems occur during connection. */ private final void initConnection() throws RakNetException { if (session != null) { log.debug("Initiated connected with server"); while (session != null) { session.update(); /* * The order here is important, as the session could end up * becoming null if we sleep before we actually update it. */ try { Thread.sleep(0, 1); // Lower CPU usage } catch (InterruptedException e) { // Ignore this, it does not matter } } } else { throw new RakNetClientException(this, "Attempted to initiate connection without session"); } } @Override public final EncapsulatedPacket sendMessage(Reliability reliability, int channel, Packet packet) { if (this.isConnected()) { return session.sendMessage(reliability, channel, packet); } return null; } /** * Disconnects the client from the server if it is connected to one. * * @param reason * the reason the client disconnected from the server. */ public final void disconnect(String reason) { if (session != null) { // Disconnect session session.closeConnection(); // Interrupt its thread if it owns one if (this.clientThread != null) { clientThread.interrupt(); } // Notify API log.info("Disconnected from server with address " + session.getAddress() + " with reason \"" + reason + "\""); for (RakNetClientListener listener : listeners) { listener.onDisconnect(session, reason); } // Destroy session this.session = null; } else { log.warn( "Attempted to disconnect from server even though it was not connected to as server in the first place"); } } /** * Disconnects the client from the server if it is connected to one. */ public final void disconnect() { this.disconnect("Disconnected"); } /** * Shuts down the client for good, once this is called the client can no * longer connect to servers. */ public final void shutdown() { // Close channel if (this.isRunning()) { channel.close(); group.shutdownGracefully(); // Shutdown discovery system if needed discoverySystem.removeClient(this); if (discoverySystem.getClients().length <= 0) { discoverySystem.shutdown(); discoverySystem = new DiscoveryThread(); } // Notify API log.info("Shutdown client"); for (RakNetClientListener listener : listeners) { listener.onClientShutdown(); } } else { log.warn("Client attempted to shutdown after it was already shutdown"); } } /** * Disconnects from the server and shuts down the client for good, once this * is called the client can no longer connect to servers. * * @param reason * the reason the client shutdown. */ public final void disconnectAndShutdown(String reason) { // Disconnect from server if (this.isConnected()) { this.disconnect(reason); } this.shutdown(); } /** * Disconnects from the server and shuts down the client for good, once this * is called the client can no longer connect to servers. */ public final void disconnectAndShutdown() { this.disconnectAndShutdown("Client shutdown"); } @Override public final void finalize() { if (this.isRunning()) { this.shutdown(); } log.debug("Finalized and collected by garbage heap"); } }
package com.wizzardo.http; import com.wizzardo.epoll.readable.ReadableByteArray; import com.wizzardo.tools.misc.pool.*; import java.io.IOException; public class ReadableByteArrayPool { private static Pool<PooledReadableByteArray> pool = new PoolBuilder<PooledReadableByteArray>() .queue(PoolBuilder.createThreadLocalQueueSupplier()) .supplier(() -> new PooledReadableByteArray(new byte[10240])) .holder((pool, value) -> value.holder = new SoftHolder<>(pool, value)) .resetter(it -> it.unread((int) it.complete())) .build(); public static class PooledReadableByteArray extends ReadableByteArray { private volatile Holder<PooledReadableByteArray> holder; PooledReadableByteArray(byte[] bytes) { super(bytes); } public byte[] bytes() { return bytes; } public void length(int length) { this.length = length; } @Override public void close() throws IOException { holder.close(); } } public static PooledReadableByteArray get() { return pool.holder().get(); } }
package de.aikiit.mailversendala; import de.aikiit.mailversendala.csv.CsvParser; import de.aikiit.mailversendala.csv.Mailing; import org.apache.commons.mail.EmailException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.assertj.core.util.Strings; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; /** * Encapsulates the actual CSV parsing and mailing generation. */ public class Mailversendala { private static final Logger LOG = LogManager.getLogger(Mailversendala.class); public static MailingResult sendOut(MailConfig configuration) throws IOException { LOG.info("**** MAILVERSENDALA: Starting .... ****"); String csvPath = configuration.getCsvPath(); MailingResult result = new MailingResult(); LOG.info("Consuming CSV: {}", csvPath); if (!Strings.isNullOrEmpty(csvPath)) { LOG.info(configuration.getCsvPath()); File asFile = new File(configuration.getCsvPath()); if (asFile.exists()) { CsvParser parser = new CsvParser(new FileReader(asFile)); final List<Mailing> mailings = parser.parse(Optional.empty()); final int total = mailings.size(); LOG.info("Will send out {} mails ... hold on tight :-)", total); mailings.forEach(mailing -> { try { new SendOut(mailing).send(); result.addSuccess(); LOG.info("Successfully send out {}.mail", result.getMailCounter().orElse(new AtomicInteger(0))); } catch (EmailException e) { result.addError(); LOG.error("Problem while sending out {}", mailing, e); } }); LOG.info("**** MAILVERSENDALA-report: {} total mails ****", total); LOG.info("**** MAILVERSENDALA-report: {} successfully send out ****", result.getMailCounter().orElse(new AtomicInteger(0))); LOG.info("**** MAILVERSENDALA-report: {} errors ****", result.getErrorCounter().orElse(new AtomicInteger(0))); } else { LOG.warn("Nothing to do - please configure your CSV path properly, either as environment variable or as a runtime parameter. Example: java -Dcsvpath=foo -jar fatJar.jar"); } } LOG.info("**** MAILVERSENDALA: Application shutdown .... ****"); return result; } }
package de.braintags.vertx.util; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toList; import java.nio.charset.Charset; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; import javax.activation.MimeType; import javax.activation.MimeTypeParameterList; import javax.activation.MimeTypeParseException; import com.google.common.base.Joiner; public class HttpContentType { public static final String MAIN_TYPE_APPLICATION = "application"; public static final String MAIN_TYPE_TEXT = "text"; public static final String MAIN_TYPE_IMAGE = "image"; public static final String MAIN_TYPE_MULTIPART = "multipart"; public static final String SUB_TYPE_JSON = "json"; public static final String SUB_TYPE_JAVASCRIPT = "javascript"; public static final String SUB_TYPE_HTML = "html"; public static final String SUB_TYPE_PLAIN = "plain"; public static final String SUB_TYPE_CSS = "css"; public static final String SUB_TYPE_FORM_URL_ENCODED = "x-www-form-urlencoded"; public static final String SUB_TYPE_OCTET_STREAM = "octet-stream"; public static final String SUB_TYPE_XHTML = "xhtml+xml"; public static final String SUB_TYPE_XML = "xml"; public static final String SUB_TYPE_PNG = "png"; public static final String SUB_TYPE_SVG = "svg+xml"; public static final String SUB_TYPE_JPEG = "jpeg"; public static final String SUB_TYPE_BMP = "bmp"; public static final String SUB_TYPE_GIF = "gif"; public static final String SUB_TYPE_TIFF = "tiff"; public static final String SUB_TYPE_WEBP = "webp"; public static final String SUB_TYPE_FORM_DATA = "form-data"; public static final String SUB_TYPE_ALTERNATIE = "alternative"; private static final String PARAM_CHARSET = "charset"; public static final HttpContentType TEXT_HTML = new HttpContentType(MAIN_TYPE_TEXT, SUB_TYPE_PLAIN, ISO_8859_1); public static final HttpContentType TEXT_HTML_UTF8 = new HttpContentType(MAIN_TYPE_TEXT, SUB_TYPE_HTML, UTF_8); public static final HttpContentType TEXT_PLAIN = new HttpContentType(MAIN_TYPE_TEXT, SUB_TYPE_HTML, ISO_8859_1); public static final HttpContentType TEXT_XML = new HttpContentType(MAIN_TYPE_TEXT, SUB_TYPE_XML, ISO_8859_1); public static final HttpContentType TEXT_CSS = new HttpContentType(MAIN_TYPE_TEXT, SUB_TYPE_CSS); public static final HttpContentType APPLICATION_JAVASCRIPT = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_JAVASCRIPT); public static final HttpContentType APPLICATION_FORM_URLENCODED = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_FORM_URL_ENCODED, ISO_8859_1); public static final HttpContentType APPLICATION_OCTET_STREAM = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_OCTET_STREAM, ISO_8859_1); public static final HttpContentType APPLICATION_SVG_XML = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_SVG, ISO_8859_1); public static final HttpContentType APPLICATION_XHTML_XML = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_XHTML, ISO_8859_1); public static final HttpContentType APPLICATION_XML = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_XML, ISO_8859_1); public static final HttpContentType APPLICATION_JSON = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_JSON, UTF_8); public static final HttpContentType IMAGE_PNG = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_PNG); public static final HttpContentType IMAGE_SVG = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_SVG); public static final HttpContentType IMAGE_JPEG = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_JPEG); public static final HttpContentType IMAGE_BMP = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_BMP); public static final HttpContentType IMAGE_GIF = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_GIF); public static final HttpContentType IMAGE_WEBP = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_WEBP); public static final HttpContentType IMAGE_TIFF = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_TIFF); public static final HttpContentType MULTIPART_ALTERNATIVE = new HttpContentType(MAIN_TYPE_MULTIPART, SUB_TYPE_JPEG, ISO_8859_1); public static final HttpContentType MULTIPART_FORM_DATA = new HttpContentType(MAIN_TYPE_MULTIPART, SUB_TYPE_JPEG, ISO_8859_1); private final String value; private final String mainType; private final String subType; private final Map<String, String> parameters; private final String mimeType; public static HttpContentType parse(final String string) { try { MimeType mimeType = new MimeType(string); return new HttpContentType(mimeType.getPrimaryType(), mimeType.getSubType(), toMap(mimeType.getParameters())); } catch (MimeTypeParseException e) { throw new IllegalArgumentException("unable to parse_ " + string, e); } } private static Map<String, String> toMap(final MimeTypeParameterList parameters) { LinkedHashMap<String, String> result = new LinkedHashMap<>(); @SuppressWarnings("rawtypes") Enumeration names = parameters.getNames(); while (names.hasMoreElements()) { String name = names.nextElement().toString(); result.put(name, parameters.get(name)); } return result; } private HttpContentType(final String mainType, final String subType, final Charset charset) { this(mainType, subType, Collections.singletonMap(PARAM_CHARSET, charset.name().toLowerCase())); } public HttpContentType(final String mainType, final String subType) { this(mainType, subType, Collections.emptyMap()); } public HttpContentType(final String mainType, final String subType, final Map<String, String> parameters) { this.mainType = mainType; this.subType = subType; this.parameters = parameters; mimeType = mainType + "/" + subType; this.value = mimeType + (parameters.isEmpty() ? "" : ";" + Joiner.on(';').join( parameters.entrySet().stream().map(param -> param.getKey() + "=" + param.getValue()).collect(toList()))); } @Override public String toString() { return value; } public String getMimeType() { return mimeType; } public String getValue() { return value; } public String getMainType() { return mainType; } public String getSubType() { return subType; } public Map<String, String> getParameters() { return parameters; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((mainType == null) ? 0 : mainType.hashCode()); result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); result = prime * result + ((subType == null) ? 0 : subType.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HttpContentType other = (HttpContentType) obj; if (mainType == null) { if (other.mainType != null) return false; } else if (!mainType.equals(other.mainType)) return false; if (parameters == null) { if (other.parameters != null) return false; } else if (!parameters.equals(other.parameters)) return false; if (subType == null) { if (other.subType != null) return false; } else if (!subType.equals(other.subType)) return false; return true; } }
package de.htw_berlin.HoboOthello.Core; public class GameRule { private Field[][] fields; /** * Default Constructor * * @param fields the gameboard fields */ public GameRule(Field[][] fields) { this.fields = fields; } /** * Method which switches the boolean possibleMove for all fields which are a * possible option for the current Player to true * * @param playerColor Color.BLACK or Color.WHITE * @return fields where PossibleMove is set right */ public void changeAllPossibleFieldsToTrue(Color playerColor) { for (int x = 0; x < this.fields.length; x++) { for (int y = 0; y < this.fields.length; y++) { this.fields[x][y].setPossibleMove(isMoveAllowed(this.fields[x][y], playerColor)); } } } /** * Check if the field in fields[x][y] is a possible move for the current Player (which is defined by it's Color) * * @param field a single Field * @param color Color.BLACK or Color.WHITE * @return true == the move is possible for this color * false == the move is not possible for this color */ public boolean isMoveAllowed(Field field, Color color) { return move(field, color, false); } /** * Set the move in field in fields[x][y] and flip every Stone which is now owned by * this Player * * @param field a single Field * @param color Color.BLACK or Color.WHITE * @return true == the move is possible for this color * false == the move is not possible for this color */ public boolean setMove(Field field, Color color) { return move(field, color, true); } /** * The Method for setMove && isMoveAllowed which do the work. * * @param field single Field * @param color Color.BLACK or Color.WHITE * @param flipStones true --> will flip every stone which will now owned by other Player * false --> just return if this field could be use for a possible turn * @return true == the move is possible for this color * false == the move is not possible for this color */ private boolean move(Field field, Color color, boolean flipStones) { if (field.isOccupiedByStone()) { return false; } // if there is a possible field, set it to true boolean possibleField = false; // set the direction vectors for methods flipStones && isPossibleField for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if (x != 0 | y != 0) { if (isPossibleField(field, color, x, y, 0)) { if (flipStones) { flipStones(field, color, x, y); possibleField = true; } else { // if this method called from isMoveAllowed than return true and break this loop return true; } } } } } return possibleField; } /** * Flip every Stone on this.fields wich is now owned by the currentPlayer, for setTurn * * @param field single Field * @param color Color.BLACK or Color.WHITE * @param x_Direction the direction on the x-axis * @param y_Direction the direction on the y-axis */ private void flipStones(Field field, Color color, int x_Direction, int y_Direction) { do { int x = field.getX() + x_Direction; int y = field.getY() + y_Direction; field = this.fields[x][y]; field.getStone().setColor(color); } while (field.getStone().getColor() != color); } /** * Method for isMoveAllowed, which check recursively if this move is possible for this direction * * @param field single Field * @param color Color.BLACK or Color.WHITE * @param x_Direction the direction on the x-axis * @param y_Direction the direction on the y-axis * @param counter how many stones are between from the start stone and the current stone * @return true == the move is possible for this color * false == the move is not possible for this color */ private boolean isPossibleField(Field field, Color color, int x_Direction, int y_Direction, int counter) { int x = field.getX() + x_Direction; int y = field.getY() + y_Direction; field = this.fields[x][y]; if (x >= 0 && y >= 0 && x < this.fields.length && y < this.fields.length) { if (field.isEmpty()) { return false; } if (field.getStone().getColor() == color && counter > 0) { return true; } if (field.getStone().getColor() != color) { counter++; return isPossibleField(field, color, x_Direction, y_Direction, counter); } } return false; } public Field[][] getFields() { return fields; } public int getPossibleMoves() { int countPossibleMoves = 0; for (int i = 0; i < this.fields.length; i++) { for (int j = 0; j < this.fields.length; j++) { if (this.fields[i][j].isPossibleMove()) { countPossibleMoves++; } } } return countPossibleMoves; } }
package eu.freme.broker.security; import java.io.IOException; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.vote.AffirmativeBased; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.ProviderNotFoundException; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import eu.freme.broker.security.database.User; import eu.freme.broker.security.database.UserRepository; import eu.freme.broker.security.tools.AccessLevelHelper; import eu.freme.broker.security.tools.PasswordHasher; import eu.freme.broker.security.voter.UserAccessDecisionVoter; /** * @author Jan Nehring - jan.nehring@dfki.de */ @Configuration @EnableWebMvcSecurity @EnableScheduling @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter implements ApplicationContextAware { Logger logger = Logger.getLogger(SecurityConfig.class); @Autowired UserRepository userRepository; @Value("${admin.username}") private String adminUsername; @Value("${admin.password}") private String adminPassword; @PostConstruct public void init() { // create or promote admin user if it does not exist if( adminUsername != null){ createAdminUser(); } } private void createAdminUser(){ User admin = userRepository.findOneByName(adminUsername); if (admin == null) { logger.info("create new admin user"); String saltedHashedPassword; try { saltedHashedPassword = PasswordHasher .getSaltedHash(adminPassword); } catch (Exception e) { logger.error(e); return; } admin = new User(adminUsername, saltedHashedPassword, User.roleAdmin); userRepository.save(admin); } else if (!admin.getRole().equals(User.roleAdmin)) { logger.info("promote user and change password"); admin.setRole(User.roleAdmin); String saltedHashedPassword; try { saltedHashedPassword = PasswordHasher .getSaltedHash(adminPassword); } catch (Exception e) { logger.error(e); return; } admin.setPassword(saltedHashedPassword); userRepository.save(admin); } } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .exceptionHandling() .authenticationEntryPoint(unauthorizedEntryPoint()); http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class).addFilterBefore( new ManagementEndpointAuthenticationFilter( authenticationManager()), BasicAuthenticationFilter.class); } @Bean public AuthenticationManager authenticationManager() { return new AuthenticationManager() { @Autowired AuthenticationProvider[] authenticationProviders; @Override public Authentication authenticate(Authentication authentication) throws ProviderNotFoundException { for (AuthenticationProvider auth : authenticationProviders) { if (auth.supports(authentication.getClass())) { return auth.authenticate(authentication); } } throw new ProviderNotFoundException( "No AuthenticationProvider found for " + authentication.getClass()); } }; } @Bean public TokenService tokenService() { return new TokenService(); } @Bean public AuthenticationProvider databaseAuthenticationProvider() { return new DatabaseAuthenticationProvider(); } @Bean public AuthenticationProvider tokenAuthenticationProvider() { return new TokenAuthenticationProvider(tokenService()); } @Bean public AuthenticationEntryPoint unauthorizedEntryPoint() { return new AuthenticationEntryPoint() { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } }; } @Bean public AffirmativeBased defaultAccessDecisionManager() { @SuppressWarnings("rawtypes") ArrayList<AccessDecisionVoter> list = new ArrayList<AccessDecisionVoter>(); list.add(new UserAccessDecisionVoter()); AffirmativeBased ab = new AffirmativeBased(list); return ab; } @Bean public AccessLevelHelper accessLevelHelper() { return new AccessLevelHelper(); } }
package eu.over9000.skadi.handler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import javafx.collections.ListChangeListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.over9000.skadi.model.Channel; import eu.over9000.skadi.model.StateContainer; import eu.over9000.skadi.model.StreamQuality; public class StreamHandler { private static final Logger LOGGER = LoggerFactory.getLogger(StreamHandler.class); private final Map<Channel, StreamProcessHandler> handlers = new HashMap<>(); public StreamHandler(final ChannelHandler channelHandler) { channelHandler.getChannels().addListener((final ListChangeListener.Change<? extends Channel> c) -> { while (c.next()) { if (c.wasRemoved()) { c.getRemoved().stream().filter(this.handlers::containsKey).forEach(channel -> { final StreamProcessHandler sph = this.handlers.remove(channel); sph.closeStream(); }); } } }); } public void openStream(final Channel channel, final StreamQuality quality) { if (this.handlers.containsKey(channel)) { return; } try { final StreamProcessHandler cph = new StreamProcessHandler(channel, quality); this.handlers.put(channel, cph); } catch (final IOException e) { LOGGER.error("exception opening stream", e); } } public void closeStream(final Channel channel) { final StreamProcessHandler sph = this.handlers.remove(channel); if (sph != null) { sph.closeStream(); } } public boolean isOpen(final Channel channel) { return this.handlers.containsKey(channel); } public void onShutdown() { this.handlers.values().forEach(StreamHandler.StreamProcessHandler::closeStream); } private class StreamProcessHandler implements Runnable { private final Process process; private final Channel channel; private final Thread thread; private StreamProcessHandler(final Channel channel, final StreamQuality quality) throws IOException { this.thread = new Thread(this); this.channel = channel; this.thread.setName("StreamHandler Thread for " + channel.getName()); String videoplayerExec = StateContainer.getInstance().getExecutableVideoplayer(); String livestreamerExec = StateContainer.getInstance().getExecutableLivestreamer(); this.process = new ProcessBuilder(livestreamerExec, channel.buildURL(), quality.getQuality(), "-p " + videoplayerExec).redirectErrorStream(true).start(); this.thread.start(); } @Override public void run() { try { final BufferedReader br = new BufferedReader(new InputStreamReader(this.process.getInputStream())); String line; while ((line = br.readLine()) != null) { LOGGER.debug("LIVESTREAMER/VIDEOPLAYER: " + line); } this.process.waitFor(); } catch (final InterruptedException | IOException e) { LOGGER.error("Exception handling stream process", e); } StreamHandler.this.handlers.remove(this.channel); } public void closeStream() { this.process.destroy(); } } }
package fi.csc.microarray.client; import java.awt.Color; 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.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import org.jdesktop.swingx.JXHyperlink; import fi.csc.microarray.constants.VisualConstants; import fi.csc.microarray.module.Module; import fi.csc.microarray.util.Strings; @SuppressWarnings("serial") public class QuickLinkPanel extends JPanel { private SwingClientApplication application; private JXHyperlink sessionLink; private JXHyperlink importLink; private JXHyperlink exampleLink; private JXHyperlink exampleLinkAlternative; private JXHyperlink importFolderLink; private JXHyperlink importURLLink; private static final String LINK_WORD = "***"; public QuickLinkPanel() { super(new GridBagLayout()); application = (SwingClientApplication) Session.getSession().getApplication(); this.setBackground(Color.white); // Prepare all available links // Check if example session is available exampleLink = null; exampleLinkAlternative = null; try { final URL[] urls = Session.getSession().getPrimaryModule().getExampleSessionUrls(application.isStandalone); if (urls != null) { if (urls.length == 1) { exampleLink = createLink("Example session ", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { application.loadSessionFrom(urls[0]); } catch (Exception exception) { application.reportException(exception); } } }); } if (urls.length == 2) { exampleLink = createLink("Microarray", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { application.loadSessionFrom(urls[0]); } catch (Exception exception) { application.reportException(exception); } } }); exampleLinkAlternative = createLink("NGS", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { application.loadSessionFrom(urls[1]); } catch (Exception exception) { application.reportException(exception); } } }); } } } catch (MalformedURLException mue) { // ignore and let exampleLink be null } importLink = createLink("Import files ", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { application.openFileImport(); } catch (Exception exception) { application.reportException(exception); } } }); importFolderLink = createLink("Import folder ", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { application.openDirectoryImportDialog(); } }); importURLLink = createLink("Import from URL ", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { application.openURLImport(); } catch (Exception exception) { application.reportException(exception); } } }); sessionLink = createLink("Open session ", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { application.loadSession(); } }); // Draw panel GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.NORTHWEST; c.insets.set(5, 10, 5, 10); c.gridwidth = 2; this.add(new JLabel("To start working with " + Session.getSession().getPrimaryModule().getDisplayName() + ", you need to load in data first:"), c); c.gridwidth = 1; c.gridy++; c.insets.set(0, 10, 0, 0); if (exampleLink != null) { if (exampleLinkAlternative == null) { exampleLink.setText("Open example session "); addLink("*** to get familiar with " + Session.getSession().getPrimaryModule().getDisplayName() + ". " , exampleLink, VisualConstants.EXAMPLE_SESSION_ICON, c); } else { List<JXHyperlink> exampleLinks = new LinkedList<JXHyperlink>(); exampleLinks.add(exampleLink); exampleLinks.add(exampleLinkAlternative); addLinks("Open example session ( *** or *** ) to get familiar with " + Session.getSession().getPrimaryModule().getDisplayName() + ". ", exampleLinks, VisualConstants.EXAMPLE_SESSION_ICON, c); } } addLink("*** to continue working on previous sessions.", sessionLink, VisualConstants.OPEN_SESSION_LINK_ICON, c); // common links List<JXHyperlink> importLinks = new LinkedList<JXHyperlink>(); importLinks.add(importLink); importLinks.add(importFolderLink); importLinks.add(importURLLink); // module specific links if (!application.isStandalone) { Module primaryModule = Session.getSession().getPrimaryModule(); primaryModule.addImportLinks(this, importLinks); } String linkTemplate = Strings.repeat("\n *** ", importLinks.size()); addLinks("Import new data to " + Session.getSession().getPrimaryModule().getDisplayName() + ": " + linkTemplate, importLinks, VisualConstants.IMPORT_LINK_ICON, c); // Panels to take rest of space JPanel bottomPanel = new JPanel(); JPanel rightPanel = new JPanel(); bottomPanel.setBackground(Color.white); rightPanel.setBackground(Color.white); c.weightx = 0.0; c.weighty = 1.0; c.fill = GridBagConstraints.VERTICAL; c.gridx = 0; c.gridy++; this.add(bottomPanel, c); c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 3; c.gridy = 0; this.add(rightPanel, c); this.setMinimumSize(new Dimension(0, 0)); this.setPreferredSize(new Dimension(VisualConstants.LEFT_PANEL_WIDTH, VisualConstants.TREE_PANEL_HEIGHT)); } private void addLink(String description, JXHyperlink link, ImageIcon icon, GridBagConstraints c) { List<JXHyperlink> list = new LinkedList<JXHyperlink>(); list.add(link); addLinks(description, list, icon, c); } private void addLinks(String description, List<JXHyperlink> links, ImageIcon icon, GridBagConstraints c) { String[] words = description.split(" "); int rowChars = 0; final int MAX_ROW_CHARS = 42; Iterator<JXHyperlink> linkIterator = links.iterator(); int rowCount = 0; c.gridx = 1; c.insets.top = 10; JPanel row = null; for (int i = 0; i < words.length; i++) { if (row == null || rowChars + words[i].length() > MAX_ROW_CHARS || words[i].equals("\n")) { FlowLayout flow = new FlowLayout(FlowLayout.LEADING); flow.setVgap(0); flow.setHgap(0); row = new JPanel(flow); row.setBackground(Color.white); c.gridy++; this.add(row, c); c.insets.top = 0; // After first row rowChars = 0; rowCount++; } if (words[i].equals(LINK_WORD)) { JXHyperlink link = linkIterator.next(); rowChars += link.getText().length() + 1; row.add(link); // row.add(new JLabel(link.getText())); } else if (!words[i].equals("\n")) { JLabel text = new JLabel(words[i] + " "); row.add(text); rowChars += words[i].length() + 1; } } c.gridy -= (rowCount - 1); c.gridheight = rowCount; c.gridx = 0; c.insets.top = 15; this.add(new JLabel(icon), c); c.gridy += (rowCount - 1); c.gridheight = 1; } public JXHyperlink createLink(String text, Action action) { JXHyperlink link = new JXHyperlink(); link.setBorder(null); link.setMargin(new Insets(0, 0, 0, 0)); link.setAction(action); link.setText(text); // must be after setAction return link; } }
package fi.csc.microarray.databeans; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.swing.Icon; import org.apache.log4j.Logger; import org.mortbay.util.IO; import fi.csc.microarray.client.ClientApplication; import fi.csc.microarray.client.operation.OperationRecord; import fi.csc.microarray.client.session.SessionLoader; import fi.csc.microarray.client.session.SessionSaver; import fi.csc.microarray.databeans.DataBean.Link; import fi.csc.microarray.databeans.DataBean.StorageMethod; import fi.csc.microarray.databeans.features.Feature; import fi.csc.microarray.databeans.features.FeatureProvider; import fi.csc.microarray.databeans.features.Modifier; import fi.csc.microarray.databeans.handlers.LocalFileDataBeanHandler; import fi.csc.microarray.databeans.handlers.ZipDataBeanHandler; import fi.csc.microarray.exception.MicroarrayException; import fi.csc.microarray.util.IOUtils; import fi.csc.microarray.util.Strings; public class DataManager { private static final String TEMP_DIR_PREFIX = "chipster"; private static final int MAX_FILENAME_LENGTH = 256; private static final Logger logger = Logger.getLogger(DataManager.class); /** * Reports session validation related problems. */ public static class ValidationException extends Exception { public ValidationException(String validationDetails) { // TODO Auto-generated constructor stub } } /** * The initial name for the root folder. */ public final static String ROOT_NAME = "Datasets"; private Map<String, FeatureProvider> factories = new HashMap<String, FeatureProvider>(); private Map<String, Modifier> modifiers = new HashMap<String, Modifier>(); /** MIME types for the DataBeans */ private Map<String, ContentType> contentTypes = new HashMap<String, ContentType>(); /** Mapping file extensions to content types */ private Map<String, String> extensionMap = new HashMap<String, String>(); private HashMap<String, TypeTag> tagMap = new HashMap<String, TypeTag>(); private LinkedList<DataChangeListener> listeners = new LinkedList<DataChangeListener>(); private boolean eventsEnabled = false; private DataFolder rootFolder; private File repositoryRoot; private ZipDataBeanHandler zipDataBeanHandler = new ZipDataBeanHandler(this); private LocalFileDataBeanHandler localFileDataBeanHandler = new LocalFileDataBeanHandler(this); public DataManager() throws IOException { rootFolder = createFolder(DataManager.ROOT_NAME); // initialize repository repositoryRoot = createRepository(); } public void setRootFolder(DataFolder folder) { this.rootFolder = folder; } public File getRepository() { return repositoryRoot; } /** * Returns the root folder, acting as a gateway into the actual data * content under this manager. */ public DataFolder getRootFolder() { return rootFolder; } public boolean isRootFolder(DataFolder folder) { return (rootFolder == folder) && (rootFolder != null); } /** * Creates a folder under this manager. Folder will be created without parent. * * @param name name for the new folder */ public DataFolder createFolder(String name) { DataFolder folder = new DataFolder(this, name); return folder; } /** * Creates a folder under this manager. * * @param parent under which folder the new folder is to be created * @param name name for the new folder */ public DataFolder createFolder(DataFolder root, String name) { DataFolder folder = new DataFolder(this, name); root.addChild(folder); // events are dispatched from here return folder; } /** * Adds a listener listening to changes in beans and folders of this manager. */ public void addDataChangeListener(DataChangeListener listener) { logger.debug("adding DataChangeListener: " + listener); if (listener == null) { throw new IllegalArgumentException("listener cannot be null"); } listeners.add(listener); } public synchronized File createNewRepositoryFile(String beanName) throws IOException { // FIXME check the file name String fileName = beanName.replaceAll("[^\\wöäåÖÄÅ\\\\.]", ""); if (fileName.length() < 1) { fileName = "data"; } else if (fileName.length() > MAX_FILENAME_LENGTH) { fileName = fileName.substring(0, MAX_FILENAME_LENGTH); } File file = new File(this.repositoryRoot, fileName); // if file with the beanName already exists, add running number to the name for (int i = 1; file.exists() && i < Integer.MAX_VALUE; i++) { file = new File(this.repositoryRoot, fileName + "-" + i); } // create the file if (!file.createNewFile()) { throw new IOException("Could not create file " + fileName); } // return the file file.deleteOnExit(); return file; } private File createRepository() throws IOException { // get temp dir File tempRoot = getTempRoot(); if (!tempRoot.canWrite()) { // give up throw new IOException("Could not create repository directory."); } String fileName = TEMP_DIR_PREFIX; File repository = new File(tempRoot, fileName); // if directory with that name already exists, add running number boolean repositoryCreated = false; for (int i = 1; !repositoryCreated && i < 1000; i++) { repositoryCreated = repository.mkdir(); if (!repositoryCreated) { repository = new File(tempRoot, fileName + "-" + i); } } if (!repositoryCreated) { throw new IOException("Could not create repository directory."); } repository.deleteOnExit(); return repository; } private File getTempRoot() { File tempDir = new File(System.getProperty("java.io.tmpdir")); // check if temp dir is writeable if (!tempDir.canWrite()) { // try home dir tempDir = new File(System.getProperty("user.home")); if (!tempDir.canWrite()) { // try current working dir tempDir = new File(System.getProperty("user.dir")); } } return tempDir; } /** * @param enabled if property change events should be sent * @see #addDataChangeListener(DataChangeListener) */ public void setEventsEnabled(boolean enabled) { this.eventsEnabled = enabled; } public void dispatchEventIfVisible(DataChangeEvent event) { if (event.getDataItem().getParent() != null) { dispatchEvent(event); } } public void dispatchEvent(DataChangeEvent event) { if (eventsEnabled) { // dispatch events only for connected datas for (DataChangeListener listener : listeners) { if (listener == null) { logger.error("One of the DataChangeListeners listeners was null."); } else { logger.debug("Notifying DataChangeListener " + listener.toString()); } try { listener.dataChanged(event); } catch (RuntimeException e) { // we will not let GUI problems to stop important DataBean manipulation operations // and possibly lead to DataBean model corruption logger.error("DataChangeEvent dispatch failed", e); } } } } public static DataBean[] wrapSource(DataBean source) { DataBean[] sources = null; if (source != null) { sources = new DataBean[1]; sources[0] = source; } else { sources = new DataBean[0]; } return sources; } /** * Guess the MIME content type using the filename. * * For now, simply use the extension to figure out the mime type. * * Types are plugged at ApplicationConstants. * */ public ContentType guessContentType(String name) { ContentType type = null; if(name.lastIndexOf(".") != -1){ String extension = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase(); String typeName = extensionMap.get(extension); if (typeName != null) { type = contentTypes.get(typeName); } } if (type == null) { type = contentTypes.get("application/octet-stream"); } return type; } /** * Guesses MIME content type from a filename and possibly file content. */ public ContentType guessContentType(File file) { return guessContentType(file.getName()); } /** * @return MIME content type for a given extension */ public ContentType getContentType(String typeName) { return contentTypes.get(typeName); } /** * Plugs a MIME content type, so that it can be used in all beans under this manager. * * @param mimeType MIME name * @param supported is this a known (supported directly) content type? * @param description a short textual description * @param extensions file extensions belonging to this type */ public void plugContentType(String mimeType, boolean supported, boolean binary, String description, Icon icon, String... extensions) { // create the content type contentTypes.put(mimeType, new ContentType(mimeType, supported, binary, description, icon, extensions)); // add extensions to search map for (String extension: extensions) { extensionMap.put(extension, mimeType); } } /** * Plugs a modifier (part of Feature API), so that it can be used in all beans under this manager. */ public void plugModifier(String name, Modifier modifier) { modifiers.put(name, modifier); } /** * Plugs a feature factory, so that it can be used in all beans under this manager. */ public void plugFeatureFactory(String name, FeatureProvider plugin) { logger.debug("plugged " + plugin.getClass().getSimpleName() + " at " + name); plugin.setName(name); factories.put(name, plugin); } public Modifier fetchModifier(String modifierName) { return modifiers.get(modifierName); } public Feature fetchFeature(String featureName, DataBean bean) { String bestMatch = null; for (String feature : factories.keySet()) { if (featureName.startsWith(feature)) { if (bestMatch == null || feature.length() > bestMatch.length()) { // current best match bestMatch = feature; } } } FeatureProvider factory = factories.get(bestMatch); if (factory == null) { throw new RuntimeException("no feature factory plugged in for \"" + featureName + "\" (total of " + factories.size() + " factories plugged)"); } logger.debug("best match for " + featureName + " was " + (factory != null ? factory.getName() : factory)); String namePostfix = getNamePostfix(featureName, factory.getName()); return factory.createFeature(namePostfix, bean); } /** * Find and return the first DataItem with the given name. * @param name the name of the DataItem being search for * @return the first found DataItem with given name */ public DataItem findDataItem(String name) { return findDataItem(name, getRootFolder()); } private DataItem findDataItem(String name, DataItem root) { DataItem matchingItem = null; // root item matches if (root.getName().equals(name)) { return root; } // root is a folder, search children else if (root instanceof DataFolder) { for (DataItem child: ((DataFolder)root).getChildren()) { matchingItem = findDataItem(name, child); if (matchingItem != null) { return matchingItem; } } } // no match found return null; } /** * Find and return the first DataBean with the given name. * @param name the name of the DataBean being search for * @return the first found DataBean with given name */ public DataBean getDataBean(String name) { for (DataBean dataBean : databeans()) { if (dataBean.getName().equals(name)) { return dataBean; } } return null; } /** * Create a local temporary file DataBean without content, without a parent folder and without sources. * If a reference to this bean is lost it can not be accessed any more. */ public DataBean createDataBean(String name) throws MicroarrayException { File contentFile; try { contentFile = createNewRepositoryFile(name); } catch (IOException e) { throw new MicroarrayException(e); } return createDataBean(name, StorageMethod.LOCAL_TEMP, null, new DataBean[] {}, contentFile); } /** * Create a local temporary file DataBean with content, without a parent * folder and without sources. If a reference to this bean * is lost it can not be accessed any more. */ public DataBean createDataBean(String name, InputStream content) throws MicroarrayException { return createDataBean(name, content, null, new DataBean[] {}); } /** * Create a local file DataBean. * The file is used directly, the contents are not copied anywhere. * */ public DataBean createDataBean(String name, File contentFile) throws MicroarrayException { return createDataBean(name, StorageMethod.LOCAL_USER, null, new DataBean[] {}, contentFile); } /** * For now, only file URLs are supported. * */ public DataBean createDataBean(String name, URL url) throws MicroarrayException { File contentFile; try { contentFile = new File(url.toURI()); } catch (Exception e) { throw new IllegalArgumentException("Could not convert " + url + " to a file"); } return createDataBean(name, StorageMethod.LOCAL_USER, null, new DataBean[] {}, contentFile); } /** * Create a zip file DataBean. Bean contents are already in the zipFile and can * be found using the zipEntryName. * * @param name * @param zipFile * @param zipEntryName * @return * @throws MicroarrayException */ public DataBean createDataBean(String name, File zipFile, String zipEntryName) throws MicroarrayException { URL url; try { url = new URL(zipFile.toURI().toURL(), "#" + zipEntryName); } catch (MalformedURLException e) { throw new MicroarrayException(e); } DataBean dataBean = new DataBean(name, StorageMethod.LOCAL_SESSION, "", url, guessContentType(name), new Date(), new DataBean[] {}, null, this, zipDataBeanHandler); dispatchEventIfVisible(new DataItemCreatedEvent(dataBean)); return dataBean; } /** * Create a zip file DataBean. Bean contents are already in the zipFile. * * @param name * @param url location of the zip file, zip entry name as the fragment * @return * @throws MicroarrayException */ public DataBean createDataBeanFromZip(String name, URL url) throws MicroarrayException { DataBean dataBean = new DataBean(name, StorageMethod.LOCAL_SESSION, "", url, guessContentType(name), new Date(), new DataBean[] {}, null, this, zipDataBeanHandler); dispatchEventIfVisible(new DataItemCreatedEvent(dataBean)); return dataBean; } /** * Create a local temporary file DataBean with content, with a parent folder and with sources. */ private DataBean createDataBean(String name, InputStream content, DataFolder folder, DataBean... sources) throws MicroarrayException { // copy the data from the input stream to the file in repository File contentFile; try { contentFile = createNewRepositoryFile(name); InputStream input = new BufferedInputStream(content); OutputStream output = new BufferedOutputStream(new FileOutputStream(contentFile)); IO.copy(input, output); input.close(); output.flush(); output.close(); } catch (IOException ioe) { throw new MicroarrayException(ioe); } // create and return the bean DataBean bean = createDataBean(name, StorageMethod.LOCAL_TEMP, folder, sources, contentFile); return bean; } /** * The file is used directly, the contents are not copied anywhere. * */ private DataBean createDataBean(String name, StorageMethod type, DataFolder folder, DataBean[] sources, File contentFile) throws MicroarrayException { URL url; try { url = contentFile.toURI().toURL(); } catch (MalformedURLException e) { throw new MicroarrayException(e); } DataBean dataBean = new DataBean(name, type, "", url, guessContentType(name), new Date(), sources, folder, this, localFileDataBeanHandler); dispatchEventIfVisible(new DataItemCreatedEvent(dataBean)); return dataBean; } /** * Load session from a file. * * @see #saveSession(File, ClientApplication) */ public void loadSession(File sessionFile, boolean restoreData) throws Exception { SessionLoader sessionLoader = new SessionLoader(sessionFile, restoreData, this); sessionLoader.loadSession(); } /** * Saves session (all data: beans, folder structure, operation metadata, links etc.) to a file. * File is a zip file with all the data files and one metadata file. * * @return true if the session was saved perfectly * @throws Exception */ public void saveSession(File sessionFile) throws Exception { // save session file boolean metadataValid = false; SessionSaver sessionSaver = new SessionSaver(sessionFile, this); metadataValid = sessionSaver.saveSession(); // check validation if (!metadataValid) { // save was successful but metadata validation failed, file might be usable String validationDetails = sessionSaver.getValidationErrors(); throw new ValidationException(validationDetails); } } /** * Saves lightweight session (folder structure, operation metadata, links etc.) to a file. * Does not save actual data inside databeans. * * @return true if the session was saved perfectly * @throws Exception */ public void saveLightweightSession(File sessionFile) throws Exception { SessionSaver sessionSaver = new SessionSaver(sessionFile, this); sessionSaver.saveLightweightSession(); } /** * Delete DataItem and its children (if any). Root folder cannot be removed. * * @param data item to be deleted */ public void delete(DataItem data) { if (data instanceof DataFolder) { deleteDataFolder((DataFolder)data); } else { deleteDataBean((DataBean)data); } } /** * Remove all DataBeans and DataFolders, except for the root folder. */ public void deleteAllDataItems() { deleteDataFolder(getRootFolder()); } private void deleteDataBean(DataBean bean) { // remove from operation history for (DataBean source : databeans()) { // we must iterate all datas because links cannot be trusted (they might have been removed by user) OperationRecord operationRecord = source.getOperationRecord(); if (operationRecord != null) { operationRecord.removeInput(bean); } } // remove links for (Link linkType : Link.values()) { // Remove outgoing links for (DataBean target : bean.getLinkTargets(linkType)) { bean.removeLink(linkType, target); } // Remove incoming links for (DataBean source : bean.getLinkSources(linkType)) { source.removeLink(linkType, bean); } } // remove bean DataFolder folder = bean.getParent(); if (folder != null) { folder.removeChild(bean); } // remove physical file bean.delete(); } /** * Return all DataBeans under this manager. */ public List<DataBean> databeans() { LinkedList<DataBean> databeans = new LinkedList<DataBean>(); for (DataFolder folder : folders()) { for (DataItem child : folder.getChildren()) { if (child instanceof DataBean) { databeans.add((DataBean) child); } } } return databeans; } /** * Return all DataFolders under this manager. */ public List<DataFolder> folders() { return folders(getRootFolder()); } public List<DataFolder> folders(DataFolder parent) { LinkedList<DataFolder> folders = new LinkedList<DataFolder>(); folders.add(parent); for (DataItem child : parent.getChildren()) { if (child instanceof DataFolder) { folders.addAll(folders((DataFolder) child)); } } return folders; } /** * FIXME add locking * * @param bean * @return * @throws IOException */ public OutputStream getContentOutputStreamAndLockDataBean(DataBean bean) throws IOException { bean.setContentChanged(true); // Only local temp beans support output, so convert to local temp bean if needed if (!bean.getStorageMethod().equals(StorageMethod.LOCAL_TEMP)) { this.convertToLocalTempDataBean(bean); } return bean.getHandler().getOutputStream(bean); } /** * FIXME locks * * @param bean * @param out * @throws MicroarrayException * @throws IOException */ public void closeContentOutputStreamAndUnlockDataBean(DataBean bean, OutputStream out) throws MicroarrayException, IOException { try { out.close(); } finally { // this.lock.writeLock().unlock(); } ContentChangedEvent cce = new ContentChangedEvent(bean); this.dispatchEventIfVisible(cce); } public File getLocalFile(DataBean bean) throws IOException { // convert non local file beans to local file beans if (!(bean.getHandler() instanceof LocalFileDataBeanHandler)) { this.convertToLocalTempDataBean(bean); } // get the file LocalFileDataBeanHandler handler = (LocalFileDataBeanHandler) bean.getHandler(); return handler.getFile(bean); } private void convertToLocalTempDataBean(DataBean bean) throws IOException { // FIXME lock bean // TODO think about that name // copy contents to new file File newFile = this.createNewRepositoryFile(bean.getName()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile)); BufferedInputStream in = new BufferedInputStream(bean.getContentByteStream()); try { IOUtils.copy(in, out); } finally { IOUtils.closeIfPossible(in); IOUtils.closeIfPossible(out); } // update url, type and handler in the bean URL newURL = newFile.toURI().toURL(); bean.setContentUrl(newURL); bean.setStorageMethod(StorageMethod.LOCAL_TEMP); bean.setHandler(localFileDataBeanHandler); bean.setContentChanged(true); } private void deleteDataFolder(DataFolder folder) { // remove children Iterable<DataItem> children = folder.getChildren(); // make a copy of the children list to avoid concurrent modification List<DataItem> childrenToBeRemoved = new LinkedList<DataItem>(); for (DataItem item : children) { childrenToBeRemoved.add(item); } // remove all children (recursively) for (DataItem item : childrenToBeRemoved) { delete(item); } // remove this folder (unless root) DataFolder parent = folder.getParent(); if (parent != null) { parent.removeChild(folder); } } private String getNamePostfix(String featureName, String factoryName) { if (factoryName.length() > featureName.length()) { return ""; } else { String npf = featureName.substring(factoryName.length()); if (npf.startsWith("/")) { return npf.substring(1); } else { return npf; } } } public void plugTypeTag(TypeTag typeTag) { this.tagMap.put(typeTag.getName(), typeTag); } public TypeTag getTypeTag(String name) { return this.tagMap.get(name); } public Iterable<File> listAllRepositories() { LinkedList<File> repositories = new LinkedList<File>(); File tempRoot = getTempRoot(); for (File file: tempRoot.listFiles()) { if (file.isDirectory() && file.getName().startsWith(TEMP_DIR_PREFIX)) { String postfix = file.getName().substring(TEMP_DIR_PREFIX.length()); if ("".equals(postfix) || Strings.isIntegerNumber(postfix)) { repositories.add(file); } } } return repositories; } public void flushSession() { zipDataBeanHandler.closeZipFiles(); } }
package fr.liglab.lcm.mapred; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Reducer; import fr.liglab.lcm.mapred.writables.ItemAndSupportWritable; import fr.liglab.lcm.mapred.writables.SupportAndTransactionWritable; import gnu.trove.map.TIntIntMap; public class AggregationReducer extends Reducer<ItemAndSupportWritable, SupportAndTransactionWritable, IntWritable, SupportAndTransactionWritable> { protected final IntWritable keyW = new IntWritable(); protected final SupportAndTransactionWritable valueW = new SupportAndTransactionWritable(); protected TIntIntMap reverseBase = null; protected int k; @Override protected void setup(Context context) throws java.io.IOException, InterruptedException { if (this.reverseBase == null) { Configuration conf = context.getConfiguration(); this.k = conf.getInt(Driver.KEY_DO_TOP_K, -1); this.reverseBase = DistCache.readReverseRebasing(conf); } } protected void reduce(ItemAndSupportWritable key, Iterable<SupportAndTransactionWritable> patterns, Context context) throws java.io.IOException, InterruptedException { int rebased = this.reverseBase.get(key.getItem()); this.keyW.set(rebased); int count = 0; Iterator<SupportAndTransactionWritable> iter = patterns.iterator(); while (count < this.k && iter.hasNext()) { count++; SupportAndTransactionWritable entry = iter.next(); int[] transaction = entry.getTransaction(); for (int i = 0; i < transaction.length; i++) { transaction[i] = this.reverseBase.get(transaction[i]); } this.valueW.set(entry.getSupport(), transaction); context.write(this.keyW, this.valueW); } } }
package function.cohort.singleton; import function.cohort.base.CalledVariant; import function.cohort.base.AnalysisBase4CalledVar; import static function.cohort.singleton.SingletonManager.COMP_HET_FLAG; import function.variant.base.Output; import global.Data; import global.Index; import utils.CommonCommand; import utils.ErrorManager; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.StringJoiner; import utils.FormatManager; import utils.LogManager; import utils.ThirdPartyToolManager; /** * * @author nick */ public class ListSingleton extends AnalysisBase4CalledVar { BufferedWriter bwSingletonGeno = null; final String genotypesFilePath = CommonCommand.outputPath + "singleton_genotypes.csv"; HashMap<String, List<SingletonOutput>> geneVariantListMap = new HashMap<>(); // avoid output duplicate carrier (comp var & single var) HashSet<String> outputCarrierSet = new HashSet<>(); @Override public void initOutput() { try { bwSingletonGeno = new BufferedWriter(new FileWriter(genotypesFilePath)); bwSingletonGeno.write(SingletonOutput.getHeader()); bwSingletonGeno.newLine(); } catch (Exception ex) { ErrorManager.send(ex); } } @Override public void doOutput() { outputSingleVarAndCompVar(); clearList(); } @Override public void closeOutput() { try { bwSingletonGeno.flush(); bwSingletonGeno.close(); } catch (Exception ex) { ErrorManager.send(ex); } } @Override public void doAfterCloseOutput() { if (SingletonCommand.isMannWhitneyTest) { ThirdPartyToolManager.runMannWhitneyTest(genotypesFilePath); } if (CommonCommand.gzip) { ThirdPartyToolManager.gzipFile(genotypesFilePath); } Output.logTierVariantCount(); } @Override public void beforeProcessDatabaseData() { SingletonManager.init(); } @Override public void afterProcessDatabaseData() { } @Override public void processVariant(CalledVariant calledVar) { try { SingletonOutput output = new SingletonOutput(calledVar); addVariantToGeneList(output); } catch (Exception e) { ErrorManager.send(e); } } private void addVariantToGeneList(SingletonOutput output) { List<SingletonOutput> geneOutputList = geneVariantListMap.get(output.getCalledVariant().getGeneName()); if (geneOutputList == null) { geneOutputList = new ArrayList<>(); geneOutputList.add(output); geneVariantListMap.put(output.getCalledVariant().getGeneName(), geneOutputList); } else { geneOutputList.add(output); } } private void outputSingleVarAndCompVar() { if (geneVariantListMap.isEmpty()) { return; } try { for (Map.Entry<String, List<SingletonOutput>> entry : geneVariantListMap.entrySet()) { LogManager.writeAndPrint("Processing variants in gene:" + entry.getKey()); doOutput(entry.getValue()); } } catch (Exception e) { ErrorManager.send(e); } } private void doOutput(List<SingletonOutput> geneOutputList) { try { outputCarrierSet.clear(); for (int i = 0; i < geneOutputList.size(); i++) { SingletonOutput output1 = geneOutputList.get(i); for (Singleton singleton : SingletonManager.getList()) { output1.initSingletonData(singleton); if (output1.isQualifiedGeno(output1.cGeno)) { output1.initTierFlag4SingleVar(); for (int j = i + 1; j < geneOutputList.size(); j++) { SingletonOutput output2 = geneOutputList.get(j); output2.initSingletonData(singleton); if (output2.isQualifiedGeno(output2.cGeno)) { output2.initTierFlag4SingleVar(); outputCompHet(output1, output2); } } outputSingleVar(output1); } } } } catch (Exception e) { ErrorManager.send(e); } } private void outputSingleVar(SingletonOutput output) throws Exception { if (SingletonCommand.isExcludeNoFlag && output.getTierFlag4SingleVar() == Data.BYTE_NA && !output.isFlag()) { return; } StringBuilder carrierIDSB = new StringBuilder(); carrierIDSB.append(output.getCalledVariant().variantId); carrierIDSB.append("-"); carrierIDSB.append(output.cCarrier.getSampleId()); if (outputCarrierSet.contains(carrierIDSB.toString())) { return; } output.countSingleVar(); StringJoiner sj = new StringJoiner(","); sj.add(output.child.getName()); sj.add(output.child.getAncestry()); sj.add(output.child.getBroadPhenotype()); sj.add("'" + output.getCalledVariant().getGeneName() + "'"); sj.add(output.getCalledVariant().getGeneLink()); sj.add(Data.STRING_NA); sj.add(Data.STRING_NA); sj.add(Data.STRING_NA); sj.add(FormatManager.getByte(output.getTierFlag4SingleVar())); sj.add(output.toString()); sj.add(FormatManager.appendDoubleQuote(output.getSummary())); bwSingletonGeno.write(sj.toString()); bwSingletonGeno.newLine(); } private void outputCompHet(SingletonOutput output1, SingletonOutput output2) throws Exception { String compHetFlag = SingletonManager.getCompHetFlag(output1.cGeno, output2.cGeno); if (!compHetFlag.equals(COMP_HET_FLAG[2])) { // no flag doCompHetOutput(output1, output2); } } private void doCompHetOutput(SingletonOutput output1, SingletonOutput output2) throws Exception { float[] coFreq = SingletonManager.getCoOccurrenceFreq(output1, output2); // apply tier rules byte tierFlag4CompVar = Data.BYTE_NA; // Restrict to High or Moderate impact or TraP >= 0.4 variants if (output1.getCalledVariant().isImpactHighOrModerate() && output2.getCalledVariant().isImpactHighOrModerate()) { // tier 1 if (coFreq[Index.CTRL] == 0 // for both variants, genotype is not observed in Hemizygous or Homozygous from IGM default controls and gnomAD (WES & WGS) controls && output1.getCalledVariant().isNotObservedInHomAmongControl() && output2.getCalledVariant().isNotObservedInHomAmongControl() // for both variants, max 0.5% AF to IGM default controls and gnomAD (WES & WGS) controls && output1.getCalledVariant().isControlAFValid() && output2.getCalledVariant().isControlAFValid()) { tierFlag4CompVar = 1; Output.tier1CompoundVarCount++; } else if ( // tier 2 // if one of the variant meets tier 2 inclusion criteria (output1.getCalledVariant().isMetTier2InclusionCriteria() || output2.getCalledVariant().isMetTier2InclusionCriteria()) // for both variants, less than 10 homozygous observed from IGM default controls + gnomAD (WES & WGS) controls && output1.getCalledVariant().isNHomFromControlsValid(10) && output2.getCalledVariant().isNHomFromControlsValid(10)) { tierFlag4CompVar = 2; Output.tier2CompoundVarCount++; } } StringBuilder compHetVarSB = new StringBuilder(); compHetVarSB.append(output1.getCalledVariant().getVariantIdStr()); compHetVarSB.append("&"); compHetVarSB.append(output2.getCalledVariant().getVariantIdStr()); String compHetVar1 = compHetVarSB.toString() + " String compHetVar2 = compHetVarSB.toString() + " // output as single var if compound var not tier 1 or 2 when --exclude-no-flag used if (SingletonCommand.isExcludeNoFlag && tierFlag4CompVar == Data.BYTE_NA) { compHetVar1 = Data.STRING_NA; compHetVar2 = Data.STRING_NA; coFreq[Index.CTRL] = Data.FLOAT_NA; } doCompHetOutput(tierFlag4CompVar, output1, coFreq, compHetVar1); doCompHetOutput(tierFlag4CompVar, output2, coFreq, compHetVar2); } private void doCompHetOutput(byte tierFlag4CompVar, SingletonOutput output, float[] coFreq, String compHetVar) throws Exception { if (SingletonCommand.isExcludeNoFlag && tierFlag4CompVar == Data.BYTE_NA && output.getTierFlag4SingleVar() == Data.BYTE_NA && !output.isFlag()) { return; } output.countSingleVar(); StringBuilder carrierIDSB = new StringBuilder(); carrierIDSB.append(output.getCalledVariant().variantId); carrierIDSB.append("-"); carrierIDSB.append(output.cCarrier.getSampleId()); outputCarrierSet.add(carrierIDSB.toString()); // if output as single var then ignore duplicate output if(compHetVar.equals(Data.STRING_NA) && outputCarrierSet.contains(carrierIDSB.toString())) { return; } StringJoiner sj = new StringJoiner(","); sj.add(output.child.getName()); sj.add(output.child.getAncestry()); sj.add(output.child.getBroadPhenotype()); sj.add("'" + output.getCalledVariant().getGeneName() + "'"); sj.add(output.getCalledVariant().getGeneLink()); sj.add(compHetVar); sj.add(FormatManager.getFloat(coFreq[Index.CTRL])); sj.add(FormatManager.getByte(tierFlag4CompVar)); sj.add(FormatManager.getByte(output.getTierFlag4SingleVar())); sj.add(output.toString()); sj.add(FormatManager.appendDoubleQuote(output.getSummary())); bwSingletonGeno.write(sj.toString()); bwSingletonGeno.newLine(); } private void clearList() { geneVariantListMap.clear(); } @Override public String toString() { return "Start running list singleton function"; } }
package harmony.mastermind.memory; import java.util.Calendar; import java.util.GregorianCalendar; public class GenericMemory implements Comparable<GenericMemory> { private static final String TYPE_STRING = "Type: "; private static final String NAME_STRING = "\nName: "; private static final String DESCRIPTION_STRING = "\nDescription : "; private static final String START_STRING = "\nStart: "; private static final String END_STRING = "\nEnd: "; private static final String DUE_BY = "\nDue by: "; private static final String STATUS_INCOMPLETE = "\nStatus: Incomplete"; private static final String STATUS_COMPLETED = "\nStatus: Completed"; private static final String STATUS_OVERDUE = "\nStatus: Overdue"; private static final String STATUS_UPCOMING = "\nStatus: Upcoming"; private static final String STATUS_OVER = "\nStatus: Over"; private static final String STATUS_ONGOING = "\nStatus: Ongoing"; private static final String PM = "PM"; private static final String AM = "AM"; private static final String SUN = "Sun"; private static final String SAT = "Sat"; private static final String FRI = "Fri"; private static final String THURS = "Thurs"; private static final String WED = "Wed"; private static final String TUES = "Tues"; private static final String MON = "Mon"; private static final String EVENT = "Event"; private static final String DEADLINE = "Deadline"; private static final String TASK = "Task"; private static final String ONGOING = "Ongoing"; private static final String OVER = "Over"; private static final String UPCOMING = "Upcoming"; private static final String OVERDUE = "Overdue"; private static final String COMPLETED = "Completed"; private static final String INCOMPLETE = "Incomplete"; private String type; private String name; private String description; private Calendar start; private Calendar end; private int state; // State public static final int INT_OVERDUE = 2; public static final int INT_ONGOING = 2; public static final int INT_COMPLETED = 1; public static final int INT_OVER = 1; public static final int INT_INCOMPLETE = 0; public static final int INT_UPCOMING = 0; //@@author A0143378Y // Setting up tasks public GenericMemory(String type, String name, String description) { this.type = type; this.name = name; this.description = description; this.state = 0; } //@@author A0143378Y // Setting up deadlines public GenericMemory(String type, String name, String description, Calendar end) { this.type = type; this.name = name; this.description = description; this.end = end; this.state = 0; } //@@author A0143378Y // Events and constructor used to load from storage public GenericMemory(String type, String name, String description, Calendar startDate, Calendar end, int state) { this.type = type; this.name = name; this.description = description; this.start = startDate; this.end = end; this.state = state; } //@@author A0143378Y // Returns type of the to do item public String getType() { return type; } //@@author A0143378Y // Returns name of the to do item public String getName() { return name; } //@@author A0143378Y // Returns description of the to do item public String getDescription() { return description; } //@@author A0143378Y // Returns Calendar start of the to do item public Calendar getStart() { return start; } //@@author A0143378Y // Returns Calendar end of the to do item public Calendar getEnd() { return end; } //@@author A0143378Y // Returns the state of the to do item public int getState() { return state; } //@@author A0143378Y // Initializes start calendar - having a real calendar instead of hard coding everything public void initStart(){ start = new GregorianCalendar(); } //@@author A0143378Y // Initializes end calendar public void initEnd(){ end = new GregorianCalendar(); } //@@author A0143378Y // Set type of to do item public void setType(String type) { this.type = type; } //@@author A0143378Y // Set name of to do item public void setName(String name) { this.name = name; } //@@author A0143378Y // Set description of to do item public void setDescription(String description) { this.description = description; } //@@author A0143378Y // Set start time of to do item using hours and minutes public void setStartTime(int hourOfDay, int minute) { start.set(Calendar.HOUR_OF_DAY, hourOfDay); start.set(Calendar.MINUTE, minute); } //@@author A0143378Y // Set start time of to do item using hours, minutes and seconds public void setStartTime(int hourOfDay, int minute, int second) { start.set(Calendar.HOUR_OF_DAY, hourOfDay); start.set(Calendar.MINUTE, minute); start.set(Calendar.SECOND, second); } //@@author A0143378Y // Set end time of to do item using hours and minutes public void setEndTime(int hourOfDay, int minute) { end.set(Calendar.HOUR_OF_DAY, hourOfDay); end.set(Calendar.MINUTE, minute); } //@@author A0143378Y // Set end time of to do item using hours, minutes and seconds public void setEndTime(int hourOfDay, int minute, int second) { end.set(Calendar.HOUR_OF_DAY, hourOfDay); end.set(Calendar.MINUTE, minute); end.set(Calendar.SECOND, second); } //@@author A0143378Y // Set start date of to do item public void setStartDate(int year, int month, int date) { start.set(Calendar.YEAR, year); start.set(Calendar.MONTH, month); start.set(Calendar.DATE, date); } //@@author A0143378Y // Set end date of to do item public void setEndDate(int year, int month, int date) { end.set(Calendar.YEAR, year); end.set(Calendar.MONTH, month); end.set(Calendar.DATE, date); } //@@author A0143378Y // Set state of to do item public void setState(int newstate) { this.state = newstate; } //@@author A0143378Y /* Converts GenericEvents object into string representation * Outputs in the format * Name * Description * Start * End * State * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { String output = TYPE_STRING + getType() + NAME_STRING + getName(); output = descriptionToString(output); if (getType().equals(TASK)) { // Task output = taskDeadlineStateToString(output); return output; } if (getType().equals(DEADLINE)) { // Deadline output = deadlineDateToString(output); output = taskDeadlineStateToString(output); return output; } if (getType().equals(EVENT)) { // Event output = eventDatesToString(output); output = eventStateToString(output); return output; } return output; } //@@author A0143378Y // Converts description into string representation private String descriptionToString(String output) { if (description != null) { // If description exists output += DESCRIPTION_STRING + getDescription(); } return output; } //@@author A0143378Y // Converts due date into string representation private String deadlineDateToString(String output) { if (end != null) { output += DUE_BY + getDate(end) + " " + getTime(end); } return output; } //@@author A0143378Y // Converts event start and end dates into string representation private String eventDatesToString(String output) { if (start != null) { output += START_STRING + getDate(start) + " " + getTime(start); } if (end != null) { output += END_STRING + getDate(end) + " " + getTime(end); } return output; } //@@author A0143378Y // Converts event state into string representation private String eventStateToString(String output) { if (getState() == 0) { // Printing of state into string output+= STATUS_UPCOMING; } else if (getState() == 1) { output+= STATUS_OVER; } else { output+= STATUS_ONGOING; } return output; } //@@author A0143378Y // Converts task or deadline state into string representation private String taskDeadlineStateToString(String output) { if (getState() == 0) { // Printing of state into string output+= STATUS_INCOMPLETE; } else if (getState() == 1) { output+= STATUS_COMPLETED; } else { output+= STATUS_OVERDUE; } return output; } //@@author A0143378Y // Returns string representation of date as DD/MM/YY public static String getDate(Calendar item){ if(item != null){ return item.get(Calendar.DATE) + "/" + (item.get(Calendar.MONTH) + 1) + "/" + (item.get(Calendar.YEAR)%100) + " " + dayOfTheWeek(item); }else{ return null; } } //@@author A0143378Y // Returns string representation of time as HH:MM AM/PM public static String getTime(Calendar item){ if(item != null){ return hour(item) + ":" + min(item) + " " + AM_PM(item); }else{ return null; } } //@@author A0143378Y // Return string representation of day of the week of calendar object public static String dayOfTheWeek(Calendar item){ int dayOfTheWeek = item.get(Calendar.DAY_OF_WEEK); switch(dayOfTheWeek){ case Calendar.MONDAY: return MON; case Calendar.TUESDAY: return TUES; case Calendar.WEDNESDAY: return WED; case Calendar.THURSDAY: return THURS; case Calendar.FRIDAY: return FRI; case Calendar.SATURDAY: return SAT; case Calendar.SUNDAY: return SUN; } return null; } //@@author A0143378Y // Check item for AM/PM and return the correct time period public static String AM_PM(Calendar item){ if(item.get(Calendar.AM_PM) == Calendar.AM){ return AM; }else{ return PM; } } //@@author A0143378Y // Return the hour of time to form of HH public static String hour(Calendar item){ if(item.get(Calendar.HOUR_OF_DAY)==12){ return "12"; }else if( item.get(Calendar.HOUR)<10){ return "0" + item.get(Calendar.HOUR); }else{ return Integer.toString(item.get(Calendar.HOUR)); } } //@@author A0143378Y // Return minute of time to form of MM public static String min(Calendar item){ if( item.get(Calendar.MINUTE)<10){ return "0" + item.get(Calendar.MINUTE); }else{ return Integer.toString(item.get(Calendar.MINUTE)); } } //@@author A0143378Y /* Comparator between to do item and o * Only valid when comparing items of the same type * eg. Task vs Task, Deadline vs Deadline, Event vs Event * Task: Compare names lexicographically, ignoring case differences -> alphabetical order * Deadline: Compare due dates * Event: Compare start dates, else end dates */ public int compareTo(GenericMemory o) { if (this.start == null && this.end == null && o.start == null && o.end == null){ //both task return this.name.compareToIgnoreCase(o.name); } if (this.start == null && this.end != null && o.start == null && o.end != null){ //both deadline return this.end.compareTo(o.end); } if (this.start != null && this.end != null && o.start != null && o.end != null){ //both event return eventCompare(o); } return 0; } //@@author A0143378Y // Compare's start date followed by end dates private int eventCompare(GenericMemory o) { if (this.start.compareTo(o.start) != 0) { return this.start.compareTo(o.start); } else { return this.end.compareTo(o.end); } } //@@author A0143378Y // Return state of the item in the form of a string public String getStateType(){ if(type.equals(DEADLINE)|| type.equals(TASK)){ if(state == INT_INCOMPLETE){ return INCOMPLETE; }else if (state == INT_COMPLETED){ return COMPLETED; }else if (state == INT_OVERDUE){ return OVERDUE; } } if(type.equals(EVENT)){ if(state == INT_UPCOMING){ return UPCOMING; }else if(state == INT_OVER){ return OVER; }else if (state == INT_ONGOING){ return ONGOING; } } return null; } }
package io.kuzzle.sdk.core; import android.support.annotation.NonNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import io.kuzzle.sdk.listeners.KuzzleResponseListener; import io.kuzzle.sdk.listeners.OnQueryDoneListener; import io.kuzzle.sdk.responses.KuzzleDocumentList; import io.kuzzle.sdk.responses.KuzzleNotificationResponse; /** * The type Kuzzle data collection. */ public class KuzzleDataCollection { private final Kuzzle kuzzle; private final String collection; private final String index; protected JSONObject headers; /** * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents, * or like a room for pub/sub messages. * * @param kuzzle the kuzzle * @param index the index * @param collection the collection */ public KuzzleDataCollection(@NonNull final Kuzzle kuzzle, @NonNull final String index, @NonNull final String collection) { if (kuzzle == null) { throw new IllegalArgumentException("KuzzleDataCollection: need a Kuzzle instance to initialize"); } if (index == null || collection == null) { throw new IllegalArgumentException("KuzzleDataCollection: index and collection required"); } this.kuzzle = kuzzle; this.collection = collection; this.index = index; try { this.headers = new JSONObject(kuzzle.getHeaders().toString()); } catch (JSONException e) { throw new RuntimeException(e); } } public KuzzleDataCollection advancedSearch(final JSONObject filter, final KuzzleResponseListener<KuzzleDocumentList> listener) { return this.advancedSearch(filter, null, listener); } public KuzzleDataCollection advancedSearch(final JSONObject filters, final KuzzleOptions options, @NonNull final KuzzleResponseListener<KuzzleDocumentList> listener) { if (listener == null) { throw new IllegalArgumentException("listener cannot be null"); } this.kuzzle.isValid(); JSONObject data = new JSONObject(); try { if (filters != null) { data.put("body", filters); } this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("read", "search"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject object) { try { JSONArray hits = object.getJSONObject("result").getJSONArray("hits"); List<KuzzleDocument> docs = new ArrayList<KuzzleDocument>(); for (int i = 0; i < hits.length(); i++) { JSONObject hit = hits.getJSONObject(i); KuzzleDocument doc = new KuzzleDocument(KuzzleDataCollection.this, hit.getString("_id"), hit.getJSONObject("_source")); docs.add(doc); } KuzzleDocumentList response = new KuzzleDocumentList(docs, object.getJSONObject("result").getInt("total")); listener.onSuccess(response); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { listener.onError(error); } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * Make query args kuzzle . query args. * * @param controller the controller * @param action the action * @return the kuzzle . query args */ public io.kuzzle.sdk.core.Kuzzle.QueryArgs makeQueryArgs(final String controller, final String action) { io.kuzzle.sdk.core.Kuzzle.QueryArgs args = new io.kuzzle.sdk.core.Kuzzle.QueryArgs(); args.action = action; args.controller = controller; args.index = this.index; args.collection = this.collection; return args; } /** * Count kuzzle data collection. * * @param filters the filters * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection count(final JSONObject filters, @NonNull final KuzzleResponseListener<Integer> listener) { return this.count(filters, null, listener); } /** * Count kuzzle data collection. * * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection count(@NonNull final KuzzleResponseListener<Integer> listener) { return this.count(null, null, listener); } public KuzzleDataCollection count(final JSONObject filters, final KuzzleOptions options, @NonNull final KuzzleResponseListener<Integer> listener) { if (listener == null) { throw new IllegalArgumentException("KuzzleDataCollection.count: listener required"); } JSONObject data = new JSONObject(); try { this.kuzzle.addHeaders(data, this.getHeaders()); data.put("body", filters); this.kuzzle.query(makeQueryArgs("read", "count"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { try { listener.onSuccess(response.getJSONObject("result").getInt("count")); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { listener.onError(error); } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * Create a new empty data collection, with no associated mapping. * Kuzzle automatically creates data collections when storing documents, but there are cases where we want to create and prepare data collections before storing documents in it. * * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection create(final KuzzleOptions options) { return this.create(options, null); } /** * Create a new empty data collection, with no associated mapping. * Kuzzle automatically creates data collections when storing documents, but there are cases where we want to create and prepare data collections before storing documents in it. * * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection create(final KuzzleResponseListener<JSONObject> listener) { return this.create(null, listener); } /** * Create a new empty data collection, with no associated mapping. * Kuzzle automatically creates data collections when storing documents, but there are cases where we want to create and prepare data collections before storing documents in it. * * @return the kuzzle data collection */ public KuzzleDataCollection create() { return this.create(null, null); } /** * Create a new empty data collection, with no associated mapping. * Kuzzle automatically creates data collections when storing documents, but there are cases where we want to create and prepare data collections before storing documents in it. * * @param options the options * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection create(final KuzzleOptions options, final KuzzleResponseListener<JSONObject> listener) { JSONObject data = new JSONObject(); try { this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("write", "createCollection"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { if (listener != null) { try { listener.onSuccess(response.getJSONObject("result")); } catch (JSONException e) { throw new RuntimeException(e); } } } @Override public void onError(JSONObject error) { if (listener != null) { listener.onError(error); } } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * * @param id - document ID * @param content - document content * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(final String id, @NonNull final JSONObject content) throws JSONException { return this.createDocument(id, content, null, null); } /** * * @param id - document ID * @param content - document content * @param opts - optional arguments * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(final String id, @NonNull final JSONObject content, KuzzleOptions opts) throws JSONException { return this.createDocument(id, content, opts, null); } /** * * @param id - document ID * @param content - document content * @param listener - result listener * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(final String id, @NonNull final JSONObject content, final KuzzleResponseListener<KuzzleDocument> listener) throws JSONException { return this.createDocument(id, content, null, listener); } /** * * @param content - document content * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(@NonNull final JSONObject content) throws JSONException { return this.createDocument(null, content, null, null); } /** * * @param content - document content * @param opts - optional arguments * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(@NonNull final JSONObject content, KuzzleOptions opts) throws JSONException { return this.createDocument(null, content, opts, null); } /** * * @param content - document content * @param listener - result listener * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(@NonNull final JSONObject content, final KuzzleResponseListener<KuzzleDocument> listener) throws JSONException { return this.createDocument(null, content, null, listener); } /** * * @param content - document content * @param opts - optional arguments * @param listener - result listener * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(@NonNull final JSONObject content, KuzzleOptions opts, final KuzzleResponseListener<KuzzleDocument> listener) throws JSONException { return this.createDocument(null, content, opts, listener); } /** * * @param id - document ID * @param content - document content * @param opts - optional arguments * @param listener - result listener * @return this object * @throws JSONException */ public KuzzleDataCollection createDocument(final String id, @NonNull final JSONObject content, KuzzleOptions opts, final KuzzleResponseListener<KuzzleDocument> listener) throws JSONException { if (content == null) { throw new IllegalArgumentException("Cannot create an empty document"); } KuzzleDocument doc = new KuzzleDocument(this, id, content); return this.createDocument(doc, opts, listener); } /** * Create a new document in Kuzzle * * @param document the document * @return kuzzle data collection */ public KuzzleDataCollection createDocument(final KuzzleDocument document) { return this.createDocument(document, null, null); } /** * Create a new document in kuzzle * * @param document the document * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection createDocument(final KuzzleDocument document, final KuzzleOptions options) { return this.createDocument(document, options, null); } /** * Create document kuzzle data collection. * * @param document the document * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection createDocument(final KuzzleDocument document, final KuzzleResponseListener<KuzzleDocument> listener) { return this.createDocument(document, null, listener); } /** * Create a new document in kuzzle * * @param document the document * @param options the options * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection createDocument(final KuzzleDocument document, final KuzzleOptions options, final KuzzleResponseListener<KuzzleDocument> listener) { String create = (options != null && options.isUpdateIfExists()) ? "createOrReplace" : "create"; JSONObject data = document.serialize(); this.kuzzle.addHeaders(data, this.getHeaders()); try { this.kuzzle.query(makeQueryArgs("write", create), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { if (listener != null) { try { JSONObject result = response.getJSONObject("result"); KuzzleDocument document = new KuzzleDocument(KuzzleDataCollection.this, result.getString("_id"), result.getJSONObject("_source")); document.setVersion(result.getLong("_version")); listener.onSuccess(document); } catch (JSONException e) { throw new RuntimeException(e); } } } @Override public void onError(JSONObject error) { if (listener != null) { listener.onError(error); } } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * @return the kuzzle data mapping */ public KuzzleDataMapping dataMappingFactory() { return new KuzzleDataMapping(this); } /** * Data mapping factory kuzzle data mapping. * * @param mapping the mapping * @return the kuzzle data mapping */ public KuzzleDataMapping dataMappingFactory(JSONObject mapping) { return new KuzzleDataMapping(this, mapping); } /** * Delete kuzzle data collection. * * @return the kuzzle data collection */ public KuzzleDataCollection delete() { return this.delete(null, null); } /** * Delete kuzzle data collection. * * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection delete(final KuzzleOptions options) { return this.delete(options, null); } /** * Delete kuzzle data collection. * * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection delete(final KuzzleResponseListener<JSONObject> listener) { return this.delete(null, listener); } /** * Delete kuzzle data collection. * * @param options the options * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection delete(final KuzzleOptions options, final KuzzleResponseListener<JSONObject> listener) { JSONObject data = new JSONObject(); try { this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("admin", "deleteCollection"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { if (listener != null) { listener.onSuccess(response); } } @Override public void onError(JSONObject error) { if (listener != null) { listener.onError(error); } } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public KuzzleDataCollection deleteDocument(@NonNull final String documentId) { return this.deleteDocument(documentId, null, null); } /** * Delete document kuzzle data collection. * * @param documentId the document id * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection deleteDocument(@NonNull final String documentId, KuzzleOptions options) { return this.deleteDocument(documentId, options, null); } public KuzzleDataCollection deleteDocument(@NonNull final String documentId, final KuzzleResponseListener<String> listener) { return this.deleteDocument(documentId, null, listener); } /** * Delete document kuzzle data collection. * * @param documentId the document id * @param options the options * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection deleteDocument(@NonNull final String documentId, final KuzzleOptions options, final KuzzleResponseListener<String> listener) { if (documentId == null) { throw new IllegalArgumentException("KuzzleDataCollection.deleteDocument: documentId required"); } return this.deleteDocument(documentId, null, options, listener, null); } public KuzzleDataCollection deleteDocument(@NonNull final JSONObject filters) { return this.deleteDocument(filters, null, null); } /** * Delete document kuzzle data collection. * * @param filters the filters * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection deleteDocument(@NonNull final JSONObject filters, final KuzzleOptions options) { return this.deleteDocument(filters, options, null); } public KuzzleDataCollection deleteDocument(@NonNull final JSONObject filters, final KuzzleResponseListener<String[]> listener) { return this.deleteDocument(filters, null, listener); } /** * Delete document kuzzle data collection. * * @param filters the filters * @param options the options * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection deleteDocument(@NonNull final JSONObject filters, final KuzzleOptions options, final KuzzleResponseListener<String[]> listener) { if (filters == null) { throw new IllegalArgumentException("KuzzleDataCollection.deleteDocument: filters required"); } return this.deleteDocument(null, filters, options, null, listener); } protected KuzzleDataCollection deleteDocument(final String documentId, final JSONObject filter, final KuzzleOptions options, final KuzzleResponseListener<String> listener, final KuzzleResponseListener<String[]> listener2) { JSONObject data = new JSONObject(); String action; try { this.kuzzle.addHeaders(data, this.getHeaders()); if (documentId != null) { data.put("_id", documentId); action = "delete"; } else { data.put("body", filter); action = "deleteByQuery"; } this.kuzzle.query(makeQueryArgs("write", action), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { try { if (listener != null) { listener.onSuccess(response.getJSONObject("result").getString("_id")); } else if (listener2 != null) { JSONArray array = response.getJSONObject("result").getJSONArray("hits"); int length = array.length(); String[] ids = new String[length]; for (int i = 0; i < length; i++) { ids[i] = array.getString(i); } listener2.onSuccess(ids); } } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { if (listener != null) { listener.onError(error); } else if (listener2 != null) { listener2.onError(error); } } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public KuzzleDocument documentFactory() throws JSONException { return new KuzzleDocument(this); } public KuzzleDocument documentFactory(final String id) throws JSONException { return new KuzzleDocument(this, id); } public KuzzleDocument documentFactory(final JSONObject content) throws JSONException { return new KuzzleDocument(this, content); } public KuzzleDocument documentFactory(final String id, final JSONObject content) throws JSONException { return new KuzzleDocument(this, id, content); } /** * Fetch document kuzzle data collection. * * @param documentId the document id * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection fetchDocument(@NonNull final String documentId, @NonNull final KuzzleResponseListener<KuzzleDocument> listener) { return this.fetchDocument(documentId, null, listener); } /** * Retrieve a single stored document using its unique document ID. * * @param documentId the document id * @param options the options * @param listener the listener * @return KuzzleDataCollection kuzzle data collection */ public KuzzleDataCollection fetchDocument(@NonNull final String documentId, final KuzzleOptions options, final KuzzleResponseListener<KuzzleDocument> listener) { if (documentId == null) { throw new IllegalArgumentException("KuzzleDataCollection.fetchDocument: documentId required"); } if (listener == null) { throw new IllegalArgumentException("KuzzleDataCollection.fetchDocument: listener required"); } try { JSONObject data = new JSONObject().put("_id", documentId); this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("read", "get"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { try { JSONObject result = response.getJSONObject("result"); KuzzleDocument document = new KuzzleDocument(KuzzleDataCollection.this, result.getString("_id"), result.getJSONObject("_source")); document.setVersion(result.getLong("_version")); listener.onSuccess(document); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { listener.onError(error); } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * Retrieves all documents stored in this data collection. * * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection fetchAllDocuments(@NonNull final KuzzleResponseListener<KuzzleDocumentList> listener) { return this.fetchAllDocuments(null, listener); } /** * Retrieves all documents stored in this data collection. * * @param options the options * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection fetchAllDocuments(final KuzzleOptions options, @NonNull final KuzzleResponseListener<KuzzleDocumentList> listener) { if (listener == null) { throw new IllegalArgumentException("KuzzleDataCollection.fetchAllDocuments: listener required"); } return this.advancedSearch(null, options, listener); } /** * Instantiates a KuzzleDataMapping object containing the current mapping of this collection. * * @param listener the listener * @return the mapping */ public KuzzleDataCollection getMapping(@NonNull final KuzzleResponseListener<KuzzleDataMapping> listener) { return this.getMapping(null, listener); } /** * Instantiates a KuzzleDataMapping object containing the current mapping of this collection. * * @param options the options * @param listener the listener * @return the mapping */ public KuzzleDataCollection getMapping(final KuzzleOptions options, @NonNull final KuzzleResponseListener<KuzzleDataMapping> listener) { if (listener == null) { throw new IllegalArgumentException("KuzzleDataCollection.getMapping: listener required"); } new KuzzleDataMapping(this).refresh(options, listener); return this; } /** * Publish a realtime message * * @param document the document * @return kuzzle data collection */ public KuzzleDataCollection publishMessage(final KuzzleDocument document) { return this.publishMessage(document, null); } /** * Publish a realtime message * * @param document the document * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection publishMessage(@NonNull final KuzzleDocument document, final KuzzleOptions options) { if (document == null) { throw new IllegalArgumentException("Cannot publish a null document"); } return this.publishMessage(document.getContent(), options); } /** * Publish a realtime message * * @return the kuzzle data collection */ public KuzzleDataCollection publishMessage(@NonNull final JSONObject content) { return this.publishMessage(content, null); } /** * Publish a realtime message * * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection publishMessage(@NonNull final JSONObject content, final KuzzleOptions options) { if (content == null) { throw new IllegalArgumentException("Cannot publish null content"); } try { JSONObject data = new JSONObject().put("body", content); this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("write", "publish"), data, options, null); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * Replace an existing document with a new one. * * @param documentId the document id * @param content the content * @return the kuzzle data collection */ public KuzzleDataCollection replaceDocument(@NonNull final String documentId, final JSONObject content) { return this.replaceDocument(documentId, content, null, null); } /** * Replace document kuzzle data collection. * * @param documentId the document id * @param content the content * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection replaceDocument(@NonNull final String documentId, final JSONObject content, final KuzzleResponseListener<KuzzleDocument> listener) { return this.replaceDocument(documentId, content, null, listener); } /** * Replace document kuzzle data collection. * * @param documentId the document id * @param options the options * @param content the content * @return the kuzzle data collection */ public KuzzleDataCollection replaceDocument(@NonNull final String documentId, final JSONObject content, final KuzzleOptions options) { return this.replaceDocument(documentId, content, options, null); } /** * Replace an existing document with a new one. * * @param documentId the document id * @param content the content * @param options the options * @param listener the listener * @return KuzzleDataCollection kuzzle data collection */ public KuzzleDataCollection replaceDocument(@NonNull final String documentId, final JSONObject content, final KuzzleOptions options, final KuzzleResponseListener<KuzzleDocument> listener) { if (documentId == null) { throw new IllegalArgumentException("KuzzleDataCollection.replaceDocument: documentId required"); } try { JSONObject data = new JSONObject().put("_id", documentId).put("body", content); this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("write", "createOrReplace"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { if (listener != null) { try { JSONObject result = response.getJSONObject("result"); KuzzleDocument document = new KuzzleDocument(KuzzleDataCollection.this, result.getString("_id"), result.getJSONObject("_source")); document.setVersion(result.getLong("_version")); listener.onSuccess(document); } catch (JSONException e) { throw new RuntimeException(e); } } } @Override public void onError(JSONObject error) { if (listener != null) { listener.onError(error); } } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public KuzzleRoom roomFactory() { return this.roomFactory(null); } public KuzzleRoom roomFactory(KuzzleRoomOptions options) { return new KuzzleRoom(this, options); } /** * Sets headers. * * @param content the content * @return the headers */ public KuzzleDataCollection setHeaders(final JSONObject content) { return this.setHeaders(content, false); } /** * Sets headers. * * @param content the content * @param replace the replace * @return the headers */ public KuzzleDataCollection setHeaders(final JSONObject content, final boolean replace) { try { if (content == null) { if (replace) { this.headers = new JSONObject(); } return this; } if (replace) { this.headers = new JSONObject(content.toString()); } else { for (Iterator ite = content.keys(); ite.hasNext(); ) { String key = (String) ite.next(); this.headers.put(key, content.get(key)); } } } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * Subscribes to this data collection with a set of filters. * To subscribe to the entire data collection, simply provide an empty filter. * * @param filters the filters * @param listener the listener * @return the kuzzle room */ public KuzzleRoom subscribe(final JSONObject filters, @NonNull final KuzzleResponseListener<KuzzleNotificationResponse> listener) { return this.subscribe(filters, null, listener); } /** * Subscribes to this data collection with a set of filters. * To subscribe to the entire data collection, simply provide an empty filter. * * @param options the options * @param listener the listener * @return the kuzzle room */ public KuzzleRoom subscribe(final KuzzleRoomOptions options, @NonNull final KuzzleResponseListener<KuzzleNotificationResponse> listener) { return this.subscribe(null, options, listener); } /** * Subscribes to this data collection with a set of filters. * To subscribe to the entire data collection, simply provide an empty filter. * * @param filters the filters * @param options the options * @param listener the listener * @return kuzzle room */ public KuzzleRoom subscribe(final JSONObject filters, final KuzzleRoomOptions options, @NonNull final KuzzleResponseListener<KuzzleNotificationResponse> listener) { if (listener == null) { throw new IllegalArgumentException("KuzzleDataCollection.subscribe: listener required"); } this.kuzzle.isValid(); KuzzleRoom room = new KuzzleRoom(this, options); return room.renew(filters, listener); } /** * Truncate the data collection, removing all stored documents but keeping all associated mappings. * This method is a lot faster than removing all documents using a query. * * @return the kuzzle data collection */ public KuzzleDataCollection truncate() { return this.truncate(null, null); } /** * Truncate the data collection, removing all stored documents but keeping all associated mappings. * This method is a lot faster than removing all documents using a query. * * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection truncate(final KuzzleOptions options) { return this.truncate(options, null); } /** * Truncate the data collection, removing all stored documents but keeping all associated mappings. * This method is a lot faster than removing all documents using a query. * * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection truncate(final KuzzleResponseListener<JSONObject> listener) { return this.truncate(null, listener); } /** * Truncate the data collection, removing all stored documents but keeping all associated mappings. * This method is a lot faster than removing all documents using a query. * * @param options the options * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection truncate(final KuzzleOptions options, final KuzzleResponseListener<JSONObject> listener) { JSONObject data = new JSONObject(); try { this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("admin", "truncateCollection"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { if (listener != null) { try { listener.onSuccess(response.getJSONObject("result")); } catch (JSONException e) { throw new RuntimeException(e); } } } @Override public void onError(JSONObject error) { if (listener != null) { listener.onError(error); } } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * Update parts of a document * * @param documentId the document id * @param content the content * @return the kuzzle data collection */ public KuzzleDataCollection updateDocument(@NonNull final String documentId, @NonNull final JSONObject content) { return this.updateDocument(documentId, content, null, null); } /** * Update parts of a document * * @param documentId the document id * @param content the content * @param options the options * @return the kuzzle data collection */ public KuzzleDataCollection updateDocument(@NonNull final String documentId, @NonNull final JSONObject content, final KuzzleOptions options) { return this.updateDocument(documentId, content, options, null); } /** * Update parts of a document * * @param documentId the document id * @param content the content * @param listener the listener * @return the kuzzle data collection */ public KuzzleDataCollection updateDocument(@NonNull final String documentId, @NonNull final JSONObject content, final KuzzleResponseListener<KuzzleDocument> listener) { return this.updateDocument(documentId, content, null, listener); } /** * Update parts of a document * * @param documentId the document id * @param content the content * @param options the options * @param listener the listener * @return kuzzle data collection */ public KuzzleDataCollection updateDocument(@NonNull final String documentId, @NonNull final JSONObject content, final KuzzleOptions options, final KuzzleResponseListener<KuzzleDocument> listener) { if (documentId == null) { throw new IllegalArgumentException("KuzzleDataCollection.updateDocument: documentId required"); } if (content == null) { throw new IllegalArgumentException("KuzzleDataCollection.updateDocument: content required"); } try { JSONObject data = new JSONObject().put("_id", documentId).put("body", content); this.kuzzle.addHeaders(data, this.getHeaders()); this.kuzzle.query(makeQueryArgs("write", "update"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { if (listener != null) { try { JSONObject result = response.getJSONObject("result"); KuzzleDocument document = new KuzzleDocument(KuzzleDataCollection.this, result.getString("_id"), result.getJSONObject("_source")); document.setVersion(result.getLong("_version")); listener.onSuccess(document); } catch (JSONException e) { throw new RuntimeException(e); } } } @Override public void onError(JSONObject error) { if (listener != null) { listener.onError(error); } } }); } catch (JSONException e) { throw new RuntimeException(e); } return this; } /** * Gets kuzzle. * * @return the kuzzle */ public Kuzzle getKuzzle() { return kuzzle; } /** * Gets collection. * * @return the collection */ public String getCollection() { return collection; } /** * Getter for the "index" property * * @return */ public String getIndex() { return this.index; } /** * Gets headers. * * @return the headers */ public JSONObject getHeaders() { return this.headers; } }
package io.rapidpro.mage.twitter; import com.twitter.hbc.ClientBuilder; import com.twitter.hbc.core.Client; import com.twitter.hbc.core.Constants; import com.twitter.hbc.core.HttpHosts; import com.twitter.hbc.core.StatsReporter; import com.twitter.hbc.core.endpoint.UserstreamEndpoint; import com.twitter.hbc.core.processor.StringDelimitedProcessor; import com.twitter.hbc.httpclient.auth.Authentication; import com.twitter.hbc.httpclient.auth.OAuth1; import com.twitter.hbc.twitter4j.Twitter4jUserstreamClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.DirectMessage; import twitter4j.PagableResponseList; import twitter4j.Paging; import twitter4j.RateLimitStatus; import twitter4j.ResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.UserStreamListener; import twitter4j.conf.ConfigurationBuilder; import javax.annotation.Nullable; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; /** * The Twitter4J and Twitter Streaming API don't lend themselves to mocking. This factory and set of wrappers makes it * easier to run Mage without actually hitting real APIs */ public class TwitterClients { protected static final Logger log = LoggerFactory.getLogger(TwitterClients.class); /** * Interface for used REST client functionality */ public static interface RestClient { ResponseList<DirectMessage> getDirectMessages(Paging paging) throws TwitterException; PagableResponseList<User> getFollowers(long cursor) throws TwitterException; void createFriendship(long userId) throws TwitterException; } /** * Interface for used streaming client functionality */ public static interface StreamingClient { void start(UserStreamListener listener); void stop(); StatsReporter.StatsTracker getStatsTracker(); } /** * Default REST client - defers to the actual REST client */ protected static class DefaultRestClient implements RestClient { private Twitter m_realClient; private static int MAX_RATE_LIMIT_RETRIES = 5; public DefaultRestClient(String apiKey, String apiSecret, String authToken, String authSecret) { ConfigurationBuilder cb = new ConfigurationBuilder() .setOAuthConsumerKey(apiKey) .setOAuthConsumerSecret(apiSecret) .setOAuthAccessToken(authToken) .setOAuthAccessTokenSecret(authSecret); TwitterFactory restClientFactory = new TwitterFactory(cb.build()); m_realClient = restClientFactory.getInstance(); } @Override public ResponseList<DirectMessage> getDirectMessages(Paging paging) throws TwitterException { return rateLimited(() -> m_realClient.getDirectMessages(paging)); } @Override public PagableResponseList<User> getFollowers(long cursor) throws TwitterException { return rateLimited(() -> m_realClient.getFollowersList(m_realClient.getId(), cursor, 200)); } @Override public void createFriendship(long userId) throws TwitterException { rateLimited(() -> m_realClient.createFriendship(userId)); } @FunctionalInterface protected interface RateLimitedOperation<T> { T perform() throws TwitterException; } /** * Performs a rate-limited operation. If Twitter API returns a rate limit error, method waits before retrying * the operation. Method is static synchronized, synchronizing calls across all client instances. */ protected static synchronized <T> T rateLimited(RateLimitedOperation<T> operation) throws TwitterException { int attempt = 1; while (true) { try { return operation.perform(); } catch (TwitterException ex) { if (ex.exceededRateLimitation()) { // log as error so goes to Sentry log.error("Exceeded rate limit", ex); if (attempt == MAX_RATE_LIMIT_RETRIES) { // no more retrying so re-throw throw ex; } RateLimitStatus status = ex.getRateLimitStatus(); try { Thread.sleep(status.getSecondsUntilReset() * 1000); attempt++; } catch (InterruptedException e) { // weren't able to wait out the rate limit, so re-throw throw ex; } } else { // not a rate limit problem, so re-throw throw ex; } } } } } /** * Stub REST client - NOOPs all around */ protected static class StubRestClient implements RestClient { @Override public ResponseList<DirectMessage> getDirectMessages(Paging paging) throws TwitterException { log.info("FAKED direct message fetch from Twitter API"); return null; } @Override public PagableResponseList<User> getFollowers(long cursor) throws TwitterException { log.info("FAKED follower list fetch from Twitter API"); return null; } @Override public void createFriendship(long userId) throws TwitterException { log.info("FAKED create friendship to user #" + userId); } } /** * Default streaming client - connects to Twitter Streaming API */ protected static class DefaultStreamingClient implements StreamingClient { private ClientBuilder m_hbcClientBuilder; private BlockingQueue<String> m_streamingQueue = new LinkedBlockingQueue<>(10000); private Twitter4jUserstreamClient m_realClient; public DefaultStreamingClient(String apiKey, String apiSecret, String authToken, String authSecret) { Authentication auth = new OAuth1(apiKey, apiSecret, authToken, authSecret); // we don't need activity of people we follow UserstreamEndpoint endpoint = new UserstreamEndpoint(); endpoint.withFollowings(false); endpoint.withUser(true); endpoint.allReplies(false); m_hbcClientBuilder = new ClientBuilder() .hosts(new HttpHosts(Constants.USERSTREAM_HOST)) .authentication(auth) .endpoint(endpoint) .processor(new MessageProcessor(m_streamingQueue)); } @Override public void start(UserStreamListener listener) { Client hbcClient = m_hbcClientBuilder.build(); ExecutorService streamingExecutor = Executors.newFixedThreadPool(1); m_realClient = new Twitter4jUserstreamClient(hbcClient, m_streamingQueue, Arrays.asList(listener), streamingExecutor); m_realClient.connect(); m_realClient.process(); } @Override public void stop() { m_realClient.stop(); } @Override public StatsReporter.StatsTracker getStatsTracker() { return m_realClient.getStatsTracker(); } /** * Override the regular message processor to allow debug logging */ protected class MessageProcessor extends StringDelimitedProcessor { public MessageProcessor(BlockingQueue<String> queue) { super(queue); } @Nullable @Override protected String processNextMessage() throws IOException { String msg = super.processNextMessage(); if (log.isDebugEnabled()) { log.debug(msg); } return msg; } } } /** * Stub streaming client - NOOPs all around */ protected static class StubStreamingClient implements StreamingClient { private StatsReporter m_statsReporter = new StatsReporter(); @Override public void start(UserStreamListener listener) { log.info("FAKED streaming client connect"); } @Override public void stop() { log.info("FAKED streaming client stop"); } @Override public StatsReporter.StatsTracker getStatsTracker() { return m_statsReporter.getStatsTracker(); } } /** * Gets a REST client instance * @param apiKey the API key * @param apiSecret the API secret token * @param authToken the OAuth token * @param authSecret the OAuth token secret * @param production whether production mode is enabled * @return the client */ public static RestClient getRestClient(String apiKey, String apiSecret, String authToken, String authSecret, boolean production) { return production ? new DefaultRestClient(apiKey, apiSecret, authToken, authSecret) : new StubRestClient(); } /** * Gets a streaming API client instance * @param apiKey the API key * @param apiSecret the API secret token * @param authToken the OAuth token * @param authSecret the OAuth token secret * @param production whether production mode is enabled * @return the client */ public static StreamingClient getStreamingClient(String apiKey, String apiSecret, String authToken, String authSecret, boolean production) { return production ? new DefaultStreamingClient(apiKey, apiSecret, authToken, authSecret) : new StubStreamingClient(); } }
package it.yudharta.peminjamanlcd.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.Size; @Entity public class Barang implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @Basic(optional = false) @Column(name = "id") private Integer id; @Size(max = 25) @Column(name = "kode", unique = true) private String kode; @Size(max = 50) @Column(name = "nama") private String nama; @Size(max = 6) @Column(name = "status") private String status; public Barang() { } public Barang(String kode, String nama, String status) { this.kode = kode; this.nama = nama; this.status = status; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getKode() { return kode; } public void setKode(String kode) { this.kode = kode; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Barang)) { return false; } Barang other = (Barang) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "it.yudharta.peminjamanlcd.entity.Products[ id=" + id + " ]"; } }
package kaaes.spotify.webapi.android; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.android.MainThreadExecutor; /** * Creates and configures a REST adapter for Spotify Web API. * * Basic usage: * SpotifyApi wrapper = new SpotifyApi(); * * Setting access token is optional for certain endpoints * so if you know you'll only use the ones that don't require authorisation * you can skip this step: * wrapper.setAccessToken(authenticationResponse.getAccessToken()); * * SpotifyService spotify = wrapper.getService(); * * Album album = spotify.getAlbum("2dIGnmEIy1WZIcZCFSj6i8"); */ public class SpotifyApi { /** * Main Spotify Web API endpoint */ public static final String SPOTIFY_WEB_API_ENDPOINT = "https://api.spotify.com/v1"; /** * The request interceptor that will add the header with OAuth * token to every request made with the wrapper. */ private class WebApiAuthenticator implements RequestInterceptor { @Override public void intercept(RequestFacade request) { if (mAccessToken != null) { request.addHeader("Authorization", "Bearer " + mAccessToken); } } } private final SpotifyService mSpotifyService; private String mAccessToken; /** * Create instance of SpotifyApi with given executors. * * @param httpExecutor executor for http request. Cannot be null. * @param callbackExecutor executor for callbacks. If null is passed than the same * thread that created the instance is used. */ public SpotifyApi(Executor httpExecutor, Executor callbackExecutor) { mSpotifyService = init(httpExecutor, callbackExecutor); } private SpotifyService init(Executor httpExecutor, Executor callbackExecutor) { final RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.BASIC) .setExecutors(httpExecutor, callbackExecutor) .setEndpoint(SPOTIFY_WEB_API_ENDPOINT) .setRequestInterceptor(new WebApiAuthenticator()) .build(); return restAdapter.create(SpotifyService.class); } /** * New instance of SpotifyApi, * with single thread executor both for http and callbacks. */ public SpotifyApi() { Executor httpExecutor = Executors.newSingleThreadExecutor(); MainThreadExecutor callbackExecutor = new MainThreadExecutor(); mSpotifyService = init(httpExecutor, callbackExecutor); } /** * Sets access token on the wrapper. * Use to set or update token with the new value. * If you want to remove token set it to null. * * @param accessToken The token to set on the wrapper. * @return The instance of the wrapper. */ public SpotifyApi setAccessToken(String accessToken) { mAccessToken = accessToken; return this; } /** * @return The SpotifyApi instance */ public SpotifyService getService() { return mSpotifyService; } }
package kaaes.spotify.webapi.android; import com.squareup.okhttp.OkHttpClient; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.client.OkClient; /** * Creates and configures a REST adapter for Spotify Web API. * * Basic usage: * SpotifyApi wrapper = new SpotifyApi(); * * Setting access token is optional for certain endpoints * so if you know you'll only use the ones that don't require authorisation * you can skip this step: * wrapper.setAccessToken(authenticationResponse.getAccessToken()); * * SpotifyService spotify = wrapper.getService(); * * Album album = spotify.getAlbum("2dIGnmEIy1WZIcZCFSj6i8"); */ public class SpotifyApi { /** * Main Spotify Web API endpoint */ public static final String SPOTIFY_WEB_API_ENDPOINT = "https://api.spotify.com/v1"; /** * The request interceptor that will add the header with OAuth * token to every request made with the wrapper. */ private class WebApiAuthenticator implements RequestInterceptor { @Override public void intercept(RequestFacade request) { if (mAccessToken != null) { request.addHeader("Authorization", "Bearer " + mAccessToken); } } } private final SpotifyService mSpotifyService; private String mAccessToken; /** * Create instance of SpotifyApi with given executors. * * @param httpExecutor executor for http request. Cannot be null. * @param callbackExecutor executor for callbacks. If null is passed than the same * thread that created the instance is used. */ public SpotifyApi(Executor httpExecutor, Executor callbackExecutor) { mSpotifyService = init(httpExecutor, callbackExecutor); } private SpotifyService init(Executor httpExecutor, Executor callbackExecutor) { final RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.BASIC) .setClient(new OkClient(new OkHttpClient())) .setExecutors(httpExecutor, callbackExecutor) .setEndpoint(SPOTIFY_WEB_API_ENDPOINT) .setRequestInterceptor(new WebApiAuthenticator()) .build(); return restAdapter.create(SpotifyService.class); } /** * New instance of SpotifyApi, * with single thread executor both for http and callbacks. */ public SpotifyApi() { final Executor executor = Executors.newSingleThreadExecutor(); mSpotifyService = init(executor, executor); } /** * Sets access token on the wrapper. * Use to set or update token with the new value. * If you want to remove token set it to null. * * @param accessToken The token to set on the wrapper. * @return The instance of the wrapper. */ public SpotifyApi setAccessToken(String accessToken) { mAccessToken = accessToken; return this; } /** * @return The SpotifyApi instance */ public SpotifyService getService() { return mSpotifyService; } }
package main.flowstoneenergy.client; import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import main.flowstoneenergy.ModInfo; import main.flowstoneenergy.entities.EntityRobot; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; @SideOnly(Side.CLIENT) public class RenderRobot extends RenderLiving{ protected FlowstoneRobot model; public RenderRobot(FlowstoneRobot model, float par2) { super(model, par2); shadowSize = 0.5F; model = new FlowstoneRobot(); } public void renderRobot(EntityRobot robot, double x, double y, double z, float yaw, float partialTickTime) { GL11.glPushMatrix(); GL11.glTranslatef((float)x, (float)y, (float)z); GL11.glRotatef(180.0F - yaw, 0.0F, 1.0F, 0.0F); GL11.glScalef(-1.0F, -1.0F, 1.0F); model.render(robot, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F); GL11.glPopMatrix(); } @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTickTime) { super.doRender(entity, x, y, z, yaw, partialTickTime); } @Override protected ResourceLocation getEntityTexture (Entity entity){ return new ResourceLocation(ModInfo.MODID + ":textures/models/FlowstoneRobot.png"); } }
package mcjty.rftools.blocks.builder; import mcjty.lib.container.GenericContainer; import mcjty.lib.container.GenericGuiContainer; import mcjty.lib.gui.Window; import mcjty.lib.gui.widgets.Button; import mcjty.lib.gui.widgets.ChoiceLabel; import mcjty.lib.gui.widgets.EnergyBar; import mcjty.lib.gui.widgets.ImageChoiceLabel; import mcjty.rftools.RFTools; import mcjty.rftools.items.builder.GuiShapeCard; import mcjty.rftools.network.RFToolsMessages; import mcjty.typed.TypedMap; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import static mcjty.rftools.blocks.builder.BuilderTileEntity.*; public class GuiBuilder extends GenericGuiContainer<BuilderTileEntity> { private EnergyBar energyBar; private Button currentLevel; private ImageChoiceLabel anchor[] = new ImageChoiceLabel[4]; public GuiBuilder(BuilderTileEntity builderTileEntity, GenericContainer container) { super(RFTools.instance, RFToolsMessages.INSTANCE, builderTileEntity, container, RFTools.GUI_MANUAL_SHAPE, "builder"); setCurrentRF(builderTileEntity.getEnergyStored()); } @Override public void initGui() { window = new Window(this, RFToolsMessages.INSTANCE, new ResourceLocation(RFTools.MODID, "gui/builder.gui")); super.initGui(); energyBar = window.findChild("energybar"); currentLevel = window.findChild("level"); anchor[0] = window.findChild("anchor0"); anchor[1] = window.findChild("anchor1"); anchor[2] = window.findChild("anchor2"); anchor[3] = window.findChild("anchor3"); initializeFields(); setupEvents(); tileEntity.requestRfFromServer(RFTools.MODID); tileEntity.requestCurrentLevel(); } private void setupEvents() { window.addChannelEvent("cardgui", (source, params) -> openCardGui()); window.addChannelEvent("anchor", (source, params) -> selectAnchor(source.getName())); } private void initializeFields() { energyBar.setMaxValue(tileEntity.getMaxEnergyStored()); energyBar.setValue(getCurrentRF()); ((ImageChoiceLabel) window.findChild("redstone")).setCurrentChoice(tileEntity.getRSMode().ordinal()); ((ChoiceLabel) window.findChild("mode")).setChoice(MODES[tileEntity.getMode()]); ChoiceLabel rotateButton = window.findChild("rotate"); rotateButton.setChoice(String.valueOf(tileEntity.getRotate() * 90)); if (!isShapeCard()) { anchor[tileEntity.getAnchor()].setCurrentChoice(1); } ((ImageChoiceLabel)window.findChild("silent")).setCurrentChoice(tileEntity.isSilent() ? 1 : 0); ((ImageChoiceLabel)window.findChild("support")).setCurrentChoice(tileEntity.hasSupportMode() ? 1 : 0); ((ImageChoiceLabel)window.findChild("entities")).setCurrentChoice(tileEntity.hasEntityMode() ? 1 : 0); ((ImageChoiceLabel)window.findChild("loop")).setCurrentChoice(tileEntity.hasLoopMode() ? 1 : 0); ((ImageChoiceLabel)window.findChild("wait")).setCurrentChoice(tileEntity.isWaitMode() ? 1 : 0); ((ImageChoiceLabel)window.findChild("hilight")).setCurrentChoice(tileEntity.isHilightMode() ? 1 : 0); } private void openCardGui() { ItemStack cardStack = inventorySlots.getSlot(SLOT_TAB).getStack(); if (!cardStack.isEmpty()) { EntityPlayerSP player = Minecraft.getMinecraft().player; GuiShapeCard.fromTEPos = tileEntity.getPos(); GuiShapeCard.fromTEStackSlot = SLOT_TAB; GuiShapeCard.returnGui = this; player.openGui(RFTools.instance, RFTools.GUI_SHAPECARD_COMPOSER, player.getEntityWorld(), (int) player.posX, (int) player.posY, (int) player.posZ); } } private void selectAnchor(String name) { int index = name.charAt(name.length()-1)-48; updateAnchorSettings(index); sendServerCommand(RFToolsMessages.INSTANCE, CMD_SETANCHOR, TypedMap.builder().put(PARAM_ANCHOR_INDEX, index).build()); } private void updateAnchorSettings(int index) { for (int i = 0 ; i < anchor.length ; i++) { if (isShapeCard()) { anchor[i].setCurrentChoice(0); } else { anchor[i].setCurrentChoice(i == index ? 1 : 0); } } } private boolean isShapeCard() { ItemStack card = tileEntity.getStackInSlot(SLOT_TAB); return !card.isEmpty() && card.getItem() == BuilderSetup.shapeCardItem; } @Override protected void drawGuiContainerBackgroundLayer(float v, int i, int i2) { int cury = getCurrentLevelClientSide(); currentLevel.setText("Y: " + (cury == -1 ? "stop" : cury)); ItemStack card = tileEntity.getStackInSlot(SLOT_TAB); if (card.isEmpty()) { window.setFlag("!validcard"); } else if (card.getItem() == BuilderSetup.shapeCardItem) { window.setFlag("!validcard"); } else { window.setFlag("validcard"); } updateAnchorSettings(tileEntity.getAnchor()); drawWindow(); energyBar.setValue(getCurrentRF()); tileEntity.requestRfFromServer(RFTools.MODID); tileEntity.requestCurrentLevel(); } }
package net.teamio.taam.content.common; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; import net.teamio.taam.content.BaseTileEntity; import net.teamio.taam.content.IRotatable; import net.teamio.taam.conveyors.ConveyorUtil; import net.teamio.taam.conveyors.ItemWrapper; import net.teamio.taam.conveyors.api.IConveyorAwareTE; import net.teamio.taam.util.TaamUtil; import codechicken.lib.inventory.InventoryRange; import codechicken.lib.inventory.InventoryUtils; public class TileEntityChute extends BaseTileEntity implements IInventory, ISidedInventory, IFluidHandler, IConveyorAwareTE, IRotatable { public boolean isConveyorVersion = false; private ForgeDirection direction = ForgeDirection.NORTH; public TileEntityChute(boolean isConveyorVersion) { this.isConveyorVersion = isConveyorVersion; } public TileEntityChute() { this(false); } @Override public void updateEntity() { // Skip item insertion if there is a solid block / other chute above us if(isConveyorVersion || !worldObj.isSideSolid(xCoord, yCoord + 1, zCoord, ForgeDirection.DOWN, false)) { ConveyorUtil.tryInsertItemsFromWorld(this, worldObj, null, false); } } @Override protected void writePropertiesToNBT(NBTTagCompound tag) { tag.setBoolean("isConveyorVersion", isConveyorVersion); if(isConveyorVersion) { tag.setInteger("direction", direction.ordinal()); } } @Override protected void readPropertiesFromNBT(NBTTagCompound tag) { isConveyorVersion = tag.getBoolean("isConveyorVersion"); if(isConveyorVersion) { direction = ForgeDirection.getOrientation(tag.getInteger("direction")); if(direction == ForgeDirection.UP || direction == ForgeDirection.DOWN || direction == ForgeDirection.UNKNOWN) { direction = ForgeDirection.NORTH; } } } private TileEntity getTarget() { return worldObj.getTileEntity(xCoord, yCoord - 1, zCoord); } private InventoryRange getTargetRange() { IInventory inventory = getTargetInventory(); if(inventory == null) { return null; } else { return new InventoryRange(inventory, ForgeDirection.UP.ordinal()); } } private IInventory getTargetInventory() { return InventoryUtils.getInventory(worldObj, xCoord, yCoord - 1, zCoord); } private IFluidHandler getTargetFluidHandler() { TileEntity target = getTarget(); if(target instanceof IFluidHandler) { return (IFluidHandler) target; } else { return null; } } private boolean canDrop() { return TaamUtil.canDropIntoWorld(worldObj, xCoord, yCoord - 1, zCoord); } /* * IInventory implementation */ @Override public int getSizeInventory() { InventoryRange target = getTargetRange(); if(target == null) { if(canDrop()) { return 1; } else { return 0; } } else { return target.slots.length; } } @Override public ItemStack getStackInSlot(int slot) { /*InventoryRange target = getTargetRange(); if(target == null) { return null; } else { return InventoryUtils.getExtractableStack(target, target.slots[slot]); }*/ return null; } @Override public ItemStack decrStackSize(int slot, int amount) { return null; } @Override public ItemStack getStackInSlotOnClosing(int slot) { return null; } @Override public void setInventorySlotContents(int slot, ItemStack stack) { InventoryRange target = getTargetRange(); if(target == null) { if(!worldObj.isRemote && canDrop()) { EntityItem item = new EntityItem(worldObj, xCoord + 0.5, yCoord - 0.3, zCoord + 0.5, stack); item.motionX = 0; item.motionY = 0; item.motionZ = 0; worldObj.spawnEntityInWorld(item); } } else { target.inv.setInventorySlotContents(target.slots[slot], stack); } } @Override public String getInventoryName() { IInventory target = getTargetInventory(); if(target == null) { return "tile.taam.chute.name"; } else { return target.getInventoryName(); } } @Override public boolean hasCustomInventoryName() { IInventory target = getTargetInventory(); if(target == null) { return true; } else { return target.hasCustomInventoryName(); } } @Override public int getInventoryStackLimit() { IInventory target = getTargetInventory(); if(target == null) { return 64; } else { return target.getInventoryStackLimit(); } } @Override public boolean isUseableByPlayer(EntityPlayer player) { IInventory target = getTargetInventory(); if(target == null) { return false; } else { return target.isUseableByPlayer(player); } } @Override public void openInventory() { IInventory target = getTargetInventory(); if(target != null) { target.openInventory(); } } @Override public void closeInventory() { IInventory target = getTargetInventory(); if(target != null) { target.closeInventory(); } } @Override public boolean isItemValidForSlot(int slot, ItemStack stack) { InventoryRange target = getTargetRange(); if(target == null) { return canDrop(); } else { return target.canInsertItem(target.slots[slot], stack); } } /* * ISidedInventory implementation */ @Override public int[] getAccessibleSlotsFromSide(int side) { if(side != ForgeDirection.UP.ordinal()) { return new int[0]; } InventoryRange target = getTargetRange(); if(target == null) { if(canDrop()) { return new int[] {0}; } else { return new int[0]; } } else { // We reorder the slots from 0 onwards, then convert back later. int[] slots = new int[target.slots.length]; for(int i = 0; i < slots.length; i++) { slots[i] = i; } return slots; } } @Override public boolean canInsertItem(int slot, ItemStack stack, int side) { if(side != ForgeDirection.UP.ordinal()) { return false; } InventoryRange target = getTargetRange(); if(target == null) { return canDrop(); } else { return target.canInsertItem(target.slots[slot], stack); } } @Override public boolean canExtractItem(int slot, ItemStack stack, int side) { /*if(side != ForgeDirection.UP.ordinal()) { return false; } ISidedInventory target = getTargetSidedInventory(); if(target == null) { IInventory invTarget = getTargetInventory(); if(invTarget != null) { return invTarget.isItemValidForSlot(slot, stack); } } else { return target.canExtractItem(slot, stack, side); }*/ return false; } /* * IFluidHandler implementation */ @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { if(from != ForgeDirection.UP) { return 0; } IFluidHandler target = getTargetFluidHandler(); if(target != null ) { return target.fill(from, resource, doFill); } else { return 0; } } @Override public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { return null; } @Override public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { return null; } @Override public boolean canFill(ForgeDirection from, Fluid fluid) { if(from != ForgeDirection.UP) { return false; } IFluidHandler target = getTargetFluidHandler(); if(target != null ) { return target.canFill(from, fluid); } else { return false; } } @Override public boolean canDrain(ForgeDirection from, Fluid fluid) { return false; } @Override public FluidTankInfo[] getTankInfo(ForgeDirection from) { if(from != ForgeDirection.UP) { return new FluidTankInfo[0]; } IFluidHandler target = getTargetFluidHandler(); if(target != null ) { return target.getTankInfo(from); } else { return new FluidTankInfo[0]; } } /* * IConveyorAwareTE implementation */ @Override public boolean canSlotMove(int slot) { return false; } @Override public boolean isSlotAvailable(int slot) { return true; } @Override public int getMovementProgress(int slot) { return 0; } @Override public byte getSpeedsteps() { return 0; } @Override public ItemWrapper getSlot(int slot) { return ItemWrapper.EMPTY; } @Override public int posX() { return xCoord; } @Override public int posY() { return yCoord; } @Override public int posZ() { return zCoord; } @Override public int insertItemAt(ItemStack stack, int slot) { InventoryRange target = getTargetRange(); if(target == null) { if(!worldObj.isRemote && canDrop()) { EntityItem item = new EntityItem(worldObj, xCoord + 0.5, yCoord - 0.3, zCoord + 0.5, stack); item.motionX = 0; item.motionY = 0; item.motionZ = 0; worldObj.spawnEntityInWorld(item); return stack.stackSize; } return 0; } else { return stack.stackSize - InventoryUtils.insertItem(target, stack, false); } } @Override public ForgeDirection getMovementDirection() { return ForgeDirection.DOWN; } @Override public boolean shouldRenderItemsDefault() { return false; } @Override public double getInsertMaxY() { if(isConveyorVersion) { return 0.9; } else { return 1.3; } } @Override public double getInsertMinY() { if(isConveyorVersion) { return 0.3; } else { return 0.9; } } /* * IRotatable Implementation */ @Override public ForgeDirection getFacingDirection() { return direction; } @Override public ForgeDirection getNextFacingDirection() { return direction.getRotation(ForgeDirection.UP); } @Override public void setFacingDirection(ForgeDirection direction) { if(isConveyorVersion) { this.direction = direction; if(direction == ForgeDirection.UP || direction == ForgeDirection.DOWN || direction == ForgeDirection.UNKNOWN) { this.direction = ForgeDirection.NORTH; } updateState(); } } public ForgeDirection getNextSlot(int slot) { return null; } }
package me.legrange.panstamp.device; import java.util.List; import java.util.Map; /** * A device library implementation for loading device definitions from the file system. * @author gideon */ public final class FileLibrary implements DeviceLibrary { FileLibrary(String path) { this.path = path; } @Override public Device findDevice(int manufacturedID, int productId) throws DeviceNotFoundException, ParseException { if (devices == null) { List<Device> all = XMLParser.parse(path); for (Device dev : all) { devices.put(makeId(dev.getDeveloper().getId(), dev.getId()), dev); } } Device dev = devices.get(makeId(manufacturedID, productId)); if (dev == null) { throw new DeviceNotFoundException(String.format("Could not find device definition for manufacturer/product %d/%d", manufacturedID, productId)); } return dev; } private String makeId(int manufacturedID, int productId) { return String.format("%d/%d", manufacturedID, productId); } private final String path; private Map<String,Device> devices; }
package cn.webfuse.common.kit; import com.sun.crypto.provider.AESKeyGenerator; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.HmacAlgorithms; import org.apache.commons.codec.digest.HmacUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import javax.crypto.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; public class CryptoKits { /** * 32MD5 */ public String md5(String input) { return DigestUtils.md5Hex(input); } /** * SHA1 */ public String sha1(String input) { return DigestUtils.sha1Hex(input); } /** * SHA256 */ public String sha256(String input) { return DigestUtils.sha256Hex(input); } /** * SHA384 */ public String sha384(String input) { return DigestUtils.sha384Hex(input); } /** * SHA512 */ public String sha512(String input) { return DigestUtils.sha512Hex(input); } /** * HmacMD5 * * @param input * @param key * @return Hex */ public String hmacMD5(String input, String key) { byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_MD5, key).hmac(input); return EncodeKits.encodeHex(hmac); } /** * HmacSHA1 * * @param input * @param key * @return Hex */ public String hmacSHA1(String input, String key) { byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, key).hmac(input); return EncodeKits.encodeHex(hmac); } /** * HmacSHA224 * * @param input * @param key * @return Hex */ public static String hmacSHA224(String input, String key) { byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_224, key).hmac(input); return EncodeKits.encodeHex(hmac); } /** * HmacSHA256 * * @param input * @param key * @return Hex */ public static String hmac256(String input, String key) { byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmac(input); return EncodeKits.encodeHex(hmac); } /** * HmacSHA384 * * @param input * @param key * @return Hex */ public static String hmac384(String input, String key) { byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_384, key).hmac(input); return EncodeKits.encodeHex(hmac); } /** * HmacSHA512 * * @param input * @param key * @return Hex */ public static String hmac512(String input, String key) { byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_512, key).hmac(input); return EncodeKits.encodeHex(hmac); } /** * DES * * @param input * @param key * @return DES */ public static String encryptDES(String input, String key) { try { DESKeySpec keySpec = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherData = cipher.doFinal(input.getBytes()); return EncodeKits.encodeBase64(cipherData); } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); throw ExceptionKits.unchecked(e); } } /** * DES * * @param input * @param key * @return DES */ public static String decryptDES(String input, String key) { try { DESKeySpec keySpec = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] cipherData = cipher.doFinal(input.getBytes()); return new String(cipherData); } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); throw ExceptionKits.unchecked(e); } } /** * AES * * @param input * @param key * @return AES */ public static String encryptAES(String input, String key) { try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES")); byte[] bytes = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8)); return EncodeKits.encodeBase64(bytes); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); throw ExceptionKits.unchecked(e); } } /** * AES * * @param input * @param key * @return AES */ public static String decryptAES(String input, String key) { try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES")); byte[] bytes = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8)); return new String(bytes); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); throw ExceptionKits.unchecked(e); } } }
package me.rkfg.xmpp.bot.plugins.doto.json; import com.fasterxml.jackson.annotation.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) public class Game { @JsonProperty("players") private List<Player> players = new ArrayList<>(); @JsonProperty("radiant_team") private TeamInfo radiantTeam; @JsonProperty("dire_team") private TeamInfo direTeam; @JsonProperty("lobby_id") private Long lobbyId; @JsonProperty("match_id") private Long matchId; @JsonProperty("spectators") private Integer spectators; @JsonProperty("league_id") private Integer leagueId; @JsonProperty("stream_delay_s") private Integer streamDelayS; @JsonProperty("radiant_series_wins") private Integer radiantSeriesWins; @JsonProperty("dire_series_wins") private Integer direSeriesWins; @JsonProperty("series_type") private Integer seriesType; @JsonProperty("league_tier") private Integer leagueTier; @JsonProperty("scoreboard") private Scoreboard scoreboard; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<>(); @JsonProperty("players") public List<Player> getPlayers() { return players; } @JsonProperty("players") public void setPlayers(List<Player> players) { this.players = players; } @JsonProperty("radiant_team") public TeamInfo getRadiantTeam() { return radiantTeam; } @JsonProperty("radiant_team") public void setRadiantTeam(TeamInfo radiantTeam) { this.radiantTeam = radiantTeam; } @JsonProperty("dire_team") public TeamInfo getDireTeam() { return direTeam; } @JsonProperty("dire_team") public void setDireTeam(TeamInfo direTeam) { this.direTeam = direTeam; } @JsonProperty("lobby_id") public Long getLobbyId() { return lobbyId; } @JsonProperty("lobby_id") public void setLobbyId(Long lobbyId) { this.lobbyId = lobbyId; } @JsonProperty("match_id") public Long getMatchId() { return matchId; } @JsonProperty("match_id") public void setMatchId(Long matchId) { this.matchId = matchId; } @JsonProperty("spectators") public Integer getSpectators() { return spectators; } @JsonProperty("spectators") public void setSpectators(Integer spectators) { this.spectators = spectators; } @JsonProperty("league_id") public Integer getLeagueId() { return leagueId; } @JsonProperty("league_id") public void setLeagueId(Integer leagueId) { this.leagueId = leagueId; } @JsonProperty("stream_delay_s") public Integer getStreamDelayS() { return streamDelayS; } @JsonProperty("stream_delay_s") public void setStreamDelayS(Integer streamDelayS) { this.streamDelayS = streamDelayS; } @JsonProperty("radiant_series_wins") public Integer getRadiantSeriesWins() { return radiantSeriesWins; } @JsonProperty("radiant_series_wins") public void setRadiantSeriesWins(Integer radiantSeriesWins) { this.radiantSeriesWins = radiantSeriesWins; } @JsonProperty("dire_series_wins") public Integer getDireSeriesWins() { return direSeriesWins; } @JsonProperty("dire_series_wins") public void setDireSeriesWins(Integer direSeriesWins) { this.direSeriesWins = direSeriesWins; } @JsonProperty("series_type") public Integer getSeriesType() { return seriesType; } @JsonProperty("series_type") public void setSeriesType(Integer seriesType) { this.seriesType = seriesType; } @JsonProperty("league_tier") public Integer getLeagueTier() { return leagueTier; } @JsonProperty("league_tier") public void setLeagueTier(Integer leagueTier) { this.leagueTier = leagueTier; } @JsonProperty("scoreboard") public Scoreboard getScoreboard() { return scoreboard; } @JsonProperty("scoreboard") public void setScoreboard(Scoreboard scoreboard) { this.scoreboard = scoreboard; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public boolean isValid() { return scoreboard != null && scoreboard.isValid(); } }
package mho.wheels.iterables; import mho.wheels.math.BinaryFraction; import mho.wheels.math.MathUtils; import mho.wheels.numberUtils.BigDecimalUtils; import mho.wheels.numberUtils.FloatingPointUtils; import mho.wheels.numberUtils.IntegerUtils; import mho.wheels.ordering.Ordering; import mho.wheels.structures.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.function.Function; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; /** * An {@code ExhaustiveProvider} produces {@code Iterable}s that generate some set of values in a specified order. * There is only a single instance of this class. */ public final strictfp class ExhaustiveProvider extends IterableProvider { /** * The single instance of this class. */ public static final @NotNull ExhaustiveProvider INSTANCE = new ExhaustiveProvider(); /** * Disallow instantiation */ private ExhaustiveProvider() {} /** * An {@link Iterable} that generates both {@link boolean}s. Does not support removal. * * Length is 2 */ @Override public @NotNull Iterable<Boolean> booleans() { return new NoRemoveIterable<>(Arrays.asList(false, true)); } /** * An {@code Iterable} that generates all {@link Ordering}s in increasing order. Does not support removal. * * Length is 3 */ @Override public @NotNull Iterable<Ordering> orderingsIncreasing() { return new NoRemoveIterable<>(Arrays.asList(LT, EQ, GT)); } /** * An {@code Iterable} that generates all {@code Ordering}s. Does not support removal. * * Length is 3 */ @Override public @NotNull Iterable<Ordering> orderings() { return new NoRemoveIterable<>(Arrays.asList(EQ, LT, GT)); } /** * An {@code Iterable} that generates all {@link RoundingMode}s. Does not support removal. * * Length is 8 */ @Override public @NotNull Iterable<RoundingMode> roundingModes() { return new NoRemoveIterable<>(Arrays.asList( RoundingMode.UNNECESSARY, RoundingMode.UP, RoundingMode.DOWN, RoundingMode.CEILING, RoundingMode.FLOOR, RoundingMode.HALF_UP, RoundingMode.HALF_DOWN, RoundingMode.HALF_EVEN )); } /** * Returns an unmodifiable version of a list. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is finite.</li> * </ul> * * Length is |{@code xs}| * * @param xs a {@code List} * @param <T> the type of {@code xs}'s elements * @return an unmodifiable version of {@code xs} */ @Override public @NotNull <T> Iterable<T> uniformSample(@NotNull List<T> xs) { return new NoRemoveIterable<>(xs); } /** * Turns a {@code String} into an {@code Iterable} of {@code Character}s. Does not support removal. * * <ul> * <li>{@code s} cannot be null.</li> * <li>The result is finite.</li> * </ul> * * Length is |{@code s}| * * @param s a {@code String} * @return the {@code Character}s in {@code s} */ @Override public @NotNull Iterable<Character> uniformSample(@NotNull String s) { return fromString(s); } /** * An {@code Iterable} that generates all {@link Byte}s in increasing order. Does not support removal. * * Length is 2<sup>8</sup> = 256 */ @Override public @NotNull Iterable<Byte> bytesIncreasing() { return IterableUtils.rangeUp(Byte.MIN_VALUE); } /** * An {@code Iterable} that generates all {@link Short}s in increasing order. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 */ @Override public @NotNull Iterable<Short> shortsIncreasing() { return IterableUtils.rangeUp(Short.MIN_VALUE); } /** * An {@code Iterable} that generates all {@link Integer}s in increasing order. Does not support removal. * * Length is 2<sup>32</sup> = 4,294,967,296 */ @Override public @NotNull Iterable<Integer> integersIncreasing() { return IterableUtils.rangeUp(Integer.MIN_VALUE); } /** * An {@code Iterable} that generates all {@link Long}s in increasing order. Does not support removal. * * Length is 2<sup>64</sup> = 18,446,744,073,709,551,616 */ @Override public @NotNull Iterable<Long> longsIncreasing() { return IterableUtils.rangeUp(Long.MIN_VALUE); } @Override public @NotNull Iterable<Byte> positiveBytes() { return IterableUtils.rangeUp((byte) 1); } @Override public @NotNull Iterable<Short> positiveShorts() { return IterableUtils.rangeUp((short) 1); } @Override public @NotNull Iterable<Integer> positiveIntegers() { return IterableUtils.rangeUp(1); } @Override public @NotNull Iterable<Long> positiveLongs() { return IterableUtils.rangeUp(1L); } /** * An {@code Iterable} that generates all positive {@link BigInteger}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> positiveBigIntegers() { return IterableUtils.rangeUp(BigInteger.ONE); } /** * An {@code Iterable} that generates all negative {@code Byte}s. Does not support removal. * * Length is 2<sup>7</sup> = 128 */ @Override public @NotNull Iterable<Byte> negativeBytes() { return IterableUtils.rangeBy((byte) -1, (byte) -1); } /** * An {@code Iterable} that generates all negative {@code Short}s. Does not support removal. * * Length is 2<sup>15</sup> = 32,768 */ @Override public @NotNull Iterable<Short> negativeShorts() { return IterableUtils.rangeBy((short) -1, (short) -1); } /** * An {@code Iterable} that generates all negative {@code Integer}s. Does not support removal. * * Length is 2<sup>31</sup> = 2,147,483,648 */ @Override public @NotNull Iterable<Integer> negativeIntegers() { return IterableUtils.rangeBy(-1, -1); } /** * An {@code Iterable} that generates all negative {@code Long}s. Does not support removal. * * Length is 2<sup>63</sup> = 9,223,372,036,854,775,808 */ @Override public @NotNull Iterable<Long> negativeLongs() { return IterableUtils.rangeBy(-1L, -1L); } /** * An {@code Iterable} that generates all negative {@code BigInteger}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> negativeBigIntegers() { return IterableUtils.rangeBy(IntegerUtils.NEGATIVE_ONE, IntegerUtils.NEGATIVE_ONE); } @Override public @NotNull Iterable<Byte> nonzeroBytes() { return mux(Arrays.asList(positiveBytes(), negativeBytes())); } @Override public @NotNull Iterable<Short> nonzeroShorts() { return mux(Arrays.asList(positiveShorts(), negativeShorts())); } @Override public @NotNull Iterable<Integer> nonzeroIntegers() { return mux(Arrays.asList(positiveIntegers(), negativeIntegers())); } @Override public @NotNull Iterable<Long> nonzeroLongs() { return mux(Arrays.asList(positiveLongs(), negativeLongs())); } /** * An {@code Iterable} that generates all nonzero {@code BigInteger}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> nonzeroBigIntegers() { return mux(Arrays.asList(positiveBigIntegers(), negativeBigIntegers())); } /** * An {@code Iterable} that generates all natural {@code Byte}s. Does not support removal. * * Length is 2<sup>7</sup> = 128 */ @Override public @NotNull Iterable<Byte> naturalBytes() { return IterableUtils.rangeUp((byte) 0); } /** * An {@code Iterable} that generates all natural {@code Short}s (including 0). Does not support removal. * * Length is 2<sup>15</sup> = 32,768 */ @Override public @NotNull Iterable<Short> naturalShorts() { return IterableUtils.rangeUp((short) 0); } /** * An {@code Iterable} that generates all natural {@code Integer}s (including 0). Does not support removal. * * Length is 2<sup>31</sup> = 2,147,483,648 */ @Override public @NotNull Iterable<Integer> naturalIntegers() { return IterableUtils.rangeUp(0); } /** * An {@code Iterable} that generates all natural {@code Long}s (including 0). Does not support removal. * * Length is 2<sup>63</sup> = 9,223,372,036,854,775,808 */ @Override public @NotNull Iterable<Long> naturalLongs() { return IterableUtils.rangeUp(0L); } /** * An {@code Iterable} that generates all natural {@code BigInteger}s (including 0). Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> naturalBigIntegers() { return rangeUp(BigInteger.ZERO); } /** * An {@code Iterable} that generates all {@code Byte}s. Does not support removal. * * Length is 2<sup>8</sup> = 128 */ @Override public @NotNull Iterable<Byte> bytes() { return cons((byte) 0, nonzeroBytes()); } /** * An {@code Iterable} that generates all {@code Short}s. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 */ @Override public @NotNull Iterable<Short> shorts() { return cons((short) 0, nonzeroShorts()); } /** * An {@code Iterable} that generates all {@code Integer}s. Does not support removal. * * Length is 2<sup>32</sup> = 4,294,967,296 */ @Override public @NotNull Iterable<Integer> integers() { return cons(0, nonzeroIntegers()); } /** * An {@code Iterable} that generates all {@code Long}s. Does not support removal. * * Length is 2<sup>64</sup> = 18,446,744,073,709,551,616 */ @Override public @NotNull Iterable<Long> longs() { return cons(0L, nonzeroLongs()); } /** * An {@code Iterable} that generates all {@code BigInteger}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> bigIntegers() { return cons(BigInteger.ZERO, nonzeroBigIntegers()); } /** * An {@code Iterable} that generates all ASCII {@link Character}s in increasing order. Does not support * removal. * * Length is 2<sup>7</sup> = 128 */ @Override public @NotNull Iterable<Character> asciiCharactersIncreasing() { return range((char) 0, (char) 127); } /** * An {@code Iterable} that generates all ASCII {@code Character}s in an order which places "friendly" characters * first. Does not support removal. * * Length is 2<sup>7</sup> = 128 */ @Override public @NotNull Iterable<Character> asciiCharacters() { return concat(Arrays.asList( range('a', 'z'), range('A', 'Z'), range('0', '9'), range('!', '/'), // printable non-alphanumeric ASCII... range(':', '@'), range('[', '`'), range('{', '~'), Collections.singleton(' '), range((char) 0, (char) 31), // non-printable and whitespace ASCII Collections.singleton((char) 127) // DEL )); } /** * An {@code Iterable} that generates all {@code Character}s in increasing order. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 */ @Override public @NotNull Iterable<Character> charactersIncreasing() { return range(Character.MIN_VALUE, Character.MAX_VALUE); } /** * An {@code Iterable} that generates all {@code Character}s in an order which places "friendly" characters * first. Does not support removal. * * Length is 2<sup>16</sup> = 65,536 */ @Override public @NotNull Iterable<Character> characters() { return concat(Arrays.asList( range('a', 'z'), range('A', 'Z'), range('0', '9'), range('!', '/'), // printable non-alphanumeric ASCII... range(':', '@'), range('[', '`'), range('{', '~'), Collections.singleton(' '), range((char) 0, (char) 31), // non-printable and whitespace ASCII rangeUp((char) 127) // DEL and non-ASCII )); } @Override public @NotNull Iterable<Byte> rangeUp(byte a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return cons( (byte) 0, mux(Arrays.asList(IterableUtils.rangeUp((byte) 1), IterableUtils.rangeBy((byte) -1, (byte) -1, a))) ); } } @Override public @NotNull Iterable<Short> rangeUp(short a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return cons( (short) 0, mux( Arrays.asList( IterableUtils.rangeUp((short) 1), IterableUtils.rangeBy((short) -1, (short) -1, a) ) ) ); } } @Override public @NotNull Iterable<Integer> rangeUp(int a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return cons(0, mux(Arrays.asList(IterableUtils.rangeUp(1), IterableUtils.rangeBy(-1, -1, a)))); } } @Override public @NotNull Iterable<Long> rangeUp(long a) { if (a >= 0) { return IterableUtils.rangeUp(a); } else { return cons(0L, mux(Arrays.asList(IterableUtils.rangeUp(1L), IterableUtils.rangeBy(-1L, -1L, a)))); } } /** * An {@code Iterable} that generates all {@code BigIntegers}s greater than or equal to {@code a}. Does not support * removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BigInteger}s.</li> * </ul> * * Length is infinite * * @param a the inclusive lower bound of the generated elements * @return {@code BigInteger}s greater than or equal to {@code a} */ @Override public @NotNull Iterable<BigInteger> rangeUp(@NotNull BigInteger a) { if (a.signum() != -1) { return IterableUtils.rangeUp(a); } else { return cons( BigInteger.ZERO, mux( Arrays.asList( IterableUtils.rangeUp(BigInteger.ONE), IterableUtils.rangeBy(IntegerUtils.NEGATIVE_ONE, IntegerUtils.NEGATIVE_ONE, a) ) ) ); } } @Override public @NotNull Iterable<Character> rangeUp(char a) { return IterableUtils.rangeUp(a); } /** * An {@code Iterable} that generates all {@code Byte}s less than or equal to {@code a}. Does not support removal. * * <ul> * <li>{@code a} may be any {@code byte}.</li> * <li>The result is a non-removable {@code Iterable} containing {@code Byte}s.</li> * </ul> * * Length is {@code a}+2<sup>7</sup>+1 * * @param a the inclusive upper bound of the generated elements * @return {@code Byte}s less than or equal to {@code a} */ @Override public @NotNull Iterable<Byte> rangeDown(byte a) { if (a <= 0) { return IterableUtils.rangeBy(a, (byte) -1); } else { return cons( (byte) 0, mux(Arrays.asList(IterableUtils.range((byte) 1, a), IterableUtils.rangeBy((byte) -1, (byte) -1))) ); } } /** * An {@code Iterable} that generates all {@code Short}s less than or equal to {@code a}. Does not support removal. * * <ul> * <li>{@code a} may be any {@code short}.</li> * <li>The result is a non-removable {@code Iterable} containing {@code Short}s.</li> * </ul> * * Length is {@code a}+2<sup>15</sup>+1 * * @param a the inclusive upper bound of the generated elements * @return {@code Short}s less than or equal to {@code a} */ @Override public @NotNull Iterable<Short> rangeDown(short a) { if (a <= 0) { return IterableUtils.rangeBy(a, (short) -1); } else { return cons( (short) 0, mux( Arrays.asList( IterableUtils.range((short) 1, a), IterableUtils.rangeBy((short) -1, (short) -1) ) ) ); } } /** * An {@code Iterable} that generates all {@code Integer}s less than or equal to {@code a}. Does not support * removal. * * <ul> * <li>{@code a} may be any {@code int}.</li> * <li>The result is a non-removable {@code Iterable} containing {@code Integer}s.</li> * </ul> * * Length is {@code a}+2<sup>31</sup>+1 * * @param a the inclusive upper bound of the generated elements * @return {@code Integer}s less than or equal to {@code a} */ @Override public @NotNull Iterable<Integer> rangeDown(int a) { if (a <= 0) { return IterableUtils.rangeBy(a, -1); } else { return cons(0, mux(Arrays.asList(IterableUtils.range(1, a), IterableUtils.rangeBy(-1, -1)))); } } /** * An {@code Iterable} that generates all {@code Long}s less than or equal to {@code a}. Does not support removal. * * <ul> * <li>{@code a} may be any {@code long}.</li> * <li>The result is a non-removable {@code Iterable} containing {@code Long}s.</li> * </ul> * * Length is {@code a}+2<sup>63</sup>+1 * * @param a the inclusive upper bound of the generated elements * @return {@code Long}s less than or equal to {@code a} */ @Override public @NotNull Iterable<Long> rangeDown(long a) { if (a <= 0) { return IterableUtils.rangeBy(a, -1L); } else { return cons(0L, mux(Arrays.asList(IterableUtils.range(1L, a), IterableUtils.rangeBy(-1L, -1L)))); } } /** * An {@code Iterable} that generates all {@code BigInteger}s less than or equal to {@code a}. Does not support * removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BigInteger}s.</li> * </ul> * * Length is infinite * * @param a the inclusive upper bound of the generated elements * @return {@code BigInteger}s less than or equal to {@code a} */ @Override public @NotNull Iterable<BigInteger> rangeDown(@NotNull BigInteger a) { if (a.signum() != 1) { return IterableUtils.rangeBy(a, IntegerUtils.NEGATIVE_ONE); } else { return cons( BigInteger.ZERO, mux( Arrays.asList( IterableUtils.range(BigInteger.ONE, a), IterableUtils.rangeBy(IntegerUtils.NEGATIVE_ONE, IntegerUtils.NEGATIVE_ONE) ) ) ); } } /** * An {@code Iterable} that generates all {@code Character}s less than or equal to {@code a}. Does not support * removal. * * <ul> * <li>{@code a} may be any {@code char}.</li> * <li>The result is a non-removable {@code Iterable} containing {@code Character}s.</li> * </ul> * * Length is {@code a}+1 * * @param a the inclusive upper bound of the generated elements * @return {@code Character}s less than or equal to {@code a} */ @Override public @NotNull Iterable<Character> rangeDown(char a) { return IterableUtils.range('\0', a); } @Override public @NotNull Iterable<Byte> range(byte a, byte b) { if (a > b) return Collections.emptyList(); if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, (byte) -1, a); } else { return cons( (byte) 0, mux( Arrays.asList( IterableUtils.range((byte) 1, b), IterableUtils.rangeBy((byte) -1, (byte) -1, a) ) ) ); } } @Override public @NotNull Iterable<Short> range(short a, short b) { if (a > b) return Collections.emptyList(); if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, (short) -1, a); } else { return cons( (short) 0, mux( Arrays.asList( IterableUtils.range((short) 1, b), IterableUtils.rangeBy((short) -1, (short) -1, a) ) ) ); } } @Override public @NotNull Iterable<Integer> range(int a, int b) { if (a > b) return Collections.emptyList(); if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, -1, a); } else { return cons(0, mux(Arrays.asList(IterableUtils.range(1, b), IterableUtils.rangeBy(-1, -1, a)))); } } @Override public @NotNull Iterable<Long> range(long a, long b) { if (a > b) return Collections.emptyList(); if (a >= 0 && b >= 0) { return IterableUtils.range(a, b); } else if (a < 0 && b < 0) { return IterableUtils.rangeBy(b, (byte) -1, a); } else { return cons(0L, mux(Arrays.asList(IterableUtils.range(1L, b), IterableUtils.rangeBy(-1L, -1L, a)))); } } @Override public @NotNull Iterable<BigInteger> range(@NotNull BigInteger a, @NotNull BigInteger b) { if (gt(a, b)) return Collections.emptyList(); if (a.signum() != -1 && b.signum() != -1) { return IterableUtils.range(a, b); } else if (a.signum() == -1 && b.signum() == -1) { return IterableUtils.rangeBy(b, IntegerUtils.NEGATIVE_ONE, a); } else { return cons( BigInteger.ZERO, mux( Arrays.asList( IterableUtils.range(BigInteger.ONE, b), IterableUtils.rangeBy(IntegerUtils.NEGATIVE_ONE, IntegerUtils.NEGATIVE_ONE, a) ) ) ); } } @Override public @NotNull Iterable<Character> range(char a, char b) { return IterableUtils.range(a, b); } /** * An {@code Iterable} that generates all positive {@link BinaryFraction}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BinaryFraction> positiveBinaryFractions() { return map( p -> BinaryFraction.of(p.a.shiftLeft(1).add(BigInteger.ONE), p.b), pairsLogarithmicOrder(naturalBigIntegers(), integers()) ); } /** * An {@code Iterable} that generates all negative {@link BinaryFraction}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BinaryFraction> negativeBinaryFractions() { return map(BinaryFraction::negate, positiveBinaryFractions()); } /** * An {@code Iterable} that generates all nonzero {@link BinaryFraction}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BinaryFraction> nonzeroBinaryFractions() { return mux(Arrays.asList(positiveBinaryFractions(), negativeBinaryFractions())); } /** * An {@code Iterable} that generates all {@link BinaryFraction}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BinaryFraction> binaryFractions() { return cons(BinaryFraction.ZERO, nonzeroBinaryFractions()); } /** * An {@code Iterable} that generates all {@code BinaryFraction}s greater than or equal to {@code a}. Does not * support removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BinaryFraction}s.</li> * </ul> * * Length is infinite * * @param a the inclusive lower bound of the generated elements * @return {@code BinaryFraction}s greater than or equal to {@code a} */ @Override public @NotNull Iterable<BinaryFraction> rangeUp(@NotNull BinaryFraction a) { return cons(a, map(bf -> bf.shiftLeft(a.getExponent()).add(a), positiveBinaryFractions())); } /** * An {@code Iterable} that generates all {@code BinaryFraction}s less than or equal to {@code a}. Does not * support removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BinaryFraction}s.</li> * </ul> * * Length is infinite * * @param a the inclusive upper bound of the generated elements * @return {@code BinaryFraction}s less than or equal to {@code a} */ @Override public @NotNull Iterable<BinaryFraction> rangeDown(@NotNull BinaryFraction a) { return cons(a, map(bf -> a.subtract(bf.shiftLeft(a.getExponent())), positiveBinaryFractions())); } /** * An {@code Iterable} that generates all {@code BinaryFraction}s between 0 and 1, exclusive. Does not support * removal. * * <ul> * <li>The result is a non-removable {@code Iterable} containing {@code BinaryFraction}s greater than 0 and less * than 1.</li> * </ul> * * Length is infinite */ private static @NotNull Iterable<BinaryFraction> positiveBinaryFractionsLessThanOne() { return concatMap( e -> map( i -> BinaryFraction.of(i.shiftLeft(1).add(BigInteger.ONE), -e), IterableUtils.range(BigInteger.ZERO, BigInteger.ONE.shiftLeft(e - 1).subtract(BigInteger.ONE)) ), IterableUtils.rangeUp(1) ); } /** * An {@code Iterable} that generates all {@code BinaryFraction}s between {@code a} and {@code b}, inclusive. If * {@code a}{@literal >}{@code b}, an empty {@code Iterable} is returned. Does not support removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>{@code b} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BinaryFraction}s.</li> * </ul> * * Length is 0 if a>b, 1 if a=b, and infinite otherwise * * @param a the inclusive lower bound of the generated elements * @param b the inclusive upper bound of the generated elements * @return {@code BinaryFraction}s between {@code a} and {@code b}, inclusive */ @Override public @NotNull Iterable<BinaryFraction> range(@NotNull BinaryFraction a, @NotNull BinaryFraction b) { switch (compare(a, b)) { case GT: return Collections.emptyList(); case EQ: return Collections.singletonList(a); case LT: BinaryFraction difference = b.subtract(a); int blockExponent = difference.getExponent(); BigInteger blockCount = difference.getMantissa(); return concat( map( i -> BinaryFraction.ONE.shiftLeft(blockExponent).multiply(BinaryFraction.of(i)).add(a), IterableUtils.range(BigInteger.ZERO, blockCount) ), concatMap( bf -> map( j -> bf.add(BinaryFraction.of(j)).shiftLeft(blockExponent).add(a), IterableUtils.range(BigInteger.ZERO, blockCount.subtract(BigInteger.ONE)) ), positiveBinaryFractionsLessThanOne() ) ); default: throw new IllegalStateException("unreachable"); } } /** * An {@code Iterable} that generates all possible positive {@code float} mantissas. A {@code float}'s mantissa is * the unique odd integer that, when multiplied by a power of 2, equals the {@code float}. Does not support * removal. * * Length is 2<sup>23</sup> = 8,388,608 */ private static final @NotNull Iterable<Integer> FLOAT_MANTISSAS = IterableUtils.rangeBy( 1, 2, 1 << (FloatingPointUtils.FLOAT_FRACTION_WIDTH + 1) ); private static final @NotNull Iterable<Integer> FLOAT_EXPONENTS = cons( 0, mux( Arrays.asList(INSTANCE.range(1, Float.MAX_EXPONENT), IterableUtils.rangeBy(-1, -1, FloatingPointUtils.MIN_SUBNORMAL_FLOAT_EXPONENT)) ) ); private static @NotNull Iterable<Float> positiveOrdinaryFloats() { return optionalMap( p -> FloatingPointUtils.floatFromMantissaAndExponent(p.a, p.b), INSTANCE.pairs(FLOAT_MANTISSAS, FLOAT_EXPONENTS) ); } private static @NotNull Iterable<Float> negativeOrdinaryFloats() { return map(f -> -f, positiveOrdinaryFloats()); } private static @NotNull Iterable<Float> nonzeroOrdinaryFloats() { return mux(Arrays.asList(positiveOrdinaryFloats(), negativeOrdinaryFloats())); } @Override public @NotNull Iterable<Float> positiveFloats() { return cons(Float.POSITIVE_INFINITY, positiveOrdinaryFloats()); } @Override public @NotNull Iterable<Float> negativeFloats() { return cons(Float.NEGATIVE_INFINITY, negativeOrdinaryFloats()); } @Override public @NotNull Iterable<Float> nonzeroFloats() { return concat( Arrays.asList(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), nonzeroOrdinaryFloats() ); } @Override public @NotNull Iterable<Float> floats() { return concat( Arrays.asList(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.0f, -0.0f), nonzeroOrdinaryFloats() ); } /** * An {@code Iterable} that generates all possible positive {@code double} mantissas. A {@code double}'s mantissa * is the unique odd integer that, when multiplied by a power of 2, equals the {@code double}. Does not support * removal. * * Length is 2<sup>52</sup> = 4,503,599,627,370,496 */ private static final @NotNull Iterable<Long> DOUBLE_MANTISSAS = IterableUtils.rangeBy( 1L, 2, 1L << (FloatingPointUtils.DOUBLE_FRACTION_WIDTH + 1) ); private static final @NotNull Iterable<Integer> DOUBLE_EXPONENTS = cons( 0, mux( Arrays.asList(INSTANCE.range(1, Double.MAX_EXPONENT), IterableUtils.rangeBy(-1, -1, FloatingPointUtils.MIN_SUBNORMAL_DOUBLE_EXPONENT)) ) ); private static @NotNull Iterable<Double> positiveOrdinaryDoubles() { return optionalMap( p -> FloatingPointUtils.doubleFromMantissaAndExponent(p.a, p.b), INSTANCE.pairs(DOUBLE_MANTISSAS, DOUBLE_EXPONENTS) ); } private static @NotNull Iterable<Double> negativeOrdinaryDoubles() { return map(d -> -d, positiveOrdinaryDoubles()); } private static @NotNull Iterable<Double> nonzeroOrdinaryDoubles() { return mux(Arrays.asList(positiveOrdinaryDoubles(), negativeOrdinaryDoubles())); } @Override public @NotNull Iterable<Double> positiveDoubles() { return cons(Double.POSITIVE_INFINITY, positiveOrdinaryDoubles()); } @Override public @NotNull Iterable<Double> negativeDoubles() { return cons(Double.NEGATIVE_INFINITY, negativeOrdinaryDoubles()); } @Override public @NotNull Iterable<Double> nonzeroDoubles() { return concat( Arrays.asList(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), nonzeroOrdinaryDoubles() ); } @Override public @NotNull Iterable<Double> doubles() { return concat( Arrays.asList(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.0, -0.0), nonzeroOrdinaryDoubles() ); } @Override public @NotNull Iterable<Float> rangeUp(float a) { if (a == Float.POSITIVE_INFINITY) return Collections.singletonList(Float.POSITIVE_INFINITY); if (a == Float.NEGATIVE_INFINITY) return filter(f -> !Float.isNaN(f), floats()); Iterable<Float> noNegativeZeros = cons( Float.POSITIVE_INFINITY, map( q -> q.a, filter( BigInteger.valueOf((long) FloatingPointUtils.POSITIVE_FINITE_FLOAT_COUNT - FloatingPointUtils.toOrderedRepresentation(a) + 1), p -> p.a.equals(p.b), map(BinaryFraction::floatRange, rangeUp(BinaryFraction.of(a).get())) ) ) ); return concatMap(f -> f == 0.0f ? Arrays.asList(0.0f, -0.0f) : Collections.singletonList(f), noNegativeZeros); } @Override public @NotNull Iterable<Float> rangeDown(float a) { return map(f -> -f, rangeUp(-a)); } @Override public @NotNull Iterable<Float> range(float a, float b) { if (Float.isNaN(a)) { throw new ArithmeticException("a cannot be NaN."); } if (Float.isNaN(b)) { throw new ArithmeticException("b cannot be NaN."); } if (a > b) return Collections.emptyList(); if (a == Float.NEGATIVE_INFINITY) return rangeDown(b); if (b == Float.POSITIVE_INFINITY) return rangeUp(a); if (a == Float.POSITIVE_INFINITY || b == Float.NEGATIVE_INFINITY) return Collections.emptyList(); BinaryFraction bfa = BinaryFraction.of(a).get(); BinaryFraction bfb = BinaryFraction.of(b).get(); if (bfa.getExponent() > bfb.getExponent()) { return map(f -> -f, range(-b, -a)); } Iterable<Float> noNegativeZeros = map( q -> q.a, filter( BigInteger.valueOf((long) FloatingPointUtils.toOrderedRepresentation(b) - FloatingPointUtils.toOrderedRepresentation(a) + 1), p -> p.a.equals(p.b), map(BinaryFraction::floatRange, range(bfa, bfb)) ) ); return concatMap(f -> f == 0.0f ? Arrays.asList(0.0f, -0.0f) : Collections.singletonList(f), noNegativeZeros); } @Override public @NotNull Iterable<Double> rangeUp(double a) { if (a == Double.POSITIVE_INFINITY) return Collections.singletonList(Double.POSITIVE_INFINITY); if (a == Double.NEGATIVE_INFINITY) return filter(d -> !Double.isNaN(d), doubles()); Iterable<Double> noNegativeZeros = cons( Double.POSITIVE_INFINITY, map( q -> q.a, filter( BigInteger.valueOf(FloatingPointUtils.POSITIVE_FINITE_DOUBLE_COUNT) .subtract(BigInteger.valueOf(FloatingPointUtils.toOrderedRepresentation(a))) .add(BigInteger.ONE), p -> p.a.equals(p.b), map(BinaryFraction::doubleRange, rangeUp(BinaryFraction.of(a).get())) ) ) ); return concatMap(d -> d == 0.0 ? Arrays.asList(0.0, -0.0) : Collections.singletonList(d), noNegativeZeros); } @Override public @NotNull Iterable<Double> rangeDown(double a) { return map(d -> -d, rangeUp(-a)); } @Override public @NotNull Iterable<Double> range(double a, double b) { if (Double.isNaN(a)) { throw new ArithmeticException("a cannot be NaN."); } if (Double.isNaN(b)) { throw new ArithmeticException("b cannot be NaN."); } if (a > b) return Collections.emptyList(); if (a == Double.NEGATIVE_INFINITY) return rangeDown(b); if (b == Double.POSITIVE_INFINITY) return rangeUp(a); if (a == Double.POSITIVE_INFINITY || b == Double.NEGATIVE_INFINITY) return Collections.emptyList(); BinaryFraction bfa = BinaryFraction.of(a).get(); BinaryFraction bfb = BinaryFraction.of(b).get(); if (bfa.getExponent() > bfb.getExponent()) { return map(f -> -f, range(-b, -a)); } Iterable<Double> noNegativeZeros = map( q -> q.a, filter( BigInteger.valueOf(FloatingPointUtils.toOrderedRepresentation(b)) .subtract(BigInteger.valueOf(FloatingPointUtils.toOrderedRepresentation(a))) .add(BigInteger.ONE), p -> p.a.equals(p.b), map(BinaryFraction::doubleRange, range(bfa, bfb)) ) ); return concatMap(d -> d == 0.0 ? Arrays.asList(0.0, -0.0) : Collections.singletonList(d), noNegativeZeros); } /** * An {@code Iterable} that generates all positive {@link BigDecimal}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> positiveBigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairsLogarithmicOrder(positiveBigIntegers(), integers())); } /** * An {@code Iterable} that generates all negative {@code BigDecimal}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> negativeBigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairsLogarithmicOrder(negativeBigIntegers(), integers())); } /** * An {@code Iterable} that generates all nonzero {@code BigDecimal}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> nonzeroBigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairsLogarithmicOrder(nonzeroBigIntegers(), integers())); } /** * An {@code Iterable} that generates all {@code BigDecimal}s. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> bigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairsLogarithmicOrder(bigIntegers(), integers())); } /** * Generates positive {@code BigDecimal}s in canonical form (see * {@link mho.wheels.numberUtils.BigDecimalUtils#canonicalize(BigDecimal)}). Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> positiveCanonicalBigDecimals() { return filterInfinite(BigDecimalUtils::isCanonical, positiveBigDecimals()); } /** * Generates negative {@code BigDecimal}s in canonical form (see * {@link mho.wheels.numberUtils.BigDecimalUtils#canonicalize(BigDecimal)}). Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> negativeCanonicalBigDecimals() { return filterInfinite(BigDecimalUtils::isCanonical, negativeBigDecimals()); } /** * Generates nonzero {@code BigDecimal}s in canonical form (see * {@link mho.wheels.numberUtils.BigDecimalUtils#canonicalize(BigDecimal)}). Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> nonzeroCanonicalBigDecimals() { return filterInfinite(BigDecimalUtils::isCanonical, nonzeroBigDecimals()); } /** * Generates {@code BigDecimal}s in canonical form (see * {@link mho.wheels.numberUtils.BigDecimalUtils#canonicalize(BigDecimal)}). Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<BigDecimal> canonicalBigDecimals() { return filterInfinite(BigDecimalUtils::isCanonical, bigDecimals()); } /** * Generates canonical {@code BigDecimal}s greater than or equal to zero and less than or equal to a specified * power of ten. * * <ul> * <li>{@code pow} may be any {@code int}.</li> * <li>The result is a non-removable, infinite {@code Iterable} containing canonical {@code BigDecimal}s between * zero and a power of ten, inclusive.</li> * </ul> * * Length is infinite * * @param pow an {@code int} * @return all canonical {@code BigDecimal}s between 0 and 10<sup>{@code pow}</sup>, inclusive */ private static @NotNull Iterable<BigDecimal> zeroToPowerOfTenCanonicalBigDecimals(int pow) { return cons( BigDecimal.ZERO, nub( map( p -> BigDecimalUtils.canonicalize( new BigDecimal( p.a, p.b + MathUtils.ceilingLog(BigInteger.TEN, p.a).intValueExact() - pow ) ), INSTANCE.pairsLogarithmicOrder( INSTANCE.positiveBigIntegers(), INSTANCE.naturalIntegers() ) ) ) ); } private static @NotNull Iterable<BigDecimal> uncanonicalize(@NotNull Iterable<BigDecimal> xs) { CachedIterator<Integer> integers = new CachedIterator<>(INSTANCE.integers()); return map( p -> p.a.equals(BigDecimal.ZERO) ? new BigDecimal(BigInteger.ZERO, integers.get(p.b).get()) : BigDecimalUtils.setPrecision( p.a.stripTrailingZeros(), p.b + p.a.stripTrailingZeros().precision() ), INSTANCE.pairsLogarithmicOrder(xs, INSTANCE.naturalIntegers()) ); } /** * An {@code Iterable} that generates all {@code BigDecimal}s greater than or equal to {@code a}. Does not support * removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BigDecimal}s.</li> * </ul> * * Length is infinite * * @param a the inclusive lower bound of the generated elements * @return {@code BigDecimal}s greater than or equal to {@code a} */ @Override public @NotNull Iterable<BigDecimal> rangeUp(@NotNull BigDecimal a) { return uncanonicalize(rangeUpCanonical(a)); } /** * An {@code Iterable} that generates all {@code BigDecimal}s less than or equal to {@code a}. Does not support * removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BigDecimal}s.</li> * </ul> * * Length is infinite * * @param a the inclusive upper bound of the generated elements * @return {@code BigDecimal}s less than or equal to {@code a} */ @Override public @NotNull Iterable<BigDecimal> rangeDown(@NotNull BigDecimal a) { return uncanonicalize(rangeDownCanonical(a)); } /** * An {@code Iterable} that generates all {@code BigDecimal}s between {@code a} and {@code b}, inclusive. If * {@code a}{@literal >}{@code b}, an empty {@code Iterable} is returned. Does not support removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>{@code b} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing {@code BigDecimal}s.</li> * </ul> * * Length is 0 if a>b, 1 if a=b, and infinite otherwise * * @param a the inclusive lower bound of the generated elements * @param b the inclusive upper bound of the generated elements * @return {@code BigDecimal}s between {@code a} and {@code b}, inclusive */ @Override public @NotNull Iterable<BigDecimal> range(@NotNull BigDecimal a, @NotNull BigDecimal b) { if (eq(a, b)) { if (a.signum() == 0) { return map(i -> new BigDecimal(BigInteger.ZERO, i), integers()); } else { return map( x -> BigDecimalUtils.setPrecision(a, x), IterableUtils.rangeUp(a.stripTrailingZeros().precision()) ); } } return uncanonicalize(rangeCanonical(a, b)); } /** * An {@code Iterable} that generates all canonical {@code BigDecimal}s greater than or equal to {@code a}. Does * not support removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing canonical {@code BigDecimal}s.</li> * </ul> * * Length is infinite * * @param a the inclusive lower bound of the generated elements * @return canonical {@code BigDecimal}s greater than or equal to {@code a} */ @Override public @NotNull Iterable<BigDecimal> rangeUpCanonical(@NotNull BigDecimal a) { BigDecimal ca = BigDecimalUtils.canonicalize(a); return map( bd -> BigDecimalUtils.canonicalize(bd.add(ca)), cons(BigDecimal.ZERO, positiveCanonicalBigDecimals()) ); } /** * An {@code Iterable} that generates all canonical {@code BigDecimal}s less than or equal to {@code a}. Does not * support removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing canonical {@code BigDecimal}s.</li> * </ul> * * Length is infinite * * @param a the inclusive upper bound of the generated elements * @return canonical {@code BigDecimal}s less than or equal to {@code a} */ @Override public @NotNull Iterable<BigDecimal> rangeDownCanonical(@NotNull BigDecimal a) { return map(BigDecimal::negate, rangeUpCanonical(a.negate())); } /** * An {@code Iterable} that generates all canonical {@code BigDecimal}s between {@code a} and {@code b}, inclusive. * If {@code a}{@literal >}{@code b}, an empty {@code Iterable} is returned. Does not support removal. * * <ul> * <li>{@code a} cannot be null.</li> * <li>{@code b} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing canonical {@code BigDecimal}s.</li> * </ul> * * Length is 0 if a>b, 1 if a=b, and infinite otherwise * * @param a the inclusive lower bound of the generated elements * @param b the inclusive upper bound of the generated elements * @return canonical {@code BigDecimal}s between {@code a} and {@code b}, inclusive */ @Override public @NotNull Iterable<BigDecimal> rangeCanonical(@NotNull BigDecimal a, @NotNull BigDecimal b) { if (gt(a, b)) return Collections.emptyList(); if (eq(a, b)) return Collections.singletonList(BigDecimalUtils.canonicalize(a)); BigDecimal difference = BigDecimalUtils.canonicalize(b.subtract(a)); return map( c -> BigDecimalUtils.canonicalize(c.add(a)), filter( bd -> le(bd, difference), zeroToPowerOfTenCanonicalBigDecimals(BigDecimalUtils.ceilingLog10(difference)) ) ); } /** * See {@link IterableUtils#cons}. */ @Override public @NotNull <T> Iterable<T> withElement(@Nullable T x, @NotNull Iterable<T> xs) { return cons(x, xs); } /** * Generates all pairs of values, given an {@code Iterable} of possible first values of the pairs, and a function * mapping each possible first value to an {@code Iterable} of possible second values. For each first value, the * second values are listed consecutively. If all the input lists are unique, the output pairs are unique as well. * This method is similar to {@link ExhaustiveProvider#dependentPairsInfinite(Iterable, Function)}, but with * different conditions on the arguments. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>{@code f} must terminate and not return null when applied to any element of {@code xs}. All results, except * possibly the result when applied to the last element of {@code xs} (if it exists) must be finite.</li> * <li>The result is non-removable and does not contain nulls.</li> * </ul> * * Length is finite iff {@code f.apply(last(xs))} is finite * * @param xs an {@code Iterable} of values * @param f a function from a value of type {@code a} to an {@code Iterable} of type-{@code B} values * @param <A> the type of values in the first slot * @param <B> the type of values in the second slot * @return all possible pairs of values specified by {@code xs} and {@code f} */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairs( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return concatMap(x -> map(y -> new Pair<>(x, y), f.apply(x)), xs); } private @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsInfinite( @NotNull Function<BigInteger, Pair<BigInteger, BigInteger>> unpairingFunction, @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new NoRemoveIterator<Pair<A, B>>() { private final @NotNull CachedIterator<A> as = new CachedIterator<>(xs); private final @NotNull Map<A, Iterator<B>> aToBs = new HashMap<>(); private final @NotNull Iterator<BigInteger> indices = naturalBigIntegers.iterator(); @Override public boolean hasNext() { return true; } @Override public @NotNull Pair<A, B> next() { Pair<BigInteger, BigInteger> index = unpairingFunction.apply(indices.next()); A a = as.get(index.a).get(); Iterator<B> bs = aToBs.get(a); if (bs == null) { bs = f.apply(a).iterator(); aToBs.put(a, bs); } return new Pair<>(a, bs.next()); } }; } /** * Generates all pairs of values, given an infinite {@code Iterable} of possible first values of the pairs, and a * function mapping each possible first value to an infinite {@code Iterable} of possible second values. The pairs * are traversed along a Z-curve. If all the input lists are unique, the output pairs are unique as well. This * method is similar to {@link ExhaustiveProvider#dependentPairs(Iterable, Function)}, but with different * conditions on the arguments. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>{@code f} must terminate and not return null when applied to any element of {@code xs}. All results must be * infinite.</li> * <li>The result is non-removable and does not contain nulls.</li> * </ul> * * Length is infinite * * @param xs an {@code Iterable} of values * @param f a function from a value of type {@code a} to an {@code Iterable} of type-{@code B} values * @param <A> the type of values in the first slot * @param <B> the type of values in the second slot * @return all possible pairs of values specified by {@code xs} and {@code f} */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsInfinite( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return dependentPairsInfinite( bi -> { List<BigInteger> list = IntegerUtils.demux(2, bi); return new Pair<>(list.get(0), list.get(1)); }, xs, f ); } /** * Generates all pairs of values in such a way that the second value grows linearly, but the first grows * logarithmically, given an infinite {@code Iterable} of possible first values of the pairs, and a function * mapping each possible first value to an infinite {@code Iterable} of possible second values. If all the input * lists are unique, the output pairs are unique as well. This method is similar to * {@link ExhaustiveProvider#dependentPairs(Iterable, Function)}, but with different conditions on the arguments. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>{@code f} must terminate and not return null when applied to any element of {@code xs}. All results must be * infinite.</li> * <li>The result is non-removable and does not contain nulls.</li> * </ul> * * Length is infinite * * @param xs an {@code Iterable} of values * @param f a function from a value of type {@code a} to an {@code Iterable} of type-{@code B} values * @param <A> the type of values in the first slot * @param <B> the type of values in the second slot * @return all possible pairs of values specified by {@code xs} and {@code f} */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsInfiniteLogarithmicOrder( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return dependentPairsInfinite( i -> { Pair<BigInteger, BigInteger> p = IntegerUtils.logarithmicDemux(i); return new Pair<>(p.b, p.a); }, xs, f ); } /** * Generates all pairs of values in such a way that the second value grows as O(n<sup>2/3</sup>), but the first * grows as O(n<sup>1/3</sup>), given an infinite {@code Iterable} of possible first values of the pairs, and a * function mapping each possible first value to an infinite {@code Iterable} of possible second values. If all the * input lists are unique, the output pairs are unique as well. This method is similar to * {@link ExhaustiveProvider#dependentPairs(Iterable, Function)}, but with different conditions on the arguments. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>{@code f} must terminate and not return null when applied to any element of {@code xs}. All results must be * infinite.</li> * <li>The result is non-removable and does not contain nulls.</li> * </ul> * * Length is infinite * * @param xs an {@code Iterable} of values * @param f a function from a value of type {@code a} to an {@code Iterable} of type-{@code B} values * @param <A> the type of values in the first slot * @param <B> the type of values in the second slot * @return all possible pairs of values specified by {@code xs} and {@code f} */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsInfiniteSquareRootOrder( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return dependentPairsInfinite( i -> { Pair<BigInteger, BigInteger> p = IntegerUtils.squareRootDemux(i); return new Pair<>(p.b, p.a); }, xs, f ); } private @NotNull <A, B> Iterable<Pair<A, B>> pairsByFunction( @NotNull Function<BigInteger, Pair<BigInteger, BigInteger>> unpairingFunction, @NotNull Iterable<A> as, @NotNull Iterable<B> bs ) { if (isEmpty(as) || isEmpty(bs)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<Pair<A, B>>() { private final @NotNull CachedIterator<A> cas = new CachedIterator<>(as); private final @NotNull CachedIterator<B> cbs = new CachedIterator<>(bs); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull Pair<A, B> advance() { while (true) { Pair<BigInteger, BigInteger> indices = unpairingFunction.apply(is.next()); NullableOptional<A> oa = cas.get(indices.a.intValueExact()); if (!oa.isPresent()) continue; NullableOptional<B> ob = cbs.get(indices.b.intValueExact()); if (!ob.isPresent()) continue; if (!outputSizeKnown() && cas.knownSize().isPresent() && cbs.knownSize().isPresent()) { setOutputSize( BigInteger.valueOf(cas.knownSize().get()) .multiply(BigInteger.valueOf(cbs.knownSize().get())) ); } return new Pair<>(oa.get(), ob.get()); } } }; } private @NotNull <T> Iterable<Pair<T, T>> pairsByFunction( @NotNull Function<BigInteger, Pair<BigInteger, BigInteger>> unpairingFunction, @NotNull Iterable<T> xs ) { if (isEmpty(xs)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<Pair<T, T>>() { private final @NotNull CachedIterator<T> cxs = new CachedIterator<>(xs); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull Pair<T, T> advance() { while (true) { Pair<BigInteger, BigInteger> indices = unpairingFunction.apply(is.next()); NullableOptional<T> oa = cxs.get(indices.a.intValueExact()); if (!oa.isPresent()) continue; NullableOptional<T> ob = cxs.get(indices.b.intValueExact()); if (!ob.isPresent()) continue; if (!outputSizeKnown() && cxs.knownSize().isPresent()) { setOutputSize(BigInteger.valueOf(cxs.knownSize().get()).pow(2)); } return new Pair<>(oa.get(), ob.get()); } } }; } /** * Returns all pairs of elements taken from two {@code Iterable}s in such a way that the first component grows * linearly but the second grows logarithmically. Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing all pairs of elements taken from two * {@code Iterable}s. The ordering of these elements is determined by mapping the sequence 0, 1, 2, ... by * {@link IntegerUtils#logarithmicDemux(BigInteger)} and interpreting the resulting pairs as indices into the * original {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}| * * @param as the {@code Iterable} from which the first components of the pairs are selected * @param bs the {@code Iterable} from which the second components of the pairs are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @return all pairs of elements from {@code as} and {@code bs} in logarithmic order */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairsLogarithmicOrder( @NotNull Iterable<A> as, @NotNull Iterable<B> bs ) { return pairsByFunction(IntegerUtils::logarithmicDemux, as, bs); } /** * Returns all pairs of elements taken from one {@code Iterable}s in such a way that the first component grows * linearly but the second grows logarithmically (hence the name). Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing all pairs of elements taken from some * {@code Iterable}. The ordering of these elements is determined by mapping the sequence 0, 1, 2, ... by * {@link IntegerUtils#logarithmicDemux(BigInteger)} and interpreting the resulting pairs as indices into the * original {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>2</sup> * * @param xs the {@code Iterable} from which elements are selected * @param <T> the type of the given {@code Iterable}'s elements * @return all pairs of elements from {@code xs} in logarithmic order */ @Override public @NotNull <T> Iterable<Pair<T, T>> pairsLogarithmicOrder(@NotNull Iterable<T> xs) { return pairsByFunction(IntegerUtils::logarithmicDemux, xs); } /** * Returns all pairs of elements taken from two {@code Iterable}s in such a way that the first component grows * as O(n<sup>2/3</sup>) but the second grows as O(n<sup>1/3</sup>). Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing all pairs of elements taken from two * {@code Iterable}s. The ordering of these elements is determined by mapping the sequence 0, 1, 2, ... by * {@link IntegerUtils#squareRootDemux(BigInteger)} and interpreting the resulting pairs as indices into the * original {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}| * * @param as the {@code Iterable} from which the first components of the pairs are selected * @param bs the {@code Iterable} from which the second components of the pairs are selected * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @return all pairs of elements from {@code as} and {@code bs} in square-root order */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairsSquareRootOrder( @NotNull Iterable<A> as, @NotNull Iterable<B> bs ) { return pairsByFunction(IntegerUtils::squareRootDemux, as, bs); } /** * Returns all pairs of elements taken from one {@code Iterable}s in such a way that the first component grows * as O(n<sup>2/3</sup>) but the second grows as O(n<sup>1/3</sup>). Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is a non-removable {@code Iterable} containing all pairs of elements taken from some * {@code Iterable}. The ordering of these elements is determined by mapping the sequence 0, 1, 2, ... by * {@link IntegerUtils#squareRootDemux(BigInteger)} and interpreting the resulting pairs as indices into the * original {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>2</sup> * * @param xs the {@code Iterable} from which elements are selected * @param <T> the type of the given {@code Iterable}'s elements * @return all pairs of elements from {@code xs} in square-root order */ @Override public @NotNull <T> Iterable<Pair<T, T>> pairsSquareRootOrder(@NotNull Iterable<T> xs) { return pairsByFunction(IntegerUtils::squareRootDemux, xs); } /** * Given a list of non-negative integers in weakly increasing order, returns all distinct permutations of these * integers in lexicographic order. * * <ul> * <li>{@code start} must be weakly increasing and can only contain non-negative integers.</li> * <li>The result is in lexicographic order, contains only non-negative integers, contains no repetitions, and is * the complete set of permutations of some list.</li> * </ul> * * Length is the number of distinct permutations of {@code start} * * @param start a lexicographically smallest permutation * @return all permutations of {@code start} */ private static @NotNull Iterable<List<Integer>> finitePermutationIndices(@NotNull List<Integer> start) { BigInteger outputSize = MathUtils.permutationCount(start); return () -> new EventuallyKnownSizeIterator<List<Integer>>() { private @NotNull List<Integer> list = toList(start); private boolean first = true; { setOutputSize(outputSize); } @Override public @NotNull List<Integer> advance() { if (first) { first = false; return list; } list = toList(list); int k = list.size() - 2; while (list.get(k) >= list.get(k + 1)) k int m = list.size() - 1; while (m > k && list.get(k) >= list.get(m)) m Collections.swap(list, k, m); int i = k + 1; int j = list.size() - 1; while (i < j) { Collections.swap(list, i, j); i++; j } return list; } }; } /** * Returns an {@code Iterable} containing every distinct permutation of a list. The result is ordered * lexicographically, preserving the order in the initial list. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is lexicographically increasing with respect to some order on {@code T}, contains no * repetitions, and is the complete set of permutations of some list.</li> * </ul> * * Length is the number of distinct permutations of {@code start} * * @param xs a list of elements * @param <T> the type of the given {@code List}'s elements * @return all distinct permutations of {@code xs} */ @Override public @NotNull <T> Iterable<List<T>> permutationsFinite(@NotNull List<T> xs) { List<T> nub = toList(nub(xs)); Map<T, Integer> indexMap = toMap(zip(nub, IterableUtils.rangeUp(0))); List<Integer> startingIndices = sort(map(indexMap::get, xs)); return map(is -> toList(map(nub::get, is)), finitePermutationIndices(startingIndices)); } /** * Returns an {@code Iterable} containing every permutation of an {@code Iterable}. If the {@code Iterable} is * finite, all permutations are generated; if it is infinite, then only permutations that are equal to the identity * except in a finite prefix are generated. Unlike {@link ExhaustiveProvider#permutationsFinite(List)}, this method * may return an {@code Iterable} with duplicate elements. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is the set of permutations of some {@code Iterable} such that each permutation differs from * {@code xs} in a finite prefix.</li> * </ul> * * Length is |{@code xs}|! * * @param xs an {@code Iterable} of elements * @param <T> the type of the given {@code Iterable}'s elements */ @Override public @NotNull <T> Iterable<Iterable<T>> prefixPermutations(@NotNull Iterable<T> xs) { if (!lengthAtLeast(2, xs)) return Collections.singletonList(new NoRemoveIterable<>(xs)); return () -> new EventuallyKnownSizeIterator<Iterable<T>>() { private final @NotNull CachedIterator<T> cxs = new CachedIterator<>(xs); private Iterator<List<Integer>> prefixIndices; private int prefixLength = 0; @Override public @NotNull Iterable<T> advance() { if (prefixIndices == null || !prefixIndices.hasNext()) { updatePrefixIndices(); } Iterable<T> permutation = concat(cxs.get(prefixIndices.next()).get(), drop(prefixLength, xs)); if (!outputSizeKnown() && cxs.knownSize().isPresent()) { setOutputSize(MathUtils.factorial(cxs.knownSize().get())); } return permutation; } private void updatePrefixIndices() { if (prefixIndices == null) { prefixLength = 0; } else if (prefixLength == 0) { prefixLength = 2; } else { prefixLength++; } prefixIndices = filter( is -> is.isEmpty() || last(is) != prefixLength - 1, finitePermutationIndices(toList(IterableUtils.range(0, prefixLength - 1))) ).iterator(); } }; } /** * Returns an {@code Iterable} containing all {@code List}s of a given length with elements from a given * {@code List}. The {@code List}s are ordered lexicographically, matching the order given by the original * {@code List}. Does not support removal. * * <ul> * <li>{@code size} cannot be negative.</li> * <li>{@code xs} cannot be null.</li> * <li>The result is finite. All of its elements have the same length. None are empty, unless the result consists * entirely of one empty element.</li> * </ul> * * Length is |{@code xs}|<sup>{@code size}</sup> * * @param size the length of the result lists * @param xs the {@code List} from which elements are selected * @param <T> the type of the given {@code List}'s elements * @return all {@code List}s of a given length created from {@code xs} */ @Override public @NotNull <T> Iterable<List<T>> listsLex(int size, @NotNull List<T> xs) { if (size < 0) { throw new IllegalArgumentException("size cannot be negative. Invalid size: " + size); } List<T> copy = toList(xs); int xsSize = copy.size(); BigInteger outputSize = BigInteger.valueOf(xsSize).pow(size); return () -> new EventuallyKnownSizeIterator<List<T>>() { private final @NotNull List<Integer> indices = toList(replicate(size, 0)); private boolean first = true; { setOutputSize(outputSize); } @Override public List<T> advance() { if (first) { first = false; } else { for (int i = size - 1; i >= 0; i int j = indices.get(i); if (j == xsSize - 1) { indices.set(i, 0); } else { indices.set(i, j + 1); break; } } } return toList(map(copy::get, indices)); } }; } /** * Given two {@code Iterable}s, returns all {@code Pair}s of elements from these {@code Iterable}s. The * {@code Pair}s are ordered lexicographically, matching the order given by the original {@code Iterable}s. The * second {@code Iterable} must be finite. Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>The result is the Cartesian product of two {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @return all ordered {@code Pair}s of elements from {@code as} and {@code bs} */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairsLex(@NotNull Iterable<A> as, @NotNull List<B> bs) { if (isEmpty(bs)) return Collections.emptyList(); return concatMap(p -> zip(repeat(p.a), p.b), zip(as, repeat(bs))); } /** * Given three {@code Iterable}s, returns all ordered {@code Triple}s of elements from these {@code Iterable}s. The * {@code Triple}s are ordered lexicographically, matching the order given by the original {@code Iterable}s. All * {@code Iterable}s but the first must be finite. Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>The result is the Cartesian product of three {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @return all ordered {@code Triple}s of elements from {@code as}, {@code bs}, and {@code cs} */ @Override public @NotNull <A, B, C> Iterable<Triple<A, B, C>> triplesLex( @NotNull Iterable<A> as, @NotNull List<B> bs, @NotNull List<C> cs ) { return map(p -> new Triple<>(p.a.a, p.a.b, p.b), pairsLex(pairsLex(as, bs), cs)); } /** * Given four {@code Iterable}s, returns all {@code Quadruple}s of elements from these {@code Iterable}s. The * {@code Quadruple}s are ordered lexicographically, matching the order given by the original {@code Iterable}s. * All {@code Iterable}s but the first must be finite. Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>The result is the Cartesian product of four {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @return all ordered {@code Quadruple}s of elements from {@code as}, {@code bs}, {@code cs}, and {@code ds} */ @Override public @NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruplesLex( @NotNull Iterable<A> as, @NotNull List<B> bs, @NotNull List<C> cs, @NotNull List<D> ds ) { return map(p -> new Quadruple<>(p.a.a, p.a.b, p.a.c, p.b), pairsLex(triplesLex(as, bs, cs), ds)); } /** * Given five {@code Iterable}s, returns all {@code Quintuple}s of elements from these {@code Iterable}s. The * {@code Quintuple}s are ordered lexicographically, matching the order given by the original {@code Iterable}s. * All {@code Iterable}s but the first must be finite. Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>{@code es} cannot be null.</li> * <li>The result is the Cartesian product of five {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}||{@code es}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param es the fifth {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @return all ordered {@code Quintuple}s of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, and * {@code es} */ @Override public @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuplesLex( @NotNull Iterable<A> as, @NotNull List<B> bs, @NotNull List<C> cs, @NotNull List<D> ds, @NotNull List<E> es ) { return map( p -> new Quintuple<>(p.a.a, p.a.b, p.a.c, p.a.d, p.b), pairsLex(quadruplesLex(as, bs, cs, ds), es) ); } /** * Given six {@code Iterable}s, returns all {@code Sextuple}s of elements from these {@code Iterable}s. The * {@code Sextuple}s are ordered lexicographically, matching the order given by the original {@code Iterable}s. * All {@code Iterable}s but the first must be finite. Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>{@code es} cannot be null.</li> * <li>{@code fs} cannot be null.</li> * <li>The result is the Cartesian product of six {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}||{@code es}||{@code fs}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param es the fifth {@code Iterable} * @param fs the sixth {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @param <F> the type of the sixth {@code Iterable}'s elements * @return all ordered {@code Sextuple}s of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, * {@code es}, and {@code fs} */ @Override public @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuplesLex( @NotNull Iterable<A> as, @NotNull List<B> bs, @NotNull List<C> cs, @NotNull List<D> ds, @NotNull List<E> es, @NotNull List<F> fs ) { return map( p -> new Sextuple<>(p.a.a, p.a.b, p.a.c, p.a.d, p.a.e, p.b), pairsLex(quintuplesLex(as, bs, cs, ds, es), fs) ); } /** * Given seven {@code Iterable}s, returns all {@code Septuple}s of elements from these {@code Iterable}s. The * {@code Septuple}s are ordered lexicographically, matching the order given by the original {@code Iterable}s. * All {@code Iterable}s but the first must be finite. Does not support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>{@code es} cannot be null.</li> * <li>{@code fs} cannot be null.</li> * <li>{@code gs} cannot be null.</li> * <li>The result is the Cartesian product of seven {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}||{@code es}||{@code fs}||{@code gs} * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param es the fifth {@code Iterable} * @param fs the sixth {@code Iterable} * @param gs the seventh {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @param <F> the type of the sixth {@code Iterable}'s elements * @param <G> the type of the seventh {@code Iterable}'s elements * @return all ordered {@code Septuple}s of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, * {@code es}, {@code fs}, and {@code gs} */ @Override public @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuplesLex( @NotNull Iterable<A> as, @NotNull List<B> bs, @NotNull List<C> cs, @NotNull List<D> ds, @NotNull List<E> es, @NotNull List<F> fs, @NotNull List<G> gs ) { return map( p -> new Septuple<>(p.a.a, p.a.b, p.a.c, p.a.d, p.a.e, p.a.f, p.b), pairsLex(sextuplesLex(as, bs, cs, ds, es, fs), gs) ); } /** * Returns an {@code Iterable} containing all {@code String}s of a given length with characters from a given * {@code String}. The {@code String}s are ordered lexicographically, matching the order given by the original * {@code String}. Does not support removal. * * <ul> * <li>{@code size} cannot be negative.</li> * <li>{@code s} cannot be null.</li> * <li>The result is finite. All of its {@code String}s have the same length. None are empty, unless the result * consists entirely of one empty {@code String}.</li> * </ul> * * Length is |{@code s}|<sup>{@code size}</sup> * * @param size the length of the result {@code String} * @param s the {@code String} from which characters are selected * @return all Strings of a given length created from {@code s} */ @Override public @NotNull Iterable<String> stringsLex(int size, @NotNull String s) { return map(IterableUtils::charsToString, listsLex(size, toList(fromString(s)))); } /** * Returns an {@code Iterable} containing all {@code Lists}s with elements from a given {@code List}. The * {@code List}s are in shortlex order; that is, shorter {@code List}s precede longer {@code List}s, and * {@code List}s of the same length are ordered lexicographically, matching the order given by the original * {@code List}. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result either consists of a single empty {@code List}, or is infinite. It is in shortlex order * (according to some ordering of its elements) and contains every {@code List} of elements drawn from some * sequence.</li> * </ul> * * Result length is 1 if {@code xs} is empty, infinite otherwise * * @param xs the {@code List} from which elements are selected * @param <T> the type of the given {@code List}'s elements * @return all {@code List}s created from {@code xs} */ @Override public @NotNull <T> Iterable<List<T>> listsShortlex(@NotNull List<T> xs) { if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList()); return concatMap(i -> listsLex(i.intValueExact(), xs), naturalBigIntegers()); } /** * Returns an {@code Iterable} containing all {@code String}s with characters from a given {@code String}. The * {@code String}s are in shortlex order; that is, shorter {@code String}s precede longer {@code String}s, and * {@code String}s of the same length are ordered lexicographically, matching the order given by the original * {@code String}. Does not support removal. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result either consists of a single empty {@code String}, or is infinite. It is in shortlex order * (according to some ordering of its characters) and contains every {@code String} with characters drawn from * some sequence.</li> * </ul> * * Result length is 1 if {@code s} is empty, infinite otherwise * * @param s the {@code String} from which characters are selected * @return all {@code String}s created from {@code s} */ @Override public @NotNull Iterable<String> stringsShortlex(@NotNull String s) { if (isEmpty(s)) return Collections.singletonList(""); return concatMap(i -> stringsLex(i.intValueExact(), s), naturalBigIntegers()); } /** * Returns an {@code Iterable} containing all {@code Lists}s with a minimum size with elements from a given * {@code List}. The {@code List}s are in shortlex order; that is, shorter {@code List}s precede longer * {@code List}s, and {@code List}s of the same length are ordered lexicographically, matching the order given by * the original {@code List}. Does not support removal. * * <ul> * <li>{@code minSize} cannot be negative.</li> * <li>{@code xs} cannot be null.</li> * <li>The result either consists of a single empty {@code List}, or is infinite. It is in shortlex order * (according to some ordering of its elements) and contains every {@code List} (with a length greater than or * equal to some minimum) of elements drawn from some sequence.</li> * </ul> * * Result length is 0 if {@code xs} is empty and {@code minSize} is greater than 0, 1 if {@code xs} is empty and * {@code minSize} is 0, and infinite otherwise * * @param minSize the minimum length of the result {@code List}s * @param xs the {@code List} from which elements are selected * @param <T> the type of the given {@code Iterable}'s elements * @return all {@code List}s created from {@code xs} */ @Override public @NotNull <T> Iterable<List<T>> listsShortlexAtLeast(int minSize, @NotNull List<T> xs) { if (minSize < 0) { throw new IllegalArgumentException("minSize cannot be negative. Invalid minSize: " + minSize); } if (isEmpty(xs)) return minSize == 0 ? Collections.singletonList(Collections.emptyList()) : Collections.emptyList(); return concatMap(i -> listsLex(i.intValueExact(), xs), rangeUp(BigInteger.valueOf(minSize))); } /** * Returns an {@code Iterable} containing all {@code String}s with a minimum size with characters from a given * {@code String}. The {@code String}s are in shortlex order; that is, shorter {@code String}s precede longer * {@code String}s, and {@code String}s of the same length are ordered lexicographically, matching the order given * by the original {@code String}. Does not support removal. * * <ul> * <li>{@code minSize} cannot be negative.</li> * <li>{@code s} cannot be null.</li> * <li>The result either consists of a single empty {@code String}, or is infinite. It is in shortlex order * (according to some ordering of its characters) and contains every {@code String} (with a length greater than or * equal to some minimum) of characters drawn from some sequence.</li> * </ul> * * Result length is 0 if {@code s} is empty and {@code minSize} is greater than 0, 1 if {@code s} is empty and * {@code minSize} is 0, and infinite otherwise * * @param minSize the minimum length of the result {@code String}s * @param s the {@code String} from which elements are selected * @return all {@code String}s created from {@code s} */ @Override public @NotNull Iterable<String> stringsShortlexAtLeast(int minSize, @NotNull String s) { if (minSize < 0) { throw new IllegalArgumentException("minSize cannot be negative. Invalid minSize: " + minSize); } if (isEmpty(s)) return minSize == 0 ? Collections.singletonList("") : Collections.emptyList(); return concatMap(i -> stringsLex(i.intValueExact(), s), rangeUp(BigInteger.valueOf(minSize))); } /** * Returns an {@code Iterable} containing all {@code List}s of a given length with elements from a given * {@code Iterable}. Does not support removal. * * <ul> * <li>{@code size} cannot be negative.</li> * <li>{@code xs} cannot be null.</li> * <li>All of the result's elements have the same length. None are empty, unless the result consists entirely of * one empty element.</li> * </ul> * * Length is |{@code xs}|<sup>{@code size}</sup> * * @param size the length of the result lists * @param xs the {@code Iterable} from which elements are selected * @param <T> the type of the given {@code Iterable}'s elements * @return all lists of a given length created from {@code xs} */ @Override public @NotNull <T> Iterable<List<T>> lists(int size, @NotNull Iterable<T> xs) { if (size < 0) { throw new IllegalArgumentException("size cannot be negative. Invalid size: " + size); } if (size == 0) return Collections.singletonList(Collections.emptyList()); if (isEmpty(xs)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<List<T>>() { private final @NotNull CachedIterator<T> cxs = new CachedIterator<>(xs); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull List<T> advance() { outer: while (true) { List<BigInteger> indices = IntegerUtils.demux(size, is.next()); List<T> list = new ArrayList<>(); for (BigInteger index : indices) { NullableOptional<T> ox = cxs.get(index.intValueExact()); if (!ox.isPresent()) continue outer; list.add(ox.get()); } if (!outputSizeKnown() && cxs.knownSize().isPresent()) { setOutputSize(BigInteger.valueOf(cxs.knownSize().get()).pow(size)); } return list; } } }; } /** * Given two {@code Iterable}s, returns all {@code Pair}s of elements from these {@code Iterable}s. Does not * support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>The result is the Cartesian product of two {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @return all ordered {@code Pair}s of elements from {@code as} and {@code bs} */ @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) { return pairsByFunction( bi -> { List<BigInteger> list = IntegerUtils.demux(2, bi); return new Pair<>(list.get(0), list.get(1)); }, as, bs ); } /** * Returns all {@code Pair}s of elements from an {@code Iterable}. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is the Cartesian square of an {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>2</sup> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all ordered {@code Pair}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Pair<T, T>> pairs(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.emptyList(); return map(list -> new Pair<>(list.get(0), list.get(1)), lists(2, xs)); } /** * Given three {@code Iterable}s, returns all {@code Triple}s of elements from these {@code Iterable}s. Does not * support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>The result is the Cartesian product of three {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @return all ordered {@code Triple}s of elements from {@code as}, {@code bs}, and {@code cs} */ @Override public @NotNull <A, B, C> Iterable<Triple<A, B, C>> triples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs ) { if (isEmpty(as) || isEmpty(bs) || isEmpty(cs)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<Triple<A, B, C>>() { private final @NotNull CachedIterator<A> cas = new CachedIterator<>(as); private final @NotNull CachedIterator<B> cbs = new CachedIterator<>(bs); private final @NotNull CachedIterator<C> ccs = new CachedIterator<>(cs); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull Triple<A, B, C> advance() { while (true) { List<BigInteger> indices = IntegerUtils.demux(3, is.next()); NullableOptional<A> oa = cas.get(indices.get(0).intValueExact()); if (!oa.isPresent()) continue; NullableOptional<B> ob = cbs.get(indices.get(1).intValueExact()); if (!ob.isPresent()) continue; NullableOptional<C> oc = ccs.get(indices.get(2).intValueExact()); if (!oc.isPresent()) continue; if (!outputSizeKnown() && cas.knownSize().isPresent() && cbs.knownSize().isPresent() && ccs.knownSize().isPresent() ) { setOutputSize( BigInteger.valueOf(cas.knownSize().get()) .multiply(BigInteger.valueOf(cbs.knownSize().get())) .multiply(BigInteger.valueOf(ccs.knownSize().get())) ); } return new Triple<>(oa.get(), ob.get(), oc.get()); } } }; } /** * Returns all {@code Triple}s of elements from an {@code Iterable}. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is the Cartesian cube of an {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>3</sup> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all ordered {@code Triple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Triple<T, T, T>> triples(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.emptyList(); return map(list -> new Triple<>(list.get(0), list.get(1), list.get(2)), lists(3, xs)); } /** * Given four {@code Iterable}s, returns all {@code Quadruple}s of elements from these {@code Iterable}s. Does not * support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>The result is the Cartesian product of four {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @return all ordered {@code Quadruple}s of elements from {@code as}, {@code bs}, {@code cs}, and {@code ds} */ @Override public @NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds ) { if (isEmpty(as) || isEmpty(bs) || isEmpty(cs) || isEmpty(ds)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<Quadruple<A, B, C, D>>() { private final @NotNull CachedIterator<A> cas = new CachedIterator<>(as); private final @NotNull CachedIterator<B> cbs = new CachedIterator<>(bs); private final @NotNull CachedIterator<C> ccs = new CachedIterator<>(cs); private final @NotNull CachedIterator<D> cds = new CachedIterator<>(ds); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull Quadruple<A, B, C, D> advance() { while (true) { List<BigInteger> indices = IntegerUtils.demux(4, is.next()); NullableOptional<A> oa = cas.get(indices.get(0).intValueExact()); if (!oa.isPresent()) continue; NullableOptional<B> ob = cbs.get(indices.get(1).intValueExact()); if (!ob.isPresent()) continue; NullableOptional<C> oc = ccs.get(indices.get(2).intValueExact()); if (!oc.isPresent()) continue; NullableOptional<D> od = cds.get(indices.get(3).intValueExact()); if (!od.isPresent()) continue; if (!outputSizeKnown() && cas.knownSize().isPresent() && cbs.knownSize().isPresent() && ccs.knownSize().isPresent() && cds.knownSize().isPresent() ) { setOutputSize( BigInteger.valueOf(cas.knownSize().get()) .multiply(BigInteger.valueOf(cbs.knownSize().get())) .multiply(BigInteger.valueOf(ccs.knownSize().get())) .multiply(BigInteger.valueOf(cds.knownSize().get())) ); } return new Quadruple<>(oa.get(), ob.get(), oc.get(), od.get()); } } }; } /** * Returns all {@code Quadruple}s of elements from an {@code Iterable}. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is the Cartesian fourth power of an {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>4</sup> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all ordered {@code Quadruple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Quadruple<T, T, T, T>> quadruples(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.emptyList(); return map(list -> new Quadruple<>(list.get(0), list.get(1), list.get(2), list.get(3)), lists(4, xs)); } /** * Given five {@code Iterable}s, returns all {@code Quintuple}s of elements from these {@code Iterable}s. Does not * support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>{@code es} cannot be null.</li> * <li>The result is the Cartesian product of five {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}||{@code es}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param es the fifth {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @return all ordered {@code Quintuple}s of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, and * {@code es} */ @Override public @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es ) { if (isEmpty(as) || isEmpty(bs) || isEmpty(cs) || isEmpty(ds) || isEmpty(es)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<Quintuple<A, B, C, D, E>>() { private final @NotNull CachedIterator<A> cas = new CachedIterator<>(as); private final @NotNull CachedIterator<B> cbs = new CachedIterator<>(bs); private final @NotNull CachedIterator<C> ccs = new CachedIterator<>(cs); private final @NotNull CachedIterator<D> cds = new CachedIterator<>(ds); private final @NotNull CachedIterator<E> ces = new CachedIterator<>(es); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull Quintuple<A, B, C, D, E> advance() { while (true) { List<BigInteger> indices = IntegerUtils.demux(5, is.next()); NullableOptional<A> oa = cas.get(indices.get(0).intValueExact()); if (!oa.isPresent()) continue; NullableOptional<B> ob = cbs.get(indices.get(1).intValueExact()); if (!ob.isPresent()) continue; NullableOptional<C> oc = ccs.get(indices.get(2).intValueExact()); if (!oc.isPresent()) continue; NullableOptional<D> od = cds.get(indices.get(3).intValueExact()); if (!od.isPresent()) continue; NullableOptional<E> oe = ces.get(indices.get(4).intValueExact()); if (!oe.isPresent()) continue; if (!outputSizeKnown() && cas.knownSize().isPresent() && cbs.knownSize().isPresent() && ccs.knownSize().isPresent() && cds.knownSize().isPresent() && ces.knownSize().isPresent() ) { setOutputSize( BigInteger.valueOf(cas.knownSize().get()) .multiply(BigInteger.valueOf(cbs.knownSize().get())) .multiply(BigInteger.valueOf(ccs.knownSize().get())) .multiply(BigInteger.valueOf(cds.knownSize().get())) .multiply(BigInteger.valueOf(ces.knownSize().get())) ); } return new Quintuple<>(oa.get(), ob.get(), oc.get(), od.get(), oe.get()); } } }; } /** * Returns all {@code Quintuple}s of elements from an {@code Iterable}. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is the Cartesian fifth power of an {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>5</sup> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all ordered {@code Quintuple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> quintuples(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.emptyList(); return map( list -> new Quintuple<>(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4)), lists(5, xs) ); } /** * Given six {@code Iterable}s, returns all {@code Sextuple}s of elements from these {@code Iterable}s. Does not * support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>{@code es} cannot be null.</li> * <li>{@code fs} cannot be null.</li> * <li>The result is the Cartesian product of six {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}||{@code es}||{@code fs}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param es the fifth {@code Iterable} * @param fs the sixth {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @param <F> the type of the sixth {@code Iterable}'s elements * @return all ordered {@code Sextuple}s of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, * {@code es}, and {@code fs} */ @Override public @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es, @NotNull Iterable<F> fs ) { if (isEmpty(as) || isEmpty(bs) || isEmpty(cs) || isEmpty(ds) || isEmpty(es) || isEmpty(fs)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<Sextuple<A, B, C, D, E, F>>() { private final @NotNull CachedIterator<A> cas = new CachedIterator<>(as); private final @NotNull CachedIterator<B> cbs = new CachedIterator<>(bs); private final @NotNull CachedIterator<C> ccs = new CachedIterator<>(cs); private final @NotNull CachedIterator<D> cds = new CachedIterator<>(ds); private final @NotNull CachedIterator<E> ces = new CachedIterator<>(es); private final @NotNull CachedIterator<F> cfs = new CachedIterator<>(fs); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull Sextuple<A, B, C, D, E, F> advance() { while (true) { List<BigInteger> indices = IntegerUtils.demux(6, is.next()); NullableOptional<A> oa = cas.get(indices.get(0).intValueExact()); if (!oa.isPresent()) continue; NullableOptional<B> ob = cbs.get(indices.get(1).intValueExact()); if (!ob.isPresent()) continue; NullableOptional<C> oc = ccs.get(indices.get(2).intValueExact()); if (!oc.isPresent()) continue; NullableOptional<D> od = cds.get(indices.get(3).intValueExact()); if (!od.isPresent()) continue; NullableOptional<E> oe = ces.get(indices.get(4).intValueExact()); if (!oe.isPresent()) continue; NullableOptional<F> of = cfs.get(indices.get(5).intValueExact()); if (!of.isPresent()) continue; if (!outputSizeKnown() && cas.knownSize().isPresent() && cbs.knownSize().isPresent() && ccs.knownSize().isPresent() && cds.knownSize().isPresent() && ces.knownSize().isPresent() && cfs.knownSize().isPresent() ) { setOutputSize( BigInteger.valueOf(cas.knownSize().get()) .multiply(BigInteger.valueOf(cbs.knownSize().get())) .multiply(BigInteger.valueOf(ccs.knownSize().get())) .multiply(BigInteger.valueOf(cds.knownSize().get())) .multiply(BigInteger.valueOf(ces.knownSize().get())) .multiply(BigInteger.valueOf(cfs.knownSize().get())) ); } return new Sextuple<>(oa.get(), ob.get(), oc.get(), od.get(), oe.get(), of.get()); } } }; } /** * Returns all {@code Sextuple}s of elements from an {@code Iterable}. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is the Cartesian sixth power of an {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>6</sup> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all ordered {@code Sextuple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> sextuples(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.emptyList(); return map( list -> new Sextuple<>(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5)), lists(6, xs) ); } /** * Given seven {@code Iterable}s, returns all {@code Septuple}s of elements from these {@code Iterable}s. Does not * support removal. * * <ul> * <li>{@code as} cannot be null.</li> * <li>{@code bs} cannot be null.</li> * <li>{@code cs} cannot be null.</li> * <li>{@code ds} cannot be null.</li> * <li>{@code es} cannot be null.</li> * <li>{@code fs} cannot be null.</li> * <li>{@code gs} cannot be null.</li> * <li>The result is the Cartesian product of seven {@code Iterable}s.</li> * </ul> * * Length is |{@code as}||{@code bs}||{@code cs}||{@code ds}||{@code es}||{@code fs}||{@code gs}| * * @param as the first {@code Iterable} * @param bs the second {@code Iterable} * @param cs the third {@code Iterable} * @param ds the fourth {@code Iterable} * @param es the fifth {@code Iterable} * @param fs the sixth {@code Iterable} * @param gs the seventh {@code Iterable} * @param <A> the type of the first {@code Iterable}'s elements * @param <B> the type of the second {@code Iterable}'s elements * @param <C> the type of the third {@code Iterable}'s elements * @param <D> the type of the fourth {@code Iterable}'s elements * @param <E> the type of the fifth {@code Iterable}'s elements * @param <F> the type of the sixth {@code Iterable}'s elements * @param <G> the type of the seventh {@code Iterable}'s elements * @return all ordered {@code Septuple}s of elements from {@code as}, {@code bs}, {@code cs}, {@code ds}, * {@code es}, {@code fs}, and {@code gs} */ @Override public @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es, @NotNull Iterable<F> fs, @NotNull Iterable<G> gs ) { if (isEmpty(as) || isEmpty(bs) || isEmpty(cs) || isEmpty(ds) || isEmpty(es) || isEmpty(fs) || isEmpty(gs)) return Collections.emptyList(); Iterable<BigInteger> naturalBigIntegers = naturalBigIntegers(); return () -> new EventuallyKnownSizeIterator<Septuple<A, B, C, D, E, F, G>>() { private final @NotNull CachedIterator<A> cas = new CachedIterator<>(as); private final @NotNull CachedIterator<B> cbs = new CachedIterator<>(bs); private final @NotNull CachedIterator<C> ccs = new CachedIterator<>(cs); private final @NotNull CachedIterator<D> cds = new CachedIterator<>(ds); private final @NotNull CachedIterator<E> ces = new CachedIterator<>(es); private final @NotNull CachedIterator<F> cfs = new CachedIterator<>(fs); private final @NotNull CachedIterator<G> cgs = new CachedIterator<>(gs); private final @NotNull Iterator<BigInteger> is = naturalBigIntegers.iterator(); @Override public @NotNull Septuple<A, B, C, D, E, F, G> advance() { while (true) { List<BigInteger> indices = IntegerUtils.demux(7, is.next()); NullableOptional<A> oa = cas.get(indices.get(0).intValueExact()); if (!oa.isPresent()) continue; NullableOptional<B> ob = cbs.get(indices.get(1).intValueExact()); if (!ob.isPresent()) continue; NullableOptional<C> oc = ccs.get(indices.get(2).intValueExact()); if (!oc.isPresent()) continue; NullableOptional<D> od = cds.get(indices.get(3).intValueExact()); if (!od.isPresent()) continue; NullableOptional<E> oe = ces.get(indices.get(4).intValueExact()); if (!oe.isPresent()) continue; NullableOptional<F> of = cfs.get(indices.get(5).intValueExact()); if (!of.isPresent()) continue; NullableOptional<G> og = cgs.get(indices.get(6).intValueExact()); if (!og.isPresent()) continue; if (!outputSizeKnown() && cas.knownSize().isPresent() && cbs.knownSize().isPresent() && ccs.knownSize().isPresent() && cds.knownSize().isPresent() && ces.knownSize().isPresent() && cfs.knownSize().isPresent() && cgs.knownSize().isPresent() ) { setOutputSize( BigInteger.valueOf(cas.knownSize().get()) .multiply(BigInteger.valueOf(cbs.knownSize().get())) .multiply(BigInteger.valueOf(ccs.knownSize().get())) .multiply(BigInteger.valueOf(cds.knownSize().get())) .multiply(BigInteger.valueOf(ces.knownSize().get())) .multiply(BigInteger.valueOf(cfs.knownSize().get())) .multiply(BigInteger.valueOf(cgs.knownSize().get())) ); } return new Septuple<>(oa.get(), ob.get(), oc.get(), od.get(), oe.get(), of.get(), og.get()); } } }; } /** * Returns all {@code Septuple}s of elements from an {@code Iterable}. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result is the Cartesian seventh power of an {@code Iterable}.</li> * </ul> * * Length is |{@code xs}|<sup>7</sup> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all ordered {@code Septuple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> septuples(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.emptyList(); return map( list -> new Septuple<>( list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5), list.get(6) ), lists(7, xs) ); } /** * Returns an {@code Iterable} containing all {@code Lists}s with elements from a given {@code List}. Does not * support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result either consists of a single empty {@code List}, or is infinite. It contains every {@code List} * of elements drawn from some sequence.</li> * </ul> * * Result length is 1 if {@code xs} is empty, infinite otherwise * * @param xs the {@code List} from which elements are selected * @param <T> the type of the given {@code List}'s elements * @return all {@code List}s created from {@code xs} */ @Override public @NotNull <T> Iterable<List<T>> lists(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList()); if (!lengthAtLeast(2, xs)) { T x = head(xs); return iterate(ys -> toList(cons(x, ys)), Collections.emptyList()); } return cons( Collections.emptyList(), optionalMap( p -> p.b, dependentPairsInfiniteLogarithmicOrder( positiveBigIntegers(), i -> concat(nonEmptyOptionals(lists(i.intValueExact(), xs)), repeat(Optional.empty())) ) ) ); } /** * Returns an {@code Iterable} containing all {@code Lists}s with a minimum size with elements from a given * {@code List}. Does not support removal. * * <ul> * <li>{@code minSize} cannot be negative.</li> * <li>{@code xs} cannot be null.</li> * <li>The result either consists of a single empty {@code List}, or is infinite. It contains every {@code List} * (with a length greater than or equal to some minimum) of elements drawn from some sequence.</li> * </ul> * * Result length is 0 if {@code xs} is empty and {@code minSize} is greater than 0, 1 if {@code xs} is empty and * {@code minSize} is 0, and infinite otherwise * * @param minSize the minimum length of the result {@code List}s * @param xs the {@code List} from which elements are selected * @param <T> the type of the given {@code Iterable}'s elements * @return all {@code List}s created from {@code xs} */ @Override public @NotNull <T> Iterable<List<T>> listsAtLeast(int minSize, @NotNull Iterable<T> xs) { if (minSize < 0) { throw new IllegalArgumentException("minSize cannot be negative. Invalid minSize: " + minSize); } if (minSize == 0) return lists(xs); if (isEmpty(xs)) return Collections.emptyList(); if (!lengthAtLeast(2, xs)) { T x = head(xs); return iterate(ys -> toList(cons(x, ys)), toList(replicate(minSize, x))); } return optionalMap( p -> p.b, dependentPairsInfiniteLogarithmicOrder( rangeUp(BigInteger.valueOf(minSize)), i -> concat(nonEmptyOptionals(lists(i.intValueExact(), xs)), repeat(Optional.empty())) ) ); } private static @NotNull Iterable<List<Integer>> distinctListIndices(int size, int elementCount) { BigInteger outputSize = MathUtils.fallingFactorial(BigInteger.valueOf(elementCount), size); Iterable<Integer> range = IterableUtils.range(0, size - 1); return () -> new EventuallyKnownSizeIterator<List<Integer>>() { private final @NotNull List<Integer> list = toList(range); private final @NotNull Set<Integer> taken; private boolean first = true; { taken = new HashSet<>(); taken.addAll(list); setOutputSize(outputSize); } @Override public @NotNull List<Integer> advance() { if (first) { first = false; return list; } for (int i = size - 1; i >= 0; i int index = list.get(i); for (int j = index + 1; j < elementCount; j++) { if (taken.contains(j)) continue; list.set(i, j); taken.remove(index); taken.add(j); int k = i + 1; for (int m = 0; m < elementCount && k < size; m++) { if (taken.contains(m)) continue; list.set(k, m); taken.add(m); k++; } return list; } taken.remove(index); } throw new IllegalStateException(); } }; } /** * Returns an {@code Iterable} containing all {@code List}s of a given length with elements from a given * {@code List}, with no repetitions. The {@code List}s are ordered lexicographically, matching the order given by * the original {@code List}. Does not support removal. * * <ul> * <li>{@code size} cannot be negative.</li> * <li>{@code xs} cannot be null.</li> * <li>The result is finite. All of its elements have the same length. None are empty, unless the result consists * entirely of one empty element.</li> * </ul> * * Length is <sub>|{@code xs}|</sub>P<sub>{@code size}</sub> * * @param size the length of the result lists * @param xs the {@code List} from which elements are selected * @param <T> the type of the given {@code List}'s elements * @return all {@code List}s of a given length created from {@code xs} with no repetitions */ @Override public @NotNull <T> Iterable<List<T>> distinctListsLex(int size, @NotNull List<T> xs) { if (size < 0) { throw new IllegalArgumentException("size cannot be negative. Invalid size: " + size); } return map(is -> toList(map(xs::get, is)), distinctListIndices(size, xs.size())); } /** * Returns all {@code Pair}s of distinct elements from an {@code Iterable}. The {@code Pair}s are ordered * lexicographically, matching the order given by the original {@code Iterable}s. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result contains all distinct {@code Pair}s of elements from an {@code Iterable}.</li> * </ul> * * Length is <sub>|{@code xs}|</sub>P<sub>2</sub> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all distinct ordered {@code Pair}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Pair<T, T>> distinctPairsLex(@NotNull List<T> xs) { return map(list -> new Pair<>(list.get(0), list.get(1)), distinctListsLex(2, xs)); } /** * Returns all {@code Triple}s of distinct elements from an {@code Iterable}. The {@code Triple}s are ordered * lexicographically, matching the order given by the original {@code Iterable}s. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result contains all distinct {@code Triple}s of elements from an {@code Iterable}.</li> * </ul> * * Length is <sub>|{@code xs}|</sub>P<sub>3</sub> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all distinct ordered {@code Triple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Triple<T, T, T>> distinctTriplesLex(@NotNull List<T> xs) { return map(list -> new Triple<>(list.get(0), list.get(1), list.get(2)), distinctListsLex(3, xs)); } /** * Returns all {@code Quadruple}s of distinct elements from an {@code Iterable}. The {@code Quadruple}s are ordered * lexicographically, matching the order given by the original {@code Iterable}s. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result contains all distinct {@code Quadruple}s of elements from an {@code Iterable}.</li> * </ul> * * Length is <sub>|{@code xs}|</sub>P<sub>4</sub> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all distinct ordered {@code Quadruple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Quadruple<T, T, T, T>> distinctQuadruplesLex(@NotNull List<T> xs) { return map( list -> new Quadruple<>(list.get(0), list.get(1), list.get(2), list.get(3)), distinctListsLex(4, xs) ); } /** * Returns all {@code Quintuple}s of distinct elements from an {@code Iterable}. The {@code Quintuple}s are ordered * lexicographically, matching the order given by the original {@code Iterable}s. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result contains all distinct {@code Quintuple}s of elements from an {@code Iterable}.</li> * </ul> * * Length is <sub>|{@code xs}|</sub>P<sub>5</sub> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all distinct ordered {@code Quintuple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> distinctQuintuplesLex(@NotNull List<T> xs) { return map( list -> new Quintuple<>(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4)), distinctListsLex(5, xs) ); } /** * Returns all {@code Sextuple}s of distinct elements from an {@code Iterable}. The {@code Sextuple}s are ordered * lexicographically, matching the order given by the original {@code Iterable}s. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result contains all distinct {@code Sextuple}s of elements from an {@code Iterable}.</li> * </ul> * * Length is <sub>|{@code xs}|</sub>P<sub>6</sub> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all distinct ordered {@code Sextuple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> distinctSextuplesLex(@NotNull List<T> xs) { return map( list -> new Sextuple<>(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5)), distinctListsLex(6, xs) ); } /** * Returns all {@code Septuple}s of distinct elements from an {@code Iterable}. The {@code Septuple}s are ordered * lexicographically, matching the order given by the original {@code Iterable}s. Does not support removal. * * <ul> * <li>{@code xs} cannot be null.</li> * <li>The result contains all distinct {@code Septuple}s of elements from an {@code Iterable}.</li> * </ul> * * Length is <sub>|{@code xs}|</sub>P<sub>6</sub> * * @param xs an {@code Iterable} * @param <T> the type of the {@code Iterable}'s elements * @return all distinct ordered {@code Septuple}s of elements from {@code xs} */ @Override public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> distinctSeptuplesLex(@NotNull List<T> xs) { return map( list -> new Septuple<>( list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5), list.get(6) ), distinctListsLex(7, xs) ); } /** * Returns an {@code Iterable} containing all {@code String}s of a given length with characters from a given * {@code String, with no repetitions. The {@code String}s are ordered lexicographically, matching the order given * by the original {@code String}. Does not support removal. * * <ul> * <li>{@code size} cannot be negative.</li> * <li>{@code s} cannot be null.</li> * <li>The result is finite. All of its {@code String}s have the same length. None are empty, unless the result * consists entirely of one empty {@code String}.</li> * </ul> * * Length is <sub>|{@code s}|</sub>P<sub>{@code size}</sub> * * @param size the length of the result {@code String} * @param s the {@code String} from which characters are selected * @return all Strings of a given length created from {@code s} with no repetitions */ @Override public @NotNull Iterable<String> distinctStringsLex(int size, @NotNull String s) { return map(IterableUtils::charsToString, distinctListsLex(size, toList(fromString(s)))); } public @NotNull <T> Iterable<List<T>> distinctListsLex(@NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> distinctStringsLex(@NotNull String s) { return null; } public @NotNull <T> Iterable<List<T>> distinctListsLexAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> distinctStringsLexAtLeast(int minSize, @NotNull String s) { return null; } public @NotNull <T> Iterable<List<T>> distinctListsShortlex(@NotNull List<T> xs) { int n = length(xs); return filter(IterableUtils::unique, takeWhile(ys -> ys.size() <= n, listsShortlex(xs))); } public @NotNull Iterable<String> distinctStringsShortlex(@NotNull String s) { return null; } public @NotNull <T> Iterable<List<T>> distinctListsShortlexAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> distinctStringsShortlexAtLeast(int minSize, @NotNull String s) { return null; } @Override public @NotNull <T> Iterable<List<T>> distinctLists(int size, @NotNull Iterable<T> xs) { return null; } @Override public @NotNull <T> Iterable<Pair<T, T>> distinctPairs(@NotNull Iterable<T> xs) { return filter(p -> !Objects.equals(p.a, p.b), pairs(xs)); } @Override public @NotNull <T> Iterable<Triple<T, T, T>> distinctTriples(@NotNull Iterable<T> xs) { return filter(t -> !t.a.equals(t.b) && !t.a.equals(t.c) && !t.b.equals(t.c), triples(xs)); } @Override public @NotNull <T> Iterable<Quadruple<T, T, T, T>> distinctQuadruples(@NotNull Iterable<T> xs) { return filter(q -> and(map(p -> !p.a.equals(p.b), pairs(Quadruple.toList(q)))), quadruples(xs)); } @Override public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> distinctQuintuples(@NotNull Iterable<T> xs) { return filter(q -> and(map(p -> !p.a.equals(p.b), pairs(Quintuple.toList(q)))), quintuples(xs)); } @Override public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> distinctSextuples(@NotNull Iterable<T> xs) { return filter(s -> and(map(p -> !p.a.equals(p.b), pairs(Sextuple.toList(s)))), sextuples(xs)); } @Override public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> distinctSeptuples(@NotNull Iterable<T> xs) { return filter(s -> and(map(p -> !p.a.equals(p.b), pairs(Septuple.toList(s)))), septuples(xs)); } @Override public @NotNull Iterable<String> distinctStrings(int size, @NotNull String s) { return null; } @Override public @NotNull Iterable<String> distinctStrings(int size) { return null; } @Override public @NotNull <T> Iterable<List<T>> distinctLists(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.singletonList(new ArrayList<>()); Iterable<List<Integer>> lists = lists(naturalIntegers()); return () -> new NoRemoveIterator<List<T>>() { private final @NotNull CachedIterator<T> cxs = new CachedIterator<>(xs); private final @NotNull Iterator<List<Integer>> xsi = lists.iterator(); private @NotNull Optional<BigInteger> outputSize = Optional.empty(); private @NotNull BigInteger index = BigInteger.ZERO; private boolean reachedEnd = false; @Override public boolean hasNext() { return !reachedEnd; } @Override public List<T> next() { if (reachedEnd) { throw new NoSuchElementException(); } outer: while (true) { List<T> list = new ArrayList<>(); Set<T> seen = new HashSet<>(); List<Integer> indices = xsi.next(); for (int index : indices) { int j = 0; T x; do { NullableOptional<T> ox = cxs.get(j); if (!ox.isPresent()) continue outer; x = ox.get(); j++; } while (seen.contains(x)); for (int i = 0; i < index; i++) { do { NullableOptional<T> ox = cxs.get(j); if (!ox.isPresent()) continue outer; x = ox.get(); j++; } while (seen.contains(x)); } list.add(x); seen.add(x); } if (!outputSize.isPresent() && cxs.knownSize().isPresent()) { outputSize = Optional.of(MathUtils.numberOfArrangementsOfASet(cxs.knownSize().get())); } index = index.add(BigInteger.ONE); if (outputSize.isPresent() && index.equals(outputSize.get())) { reachedEnd = true; } return list; } } }; } @Override public @NotNull Iterable<String> distinctStrings(@NotNull String s) { return null; } @Override public @NotNull <T> Iterable<List<T>> distinctListsAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } @Override public @NotNull Iterable<String> distinctStringsAtLeast(int minSize, @NotNull String s) { return null; } @Override public @NotNull Iterable<String> distinctStringsAtLeast(int minSize) { return null; } public @NotNull <T> Iterable<List<T>> bagsLex(int size, @NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> stringBagsLex(int size, @NotNull String s) { return null; } public @NotNull <T> Iterable<List<T>> bagsShortlex(@NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> stringBagsShortlex(@NotNull String s) { return null; } public @NotNull <T> Iterable<List<T>> bagsShortlexAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> stringBagsShortlexAtLeast(int minSize, @NotNull String s) { return null; } @Override public @NotNull <T> Iterable<List<T>> bags(int size, @NotNull Iterable<T> xs) { return null; } @Override public @NotNull Iterable<String> stringBags(int size, @NotNull String s) { return null; } @Override public @NotNull Iterable<String> stringBags(int size) { return null; } @Override public @NotNull <T> Iterable<List<T>> bags(@NotNull Iterable<T> xs) { return null; } @Override public @NotNull Iterable<String> stringBags(@NotNull String s) { return null; } @Override public @NotNull Iterable<String> stringBags() { return null; } @Override public @NotNull <T> Iterable<List<T>> bagsAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } @Override public @NotNull Iterable<String> stringBagsAtLeast(int minSize, @NotNull String s) { return null; } @Override public @NotNull Iterable<String> stringBagsAtLeast(int minSize) { return null; } public @NotNull <T> Iterable<List<T>> subsetsLex(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Collections.singletonList(new ArrayList<>()); return () -> new NoRemoveIterator<List<T>>() { private final @NotNull CachedIterator<T> cxs = new CachedIterator<>(xs); private @NotNull List<Integer> indices = new ArrayList<>(); @Override public boolean hasNext() { return indices != null; } @Override public List<T> next() { List<T> subsequence = cxs.get(indices).get(); if (indices.isEmpty()) { indices.add(0); } else { int lastIndex = last(indices); if (lastIndex < cxs.size() - 1) { indices.add(lastIndex + 1); } else if (indices.size() == 1) { indices = null; } else { indices.remove(indices.size() - 1); indices.set(indices.size() - 1, last(indices) + 1); } } return subsequence; } }; } public @NotNull Iterable<String> stringSubsetsLex(@NotNull String s) { return map(IterableUtils::charsToString, subsetsLex(fromString(s))); } public @NotNull <T> Iterable<List<T>> subsetsLexAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> stringSubsetsLexAtLeast(int minSize, @NotNull String s) { return null; } public @NotNull <T> Iterable<List<T>> subsetsShortlex(@NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> stringSubsetsShortlex(@NotNull String s) { return null; } public @NotNull <T> Iterable<List<T>> subsetsShortlexAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } public @NotNull Iterable<String> stringSubsetsShortlexAtLeast(int minSize, @NotNull String s) { return null; } @Override public @NotNull <T> Iterable<List<T>> subsets(int size, @NotNull Iterable<T> xs) { return null; } @Override public @NotNull Iterable<String> stringSubsets(int size, @NotNull String s) { return null; } @Override public @NotNull Iterable<String> stringSubsets(int size) { return null; } @Override public @NotNull <T> Iterable<List<T>> subsets(@NotNull Iterable<T> xs) { CachedIterator<T> cxs = new CachedIterator<>(xs); return map( Optional::get, takeWhile( Optional::isPresent, map(i -> cxs.select(IntegerUtils.bits(i)), IterableUtils.rangeUp(BigInteger.ZERO)) ) ); } @Override public @NotNull <T> Iterable<List<T>> subsetsAtLeast(int minSize, @NotNull Iterable<T> xs) { return null; } @Override public @NotNull Iterable<String> stringSubsetsAtLeast(int minSize, @NotNull String s) { return null; } @Override public @NotNull Iterable<String> stringSubsetsAtLeast(int minSize) { return null; } public @NotNull <T> Iterable<List<T>> controlledListsLex(@NotNull List<Iterable<T>> xss) { if (xss.size() == 0) return Collections.singletonList(new ArrayList<>()); if (xss.size() == 1) return map(Collections::singletonList, xss.get(0)); if (xss.size() == 2) return map(p -> Arrays.<T>asList(p.a, p.b), pairsLex(xss.get(0), toList(xss.get(1)))); List<Iterable<T>> leftList = new ArrayList<>(); List<Iterable<T>> rightList = new ArrayList<>(); for (int i = 0; i < xss.size() / 2; i++) { leftList.add(xss.get(i)); } for (int i = xss.size() / 2; i < xss.size(); i++) { rightList.add(xss.get(i)); } Iterable<List<T>> leftLists = controlledListsLex(leftList); Iterable<List<T>> rightLists = controlledListsLex(rightList); return map(p -> toList(concat(p.a, p.b)), pairsLex(leftLists, toList(rightLists))); } @Override public @NotNull Iterable<String> substrings(@NotNull String s) { return nub(super.substrings(s)); } /** * Determines whether {@code this} is equal to {@code that}. This implementation is the same as in * {@link java.lang.Object#equals}, but repeated here for clarity. * * <ul> * <li>{@code this} may be any {@code ExhaustiveProvider}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that The {@code ExhaustiveProvider} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { return this == that; } /** * Calculates the hash code of {@code this}. * * <ul> * <li>{@code this} may be any {@code ExhaustiveProvider}.</li> * <li>The result is 0.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { return 0; } /** * Creates a {@code String} representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code ExhaustiveProvider}.</li> * <li>The result is {@code "ExhaustiveProvider"}.</li> * </ul> * * @return a {@code String} representation of {@code this} */ @Override public String toString() { return "ExhaustiveProvider"; } }
package duro.reflang; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Hashtable; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTreeWalker; import duro.reflang.antlr4.DuroBaseListener; import duro.reflang.antlr4.DuroLexer; import duro.reflang.antlr4.DuroParser; import duro.reflang.antlr4.DuroParser.IntegerContext; import duro.reflang.antlr4.DuroParser.AssignmentContext; import duro.reflang.antlr4.DuroParser.PauseContext; import duro.reflang.antlr4.DuroParser.ProgramContext; import duro.runtime.CustomProcess; import duro.runtime.Instruction; public class Compiler { public static duro.runtime.Process compile(InputStream sourceCode) throws IOException { CharStream charStream = new ANTLRInputStream(sourceCode); DuroLexer lexer = new DuroLexer(charStream); TokenStream tokenStream = new CommonTokenStream(lexer); DuroParser parser = new DuroParser(tokenStream); ProgramContext programCtx = parser.program(); final Hashtable<String, Integer> idToIndexMap = new Hashtable<String, Integer>(); final ArrayList<Instruction> instructions = new ArrayList<Instruction>(); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(new DuroBaseListener() { @Override public void enterInteger(IntegerContext ctx) { int value = Integer.parseInt(ctx.INT().getText()); instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, value)); } @Override public void exitAssignment(AssignmentContext ctx) { String id = ctx.ID().getText(); Integer index = idToIndexMap.get(id); if(index == null) { index = idToIndexMap.size(); idToIndexMap.put(id, index); } instructions.add(new Instruction(Instruction.OPCODE_STORE, index)); } @Override public void enterPause(PauseContext ctx) { instructions.add(new Instruction(Instruction.OPCODE_PAUSE)); } }, programCtx); return new CustomProcess(idToIndexMap.size(), instructions.toArray(new Instruction[instructions.size()])); } }
package net.imagej.ops.image.ascii; import net.imagej.ops.Ops; import net.imagej.ops.special.function.AbstractUnaryFunctionOp; import net.imagej.ops.special.function.Functions; import net.imagej.ops.special.function.UnaryFunctionOp; import net.imglib2.Cursor; import net.imglib2.IterableInterval; import net.imglib2.type.numeric.RealType; import net.imglib2.util.Pair; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Generates an ASCII version of an image. * <p> * Only the first two dimensions of the image are considered. * </p> * * @author Curtis Rueden */ @Plugin(type = Ops.Image.ASCII.class) public class DefaultASCII<T extends RealType<T>> extends AbstractUnaryFunctionOp<IterableInterval<T>, String> implements Ops.Image.ASCII { private static final String CHARS = " .,-+o*O @Parameter(required = false) private T min; @Parameter(required = false) private T max; private UnaryFunctionOp<IterableInterval<T>, Pair<T, T>> minMaxFunc; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void initialize() { minMaxFunc = (UnaryFunctionOp) Functions.unary(ops(), Ops.Stats.MinMax.class, Pair.class, in()); } @Override public String calculate(final IterableInterval<T> input) { if (min == null || max == null) { final Pair<T, T> minMax = minMaxFunc.calculate(input); if (min == null) min = minMax.getA(); if (max == null) max = minMax.getB(); } return ascii(input, min, max); } // -- Utility methods -- public static <T extends RealType<T>> String ascii( final IterableInterval<T> image, final T min, final T max) { final long dim0 = image.dimension(0); final long dim1 = image.dimension(1); // TODO: Check bounds. final int w = (int) (dim0 + 1); final int h = (int) dim1; // span = max - min final T span = max.copy(); span.sub(min); // allocate ASCII character array final char[] c = new char[w * h]; for (int y = 1; y <= h; y++) { c[w * y - 1] = '\n'; // end of row } // loop over all available positions final Cursor<T> cursor = image.localizingCursor(); final int[] pos = new int[image.numDimensions()]; final T tmp = image.firstElement().copy(); while (cursor.hasNext()) { cursor.fwd(); cursor.localize(pos); final int index = w * pos[1] + pos[0]; // normalized = (value - min) / (max - min) tmp.set(cursor.get()); tmp.sub(min); final double normalized = tmp.getRealDouble() / span.getRealDouble(); final int charLen = CHARS.length(); final int charIndex = (int) (charLen * normalized); c[index] = CHARS.charAt(charIndex < charLen ? charIndex : charLen - 1); } return new String(c); } }
package net.openhft.chronicle.bytes; import net.openhft.chronicle.core.OS; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; /** * Bytes to wrap memory mapped data. */ public class MappedBytes extends AbstractBytes<Void> { private final MappedFile mappedFile; // assume the mapped file is reserved already. public MappedBytes(MappedFile mappedFile) throws IllegalStateException { super(NoBytesStore.noBytesStore(), NoBytesStore.noBytesStore().writePosition(), NoBytesStore.noBytesStore().writeLimit()); this.mappedFile = mappedFile; clear(); } @NotNull public static MappedBytes mappedBytes(@NotNull String filename, long chunkSize) throws FileNotFoundException, IllegalStateException { return mappedBytes(new File(filename), chunkSize); } @NotNull public static MappedBytes mappedBytes(@NotNull File file, long chunkSize) throws FileNotFoundException, IllegalStateException { MappedFile rw = new MappedFile(file, chunkSize, OS.pageSize()); return new MappedBytes(rw); } @Override public BytesStore<Bytes<Void>, Void> copy() { return NativeBytes.copyOf(this); } @Override public long capacity() { return mappedFile == null ? 0L : mappedFile.capacity(); } @Override public long refCount() { return Math.max(super.refCount(), mappedFile.refCount()); } @Override protected void readCheckOffset(long offset, long adding) throws BufferUnderflowException, IORuntimeException { if (!bytesStore.inside(offset)) { BytesStore oldBS = bytesStore; try { bytesStore = (BytesStore) mappedFile.acquireByteStore(offset); oldBS.release(); } catch (IOException | IllegalStateException e) { throw new IORuntimeException(e); } catch (IllegalArgumentException e) { throw new BufferUnderflowException(); } } } @Override protected void writeCheckOffset(long offset, long adding) throws BufferOverflowException, IORuntimeException { if (!bytesStore.inside(offset)) { BytesStore oldBS = bytesStore; try { bytesStore = (BytesStore) mappedFile.acquireByteStore(offset); oldBS.release(); } catch (IOException | IllegalStateException e) { throw new IORuntimeException(e); } catch (IllegalArgumentException e) { throw new BufferOverflowException(); } } } @Override public long start() { return 0L; } @Override protected void performRelease() { super.performRelease(); mappedFile.close(); } @Override public boolean isElastic() { return true; } @NotNull @Override public Bytes<Void> write(BytesStore buffer, long offset, long length) { throw new UnsupportedOperationException("todo"); } }
package net.sf.gaboto.time; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import net.sf.gaboto.Gaboto; import net.sf.gaboto.IncoherenceException; import net.sf.gaboto.util.GabotoPredefinedQueries; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import de.fuberlin.wiwiss.ng4j.NamedGraph; /** * <p> * Querying the cdg (see {@link Gaboto#getContextDescriptionGraph()}) using SPARQL is * hardly possible (or at least not feasible). TimeDimensionIndexer relieves Gaboto of * that problem by parsing all time information into a Java representation and providing * methods to query that information. * </p> * NOTE This class does not use any proper data structure to do the task. * * TODO think of a proper tree to do the indexing! * * @author Arno Mittelbach * */ public class TimeDimensionIndexer { private Map<String, TimeSpan> lookup = new HashMap<String, TimeSpan>(); /** * Builds the index. * * @param graphset The graphset the index should be built upon. */ public void createIndex(Model cdg) throws IncoherenceException { System.err.println("Creating time index"); String query = GabotoPredefinedQueries.getTimeDimensionIndexQuery(); QueryExecution qe = QueryExecutionFactory.create( query, cdg ); ResultSet rs = qe.execSelect(); int count = 0; while(rs.hasNext()){ QuerySolution qs = rs.nextSolution(); count++; // get variables RDFNode graphNode = qs.get("graph"); RDFNode startYearNode = qs.get("beginDescYear"); RDFNode startMonthNode = qs.get("beginDescMonth"); RDFNode startDayNode = qs.get("beginDescDay"); RDFNode durationYearNode = qs.get("durationYears"); RDFNode durationMonthNode = qs.get("durationMonths"); RDFNode durationDayNode = qs.get("durationDays"); // extract graph String graph = ((Resource)graphNode).getURI(); try{ // extract timespan TimeSpan ts = new TimeSpan(); ts.setStartYear(((Literal)startYearNode).getInt()); if(null != startMonthNode) ts.setStartMonth(((Literal)startMonthNode).getInt()); if(startDayNode != null) ts.setStartDay(((Literal)startDayNode).getInt()); if(durationYearNode != null) ts.setDurationYear(((Literal)durationYearNode).getInt()); if(durationMonthNode != null) ts.setDurationMonth(((Literal)durationMonthNode).getInt()); if(durationDayNode != null) ts.setDurationDay(((Literal)durationDayNode).getInt()); add(graph, ts); } catch(IllegalArgumentException e){ throw new IncoherenceException("The data seems to be corrupt. Can not load graph " + graph , e); } } System.err.println("Added " + count + " to time index"); } /** * Adds another graph to the index. * * @param graph The graph's name. * @param ts The graph's time span. */ public void add(String graph, TimeSpan ts){ lookup.put(graph, ts); } /** * Adds another graph to the index. * * @param graph The graph. * @param ts The graph's time span. */ public void add(NamedGraph graph, TimeSpan ts){ add(graph.getGraphName().getURI(), ts); } /** * Returns the time span for a given graph * * @param graphURI The graph's name. * * @return The graph's time span (or null). */ public Collection<String> getGraphsForDuration(TimeSpan ts) { Set<String> graphs = new HashSet<String>(); for(Entry<String, TimeSpan> entry : lookup.entrySet()) if(entry.getValue().contains(ts)) graphs.add(entry.getKey()); return graphs; } /** * Returns all the graphs that hold information which is valid at the given point in time. * * @param ti The time instant. * * @return A collection of graph names. */ public Collection<String> getGraphsForInstant(TimeInstant ti) { Set<String> graphs = new HashSet<String>(); for(Entry<String, TimeSpan> entry : lookup.entrySet()) { if(entry.getValue().contains(ti)) { graphs.add(entry.getKey()); } else { System.err.println("Ignoring " + entry.getKey()); } } return graphs; } /** * Returns all the graphs that hold information which is valid over a given time span. * * @param ts The time span. * * @return A collection of graph names. */ public TimeSpan getTimeSpanFor(String graphURI) { return lookup.get(graphURI); } }
package org.broad.igv.prefs; import org.apache.log4j.Logger; import org.broad.igv.DirectoryManager; import org.broad.igv.Globals; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.FileDialogUtils; import org.broad.igv.ui.util.UIUtilities; import javax.swing.*; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.io.*; import java.util.*; import java.util.List; public class PreferenceEditorNew { private static Logger log = Logger.getLogger(PreferenceEditorNew.class); private static final Font labelFont = new Font("Lucida Grande", Font.BOLD, 14); public static void main(String[] args) throws IOException { open(null); } public static void open(Frame parent) throws IOException { List<PreferencesManager.PreferenceGroup> preferenceGroups = PreferencesManager.loadPreferenceList(); SwingUtilities.invokeLater(() -> { JDialog frame = new JDialog(parent, "Preferences", true); final JPanel panel = new JPanel(); SwingUtilities.invokeLater(() -> { init(frame, panel, preferenceGroups); }); panel.setPreferredSize(new Dimension(750, 590)); panel.setMaximumSize(new Dimension(750, 590)); frame.add(panel); frame.pack(); frame.setSize(800, 600); frame.setLocationRelativeTo(parent); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); }); } private static void init(final JDialog parent, JPanel panel, List<PreferencesManager.PreferenceGroup> preferenceGroups) { // final Map<String, String> updatedPrefs = new HashMap<>(); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.setPreferredSize(new Dimension(750, 590)); tabbedPane.setMaximumSize(new Dimension(750, 590)); panel.setLayout(new BorderLayout()); panel.add(tabbedPane, BorderLayout.CENTER); Map<String, Map<String, String>> updatedPreferencesMap = new HashMap<>(); for (PreferencesManager.PreferenceGroup entry : preferenceGroups) { if (entry.tabLabel.equals("Hidden")) continue; final IGVPreferences preferences = PreferencesManager.getPreferences(entry.category); final Map<String, String> updatedPrefs = updatedPreferencesMap.containsKey(entry.category) ? updatedPreferencesMap.get(entry.category) : new HashMap<>(); updatedPreferencesMap.put(entry.category, updatedPrefs); final String tabLabel = entry.tabLabel; JScrollPane scrollPane = new JScrollPane(); scrollPane.setPreferredSize(new Dimension(750, 590)); scrollPane.setMaximumSize(new Dimension(750, 590)); scrollPane.setName(tabLabel); tabbedPane.addTab(tabLabel, scrollPane); JPanel content = new JPanel(); // content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); int contentRow = 0; GridBagLayout contentGrid = new GridBagLayout(); content.setLayout(contentGrid); scrollPane.setViewportView(content); JPanel group = new JPanel(); int row = 0; GridBagLayout grid = new GridBagLayout(); group.setLayout(grid); contentGrid.addLayoutComponent(group, new GridBagConstraints(0, contentRow++, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 5, 5)); content.add(group); String currentGroup = null; // Add an empty spacer component to fill any remaining horizontal group space JLabel groupSpacer = new JLabel(" "); groupSpacer.setPreferredSize(new Dimension(1, 1)); grid.addLayoutComponent(groupSpacer, new GridBagConstraints(0, row++, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); group.add(groupSpacer); for (PreferencesManager.Preference pref : entry.preferences) { try { if (pref.getKey().equals(PreferencesManager.SEPARATOR_KEY)) { JSeparator sep = new JSeparator(); grid.addLayoutComponent(sep, new GridBagConstraints(0, row, 4, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 2)); group.add(sep); row++; continue; } if (pref.getKey().equals(PreferencesManager.INFO_KEY)) { row++; JLabel label = new JLabel(pref.getLabel()); label.setFont(labelFont); grid.addLayoutComponent(label, new GridBagConstraints(0, row, 4, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(3, 5, 5, 5), 5, 2)); group.add(label); row++; continue; } if (pref.group != null && !pref.group.equals(currentGroup)) { // Start a new group row = 0; if (group.getComponentCount() > 0) { // Don't create a new JPanel and Layout if nothing has been added to the existing one. group = new JPanel(); grid = new GridBagLayout(); group.setLayout(grid); contentGrid.addLayoutComponent(group, new GridBagConstraints(0, contentRow++, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 5, 5)); content.add(group); // Add an empty spacer component to fill any remaining horizontal group space groupSpacer = new JLabel(" "); groupSpacer.setPreferredSize(new Dimension(1, 1)); grid.addLayoutComponent(groupSpacer, new GridBagConstraints(0, row++, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); group.add(groupSpacer); } currentGroup = pref.group; group.setBorder(BorderFactory.createTitledBorder(currentGroup)); } if (pref.getType().equals("boolean")) { JCheckBox cb = new JCheckBox(pref.getLabel()); cb.setSelected(preferences.getAsBoolean(pref.getKey())); cb.addActionListener(event -> { updatedPrefs.put(pref.getKey(), Boolean.toString(cb.isSelected())); log.debug("Set " + pref.getLabel() + ": " + cb.isSelected()); }); grid.addLayoutComponent(cb, new GridBagConstraints(0, row, 2, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(3, 5, 2, 5), 2, 2)); group.add(cb); if (pref.getComment() != null) { cb.setToolTipText(pref.getComment()); } } else if (pref.getType().startsWith("select")) { JLabel label = new JLabel(pref.getLabel()); String[] selections = Globals.whitespacePattern.split(pref.getType())[1].split("\\|"); final JComboBox<String> comboBox = new JComboBox<String>(selections); comboBox.setSelectedItem(pref.getDefaultValue().toString()); comboBox.addActionListener(event -> { log.debug("Set " + pref.getLabel() + " " + comboBox.getSelectedItem()); }); grid.addLayoutComponent(label, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 5, 2, 3), 2, 2)); grid.addLayoutComponent(comboBox, new GridBagConstraints(1, row, 3, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 2, 2, 5), 2, 2)); group.add(label); group.add(comboBox); if (pref.getComment() != null) { label.setToolTipText(pref.getComment()); comboBox.setToolTipText(pref.getComment()); } } else { JLabel label = new JLabel(pref.getLabel()); JTextField field = new JTextField(preferences.get(pref.getKey())); Dimension d = field.getPreferredSize(); d.width = 300; field.setPreferredSize(d); field.setMaximumSize(d); field.addActionListener(event -> { final String text = field.getText(); if (validate(text, pref.getType())) { updatedPrefs.put(pref.getKey(), text); } else { field.setText(preferences.get(pref.getKey())); } }); field.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { // Validate and save the value if the Preference field loses focus final String text = field.getText(); if (validate(text, pref.getType())) { updatedPrefs.put(pref.getKey(), text); } else { field.setText(preferences.get(pref.getKey())); } } }); grid.addLayoutComponent(label, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 5, 2, 3), 2, 2)); grid.addLayoutComponent(field, new GridBagConstraints(1, row, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 2, 2, 5), 2, 2)); group.add(label); group.add(field); if (pref.getComment() != null) { label.setToolTipText(pref.getComment()); field.setToolTipText(pref.getComment()); } } row++; } catch (Exception e) { e.printStackTrace(); } } if (tabLabel.equalsIgnoreCase("Cram")) { // Add Cram cache directory management at the end. This is a special case String currentDirectory = DirectoryManager.getFastaCacheDirectory().getAbsolutePath(); final JLabel currentDirectoryLabel = new JLabel("Cache directory: " + currentDirectory); final JButton moveButton = new JButton("Move..."); row++; grid.addLayoutComponent(currentDirectoryLabel, new GridBagConstraints(0, row, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 5, 2, 5), 2, 2)); grid.addLayoutComponent(moveButton, new GridBagConstraints(1, row, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 5, 2, 5), 2, 2)); group.add(currentDirectoryLabel); group.add(moveButton); moveButton.addActionListener(event -> { UIUtilities.invokeOnEventThread(() -> { final File directory = DirectoryManager.getFastaCacheDirectory(); final File newDirectory = FileDialogUtils.chooseDirectory("Select cache directory", DirectoryManager.getUserDirectory()); if (newDirectory != null && !newDirectory.equals(directory)) { DirectoryManager.moveDirectoryContents(directory, newDirectory); SwingUtilities.invokeLater(() -> currentDirectoryLabel.setText(newDirectory.getAbsolutePath())); } }); }); } if (tabLabel.equalsIgnoreCase("Advanced")) { // Add IGV directory management at the end. This is a special case String currentDirectory = DirectoryManager.getIgvDirectory().getAbsolutePath(); final JLabel currentDirectoryLabel = new JLabel("IGV Directory: " + currentDirectory); final JButton moveButton = new JButton("Move..."); row++; grid.addLayoutComponent(currentDirectoryLabel, new GridBagConstraints(0, row, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 5, 2, 5), 2, 2)); grid.addLayoutComponent(moveButton, new GridBagConstraints(1, row, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 5, 2, 5), 2, 2)); group.add(currentDirectoryLabel); group.add(moveButton); moveButton.addActionListener(event -> { UIUtilities.invokeOnEventThread(() -> { final File igvDirectory = DirectoryManager.getIgvDirectory(); final File newDirectory = FileDialogUtils.chooseDirectory("Select IGV directory", DirectoryManager.getUserDirectory()); if (newDirectory != null && !newDirectory.equals(igvDirectory)) { DirectoryManager.moveIGVDirectory(newDirectory); SwingUtilities.invokeLater(() -> currentDirectoryLabel.setText(newDirectory.getAbsolutePath())); } }); }); } // Add an empty spacer component to fill any remaining vertical content space in order to give a compact presentation. This will occupy no appreciable space unless contents are too small to fill the ScrollPane JPanel contentSpacer = new JPanel(); contentGrid.addLayoutComponent(contentSpacer, new GridBagConstraints(0, contentRow++, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 2, 2)); content.add(contentSpacer); } JPanel saveCancelPanel = new JPanel(); saveCancelPanel.setBackground(new Color(0x33, 0x66, 0x99)); saveCancelPanel.setPreferredSize(new Dimension(750, 40)); saveCancelPanel.setMaximumSize(new Dimension(750, 40)); JButton cancelButton = new JButton("Cancel"); cancelButton.setPreferredSize(new Dimension(100, 30)); cancelButton.setMaximumSize(new Dimension(100, 30)); cancelButton.addActionListener((event) -> { SwingUtilities.invokeLater(() -> parent.setVisible(false)); }); JButton saveButton = new JButton("Save"); saveButton.setPreferredSize(new Dimension(100, 30)); saveButton.setMaximumSize(new Dimension(100, 30)); saveButton.setDefaultCapable(true); saveButton.addActionListener((event) -> { PreferencesManager.updateAll(updatedPreferencesMap); SwingUtilities.invokeLater(() -> parent.setVisible(false)); if (IGV.hasInstance()) { IGV.getInstance().doRefresh(); } }); saveCancelPanel.add(cancelButton); saveCancelPanel.add(saveButton); panel.add(saveCancelPanel, BorderLayout.SOUTH); } private static boolean validate(String text, String type) { if (type.equals("integer")) { try { Integer.parseInt(text); } catch (NumberFormatException e) { return false; } } else if (type.equals("float")) { try { Double.parseDouble(text); } catch (NumberFormatException e) { return false; } } return true; } }
package org.cryptonit.cloud.interfaces; import java.security.PrivateKey; import java.security.PublicKey; public interface KeyStore { public enum KeyParameters { RSA_2048("RSA", null, 2048), RSA_4096("RSA", null, 4096), EC_P256("EC", "P-256", 256), EC_P384("EC", "P-384", 384), EC_P521("EC", "P-521", 521); final private String algorithm; final private String parameter; final private int size; KeyParameters(String algorithm, String parameter, int size) { this.algorithm = algorithm; this.parameter = parameter; this.size = size; } public String getAlgorithm() { return algorithm; } public String getParameter() { return parameter; } public int getSize() { return size; } }; String generateKey(String domain, KeyParameters params); PrivateKey getPrivateKey(String domain, String keyIdentifier); PublicKey getPublicKey(String domain, String keyIdentifier); }
package org.deepsymmetry.beatlink; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Represents rekordbox metadata (title, artist, etc.) about tracks loaded into players on a DJ Link network. * * @author James Elliott */ public class TrackMetadata { /** * The raw packet data containing the metadata. */ private final List<byte[]> rawFields; /** * Get the raw packet data, to analyze fields that have not yet been reliably understood. * * @return the raw bytes we received from the CDJ when asked for metadata */ public List<byte[]> getRawFields() { List<byte[]> result = new LinkedList<byte[]>(); for (byte[] field: rawFields) { byte[] copy = new byte[field.length]; System.arraycopy(field, 0, copy, 0, field.length); result.add(copy); } return result; } /** * The title of the track. */ private final String title; /** * The artist that created the track. */ private final String artist; /** * The length, in seconds, of the track. */ private final int length; /** * The album on which the track was released. */ private final String album; /** * The comment assigned to the track. */ private final String comment; /** * The dominant key of the track. */ private final String key; /** * The musical genre of the track. */ private final String genre; /** * The label of the track. */ private final String label; /** * Extracts the value of a string field from the metadata. * * @param field the field known to contain a string value. * @return the value present in that field. * * @throws UnsupportedEncodingException if there is a problem interpreting the metadata */ private String extractString(byte[] field) throws UnsupportedEncodingException { if (field.length > 46) { int length = (int) Util.bytesToNumber(field, 42, 4); if (length > 0) { return new String(field, 46, (2 * (length - 1)), "UTF-16"); } } return ""; } /** * Constructor sets all the immutable interpreted fields based on the received content. * * @param device the device number from which the metadata was received * @param fields the metadata that was received * * @throws UnsupportedEncodingException if there is a problem interpreting the metadata */ public TrackMetadata(int device, List<byte[]> fields) throws UnsupportedEncodingException { rawFields = fields; Iterator<byte[]> iterator = fields.iterator(); iterator.next(); // TODO: Consider extracting artwork iterator.next(); title = extractString(iterator.next()); artist = extractString(iterator.next()); album = extractString(iterator.next()); length = (int)Util.bytesToNumber(iterator.next(), 32, 4); iterator.next(); comment = extractString(iterator.next()); key = extractString(iterator.next()); iterator.next(); iterator.next(); genre = extractString(iterator.next()); label = extractString(iterator.next()); } @Override public String toString() { return "Track Metadata: Title: " + title + ", Artist: " + artist + ", Album: " + album + ", Length: " + length + ", Comment: " + comment + ", Key: " + key + ", Genre: " + genre + ", Label: " + label; } /** * Get the artist of the track. * * @return the track artist */ public String getArtist() { return artist; } /** * Get the comment assigned to the track. * * @return the track comment */ public String getComment() { return comment; } /** * Get the genre of the track. * * @return the track genre */ public String getGenre() { return genre; } /** * Get the musical key of the track. * * @return the track key */ public String getKey() { return key; } /** * Get the label assigned the track. * * @return the track label */ public String getLabel() { return label; } /** * Get the length of the track, in seconds. * * @return the track length in seconds. */ public int getLength() { return length; } /** * Get the title of the track. * * @return the track title */ public String getTitle() { return title; } }
package org.jfrog.hudson.util; import com.google.common.base.Function; import com.google.common.collect.Lists; import hudson.model.Hudson; import jenkins.model.Jenkins; import org.apache.commons.lang.StringUtils; import org.jfrog.build.api.util.NullLog; import org.jfrog.build.client.ArtifactoryBuildInfoClient; import org.jfrog.build.client.ProxyConfiguration; import org.jfrog.hudson.*; import java.io.IOException; import java.util.List; /** * @author Shay Yaakov */ public abstract class RepositoriesUtils { public static List<String> getReleaseRepositoryKeysFirst(DeployerOverrider deployer, ArtifactoryServer server) { if (server == null) { return Lists.newArrayList(); } return server.getReleaseRepositoryKeysFirst(deployer); } public static List<String> getSnapshotRepositoryKeysFirst(DeployerOverrider deployer, ArtifactoryServer server) { if (server == null) { return Lists.newArrayList(); } return server.getSnapshotRepositoryKeysFirst(deployer); } public static List<VirtualRepository> getVirtualRepositoryKeys(ResolverOverrider resolverOverrider, DeployerOverrider deployerOverrider, ArtifactoryServer server) { if (server == null) { return Lists.newArrayList(); } return server.getVirtualRepositoryKeys(resolverOverrider, deployerOverrider); } public static List<VirtualRepository> generateVirtualRepos(ArtifactoryBuildInfoClient client) throws IOException { List<VirtualRepository> virtualRepositories; List<String> keys = client.getVirtualRepositoryKeys(); virtualRepositories = Lists.newArrayList(Lists.transform(keys, new Function<String, VirtualRepository>() { public VirtualRepository apply(String from) { return new VirtualRepository(from, from); } })); return virtualRepositories; } public static List<VirtualRepository> getVirtualRepositoryKeys(String url, String credentialsUsername, String credentialsPassword, boolean overridingDeployerCredentials, ArtifactoryServer artifactoryServer) throws IOException { List<VirtualRepository> virtualRepositories; String username; String password; if (overridingDeployerCredentials && StringUtils.isNotBlank(credentialsUsername) && StringUtils.isNotBlank(credentialsPassword)) { username = credentialsUsername; password = credentialsPassword; } else { Credentials deployedCredentials = artifactoryServer.getResolvingCredentials(); username = deployedCredentials.getUsername(); password = deployedCredentials.getPassword(); } ArtifactoryBuildInfoClient client; if (StringUtils.isNotBlank(username)) { client = new ArtifactoryBuildInfoClient(url, username, password, new NullLog()); } else { client = new ArtifactoryBuildInfoClient(url, new NullLog()); } client.setConnectionTimeout(artifactoryServer.getTimeout()); if (Jenkins.getInstance().proxy != null && !artifactoryServer.isBypassProxy()) { client.setProxyConfiguration(createProxyConfiguration(Jenkins.getInstance().proxy)); } virtualRepositories = RepositoriesUtils.generateVirtualRepos(client); return virtualRepositories; } public static List<String> getLocalRepositories(String url, String credentialsUsername, String credentialsPassword, boolean overridingDeployerCredentials, ArtifactoryServer artifactoryServer) throws IOException { List<String> localRepository; String username; String password; if (overridingDeployerCredentials && StringUtils.isNotBlank(credentialsUsername) && StringUtils.isNotBlank(credentialsPassword)) { username = credentialsUsername; password = credentialsPassword; } else { Credentials deployedCredentials = artifactoryServer.getDeployerCredentials(); username = deployedCredentials.getUsername(); password = deployedCredentials.getPassword(); } ArtifactoryBuildInfoClient client; if (StringUtils.isNotBlank(username)) { client = new ArtifactoryBuildInfoClient(url, username, password, new NullLog()); } else { client = new ArtifactoryBuildInfoClient(url, new NullLog()); } client.setConnectionTimeout(artifactoryServer.getTimeout()); if (Jenkins.getInstance().proxy != null && !artifactoryServer.isBypassProxy()) { client.setProxyConfiguration(createProxyConfiguration(Jenkins.getInstance().proxy)); } localRepository = client.getLocalRepositoriesKeys(); return localRepository; } public static ProxyConfiguration createProxyConfiguration(hudson.ProxyConfiguration proxy) { ProxyConfiguration proxyConfiguration = null; if (proxy != null) { proxyConfiguration = new ProxyConfiguration(); proxyConfiguration.host = proxy.name; proxyConfiguration.port = proxy.port; proxyConfiguration.username = proxy.getUserName(); proxyConfiguration.password = proxy.getPassword(); } return proxyConfiguration; } public static ArtifactoryServer getArtifactoryServer(String artifactoryIdentity, List<ArtifactoryServer> artifactoryServers) { if (artifactoryServers != null) { for (ArtifactoryServer server : artifactoryServers) { if (server.getUrl().equals(artifactoryIdentity) || server.getName().equals(artifactoryIdentity)) { return server; } } } return null; } /** * Returns the list of {@link org.jfrog.hudson.ArtifactoryServer} configured. * * @return can be empty but never null. */ public static List<ArtifactoryServer> getArtifactoryServers() { ArtifactoryBuilder.DescriptorImpl descriptor = (ArtifactoryBuilder.DescriptorImpl) Hudson.getInstance().getDescriptor(ArtifactoryBuilder.class); return descriptor.getArtifactoryServers(); } }
package org.kitteh.irc.client.library; import org.kitteh.irc.client.library.element.Actor; import org.kitteh.irc.client.library.element.ChannelUserMode; import org.kitteh.irc.client.library.element.MessageReceiver; import org.kitteh.irc.client.library.element.User; import org.kitteh.irc.client.library.event.channel.ChannelCTCPEvent; import org.kitteh.irc.client.library.event.channel.ChannelInviteEvent; import org.kitteh.irc.client.library.event.channel.ChannelJoinEvent; import org.kitteh.irc.client.library.event.channel.ChannelKickEvent; import org.kitteh.irc.client.library.event.channel.ChannelModeEvent; import org.kitteh.irc.client.library.event.channel.ChannelNoticeEvent; import org.kitteh.irc.client.library.event.channel.ChannelUsersUpdatedEvent; import org.kitteh.irc.client.library.event.client.ClientConnectedEvent; import org.kitteh.irc.client.library.event.user.PrivateCTCPReplyEvent; import org.kitteh.irc.client.library.event.user.PrivateNoticeEvent; import org.kitteh.irc.client.library.event.user.UserNickChangeEvent; import org.kitteh.irc.client.library.exception.KittehISupportProcessingFailureException; import org.kitteh.irc.client.library.util.LCSet; import org.kitteh.irc.client.library.util.QueueProcessingThread; import org.kitteh.irc.client.library.util.Sanity; import org.kitteh.irc.client.library.element.Channel; import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent; import org.kitteh.irc.client.library.event.channel.ChannelPartEvent; import org.kitteh.irc.client.library.event.channel.ChannelTopicEvent; import org.kitteh.irc.client.library.event.user.PrivateCTCPQueryEvent; import org.kitteh.irc.client.library.event.user.PrivateMessageEvent; import org.kitteh.irc.client.library.event.user.UserQuitEvent; import org.kitteh.irc.client.library.util.StringUtil; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.regex.Matcher; import java.util.regex.Pattern; final class IRCClient implements Client { private class ConnectedServerInfo implements ServerInfo { private CaseMapping caseMapping = CaseMapping.RFC1459; private Map<Character, Integer> channelLimits = new HashMap<>(); private String networkName; @Override public CaseMapping getCaseMapping() { return this.caseMapping; } @Override public int getChannelLengthLimit() { return IRCClient.this.actorProvider.getChannelLength(); } @Override public Map<Character, Integer> getChannelLimits() { return new HashMap<>(this.channelLimits); } @Override public Map<Character, ChannelModeType> getChannelModes() { return new HashMap<>(IRCClient.this.modes); } @Override public List<Character> getChannelPrefixes() { List<Character> list = new ArrayList<>(); for (char prefix : IRCClient.this.actorProvider.getChannelPrefixes()) { list.add(prefix); } return list; } @Override public List<ChannelUserMode> getChannelUserModes() { return new ArrayList<>(IRCClient.this.prefixes); } @Override public String getNetworkName() { return this.networkName; } @Override public int getNickLengthLimit() { return IRCClient.this.actorProvider.getNickLength(); } } private class InputProcessor extends QueueProcessingThread<String> { private InputProcessor() { super("Kitteh IRC Client Input Processor (" + IRCClient.this.getName() + ")"); } @Override protected void processElement(String element) { try { IRCClient.this.handleLine(element); } catch (final Throwable thrown) { // NOOP } } } private enum ISupport { CASEMAPPING { @Override boolean process(String value, IRCClient client) { CaseMapping caseMapping = CaseMapping.getByName(value); if (caseMapping != null) { client.serverInfo.caseMapping = caseMapping; return true; } return false; } }, CHANNELLEN { @Override boolean process(String value, IRCClient client) { try { int length = Integer.parseInt(value); client.actorProvider.setChannelLength(length); return true; } catch (NumberFormatException ignored) { return false; } } }, CHANLIMIT { @Override boolean process(String value, IRCClient client) { String[] pairs = value.split(","); Map<Character, Integer> limits = new HashMap<>(); for (String p : pairs) { String[] pair = p.split(":"); if (pair.length != 2) { return false; } int limit; try { limit = Integer.parseInt(pair[1]); } catch (Exception e) { return false; } for (char prefix : pair[0].toCharArray()) { limits.put(prefix, limit); } } if (limits.isEmpty()) { return false; } client.serverInfo.channelLimits = limits; return true; } }, CHANMODES { @Override boolean process(String value, IRCClient client) { String[] modes = value.split(","); Map<Character, ChannelModeType> modesMap = new ConcurrentHashMap<>(); for (int typeId = 0; typeId < modes.length; typeId++) { for (char mode : modes[typeId].toCharArray()) { ChannelModeType type = null; switch (typeId) { case 0: type = ChannelModeType.A_MASK; break; case 1: type = ChannelModeType.B_PARAMETER_ALWAYS; break; case 2: type = ChannelModeType.C_PARAMETER_ON_SET; break; case 3: type = ChannelModeType.D_PARAMETER_NEVER; } modesMap.put(mode, type); } } client.modes = modesMap; return true; } }, CHANTYPES { @Override boolean process(String value, IRCClient client) { if (value.isEmpty()) { return false; } client.actorProvider.setChannelPrefixes(value.toCharArray()); return true; } }, NETWORK { @Override boolean process(String value, IRCClient client) { client.serverInfo.networkName = value; return true; } }, NICKLEN { @Override boolean process(String value, IRCClient client) { try { int length = Integer.parseInt(value); client.actorProvider.setNickLength(length); return true; } catch (NumberFormatException ignored) { return false; } } }, PREFIX { final Pattern PATTERN = Pattern.compile("\\(([a-zA-Z]+)\\)([^ ]+)"); @Override boolean process(String value, IRCClient client) { Matcher matcher = PATTERN.matcher(value); if (!matcher.find()) { return false; } String modes = matcher.group(1); String display = matcher.group(2); if (modes.length() == display.length()) { List<ChannelUserMode> prefixList = new ArrayList<>(); for (int index = 0; index < modes.length(); index++) { prefixList.add(new ActorProvider.IRCChannelUserMode(modes.charAt(index), display.charAt(index))); } client.prefixes = prefixList; } return true; } }; private static final Map<String, ISupport> MAP; private static final Pattern PATTERN = Pattern.compile("([A-Z0-9]+)=(.*)"); static { MAP = new ConcurrentHashMap<>(); for (ISupport iSupport : ISupport.values()) { MAP.put(iSupport.name(), iSupport); } } private static void handle(String arg, IRCClient client) { Matcher matcher = PATTERN.matcher(arg); if (!matcher.find()) { return; } ISupport iSupport = MAP.get(matcher.group(1)); if (iSupport != null) { boolean success = iSupport.process(matcher.group(2), client); if (!success) { client.exceptionListener.queue(new KittehISupportProcessingFailureException(arg)); } } } abstract boolean process(String value, IRCClient client); } private enum MessageTarget { CHANNEL, PRIVATE, UNKNOWN } private final String[] pingPurr = new String[]{"MEOW", "MEOW!", "PURR", "PURRRRRRR"}; private int pingPurrCount; private final Config config; private final InputProcessor processor; private ConnectedServerInfo serverInfo = new ConnectedServerInfo(); private String goalNick; private String currentNick; private String requestedNick; private final Set<Channel> channels = new CopyOnWriteArraySet<>(); private final Set<String> channelsIntended = new LCSet(this); // TODO use lowercasing dependent on ISUPPORT private NettyManager.ClientConnection connection; private final EventManager eventManager = new EventManager(this); private final Listener<Exception> exceptionListener; private final Listener<String> inputListener; private final Listener<String> outputListener; private final ActorProvider actorProvider = new ActorProvider(this); private List<ChannelUserMode> prefixes = new ArrayList<ChannelUserMode>() { { this.add(new ActorProvider.IRCChannelUserMode('o', '@')); this.add(new ActorProvider.IRCChannelUserMode('v', '+')); } }; private Map<Character, ChannelModeType> modes = ChannelModeType.getDefaultModes(); IRCClient(Config config) { this.config = config; this.currentNick = this.requestedNick = this.goalNick = this.config.get(Config.NICK); final String name = this.config.get(Config.NAME); Config.ExceptionConsumerWrapper exceptionListenerWrapper = this.config.get(Config.LISTENER_EXCEPTION); this.exceptionListener = new Listener<>(name, exceptionListenerWrapper == null ? null : exceptionListenerWrapper.getConsumer()); Config.StringConsumerWrapper inputListenerWrapper = this.config.get(Config.LISTENER_INPUT); this.inputListener = new Listener<>(name, inputListenerWrapper == null ? null : inputListenerWrapper.getConsumer()); Config.StringConsumerWrapper outputListenerWrapper = this.config.get(Config.LISTENER_OUTPUT); this.outputListener = new Listener<>(name, outputListenerWrapper == null ? null : outputListenerWrapper.getConsumer()); this.processor = new InputProcessor(); this.connect(); } @Override public void addChannel(String... channels) { Sanity.nullCheck(channels, "Channels cannot be null"); Sanity.truthiness(channels.length > 0, "Channels cannot be empty array"); for (String channelName : channels) { if (!this.actorProvider.isValidChannel(channelName)) { continue; } this.channelsIntended.add(channelName); this.sendRawLine("JOIN :" + channelName); } } @Override public Set<Channel> getChannels() { return Collections.unmodifiableSet(new HashSet<>(this.channels)); } @Override public EventManager getEventManager() { return this.eventManager; } @Override public String getIntendedNick() { return this.goalNick; } @Override public String getName() { return this.config.get(Config.NAME); } @Override public String getNick() { return this.currentNick; } @Override public ServerInfo getServerInfo() { return this.serverInfo; } @Override public void removeChannel(String channelName, String reason) { Sanity.nullCheck(channelName, "Channel cannot be null"); Channel channel = this.actorProvider.getChannel(channelName); if (channel != null) { this.removeChannel(channel, reason); } } @Override public void removeChannel(Channel channel, String reason) { Sanity.nullCheck(channel, "Channel cannot be null"); String channelName = channel.getName(); this.channelsIntended.remove(channelName); if (this.channels.contains(channel)) { this.sendRawLine("PART " + channelName + (reason == null ? "" : " :" + reason)); } } @Override public void sendCTCPMessage(String target, String message) { Sanity.nullCheck(target, "Target cannot be null"); Sanity.nullCheck(message, "Message cannot be null"); Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces"); this.sendRawLine("PRIVMSG " + target + " :" + CTCPUtil.toCTCP(message)); } @Override public void sendCTCPMessage(MessageReceiver target, String message) { Sanity.nullCheck(target, "Target cannot be null"); this.sendCTCPMessage(target.getMessagingName(), message); } @Override public void sendMessage(String target, String message) { Sanity.nullCheck(target, "Target cannot be null"); Sanity.nullCheck(message, "Message cannot be null"); Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces"); this.sendRawLine("PRIVMSG " + target + " :" + message); } @Override public void sendMessage(MessageReceiver target, String message) { Sanity.nullCheck(target, "Target cannot be null"); this.sendMessage(target.getMessagingName(), message); } @Override public void sendNotice(String target, String message) { Sanity.nullCheck(target, "Target cannot be null"); Sanity.nullCheck(message, "Message cannot be null"); Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces"); this.sendRawLine("NOTICE " + target + " :" + message); } @Override public void sendNotice(MessageReceiver target, String message) { Sanity.nullCheck(target, "Target cannot be null"); this.sendNotice(target.getMessagingName(), message); } @Override public void sendRawLine(String message) { Sanity.nullCheck(message, "Message cannot be null"); this.connection.sendMessage(message, false); } @Override public void setAuth(AuthType authType, String name, String pass) { Sanity.nullCheck(authType, "Auth type cannot be null!"); Sanity.nullCheck(name, "Name cannot be null!"); Sanity.nullCheck(pass, "Password cannot be null!"); this.config.set(Config.AUTH_TYPE, authType); this.config.set(Config.AUTH_NAME, name); this.config.set(Config.AUTH_PASS, pass); } @Override public void setMessageDelay(int delay) { Sanity.truthiness(delay > -1, "Delay must be a positive value"); this.config.set(Config.MESSAGE_DELAY, delay); if (this.connection != null) { this.connection.scheduleSending(delay); } } @Override public void setNick(String nick) { Sanity.nullCheck(nick, "Nick cannot be null"); this.goalNick = nick.trim(); this.sendNickChange(this.goalNick); } @Override public void shutdown(String reason) { this.processor.interrupt(); this.connection.shutdown(reason != null && reason.isEmpty() ? null : reason); // Shut these down last, so they get any last firings this.exceptionListener.shutdown(); this.inputListener.shutdown(); this.outputListener.shutdown(); } /** * Queue up a line for processing. * * @param line line to be processed */ void processLine(String line) { if (line.startsWith("PING ")) { this.sendPriorityRawLine("PONG " + line.substring(5)); } else { this.processor.queue(line); } } Config getConfig() { return this.config; } Listener<Exception> getExceptionListener() { return this.exceptionListener; } Listener<String> getInputListener() { return this.inputListener; } Listener<String> getOutputListener() { return this.outputListener; } void authenticate() { AuthType authType = this.config.get(Config.AUTH_TYPE); if (authType != null) { String auth; String authReclaim; String name = this.config.get(Config.AUTH_NAME); String pass = this.config.get(Config.AUTH_PASS); switch (authType) { case GAMESURGE: auth = "PRIVMSG AuthServ@services.gamesurge.net :auth " + name + " " + pass; authReclaim = ""; break; case NICKSERV: default: auth = "PRIVMSG NickServ :identify " + name + " " + pass; authReclaim = "PRIVMSG NickServ :ghost " + name + " " + pass; } if (!this.currentNick.equals(this.goalNick) && authType.isNickOwned()) { this.sendPriorityRawLine(authReclaim); this.sendNickChange(this.goalNick); } this.sendPriorityRawLine(auth); } } void connect() { this.connection = NettyManager.connect(this); // If the server has a password, send that along first if (this.config.get(Config.SERVER_PASSWORD) != null) { this.sendPriorityRawLine("PASS " + this.config.get(Config.SERVER_PASSWORD)); } // Initial USER and NICK messages. Let's just assume we want +iw (send 8) this.sendPriorityRawLine("USER " + this.config.get(Config.USER) + " 8 * :" + this.config.get(Config.REAL_NAME)); this.sendNickChange(this.goalNick); } void ping() { this.sendRawLine("PING :" + this.pingPurr[this.pingPurrCount++ % this.pingPurr.length]); // Connection's asleep, post cat sounds } private String[] handleArgs(String[] split, int start) { final List<String> argsList = new LinkedList<>(); int index = start; for (; index < split.length; index++) { if (split[index].startsWith(":")) { split[index] = split[index].substring(1); argsList.add(StringUtil.combineSplit(split, index)); break; } argsList.add(split[index]); } return argsList.toArray(new String[argsList.size()]); } private void handleLine(final String line) { if ((line == null) || (line.length() == 0)) { return; } final String[] split = line.split(" "); int argsIndex = 1; final String actorName; if (split[0].startsWith(":")) { argsIndex++; actorName = split[0].substring(1); } else { actorName = ""; } final Actor actor = this.actorProvider.getActor(actorName); final String commandString = split[argsIndex - 1]; final String[] args = this.handleArgs(split, argsIndex); int numeric = -1; try { numeric = Integer.parseInt(commandString); } catch (NumberFormatException ignored) { } if (numeric > -1) { this.handleLineNumeric(actor, numeric, args); } else { Command command = Command.getByName(commandString); if (command != null) { this.handleLineCommand(actor, command, args); } } } private void handleLineNumeric(final Actor actor, final int command, final String[] args) { switch (command) { case 1: // Welcome break; case 2: // Your host is... break; case 3: // server created break; case 4: // version / modes // We're in! Start sending all messages. this.authenticate(); this.serverInfo = new ConnectedServerInfo(); this.eventManager.callEvent(new ClientConnectedEvent(this, actor, this.serverInfo)); this.connection.scheduleSending(this.config.get(Config.MESSAGE_DELAY)); break; case 5: // ISUPPORT for (String arg : args) { ISupport.handle(arg, this); } break; case 250: // Highest connection count case 251: // There are X users case 252: // X IRC OPs case 253: // X unknown connections case 254: // X channels formed case 255: // X clients, X servers case 265: // Local users, max case 266: // global users, max break; case 315: // Self is arg 0 if (this.actorProvider.isValidChannel(args[1])) { // target this.eventManager.callEvent(new ChannelUsersUpdatedEvent(this, this.actorProvider.getChannel(args[1]))); } break; // Channel info case 332: // Channel topic case 333: // Topic set by break; case 352: // WHO list // Self is arg 0 if (this.actorProvider.isValidChannel(args[1])) { final String channelName = args[1]; final String ident = args[2]; final String host = args[3]; // server is arg 4 final String nick = args[5]; final String status = args[6]; // The rest I don't care about final User user = (User) this.actorProvider.getActor(nick + "!" + ident + "@" + host); final ActorProvider.IRCChannel channel = this.actorProvider.getChannel(channelName); final Set<ChannelUserMode> modes = new HashSet<>(); for (char prefix : status.substring(1).toCharArray()) { for (ChannelUserMode mode : this.prefixes) { if (mode.getPrefix() == prefix) { modes.add(mode); break; } } } channel.trackUser(user, modes); } break; case 353: // Channel users list (/names). format is 353 nick = #channel :names case 366: // End of /names case 372: // info, such as continued motd case 375: // motd start case 376: // motd end case 422: // MOTD missing break; // Nick errors, try for new nick below case 431: // No nick given case 432: // Erroneous nickname case 433: // Nick in use this.sendNickChange(this.requestedNick + '`'); break; } } private void handleLineCommand(final Actor actor, final Command command, final String[] args) { // CTCP if ((command == Command.NOTICE || command == Command.PRIVMSG) && CTCPUtil.isCTCP(args[1])) { final String ctcpMessage = CTCPUtil.fromCTCP(args[1]); final MessageTarget messageTarget = this.getTypeByTarget(args[0]); User user = (User) actor; switch (command) { case NOTICE: if (messageTarget == MessageTarget.PRIVATE) { this.eventManager.callEvent(new PrivateCTCPReplyEvent(this, user, ctcpMessage)); } break; case PRIVMSG: switch (messageTarget) { case PRIVATE: String reply = null; // Message to send as CTCP reply (NOTICE). Send nothing if null. if (ctcpMessage.equals("VERSION")) { reply = "VERSION I am Kitteh!"; } else if (ctcpMessage.equals("TIME")) { reply = "TIME " + new Date().toString(); } else if (ctcpMessage.equals("FINGER")) { reply = "FINGER om nom nom tasty finger"; } else if (ctcpMessage.startsWith("PING ")) { reply = ctcpMessage; } PrivateCTCPQueryEvent event = new PrivateCTCPQueryEvent(this, user, ctcpMessage, reply); this.eventManager.callEvent(event); reply = event.getReply(); if (reply != null) { this.sendRawLine("NOTICE " + actor.getName() + " :" + CTCPUtil.toCTCP(reply)); } break; case CHANNEL: this.eventManager.callEvent(new ChannelCTCPEvent(this, user, this.actorProvider.getChannel(args[0]), ctcpMessage)); break; } break; } return; // If handled as CTCP we don't care about further handling. } switch (command) { case NOTICE: switch (this.getTypeByTarget(args[0])) { case CHANNEL: this.eventManager.callEvent(new ChannelNoticeEvent(this, (User) actor, this.actorProvider.getChannel(args[0]), args[1])); break; case PRIVATE: this.eventManager.callEvent(new PrivateNoticeEvent(this, (User) actor, args[1])); break; } break; case PRIVMSG: switch (this.getTypeByTarget(args[0])) { case CHANNEL: this.eventManager.callEvent(new ChannelMessageEvent(this, (User) actor, this.actorProvider.getChannel(args[0]), args[1])); break; case PRIVATE: this.eventManager.callEvent(new PrivateMessageEvent(this, (User) actor, args[1])); break; } break; case MODE: // TODO handle this format: "+mode param +mode param" if (this.getTypeByTarget(args[0]) == MessageTarget.CHANNEL) { ActorProvider.IRCChannel channel = this.actorProvider.getChannel(args[0]); String modechanges = args[1]; int currentArg = 2; boolean add; switch (modechanges.charAt(0)) { case '+': add = true; break; case '-': add = false; break; default: return; } for (int i = 1; i < modechanges.length() && currentArg < args.length; i++) { char next = modechanges.charAt(i); if (next == '+') { add = true; } else if (next == '-') { add = false; } else { boolean hasArg; boolean isPrefix = false; for (ChannelUserMode prefix : this.prefixes) { if (prefix.getMode() == next) { isPrefix = true; break; } } if (isPrefix) { hasArg = true; } else { ChannelModeType type = this.modes.get(next); if (type == null) { // TODO clean up error handling return; } hasArg = (add && type.isParameterRequiredOnSetting()) || (!add && type.isParameterRequiredOnRemoval()); } final String nick = hasArg ? args[currentArg++] : null; if (isPrefix) { if (add) { channel.trackUserModeAdd(nick, this.prefixes.get(next)); } else { channel.trackUserModeRemove(nick, this.prefixes.get(next)); } } this.eventManager.callEvent(new ChannelModeEvent(this, actor, channel, add, next, nick)); } } } break; case JOIN: if (actor instanceof User) { // Just in case ActorProvider.IRCChannel channel = this.actorProvider.getChannel(args[0]); User user = (User) actor; channel.trackUserJoin(user); if (user.getNick().equals(this.currentNick)) { this.channels.add(channel); this.sendRawLine("WHO " + channel.getName()); } this.eventManager.callEvent(new ChannelJoinEvent(this, channel, user)); } break; case PART: if (actor instanceof User) { // Just in case ActorProvider.IRCChannel channel = this.actorProvider.getChannel(args[0]); User user = (User) actor; channel.trackUserPart(user); if (user.getNick().equals(this.currentNick)) { this.channels.remove(channel); } this.eventManager.callEvent(new ChannelPartEvent(this, channel, user, args.length > 1 ? args[1] : "")); } break; case QUIT: if (actor instanceof User) { // Just in case this.actorProvider.trackUserQuit((User) actor); this.eventManager.callEvent(new UserQuitEvent(this, (User) actor, args.length > 0 ? args[0] : "")); } break; case KICK: ActorProvider.IRCChannel kickedChannel = this.actorProvider.getChannel(args[0]); if (args[1].equals(this.currentNick)) { this.channels.remove(kickedChannel); } this.eventManager.callEvent(new ChannelKickEvent(this, kickedChannel, actor, kickedChannel.getUser(args[1]), args.length > 2 ? args[2] : "")); break; case NICK: if (actor instanceof User) { User user = (User) actor; if (user.getNick().equals(this.currentNick)) { this.currentNick = args[0]; } this.eventManager.callEvent(new UserNickChangeEvent(this, user, args[0])); } break; case INVITE: Channel invitedChannel = this.actorProvider.getChannel(args[1]); if (this.getTypeByTarget(args[0]) == MessageTarget.PRIVATE && this.channelsIntended.contains(invitedChannel.getName())) { this.sendRawLine("JOIN " + invitedChannel.getName()); } this.eventManager.callEvent(new ChannelInviteEvent(this, invitedChannel, actor, args[0])); break; case TOPIC: this.eventManager.callEvent(new ChannelTopicEvent(this, actor, this.actorProvider.getChannel(args[0]), args[1])); break; default: break; } } private MessageTarget getTypeByTarget(String target) { if (this.currentNick.equalsIgnoreCase(target)) { return MessageTarget.PRIVATE; } if (this.actorProvider.isValidChannel(target)) { return MessageTarget.CHANNEL; } return MessageTarget.UNKNOWN; } private void sendNickChange(String newnick) { this.requestedNick = newnick; this.sendPriorityRawLine("NICK " + newnick); } private void sendPriorityRawLine(String message) { this.connection.sendMessage(message, true); } }
package org.lemsml.jlems.io.xmlio; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.lemsml.jlems.core.logging.E; import org.lemsml.jlems.core.serial.WrapperElement; import org.lemsml.jlems.core.sim.ContentError; import org.lemsml.jlems.core.type.Attribute; import org.lemsml.jlems.core.type.BodyValued; import org.lemsml.jlems.core.type.Component; import org.lemsml.jlems.core.type.Inheritor; import org.lemsml.jlems.core.type.LemsCollection; import org.lemsml.jlems.core.xml.XMLElement; public class XMLSerializer { static HashMap<String, String> defaultAttributeMap = new HashMap<String, String>(); static { defaultAttributeMap.put("eXtends", "extends"); } HashMap<String, String> attributeMap = defaultAttributeMap; boolean conciseTags; boolean quoteStrings; List<Component> refComponents = new ArrayList<Component>(); Boolean includeRefComponents = false; public XMLSerializer() { conciseTags = true; quoteStrings = true; } public XMLSerializer(Boolean includeRefComponents) { conciseTags = true; quoteStrings = true; this.includeRefComponents = includeRefComponents; } public void setConciseTags(boolean b) { conciseTags = b; } public void setQuoteStrings(boolean b) { quoteStrings = b; } public static XMLSerializer newInstance() { return new XMLSerializer(); } public static String serialize(Object ob) throws ContentError { return getSerialization(ob); } public static String getSerialization(Object ob) throws ContentError { return newInstance().writeObject(ob); } public String writeObject(Object obj) throws ContentError { XMLElement xe = makeXMLElement(null, null, null, obj); String serializeObject = xe.serialize(); // If includeRedComponents = true, serialise ref component too // Probably because it is a resolved lems component if (this.includeRefComponents){ this.includeRefComponents = false; for (Component refComponent : refComponents){ serializeObject += makeXMLElement(null, null, null, refComponent).serialize(); } } return serializeObject; } public XMLElement makeXMLElement(XMLElement dest, Object parent, String knownAs, Object ob) throws ContentError { XMLElement ret = null; if (ob instanceof String) { ret = new XMLElement("String"); ret.setBody((String) ob); } else if (ob instanceof Component) { // TODO knownAs intead of null? ret = makeComponentElement(null, (Component) ob); } else if (ob instanceof LemsCollection) { LemsCollection<?> lc = (LemsCollection<?>) ob; if (lc.size() > 0) { ret = new WrapperElement("anon"); for (Object child : lc) { if (parent instanceof Inheritor && ((Inheritor) parent).inherited(child)) { // we inherited it from the parent of the object that // contains the list // dont need to write it out again } else { XMLElement che = makeXMLElement(dest, null, null, child); if (che != null) { ret.add(che); } } } } } else { String tag = "error"; if (knownAs != null) { tag = knownAs; } else { tag = ob.getClass().getName(); if (conciseTags) { int ilast = tag.lastIndexOf("."); if (ilast >= 0) { tag = tag.substring(ilast + 1, tag.length()); } } } String stag = tag; ret = new XMLElement(stag); if (ob instanceof BodyValued) { String sb = ((BodyValued) ob).getBodyValue(); if (sb != null) { ret.setBody(sb); } } Field[] flds = ob.getClass().getFields(); for (int i = 0; i < flds.length; i++) { String fieldName = flds[i].getName(); Object wk = null; try { wk = flds[i].get(ob); } catch (Exception e) { E.warning("failed to get field " + fieldName + " in " + ob); } if (Modifier.isFinal(flds[i].getModifiers())) { wk = null; // not settable } else if (Modifier.isPublic(flds[i].getModifiers())) { if (fieldName.startsWith("p_") || fieldName.startsWith("r_")) { // leave it out all the same - local private and // reference elements } else { // export map may set it null if it shouldn't be // exported if (fieldName != null) { if (wk instanceof Double) { setAttribute(ret, fieldName, "" + ((Double) wk).doubleValue()); } else if (wk instanceof Integer) { setAttribute(ret, fieldName, "" + ((Integer) wk).intValue()); } else if (wk instanceof Boolean) { setAttribute(ret, fieldName, (((Boolean) wk).booleanValue() ? "true" : "false")); } else if (wk instanceof String) { setAttribute(ret, fieldName, (String) wk); } else if (wk instanceof double[]) { setAttribute(ret, fieldName, makeString((double[]) wk)); } else if (wk instanceof int[]) { setAttribute(ret, fieldName, makeString((int[]) wk)); } else if (wk instanceof boolean[]) { setAttribute(ret, fieldName, makeString((boolean[]) wk)); } else if (wk instanceof String[]) { setAttribute(ret, fieldName, makeString((String[]) wk)); } else if (wk != null) { // should child elements be known by the field // name in the parent, or their element type? // XMLElement xe = makeXMLElement(ob, fieldName, XMLElement xe = makeXMLElement(ret, ob, null, wk); if (xe == null) { // must have been something we don't want } else if (xe instanceof WrapperElement) { for (XMLElement sub : xe.getElements()) { ret.add(sub); } } else { ret.add(xe); } } } } } } } return ret; } private void setAttribute(XMLElement ret, String fieldName, String avalue) { String value = avalue; String anm = fieldName; if (attributeMap.containsKey(anm)) { anm = attributeMap.get(anm); } ret.addAttribute(anm, value); } private XMLElement makeComponentElement(String tagName, Component cpt) { String typeName = cpt.getTypeName(); XMLElement ret = null; if (tagName == null) { ret = new XMLElement(typeName); } else { ret = new XMLElement(tagName); ret.addAttribute("type", typeName); } String enm = cpt.getExtendsName(); if (enm != null) { ret.addAttribute("extends", enm); } if (cpt.getID() != null) { ret.addAttribute("id", cpt.getID()); } // ParamValues are the parsed ones - could put them back in with units // added? // for (ParamValue pv : cpt.getParamValues()) { // ret.addAttribute(pv.getName(), pv.parseValue(s)); HashSet<String> atts = new HashSet<String>(); HashMap<String, Component> refHM = cpt.getRefComponents(); if (refHM != null) { for (String s : refHM.keySet()) { Component tgt = refHM.get(s); ret.addAttribute(s, tgt.getID()); atts.add(s); // Add Ref Components to list to serialise them if (includeRefComponents) refComponents.add(tgt); } } for (Attribute att : cpt.getAttributes()) { String sa = att.getName(); if (!atts.contains(sa)) { ret.addAttribute(sa, att.getValue().toString()); } } for (Component cch : cpt.getStrictChildren()) { ret.add(makeComponentElement(null, cch)); } HashMap<String, Component> chm = cpt.getChildHM(); if (chm != null) { for (String s : chm.keySet()) { Component c = chm.get(s); XMLElement xe = makeComponentElement(s, c); ret.add(xe); } } return ret; } private String makeString(double[] wk) { StringBuilder sb = new StringBuilder(); boolean first = true; for (double d : wk) { if (!first) { sb.append(","); } sb.append("" + d); first = false; } return sb.toString(); } private String makeString(int[] wk) { StringBuilder sb = new StringBuilder(); boolean first = true; for (int d : wk) { if (!first) { sb.append(","); } sb.append("" + d); first = false; } return sb.toString(); } // lots to go wrong here... TODO private String makeString(String[] wk) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String d : wk) { if (!first) { sb.append(","); } sb.append("" + d); first = false; } return sb.toString(); } private String makeString(boolean[] wk) { StringBuilder sb = new StringBuilder(); boolean first = true; for (boolean b : wk) { if (!first) { sb.append(","); } sb.append("" + (b ? "true" : "false")); first = false; } return sb.toString(); } }
// Jotto // @description: Module for providing functions to work with IWordPredicate // interface // Classes implementing IWordPredicate are used to find // out whether or not a given word meets some criteria // determined by the implementation of isOK(Word w). public interface IWordPredicate { // Does the given Word meet a condition? public boolean isOK(Word aWord); }
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 Tsinadze * @since 0.0.65-SNAPSHOT * @see org.lightmare.deploy.BeanLoader#initializeDatasource(org.lightmare.deploy.BeanLoader.DataSourceParameters) * @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters) * @see org.lightmare.ejb.EjbConnector */ 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; // Creates and caches ConnectionSemaphore instance for passed unit and // JNDI names 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); } 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(); // Checks if users (EJB beans) for appropriated ConnectionSemaphore is // less or equals minimal amount to close appropriated connection if (users < ConnectionSemaphore.MINIMAL_USERS) { EntityManagerFactory emf = semaphore.getEmf(); JpaManager.closeEntityManagerFactory(emf); unbindConnection(semaphore); 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 removes bindings of * JNDI name from {@link javax.naming.Context} lookups * * @param unitName */ public static void removeConnection(String unitName) { // Removes appropriate connection from cache and JNDI lookup 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(); } }
// MetadataTools.java package loci.formats; import java.util.Arrays; import java.util.Hashtable; import java.util.Map; import loci.common.DateTools; import loci.common.Location; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; import loci.formats.services.OMEXMLService; import ome.xml.model.enums.DimensionOrder; import ome.xml.model.enums.EnumerationException; import ome.xml.model.enums.PixelType; import ome.xml.model.primitives.PositiveInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class MetadataTools { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(MetadataTools.class); // -- Static fields -- // -- Constructor -- private MetadataTools() { } // -- Utility methods - OME-XML -- /** * Populates the 'pixels' element of the given metadata store, using core * metadata from the given reader. */ public static void populatePixels(MetadataStore store, IFormatReader r) { populatePixels(store, r, false, true); } /** * Populates the 'pixels' element of the given metadata store, using core * metadata from the given reader. If the 'doPlane' flag is set, * then the 'plane' elements will be populated as well. */ public static void populatePixels(MetadataStore store, IFormatReader r, boolean doPlane) { populatePixels(store, r, doPlane, true); } /** * Populates the 'pixels' element of the given metadata store, using core * metadata from the given reader. If the 'doPlane' flag is set, * then the 'plane' elements will be populated as well. * If the 'doImageName' flag is set, then the image name will be populated * as well. By default, 'doImageName' is true. */ public static void populatePixels(MetadataStore store, IFormatReader r, boolean doPlane, boolean doImageName) { if (store == null || r == null) return; int oldSeries = r.getSeries(); for (int i=0; i<r.getSeriesCount(); i++) { r.setSeries(i); store.setImageID(createLSID("Image", i), i); if (doImageName) store.setImageName(r.getCurrentFile(), i); String pixelsID = createLSID("Pixels", i); store.setPixelsID(pixelsID, i); store.setPixelsSizeX(new PositiveInteger(r.getSizeX()), i); store.setPixelsSizeY(new PositiveInteger(r.getSizeY()), i); store.setPixelsSizeZ(new PositiveInteger(r.getSizeZ()), i); store.setPixelsSizeC(new PositiveInteger(r.getSizeC()), i); store.setPixelsSizeT(new PositiveInteger(r.getSizeT()), i); store.setPixelsBinDataBigEndian(new Boolean(!r.isLittleEndian()), i, 0); try { store.setPixelsType(PixelType.fromString( FormatTools.getPixelTypeString(r.getPixelType())), i); store.setPixelsDimensionOrder( DimensionOrder.fromString(r.getDimensionOrder()), i); } catch (EnumerationException e) { LOGGER.debug("Failed to create enumeration", e); } if (r.getSizeC() > 0) { Integer sampleCount = new Integer(r.getRGBChannelCount()); for (int c=0; c<r.getEffectiveSizeC(); c++) { store.setChannelID(createLSID("Channel", i, c), i, c); store.setChannelSamplesPerPixel(sampleCount, i, c); } } if (doPlane) { for (int q=0; q<r.getImageCount(); q++) { int[] coords = r.getZCTCoords(q); store.setPlaneTheZ(new Integer(coords[0]), i, q); store.setPlaneTheC(new Integer(coords[1]), i, q); store.setPlaneTheT(new Integer(coords[2]), i, q); } } } r.setSeries(oldSeries); } /** * Constructs an LSID, given the object type and indices. * For example, if the arguments are "Detector", 1, and 0, the LSID will * be "Detector:1:0". */ public static String createLSID(String type, int... indices) { StringBuffer lsid = new StringBuffer(type); for (int index : indices) { lsid.append(":"); lsid.append(index); } return lsid.toString(); } /** * Checks whether the given metadata object has the minimum metadata * populated to successfully describe an Image. * * @throws FormatException if there is a missing metadata field, * or the metadata object is uninitialized */ public static void verifyMinimumPopulated(MetadataRetrieve src) throws FormatException { verifyMinimumPopulated(src, 0); } /** * Checks whether the given metadata object has the minimum metadata * populated to successfully describe the nth Image. * * @throws FormatException if there is a missing metadata field, * or the metadata object is uninitialized */ public static void verifyMinimumPopulated(MetadataRetrieve src, int n) throws FormatException { if (src == null) { throw new FormatException("Metadata object is null; " + "call IFormatWriter.setMetadataRetrieve() first"); } if (src instanceof MetadataStore && ((MetadataStore) src).getRoot() == null) { throw new FormatException("Metadata object has null root; " + "call IMetadata.createRoot() first"); } if (src.getImageID(n) == null) { throw new FormatException("Image ID #" + n + " is null"); } if (src.getPixelsID(n) == null) { throw new FormatException("Pixels ID #" + n + " is null"); } for (int i=0; i<src.getChannelCount(n); i++) { if (src.getChannelID(n, i) == null) { throw new FormatException("Channel ID #" + i + " in Image #" + n + " is null"); } } if (src.getPixelsBinDataBigEndian(n, 0) == null) { throw new FormatException("BigEndian #" + n + " is null"); } if (src.getPixelsDimensionOrder(n) == null) { throw new FormatException("DimensionOrder #" + n + " is null"); } if (src.getPixelsType(n) == null) { throw new FormatException("PixelType #" + n + " is null"); } if (src.getPixelsSizeC(n) == null) { throw new FormatException("SizeC #" + n + " is null"); } if (src.getPixelsSizeT(n) == null) { throw new FormatException("SizeT #" + n + " is null"); } if (src.getPixelsSizeX(n) == null) { throw new FormatException("SizeX #" + n + " is null"); } if (src.getPixelsSizeY(n) == null) { throw new FormatException("SizeY #" + n + " is null"); } if (src.getPixelsSizeZ(n) == null) { throw new FormatException("SizeZ #" + n + " is null"); } } /** * Sets a default creation date. If the named file exists, then the creation * date is set to the file's last modification date. Otherwise, it is set * to the current date. */ public static void setDefaultCreationDate(MetadataStore store, String id, int series) { Location file = new Location(id).getAbsoluteFile(); long time = System.currentTimeMillis(); if (file.exists()) time = file.lastModified(); store.setImageAcquiredDate(DateTools.convertDate(time, DateTools.UNIX), series); } /** * Adjusts the given dimension order as needed so that it contains exactly * one of each of the following characters: 'X', 'Y', 'Z', 'C', 'T'. */ public static String makeSaneDimensionOrder(String dimensionOrder) { String order = dimensionOrder.toUpperCase(); order = order.replaceAll("[^XYZCT]", ""); String[] axes = new String[] {"X", "Y", "C", "Z", "T"}; for (String axis : axes) { if (order.indexOf(axis) == -1) order += axis; while (order.indexOf(axis) != order.lastIndexOf(axis)) { order = order.replaceFirst(axis, ""); } } return order; } // -- Utility methods - original metadata -- /** Gets a sorted list of keys from the given hashtable. */ public static String[] keys(Hashtable<String, Object> meta) { String[] keys = new String[meta.size()]; meta.keySet().toArray(keys); Arrays.sort(keys); return keys; } /** * Merges the given lists of metadata, prepending the * specified prefix for the destination keys. */ public static void merge(Map<String, Object> src, Map<String, Object> dest, String prefix) { for (String key : src.keySet()) { dest.put(prefix + key, src.get(key)); } } // -- Deprecated methods -- private static OMEXMLService omexmlService = createOMEXMLService(); private static OMEXMLService createOMEXMLService() { try { return new ServiceFactory().getInstance(OMEXMLService.class); } catch (DependencyException exc) { return null; } } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#asRetrieve(MetadataStore)} * instead. */ public static MetadataRetrieve asRetrieve(MetadataStore meta) { if (omexmlService == null) return null; return omexmlService.asRetrieve(meta); } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#getLatestVersion()} * instead. */ public static String getLatestVersion() { if (omexmlService == null) return null; return omexmlService.getLatestVersion(); } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#createOMEXMLMetadata()} * instead. */ public static IMetadata createOMEXMLMetadata() { if (omexmlService == null) return null; try { return omexmlService.createOMEXMLMetadata(); } catch (ServiceException exc) { return null; } } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#createOMEXMLMetadata(String)} * instead. */ public static IMetadata createOMEXMLMetadata(String xml) { if (omexmlService == null) return null; try { return omexmlService.createOMEXMLMetadata(xml); } catch (ServiceException exc) { return null; } } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#createOMEXMLMetadata(String, * String)} * instead. */ public static IMetadata createOMEXMLMetadata(String xml, String version) { if (omexmlService == null) return null; try { return omexmlService.createOMEXMLMetadata(xml); } catch (ServiceException exc) { return null; } } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#createOMEXMLRoot(String)} * instead. */ public static Object createOMEXMLRoot(String xml) { if (omexmlService == null) return null; try { return omexmlService.createOMEXMLMetadata(xml); } catch (ServiceException exc) { return null; } } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#isOMEXMLMetadata(Object)} * instead. */ public static boolean isOMEXMLMetadata(Object o) { if (omexmlService == null) return false; return omexmlService.isOMEXMLMetadata(o); } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#isOMEXMLRoot(Object)} * instead. */ public static boolean isOMEXMLRoot(Object o) { if (omexmlService == null) return false; return omexmlService.isOMEXMLRoot(o); } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#getOMEXMLVersion(Object)} * instead. */ public static String getOMEXMLVersion(Object o) { if (omexmlService == null) return null; return omexmlService.getOMEXMLVersion(o); } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#getOMEMetadata(MetadataRetrieve)} * instead. */ public static IMetadata getOMEMetadata(MetadataRetrieve src) { if (omexmlService == null) return null; try { return omexmlService.getOMEMetadata(src); } catch (ServiceException exc) { return null; } } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#getOMEXML(MetadataRetrieve)} * instead. */ public static String getOMEXML(MetadataRetrieve src) { if (omexmlService == null) return null; try { return omexmlService.getOMEXML(src); } catch (ServiceException exc) { return null; } } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#validateOMEXML(String)} * instead. */ public static boolean validateOMEXML(String xml) { if (omexmlService == null) return false; return omexmlService.validateOMEXML(xml); } /** * @deprecated This method is not thread-safe; use * {@link loci.formats.services.OMEXMLService#validateOMEXML(String, boolean)} * instead. */ public static boolean validateOMEXML(String xml, boolean pixelsHack) { if (omexmlService == null) return false; return omexmlService.validateOMEXML(xml, pixelsHack); } }
package org.owasp.esapi.util; /** * Conversion to/from byte arrays to/from short, int, long. The assumption * is that they byte arrays are in network byte order (i.e., big-endian * ordered). * * @see org.owasp.esapi.crypto.CipherTextSerializer * @author kevin.w.wall@gmail.com */ public class ByteConversionUtil { ////////// Convert from short, int, long to byte array. ////////// /** * Returns a byte array containing 2 network byte ordered bytes representing * the given {@code short}. * * @param input An {@code short} to convert to a byte array. * @return A byte array representation of an {@code short} in network byte * order (i.e., big-endian order). */ public static byte[] fromShort(short input) { byte[] output = new byte[2]; output[0] = (byte) (input >> 8); output[1] = (byte) input; return output; } /** * Returns a byte array containing 4 network byte-ordered bytes representing the * given {@code int}. * * @param input An {@code int} to convert to a byte array. * @return A byte array representation of an {@code int} in network byte order * (i.e., big-endian order). */ public static byte[] fromInt(int input) { byte[] output = new byte[4]; output[0] = (byte) (input >> 24); output[1] = (byte) (input >> 16); output[2] = (byte) (input >> 8); output[3] = (byte) input; return output; } /** * Returns a byte array containing 8 network byte-ordered bytes representing * the given {@code long}. * * @param input The {@code long} to convert to a {@code byte} array. * @return A byte array representation of a {@code long}. */ public static byte[] fromLong(long input) { byte[] output = new byte[8]; // Note: I've tried using '>>>' instead of '>>' but that seems to // make no difference. The testLongConversion() still fails // in the same manner. output[0] = (byte) (input >> 56); output[1] = (byte) (input >> 48); output[2] = (byte) (input >> 40); output[3] = (byte) (input >> 32); output[4] = (byte) (input >> 24); output[5] = (byte) (input >> 16); output[6] = (byte) (input >> 8); output[7] = (byte) input; return output; } ////////// Convert from byte array to short, int, long. ////////// /** * Converts a given byte array to an {@code short}. Bytes are expected in * network byte * order. * * @param input A network byte-ordered representation of an {@code short}. * @return The {@code short} value represented by the input array. */ public static short toShort(byte[] input) { assert input.length == 2 : "toShort(): Byte array length must be 2."; short output = 0; output = (short)(((input[0] & 0xff) << 8) | (input[1] & 0xff)); return output; } /** * Converts a given byte array to an {@code int}. Bytes are expected in * network byte order. * * @param input A network byte-ordered representation of an {@code int}. * @return The {@code int} value represented by the input array. */ public static int toInt(byte[] input) { assert input.length == 4 : "toInt(): Byte array length must be 4."; int output = 0; output = ((input[0] & 0xff) << 24) | ((input[1] & 0xff) << 16) | ((input[2] & 0xff) << 8) | (input[3] & 0xff); return output; } /** * Converts a given byte array to a {@code long}. Bytes are expected in * network byte * * @param input A network byte-ordered representation of a {@code long}. * @return The {@code long} value represented by the input array */ public static long toLong(byte[] input) { assert input.length == 8 : "toLong(): Byte array length must be 8."; long output = 0; // Tried both of these ways, each w/ and w/out casts, but // testLongConversion() still failing. // output = (long)((input[0] & 0xff) << 56) | ((input[1] & 0xff) << 48) | // ((input[2] & 0xff) << 40) | ((input[3] & 0xff) << 32) | // ((input[4] & 0xff) << 24) | ((input[5] & 0xff) << 16) | // ((input[6] & 0xff) << 8) | (input[7] & 0xff); output = (long)((input[0] & 0xff) << 56); output |= (long)((input[1] & 0xff) << 48); output |= (long)((input[2] & 0xff) << 40); output |= (long)((input[3] & 0xff) << 32); output |= (long)((input[4] & 0xff) << 24); output |= (long)((input[5] & 0xff) << 16); output |= (long)((input[6] & 0xff) << 8); output |= (long)(input[7] & 0xff); return output; } }
package org.pfaa.geologica.processing; import org.pfaa.chemica.model.Compound.Compounds; import org.pfaa.chemica.model.Mixture; import org.pfaa.chemica.model.MixtureComponent; import org.pfaa.chemica.model.SimpleMixture; public class Solutions { public static final Mixture PURIFIED_BRINE = new SimpleMixture("brine.purified", new MixtureComponent(Compounds.H2O, 1.0), new MixtureComponent(Compounds.NaCl, 0.3)); }
package org.royaldev.royalcommands; import org.bukkit.Bukkit; import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.weather.ThunderChangeEvent; import org.bukkit.event.weather.WeatherChangeEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.royaldev.royalcommands.listeners.InventoryListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; // TODO: Use WE for regions for portals? public class WorldManager { private class WorldWatcher implements Listener { @EventHandler public void worldUnload(WorldUnloadEvent e) { if (e.isCancelled()) return; synchronized (loadedWorlds) { if (loadedWorlds.contains(e.getWorld().getName())) loadedWorlds.remove(e.getWorld().getName()); } } @EventHandler public void worldLoad(WorldLoadEvent e) { synchronized (loadedWorlds) { if (!loadedWorlds.contains(e.getWorld().getName())) loadedWorlds.add(e.getWorld().getName()); addNewToConfig(); } } @EventHandler public void onWorldTele(PlayerChangedWorldEvent e) { World to = e.getPlayer().getWorld(); if (!configuredWorlds.contains(to.getName())) return; if (!loadedWorlds.contains(to.getName())) return; GameMode gm; String mode = config.getString("worlds." + to.getName() + ".gamemode", "SURVIVAL").trim(); if (mode == null) mode = "SURVIVAL"; // how? try { gm = GameMode.valueOf(mode); } catch (IllegalArgumentException ex) { gm = GameMode.SURVIVAL; } e.getPlayer().setGameMode(gm); } @EventHandler public void onWeather(WeatherChangeEvent e) { if (e.isCancelled()) return; World w = e.getWorld(); if (!configuredWorlds.contains(w.getName())) return; if (!loadedWorlds.contains(w.getName())) return; boolean allowWeather = config.getBoolean("worlds." + w.getName() + ".weather", true); if (!allowWeather) e.setCancelled(true); } @EventHandler public void onThunder(ThunderChangeEvent e) { if (e.isCancelled()) return; World w = e.getWorld(); if (!configuredWorlds.contains(w.getName())) return; if (!loadedWorlds.contains(w.getName())) return; boolean allowWeather = config.getBoolean("worlds." + w.getName() + ".weather", true); if (!allowWeather) e.setCancelled(true); } } private final List<String> loadedWorlds = new ArrayList<String>(); private final List<String> configuredWorlds = new ArrayList<String>(); public static InventoryListener il; private final ConfManager config = new ConfManager("worlds.yml"); private final Logger log = RoyalCommands.instance.getLogger(); public WorldManager() { if (!RoyalCommands.useWorldManager) return; if (!config.exists()) config.createFile(); if (config.getConfigurationSection("worlds") != null) { synchronized (configuredWorlds) { for (String key : config.getConfigurationSection("worlds").getKeys(false)) { configuredWorlds.add(key); } } } for (World w : Bukkit.getWorlds()) { if (loadedWorlds.contains(w.getName())) continue; loadedWorlds.add(w.getName()); } addNewToConfig(); setupWorlds(); for (String s : loadedWorlds) { if (!configuredWorlds.contains(s)) continue; World w = Bukkit.getWorld(s); if (w == null) continue; boolean isStorming = config.getBoolean("worlds." + w.getName() + ".is_storming_if_weather_false", false); w.setStorm(isStorming); } il = new InventoryListener(RoyalCommands.instance); Bukkit.getPluginManager().registerEvents(il, RoyalCommands.instance); Bukkit.getPluginManager().registerEvents(new WorldWatcher(), RoyalCommands.instance); } public ConfManager getConfig() { return config; } public void reloadConfig() { config.reload(); setupWorlds(); } public void setupWorlds() { for (String ws : configuredWorlds) { String path = "worlds." + ws + "."; World w = null; if (config.getBoolean(path + "loadatstartup") && Bukkit.getWorld(ws) == null) { try { w = loadWorld(ws); } catch (IllegalArgumentException e) { log.warning("Could not load world " + ws + " as specified in worlds.yml: " + e.getMessage()); continue; } catch (NullPointerException e) { log.warning("Could not load world " + ws + " as specified in worlds.yml: " + e.getMessage()); continue; } } if (!loadedWorlds.contains(ws)) continue; if (w == null) w = Bukkit.getWorld(ws); if (w == null) { log.warning("Could not manage world " + ws + ": No such world"); continue; } w.setSpawnFlags(config.getBoolean(path + "spawnmonsters", true), config.getBoolean(path + "spawnanimals", true)); w.setKeepSpawnInMemory(config.getBoolean("keepspawnloaded", true)); w.setPVP(config.getBoolean(path + "pvp", true)); w.setMonsterSpawnLimit(config.getInteger(path + "monsterspawnlimit", 70)); w.setAnimalSpawnLimit(config.getInteger(path + "animalspawnlimit", 15)); w.setWaterAnimalSpawnLimit(config.getInteger(path + "wateranimalspawnlimit", 5)); w.setTicksPerAnimalSpawns(config.getInteger(path + "animalspawnticks", 400)); w.setTicksPerMonsterSpawns(config.getInteger(path + "monsterspawnticks", 1)); Difficulty d; try { d = Difficulty.valueOf(config.getString(path + "difficulty", "normal").toUpperCase()); } catch (Exception e) { d = Difficulty.NORMAL; } w.setDifficulty(d); } } public void addToLoadedWorlds(String name) { synchronized (loadedWorlds) { if (!loadedWorlds.contains(name)) loadedWorlds.add(name); } } public void addToLoadedWorlds(World w) { synchronized (loadedWorlds) { if (!loadedWorlds.contains(w.getName())) loadedWorlds.add(w.getName()); } } public void removeFromLoadedWorlds(String name) { synchronized (loadedWorlds) { if (loadedWorlds.contains(name)) loadedWorlds.remove(name); } } public void removeFromLoadedWorlds(World w) { synchronized (loadedWorlds) { if (loadedWorlds.contains(w.getName())) loadedWorlds.remove(w.getName()); } } public World loadWorld(String name) throws IllegalArgumentException, NullPointerException { if (Bukkit.getServer().getWorldContainer() == null) throw new NullPointerException("Could not read world files!"); File world = new File(Bukkit.getServer().getWorldContainer(), name); if (!world.exists()) throw new IllegalArgumentException("No such world!"); if (!world.isDirectory()) throw new IllegalArgumentException("World is not a directory!"); WorldCreator wc = new WorldCreator(name); String generator = config.getString("worlds." + name + ".generator", "DefaultGen"); if (generator.equals("DefaultGen")) generator = null; World w; try { wc.generator(generator); w = wc.createWorld(); } catch (Exception e) { // catch silly generators using old code throw new IllegalArgumentException("Generator is using old code!"); } synchronized (loadedWorlds) { loadedWorlds.add(w.getName()); } return w; } /** * Attempts to unload a world * * @param w World to unload * @return If world was unloaded */ public boolean unloadWorld(World w) { boolean worked = Bukkit.unloadWorld(w, true); synchronized (loadedWorlds) { if (loadedWorlds.contains(w.getName()) && worked) loadedWorlds.remove(w.getName()); } return worked; } /** * Attempts to unload a world * * @param name Name of world to unload * @return If world was unloaded */ public boolean unloadWorld(String name) { boolean worked = Bukkit.unloadWorld(name, true); synchronized (loadedWorlds) { if (loadedWorlds.contains(name) && worked) loadedWorlds.remove(name); } return worked; } public void addNewToConfig() { for (String ws : loadedWorlds) { if (configuredWorlds.contains(ws)) continue; World w = Bukkit.getWorld(ws); if (w == null) continue; String path = "worlds." + ws + "."; config.setString(ws, path + "displayname"); config.setBoolean(w.getAllowMonsters(), path + "spawnmonsters"); config.setBoolean(w.getAllowAnimals(), path + "spawnanimals"); config.setBoolean(w.getKeepSpawnInMemory(), path + "keepspawnloaded"); config.setBoolean(w.canGenerateStructures(), path + "generatestructures"); config.setBoolean(w.getPVP(), path + "pvp"); config.setBoolean(true, path + "weather"); config.setInteger(w.getMaxHeight(), path + "maxheight"); config.setInteger(w.getMonsterSpawnLimit(), path + "monsterspawnlimit"); config.setInteger(w.getAnimalSpawnLimit(), path + "animalspawnlimit"); config.setInteger(w.getWaterAnimalSpawnLimit(), path + "wateranimalspawnlimit"); config.setLong(w.getTicksPerAnimalSpawns(), path + "animalspawnticks"); config.setLong(w.getTicksPerMonsterSpawns(), path + "monsterspawnticks"); config.setString(w.getDifficulty().name(), path + "difficulty"); config.setString(w.getWorldType().name(), path + "worldtype"); config.setString(w.getEnvironment().name(), path + "environment"); config.setString(Bukkit.getServer().getDefaultGameMode().name(), path + "gamemode"); if (w.getGenerator() == null) config.setString("DefaultGen", path + "generator"); config.setLong(w.getSeed(), path + "seed"); config.setBoolean(false, path + "freezetime"); config.setBoolean(true, path + "loadatstartup"); } } /** * Gets a world based on its alias (case-insensitive). * * @param name Alias of world * @return World or null if no matching alias */ public World getWorld(String name) { World w; for (String s : loadedWorlds) { String path = "worlds." + s + "."; if (config.getString(path + "displayname", "").equalsIgnoreCase(name)) { w = Bukkit.getWorld(s); return w; } } return null; } /** * Gets a world based on its alias (case-sensitive). * * @param name Alias of world * @return World or null if no matching alias */ public World getCaseSensitiveWorld(String name) { World w; for (String s : loadedWorlds) { String path = "worlds." + s + "."; if (config.getString(path + "displayname", "").equals(name)) { w = Bukkit.getWorld(s); return w; } } return null; } }
package org.scijava.plugin; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.scijava.InstantiableException; import org.scijava.Priority; import org.scijava.event.EventService; import org.scijava.log.LogService; import org.scijava.plugin.event.PluginsAddedEvent; import org.scijava.plugin.event.PluginsRemovedEvent; import org.scijava.service.AbstractService; import org.scijava.service.Service; import org.scijava.util.ListUtils; @Plugin(type = Service.class) public class DefaultPluginService extends AbstractService implements PluginService { @Parameter private LogService log; @Parameter private EventService eventService; /** Index of registered plugins. */ private PluginIndex pluginIndex; // -- PluginService methods -- @Override public PluginIndex getIndex() { return pluginIndex; } @Override public void reloadPlugins() { // clear all old plugins, and notify interested parties final List<PluginInfo<?>> oldPlugins = pluginIndex.getAll(); pluginIndex.clear(); if (oldPlugins.size() > 0) { eventService.publish(new PluginsRemovedEvent(oldPlugins)); } // re-discover all available plugins, and notify interested parties pluginIndex.discover(); final List<PluginInfo<?>> newPlugins = pluginIndex.getAll(); if (newPlugins.size() > 0) { eventService.publish(new PluginsAddedEvent(newPlugins)); } logExceptions(); } @Override public void addPlugin(final PluginInfo<?> plugin) { if (pluginIndex.add(plugin)) { eventService.publish(new PluginsAddedEvent(plugin)); } } @Override public <T extends PluginInfo<?>> void addPlugins(final Collection<T> plugins) { if (pluginIndex.addAll(plugins)) { eventService.publish(new PluginsAddedEvent(plugins)); } } @Override public void removePlugin(final PluginInfo<?> plugin) { if (pluginIndex.remove(plugin)) { eventService.publish(new PluginsRemovedEvent(plugin)); } } @Override public <T extends PluginInfo<?>> void removePlugins( final Collection<T> plugins) { if (pluginIndex.removeAll(plugins)) { eventService.publish(new PluginsRemovedEvent(plugins)); } } @Override public List<PluginInfo<?>> getPlugins() { return pluginIndex.getAll(); } @Override public <P extends SciJavaPlugin> PluginInfo<SciJavaPlugin> getPlugin( final Class<P> pluginClass) { return ListUtils.first(getPluginsOfClass(pluginClass)); } @Override public <PT extends SciJavaPlugin, P extends PT> PluginInfo<PT> getPlugin(final Class<P> pluginClass, final Class<PT> type) { return ListUtils.first(getPluginsOfClass(pluginClass, type)); } @Override public PluginInfo<SciJavaPlugin> getPlugin(final String className) { return ListUtils.first(getPluginsOfClass(className)); } @Override public <PT extends SciJavaPlugin> List<PluginInfo<PT>> getPluginsOfType( final Class<PT> type) { return pluginIndex.getPlugins(type); } @Override public <P extends SciJavaPlugin> List<PluginInfo<SciJavaPlugin>> getPluginsOfClass(final Class<P> pluginClass) { // NB: We must scan *all* plugins for a match. In theory, the same plugin // Class could be associated with multiple PluginInfo entries of differing // type anyway. If performance of this method is insufficient, the solution // will be to rework the PluginIndex data structure to include an index on // plugin class names. return getPluginsOfClass(pluginClass, SciJavaPlugin.class); } @Override public <PT extends SciJavaPlugin, P extends PT> List<PluginInfo<PT>> getPluginsOfClass(final Class<P> pluginClass, final Class<PT> type) { final ArrayList<PluginInfo<PT>> result = new ArrayList<PluginInfo<PT>>(); findPluginsOfClass(pluginClass, getPluginsOfType(type), result); filterNonmatchingClasses(pluginClass, result); return result; } @Override public List<PluginInfo<SciJavaPlugin>> getPluginsOfClass( final String className) { // NB: Since we cannot load the class in question, and cannot know its type // hierarch(y/ies) even if we did, we must scan *all* plugins for a match. return getPluginsOfClass(className, SciJavaPlugin.class); } @Override public <PT extends SciJavaPlugin> List<PluginInfo<SciJavaPlugin>> getPluginsOfClass(final String className, final Class<PT> type) { final ArrayList<PluginInfo<SciJavaPlugin>> result = new ArrayList<PluginInfo<SciJavaPlugin>>(); findPluginsOfClass(className, getPluginsOfType(type), result); return result; } @Override public <PT extends SciJavaPlugin> List<PT> createInstancesOfType( final Class<PT> type) { final List<PluginInfo<PT>> plugins = getPluginsOfType(type); return createInstances(plugins); } @Override public <PT extends SciJavaPlugin> List<PT> createInstances( final List<PluginInfo<PT>> infos) { final ArrayList<PT> list = new ArrayList<PT>(); for (final PluginInfo<? extends PT> info : infos) { final PT p = createInstance(info); if (p != null) list.add(p); } return list; } @Override public <PT extends SciJavaPlugin> PT createInstance(final PluginInfo<PT> info) { try { final PT p = info.createInstance(); getContext().inject(p); Priority.inject(p, info.getPriority()); return p; } catch (final Throwable t) { log.error("Cannot create plugin: " + info, t); } return null; } // -- Service methods -- @Override public void initialize() { pluginIndex = getContext().getPluginIndex(); log.info("Found " + pluginIndex.size() + " plugins."); if (log.isDebug()) { for (final PluginInfo<?> info : pluginIndex) { log.debug("- " + info); } } logExceptions(); } // -- Utility methods -- /** * Transfers plugins of the given class from the source list to the * destination list. Note that because this method compares class name * strings, it does not need to actually load the class in question. * * @param className The class name of the desired plugins. * @param srcList The list to scan for matching plugins. * @param destList The list to which matching plugins are added. */ public static <T extends PluginInfo<?>> void findPluginsOfClass( final String className, final List<? extends PluginInfo<?>> srcList, final List<T> destList) { for (final PluginInfo<?> info : srcList) { if (info.getClassName().equals(className)) { @SuppressWarnings("unchecked") final T match = (T) info; destList.add(match); } } } /** * Gets the plugin type of the given plugin class, as declared by its * {@code @Plugin} annotation (i.e., {@link Plugin#type()}). * * @param pluginClass The plugin class whose plugin type is needed. * @return The plugin type, or null if no {@link Plugin} annotation exists for * the given class. */ public static <PT extends SciJavaPlugin, P extends PT> Class<PT> getPluginType( final Class<P> pluginClass) { final Plugin annotation = pluginClass.getAnnotation(Plugin.class); if (annotation == null) return null; @SuppressWarnings("unchecked") final Class<PT> type = (Class<PT>) annotation.type(); return type; } // -- Helper methods -- /** * Transfers plugins of the given class from the source list to the * destination list. Note that because this method compares class objects, it * <em>must</em> load the classes in question. * * @param pluginClass The class of the desired plugins. * @param srcList The list to scan for matching plugins. * @param destList The list to which matching plugins are added. */ private <T extends PluginInfo<?>> void findPluginsOfClass( final Class<?> pluginClass, final List<? extends PluginInfo<?>> srcList, final List<T> destList) { final String className = pluginClass.getName(); for (final PluginInfo<?> info : srcList) { try { final Class<?> clazz2 = info.getPluginClass(); if (clazz2 == pluginClass || (info.getClassName().equals(className) && info.loadClass() == pluginClass)) { @SuppressWarnings("unchecked") final T match = (T) info; destList.add(match); } } catch (InstantiableException exc) { log.debug("Ignoring plugin: " + info, exc); } } } /** * Filters the given list to include only entries with matching * <em>classes</em> (not just class <em>names</em>). */ private <PT extends SciJavaPlugin, P extends PT> void filterNonmatchingClasses(final Class<P> pluginClass, final ArrayList<PluginInfo<PT>> result) { for (final Iterator<PluginInfo<PT>> iter = result.iterator(); iter.hasNext(); ) { try { if (iter.next().loadClass() != pluginClass) iter.remove(); } catch (InstantiableException exc) { log.debug(exc); iter.remove(); } } } /** Logs any exceptions that occurred during the last plugin discovery. */ private void logExceptions() { final Map<String, Throwable> exceptions = pluginIndex.getExceptions(); final int excCount = exceptions.size(); if (excCount > 0) { log.warn(excCount + " exceptions occurred during plugin discovery."); if (log.isDebug()) { for (final String name : exceptions.keySet()) { final Throwable t = exceptions.get(name); log.debug(name, t); } } } } }
package org.scijava.script; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.scijava.Context; import org.scijava.Gateway; import org.scijava.InstantiableException; import org.scijava.MenuPath; import org.scijava.Priority; import org.scijava.command.CommandService; import org.scijava.event.EventHandler; import org.scijava.log.LogService; import org.scijava.module.Module; import org.scijava.module.ModuleService; import org.scijava.object.LazyObjects; import org.scijava.plugin.AbstractSingletonService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.service.Service; import org.scijava.service.event.ServicesLoadedEvent; import org.scijava.util.AppUtils; import org.scijava.util.ClassUtils; import org.scijava.util.ColorRGB; import org.scijava.util.ColorRGBA; /** * Default service for working with scripting languages. * * @author Johannes Schindelin * @author Curtis Rueden */ @Plugin(type = Service.class, priority = Priority.HIGH_PRIORITY) public class DefaultScriptService extends AbstractSingletonService<ScriptLanguage> implements ScriptService { @Parameter private PluginService pluginService; @Parameter private ModuleService moduleService; @Parameter private CommandService commandService; @Parameter private LogService log; /** Index of registered scripting languages. */ private ScriptLanguageIndex scriptLanguageIndex; /** List of directories to scan for scripts. */ private ArrayList<File> scriptDirs; /** Menu prefix to use for each script directory, if any. */ private HashMap<File, MenuPath> menuPrefixes; /** Index of available scripts, by script <em>file</em>. */ private HashMap<File, ScriptInfo> scripts; /** Table of short type names to associated {@link Class}. */ private HashMap<String, Class<?>> aliasMap; // -- ScriptService methods - scripting languages -- @Override public ScriptLanguageIndex getIndex() { return scriptLanguageIndex(); } @Override public List<ScriptLanguage> getLanguages() { return new ArrayList<ScriptLanguage>(getIndex()); } @Override public ScriptLanguage getLanguageByExtension(final String extension) { return getIndex().getByExtension(extension); } @Override public ScriptLanguage getLanguageByName(final String name) { return getIndex().getByName(name); } // -- ScriptService methods - scripts -- @Override public List<File> getScriptDirectories() { return Collections.unmodifiableList(scriptDirs()); } @Override public MenuPath getMenuPrefix(final File scriptDirectory) { return menuPrefixes().get(scriptDirectory); } @Override public void addScriptDirectory(final File scriptDirectory) { scriptDirs().add(scriptDirectory); } @Override public void addScriptDirectory(final File scriptDirectory, final MenuPath menuPrefix) { scriptDirs().add(scriptDirectory); menuPrefixes().put(scriptDirectory, menuPrefix); } @Override public void removeScriptDirectory(final File scriptDirectory) { scriptDirs().remove(scriptDirectory); } @Override public Collection<ScriptInfo> getScripts() { return Collections.unmodifiableCollection(scripts().values()); } @Override public ScriptInfo getScript(final File scriptFile) { return scripts().get(scriptFile); } @Override public Future<ScriptModule> run(final File file, final boolean process, final Object... inputs) { return run(getOrCreate(file), process, inputs); } @Override public Future<ScriptModule> run(final File file, final boolean process, final Map<String, Object> inputMap) { return run(getOrCreate(file), process, inputMap); } @Override public Future<ScriptModule> run(final String path, final String script, final boolean process, final Object... inputs) { return run(path, new StringReader(script), process, inputs); } @Override public Future<ScriptModule> run(final String path, final String script, final boolean process, final Map<String, Object> inputMap) { return run(path, new StringReader(script), process, inputMap); } @Override public Future<ScriptModule> run(final String path, final Reader reader, final boolean process, final Object... inputs) { return run(new ScriptInfo(getContext(), path, reader), process, inputs); } @Override public Future<ScriptModule> run(final String path, final Reader reader, final boolean process, final Map<String, Object> inputMap) { return run(new ScriptInfo(getContext(), path, reader), process, inputMap); } @Override public Future<ScriptModule> run(final ScriptInfo info, final boolean process, final Object... inputs) { return cast(moduleService.run(info, process, inputs)); } @Override public Future<ScriptModule> run(final ScriptInfo info, final boolean process, final Map<String, Object> inputMap) { return cast(moduleService.run(info, process, inputMap)); } @Override public boolean canHandleFile(final File file) { return getIndex().canHandleFile(file); } @Override public boolean canHandleFile(final String fileName) { return getIndex().canHandleFile(fileName); } @Override public void addAlias(final Class<?> type) { addAlias(type.getSimpleName(), type); } @Override public void addAlias(final String alias, final Class<?> type) { aliasMap().put(alias, type); } @Override public synchronized Class<?> lookupClass(final String alias) throws ScriptException { final Class<?> type = aliasMap().get(alias); if (type != null) return type; final Class<?> c = ClassUtils.loadClass(alias); if (c != null) { aliasMap().put(alias, c); return c; } throw new ScriptException("Unknown type: " + alias); } // -- PTService methods -- @Override public Class<ScriptLanguage> getPluginType() { return ScriptLanguage.class; } // -- Service methods -- @Override public void initialize() { super.initialize(); // add scripts to the module index... only when needed! moduleService.getIndex().addLater(new LazyObjects<ScriptInfo>() { @Override public Collection<ScriptInfo> get() { return scripts().values(); } }); } // -- Event handlers -- @EventHandler private void onEvent(@SuppressWarnings("unused") final ServicesLoadedEvent evt) { // NB: Add service type aliases after all services have joined the context. for (final Service service : getContext().getServiceIndex()) { addAliases(aliasMap, service.getClass()); } } // -- Helper methods - lazy initialization -- /** Gets {@link #scriptLanguageIndex}, initializing if needed. */ private ScriptLanguageIndex scriptLanguageIndex() { if (scriptLanguageIndex == null) initScriptLanguageIndex(); return scriptLanguageIndex; } /** Gets {@link #scriptDirs}, initializing if needed. */ private List<File> scriptDirs() { if (scriptDirs == null) initScriptDirs(); return scriptDirs; } /** Gets {@link #menuPrefixes}, initializing if needed. */ private HashMap<File, MenuPath> menuPrefixes() { if (menuPrefixes == null) initMenuPrefixes(); return menuPrefixes; } /** Gets {@link #scripts}, initializing if needed. */ private HashMap<File, ScriptInfo> scripts() { if (scripts == null) initScripts(); return scripts; } /** Gets {@link #aliasMap}, initializing if needed. */ private HashMap<String, Class<?>> aliasMap() { if (aliasMap == null) initAliasMap(); return aliasMap; } /** Initializes {@link #scriptLanguageIndex}. */ private synchronized void initScriptLanguageIndex() { if (scriptLanguageIndex != null) return; // already initialized final ScriptLanguageIndex index = new ScriptLanguageIndex(log); // add ScriptLanguage plugins for (final ScriptLanguage language : getInstances()) { index.add(language, false); } // Now look for the ScriptEngines in javax.scripting. We only do that // now since the javax.scripting framework does not provide all the // functionality we might want to use in ImageJ2. final ScriptEngineManager manager = new ScriptEngineManager(); for (final ScriptEngineFactory factory : manager.getEngineFactories()) { index.add(factory, true); } scriptLanguageIndex = index; } /** Initializes {@link #scriptDirs}. */ private synchronized void initScriptDirs() { if (scriptDirs != null) return; final ArrayList<File> dirs = new ArrayList<File>(); // append default script directories final File baseDir = AppUtils.getBaseDirectory(getClass()); //FIXME dirs.add(new File(baseDir, "scripts")); // append additional script directories from system property final String scriptsPath = System.getProperty(SCRIPTS_PATH_PROPERTY); if (scriptsPath != null) { for (final String dir : scriptsPath.split(File.pathSeparator)) { dirs.add(new File(dir)); } } scriptDirs = dirs; } /** Initializes {@link #menuPrefixes}. */ private synchronized void initMenuPrefixes() { if (menuPrefixes != null) return; menuPrefixes = new HashMap<File, MenuPath>(); } /** Initializes {@link #scripts}. */ private synchronized void initScripts() { if (scripts != null) return; // already initialized final HashMap<File, ScriptInfo> map = new HashMap<File, ScriptInfo>(); final ArrayList<ScriptInfo> scriptList = new ArrayList<ScriptInfo>(); new ScriptFinder(this).findScripts(scriptList); for (final ScriptInfo info : scriptList) { map.put(asFile(info.getPath()), info); } scripts = map; } /** Initializes {@link #aliasMap}. */ private synchronized void initAliasMap() { if (aliasMap != null) return; // already initialized final HashMap<String, Class<?>> map = new HashMap<String, Class<?>>(); // primitives addAliases(map, boolean.class, byte.class, char.class, double.class, float.class, int.class, long.class, short.class); // primitive wrappers addAliases(map, Boolean.class, Byte.class, Character.class, Double.class, Float.class, Integer.class, Long.class, Short.class); // built-in types addAliases(map, Context.class, BigDecimal.class, BigInteger.class, ColorRGB.class, ColorRGBA.class, File.class, String.class); // gateway types final List<PluginInfo<Gateway>> gatewayPlugins = pluginService.getPluginsOfType(Gateway.class); for (final PluginInfo<Gateway> info : gatewayPlugins) { try { addAliases(map, info.loadClass()); } catch (final InstantiableException exc) { log.warn("Ignoring invalid gateway: " + info.getClassName(), exc); } } aliasMap = map; } private void addAliases(final HashMap<String, Class<?>> map, final Class<?>... types) { for (final Class<?> type : types) { addAlias(map, type); } } private void addAlias(final HashMap<String, Class<?>> map, final Class<?> type) { if (type == null) return; map.put(type.getSimpleName(), type); // NB: Recursively add supertypes. addAlias(map, type.getSuperclass()); addAliases(map, type.getInterfaces()); } // -- Helper methods - run -- /** * Gets a {@link ScriptInfo} for the given file, creating a new one if none * are registered with the service. */ private ScriptInfo getOrCreate(final File file) { final ScriptInfo info = getScript(file); if (info != null) return info; return new ScriptInfo(getContext(), file); } private File asFile(final String path) { final File file = new File(path); try { return file.getCanonicalFile(); } catch (final IOException exc) { log.warn(exc); return file.getAbsoluteFile(); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private Future<ScriptModule> cast(final Future<Module> future) { return (Future) future; } }
package org.simpleframework.xml.core; import org.simpleframework.xml.stream.Style; /** * The <code>CacheLabel</code> object is used to acquire details from an * inner label object so that details can be retrieved repeatedly without * the need to perform any logic for extracting the values. This ensures * that a class XML schema requires only initial processing the first * time the class XML schema is required. * * @author Niall Gallagher */ class CacheLabel implements Label { /** * This is the decorator that is associated with the label. */ private final Decorator decorator; /** * This is the contact used to set and get the value for the node. */ private final Contact contact; /** * This is used to represent the dependent class to be used. */ private final Class depend; /** * This is used to represent the label class that this will use. */ private final Class type; /** * This is used to represent the name of the entry item use. */ private final String entry; /** * This is used to represent the name override for the annotation. */ private final String override; /** * This is used to represent the name of the annotated element. */ private final String name; /** * This is used to represent whether the data is written as data. */ private final boolean data; /** * This is used to represent whether the entity is required or not. */ private final boolean required; /** * This is used to determine whether the entity is inline or not. */ private final boolean inline; /** * This is the label the this cache is wrapping the values for. */ private final Label label; /** * Constructor for the <code>CacheLabel</code> object. This is used * to create a <code>Label</code> that acquires details from another * label in such a way that any logic involved in acquiring details * is performed only once. * * @param label this is the label to acquire the details from */ public CacheLabel(Label label) throws Exception { this.decorator = label.getDecorator(); this.contact = label.getContact(); this.depend = label.getDependant(); this.required = label.isRequired(); this.override = label.getOverride(); this.inline = label.isInline(); this.type = label.getType(); this.name = label.getName(); this.entry = label.getEntry(); this.data = label.isData(); this.label = label; } /** * This is used to acquire the contact object for this label. The * contact retrieved can be used to set any object or primitive that * has been deserialized, and can also be used to acquire values to * be serialized in the case of object persistence. All contacts * that are retrieved from this method will be accessible. * * @return returns the field that this label is representing */ public Contact getContact() { return contact; } /** * This is used to acquire the <code>Decorator</code> for this. * A decorator is an object that adds various details to the * node without changing the overall structure of the node. For * example comments and namespaces can be added to the node with * a decorator as they do not affect the deserialization. * * @return this returns the decorator associated with this */ public Decorator getDecorator() throws Exception { return decorator; } /** * This method returns a <code>Converter</code> which can be used to * convert an XML node into an object value and vice versa. The * converter requires only the context object in order to perform * serialization or deserialization of the provided XML node. * * @param context this is the context object for the serialization * * @return this returns an object that is used for conversion */ public Converter getConverter(Context context) throws Exception { return label.getConverter(context); } /** * This is used to acquire the name of the element or attribute * that is used by the class schema. The name is determined by * checking for an override within the annotation. If it contains * a name then that is used, if however the annotation does not * specify a name the the field or method name is used instead. * * @param context this is the context used to style the name * * @return returns the name that is used for the XML property */ public String getName(Context context) throws Exception { Style style = context.getStyle(); if(style != null) { return style.getElement(name); } return name; } /** * This is used to provide a configured empty value used when the * annotated value is null. This ensures that XML can be created * with required details regardless of whether values are null or * not. It also provides a means for sensible default values. * * @param context this is the context object for the serialization * * @return this returns the string to use for default values */ public Object getEmpty(Context context) throws Exception { return label.getEmpty(context); } /** * This returns the dependent type for the annotation. This type * is the type other than the annotated field or method type that * the label depends on. For the <code>ElementList</code> and * the <code>ElementArray</code> this is the component type that * is deserialized individually and inserted into the container. * * @return this is the type that the annotation depends on */ public Class getDependant() throws Exception { return depend; } /** * This is used to either provide the entry value provided within * the annotation or compute a entry value. If the entry string * is not provided the the entry value is calculated as the type * of primitive the object is as a simplified class name. * * @return this returns the name of the XML entry element used */ public String getEntry() throws Exception { return entry; } /** * This is used to acquire the name of the element or attribute * that is used by the class schema. The name is determined by * checking for an override within the annotation. If it contains * a name then that is used, if however the annotation does not * specify a name the the field or method name is used instead. * * @return returns the name that is used for the XML property */ public String getName() throws Exception { return name; } /** * This is used to acquire the name of the element or attribute * as taken from the annotation. If the element or attribute * explicitly specifies a name then that name is used for the * XML element or attribute used. If however no overriding name * is provided then the method or field is used for the name. * * @return returns the name of the annotation for the contact */ public String getOverride() { return override; } /** * This acts as a convenience method used to determine the type of * the field this represents. This is used when an object is written * to XML. It determines whether a <code>class</code> attribute * is required within the serialized XML element, that is, if the * class returned by this is different from the actual value of the * object to be serialized then that type needs to be remembered. * * @return this returns the type of the field class */ public Class getType() { return type; } /** * This is used to determine whether the annotation requires it * and its children to be written as a CDATA block. This is done * when a primitive or other such element requires a text value * and that value needs to be encapsulated within a CDATA block. * * @return this returns true if the element requires CDATA */ public boolean isData() { return data; } /** * This is used to determine whether the label represents an * inline XML entity. The <code>ElementList</code> annotation * and the <code>Text</code> annotation represent inline * items. This means that they contain no containing element * and so can not specify overrides or special attributes. * * @return this returns true if the annotation is inline */ public boolean isInline() { return inline; } /** * Determines whether the XML attribute or element is required. * This ensures that if an XML element is missing from a document * that deserialization can continue. Also, in the process of * serialization, if a value is null it does not need to be * written to the resulting XML document. * * @return true if the label represents a some required data */ public boolean isRequired() { return required; } /** * This is used to describe the annotation and method or field * that this label represents. This is used to provide error * messages that can be used to debug issues that occur when * processing a method. This should provide enough information * such that the problem can be isolated correctly. * * @return this returns a string representation of the label */ public String toString() { return label.toString(); } }