answer
stringlengths
17
10.2M
package org.jtrfp.trcl.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.concurrent.Callable; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import org.jtrfp.trcl.core.RootWindow; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.flow.EngineTests; import org.jtrfp.trcl.flow.Game; import org.jtrfp.trcl.flow.IndirectProperty; import org.jtrfp.trcl.mem.GPUMemDump; import com.jogamp.newt.event.KeyEvent; public class MenuSystem { private final FramebufferStateWindow fbsw; private final ConfigWindow configWindow; private final LevelSkipWindow levelSkipWindow; private final PropertyChangeListener pausePCL; private final IndirectProperty<Game>game = new IndirectProperty<Game>(); private final IndirectProperty<Boolean>paused = new IndirectProperty<Boolean>(); public MenuSystem(final TR tr){ final RootWindow rw = tr.getRootWindow(); final JMenu file = new JMenu("File"), window = new JMenu("Window"), gameMenu = new JMenu("Game"), debugMenu = new JMenu("Debug"); // And menus to menubar final JMenuItem file_quit = new JMenuItem("Quit"); final JMenuItem file_config = new JMenuItem("Configure"); final JMenuItem game_new = new JMenuItem("New Game"); final JMenuItem game_start = new JMenuItem("Start Game"); final JMenuItem game_pause = new JMenuItem("Pause"); final JMenuItem game_skip = new JMenuItem("Skip To Level..."); final JMenuItem game_abort= new JMenuItem("Abort Game"); final JMenuItem debugStatesMenuItem = new JMenuItem("Debug States"); final JMenuItem frameBufferStatesMenuItem = new JMenuItem("Framebuffer States"); final JMenuItem gpuMemDump = new JMenuItem("Dump GPU Memory"); final JMenuItem debugSinglet = new JMenuItem("Singlet (fill)"); // Accellerator keys file_quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK)); game_pause.setAccelerator(KeyStroke.getKeyStroke("F3")); fbsw = new FramebufferStateWindow(tr); configWindow = new ConfigWindow(tr.getTrConfig()); levelSkipWindow = new LevelSkipWindow(tr); // Menu item behaviors game_new.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { tr.getThreadManager().submitToThreadPool(new Callable<Void>(){ @Override public Void call() throws Exception { tr.getGameShell().newGame(); return null; }}); }}); game_start.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { tr.getThreadManager().submitToThreadPool(new Callable<Void>(){ @Override public Void call() throws Exception { tr.getGameShell().startGame(); return null; }}); }}); game_pause.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { tr.getThreadManager().submitToThreadPool(new Callable<Void>(){ @Override public Void call() throws Exception { final Game game = tr.getGame(); game.setPaused(!game.isPaused()); return null; }}); }}); game_skip.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { levelSkipWindow.setVisible(true); }}); game_abort.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { game_abort.setText("Aborting Game..."); game_abort.setEnabled(false); tr.getThreadManager().submitToThreadPool(new Callable<Void>(){ @Override public Void call() throws Exception { tr.abortCurrentGame(); SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { game_abort.setText("Abort Game"); game_abort.setEnabled(false); }});//end EDT task return null; }});//end threadPool task }});//end actionListener(game_abort) file_config.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { configWindow.setVisible(true); }}); file_quit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { System.exit(1); } }); debugStatesMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { tr.getReporter().setVisible(true); }; }); frameBufferStatesMenuItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { fbsw.setVisible(true); }}); gpuMemDump.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { tr.getThreadManager().submitToThreadPool(new Callable<Void>(){ @Override public Void call() throws Exception { new GPUMemDump(tr); return null; }}); }; }); debugSinglet.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { Object result = JOptionPane.showInputDialog(rw, "Enter number of instances", "How many?", JOptionPane.QUESTION_MESSAGE, null, null, null); try{ final int numInstances = Integer.parseInt((String)result); tr.threadManager.submitToThreadPool(new Callable<Void>(){ @Override public Void call() throws Exception { EngineTests.singlet(tr, numInstances); return null; }}); }catch(NumberFormatException e) {JOptionPane.showMessageDialog(rw, "Please supply an integer value.");} }}); final String showDebugStatesOnStartup = System .getProperty("org.jtrfp.trcl.showDebugStates"); if (showDebugStatesOnStartup != null) { if (showDebugStatesOnStartup.toUpperCase().contains("TRUE")) { tr.getReporter().setVisible(true); } } try{//Get this done in the local thread to minimize use of the EDT final JMenuBar mb = new JMenuBar(); file.add(file_config); file.add(gpuMemDump); file.add(file_quit); window.add(debugStatesMenuItem); window.add(frameBufferStatesMenuItem); gameMenu.add(game_new); game_pause.setEnabled(false); game_start.setEnabled(false); game_skip.setEnabled(false); game_abort.setEnabled(false); gameMenu.add(game_start); gameMenu.add(game_pause); gameMenu.add(game_skip); gameMenu.add(game_abort); debugMenu.add(debugSinglet); SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { rw.setVisible(false);//Frame must be invisible to modify. rw.setJMenuBar(mb); mb.add(file); mb.add(gameMenu); mb.add(debugMenu); mb.add(window); rw.setVisible(true); }}); }catch(Exception e){tr.showStopper(e);} pausePCL = new PropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().contentEquals("paused")) game_pause.setText((Boolean)evt.getNewValue()==true?"Unpause":"Pause"); }//end if(paused) };//end gamePCL tr.addPropertyChangeListener("game", new PropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent evt) { game_pause.setEnabled(evt.getNewValue()!=null); game_new.setEnabled(evt.getNewValue()==null); game_skip.setEnabled(evt.getNewValue()!=null); game_abort.setEnabled(evt.getNewValue()!=null); }}); IndirectProperty<Game> gameIP = new IndirectProperty<Game>(); tr.addPropertyChangeListener("game", gameIP); gameIP.addTargetPropertyChangeListener("paused", pausePCL); gameIP.addTargetPropertyChangeListener("currentMission", new PropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent pc) { game_start.setEnabled(pc.getNewValue()!=null && !tr.getGame().isInGameplay()); }}); gameIP.addTargetPropertyChangeListener("inGameplay", new PropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent pc) { game_start.setEnabled(pc.getNewValue()!=null && pc.getNewValue()==Boolean.FALSE); }}); }//end constructor }//end MenuSystem
package org.lantern; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation of the Lantern API. */ public class DefaultLanternApi implements LanternApi { private final Logger log = LoggerFactory.getLogger(getClass()); private final SettingsChangeImplementor implementor = new SettingsChangeImplementor(); /** * Enumeration of calls to the Lantern API. */ private enum LanternApiCall { SIGNIN, SIGNOUT, ADDTOWHITELIST, REMOVEFROMWHITELIST, ADDTRUSTEDPEER, REMOVETRUSTEDPEER, RESET, } @Override public void processCall(final HttpServletRequest req, final HttpServletResponse resp) { final Settings set = LanternHub.settings(); final String uri = req.getRequestURI(); final String id = StringUtils.substringAfter(uri, "/api/"); final LanternApiCall call = LanternApiCall.valueOf(id.toUpperCase()); log.debug("Got API call {}", call); switch (call) { case SIGNIN: LanternHub.xmppHandler().disconnect(); final Map<String, String> params = LanternUtils.toParamMap(req); final String email = params.remove("email"); String pass = params.remove("password"); if (StringUtils.isBlank(pass) && set.isSavePassword()) { pass = set.getStoredPassword(); if (StringUtils.isBlank(pass)) { sendError(resp, "No password given and no password stored"); return; } } set.setEmail(email); set.setPassword(pass); changeSetting(resp, params); try { LanternHub.xmppHandler().connect(); if (LanternUtils.shouldProxy()) { // We automatically start proxying upon connect if the user's // settings say they're in get mode and to use the system proxy. Configurator.startProxying(); } } catch (final IOException e) { sendError(resp, "Could not login: "+e.getMessage()); } break; case SIGNOUT: log.info("Signing out"); LanternHub.xmppHandler().disconnect(); // We stop proxying outside of any user settings since if we're // not logged in there's no sense in proxying. Could theoretically // use cached proxies, but definitely no peer proxies would work. Configurator.stopProxying(); break; case ADDTOWHITELIST: LanternHub.whitelist().addEntry(req.getParameter("site")); break; case REMOVEFROMWHITELIST: LanternHub.whitelist().removeEntry(req.getParameter("site")); break; case ADDTRUSTEDPEER: // TODO: Add data validation. LanternHub.getTrustedContactsManager().addTrustedContact( req.getParameter("email")); break; case REMOVETRUSTEDPEER: // TODO: Add data validation. LanternHub.getTrustedContactsManager().removeTrustedContact( req.getParameter("email")); break; case RESET: try { FileUtils.forceDelete(LanternConstants.DEFAULT_SETTINGS_FILE); LanternHub.resetSettings(); } catch (final IOException e) { sendServerError(resp, "Error resetting settings: "+ e.getMessage()); } break; } LanternHub.asyncEventBus().post(new SyncEvent()); LanternHub.settingsIo().write(); } private void sendServerError(final HttpServletResponse resp, final String msg) { try { resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg); } catch (final IOException e) { log.info("Could not send error", e); } } private void sendError(final HttpServletResponse resp, final String msg) { try { resp.sendError(HttpStatus.SC_BAD_REQUEST, msg); } catch (final IOException e) { log.info("Could not send error", e); } } @Override public void changeSetting(final HttpServletRequest req, final HttpServletResponse resp) { final Map<String, String> params = LanternUtils.toParamMap(req); changeSetting(resp, params); } private void changeSetting(final HttpServletResponse resp, final Map<String, String> params) { if (params.isEmpty()) { sendError(resp, "You must set at least one setting"); return; } final Entry<String, String> keyVal = params.entrySet().iterator().next(); log.debug("Got keyval: {}", keyVal); final String key = keyVal.getKey(); final String val = keyVal.getValue(); setProperty(LanternHub.settings(), key, val, true, resp); setProperty(implementor, key, val, false, resp); resp.setStatus(HttpStatus.SC_OK); LanternHub.asyncEventBus().post(new SyncEvent()); LanternHub.settingsIo().write(); } private void setProperty(final Object bean, final String key, final String val, final boolean logErrors, final HttpServletResponse resp) { log.info("Setting property on {}", bean); final Object obj; if (LanternUtils.isTrue(val)) { obj = true; } else if (LanternUtils.isFalse(val)) { obj = false; } else if (NumberUtils.isNumber(val)) { obj = Integer.parseInt(val); } else { obj = val; } try { PropertyUtils.setSimpleProperty(bean, key, obj); //PropertyUtils.setProperty(bean, key, obj); } catch (final IllegalAccessException e) { sendError(e, resp, logErrors); } catch (final InvocationTargetException e) { sendError(e, resp, logErrors); } catch (final NoSuchMethodException e) { sendError(e, resp, logErrors); } } private void sendError(final Exception e, final HttpServletResponse resp, final boolean logErrors) { if (logErrors) { try { resp.sendError(HttpStatus.SC_SERVICE_UNAVAILABLE, e.getMessage()); } catch (final IOException ioe) { log.info("Could not send response", e); } } } }
package org.pfaa.chemica.model; public class Fusion { private int temperature; public Fusion(int temperature) { this.temperature = temperature; } public int getTemperature() { return temperature; } public Condition getCondition() { return new Condition(this.temperature); } }
package ptrman.levels.retina; import org.apache.commons.math3.linear.ArrayRealVector; import ptrman.Datastructures.IMap2d; import ptrman.Datastructures.Vector2d; import ptrman.misc.Assert; import java.util.ArrayList; import java.util.List; /** * * samples from the input image and puts the set pixels into a queue (is for now just a list) */ public class ProcessA implements IProcess { @Override public void setImageSize(Vector2d<Integer> imageSize) { Assert.Assert((imageSize.x % 4) == 0, "imageSize.x must be divisable by 4"); Assert.Assert((imageSize.y % 4) == 0, "imageSize.y must be divisable by 4"); } @Override public void setup() { } @Override public void processData() { // TODO< refactor code so it uses this new interface > } public static class Sample { public Sample getClone() { Sample clone = new Sample(position); clone.altitude = this.altitude; clone.type = this.type; clone.objectId = this.objectId; return clone; } public enum EnumType { ENDOSCELETON, EXOSCELETON } public Sample(ArrayRealVector position) { this.position = position; } public boolean isAltitudeValid() { return altitude != Double.NaN; } public boolean isObjectIdValid() { return objectId != -1; } public ArrayRealVector position; public double altitude = Double.NaN; public EnumType type; public int objectId = -1; } public void set(IMap2d<Boolean> image, IMap2d<Integer> idMap) { workingImage = image.copy(); this.idMap = idMap; } /** * * avoids samping the same pixel by setting the sampled positions to false * * * */ public List<Sample> sampleImage() { List<Sample> resultSamples; resultSamples = new ArrayList<>(); for( int blockY = 0; blockY < workingImage.getLength()/4; blockY++ ) { for( int blockX = 0; blockX < workingImage.getWidth()/4; blockX++ ) { int hitCount = 0; for( int y = blockY*4; y < (blockY+1)*4; y++ ) { for (int x = blockX; x < (blockX+1)*4; x++) { if( sampleMaskAtPosition(new Vector2d<>(x, y), MaskDetail0) ) { if( workingImage.readAt(x, y) ) { hitCount++; workingImage.setAt(x, y, false); final int objectId = idMap.readAt(x, y); addSampleToList(resultSamples, x, y, objectId); } } } } if( hitCount == 8 ) { continue; } // sample it a second time for nearly all of the missing pixels for( int y = blockY*4; y < (blockY+1)*4; y++ ) { for (int x = blockX; x < (blockX+1)*4; x++) { if( sampleMaskAtPosition(new Vector2d<>(x, y), MaskDetail1) ) { if( workingImage.readAt(x, y) ) { hitCount++; workingImage.setAt(x, y, false); final int objectId = idMap.readAt(x, y); addSampleToList(resultSamples, x, y, objectId); } } } } } } return resultSamples; } private static void addSampleToList(List<Sample> samples, final int x, final int y, final int objectId) { Sample addSample = new Sample(new ArrayRealVector(new double[]{(double)x, (double)y})); addSample.objectId = objectId; samples.add(addSample); } private static boolean sampleMaskAtPosition(Vector2d<Integer> position, boolean[] mask4by4) { int modX, modY; modX = position.x % 4; modY = position.y % 4; return mask4by4[modX + modY * 4]; } private IMap2d<Boolean> workingImage; private IMap2d<Integer> idMap; private static final boolean[] MaskDetail0 = { true, false, false, true, false, true, true, false, true, false, true, false, false, true, false, true }; private static final boolean[] MaskDetail1 = { false, false, false, true, true, false, false, true, false, true, false, false, false, false, true, false }; }
package ptrman.levels.retina; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.commons.math3.stat.regression.SimpleRegression; import ptrman.Datastructures.Vector2d; import ptrman.bpsolver.HardParameters; import ptrman.bpsolver.Parameters; import ptrman.levels.retina.helper.SpatialDrawer; import ptrman.levels.retina.helper.SpatialListMap2d; import ptrman.math.ArrayRealVectorHelper; import ptrman.misc.Assert; import java.util.*; import static java.util.Collections.sort; import static ptrman.Datastructures.Vector2d.IntegerHelper.add; import static ptrman.Datastructures.Vector2d.IntegerHelper.sub; import static ptrman.math.ArrayRealVectorHelper.*; import static ptrman.math.Math.getRandomElements; // TODO< remove detectors which are removable which have a activation less than <constant> * sumofAllActivations > /** * detects lines * * forms line hypothesis and tries to strengthen it * uses the method of the least squares to fit the potential lines * each line detector either will survive or decay if it doesn't receive enought fitting points * */ public class ProcessD implements IProcess { public void preSetupSet(double maximalDistanceOfPositions) { this.maximalDistanceOfPositions = maximalDistanceOfPositions; } public void set(Queue<ProcessA.Sample> inputSampleQueue) { this.inputSampleQueue = inputSampleQueue; } public List<RetinaPrimitive> getResultRetinaPrimitives() { return resultRetinaPrimitives; } private static class LineDetectorWithMultiplePoints { public List<ArrayRealVector> cachedSamplePositions; public List<Integer> integratedSampleIndices; // variable for the line drawing in the acceleration structure public ArrayRealVector spatialAccelerationLineDirection; // can be null public double spatialAccelerationLineLength; // can be null public Vector2d<Integer> spatialAccelerationCenterPosition; public double m, n; public double mse = 0.0f; public boolean isLocked = false; // has the detector received enought activation so it stays? public int commonObjectId = -1; public boolean doesContainSampleIndex(int index) { return integratedSampleIndices.contains(index); } public double getActivation() { return integratedSampleIndices.size() + (Parameters.getProcessdMaxMse() - mse)*Parameters.getProcessdLockingActivationScale(); } public boolean isCommonObjectIdValid() { return commonObjectId != -1; } public ArrayRealVector projectPointOntoLine(ArrayRealVector point) { if( isYAxisSingularity() ) { // call isn't allowed throw new RuntimeException("internal error"); //return projectPointOntoLineForSingular(point); } else { return projectPointOntoLineForNonsingular(point); } } /*private Vector2d<Float> projectPointOntoLineForSingular(Vector2d<Float> point) { return new Vector2d<Float>(point.x, horizontalOffset); }*/ public ArrayRealVector projectPointOntoLineForNonsingular(ArrayRealVector point) { ArrayRealVector lineDirection = getNormalizedDirection(); ArrayRealVector diffFromAToPoint = point.subtract(new ArrayRealVector(new double[]{0.0f, n})); double dotResult = lineDirection.dotProduct(diffFromAToPoint); return new ArrayRealVector(new double[]{0.0f, n}).add(getScaled(lineDirection, dotResult)); } private ArrayRealVector getNormalizedDirection() { if( isYAxisSingularity() ) { throw new RuntimeException("internal error"); } else { return ArrayRealVectorHelper.normalize(new ArrayRealVector(new double[]{1.0f, m})); } } // TODO< just simply test flag > public boolean isYAxisSingularity() { return Double.isInfinite(m); } public double getHorizontalOffset(List<ProcessA.Sample> samples) { Assert.Assert(isYAxisSingularity(), ""); int sampleIndex = integratedSampleIndices.get(0); return samples.get(sampleIndex).position.getDataRef()[0]; } public double getLength() { List<ArrayRealVector> sortedSamplePositions = getSortedSamplePositions(this); Assert.Assert(sortedSamplePositions.size() >= 2, "samples size must be equal or greater than two"); // it doesn't care if the line is singuar or not, the distance is always the length final ArrayRealVector lastSamplePosition = sortedSamplePositions.get(sortedSamplePositions.size()-1); final ArrayRealVector firstSamplePosition = sortedSamplePositions.get(0); return lastSamplePosition.subtract(firstSamplePosition).getNorm(); } } private static class LineDetectors { public LineDetectors(List<LineDetectorWithMultiplePoints> lineDetectors) { this.lineDetectors = lineDetectors; } public List<LineDetectorWithMultiplePoints> lineDetectors; } @Override public void setImageSize(final Vector2d<Integer> imageSize) { this.imageSize = imageSize; } @Override public void setup() { Assert.Assert((imageSize.x % gridcellSize) == 0, ""); Assert.Assert((imageSize.y % gridcellSize) == 0, ""); // small size hack because else the map is accessed out of range accelerationMap = new SpatialListMap2d<>(new Vector2d<>(imageSize.x + gridcellSize, imageSize.y + gridcellSize), gridcellSize); } @Override public void processData() { // take samples from queue and put into array List<ProcessA.Sample> samplesAsList = new ArrayList<>(); final int inputSampleQueueSize = inputSampleQueue.size(); for( int i = 0; i < inputSampleQueueSize; i++ ) { samplesAsList.add(inputSampleQueue.poll()); } resultRetinaPrimitives = detectLines(samplesAsList); } /** * * \param samples doesn't need to be filtered for endo/exosceleton points, it does it itself * * \return only the surviving line segments */ private List<RetinaPrimitive> detectLines(List<ProcessA.Sample> samples) { List<LineDetectorWithMultiplePoints> multiplePointsLineDetector = new ArrayList<>(); final List<ProcessA.Sample> workingSamples = samples; if( workingSamples.isEmpty() ) { return new ArrayList<>(); } // we store all samples inside the acceleration datastructure int sampleIndex = 0; // NOTE< index in endosceletonPoint / workingSamples > for( final ProcessA.Sample iterationSample : workingSamples ) { putSampleIndexAtPositionIntoAccelerationDatastructure(arrayRealVectorToInteger(iterationSample.position, EnumRoundMode.DOWN), sampleIndex); sampleIndex++; } int numberOfTries = (int)( samples.size() * HardParameters.ProcessD.SAMPLES_NUMBER_OF_TRIES_MULTIPLIER); // TODO< imagesize > double maxLength = Math.sqrt(100.0f*100.0f + 80.0f*80.0f); final int numberOfMaximalLengthCycles = 5; Deque<LineDetectors> lineDetectorsRecords = new ArrayDeque<>(); for( int lengthCycle = 0; lengthCycle < numberOfMaximalLengthCycles; lengthCycle++ ) { // pick out a random cell and pick out a random sample in it and try to build a (small) line out of it for( int tryCounter = 0; tryCounter < numberOfTries; tryCounter++ ) { List<Integer> keys = new ArrayList<>(accelerationMapCellUsed.keySet()); final int randomCellPositionIndex = keys.get(random.nextInt(keys.size())); final Vector2d<Integer> randomCellPosition = new Vector2d<>(randomCellPositionIndex % accelerationMap.getWidth(), randomCellPositionIndex / accelerationMap.getWidth()); final List<Integer> allCandidateSampleIndices; // strategy for getting a "protoline" final int ACCELERATIONSTRUCUTRE_LINE_CANDIDATES_RADIUS = 2; // variables for LineDetectorWithMultiplePoints final ArrayRealVector spatialAccelerationLineDirection; final Vector2d<Integer> spatialAccelerationCenterPosition = randomCellPosition; // pick out possible direction(s) from the neightbor (acceleration structure) cells final List<Vector2d<Integer>> possibleNeightborAccelerationCellsWithSamples = getAccelerationStructureNeightborCellsWithContent(spatialAccelerationCenterPosition, ACCELERATIONSTRUCUTRE_LINE_CANDIDATES_RADIUS); if (possibleNeightborAccelerationCellsWithSamples.isEmpty()) { spatialAccelerationLineDirection = null; // TODO< get sample indices just from the one cell > allCandidateSampleIndices = getAllIndicesOfSamplesOfCellAndNeightborCells(spatialAccelerationCenterPosition); if (allCandidateSampleIndices.size() < 3) { continue; } } else { // * pick out a random neightbor cell and pick out a random direction for the accelerationstructure line final int possibleNeightborAccelerationCellIndex = random.nextInt(possibleNeightborAccelerationCellsWithSamples.size()); final Vector2d<Integer> chosenAccelerationStructureNeightborCellPosition = possibleNeightborAccelerationCellsWithSamples.get(possibleNeightborAccelerationCellIndex); final Vector2d<Integer> cellDelta = sub(chosenAccelerationStructureNeightborCellPosition, spatialAccelerationCenterPosition); final Vector2d<Integer> minusCellDelta = new Vector2d<>(-cellDelta.x, -cellDelta.y); final Vector2d<Integer> otherCellPosition = add(spatialAccelerationCenterPosition, minusCellDelta); final ArrayRealVector absoluteRandomPositionInChosenNeightborCell = calcAbsolutePositionInAccelerationCell(chosenAccelerationStructureNeightborCellPosition); final ArrayRealVector absoluteCenterPosition = getAbsolutePositionOfLeftTopCornerOfAccelerationCell(spatialAccelerationCenterPosition).add(new ArrayRealVector(new double[]{0.5 * (double) gridcellSize, 0.5 * (double) gridcellSize})); final ArrayRealVector absoluteDiff = absoluteRandomPositionInChosenNeightborCell.subtract(absoluteCenterPosition); spatialAccelerationLineDirection = normalize(absoluteDiff); // * draw line in acceleration structure final List<Vector2d<Integer>> accelerationCandidateCells = SpatialDrawer.getPositionsOfCellsOfLineUnbound(otherCellPosition, chosenAccelerationStructureNeightborCellPosition); // * filter out valid candidates accelerationCandidateCells.removeIf(cellPosition -> cellPosition == null); // * select random points from the validAccelerationCandidateCells (happens outside) // * fitting (happens outside) // TODO< other strategy, select two samples and find all points whcih are not too far away from the line > allCandidateSampleIndices = getAllSampleIndicesOfCells(accelerationCandidateCells); } List<Integer> chosenCandidateSampleIndices = new ArrayList<>(); if( allCandidateSampleIndices.size() < 3 ) { continue; } final List<Integer> allCandidateSampleIndicesChosenIndices = getRandomElements(allCandidateSampleIndices.size(), 3, random); for (final int iterationChosenIndex : allCandidateSampleIndicesChosenIndices) { final int currentChosenCandidateSampleIndex = allCandidateSampleIndices.get(iterationChosenIndex); chosenCandidateSampleIndices.add(currentChosenCandidateSampleIndex); } final List<ProcessA.Sample> selectedSamples = getSamplesByIndices(workingSamples, chosenCandidateSampleIndices); final boolean doAllSamplesHaveId = doAllSamplesHaveObjectId(selectedSamples); if( !doAllSamplesHaveId ) { continue; } // check if object ids are the same final boolean objectIdsOfSamplesTheSame = areObjectIdsTheSameOfSamples(selectedSamples); if( !objectIdsOfSamplesTheSame ) { continue; } final List<ArrayRealVector> positionsOfSamples = getPositionsOfSamples(selectedSamples); final ArrayRealVector averageOfPositionsOfSamples = getAverage(positionsOfSamples); final double currentMaximalDistanceOfPositions = getMaximalDistanceOfPositionsTo(positionsOfSamples, averageOfPositionsOfSamples); if( currentMaximalDistanceOfPositions > Math.min(maximalDistanceOfPositions, maxLength*0.5f) ) { // one point is too far away from the average position, so this line is not formed continue; } // else we are here final RegressionForLineResult regressionResult = calcRegressionForPoints(positionsOfSamples); if( regressionResult.mse > Parameters.getProcessdMaxMse() ) { continue; } // else we are here // create new line detector LineDetectorWithMultiplePoints createdLineDetector = new LineDetectorWithMultiplePoints(); createdLineDetector.integratedSampleIndices = chosenCandidateSampleIndices; createdLineDetector.cachedSamplePositions = positionsOfSamples; createdLineDetector.spatialAccelerationLineDirection = spatialAccelerationLineDirection; createdLineDetector.spatialAccelerationCenterPosition = spatialAccelerationCenterPosition; Assert.Assert(areObjectIdsTheSameOfSamples(selectedSamples), ""); createdLineDetector.commonObjectId = selectedSamples.get(0).objectId; Assert.Assert(createdLineDetector.integratedSampleIndices.size() >= 2, ""); // the regression mse is not defined if it are only two points boolean addCreatedLineDetector = false; if( createdLineDetector.integratedSampleIndices.size() == 2 ) { createdLineDetector.mse = 0.0f; createdLineDetector.n = regressionResult.n; createdLineDetector.m = regressionResult.m; addCreatedLineDetector = true; } else { if( regressionResult.mse < Parameters.getProcessdMaxMse() ) { createdLineDetector.mse = regressionResult.mse; createdLineDetector.n = regressionResult.n; createdLineDetector.m = regressionResult.m; addCreatedLineDetector = true; } } if( createdLineDetector.getLength() > maxLength ) { continue; } // else we are here if( addCreatedLineDetector ) { multiplePointsLineDetector.add(createdLineDetector); } } // compile statistics SummaryStatistics lineLengthStatistics = new SummaryStatistics(); for( LineDetectorWithMultiplePoints currentLineDetectorWithMultipleLines : multiplePointsLineDetector ) { double length = currentLineDetectorWithMultipleLines.getLength(); lineLengthStatistics.addValue(length); } final double currentLineLengthMean = lineLengthStatistics.getMean(); final double newMaxLength = currentLineLengthMean * HardParameters.ProcessD.LENGTH_MEAN_MULTIPLIER; System.out.println("length mean " + Double.toString(currentLineLengthMean)); maxLength = Math.min(maxLength, newMaxLength); final double finalizedMaxLength = maxLength; lineDetectorsRecords.push(new LineDetectors(copyLineDetectors(multiplePointsLineDetector))); if( currentLineLengthMean < HardParameters.ProcessD.MINIMAL_LINESEGMENTLENGTH ) { break; } // throw out multiplePointsLineDetector.removeIf(candidate -> candidate.getLength() > finalizedMaxLength); if( multiplePointsLineDetector.size() == 0 ) { break; } } multiplePointsLineDetector.clear(); // add last n records for( int lastNRecordsI = 0; lastNRecordsI < HardParameters.ProcessD.LAST_RECORDS_FROM_LINECANDIDATES_STACK; lastNRecordsI++ ) { if( lineDetectorsRecords.isEmpty() ) { break; } multiplePointsLineDetector.addAll(lineDetectorsRecords.pop().lineDetectors); } // split the detectors into one or many lines List<RetinaPrimitive> resultSingleDetectors = splitDetectorsIntoLines(multiplePointsLineDetector); return resultSingleDetectors; } private List<Integer> getAllSampleIndicesOfCells(final List<Vector2d<Integer>> cellPositions) { List<Integer> resultIndices = new ArrayList<>(); for( final Vector2d<Integer> iterationCellPosition : cellPositions ) { final List<Integer> cellContent = accelerationMap.readAt(iterationCellPosition.x, iterationCellPosition.y); if( cellContent != null ) { resultIndices.addAll(accelerationMap.readAt(iterationCellPosition.x, iterationCellPosition.y)); } } return resultIndices; } private boolean isAccelerationCellEmpty(final Vector2d<Integer> position) { return accelerationMap.readAt(position.x, position.y).isEmpty(); } private ArrayRealVector calcAbsolutePositionInAccelerationCell(final Vector2d<Integer> cellPosition) { final ArrayRealVector absoluteTopLeftPositionOfCell = getAbsolutePositionOfLeftTopCornerOfAccelerationCell(cellPosition); final ArrayRealVector randomOffset = new ArrayRealVector(new double[]{random.nextDouble() * (double)gridcellSize, random.nextDouble() * (double)gridcellSize}); return absoluteTopLeftPositionOfCell.add(randomOffset); } private ArrayRealVector getAbsolutePositionOfLeftTopCornerOfAccelerationCell(final Vector2d<Integer> cellPosition) { return new ArrayRealVector(new double[]{(double)gridcellSize * cellPosition.x, (double)gridcellSize * cellPosition.y}); } private List<Vector2d<Integer>> getAccelerationStructureNeightborCellsWithContent(final Vector2d<Integer> centerCellPosition, final int cellRadius) { final int minx = java.lang.Math.max(0, centerCellPosition.x - cellRadius); final int maxx = java.lang.Math.min(accelerationMap.getWidth(), centerCellPosition.x + cellRadius); final int miny = java.lang.Math.max(0, centerCellPosition.y - cellRadius); final int maxy = java.lang.Math.min(accelerationMap.getLength(), centerCellPosition.y + cellRadius); List<Vector2d<Integer>> resultCellPositions = new ArrayList<>(); for( int y = miny; y < maxy; y++ ) { for( int x = minx; x < maxx; x++ ) { if( centerCellPosition.x != x && centerCellPosition.y != y && accelerationMap.readAt(x, y) != null ) { resultCellPositions.add(new Vector2d<>(x, y)); } } } return resultCellPositions; } private static List<LineDetectorWithMultiplePoints> copyLineDetectors(final List<LineDetectorWithMultiplePoints> lineDetectors) { List<LineDetectorWithMultiplePoints> result = new ArrayList<>(); for( final LineDetectorWithMultiplePoints iterationLineDetector : lineDetectors ) { result.add(iterationLineDetector); } return result; } private static boolean doAllSamplesHaveObjectId(final List<ProcessA.Sample> samples) { for( final ProcessA.Sample iterationSamples : samples ) { if( !iterationSamples.isObjectIdValid() ) { return false; } } return true; } private static boolean areObjectIdsTheSameOfSamples(final List<ProcessA.Sample> samples) { Assert.Assert(samples.get(0).isObjectIdValid(), ""); final int objectId = samples.get(0).objectId; for( final ProcessA.Sample iterationSamples : samples ) { Assert.Assert(iterationSamples.isObjectIdValid(), ""); if( iterationSamples.objectId != objectId ) { return false; } } return true; } private static List<ArrayRealVector> getPositionsOfSamples(final List<ProcessA.Sample> samples) { List<ArrayRealVector> resultPositions = new ArrayList<>(); for( final ProcessA.Sample iterationSample : samples ) { resultPositions.add(iterationSample.position); } return resultPositions; } private static double getMaximalDistanceOfPositionsTo(final List<ArrayRealVector> positions, final ArrayRealVector comparePosition) { double maxDistance = 0.0; for( final ArrayRealVector iterationPosition : positions) { final double currentDistance = iterationPosition.getDistance(comparePosition); maxDistance = java.lang.Math.max(maxDistance, currentDistance); } return maxDistance; } private List<Vector2d<Integer>> getUnionOfCellsByPositions(final List<ArrayRealVector> positions) { Set<Vector2d<Integer>> tempSet = new HashSet<>(); for( final ArrayRealVector iterationPosition : positions ) { final Vector2d<Integer> positionAsInteger = arrayRealVectorToInteger(iterationPosition, EnumRoundMode.DOWN); final Vector2d<Integer> cellPosition = new Vector2d<>(positionAsInteger.x / gridcellSize, positionAsInteger.y / gridcellSize); tempSet.add(cellPosition); } List<Vector2d<Integer>> resultList = new ArrayList<>(); resultList.addAll(tempSet); return resultList; } private List<Integer> getAllIndicesOfSamplesOfCellAndNeightborCells(final Vector2d<Integer> centerCellPosition) { List<Integer> result = new ArrayList<>(); for( int y = centerCellPosition.y - 1; y < centerCellPosition.y + 1; y++ ) { for( int x = centerCellPosition.x - 1; x < centerCellPosition.x + 1; x++ ) { if( !accelerationMap.inBounds(new Vector2d<>(x, y)) ) { continue; } final List<Integer> listAtPosition = accelerationMap.readAt(x, y); if( listAtPosition != null ) { result.addAll(listAtPosition); } } } return result; } private static List<ProcessA.Sample> getSamplesByIndices(final List<ProcessA.Sample> samples, final List<Integer> indices) { List<ProcessA.Sample> resultPositions = new ArrayList<>(); for( final int index : indices ) { resultPositions.add(samples.get(index)); } return resultPositions; } private void putSampleIndexAtPositionIntoAccelerationDatastructure(final Vector2d<Integer> position, final int sampleIndex) { final Vector2d<Integer> cellPosition = new Vector2d<>(position.x / gridcellSize, position.y /gridcellSize); if( accelerationMap.readAt(cellPosition.x, cellPosition.y) == null ) { Assert.Assert(!accelerationMapCellUsed.containsKey(cellPosition.x + cellPosition.y * accelerationMap.getWidth()), ""); accelerationMap.setAt(cellPosition.x, cellPosition.y, new ArrayList<>(Arrays.asList(new Integer[]{sampleIndex}))); accelerationMapCellUsed.put(cellPosition.x + cellPosition.y * accelerationMap.getWidth(), true); } else { Assert.Assert(accelerationMapCellUsed.containsKey(cellPosition.x + cellPosition.y * accelerationMap.getWidth()), ""); List<Integer> indices = accelerationMap.readAt(cellPosition.x, cellPosition.y); indices.add(sampleIndex); } } /** * works by counting the "overlapping" pixel coordinates, chooses the axis with the less overlappings * */ private static RegressionForLineResult calcRegressionForPoints(List<ArrayRealVector> positions) { SimpleRegression regression; int overlappingPixelsOnX, overlappingPixelsOnY; RegressionForLineResult regressionResultForLine; overlappingPixelsOnX = calcCountOfOverlappingPixelsForAxis(positions, EnumAxis.X); overlappingPixelsOnY = calcCountOfOverlappingPixelsForAxis(positions, EnumAxis.Y); regression = new SimpleRegression(); regressionResultForLine = new RegressionForLineResult(); if( overlappingPixelsOnX <= overlappingPixelsOnY ) { // regression on x axis for( ArrayRealVector iterationPosition : positions ) { regression.addData(iterationPosition.getDataRef()[0], iterationPosition.getDataRef()[1]); } regressionResultForLine.mse = regression.getMeanSquareError(); regressionResultForLine.n = regression.getIntercept(); regressionResultForLine.m = regression.getSlope(); } else { // regression on y axis // we switch x and y and calculate m and n from the regression result for( ArrayRealVector iterationPosition : positions ) { regression.addData(iterationPosition.getDataRef()[1], iterationPosition.getDataRef()[0]); } // calculate m and n double regressionM = regression.getSlope(); double regressionN = regression.getIntercept(); double m = 1.0f/regressionM; ArrayRealVector pointOnRegressionLine = new ArrayRealVector(new double[]{regressionN, 0.0}); double n = pointOnRegressionLine.getDataRef()[1] - m * pointOnRegressionLine.getDataRef()[0]; regressionResultForLine.mse = regression.getMeanSquareError(); regressionResultForLine.n = n; regressionResultForLine.m = m; } return regressionResultForLine; } private static int calcCountOfOverlappingPixelsForAxis(List<ArrayRealVector> positions, EnumAxis axis) { double maxCoordinatOnAxis = getMaximalCoordinateForPoints(positions, axis); int arraysizeOfDimension = Math.round((float)maxCoordinatOnAxis)+1; int[] dimensionCounter = new int[arraysizeOfDimension]; for( ArrayRealVector iterationPosition : positions ) { int dimensionCounterIndex = Math.round((float)Helper.getAxis(iterationPosition, axis)); dimensionCounter[dimensionCounterIndex]++; } // count the "rows" where the count is greater than 1 int overlappingCounter = 0; for( int arrayI = 0; arrayI < dimensionCounter.length; arrayI++ ) { if( dimensionCounter[arrayI] > 1 ) { overlappingCounter++; } } return overlappingCounter; } // used to calculate the arraysize private static double getMaximalCoordinateForPoints(List<ArrayRealVector> positions, EnumAxis axis) { double max = 0; for( ArrayRealVector iterationPosition : positions ) { max = Math.max(max, Helper.getAxis(iterationPosition, axis)); } return max; } private static List<RetinaPrimitive> splitDetectorsIntoLines(List<LineDetectorWithMultiplePoints> lineDetectorsWithMultiplePoints) { List<RetinaPrimitive> result; result = new ArrayList<>(); for( LineDetectorWithMultiplePoints iterationDetector : lineDetectorsWithMultiplePoints ) { result.addAll(splitDetectorIntoLines(iterationDetector)); } return result; } private static List<ArrayRealVector> getSortedSamplePositions(LineDetectorWithMultiplePoints lineDetectorWithMultiplePoints) { List<ArrayRealVector> samplePositions = new ArrayList<>(); if( lineDetectorWithMultiplePoints.isYAxisSingularity() ) { for( ArrayRealVector iterationSamplePosition : lineDetectorWithMultiplePoints.cachedSamplePositions ) { samplePositions.add(iterationSamplePosition); } sort(samplePositions, new VectorComperatorByAxis(EnumAxis.Y)); } else { // project for( ArrayRealVector iterationSamplePosition : lineDetectorWithMultiplePoints.cachedSamplePositions ) { ArrayRealVector projectedSamplePosition = lineDetectorWithMultiplePoints.projectPointOntoLine(iterationSamplePosition); samplePositions.add(projectedSamplePosition); } sort(samplePositions, new VectorComperatorByAxis(EnumAxis.X)); } return samplePositions; } private static List<RetinaPrimitive> splitDetectorIntoLines(LineDetectorWithMultiplePoints lineDetectorWithMultiplePoints) { List<ArrayRealVector> sortedSamplePositions = getSortedSamplePositions(lineDetectorWithMultiplePoints); if( lineDetectorWithMultiplePoints.isYAxisSingularity() ) { return clusterPointsFromLinedetectorToLinedetectors(lineDetectorWithMultiplePoints.commonObjectId, sortedSamplePositions, EnumAxis.Y); } else { return clusterPointsFromLinedetectorToLinedetectors(lineDetectorWithMultiplePoints.commonObjectId, sortedSamplePositions, EnumAxis.X); } } private static List<RetinaPrimitive> clusterPointsFromLinedetectorToLinedetectors(final int objectId, final List<ArrayRealVector> pointPositions, final EnumAxis axis) { List<RetinaPrimitive> resultSingleLineDetectors = new ArrayList<>(); boolean nextIsNewLineStart = true; ArrayRealVector lineStartPosition = pointPositions.get(0); double lastAxisPosition = Helper.getAxis(pointPositions.get(0), axis); for( ArrayRealVector iterationPoint : pointPositions ) { if( nextIsNewLineStart ) { lineStartPosition = iterationPoint; lastAxisPosition = Helper.getAxis(iterationPoint, axis); nextIsNewLineStart = false; continue; } // else we are here if( Helper.getAxis(iterationPoint, axis) - lastAxisPosition < HardParameters.ProcessD.LINECLUSTERINGMAXDISTANCE ) { lastAxisPosition = Helper.getAxis(iterationPoint, axis); } else { // form a new line RetinaPrimitive newPrimitive = RetinaPrimitive.makeLine(SingleLineDetector.createFromFloatPositions(lineStartPosition, iterationPoint)); newPrimitive.objectId = objectId; resultSingleLineDetectors.add(newPrimitive); nextIsNewLineStart = true; } } // form a new line for the last point ArrayRealVector lastPoint = pointPositions.get(pointPositions.size()-1); if( !nextIsNewLineStart && Helper.getAxis(lastPoint, axis) - lastAxisPosition < HardParameters.ProcessD.LINECLUSTERINGMAXDISTANCE ) { RetinaPrimitive newPrimitive = RetinaPrimitive.makeLine(SingleLineDetector.createFromFloatPositions(lineStartPosition, lastPoint)); newPrimitive.objectId = objectId; resultSingleLineDetectors.add(newPrimitive); } return resultSingleLineDetectors; } private static List<ProcessA.Sample> filterEndosceletonPoints(List<ProcessA.Sample> samples) { List<ProcessA.Sample> filtered; filtered = new ArrayList<>(); for( ProcessA.Sample iterationSample : samples ) { if( iterationSample.type == ProcessA.Sample.EnumType.ENDOSCELETON ) { filtered.add(iterationSample); } } return filtered; } // TODO< belongs into dedicated helper > static private class Helper { private static boolean isDistanceBetweenPositionsBelow(ArrayRealVector a, ArrayRealVector b, double maxDistance) { return a.subtract(b).getNorm() < maxDistance; } private static double getAxis(ArrayRealVector vector, EnumAxis axis) { if( axis == EnumAxis.X ) { return vector.getDataRef()[0]; } else { return vector.getDataRef()[1]; } } } private static class VectorComperatorByAxis implements Comparator<ArrayRealVector> { public VectorComperatorByAxis(EnumAxis axis) { this.axis = axis; } @Override public int compare(ArrayRealVector a, ArrayRealVector b) { if( Helper.getAxis(a, axis) > Helper.getAxis(b, axis) ) { return 1; } return -1; } private final EnumAxis axis; } private static class RegressionForLineResult { public double mse; public double m, n; } private enum EnumAxis { X, Y } private Vector2d<Integer> imageSize; private int gridcellSize = 8; private Random random = new Random(); // each cell contains the incides of the points/samples inside the accelerationMap private SpatialListMap2d<Integer> accelerationMap; private Map<Integer, Boolean> accelerationMapCellUsed = new HashMap<>(); private List<RetinaPrimitive> resultRetinaPrimitives; private double maximalDistanceOfPositions; private Queue<ProcessA.Sample> inputSampleQueue; }
package rmblworx.tools.timey.gui; import java.io.IOException; import java.util.Locale; import java.util.ResourceBundle; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { private ResourceBundle i18n; public void start(final Stage stage) { try { String locale = "de"; i18n = ResourceBundle.getBundle(getClass().getPackage().getName() + ".TimeyGui_i18n", new Locale(locale)); final FXMLLoader loader = new FXMLLoader(getClass().getResource("TimeyGui.fxml"), i18n); final Parent root = (Parent) loader.load(); final Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle(i18n.getString("application.title")); stage.setResizable(false); stage.show(); final TimeyController timeyController = (TimeyController) loader.getController(); timeyController.setStage(stage); } catch (final IOException e) { e.printStackTrace(); } } public static void main(final String[] args) { launch(args); } }
package seedu.geekeep.model.task; import java.util.Objects; import seedu.geekeep.commons.util.CollectionUtil; import seedu.geekeep.model.tag.UniqueTagList; /** * Represents a Task in the Task Manager. Guarantees: details are present and not null, field values are validated. */ public class Task implements ReadOnlyTask { private Title title; private DateTime endDateTime; private DateTime startDateTime; private Location location; private boolean isDone; private UniqueTagList tags; /** * Creates a copy of the given ReadOnlyTask. */ public Task(ReadOnlyTask source) { this(source.getTitle(), source.getStartDateTime(), source.getEndDateTime(), source.getLocation(), source.getTags()); } /** * Every field must be present and not null. */ public Task(Title title, DateTime startDateTime, DateTime endDateTime, Location location, UniqueTagList tags) { assert !CollectionUtil.isAnyNull(title); if (startDateTime != null) assert endDateTime != null; if(startDateTime != null && endDateTime != null) assert endDateTime.dateTime.isAfter(startDateTime.dateTime); this.title = title; this.endDateTime = endDateTime; this.startDateTime = startDateTime; this.location = location; this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ReadOnlyTask // instanceof handles nulls && this.isSameStateAs((ReadOnlyTask) other)); } @Override public DateTime getEndDateTime() { return endDateTime; } @Override public Location getLocation() { return location; } @Override public DateTime getStartDateTime() { return startDateTime; } @Override public UniqueTagList getTags() { return new UniqueTagList(tags); } @Override public Title getTitle() { return title; } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(title, endDateTime, startDateTime, location, tags); } /** * Updates this task with the details of {@code replacement}. */ public void resetData(ReadOnlyTask replacement) { assert replacement != null; this.setTitle(replacement.getTitle()); this.setEndDateTime(replacement.getEndDateTime()); this.setStartDateTime(replacement.getStartDateTime()); this.setLocation(replacement.getLocation()); this.setTags(replacement.getTags()); } public void setStartDateTime(DateTime startDateTime) { assert startDateTime != null; this.startDateTime = startDateTime; } public void setEndDateTime(DateTime endDateTime) { assert endDateTime != null; this.endDateTime = endDateTime; } public void setLocation(Location location) { assert location != null; this.location = location; } /** * Replaces this Task's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } public void setTitle(Title title) { assert title != null; this.title = title; } @Override public String toString() { return getAsText(); } public boolean isFloatingTask() { return startDateTime == null && endDateTime == null; } public boolean isEvent() { return startDateTime != null && endDateTime != null; } public boolean isDeadline() { return startDateTime == null && endDateTime != null; } @Override public boolean isDone() { return isDone; } public void markDone() { isDone = true; } public void markUndone () { isDone = false; } }
/** @@author A0142130A **/ package seedu.taskell.ui; import javafx.scene.Node; import javafx.scene.control.TextArea; import javafx.scene.layout.AnchorPane; import jfxtras.scene.control.agenda.Agenda; import seedu.taskell.commons.core.LogsCenter; import seedu.taskell.commons.util.FxViewUtil; import java.util.ArrayList; import java.util.logging.Logger; /** * The Display Panel of the App. */ public class DisplayPanel extends UiPart{ private static Logger logger = LogsCenter.getLogger(DisplayPanel.class); public static final String RESULT_DISPLAY_ID = "resultDisplay"; private static final String STATUS_BAR_STYLE_SHEET = "result-display"; private TextArea display; private CalendarView calendarView; /** * Constructor is kept private as {@link #load(AnchorPane)} is the only way to create a DisplayPanel. */ private DisplayPanel() { calendarView = new CalendarView(); display = new TextArea(); } @Override public void setNode(Node node) { //not applicable } @Override public String getFxmlPath() { return null; //not applicable } /** * This method should be called after the FX runtime is initialized and in FX application thread. * @param placeholder The AnchorPane where the DisplayPanel must be inserted */ public static DisplayPanel load(AnchorPane placeholder){ logger.info("Initializing display panel"); DisplayPanel displayPanel = new DisplayPanel(); //displayPanel.display = new TextArea(); displayPanel.display.setEditable(false); displayPanel.display.setId(RESULT_DISPLAY_ID); displayPanel.display.getStyleClass().removeAll(); displayPanel.display.getStyleClass().add(STATUS_BAR_STYLE_SHEET); FxViewUtil.applyAnchorBoundaryParameters(displayPanel.display, 0.0, 0.0, 0.0, 0.0); placeholder.getChildren().add(displayPanel.display); displayPanel.display.setText("Welcome to Taskell!\n" + "Enter 'add' in command box to add a task.\n" + "Enter 'list-undo' for list of commands to undo.\n" + "Enter 'help' for more information about commands.\n" + "Enter 'calendar' to view calendar."); return displayPanel; } public void loadList(AnchorPane placeholder, ArrayList<String> list) { placeholder.getChildren().clear(); placeholder.getChildren().add(display); display.setText(""); if (list.isEmpty()) { display.setText("No commands available for undo."); } else { for (int i=0; i<list.size(); i++) { int index = i+1; display.appendText(index + ". " + list.get(i) + "\n"); } } } public void loadCalendar(AnchorPane placeholder) { placeholder.getChildren().clear(); Agenda agenda = calendarView.getAgenda(); FxViewUtil.applyAnchorBoundaryParameters(agenda, 0.0, 0.0, 0.0, 0.0); placeholder.getChildren().add(agenda); } /** @@author **/ }
import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import Support.FileDrop; public class MainUI { private JFrame frmNuttysync; private JTextField sourceTextField; private JTextField destinationTextField; private JTextField crcDelimiterTextField; private JTextField crcDelimiterLeadingTextField; private JTextField crcDelimiterTrailingTextField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainUI window = new MainUI(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); System.out.println("Look and feel: " + UIManager.getSystemLookAndFeelClassName()); window.frmNuttysync.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainUI() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmNuttysync = new JFrame(); frmNuttysync.setTitle("NuttySync"); frmNuttysync.setBounds(100, 100, 526, 320); frmNuttysync.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel sourceLabel = new JLabel("Source:"); sourceLabel.setPreferredSize(new Dimension(57, 14)); sourceLabel.setMinimumSize(new Dimension(57, 14)); sourceLabel.setMaximumSize(new Dimension(57, 14)); sourceLabel.setBounds(7, 7, 67, 22); sourceLabel.setHorizontalAlignment(SwingConstants.RIGHT); sourceLabel.setFont(new Font("Arial", Font.BOLD, 11)); sourceTextField = new JTextField(); sourceTextField.setBounds(93, 7, 352, 22); sourceTextField.setMinimumSize(new Dimension(50, 20)); sourceTextField.setToolTipText(""); sourceTextField.setColumns(10); JButton sourceMoreButton = new JButton("..."); sourceMoreButton.setBounds(463, 7, 40, 22); sourceMoreButton.setAlignmentX(Component.CENTER_ALIGNMENT); sourceMoreButton.setMinimumSize(new Dimension(23, 23)); sourceMoreButton.setMaximumSize(new Dimension(45, 22)); sourceMoreButton.setDefaultCapable(false); sourceMoreButton.setFocusPainted(false); JLabel destinationLabel = new JLabel("Destination:"); destinationLabel.setBounds(7, 33, 67, 22); destinationLabel.setHorizontalAlignment(SwingConstants.RIGHT); destinationLabel.setFont(new Font("Arial", Font.BOLD, 11)); destinationTextField = new JTextField(); destinationTextField.setBounds(93, 33, 352, 22); destinationTextField.setMinimumSize(new Dimension(50, 20)); destinationTextField.setColumns(10); new FileDrop(sourceTextField, new FileDrop.Listener() { @Override public void filesDropped(File[] files) { System.out.println(files[0].getPath()); // TODO Auto-generated method stub } // end filesDropped }); // end FileDrop.Listener JButton destinationMoreButton = new JButton("..."); destinationMoreButton.setBounds(463, 33, 40, 22); destinationMoreButton.setAlignmentX(Component.CENTER_ALIGNMENT); destinationMoreButton.setMinimumSize(new Dimension(23, 23)); destinationMoreButton.setMaximumSize(new Dimension(45, 22)); destinationMoreButton.setDefaultCapable(false); destinationMoreButton.setFocusTraversalKeysEnabled(false); destinationMoreButton.setFocusPainted(false); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBounds(7, 58, 498, 169); tabbedPane.setPreferredSize(new Dimension(5, 150)); JPanel flagPanel = new JPanel(); tabbedPane.addTab("Flags", null, flagPanel, null); flagPanel.setLayout(null); JRadioButton auditTrailButton = new JRadioButton("Enable Audit Trail"); auditTrailButton.setBounds(7, 7, 231, 23); flagPanel.add(auditTrailButton); JRadioButton crcCheckButton = new JRadioButton("Enable CRC Check"); crcCheckButton.setBounds(7, 34, 231, 23); flagPanel.add(crcCheckButton); Box horizontalBox_1 = Box.createHorizontalBox(); horizontalBox_1.setBorder(new LineBorder(Color.LIGHT_GRAY)); horizontalBox_1.setBounds(7, 64, 476, 2); flagPanel.add(horizontalBox_1); JLabel afterCompletionLabel = new JLabel("After Completion"); afterCompletionLabel.setBounds(7, 77, 109, 14); flagPanel.add(afterCompletionLabel); JRadioButton doNothingButton = new JRadioButton("Do nothing"); doNothingButton.setBounds(7, 95, 109, 23); flagPanel.add(doNothingButton); JRadioButton standbyButton = new JRadioButton("Standby"); standbyButton.setBounds(191, 95, 109, 23); flagPanel.add(standbyButton); JRadioButton shutdownButton = new JRadioButton("Shutdown"); shutdownButton.setBounds(341, 95, 109, 23); flagPanel.add(shutdownButton); JPanel crcOptionPanel = new JPanel(); crcOptionPanel.setPreferredSize(new Dimension(10, 150)); crcOptionPanel.setMaximumSize(new Dimension(32767, 165)); tabbedPane.addTab("CRC Options", null, crcOptionPanel, null); crcOptionPanel.setLayout(null); JLabel delimiterTitleLabel = new JLabel("Use the following delimiters to determine CRC in filename"); delimiterTitleLabel.setBounds(7, 7, 479, 14); crcOptionPanel.add(delimiterTitleLabel); JLabel crcDelimiterLabel = new JLabel("CRC Delimiter"); crcDelimiterLabel.setBounds(7, 29, 83, 14); crcOptionPanel.add(crcDelimiterLabel); crcDelimiterTextField = new JTextField(); crcDelimiterTextField.setBounds(100, 25, 202, 22); crcDelimiterTextField.setMargin(new Insets(1, 2, 3, 2)); crcDelimiterTextField.setPreferredSize(new Dimension(50, 20)); crcDelimiterTextField.setMinimumSize(new Dimension(50, 20)); crcDelimiterTextField.setText("[], {}, (), __"); crcOptionPanel.add(crcDelimiterTextField); crcDelimiterTextField.setColumns(10); JLabel crcDelimiterExampleLabel = new JLabel("Seperate with ',' (ie. \"[], {}, ()\")"); crcDelimiterExampleLabel.setBounds(318, 26, 175, 21); crcOptionPanel.add(crcDelimiterExampleLabel); JRadioButton checkWithoutDelimiterButton = new JRadioButton("Check without delimiters"); checkWithoutDelimiterButton.setBounds(7, 50, 186, 22); checkWithoutDelimiterButton.setFocusPainted(false); crcOptionPanel.add(checkWithoutDelimiterButton); Box horizontalBox = Box.createHorizontalBox(); horizontalBox.setBounds(7, 76, 479, 2); horizontalBox.setBorder(new LineBorder(Color.LIGHT_GRAY)); crcOptionPanel.add(horizontalBox); JRadioButton addCrcFilenameButton = new JRadioButton("Add CRC to filename"); addCrcFilenameButton.setBounds(7, 82, 143, 22); addCrcFilenameButton.setFocusPainted(false); addCrcFilenameButton.setToolTipText("Add CRC to both source and destination if CRC not in file name"); crcOptionPanel.add(addCrcFilenameButton); JLabel crcDelimiterLeadingLabel = new JLabel("CRC Delimiter - Leading"); crcDelimiterLeadingLabel.setBounds(7, 112, 143, 14); crcOptionPanel.add(crcDelimiterLeadingLabel); crcDelimiterLeadingTextField = new JTextField(); crcDelimiterLeadingTextField.setBounds(155, 109, 70, 21); crcOptionPanel.add(crcDelimiterLeadingTextField); crcDelimiterLeadingTextField.setColumns(10); JLabel crcDelimiterTrailingLabel = new JLabel("CRC Delimiter - Trailing"); crcDelimiterTrailingLabel.setBounds(268, 112, 131, 14); crcOptionPanel.add(crcDelimiterTrailingLabel); crcDelimiterTrailingTextField = new JTextField(); crcDelimiterTrailingTextField.setBounds(413, 109, 70, 21); crcOptionPanel.add(crcDelimiterTrailingTextField); crcDelimiterTrailingTextField.setColumns(10); JPanel auditPanel = new JPanel(); tabbedPane.addTab("Audit (Logs)", null, auditPanel, null); auditPanel.setLayout(null); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBackground(Color.WHITE); scrollPane_1.setBorder(new EmptyBorder(0, 3, 0, 3)); scrollPane_1.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); scrollPane_1.setBounds(0, 0, 493, 141); auditPanel.add(scrollPane_1); JTextArea auditTextPane = new JTextArea(); auditTextPane.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); auditTextPane.setEditable(false); auditTextPane.setBorder(null); scrollPane_1.setViewportView(auditTextPane); auditTextPane.setWrapStyleWord(true); auditTextPane.setLineWrap(true); auditTextPane.setText("This is a very long text that might occur when we have very long audit log and or long directory nagmes\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n0\r\n-"); frmNuttysync.getContentPane().setLayout(null); frmNuttysync.getContentPane().add(sourceLabel); frmNuttysync.getContentPane().add(sourceTextField); frmNuttysync.getContentPane().add(sourceMoreButton); frmNuttysync.getContentPane().add(destinationLabel); frmNuttysync.getContentPane().add(destinationTextField); frmNuttysync.getContentPane().add(destinationMoreButton); frmNuttysync.getContentPane().add(tabbedPane); JPanel errorLogsPanel = new JPanel(); tabbedPane.addTab("Error Logs", null, errorLogsPanel, null); errorLogsPanel.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBackground(Color.WHITE); scrollPane.setBorder(new EmptyBorder(0, 3, 0, 3)); scrollPane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); scrollPane.setBounds(0, 0, 493, 141); errorLogsPanel.add(scrollPane); JTextArea textArea = new JTextArea(); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); scrollPane.setViewportView(textArea); JLabel sizeReadLabel = new JLabel("Read: "); sizeReadLabel.setBounds(7, 238, 99, 14); frmNuttysync.getContentPane().add(sizeReadLabel); JLabel sizeReadSpeedLabel = new JLabel("Read Speed:"); sizeReadSpeedLabel.setBounds(116, 238, 154, 14); frmNuttysync.getContentPane().add(sizeReadSpeedLabel); JLabel totalRunningTimeLabel = new JLabel("Running Time:"); totalRunningTimeLabel.setBounds(280, 238, 223, 14); frmNuttysync.getContentPane().add(totalRunningTimeLabel); JProgressBar processingFileProgressBar = new JProgressBar(); processingFileProgressBar.setBounds(7, 256, 496, 14); frmNuttysync.getContentPane().add(processingFileProgressBar); } private static void addPopup(Component component, final JPopupMenu popup) { component.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } private void showMenu(MouseEvent e) { popup.show(e.getComponent(), e.getX(), e.getY()); } }); } }
import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.MatteBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.*; import java.util.List; import java.util.ArrayList; /** * Basic Cell Grid GUI used for printing out numeric boolean (0 & 1) values for each selected * and non-selected cell. */ public class GUI { private GridPane grid; private JFrame frame; private JButton setButton; /** * Main function for running GUI * @param args */ public static void main(String[] args) { new GUI(); } /** * Default Constructor */ public GUI() { grid = new GridPane(); frame = new JFrame("Grid"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); setButton = new JButton("What number is this?"); setButton.setPreferredSize(new Dimension(160, 40)); setButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { PrintWriter out = new PrintWriter("../../test"); out.println(grid.toString()); out.close(); } catch (FileNotFoundException er) { er.printStackTrace(); } grid.clear(); } }); frame.add(grid, BorderLayout.CENTER); frame.add(setButton, BorderLayout.PAGE_END); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } /** * Grid of 2 dimensional cells. * * Default size: 7 x 5 */ private class GridPane extends JPanel { private int colCount; private int rowCount; private List<CellPane> cells = new ArrayList<>(colCount * rowCount); /** * Default Constructor */ public GridPane() { colCount = 5; rowCount = 7; init(); } /** * Custom Grid Constructor * * Sets the number of rows and columns by the user. * If number of rows <= 0 then will default to 8. * If number of columns <= 0 then will default to 8. * * @param row * @param col */ public GridPane(int row, int col) { rowCount = row > 0 ? row : 8; colCount = col > 0 ? col : 8; init(); } /** * Initializes the pane by adding cells */ private void init() { setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); for(int row = 0; row < rowCount; row++) { for(int col = 0; col < colCount; col++) { gbc.gridx = col; gbc.gridy = row; cells.add(new CellPane()); CellPane cellPane = cells.get(cells.size() - 1); Border border = null; if(row < rowCount - 1) { if(col < colCount - 1) { border = new MatteBorder(1, 1, 0, 0, Color.GRAY); } else { border = new MatteBorder(1, 1, 0, 1, Color.GRAY); } } else { if(col < colCount - 1) { border = new MatteBorder(1, 1, 1, 0, Color.GRAY); } else { border = new MatteBorder(1, 1, 1, 1, Color.GRAY); } } cellPane.setBorder(border); add(cellPane, gbc); } } } /** * Sets all cells to unselected. */ public void clear() { for(int i = 0; i < cells.size(); i++) { cells.get(i).clear(); } } /** * Returns a list of cells. * * @return */ public List<CellPane> getCells() { return cells; } /** * Returns a list of integers where 1s represents selected cells * and 0 represents unselected cells. * * @return */ public List<Integer> getValues() { List<Integer> cellValues = new ArrayList(cells.size()); for(int i = 0; i < cells.size(); i++) { cellValues.add(cells.get(i).getValue()); } return cellValues; } /** * Returns a string set of cell values. * * @return */ public String toString() { String str = ""; List<Integer> cellValues = this.getValues(); for(int i = 0; i < cellValues.size(); i++) { str += cellValues.get(i); if(i < cellValues.size() - 1) { str += " "; } } return str; } } /** * Individual cell from grid. * They may be selected or unselected by clicking and returns 1 when selected and 0 when not. */ public class CellPane extends JPanel { private Color defaultBackground; /** * Default Constructor */ public CellPane() { setPreferredSize(new Dimension(50, 50)); defaultBackground = getBackground(); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (getBackground().getBlue() == 0) { setBackground(defaultBackground); } else { setBackground(Color.BLACK); } } }); } /** * Sets cell to unselected */ public void clear() { setBackground(defaultBackground); } /** * Returns 1 when cell is selected and 0 when it is not selected. * * @return */ public int getValue() { if(getBackground().getBlue() == 0) { return 1; } return 0; } /** * Returns cell's value as a string. * * @return */ public String toString() { return Integer.toString(this.getValue()); } } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import javax.swing.*; import javax.swing.plaf.basic.BasicComboBoxUI; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); UIManager.put("ComboBox.buttonDarkShadow", UIManager.getColor("TextField.foreground")); String[] comboModel = {"Name 0", "Name 1", "Name 2"}; String[] columnNames = {"Integer", "String", "Boolean"}; Object[][] data = { {12, comboModel[0], true}, {5, comboModel[2], false}, {92, comboModel[1], true}, {3, comboModel[0], false} }; TableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; JTable table = new JTable(model); TableColumn col = table.getColumnModel().getColumn(0); col.setMinWidth(60); col.setMaxWidth(60); col.setResizable(false); col = table.getColumnModel().getColumn(1); col.setCellEditor(new DefaultCellEditor(makeComboBox(new DefaultComboBoxModel<>(comboModel)))); // table.setDefaultEditor(JComboBox.class, new DefaultCellEditor(combo)); table.setAutoCreateRowSorter(true); add(new JScrollPane(table)); setPreferredSize(new Dimension(320, 240)); } private static <E> JComboBox<E> makeComboBox(ComboBoxModel<E> model) { return new JComboBox<E>(model) { @Override public void updateUI() { super.updateUI(); setBorder(BorderFactory.createEmptyBorder()); setUI(new BasicComboBoxUI() { @Override protected JButton createArrowButton() { JButton button = super.createArrowButton(); button.setContentAreaFilled(false); button.setBorder(BorderFactory.createEmptyBorder()); return button; } }); // JTextField editor = (JTextField) getEditor().getEditorComponent(); // editor.setBorder(BorderFactory.createEmptyBorder()); // editor.setOpaque(true); // editor.setEditable(false); } }; // combo.setBorder(BorderFactory.createEmptyBorder()); // ((JTextField) combo.getEditor().getEditorComponent()).setBorder(null); // ((JTextField) combo.getEditor().getEditorComponent()).setMargin(null); // combo.setBackground(Color.WHITE); // combo.setOpaque(true); // combo.setEditable(true); // return combo; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.List; public class Pacman { private static final List<CallGroup> mRequestedCallGroups = new ArrayList<>(); private static final List<CallGroup> mCompletedCallGroups = new ArrayList<>(); private static OnCallsCompleteListener mOnCallsCompleteListener; /** * Check whether all specified API calls are completed */ private static void checkForApiCallsCompletion() { boolean allCallsComplete = true; for (CallGroup callGroup : mRequestedCallGroups) { if (!mCompletedCallGroups.contains(callGroup)) { allCallsComplete = false; break; } else { int indexOfSelectedCallGroup = mCompletedCallGroups.indexOf(callGroup); CallGroup selectedGroup = mCompletedCallGroups.get(indexOfSelectedCallGroup); if (selectedGroup.getCalls() < callGroup.getCalls()) { allCallsComplete = false; break; } } } //If all calls are made then fire a callback to the listener if (allCallsComplete) { mOnCallsCompleteListener.onCallsCompleted(); } } /** * Required to initialize Pacman with the API call groups details * and a callback listener to be notified when all calls have been * completed * * @param callGroups An ArrayList of CallGroup objects with details for the call groups * @param onCallsCompleteListener A callback listener to get notified when all calls are finished */ public static void initialize(@NonNull List<CallGroup> callGroups, @NonNull OnCallsCompleteListener onCallsCompleteListener) { mRequestedCallGroups.clear(); mCompletedCallGroups.clear(); mRequestedCallGroups.addAll(callGroups); mOnCallsCompleteListener = onCallsCompleteListener; } /** * Post an API call update to a specific call group * * @param groupId ID for the Call Group */ public static void postCallGroupUpdate(long groupId) { CallGroup callGroupToUpdate = new CallGroup(groupId, 0); if (!mRequestedCallGroups.contains(callGroupToUpdate)) { return; } if (mCompletedCallGroups.contains(callGroupToUpdate)) { int indexOfSpecifiedCallGroup = mCompletedCallGroups.indexOf(callGroupToUpdate); CallGroup specifiedCallGroup = mCompletedCallGroups.get(indexOfSpecifiedCallGroup); int callsMade = specifiedCallGroup.getCalls() + 1; specifiedCallGroup.setCalls(callsMade); mCompletedCallGroups.remove(indexOfSpecifiedCallGroup); mCompletedCallGroups.add(specifiedCallGroup); } else { mCompletedCallGroups.add(new CallGroup(groupId, 1)); } checkForApiCallsCompletion(); } /** * Post an API call update to a specific call group and also * increase the no of calls to expect for that group * * @param groupId ID for the specific call group * @param callsToAdd No of calls to add to that group */ public static void postCallGroupUpdate(long groupId, int callsToAdd) { CallGroup callGroupToUpdate = new CallGroup(groupId, 0); if (mRequestedCallGroups.contains(callGroupToUpdate)) { int indexOfSpecifiedCallGroup = mRequestedCallGroups.indexOf(callGroupToUpdate); CallGroup specifiedCallGroup = mRequestedCallGroups.get(indexOfSpecifiedCallGroup); int callsToMake = specifiedCallGroup.getCalls() + callsToAdd; specifiedCallGroup.setCalls(callsToMake); mRequestedCallGroups.remove(indexOfSpecifiedCallGroup); mRequestedCallGroups.add(specifiedCallGroup); } postCallGroupUpdate(groupId); } public interface OnCallsCompleteListener { void onCallsCompleted(); } }
package torrent.network.utp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Random; import org.johnnei.utils.JMath; import org.johnnei.utils.ThreadUtils; import torrent.Manager; import torrent.download.peer.Peer; import torrent.network.ByteInputStream; import torrent.network.ByteOutputStream; import torrent.network.Stream; /** * The uTorrent Transport Protocol Socket.<br/> * The socket supports: TCP and uTP.<br/> * The socket will by default send data over TCP until the switch is being hit to send via uTP. * * @author Johnnei * */ public class UtpSocket extends Socket { /** * The implemented version of the uTP Protocol */ public static final byte VERSION = 1; /** * Regular Data packet<br/> * Must have data payload */ public static final byte ST_DATA = 0; /** * Finalize Packet<br/> * Closes the socket in a formal manner<br/> * The seq_nr of this packet will be the eof_pkt and no seq_nr will become higher.<br/> * The other end may wait for missing/ out of order packets which are still pending and lower than eof_pkt */ public static final byte ST_FIN = 1; /** * State Packet<br/> * A packet which is used to send ACK messages whilst there is no data to be send along with it<br/> * This packet does not increase {@link #seq_nr} */ public static final byte ST_STATE = 2; /** * Reset Packet<br/> * Abruptly closes the socket<br/> */ public static final byte ST_RESET = 3; /** * Connect Packet<br/> * {@link #seq_nr} is initialized to 1<br/> * {@link #connection_id_recv} is initialized to a random number.<br/> * {@link #connection_id_send} is initialized to {@link #connection_id_recv} + 1<br/> * This message is send with {@link #connection_id_recv} instead of {@link #connection_id_send}<br/> * The other end will copy the received id */ public static final byte ST_SYN = 4; /** * The connectionId for sockets which have not yet been initialised */ public static final int NO_CONNECTION = Integer.MAX_VALUE; /** * This is the default state for either:<br/> * TCP Connection or uTP is being initialized */ /** * UDP Socket */ private DatagramSocket socket; /** * The maximum amount of bytes which have not yet been acked */ private int max_window; /** * The number of bytes which have not yet been acked */ private int cur_window; /** * The {@link #max_window} as received from the other end.<br/> * This sets the upper limit for the bytes which have not yet been acked */ private int wnd_size; /** * Our 16-bit connection id */ private int connection_id_send; /** * Their 16-bit connection id.<br/> * This should be {@link #connection_id_send} value + 1 */ private int connection_id_recv; /** * The next packet id */ private short seq_nr; /** * The last received packet id */ private short ack_nr; /** * The last measured delay on this socket */ private long measured_delay; /** * The state of the uTP Connection.<br/> * For {@link #ST_RESET} is (as specified) no state */ private ConnectionState utpConnectionState; /** * The size of each packet which send on the stream */ private int packetSize; /** * The current state of the Socket<br/> * If true: uTP is being used<br/> * If false <i>default</i>: TCP is being used */ private boolean utpEnabled; /** * A buffer to store data blocks in */ private Stream utpBuffer; /** * The messages which have not yet been acked */ private ArrayList<UtpMessage> messagesInFlight; /** * The messages which have not yet been send by limitations */ private ArrayList<UtpMessage> messageQueue; /** * The window in which messages have to arrive before being "lost" */ private int timeout; private SocketAddress remoteAddress; /** * Creates a new uTP socket */ public UtpSocket() { utpEnabled = true; cur_window = 0; utpConnectionState = ConnectionState.PENDING; packetSize = 150; wnd_size = 150; seq_nr = 1; timeout = 1000; utpBuffer = new Stream(5000); connection_id_recv = NO_CONNECTION; connection_id_send = NO_CONNECTION; messagesInFlight = new ArrayList<>(); messageQueue = new ArrayList<>(); } /** * Creates a new uTP socket */ public UtpSocket(boolean utpEnabled) { this(); this.utpEnabled = utpEnabled; } public UtpSocket(SocketAddress address, boolean utpEnabled) throws IOException { this(utpEnabled); remoteAddress = address; socket = new DatagramSocket(); } /** * Gets called if the socket got accepted from outside the client to set the remoteAddress correctly */ public void accepted() throws IOException { remoteAddress = getRemoteSocketAddress(); socket = new DatagramSocket(remoteAddress); } /** * Connects to the TCP Socket * * @throws IOException */ public void connect() throws IOException { System.out.println("Connecting TCP to " + remoteAddress); utpConnectionState = ConnectionState.DISCONNECTED; utpEnabled = false; super.connect(remoteAddress, 1000); } /** * Connects to the uTP Socket and prepares the UDP Socket * * @param address The address to connect to */ public void connect(SocketAddress address) throws IOException { connect(address, 1000); } /** * Connects to the uTP Socket and prepares the UDP Socket * * @param address The address to connect to * @param timeout The maximum amount of miliseconds this connect attempt may take */ public void connect(SocketAddress address, int timeout) throws IOException { socket = new DatagramSocket(getPort()); remoteAddress = address; this.timeout = timeout; utpConnectionState = ConnectionState.CONNECTING; connection_id_recv = new Random().nextInt() & 0xFFFF; connection_id_send = connection_id_recv + 1; System.out.println("Connecting uTP to " + address + " connId: " + connection_id_recv); UtpMessage synMessage = new UtpMessage(connection_id_recv, cur_window, ST_SYN, seq_nr++, 0); write(synMessage); long sendTime = System.currentTimeMillis(); int tries = 1; byte[] response = null; while (response == null) { if (System.currentTimeMillis() - sendTime >= 1000) { // Timeout write(synMessage); sendTime = System.currentTimeMillis(); if (++tries == 3) { connect(); break; } } response = Manager.getManager().getUdpMultiplexer().accept(remoteAddress, connection_id_recv); if (response == null) { ThreadUtils.sleep(100); } else { if (response[0] >>> 4 != ST_STATE) {// Check Type System.err.println("Invalid SYN Response: " + (response[0] >>> 4)); connect(); } else { System.out.println("Connected to " + address); receive(response); utpConnectionState = ConnectionState.CONNECTED; } } } } /** * Tries to send a uTP Message, If the window is to small it will get queued<br/> * If the packet got queued it will return false<br/> * It will not requeue messages which are already in the queue * * @param message the UtpMessage which should be attempted to write * @return true if the message has been send else false */ public boolean send(UtpMessage message) { if (getBytesInFlight() + message.getSize() < wnd_size) { return write(message); } else { if(!messageQueue.contains(message)) { messageQueue.add(message); } return false; } } /** * Sends a UDP Message * * @return true if the packet got sended */ private boolean write(UtpMessage message) { message.setTimestamp(this); byte[] data = message.getData(); try { DatagramPacket packet = new DatagramPacket(data, data.length, remoteAddress); socket.send(packet); if(message.getType() != ST_STATE) { //We don't expect ACK's on STATE messages messagesInFlight.add(message); } System.out.println("[uTP] Wrote message: " + (data[0] >>> 4)); return true; } catch (IOException e) { System.err.println("[uTP] Failed to send message: " + e.getMessage()); return false; } } /** * Accept a UDP Packet from the UDP Multiplexer * * @param dataBuffer The data buffer used in the packet */ private void receive(byte[] dataBuffer) { receive(dataBuffer, dataBuffer.length); } /** * Accept a UDP Packet from the UDP Multiplexer * * @param dataBuffer The data buffer used in the packet * @param length The amount of bytes received in the packet */ public void receive(byte[] dataBuffer, int length) { if (length < 20) { System.err.println("UDP Packet to small for header: " + length + " bytes"); return; } Stream data = new Stream(dataBuffer); int versionAndType = data.readByte(); int version = versionAndType & 0x7; int type = versionAndType >>> 4; System.out.println("Received UDP Message: " + type + " (Version " + version + "), Size: " + length); int extension = data.readByte(); int connection_id = data.readShort(); long timestamp = (long)(data.readInt() & 0xFFFFFFFFL); long timestampDiff = (long)(data.readInt() & 0xFFFFFFFFL); long windowSize = data.readInt(); short sequenceNumber = (short)data.readShort(); short ackNumber = (short)data.readShort(); System.out.println("Extension: " + extension); System.out.println("Connection ID: " + connection_id); System.out.println("timestampc " + (getCurrentMicroseconds() & 0xFFFFFFFFL)); System.out.println("timestamp: " + timestamp); System.out.println("timestampDiff: " + timestampDiff); System.out.println("windowSize: " + windowSize); System.out.println("sequenceNumber: " + sequenceNumber); System.out.println("ackNumber: " + ackNumber); if (extension != 0) { while (data.available() > 0) { extension = data.readByte(); int extensionLength = data.readByte(); System.out.println("Extension " + extension + " of length " + extensionLength); data.moveBack(-extensionLength); } } measured_delay = getCurrentMicroseconds() - timestamp; System.out.println("Message Delay: " + measured_delay); // Process Data switch (type) { case ST_SYN: { // Connect System.out.println("[uTP Protocol] SYN"); if(utpConnectionState == ConnectionState.CONNECTED) { System.out.println("[uTP Protocol] Ignored SYN on uTP Connected Socket"); return; } connection_id_send = connection_id; connection_id_recv = connection_id + 1; seq_nr = (short)(new Random().nextInt() & 0xFFFF); ack_nr = ackNumber; utpConnectionState = ConnectionState.CONNECTED; utpEnabled = true; System.out.println("[uTP] Connected"); messageQueue.add(new UtpMessage(this, ST_STATE, seq_nr, ackNumber)); break; } case ST_STATE: { // ACK System.out.println("[uTP Protocol] STATE"); messagesInFlight.remove(new UtpMessage(sequenceNumber)); break; } case ST_DATA: { // Data System.out.println("[uTP Protocol] DATA"); break; } case ST_FIN: { // Disconenct System.out.println("[uTP Protocol] FIN"); break; } case ST_RESET: { //Crash System.out.println("[uTP Protocol] RESET"); break; } default: { System.err.println("[uTP Protocol] Unkown type: " + type); break; } } } /** * Sets the max_window in bytes to the larger of <tt>window</tt> or 150 * @param window The new max_window */ private void setMaxWindow(int window) { max_window = JMath.max(window, 150); } /** * Sets the timeout in milliseconds to the larger of <tt>timeout</tt> or 500 * @param timeout The new timeout */ private void setTimeout(int timeout) { timeout = JMath.max(timeout, 500); } /** * Store the filtered data in the output buffer<br/> * This data will be available for the client to read * * @param dataBuffer The buffer containing all data * @param offset The start offset to start reading * @param length The amount of bytes to be read */ private void storeData(byte[] dataBuffer, int offset, int length) { if (utpBuffer.writeableSpace() >= length) { for (int i = 0; i < length; i++) { utpBuffer.writeByte(dataBuffer[offset + i]); } } else { utpBuffer.refit(); // Try to reshape the buffer so we can append the data if (utpBuffer.writeableSpace() < length) { // Still not enough so we expand the buffer utpBuffer.expand(length - utpBuffer.writeableSpace()); } storeData(dataBuffer, offset, length); } } /** * Checks if we need to try to send messages */ public void checkForSendingPackets() { while(messageQueue.size() > 0) { UtpMessage message = messageQueue.get(0); if(send(messageQueue.get(0))) { messageQueue.remove(message); } else { break; } } //Resend ack for(int i = 0; i < messagesInFlight.size(); i++) { UtpMessage message = messagesInFlight.get(i); long delay = getDelay(message, false); if(delay > timeout) { write(message); System.out.println("[uTP] Resending Message (SendTime: " + message.getSendTime() + ", Timeout: " + delay +")"); } } } /** * Calculates the delay from a message * * @param message The message to compare with * @param usPrecision If it should be microsecond precision instead of milisecond * @return the delay */ private long getDelay(UtpMessage message, boolean msPrecision) { long cTime = (int)getCurrentMicroseconds() & 0xFFFFFFFFL; long messageTime = message.getSendTime(); if(msPrecision) return cTime - messageTime; else return (cTime - messageTime) / 1000; } /** * Checks the connection if there are pending messages */ public void checkForPackets() { byte[] data = Manager.getManager().getUdpMultiplexer().accept(remoteAddress, connection_id_recv); if (data != null) { receive(data); } } /** * Calculates the amount of bytes which have not yet been acked * * @return */ private int getBytesInFlight() { int bytes = 0; for (int i = 0; i < messagesInFlight.size(); i++) { bytes += messagesInFlight.get(i).getSize(); } return bytes; } /** * Gets the current microseconds<br/> * The problem is that java does not have a precise enough system so it's just the currentMillis * 1000<br/> * But there is nanoSeconds bla bla, Read the javadocs please * * @return */ public long getCurrentMicroseconds() { return (System.currentTimeMillis() & 0xFFFFFFFFL) * 1000L;//Strip to 32-bit precision } /** * Switches the stream to TCP<br/> * */ public void disableUTP() throws IOException { utpEnabled = false; utpConnectionState = ConnectionState.CONNECTING; } public boolean isClosed() { if (utpEnabled) { return utpConnectionState == ConnectionState.DISCONNECTED; } else { if (socket == null) return false; // Else it won't even connect return socket.isClosed(); } } /** * Creates a new ByteInputStream for this socket * * @param peer The associated peer * @return The inputStream for this socket * @throws IOException */ public ByteInputStream getInputStream(Peer peer) throws IOException { if(!super.isConnected()) { return new ByteInputStream(this, peer, null); } else { return new ByteInputStream(this, peer, getInputStream()); } } public ByteOutputStream getOutputStream() throws IOException { if(!super.isConnected()) { return new ByteOutputStream(this, null); } else { return new ByteOutputStream(this, super.getOutputStream()); } } @Override public String toString() { if(!super.isConnected()) { return remoteAddress.toString(); } else { return super.getInetAddress().toString(); } } @Override public int getPort() { if(!super.isConnected()) { return 0; } else { return super.getPort(); } } /** * Gets the last measured delay on the socket * * @return The delay on this socket in microseconds */ public long getDelay() { return measured_delay; } /** * Gets the connection ID which we use to sign messages with * * @return */ public int getConnectionId() { return connection_id_send; } /** * Gets the current window size which we want to advertise * * @return */ public int getWindowSize() { return max_window; } /** * Gets the available data on the stream * * @return The stream containing the available data */ public Stream getStream() { return utpBuffer; } /** * Checks if the stream has switched to uTP Mode * * @return true if the uTP mode has been enabled */ public boolean isUTP() { return utpEnabled; } }
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.System.Logger.Level; import java.math.BigInteger; import java.net.URI; import java.nio.file.CopyOption; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.StandardCopyOption; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Comparator; import java.util.Deque; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.UnaryOperator; import java.util.spi.ToolProvider; import java.util.stream.Stream; import jdk.jfr.Category; import jdk.jfr.Event; import jdk.jfr.Label; import jdk.jfr.Name; import jdk.jfr.Recording; import jdk.jfr.StackTrace; public record Bach( Printer printer, Options options, Paths paths, Externals externals, Tools tools) { public static void main(String... args) { var bach = Bach.of(args); var code = bach.main(); if (code != 0) System.exit(code); } public static Bach of(String... args) { return Bach.of(Printer.ofSystem(), args); } public static Bach of(Printer printer, String... args) { var options = Options.of(args); var properties = PathSupport.properties(options.__chroot.resolve("bach.properties")); var programs = new TreeMap<Path, URI>(); for (var key : properties.stringPropertyNames()) { if (key.startsWith(".bach/external-tool-program/")) { var to = Path.of(key).normalize(); var from = URI.create(properties.getProperty(key)); programs.put(to, from); } } return new Bach( printer, options, new Paths(options.__chroot, options.__destination), new Externals( properties.getProperty("bach.externals.default-checksum-algorithm", "SHA-256"), programs), new Tools( ToolFinder.compose( ToolFinder.of( Tool.of("help", Tool::help), Tool.of("/?", Tool::help), Tool.of("/save", Tool::save)), ToolFinder.ofBasicTools(options.__chroot.resolve(".bach/basic-tools")), ToolFinder.ofPrograms( options.__chroot.resolve(".bach/external-tool-program"), Path.of(System.getProperty("java.home"), "bin", "java"), "java.args"), ToolFinder.of( Tool.of("banner", Tool::banner), Tool.of("checksum", Tool::checksum), new DirectoriesToolProvider(), Tool.of("download", Tool::download), Tool.of("info", Tool::info)), ToolFinder.ofSystem(), ToolFinder.of( Tool.ofJavaHomeBinary("jarsigner"), Tool.ofJavaHomeBinary("jdeprscan"), Tool.ofJavaHomeBinary("jfr"))))); } public boolean is(Flag flag) { return options.flags.contains(flag); } public void banner(String text) { var line = "=".repeat(text.length()); printer.print(""" %s %s %s""".formatted(line, text, line)); } public void info() { printer.print("bach.paths = %s".formatted(paths)); if (!is(Flag.VERBOSE)) return; Stream.of( ToolCall.of("jar").with("--version"), ToolCall.of("javac").with("--version"), ToolCall.of("javadoc").with("--version")) .parallel() .forEach(this::run); Stream.of( ToolCall.of("jdeps").with("--version"), ToolCall.of("jlink").with("--version"), ToolCall.of("jmod").with("--version"), ToolCall.of("jpackage").with("--version")) .sequential() .forEach(this::run); } public void help() { printer.print( """ Usage: java Bach.java [OPTIONS] TOOL-NAME [TOOL-ARGS...] Available tools include: """); tools.finder().tree(printer.out()); } public void checksum(Path path) { run("checksum", path, externals.defaultChecksumAlgorithm()); } public void checksum(Path path, String algorithm) { var checksum = PathSupport.computeChecksum(path, algorithm); printer.print("%s %s".formatted(checksum, path)); } public void checksum(Path path, String algorithm, String expected) { var computed = PathSupport.computeChecksum(path, algorithm); if (computed.equalsIgnoreCase(expected)) return; throw new AssertionError( """ Checksum mismatch detected! path: %s algorithm: %s computed: %s expected: %s """ .formatted(path, algorithm, computed, expected)); } public void download(Map<Path, URI> map) { map.entrySet().stream() .parallel() .forEach(entry -> run("download", entry.getKey(), entry.getValue())); } public void download(Path to, URI from, CopyOption... options) { if (Set.of(options).contains(StandardCopyOption.REPLACE_EXISTING) || Files.notExists(to)) { log("Downloading %s".formatted(from)); try (var stream = from.toURL().openStream()) { var parent = to.getParent(); if (parent != null) Files.createDirectories(parent); var size = Files.copy(stream, to, options); log("Downloaded %,12d %s".formatted(size, to.getFileName())); } catch (Exception exception) { throw new RuntimeException(exception); } } var fragment = from.getFragment(); if (fragment == null) return; for (var element : fragment.split("&")) { var property = StringSupport.parseProperty(element); var algorithm = property.key(); var expected = property.value(); run("checksum", to, algorithm, expected); } } public void log(String message) { log(Level.DEBUG, message); } public void log(Level level, String message) { var event = new LogEvent(); event.level = level.name(); event.message = message; event.commit(); var severity = level.getSeverity(); if (severity < options.__logbook_threshold.getSeverity()) return; if (severity <= Level.DEBUG.getSeverity()) { printer.print(message); return; } if (severity >= Level.ERROR.getSeverity()) { printer.error(message); return; } var max = 1000; printer.print(message.length() <= max ? message : message.substring(0, max - 5) + "[...]"); } private int main() { var seed = options.seed(); if (seed == null) { help(); return 1; } try (var recording = new Recording()) { recording.start(); log("BEGIN"); try { run(seed, Level.DEBUG); return 0; } catch (RuntimeException exception) { log(Level.ERROR, exception.toString()); return -1; } finally { log("END."); recording.stop(); var jfr = Files.createDirectories(paths.out()).resolve("bach-logbook.jfr"); recording.dump(jfr); } } catch (Exception exception) { log(Level.ERROR, exception.toString()); return -2; } } public void run(String name, Object... arguments) { run(ToolCall.of(name, arguments)); } public void run(String name, UnaryOperator<ToolCall> operator) { run(operator.apply(ToolCall.of(name))); } public void run(ToolCall call) { run(call, Level.INFO); } void run(ToolCall call, Level level) { var name = call.name(); var arguments = call.arguments(); var event = new RunEvent(); event.name = name; event.args = String.join(" ", arguments); log(level, arguments.isEmpty() ? name : name + ' ' + event.args); var tool = tools.finder().find(name).orElseThrow(() -> new ToolNotFoundException(name)); var out = new ForwardingStringWriter(s -> printer().out().accept(s.indent(2).stripTrailing())); var err = new ForwardingStringWriter(s -> printer().err().accept(s.indent(2).stripTrailing())); var args = arguments.toArray(String[]::new); event.begin(); event.code = tool instanceof Tool.Provider provider ? provider.run(this, new PrintWriter(out, true), new PrintWriter(err, true), args) : tool.run(new PrintWriter(out, true), new PrintWriter(err, true), args); event.end(); event.out = out.toString().strip(); event.err = err.toString().strip(); event.commit(); if (event.code == 0) return; throw new AssertionError( """ %s returned non-zero exit code: %d """ .formatted(call.name(), event.code)); } public record Printer(Consumer<String> out, Consumer<String> err, Deque<Line> lines) { record Line(Level level, String text) {} public static Printer ofSilent() { return new Printer(__ -> {}, __ -> {}, new ConcurrentLinkedDeque<>()); } public static Printer ofSystem() { return new Printer(System.out::println, System.err::println, new ConcurrentLinkedDeque<>()); } public void print(String string) { lines.add(new Line(Level.INFO, string)); out.accept(string); } public void error(String string) { lines.add(new Line(Level.ERROR, string)); err.accept(string); } } @FunctionalInterface public interface Tool { int run(Bach bach, PrintWriter out, PrintWriter err, String... args); interface Provider extends Tool, ToolProvider { @Override default int run(PrintWriter out, PrintWriter err, String... args) { return run(Bach.of(Printer.ofSilent()), out, err, args); } } static Provider of(String name, Tool tool) { record Wrapper(String name, Tool tool) implements Provider { @Override public int run(Bach bach, PrintWriter out, PrintWriter err, String... args) { return tool.run(bach, out, err, args); } } return new Wrapper(name, tool); } static ToolProvider ofJavaHomeBinary(String name) { var executable = Path.of(System.getProperty("java.home"), "bin", name); return new ToolFinder.ExecuteProgramToolProvider(name, List.of(executable.toString())); } private static int banner(Bach bach, PrintWriter out, PrintWriter err, String... args) { if (args.length == 0) { err.println("Usage: banner TEXT"); return 1; } bach.banner(String.join(" ", args)); return 0; } private static int checksum(Bach bach, PrintWriter out, PrintWriter err, String... args) { if (args.length < 1 || args.length > 3) { err.println("Usage: checksum FILE [ALGORITHM [EXPECTED-CHECKSUM]]"); return 1; } var file = Path.of(args[0]); switch (args.length) { case 1 -> bach.checksum(file); case 2 -> bach.checksum(file, args[1]); case 3 -> bach.checksum(file, args[1], args[2]); } return 0; } private static int download(Bach bach, PrintWriter out, PrintWriter err, String... args) { if (args.length == 0) { // everything bach.download(bach.externals().programs()); return 0; } if (args.length == 2) { var to = Path.of(args[0]); var from = URI.create(args[1]); bach.download(to, from); return 0; } err.println("Usage: download TO-PATH FROM-URI"); return 1; } private static int help(Bach bach, PrintWriter out, PrintWriter err, String... args) { bach.help(); return 0; } private static int info(Bach bach, PrintWriter out, PrintWriter err, String... args) { bach.info(); return 0; } private static int save(Bach bach, PrintWriter out, PrintWriter err, String... args) { var usage = """ Usage: save TARGET VERSION Examples: save Bach.java 1.0 save .bach/Bach-HEAD.java HEAD """; if (args.length == 1 && args[0].equalsIgnoreCase("--help")) { out.println(usage); return 0; } if (args.length != 2) { err.println(usage); return 1; } var target = Path.of(args[0]); var version = args[1]; var from = "https://github.com/sormuras/bach/raw/%s/src/Bach.java".formatted(version); out.println("<< " + from); bach.download(target, URI.create(from), StandardCopyOption.REPLACE_EXISTING); out.println(">> " + target); return 0; } } public record Paths(Path root, Path out) {} public record Externals(String defaultChecksumAlgorithm, Map<Path, URI> programs) {} public record Tools(ToolFinder finder) {} public enum Flag { VERBOSE } public record Options( Set<Flag> flags, Level __logbook_threshold, Path __chroot, Path __destination, ToolCall seed) { static Options of(String... args) { var flags = EnumSet.noneOf(Flag.class); var level = Level.INFO; var root = Path.of(""); var destination = Path.of(".bach", "out"); ToolCall seed = null; var arguments = new ArrayDeque<>(List.of(args)); while (!arguments.isEmpty()) { var argument = arguments.removeFirst(); if (argument.startsWith(" if (argument.equals("--verbose")) { flags.add(Flag.VERBOSE); continue; } var delimiter = argument.indexOf('=', 2); var key = delimiter == -1 ? argument : argument.substring(0, delimiter); var value = delimiter == -1 ? arguments.removeFirst() : argument.substring(delimiter + 1); if (key.equals("--logbook-threshold")) { level = Level.valueOf(value); continue; } if (key.equals("--chroot")) { root = Path.of(value).normalize(); continue; } if (key.equals("--destination")) { destination = Path.of(value).normalize(); continue; } throw new IllegalArgumentException("Unsupported option `%s`".formatted(key)); } seed = new ToolCall(argument, arguments.stream().toList()); break; } return new Options(Set.copyOf(flags), level, root, root.resolve(destination), seed); } } public record ToolCall(String name, List<String> arguments) { public static ToolCall of(String name, Object... arguments) { if (arguments.length == 0) return new ToolCall(name, List.of()); if (arguments.length == 1) return new ToolCall(name, List.of(arguments[0].toString())); return new ToolCall(name, List.of()).with(Stream.of(arguments)); } public ToolCall with(Stream<?> objects) { var strings = objects.map(Object::toString); return new ToolCall(name, Stream.concat(arguments.stream(), strings).toList()); } public ToolCall with(Object argument) { return with(Stream.of(argument)); } public ToolCall with(String key, Object value, Object... values) { var call = with(Stream.of(key, value)); return values.length == 0 ? call : call.with(Stream.of(values)); } public ToolCall withFindFiles(String glob) { return withFindFiles(Path.of(""), glob); } public ToolCall withFindFiles(Path start, String glob) { return withFindFiles(start, "glob", glob); } public ToolCall withFindFiles(Path start, String syntax, String pattern) { var syntaxAndPattern = syntax + ':' + pattern; var matcher = start.getFileSystem().getPathMatcher(syntaxAndPattern); return withFindFiles(start, Integer.MAX_VALUE, matcher); } public ToolCall withFindFiles(Path start, int maxDepth, PathMatcher matcher) { try (var files = Files.find(start, maxDepth, (p, a) -> matcher.matches(p))) { return with(files); } catch (Exception exception) { throw new RuntimeException("Find files failed in: " + start, exception); } } } /** * A finder of tool providers. * * <p>What {@link java.lang.module.ModuleFinder ModuleFinder} is to {@link * java.lang.module.ModuleReference ModuleReference}, is {@link ToolFinder} to {@link * ToolProvider}. */ @FunctionalInterface public interface ToolFinder { List<ToolProvider> findAll(); default Optional<ToolProvider> find(String name) { return findAll().stream().filter(tool -> tool.name().equals(name)).findFirst(); } default String title() { return getClass().getSimpleName(); } default void tree(Consumer<String> out) { visit(0, (depth, finder) -> tree(out, depth, finder)); } private void tree(Consumer<String> out, int depth, ToolFinder finder) { var indent = " ".repeat(depth); out.accept(indent + finder.title()); if (finder instanceof CompositeToolFinder) return; finder.findAll().stream() .sorted(Comparator.comparing(ToolProvider::name)) .forEach(tool -> out.accept(indent + " - " + tool.name())); } default void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) { visitor.accept(depth, this); } static ToolFinder of(ToolProvider... providers) { record DirectToolFinder(List<ToolProvider> findAll) implements ToolFinder { @Override public String title() { return "DirectToolFinder (%d)".formatted(findAll.size()); } } return new DirectToolFinder(List.of(providers)); } static ToolFinder of(ClassLoader loader) { return ToolFinder.of(ServiceLoader.load(ToolProvider.class, loader)); } static ToolFinder of(ServiceLoader<ToolProvider> loader) { record ServiceLoaderToolFinder(ServiceLoader<ToolProvider> loader) implements ToolFinder { @Override public List<ToolProvider> findAll() { synchronized (loader) { return loader.stream().map(ServiceLoader.Provider::get).toList(); } } } return new ServiceLoaderToolFinder(loader); } static ToolFinder ofSystem() { return ToolFinder.of(ClassLoader.getSystemClassLoader()); } static ToolFinder ofBasicTools(Path directory) { record BasicToolProvider(String name, Properties properties) implements Tool.Provider { @Override public int run(Bach bach, PrintWriter out, PrintWriter err, String... args) { var commands = properties.stringPropertyNames().stream() .sorted(Comparator.comparing(Integer::parseInt)) .map(properties::getProperty) .toList(); for (var command : commands) { var lines = command.lines().map(line -> replace(bach, line)).toList(); var name = lines.get(0); if (name.toUpperCase().startsWith("GOTO")) throw new Error("GOTO IS TOO BASIC!"); var call = ToolCall.of(name).with(lines.stream().skip(1)); bach.run(call); } return 0; } private String replace(Bach bach, String line) { return line.trim() .replace("{{bach.paths.root}}", PathSupport.normalized(bach.paths.root)) .replace("{{bach.paths.out}}", PathSupport.normalized(bach.paths.out)) .replace("{{path.separator}}", System.getProperty("path.separator")); } } record BasicToolFinder(Path directory) implements ToolFinder { @Override public String title() { return "BasicToolFinder (%s)".formatted(directory); } @Override public List<ToolProvider> findAll() { if (!Files.isDirectory(directory)) return List.of(); var list = new ArrayList<ToolProvider>(); try (var paths = Files.newDirectoryStream(directory, "*.properties")) { for (var path : paths) { if (Files.isDirectory(path)) continue; var filename = path.getFileName().toString(); var name = filename.substring(0, filename.length() - ".properties".length()); var properties = PathSupport.properties(path); list.add(new BasicToolProvider(name, properties)); } } catch (Exception exception) { throw new RuntimeException(exception); } return List.copyOf(list); } } return new BasicToolFinder(directory); } static ToolFinder ofPrograms(Path directory, Path java, String argsfile) { record ProgramToolFinder(Path path, Path java, String argsfile) implements ToolFinder { @Override public List<ToolProvider> findAll() { var name = path.normalize().toAbsolutePath().getFileName().toString(); return find(name).map(List::of).orElseGet(List::of); } @Override public Optional<ToolProvider> find(String name) { var directory = path.normalize().toAbsolutePath(); if (!Files.isDirectory(directory)) return Optional.empty(); if (!name.equals(directory.getFileName().toString())) return Optional.empty(); var command = new ArrayList<String>(); command.add(java.toString()); var args = directory.resolve(argsfile); if (Files.isRegularFile(args)) { command.add("@" + args); return Optional.of(new ExecuteProgramToolProvider(name, command)); } var jars = PathSupport.list(directory, PathSupport::isJarFile); if (jars.size() == 1) { command.add("-jar"); command.add(jars.get(0).toString()); return Optional.of(new ExecuteProgramToolProvider(name, command)); } var javas = PathSupport.list(directory, PathSupport::isJavaFile); if (javas.size() == 1) { command.add(javas.get(0).toString()); return Optional.of(new ExecuteProgramToolProvider(name, command)); } throw new UnsupportedOperationException("Unknown program layout in " + directory.toUri()); } } record ProgramsToolFinder(Path path, Path java, String argsfile) implements ToolFinder { @Override public String title() { return "ProgramsToolFinder (%s -> %s)".formatted(path, java); } @Override public List<ToolProvider> findAll() { return PathSupport.list(path, Files::isDirectory).stream() .map(directory -> new ProgramToolFinder(directory, java, argsfile)) .map(ToolFinder::findAll) .flatMap(List::stream) .toList(); } } return new ProgramsToolFinder(directory, java, argsfile); } static ToolFinder compose(ToolFinder... finders) { return new CompositeToolFinder(List.of(finders)); } record CompositeToolFinder(List<ToolFinder> finders) implements ToolFinder { @Override public String title() { return "CompositeToolFinder (%d)".formatted(finders.size()); } @Override public List<ToolProvider> findAll() { return finders.stream().flatMap(finder -> finder.findAll().stream()).toList(); } @Override public Optional<ToolProvider> find(String name) { for (var finder : finders) { var tool = finder.find(name); if (tool.isPresent()) return tool; } return Optional.empty(); } @Override public void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) { visitor.accept(depth, this); depth++; for (var finder : finders) finder.visit(depth, visitor); } } record ExecuteProgramToolProvider(String name, List<String> command) implements ToolProvider { @Override public int run(PrintWriter out, PrintWriter err, String... arguments) { var builder = new ProcessBuilder(new ArrayList<>(command)); builder.command().addAll(List.of(arguments)); try { var process = builder.start(); new Thread(new StreamLineConsumer(process.getInputStream(), out::println)).start(); new Thread(new StreamLineConsumer(process.getErrorStream(), err::println)).start(); return process.waitFor(); } catch (Exception exception) { exception.printStackTrace(err); return -1; } } } } record StreamLineConsumer(InputStream stream, Consumer<String> consumer) implements Runnable { public void run() { new BufferedReader(new InputStreamReader(stream)).lines().forEach(consumer); } } static final class ForwardingStringWriter extends StringWriter { private int beginIndex = 0; private final Consumer<String> consumer; ForwardingStringWriter(Consumer<String> consumer) { this.consumer = consumer; } @Override public void flush() { var buffer = getBuffer(); if (buffer.isEmpty()) return; var string = buffer.toString(); var length = string.length(); if (beginIndex >= length) return; consumer.accept(string.substring(beginIndex)); beginIndex = length; } } static final class PathSupport { static String computeChecksum(Path path, String algorithm) { if (Files.notExists(path)) throw new RuntimeException("File not found: " + path); try { if ("size".equalsIgnoreCase(algorithm)) return Long.toString(Files.size(path)); var md = MessageDigest.getInstance(algorithm); try (var source = new BufferedInputStream(new FileInputStream(path.toFile())); var target = new DigestOutputStream(OutputStream.nullOutputStream(), md)) { source.transferTo(target); } return String.format( "%0" + (md.getDigestLength() * 2) + "x", new BigInteger(1, md.digest())); } catch (Exception exception) { throw new RuntimeException(exception); } } static Properties properties(Path path) { var properties = new Properties(); if (Files.exists(path)) { try { properties.load(new FileInputStream(path.toFile())); } catch (Exception exception) { throw new RuntimeException(exception); } } return properties; } static boolean isJarFile(Path path) { return nameOrElse(path, "").endsWith(".jar") && Files.isRegularFile(path); } static boolean isJavaFile(Path path) { return nameOrElse(path, "").endsWith(".java") && Files.isRegularFile(path); } static boolean isModuleInfoJavaFile(Path path) { return "module-info.java".equals(name(path)) && Files.isRegularFile(path); } static List<Path> list(Path directory, DirectoryStream.Filter<? super Path> filter) { if (Files.notExists(directory)) return List.of(); var paths = new TreeSet<>(Comparator.comparing(Path::toString)); try (var stream = Files.newDirectoryStream(directory, filter)) { stream.forEach(paths::add); } catch (Exception exception) { throw new RuntimeException(exception); } return List.copyOf(paths); } static String name(Path path) { return nameOrElse(path, null); } static String nameOrElse(Path path, String defautName) { var normalized = path.normalize(); var candidate = normalized.toString().isEmpty() ? normalized.toAbsolutePath() : normalized; var name = candidate.getFileName(); return name != null ? name.toString() : defautName; } static String normalized(Path path) { var string = path.normalize().toString(); return string.isEmpty() ? "." : string; } } static final class StringSupport { record Property(String key, String value) {} static Property parseProperty(String string) { return StringSupport.parseProperty(string, '='); } static Property parseProperty(String string, char separator) { int index = string.indexOf(separator); if (index < 0) { var message = "Expected a `KEY%sVALUE` string, but got: %s".formatted(separator, string); throw new IllegalArgumentException(message); } var key = string.substring(0, index); var value = string.substring(index + 1); return new Property(key, value); } } static final class ToolNotFoundException extends RuntimeException { @java.io.Serial private static final long serialVersionUID = -417539767734303099L; public ToolNotFoundException(String name) { super("Tool named `%s` not found".formatted(name)); } } public record DirectoriesToolProvider() implements ToolProvider { private enum Mode { CREATE, CLEAN, DELETE } @Override public String name() { return "directories"; } @Override public int run(PrintWriter out, PrintWriter err, String... args) { if (args.length != 2) { out.println(""" Usage: directories [create|clean|delete] PATH """); return 1; } try { var mode = Mode.valueOf(args[0].toUpperCase()); var path = Path.of(args[1]); if (mode == Mode.DELETE || mode == Mode.CLEAN) deleteDirectories(path); if (mode == Mode.CREATE || mode == Mode.CLEAN) createDirectories(path); } catch (Exception exception) { exception.printStackTrace(err); return 2; } return 0; } static void createDirectories(Path root) throws Exception { Files.createDirectories(root); } static void deleteDirectories(Path root) throws Exception { if (Files.notExists(root)) return; try (var stream = Files.walk(root)) { var paths = stream.sorted((p, q) -> -p.compareTo(q)); for (var path : paths.toArray(Path[]::new)) Files.deleteIfExists(path); } } } @Category("Bach") @Name("Bach.LogEvent") @Label("Log") @StackTrace(false) static final class LogEvent extends Event { String level; String message; } @Category("Bach") @Name("Bach.RunEvent") @Label("Run") @StackTrace(false) static final class RunEvent extends Event { String name; String args; int code; String out; String err; } }
package models; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import controllers.SQLCommander; import org.json.simple.JSONObject; import utilities.Converter; import utilities.General; import utilities.Loggy; import java.util.List; public class Activity extends AbstractSimpleMessage { public static final String TAG = Activity.class.getName(); public static final int CREATED = 0; public static final int PENDING = 1; public static final int REJECTED = 2; public static final int ACCEPTED = 3; public static final String TABLE = "activity"; public static final String TITLE = "title"; public static final String ADDRESS = "address"; public static final String CREATED_TIME = "created_time"; public static final String BEGIN_TIME = "begin_time"; public static final String DEADLINE = "application_deadline"; public static final String CAPACITY = "capacity"; public static final String NUM_APPLIED = "num_applied"; public static final String NUM_SELECTED = "num_selected"; public static final String STATUS = "status"; public static final String HOST_ID = "host_id"; public static final String HOST = "host"; public static final String VIEWER = "viewer"; public static final String LAST_ACCEPTED_TIME = "last_accepted_time"; public static final String LAST_REJECTED_TIME = "last_rejected_time"; public static final String ACTIVITIES = "activities"; public static String[] QUERY_FIELDS = {Activity.ID, Activity.TITLE, Activity.ADDRESS, Activity.CONTENT, Activity.CREATED_TIME, Activity.BEGIN_TIME, Activity.DEADLINE, Activity.CAPACITY, Activity.NUM_APPLIED, NUM_SELECTED, Activity.STATUS, Activity.HOST_ID}; protected String m_title = null; public String getTitle() { return m_title; } public void setTitle(final String title) { m_title = title; } protected Long m_createdTime = null; public long getCreatedTime() { return m_createdTime; } protected Long m_beginTime = null; public long getBeginTime() { return m_beginTime; } public void setBeginTime(long beginTime) { m_beginTime = beginTime; } protected Long m_deadline = null; public long getDeadline() { return m_deadline; } public void setDeadline(long deadline) { m_deadline = deadline; } protected Long m_lastAcceptedTime = null; public void setLastAcceptedTime(long time) { m_lastAcceptedTime = time; } protected Long m_lastRejectedTime = null; public void setLastRejectedTime(long time) { m_lastRejectedTime = time; } protected int m_capacity = 0; public int getCapacity() { return m_capacity; } protected int m_numApplied = 0; public int getNumApplied() { return m_numApplied; } protected int m_numSelected = 0; public int getNumSelected() { return m_numSelected; } protected int m_status = CREATED; public int getStatus() { return m_status; } public void setStatus(int status) { m_status = status; } protected String m_address = null; public String getAddress() { return m_address; } public void setAddress(final String address) { m_address = address; } protected User m_host = null; public User getHost() { return m_host; } public void setHost(User host) { m_host = host; } protected User m_viewer = null; public boolean isDeadlineExpired() { return General.millisec() > m_deadline; } public boolean hasBegun() { return General.millisec() > m_beginTime; } public Activity() { super(); } public Activity(JSONObject activityJson, User host) { super(activityJson); if (activityJson.containsKey(TITLE)) m_title = (String) activityJson.get(TITLE); if (activityJson.containsKey(CREATED_TIME)) m_createdTime = Converter.toLong(activityJson.get(CREATED_TIME)); if (activityJson.containsKey(BEGIN_TIME)) m_beginTime = Converter.toLong(activityJson.get(BEGIN_TIME)); if (activityJson.containsKey(DEADLINE)) m_deadline = Converter.toLong(activityJson.get(DEADLINE)); if (activityJson.containsKey(CAPACITY)) m_capacity = Converter.toInteger(activityJson.get(CAPACITY)); if (activityJson.containsKey(NUM_APPLIED)) m_numApplied = Converter.toInteger(activityJson.get(NUM_APPLIED)); if (activityJson.containsKey(NUM_SELECTED)) m_numSelected = Converter.toInteger(activityJson.get(NUM_SELECTED)); if (activityJson.containsKey(STATUS)) m_status = Converter.toInteger(activityJson.get(STATUS)); if (activityJson.containsKey(LAST_ACCEPTED_TIME)) m_lastAcceptedTime = Converter.toLong(activityJson.get(LAST_ACCEPTED_TIME)); if (activityJson.containsKey(LAST_REJECTED_TIME)) m_lastRejectedTime = Converter.toLong(activityJson.get(LAST_REJECTED_TIME)); if (activityJson.containsKey(ADDRESS)) m_address = (String) activityJson.get(ADDRESS); if (host != null) m_host = host; } public ObjectNode toObjectNode(Long viewerId) { ObjectNode ret = super.toObjectNode(); try { ret.put(TITLE, m_title); ret.put(ADDRESS, m_address); ret.put(CREATED_TIME, String.valueOf(m_createdTime)); ret.put(BEGIN_TIME, String.valueOf(m_beginTime)); ret.put(DEADLINE, String.valueOf(m_deadline)); ret.put(CAPACITY, String.valueOf(m_capacity)); ret.put(NUM_APPLIED, String.valueOf(m_numApplied)); ret.put(NUM_SELECTED, String.valueOf(m_numSelected)); ret.put(HOST, m_host.toObjectNode(viewerId)); if (viewerId == null) return ret; int relation = SQLCommander.queryUserActivityRelation(viewerId, m_id); if (relation != UserActivityRelation.INVALID) ret.put(UserActivityRelation.RELATION, relation); m_viewer = SQLCommander.queryUser(viewerId); if (viewerId.equals(m_host.getId())) ret.put(STATUS, String.valueOf(m_status)); if (m_viewer != null && m_viewer.getGroupId() == User.ADMIN) ret.put(STATUS, String.valueOf(m_status)); } catch (Exception e) { Loggy.e(TAG, "toObjectNode", e); } return ret; } public ObjectNode toObjectNodeWithImages(Long viewerId) { ObjectNode ret = this.toObjectNode(viewerId); try { List<Image> images = SQLCommander.queryImages(m_id); if (images == null || images.size() <= 0) return ret; ArrayNode imagesNode = new ArrayNode(JsonNodeFactory.instance); for (Image image : images) imagesNode.add(image.toObjectNode()); ret.put(ActivityDetail.IMAGES, imagesNode); } catch (Exception e) { Loggy.e(TAG, "toObjectNodeWithImages", e); } return ret; } }
package apfe.maze.runtime; import org.junit.Test; import static org.junit.Assert.*; /** * * @author gburdell */ public class SequenceTest { public static final int MODULE = 1; public static final int IDENT = 2; public static final int LPAREN = 3; public static final int RPAREN = 4; public static final int SEMI = 5; public static final int COMMA = 6; public static final int EOF = Token.EOF; public static class MyScanner extends Scanner { public MyScanner() { super.add(create("module", MODULE)); super.add(create("mod1", IDENT)); super.add(create("(", LPAREN)); super.add(create("p1", IDENT)); super.add(create(",", COMMA)); super.add(create("p2", IDENT)); super.add(create(")", RPAREN)); super.add(create(";", SEMI)); } private static Token create(String text, int code) { return Token.create(text, code); } @Override public boolean isEOF() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Token nextToken() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } public static class PortDecl extends Acceptor implements NonTerminal { @Override public Acceptor create() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override protected boolean acceptImpl() { Acceptor acc1; Repetition r1 = new Repetition(new Sequence(new Terminal(COMMA), new Terminal(IDENT))); Sequence s2 = new Sequence(new Terminal(LPAREN), new Terminal(IDENT), //new Terminal(COMMA), new Terminal(IDENT), new Terminal(RPAREN)); r1, new Terminal(RPAREN)); if (true) { acc1 = s2; } else { //TODO: need to test this after above works. //And then add stale branch/path removal. Sequence s1 = new Sequence(new Terminal(LPAREN), new Terminal(RPAREN)); Sequence s3 = new Sequence(new Optional(new Terminal(LPAREN)), new Optional(new Terminal(IDENT)), new Optional(new Terminal(RPAREN))); Alternates a1 = new Alternates(s1, s2, s3); acc1 = a1; } Graph subg = acc1.accept(getSubgraphRoot()); boolean ok = (null != subg); if (ok) { //addEdge(getSubgraphRoot(), this, subg); setSubGraph(subg); } return ok; } } public static class ModuleDefn extends Acceptor implements NonTerminal { public ModuleDefn(Scanner lex) { m_lex = lex; } public Graph run() { Graph g = new Graph(m_lex); g = accept(g.getRoot()); return g; } private final Scanner m_lex; @Override public Acceptor create() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override protected boolean acceptImpl() { Sequence s1 = new Sequence(new Terminal(MODULE), new Terminal(IDENT), new PortDecl(), new Terminal(SEMI)); Graph subg = s1.accept(getSubgraph().getRoot()); boolean ok = (null != subg); if (ok) { //addEdge(getSubgraphRoot(), this, subg); setSubGraph(subg); } return ok; } } public static final Scanner stScanner = new MyScanner(); /** * Test of acceptImpl method, of class Sequence. */ @Test public void testAcceptImpl() { System.out.println("acceptImpl"); ModuleDefn moduleDefn = new ModuleDefn(stScanner); Graph result = moduleDefn.run(); System.out.println(result.toString()); assertNotNull(result); } }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; /** * The main server program. * @author Kevin * */ public class Server { public static final int INCREMENT = 1; //payload tags in Slack POST public static final String PAYLOAD_START = "token="; public static final String CMD_TAG = "command="; public static final String TEXT_TAG = "text="; public static final String CHANNEL_NAME_TAG = "channel_name="; public static final String CHANNEL_ID_TAG = "channel_id="; public static final String USER_NAME_TAG = "user_name="; public static final String USER_ID_TAG = "user_id="; //custom commands. public static final String TIP_CMD = "%2Ftip"; public static final String CHECK_CMD = "%2Fcheck"; public static final String REGISTER_CMD = "%2Fregister"; private static ServerSocket listenSock; private static volatile Logger log; private static Thread acceptThread; private static boolean running = true; private static Server instance; public static Server getInstance(){ if (instance == null){ instance = new Server(); } return instance; } private Server(){} /** * Starts the server, binds all resources. If an instance has already is or has been * running, then nothing happens. */ public void startServer(){ //run only if the current thread is not created. Single instance if (acceptThread == null){ println("Getting configuration settings..."); Config.getInstance().getCount(); println("Retriving user database..."); println("Found " + UserDB.getInstance().getUserCount() + " users in database."); UserMapping.getInstance().getCount(); //Initialize the mapping //if there's no users in the database, warn user to add some if (UserDB.getInstance().getUserCount() == 0){ println("Warning! Server has no users registered in database."); } //create the system log println("Creating system log..."); log = new Logger("log" + logDate() + ".txt"); println("Log started in file: " + log.getFileName()); println("Starting server on port " + Config.getPort() + "..."); System.out.println("\n====================================================="); //create the listen socket try { listenSock = new ServerSocket(Config.getPort()); println("Server now running."); } catch (BindException e){ System.err.println(e.getMessage()); System.err.println("Cannot setup server! Quitting..."); System.exit(-1); } catch (UnknownHostException e) { e.printStackTrace(); System.err.println("Cannot setup server! Quitting..."); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.err.println("Cannot setup server! Quitting..."); System.exit(-1); } //create the handling thread and run it. acceptThread = new Thread(new SocketAccepter()); acceptThread.run(); } } /** * Gets the current log date and returns a string. * These strings only differ by day. * @return */ private static String logDate(){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); return formatter.format(new Date(System.currentTimeMillis())); } /** * Posts a message on slack on the specified channel * @param message * @param channel */ private static void messageSlack(String textPost, String channel){ System.out.println(textPost); //construct the JSON message String message = "payload={\"text\":\"`" + textPost + "`\", \"channel\":\"#" + channel + "\", \"username\": \"" + Config.getBotName() + "\"}"; //System.out.println(message); try { CloseableHttpClient slackServer = HttpClients.createDefault(); HttpPost slackMessage = new HttpPost(Config.getSlackWebHook()); slackMessage.setHeader("User-Agent", "Slack Points Server"); slackMessage.setHeader("content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); slackMessage.setEntity(new StringEntity(message)); HttpResponse response = slackServer.execute(slackMessage); //print reply from slack server if any. ByteArrayOutputStream baos = new ByteArrayOutputStream(); response.getEntity().writeTo(baos); Server.getInstance().println("<Slack Server>: " + (new String(baos.toByteArray()))); slackServer.close(); } catch (UnknownHostException e){ printException(e); } catch (IOException e) { printException(e); } } /** * The request handler created when a new request is being made. * @author Kevin * */ private final class RequestHandler implements Runnable{ Socket client; public RequestHandler(Socket client){ this.client = client; } @Override public void run() { try { BufferedReader buff = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8")); //find the command field of the POST request //gather all lines String complete = ""; String nextLine = buff.readLine(); while (nextLine != null){ complete = complete + nextLine; nextLine = buff.readLine(); } String payload = complete.substring(complete.indexOf("token=")); //with complete request, find the command sent String channelName = getTagArg(payload, CHANNEL_NAME_TAG); //String channelID = getTagArg(payload, CHANNEL_ID_TAG); String userID = getTagArg(payload, USER_ID_TAG); String userName = getTagArg(payload, USER_NAME_TAG); String command = getTagArg(payload, CMD_TAG); String[] args = getTextArgs(payload); //arguements of the command //print command out String fullCommand = command; for (int i =0; i < args.length; i++){ fullCommand = fullCommand + " " + args[i]; } println(userName + " issued command: \t"+fullCommand + "\n"); if (command.equals(TIP_CMD)){ //increment command sent, increment points //increment only if there is a user that exists. if (args.length == 1){ String targetID = UserMapping.getInstance().getID(args[0]); if (targetID != null){ if (UserDB.hasUser(targetID)){ if (targetID.equals(userID) == false){ //not self, do tipping UserDB.increment(targetID, INCREMENT); log.writeLine(userName + " gave " + args[0] + " " + INCREMENT + Config.getCurrencyName()); messageSlack(userName + " gave " + args[0] + " " + INCREMENT + Config.getCurrencyName(), channelName); } else{ //error, cannot tip self. messageSlack("You cannot tip yourself " + userName + "!", channelName); } } } else{ //no mapping found, return error messageSlack("I do not recognize who " + args[0] + " is! Did that user get an account with the bank of Slack? Get that user to enter the command /register to sign up. If you already have an account, but changed your name recently please enter the command /register ASAP.", channelName); } } } else if (command.equals(CHECK_CMD)){ //check command sent, return current points. if ((args.length == 1) && (args[0].equals("") == false)){ //get the id of the user String targetID = UserMapping.getInstance().getID(args[0]); if(targetID != null){ if (UserDB.hasUser(targetID)){ //user exists, return their count. User check = UserDB.getUser(targetID); String humanName = UserMapping.getInstance().getName(targetID); messageSlack(humanName + " has " + check.getPts() + Config.getCurrencyName() + ".", channelName); } } else{ //no such user exists, report back messageSlack("No such user named " + userName + " exists. Have they registered yet?", channelName); } } else if ((args.length == 1) && (args[0].equals("") == true)){ //get the id of the user String targetID = UserMapping.getInstance().getID(userName); if(targetID != null){ if (UserDB.hasUser(targetID)){ //user exists, return their count. User check = UserDB.getUser(targetID); String humanName = UserMapping.getInstance().getName(targetID); messageSlack(humanName + " has " + check.getPts() + Config.getCurrencyName() + ".", channelName); } } else{ //no such user exists, report back messageSlack("I cannot find your record " + userName + ". Have you registered yet?", channelName); } } } else if (command.equals(REGISTER_CMD)){ //register command sent, update id of new user. if (UserMapping.getInstance().registerPair(userName, userID)){ UserMapping.saveAll(); log.writeLine("Added " + userName + " as new ID: " + userID); //create new user in database UserDB.registerUser(userID); UserDB.saveAll(); messageSlack("Welcome "+ userName + "! You have " + UserDB.getUser(userID).getPts() + Config.getCurrencyName() + ". Earn more by getting tips from friends.", channelName); } else{ String oldName = UserMapping.getInstance().getName(userID); if (UserMapping.getInstance().updateName(oldName, userName)){ //successful name update. UserMapping.saveAll(); log.writeLine("Updated " + oldName + " -> " + userName); messageSlack("Gotcha! I'll remember you as " + userName + " from now on.", channelName); } } } else{ //invalid command messageSlack("Sorry I don't understand that command. :frown:", channelName); } } catch (IOException e) { printException(e); } finally{ //always close the client try { client.close(); } catch (IOException e) { printException(e); } } } } /** * Gets the command argument of the Slack slash command of the * specified tag in the request. * Returned string is pre-trimmed. * @param postRequest The request to parse * @param tag The tag to extract the value of * @return Empty string if tag is not found, Value of the tag otherwise. */ private static String getTagArg(String payload, String tag){ int index = payload.indexOf(tag); if (index >= 0){ String arg = payload.substring(index + tag.length(),payload.indexOf("&", index)); return arg.trim(); } return ""; } /** * Gets all the arguments seperated by spaces (the '+' symbol). * Returns a String array of each argument in the order they are found in. * * If there are no arguments, an empty array is returned. * If the string does not contain the " * @param payload * @return */ private static String[] getTextArgs(String payload){ int index = payload.indexOf(TEXT_TAG); if (index >=0){ String raw = payload.substring(index + TEXT_TAG.length()); return raw.split("\\+"); } return (new String[0]); } /** * The socket accepting thread that accepts all connections and attempts * to service them. * @author Kevin * */ private final class SocketAccepter implements Runnable{ @Override public void run() { while( running == true ){ try { Socket client = listenSock.accept(); //got a connection println("Recieved connection from: " + client.getInetAddress().toString() + ":" + client.getPort()); //handle request in new thread Thread clientHandler = new Thread(new RequestHandler(client)); clientHandler.run(); } catch (IOException e) { printException(e); } } } } private static SimpleDateFormat consoleDate = new SimpleDateFormat("HH:mm:ss"); private static String timeStamp(){ return "[" + (consoleDate.format(new Date(System.currentTimeMillis()))) + "]: "; } /** * Prints out an exception when it occurs. Only the stack * trace is printed to the log. But an occurance is shown * in both the console and the log. * @param e */ public static void printException(Exception e){ String message = timeStamp() + "Exception occurred. " + UnknownHostException.class.getName() + ": " + e.getMessage() + " --Please see log for stack trace System.err.println(message); //Convert stack trace into string and print to log StringWriter error = new StringWriter(); e.printStackTrace(new PrintWriter(error)); String stackTrace = error.toString(); log.writeLine(message + "\n" + stackTrace); } /** * Prints a line in the server and in the log. Time stamped */ public static void printRecord(String message){ System.out.println(timeStamp() + message); log.writeLine(message); } /** * Prints a line in the server. Time stamped */ public void println(String message){ System.out.println(timeStamp() + message); } /* public static void main(String[] args){ Config.getInstance().getCount(); Server.messageSlack("Because I can testify!", "general"); } */ }
package obvious.jung.data; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import edu.uci.ics.jung.graph.AbstractGraph; import edu.uci.ics.jung.graph.util.Pair; import obvious.ObviousRuntimeException; import obvious.data.Edge; import obvious.data.Network; import obvious.data.Node; import obvious.data.Schema; import obvious.data.Table; import obvious.data.event.NetworkListener; import obvious.impl.EdgeImpl; import obvious.impl.NodeImpl; import obvious.prefuse.PrefuseObviousTable; /** * Implementation of an Obvious Network based on Jung toolkit. * @author Pierre-Luc Hemery * */ public class JungObviousNetwork implements Network { /** * A Jung graph used for this obvious implementation. */ private edu.uci.ics.jung.graph.Graph<Node, Edge> jungGraph; /** * Collection of listeners. */ private Collection<NetworkListener> listeners = new ArrayList<NetworkListener>(); /** * Constructor from Jung Graph instance. * @param graph original Jung graph instance */ public JungObviousNetwork(edu.uci.ics.jung.graph.Graph<Node, Edge> graph) { this.jungGraph = graph; } /** * Constructor from Obvious Schema. * @param nodeSchema schema for the node Table * @param edgeSchema schema for the edge Table */ public JungObviousNetwork(Schema nodeSchema, Schema edgeSchema) { JungGraph graph = new JungGraph(nodeSchema, edgeSchema); this.jungGraph = graph; } /** * Constructor from Obvious Schema. * @param nodeSchema schema for the node Table * @param edgeSchema schema for the edge Table * @param source column name used in edge schema to identify source node * @param target column name used in edge schema to identify target node */ public JungObviousNetwork(Schema nodeSchema, Schema edgeSchema, String source, String target) { JungGraph graph = new JungGraph(nodeSchema, edgeSchema, source, target); this.jungGraph = graph; } /** * Constructor from Obvious Schema. * @param nodeSchema schema for the node Table * @param edgeSchema schema for the edge Table * @param node column name used in node schema to spot a node (can be null) * @param source column name used in edge schema to identify source node * @param target column name used in edge schema to identify target node */ public JungObviousNetwork(Schema nodeSchema, Schema edgeSchema, String node, String source, String target) { JungGraph graph = new JungGraph(nodeSchema, edgeSchema, node, source, target); this.jungGraph = graph; } /** * Adds a hyperedge. * @param edge to add * @param nodes concerned by addition * @param edgeType directed or undirected edge * @return true if added */ public boolean addEdge(Edge edge, Collection<? extends Node> nodes, obvious.data.Graph.EdgeType edgeType) { try { edu.uci.ics.jung.graph.util.EdgeType type = edu.uci.ics.jung.graph.util.EdgeType.UNDIRECTED; if (edgeType == obvious.data.Graph.EdgeType.DIRECTED) { type = edu.uci.ics.jung.graph.util.EdgeType.DIRECTED; } return this.jungGraph.addEdge(edge, nodes, type); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Convenience method for multigraphs. * @param edge edge to add * @param source source node * @param target target node * @param edgeType directed or undirected edge * @return true if added */ public boolean addEdge(Edge edge, Node source, Node target, obvious.data.Graph.EdgeType edgeType) { try { edu.uci.ics.jung.graph.util.EdgeType type = edu.uci.ics.jung.graph.util.EdgeType.UNDIRECTED; if (edgeType == obvious.data.Graph.EdgeType.DIRECTED) { type = edu.uci.ics.jung.graph.util.EdgeType.DIRECTED; } Pair<Node> nodes = new Pair<Node>(source, target); return this.jungGraph.addEdge(edge, nodes, type); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Adds a node. * @param node node to add * @return true if added */ public boolean addNode(Node node) { try { return this.jungGraph.addVertex(node); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Gets for two nodes the connecting edge. * @param v1 a node of the graph * @param v2 another node of the graph * @return connecting edge */ public Edge getConnectingEdge(Node v1, Node v2) { return this.jungGraph.findEdge(v1, v2); } /** * Gets connecting edges between two nodes. * @param v1 a node of the graph * @param v2 another node of the graph * @return collection of connecting edges */ public Collection<Edge> getConnectingEdges(Node v1, Node v2) { return this.jungGraph.findEdgeSet(v1, v2); } /** * Get the edge type. * @param edge an edge of the graph * @return directed or indirected {@link #EdgeType} */ public obvious.data.Graph.EdgeType getEdgeType(Edge edge) { edu.uci.ics.jung.graph.util.EdgeType type = jungGraph.getEdgeType(edge); if (type == edu.uci.ics.jung.graph.util.EdgeType.DIRECTED) { return obvious.data.Graph.EdgeType.DIRECTED; } else { return obvious.data.Graph.EdgeType.UNDIRECTED; } } /** * Gets the edges of the graph instance. * @return collection of edges */ public Collection<Edge> getEdges() { return this.jungGraph.getEdges(); } /** * Gets in-linking edges for a specific node. * @param node a node of the graph * @return collection of in-linking edges */ public Collection<Edge> getInEdges(Node node) { return this.jungGraph.getInEdges(node); } /** * Gets incident edges for a spotted node. * @param node a node of the graph * @return collection of incident edges */ public Collection<Edge> getIncidentEdges(Node node) { return this.jungGraph.getIncidentEdges(node); } /** * Gets incident nodes for a spotted edge. * @param edge an edge of the graph * @return collection of incident nodes */ public Collection<Node> getIncidentNodes(Edge edge) { return this.jungGraph.getIncidentVertices(edge); } /** * Gets the neighbors node. * @param node central node to determine the neighborhood * @return collection of nodes that are neighbors */ public Collection<Node> getNeighbors(Node node) { return this.jungGraph.getNeighbors(node); } /** * Returns a collection of all nodes of the graph. * @return all nodes of the graph */ public Collection<Node> getNodes() { return this.jungGraph.getVertices(); } /** * Get the opposite node for a couple (node,edge). * @param node spotted node * @param edge spotted edge * @return opposite node */ public Node getOpposite(Node node, Edge edge) { return this.jungGraph.getOpposite(node, edge); } /** * Gets out-linking edges for a specific node. * @param node a node of the graph * @return collection of out-linking edges */ public Collection<Edge> getOutEdges(Node node) { return this.jungGraph.getOutEdges(node); } /** * Get predecessors nodes for a specific node. * @param node spotted node * @return collection of nodes */ public Collection<Node> getPredecessors(Node node) { return this.jungGraph.getPredecessors(node); } /** * Gets the source of a directed edge. * @param directedEdge a directed edge of the graph * @return source node */ public Node getSource(Edge directedEdge) { return this.jungGraph.getSource(directedEdge); } /** * Get successor nodes. * @param node a node of the graph * @return collection of nodes */ public Collection<Node> getSuccessors(Node node) { return this.jungGraph.getSuccessors(node); } /** * Get the target of a directed edge. * @param directedEdge a directed edge of the graph * @return target node */ public Node getTarget(Edge directedEdge) { return this.jungGraph.getDest(directedEdge); } /** * Removes an edge. * @param edge edge to remove * @return true if removed */ public boolean removeEdge(Edge edge) { try { return this.jungGraph.removeEdge(edge); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Removes a node. * @param node node to remove * @return true if removed */ public boolean removeNode(Node node) { try { return this.jungGraph.removeVertex(node); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Returns the node table. * @return the node table */ public obvious.data.Table getNodeTable() { Table nodeTable = new PrefuseObviousTable( getNodes().iterator().next().getSchema()); for (Node node : this.getNodes()) { nodeTable.addRow(node); } return nodeTable; } /** * Returns the edge table. * @return the edge table */ public obvious.data.Table getEdgeTable() { Table edgeTable = new PrefuseObviousTable( getEdges().iterator().next().getSchema()); for (Edge edge : this.getEdges()) { edgeTable.addRow(edge); } return edgeTable; } /** * Simple implementation of Jung AbstractGraph. * Used as default Jung Graph implementation for Obvious Jung. * @author Pierre-Luc Hmery * */ protected static class JungGraph extends AbstractGraph<Node, Edge> { /** * Table of the nodes of the graph. */ protected Table nodeTable; /** * Table of the edges of the graph. */ protected Table edgeTable; /** * Map indicating the type of an edge. */ protected Map<Edge, edu.uci.ics.jung.graph.util.EdgeType> edgeTypeMap; /** * Column used to spot source node in edge table. */ private String sourceCol; /** * Column used to spot target node in edge table. */ private String targetCol; /** * Column used to spot a node in node table. */ private String nodeCol = null; /** * Name for the Source Node index in edgeSchema. */ public static final String SRCNODE = "SRCNODE"; /** * Name for the Target Node index in edgeSchema. */ public static final String DESTNODE = "DESTNODE"; /** * Constructor for Jung Graph. * @param nodeSchema schema for the nodeTable * @param edgeSchema schema for the edgeTable * @param source column name used in edge schema to identify source node * @param target column name used in edge schema to identify target node */ protected JungGraph(Schema nodeSchema, Schema edgeSchema, String source, String target) { this.nodeTable = new PrefuseObviousTable(nodeSchema); this.edgeTable = new PrefuseObviousTable(edgeSchema); this.sourceCol = source; this.targetCol = target; this.edgeTypeMap = new HashMap<Edge, edu.uci.ics.jung.graph.util.EdgeType>(); for (int i = 0; i < edgeTable.getRowCount(); i++) { this.edgeTypeMap.put(new EdgeImpl(edgeTable, i), getDefaultEdgeType()); } } /** * Constructor for Jung Graph. * @param nodeSchema schema for the nodeTable * @param edgeSchema schema for the edgeTable */ protected JungGraph(Schema nodeSchema, Schema edgeSchema) { this(nodeSchema, edgeSchema, SRCNODE, DESTNODE); } /** * Constructor from Obvious Schema. * @param nodeSchema schema for the node Table * @param edgeSchema schema for the edge Table * @param node column name used in node schema to spot a node (can be null) * @param source column name used in edge schema to identify source node * @param target column name used in edge schema to identify target node */ protected JungGraph(Schema nodeSchema, Schema edgeSchema, String node, String source, String target) { this(nodeSchema, edgeSchema, source, target); this.nodeCol = node; } @Override public boolean addEdge(Edge edge, Pair<? extends Node> nodes, edu.uci.ics.jung.graph.util.EdgeType type) { if (!containsVertex(nodes.getFirst()) || !containsVertex(nodes.getSecond())) { return false; } else { int r = edgeTable.addRow(); Object source = edge.get(sourceCol) != null ? edge.get(sourceCol) : nodes.getFirst().getRow(); Object target = edge.get(targetCol) != null ? edge.get(targetCol) : nodes.getSecond().getRow(); edgeTable.set(r, sourceCol, source); edgeTable.set(r, targetCol, target); for (int i = 0; i < edgeTable.getSchema().getColumnCount(); i++) { if (!edgeTable.getSchema().getColumnName(i).equals(sourceCol) && !edgeTable.getSchema().getColumnName(i).equals(targetCol)) { edgeTable.set(r, i, edge.get(edgeTable.getSchema().getColumnName(i))); } } setType(new EdgeImpl(edgeTable, r), type); return true; } } /** * Set the convenient type in edgeTypeMap. * @param edge an edge of the graph * @param type DIRECTED or UNDIRECTED */ protected void setType(Edge edge, edu.uci.ics.jung.graph.util.EdgeType type) { edgeTypeMap.put(edge, type); } /** * Gets the target node for a directed edge. * @param e of the graph * @return target node or null if the edge is undirected */ public Node getDest(Edge e) { if (!getEdgeType(e).equals(edu.uci.ics.jung.graph.util.EdgeType.DIRECTED) || !containsEdge(e)) { return null; } else { return new NodeImpl(nodeTable, e.getInt(targetCol)); } } /** * Gets the two endpoints for a given edge. * @param edge an edge of the graph * @return two endpoints nodes */ public Pair<Node> getEndpoints(Edge edge) { Pair<Node> endpoint = new Pair<Node>(new NodeImpl(nodeTable, edge.getInt(sourceCol)), new NodeImpl(nodeTable, edge.getInt(targetCol))); return endpoint; } /** * Gets all in-linking edges for a node of the graph. * @param node a node of the graph * @return collection of in-linking edges */ public Collection<Edge> getInEdges(Node node) { Collection<Edge> inEdges = new ArrayList<Edge>(); int nodeId = nodeCol != null ? node.getInt(nodeCol) : node.getRow(); for (Map.Entry<Edge, edu.uci.ics.jung.graph.util.EdgeType> e : edgeTypeMap.entrySet()) { if (e.getValue().equals( edu.uci.ics.jung.graph.util.EdgeType.DIRECTED)) { if (e.getKey().getInt(targetCol) == nodeId) { inEdges.add(e.getKey()); } } else { if (e.getKey().getInt(targetCol) == nodeId || e.getKey().getInt(sourceCol) == nodeId) { inEdges.add(e.getKey()); } } } return inEdges; } /** * Gets all out-linking edges for a node of the graph. * @param node a node of the graph * @return collection of out-linking edges */ public Collection<Edge> getOutEdges(Node node) { Collection<Edge> outEdges = new ArrayList<Edge>(); int nodeId = nodeCol != null ? node.getInt(nodeCol) : node.getRow(); for (Map.Entry<Edge, edu.uci.ics.jung.graph.util.EdgeType> e : edgeTypeMap.entrySet()) { int source = e.getKey().getInt(sourceCol); int target = e.getKey().getInt(targetCol); if (e.getValue().equals( edu.uci.ics.jung.graph.util.EdgeType.DIRECTED)) { if (source == nodeId) { outEdges.add(e.getKey()); } } else { if (target == nodeId || source == nodeId) { outEdges.add(e.getKey()); } } } return outEdges; } /** * Gets the predecessors of a node in the graph. * @param node a node of the graph * @return collection of predecessors */ public Collection<Node> getPredecessors(Node node) { Collection<Node> preds = new ArrayList<Node>(); // a node is predecessor of "our node", if for a directed edge, this node // is the source and "our node" the target. For an undirected edge, the // opposite of the node for this edge is a predecessor. for (Map.Entry<Edge, edu.uci.ics.jung.graph.util.EdgeType> e : edgeTypeMap.entrySet()) { if (e.getValue().equals( edu.uci.ics.jung.graph.util.EdgeType.DIRECTED) && node.getRow() == e.getKey().getInt(targetCol)) { preds.add(new NodeImpl(nodeTable, e.getKey().getInt(sourceCol))); } else if (e.getValue().equals( edu.uci.ics.jung.graph.util.EdgeType.UNDIRECTED) && (node.getRow() == e.getKey().getInt(sourceCol) || node.getRow() == e.getKey().getInt(targetCol))) { preds.add(new NodeImpl(nodeTable, getOpposite(node, e.getKey()).getRow())); } } return preds; } /** * Gets the source node for a directed edge. * @param e of the graph * @return source node or null if the edge is undirected */ public Node getSource(Edge e) { if (!getEdgeType(e).equals(edu.uci.ics.jung.graph.util.EdgeType.DIRECTED) || !containsEdge(e)) { return null; } else { return new NodeImpl(nodeTable, e.getInt(sourceCol)); } } /** * Gets the successors of a node in the graph. * @param node a node of the graph * @return collection of successors */ public Collection<Node> getSuccessors(Node node) { Collection<Node> succs = new ArrayList<Node>(); // a node is successor of "our node", if for a directed edge, this node // is the target and "our node" the source. For an undirected edge, the // opposite of the node for this edge is a successor. for (Map.Entry<Edge, edu.uci.ics.jung.graph.util.EdgeType> e : edgeTypeMap.entrySet()) { if (e.getValue().equals( edu.uci.ics.jung.graph.util.EdgeType.DIRECTED) && node.getRow() == e.getKey().getInt(sourceCol)) { succs.add(new NodeImpl(nodeTable, e.getKey().getInt(DESTNODE))); } else if (e.getValue().equals( edu.uci.ics.jung.graph.util.EdgeType.UNDIRECTED) && (node.getRow() == e.getKey().getInt(sourceCol) || node.getRow() == e.getKey().getInt(targetCol))) { succs.add(new NodeImpl(nodeTable, getOpposite(node, e.getKey()).getRow())); } } return succs; } /** * Checks if a node is the target of a specific edge. * @param node supposed target node * @param edge an edge of the graph * @return true if the node is target for this edge */ public boolean isDest(Node node, Edge edge) { return node.equals(this.getDest(edge)); } /** * Checks if a node is source of a specific edge. * @param node supposed source node * @param edge an edge of the graph * @return true if the node is source for this edge */ public boolean isSource(Node node, Edge edge) { return node.equals(this.getSource(edge)); } /** * Adds a node to the graph. * @param node node to add * @return true if added */ public boolean addVertex(Node node) { for (int i = 0; i < node.getSchema().getColumnCount(); i++) { if (!nodeTable.getSchema().hasColumn( node.getSchema().getColumnName(i))) { return false; } } nodeTable.addRow(); for (int i = 0; i < nodeTable.getSchema().getColumnCount(); i++) { nodeTable.set(nodeTable.getRowCount() - 1, node.getSchema().getColumnName(i), node.get(i)); } return true; } /** * Checks if a specific edge is in the graph. * @param edge an edge * @return true if the input edge is in the graph */ public boolean containsEdge(Edge edge) { for (int i = 0; i < edge.getSchema().getColumnCount(); i++) { if (i > edgeTable.getSchema().getColumnCount()) { // check schema size return false; } else if (!edgeTable.getSchema().hasColumn( edge.getSchema().getColumnName(i))) { // check column name return false; } } return edge.getRow() < edgeTable.getRowCount() && nodeTable.isValidRow(edge.getRow()); } /** * Checks if a specific node is in the graph. * @param node a node * @return true if the input node is in the graph */ public boolean containsVertex(Node node) { for (int i = 0; i < node.getSchema().getColumnCount(); i++) { if (i > nodeTable.getSchema().getColumnCount()) { // check schema size return false; } else if (!nodeTable.getSchema().hasColumn( node.getSchema().getColumnName(i))) { // check column name return false; } } return node.getRow() < nodeTable.getRowCount() && nodeTable.isValidRow(node.getRow()); } /** * Gets the default edgeType for the graph. * @return UNDIRECTED */ public edu.uci.ics.jung.graph.util.EdgeType getDefaultEdgeType() { // TODO Auto-generated method stub return edu.uci.ics.jung.graph.util.EdgeType.UNDIRECTED; } /** * Gets the number of edges in the graph. * @return number of edges */ public int getEdgeCount() { return getEdges().size(); } /** * Gets the number of edges of a specified type. * @param type type to match (directed or undirected) * @return number of edges of the specified type */ public int getEdgeCount(edu.uci.ics.jung.graph.util.EdgeType type) { return this.getEdges(type).size(); } /** * Gets the type of an edge. * @param edge an edge of the graph * @return the type of the edge (directed or undirected) */ public edu.uci.ics.jung.graph.util.EdgeType getEdgeType(Edge edge) { for (Entry<Edge, edu.uci.ics.jung.graph.util.EdgeType> e : edgeTypeMap.entrySet()) { if (e.getKey().equals(edge)) { return edgeTypeMap.get(e.getKey()); } } edgeTypeMap.put(edge, this.getDefaultEdgeType()); return edgeTypeMap.get(edge); } /** * Gets a collection of the edges of the graph. * @return collection of edges */ public Collection<Edge> getEdges() { Collection<Edge> edgeColl = new ArrayList<Edge>(); for (int i = 0; i < edgeTable.getRowCount(); i++) { if (this.edgeTable.isValidRow(i)) { edgeColl.add(new EdgeImpl(edgeTable, i)); } } return edgeColl; } /** * Gets edges of a specific type. * @param type type to match (directed or undirected) * @return edge of the specified type */ public Collection<Edge> getEdges( edu.uci.ics.jung.graph.util.EdgeType type) { Collection<Edge> edgeTypedColl = new ArrayList<Edge>(); for (Map.Entry<Edge, edu.uci.ics.jung.graph.util.EdgeType> e : edgeTypeMap.entrySet()) { if (e.getValue() == type) { edgeTypedColl.add(e.getKey()); } } return edgeTypedColl; } /** * Gets incident edges for a specific node. * @param node a node of the graph * @return a collection of edges */ public Collection<Edge> getIncidentEdges(Node node) { Collection<Edge> incidentEdge = new ArrayList<Edge>(); for (int i = 0; i < edgeTable.getRowCount(); i++) { if (edgeTable.getValue(i, sourceCol).equals(node.getRow()) || edgeTable.getValue(i, targetCol).equals(node.getRow())) { incidentEdge.add(new EdgeImpl(edgeTable, i)); } } return incidentEdge; } /** * Gets the neighbors for a given node. * @param node a node of the graph * @return collection of neighbors node */ public Collection<Node> getNeighbors(Node node) { Collection<Node> neighbors = new ArrayList<Node>(); for (int i = 0; i < edgeTable.getRowCount(); i++) { if (edgeTable.getValue(i, sourceCol).equals(node.getRow())) { neighbors.add(new NodeImpl(nodeTable, (Integer) edgeTable.getValue(i, targetCol))); } else if (edgeTable.getValue(i, targetCol).equals(node.getRow())) { neighbors.add(new NodeImpl(nodeTable, (Integer) edgeTable.getValue(i, sourceCol))); } } return neighbors; } /** * Gets the number of nodes in the graph. * @return number of nodes */ public int getVertexCount() { return getVertices().size(); } /** * Gets a collection of the nodes of the graph. * @return collection of nodes */ public Collection<Node> getVertices() { Collection<Node> nodeColl = new ArrayList<Node>(); for (int i = 0; i < nodeTable.getRowCount(); i++) { if (this.nodeTable.isValidRow(i)) { nodeColl.add(new NodeImpl(nodeTable, i)); } } return nodeColl; } /** * Removes an edge from the graph. * @param edge an edge of the graph * @return true if removed */ public boolean removeEdge(Edge edge) { if (!this.containsEdge(edge)) { return false; } else { edgeTable.removeRow(edge.getRow()); return true; } } /** * Removes a node from the graph. * @param node a node of the graph * @return true if removed */ public boolean removeVertex(Node node) { if (!this.containsVertex(node)) { return false; } else { nodeTable.removeRow(node.getRow()); // removing the associated edge for (int i = 0; i < edgeTable.getRowCount(); i++) { if (edgeTable.getValue(i, sourceCol).equals(node.getRow()) || edgeTable.getValue(i, targetCol).equals(node.getRow())) { edgeTable.removeRow(i); } } return true; } } /** * Returns the node table. * @return the node table */ public obvious.data.Table getNodeTable() { return nodeTable; } /** * Returns the edge table. * @return the edge table */ public obvious.data.Table getEdgeTable() { return edgeTable; } } /** * Return the underlying implementation. * @param type targeted class * @return Cytoscape graph instance or null */ public Object getUnderlyingImpl(Class<?> type) { return null; } public Collection<NetworkListener> getNetworkListeners() { return listeners; } public void removeNetworkListener(NetworkListener l) { listeners.remove(l); } public void addNetworkListener(NetworkListener l) { listeners.add(l); } }
import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; public class GamePanel extends JPanel implements KeyListener { private boolean gameRunning = true; private Hextile[][] hextiles; private double fps; private MouseStatus mouse; private StarchildAbilities abilities; private int difficulty; private static Battle_Player player; private static ProjectileHandler projectiles; private static EnemyHandler enemies; private static SpawnAndCast spawncast; private static PlayerSpells spells; public GamePanel(int health, int cdr, int attack, int difficulty) throws IOException { setFocusable(true); addKeyListener(this); mouse = new MouseStatus(); addMouseListener(mouse); addMouseMotionListener(mouse); // Fills the grid up hextiles = Hextile.fillHexGrid(1); Hextile.createBigContainHex(hextiles); // debug code for saving the grid data for (int i = 0; i < hextiles.length; i++) { for (int j = 0; j < hextiles[i].length; j++) { if (hextiles[i][j] == null) { System.out.print("X"); } else { System.out.print("O"); } } System.out.println(); } player = new Battle_Player(health); abilities = new StarchildAbilities(cdr); projectiles = new ProjectileHandler(); enemies = new EnemyHandler(difficulty, hextiles); spawncast = new SpawnAndCast(); spells = new PlayerSpells(attack); } public static boolean winCheck() { if (player.getHealth() <= 0) { return true; } return false; } // The main game loop capped at ~120 frames/second (variable timestep loop) public void runGameLoop() { long lastTime = System.nanoTime(), fpsTimer = 0, currentTime, updateLength; final int optimalFPS = 60; final long optimalDelta = 1000000000 / optimalFPS; double delta; int fpsCnt = 0; while (gameRunning) { currentTime = System.nanoTime(); updateLength = currentTime - lastTime; lastTime = currentTime; delta = updateLength / 1000000000.0; fpsTimer += updateLength; fpsCnt++; if (fpsTimer >= 1000000000) { fps = fpsCnt; fpsTimer = 0; fpsCnt = 0; } // delta is change in time in seconds updateGame(delta); repaint(); // limits the framerate try { Thread.sleep((optimalDelta - (lastTime - System.nanoTime())) / 1000000); } catch (Exception e) { e.printStackTrace(); } } } // Updates all the units in the game, where delta is change in time private void updateGame(double delta) { mouse.updateMouseTile(hextiles); player.update(mouse, hextiles, delta); mouse.updateClicks(delta); abilities.updateCD(delta); projectiles.update(delta, Hextile.getBigContainHex(), hextiles); spawncast.update(delta); spells.update(delta); enemies.update(delta); winCheck(); } // Paints everything public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(new Color(51, 51, 51)); g2d.fillRect(0, 0, 1280, 720); player.drawhealth(g2d, player.getMaxHealth(), player.getHealth()); g2d.setColor(new Color(51, 51, 51)); Hextile.fillBigContainHex(g2d); g2d.setColor(Color.gray); // Draws all the tiles in the grid for (int i = 0; i < hextiles.length; i++) { for (int j = 0; j < hextiles[i].length; j++) { if (hextiles[i][j] != null) { hextiles[i][j].draw(g2d); // Draws the player indicator if (hextiles[i][j].getQ() == player.getQ() && hextiles[i][j].getR() == player.getR()) { hextiles[i][j].drawPlayerOcc(g2d); } int[] tArr = new int[2]; tArr[0] = hextiles[i][j].getQ(); tArr[1] = hextiles[i][j].getR(); // Draws the casting indicators g2d.setColor(Color.white); for (int k = 1; k < 4; k++) { if (search2DArray(spawncast.getList(k), tArr)) { hextiles[i][j].drawCasting(g2d, spawncast.getProgress(k)); } } // Drawing the enemy spawning indicators for (int k = 1; k < 4; k++) { if (search2DArray(spawncast.getSpawnList(), tArr)) { hextiles[i][j].drawSpawning(g2d, spawncast.getSpawningProgress()); } } // Draws the player projectiles g2d.setColor(Color.gray); if (search2DArray(projectiles.getPShots(), tArr)) { hextiles[i][j].drawPShot(g2d, 0); } // Drawing the spell animations for (int k = 1; k < 4; k++) { if (search2DArray(spells.getList(k), tArr)) { hextiles[i][j].drawPShot(g2d, k); } } // TODO Draws the ability area indicators if (search2DArray(abilities.getIndicator(), tArr)) { hextiles[i][j].drawIndicatorOcc(g2d); } g2d.setColor(Color.gray); } } } abilities.drawIndicator(g2d, hextiles, player.getQ(), player.getR(), mouse.getQ(), mouse.getR(), player.getX(), player.getY(), mouse.getMx(), mouse.getMy()); g2d.setColor(Color.white); Hextile.drawBigContainHex(g2d); enemies.draw(g2d); projectiles.draw(g2d); player.draw(g2d); g2d.setColor(Color.white); mouse.drawClicks(g2d); // Draws the frames per second g2d.drawString("FPS: " + fps, 2, 12); abilities.drawCooldown(g2d); } public boolean search2DArray(int[][] arr2d, int[] arr) { if (arr2d == null || arr.length == 0) { return false; } for (int i = 0; i < arr2d.length; i++) { if (arr2d[i][0] == arr[0] && arr2d[i][1] == arr[1]) return true; } return false; } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub switch (e.getKeyCode()) { case KeyEvent.VK_Q: abilities.setFoc(0); break; case KeyEvent.VK_W: abilities.setFoc(1); break; case KeyEvent.VK_E: abilities.setFoc(2); break; case KeyEvent.VK_R: abilities.setFoc(3); break; } } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub switch (e.getKeyCode()) { case KeyEvent.VK_Q: abilities.setFoc(0); break; case KeyEvent.VK_W: abilities.setFoc(1); break; case KeyEvent.VK_E: abilities.setFoc(2); break; case KeyEvent.VK_R: abilities.setFoc(3); break; } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }
package algorithms.compGeometry; import algorithms.imageProcessing.MiscellaneousCurveHelper; import algorithms.misc.Misc; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * * @author nichole */ public class ButterflySectionFinder { /** * Find sections of the closed curve that are two pixels wide and separate * loops in the curve: * <pre> * for example: # # * # # # # # * # # # # # * # # # # # # # # * </pre> * These sections are thinned to width of '1' by the line thinner, * so need to be restored afterwards or prevented from being removed. * @param closedCurve * @return list of points that are part of the 2 pixel width patterns in * a curve where the curve closes, but is still connected. */ public List<Routes> findButterflySections(PairIntArray closedCurve) { Set<PairInt> points = Misc.convert(closedCurve); List<Routes> output = new ArrayList<Routes>(); List<Routes> sections = findButterflySectionsLarge(closedCurve, points); if (sections != null && !sections.isEmpty()) { output.addAll(sections); } List<Routes> sectionsSmall = findButterflySectionsSmall(closedCurve, points); if (sectionsSmall != null && !sectionsSmall.isEmpty()) { output.addAll(sectionsSmall); } setNullEndpoints(output); return output; } /** * Find sections of the closed curve that are two pixels wide and separate * loops in the curve: * <pre> * for example: # # * # # # # # * # # # # # * # # # # # # # # * </pre> * These sections are thinned to width of '1' by the line thinner, * so need to be restored afterwards or prevented from being removed. * @param closedCurve * @param points * @return list of points that are part of the 2 pixel width patterns in * a curve where the curve closes, but is still connected. */ protected List<Routes> findButterflySectionsLarge(PairIntArray closedCurve, Set<PairInt> points) { MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); List<LinkedList<Segment>> candidateSections = new ArrayList<LinkedList<Segment>>(); LinkedList<Segment> currentList = null; for (int i = 0; i < closedCurve.getN(); ++i) { int x = closedCurve.getX(i); int y = closedCurve.getY(i); Set<PairInt> neighbors = curveHelper.findNeighbors(x, y, points); // 3 for large diagonal patterns, else 4 or 5 if ((neighbors.size() < 3) || (neighbors.size() > 5)) { if (currentList != null) { candidateSections.add(currentList); currentList = null; } continue; } Segment segment = checkSegmentPatterns(x, y, points, neighbors); // cannot have a segment touching the image boundaries, though // that may need to change if ((segment != null) && isOnImageBoundaries(segment)) { segment = null; } if (segment == null) { if (currentList != null) { candidateSections.add(currentList); currentList = null; } continue; } if (currentList == null) { currentList = new LinkedList<Segment>(); } currentList.add(segment); } if (currentList != null) { candidateSections.add(currentList); } if (candidateSections.isEmpty()) { return null; } mergeIfAdjacent(candidateSections); List<Routes> output = new ArrayList<Routes>(); // -- scan for endpoints -- for (LinkedList<Segment> section : candidateSections) { Routes routes = checkForAdjacentEndpoints(points, section); if (routes == null) { continue; } output.add(routes); } return output; /* endpoints for vert: # # # . = - . - - . - - . or - - . or # . # # endpoints for horiz: - - - - # - # # - - # # - # . . . . . . endpoints for diag: - # - # - # - . - - . # - . # . . # . . - . . . . . The sections of line which are 2 pixels wide and 1 further from the endpoint have 3 non-point neighbors each and 5 point set neighbors An area limit further constrains the geometry. For sections matching the patterns below, could consider storing the pattern for each pix as 'v', 'h', or 'd'...not an apparent use for that yet though. Segment patterns between endpoints: 4 - - - - 3 . # # . 2 . # # . 1 - - - - 0 0 1 2 3 4 4 - . . - 3 - # # - 2 - # # - 1 - . . - 0 0 1 2 3 4 # # - - 3 - # # - - 2 - - # # 1 - - - - - 0 0 1 2 3 4 5 data structures: linked lists of found pattern points as segments with specialization of each segment as VertSegment, HorizSegment, UUdiagsegment, ULdiagsegment Scan the line, if a point fits one of the 4 segment patterns (4th is diag transformed by x=-x), add it to a group and add the remaining pts fitting the pattern to a stack -- traverse the stack adding contiguous points to the group that fit the pattern. -- note where the first point in the pattern started, because when there are no more contiguous pattern matching points, the scan will continue at the next point after that first, but will skip those already added to a group. When the scan for groups has finished, for each group, need to apply the above endpoint patterns to see if the candidate segment is surrounded by 2 endpoints. test all candidate group points as adjacent to potential endpoints. When a match is found, have to exclude all of the matching pattern from the oppossing endpoint tests. This is the smallest pattern which will match that suggestion: - - - - # # @ # # - - # @ # - # - - - # The '@'s are the candidate group points. The #'s are points matching endoint patterns. The found endpoints for one end, the left for example, would be excluded from a search for matching to the other endpoints. Note that this pattern and variants of it as very short sections and endpoints should be scanned after the above to find the shortest butterfly segments. - - # # @ # - - # @ - # - - # # # # # # # # # # # # For each segment group which has 2 matching endpoints, those should be stored as butterfly sections in a set. Each one of those should be passed back in a list as the return of this method. runtime complexity is linear in the number of points in the given closed curve. */ } protected List<Routes> findButterflySectionsSmall(PairIntArray closedCurve, Set<PairInt> points) { List<Routes> routesList = findButterflySectionsSmallZigZag(closedCurve, points); if (routesList != null && !routesList.isEmpty()) { return routesList; } routesList = findButterflySectionsSmallDiagZigZag(closedCurve, points); return routesList; } protected List<Routes> findButterflySectionsSmallZigZag(PairIntArray closedCurve, Set<PairInt> points) { MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); List<Routes> output = new ArrayList<Routes>(); for (int i = 0; i < closedCurve.getN(); ++i) { int x = closedCurve.getX(i); int y = closedCurve.getY(i); Set<PairInt> neighbors = curveHelper.findNeighbors(x, y, points); // scanning for segments if (neighbors.size() != 3) { continue; } Segment segment = checkZigZagSegmentPattern(x, y, points); if (segment == null) { segment = checkZigZag2SegmentPattern(x, y, points); if (segment == null) { continue; } } /* Each of the 4 segment points needs at least one neighbor that is not one of the 4 points in the zig zap and all of their neighbors cannot be adjacent to any of the other neighbors. */ Set<PairInt> endPoints = checkForZigZagEndPoints(points, segment); if (endPoints == null || endPoints.isEmpty()) { continue; } ZigZagSegmentRoutes routes = parseZigZag(segment, endPoints); output.add(routes); } return output; } protected List<Routes> findButterflySectionsSmallDiagZigZag(PairIntArray closedCurve, Set<PairInt> points) { MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); List<Routes> output = new ArrayList<Routes>(); for (int i = 0; i < closedCurve.getN(); ++i) { int x = closedCurve.getX(i); int y = closedCurve.getY(i); Set<PairInt> neighbors = curveHelper.findNeighbors(x, y, points); //TODO: one point in this pattern has 3 neigbhors, so may need to change this // scanning for segments if (neighbors.size() != 4) { continue; } Segment segment = checkDiagZigZagSegmentPattern(x, y, points); if (segment == null) { segment = checkDiagZigZag2SegmentPattern(x, y, points); if (segment == null) { continue; } } /* Each of the 4 segment points needs at least one neighbor that is not one of the 4 points in the zig zap and all of their neighbors cannot be adjacent to any of the other neighbors. */ Set<PairInt> endPoints = checkForZigZagEndPoints(points, segment); if (endPoints == null || endPoints.isEmpty()) { continue; } ZigZagSegmentRoutes routes = parseDiagZigZag(segment, endPoints); output.add(routes); } return output; } private Segment checkSegmentPatterns(final int x, final int y, Set<PairInt> points, Set<PairInt> neighbors) { boolean useVert = true; Segment segment = checkVertHorizSegmentPattern(x, y, neighbors, useVert); if (segment != null) { return segment; } useVert = false; segment = checkVertHorizSegmentPattern(x, y, neighbors, useVert); if (segment != null) { return segment; } segment = checkDiagSegmentPattern(x, y, points, neighbors); if (segment != null) { return segment; } return null; } private void swapYDirection(Pattern pattern) { for (PairInt p : pattern.zeroes) { p.setY(-1 * p.getY()); } for (PairInt p : pattern.ones) { p.setY(-1 * p.getY()); } } private void swapXDirection(Pattern pattern) { for (PairInt p : pattern.zeroes) { p.setX(-1 * p.getX()); } for (PairInt p : pattern.ones) { p.setX(-1 * p.getX()); } } private Routes checkForAdjacentEndpoints(Set<PairInt> points, LinkedList<Segment> section) { // the list of segments was built from a closed curve Routes routes = null; for (int i = 0; i < 2; ++i) { Segment firstOrLastSegment = (i == 0) ? section.getFirst() : section.getLast(); if (firstOrLastSegment instanceof VertSegment) { boolean useVertical = true; routes = findEndPointsVertHorizPatterns(points, routes, firstOrLastSegment, useVertical); } else if (firstOrLastSegment instanceof HorizSegment) { boolean useVertical = false; routes = findEndPointsVertHorizPatterns(points, routes, firstOrLastSegment, useVertical); } else if (firstOrLastSegment instanceof DiagSegment) { routes = findEndPointsDiagPatterns(points, routes, (DiagSegment)firstOrLastSegment); } if (routes == null) { return routes; } if ((i == 0) && section.size() > 1) { int added = 0; for (int ii = 1; ii < section.size(); ++ii) { Segment segment = section.get(ii); // add node to routes int didAdd = addSegmentToRoutes(routes, segment); added = added | didAdd; } if (!((added == 1) && (routes.ep0 == null || routes.ep0End == null || routes.ep1 == null || routes.ep1End == null))) { break; } } } return routes; } private Routes findEndPointsVertHorizPatterns(Set<PairInt> points, Routes routes, Segment segment, boolean useVert) { int x0 = segment.p0.getX(); int y0 = segment.p0.getY(); for (int i = 0; i < 6; ++i) { Pattern pattern; switch(i) { case 0: pattern = getEndPointsVertPattern1S(); break; case 1: pattern = getEndPointsVertPattern1Opp(); break; case 2: pattern = getEndPointsVertPattern2S(); break; case 3: pattern = getEndPointsVertPattern2Opp(); break; case 4: pattern = getEndPointsVertPattern3S(); break; case 5: pattern = getEndPointsVertPattern3Opp(); break; default: return null; } if (!useVert) { rotatePattern(pattern, -0.5*Math.PI); } boolean found = true; for (PairInt p : pattern.zeroes) { PairInt p2 = new PairInt(x0 + p.getX(), y0 + p.getY()); if (points.contains(p2)) { found = false; break; } } if (found) { Set<PairInt> endPoints = new HashSet<PairInt>(); for (PairInt p : pattern.ones) { PairInt p2 = new PairInt(x0 + p.getX(), y0 + p.getY()); if (segment.contains(p2)) { continue; } if (!points.contains(p2)) { found = false; break; } endPoints.add(p2); } if (found) { if (routes == null) { routes = createRoute(segment, x0, y0); } if ((i & 1) == 0) { addEndpointsForHorizVertPatternForward(x0, y0, pattern, routes, endPoints, useVert); } else { addEndpointsForHorizVertPatternOppos(x0, y0, pattern, routes, endPoints, useVert); } break; } } } return routes; } /* private Pattern getEndPointsVertPattern1() { // the pattern returned is relative to //position '0', just like the other patterns. //searching for .'s and #'s // -2 // - 2 1 - -1 // - 3 0 - 0 // - . . - 1 // # - # 2 // - 3 // -2 -1 0 1 Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); // '.' intermediate points pattern.ones.add(new PairInt(-1, 1)); pattern.ones.add(new PairInt(0, 1)); // '#' end points PairInt t1 = new PairInt(-1, 2); pattern.ones.add(t1); PairInt t0 = new PairInt(1, 2); pattern.ones.add(t0); pattern.ep0 = t0; pattern.ones.add(t1); pattern.ep1 = t1; pattern.zeroes.add(new PairInt(-2, 1)); pattern.zeroes.add(new PairInt(1, 1)); pattern.zeroes.add(new PairInt(0, 2)); pattern.zeroes.add(new PairInt(0, 3)); return pattern; } */ private Pattern getEndPointsVertPattern1S() { /* the pattern returned is relative to position '0', just like the other patterns. searching for .'s and #'s -2 - 2 1 - -1 - 3 0 - 0 # - # 1 - 2 -2 -1 0 1 */ Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); // '#' end points PairInt t1 = new PairInt(-1, 1); pattern.ones.add(t1); PairInt t0 = new PairInt(1, 1); pattern.ones.add(t0); pattern.ep0 = t0; pattern.ones.add(t1); pattern.ep1 = t1; pattern.zeroes.add(new PairInt(-2, -1)); pattern.zeroes.add(new PairInt(-2, 0)); pattern.zeroes.add(new PairInt(0, 2)); pattern.zeroes.add(new PairInt(0, 1)); pattern.zeroes.add(new PairInt(1, 0)); pattern.zeroes.add(new PairInt(1, -1)); return pattern; } private Pattern getEndPointsVertPattern1Opp() { /* the pattern returned is relative to position '0', just like the other patterns. R1 R0 /|\ | | \|/ - -3 # - # -2 - 2 1 - -1 3 0 0 -2 -1 0 1 */ Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); PairInt t1 = new PairInt(-1, -2); pattern.ones.add(t1); pattern.ep1 = t1; PairInt t0 = new PairInt(1, -2); pattern.ones.add(t0); pattern.ep0 = t0; pattern.zeroes.add(new PairInt(-2, -1)); pattern.zeroes.add(new PairInt(0, -2)); pattern.zeroes.add(new PairInt(0, -3)); pattern.zeroes.add(new PairInt(1, -1)); return pattern; } /* private Pattern getEndPointsVertPattern2() { // the pattern returned is relative to //position '0', just like the other patterns. //searching for .'s and #'s // -2 // - 2 1 - -1 // - 3 0 - 0 // - . . - 1 // # - - # 2 // - - 3 // -2 -1 0 1 Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); // '.' intermediate points pattern.ones.add(new PairInt(-1, 1)); pattern.ones.add(new PairInt(0, 1)); // '#' end points PairInt t1 = new PairInt(-2, 2); pattern.ones.add(t1); PairInt t0 = new PairInt(1, 2); pattern.ones.add(t0); pattern.ep1 = t1; pattern.ep0 = t0; pattern.zeroes.add(new PairInt(-2, 1)); pattern.zeroes.add(new PairInt(1, 1)); pattern.zeroes.add(new PairInt(-1, 2)); pattern.zeroes.add(new PairInt(-1, 3)); pattern.zeroes.add(new PairInt(0, 2)); pattern.zeroes.add(new PairInt(0, 3)); return pattern; } */ private Pattern getEndPointsVertPattern2S() { /* the pattern returned is relative to position '0', just like the other patterns. searching for .'s and #'s -2 2 1 -1 - 3 0 - 0 # - - # 1 - - 2 -2 -1 0 1 */ Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); // '#' end points PairInt t1 = new PairInt(-2, 1); pattern.ones.add(t1); PairInt t0 = new PairInt(1, 1); pattern.ones.add(t0); pattern.ep1 = t1; pattern.ep0 = t0; pattern.zeroes.add(new PairInt(-2, 0)); pattern.zeroes.add(new PairInt(-1, 2)); pattern.zeroes.add(new PairInt(-1, 1)); pattern.zeroes.add(new PairInt(0, 2)); pattern.zeroes.add(new PairInt(0, 1)); pattern.zeroes.add(new PairInt(1, 0)); return pattern; } private Pattern getEndPointsVertPattern2Opp() { /* the pattern returned is relative to position '0', just like the other patterns. R1 R0 /|\ | | \|/ - - -3 # - - # -2 - 2 1 - -1 3 0 0 -2 -1 0 1 */ Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); // '#' end points PairInt t1 = new PairInt(-2, -2); PairInt t0 = new PairInt(1, -2); pattern.ones.add(t1); pattern.ones.add(t0); pattern.ep0 = t0; pattern.ep1 = t1; pattern.zeroes.add(new PairInt(-2, -1)); pattern.zeroes.add(new PairInt(-1, -2)); pattern.zeroes.add(new PairInt(-1, -3)); pattern.zeroes.add(new PairInt(0, -2)); pattern.zeroes.add(new PairInt(0, -3)); pattern.zeroes.add(new PairInt(1, -1)); return pattern; } /* private Pattern getEndPointsVertPattern3() { // the pattern returned is relative to //position '0', just like the other patterns. //searching for .'s and #'s // -2 // - 2 1 - -1 // - 3 0 - 0 // - . . - 1 // # - # 2 // - 3 // -2 -1 0 1 Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); pattern.zeroes.add(new PairInt(-2, 1)); pattern.zeroes.add(new PairInt(-1, 2)); pattern.zeroes.add(new PairInt(-1, 3)); pattern.zeroes.add(new PairInt(1, 1)); // '.' intermediate points pattern.ones.add(new PairInt(-1, 1)); pattern.ones.add(new PairInt(0, 1)); // '#' end points PairInt t1 = new PairInt(-2, 2); pattern.ones.add(t1); PairInt t0 = new PairInt(0, 2); pattern.ones.add(t0); pattern.ep1 = t1; pattern.ep0 = t0; return pattern; } */ private Pattern getEndPointsVertPattern3S() { /* the pattern returned is relative to position '0', just like the other patterns. searching for .'s and #'s -2 - 2 1 - -1 - 3 0 - 0 # - # 1 - 2 -2 -1 0 1 */ Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); pattern.zeroes.add(new PairInt(-2, -1)); pattern.zeroes.add(new PairInt(-2, 0)); pattern.zeroes.add(new PairInt(-1, 2)); pattern.zeroes.add(new PairInt(-1, 1)); pattern.zeroes.add(new PairInt(1, 0)); pattern.zeroes.add(new PairInt(1, -1)); // '#' end points PairInt t1 = new PairInt(-2, 1); pattern.ones.add(t1); PairInt t0 = new PairInt(0, 1); pattern.ones.add(t0); pattern.ep1 = t1; pattern.ep0 = t0; return pattern; } private Pattern getEndPointsVertPattern3Opp() { /* the pattern returned is relative to position '0', just like the other patterns. R1 R0 /|\ | | \|/ - -3 # - # -2 - 2 1 - -1 3 0 0 -2 -1 0 1 */ Pattern pattern = new Pattern(); pattern.ones = new HashSet<PairInt>(); pattern.zeroes = new HashSet<PairInt>(); // '#' end points PairInt t1 = new PairInt(-2, -2); PairInt t0 = new PairInt(0, -2); pattern.ones.add(t1); pattern.ones.add(t0); pattern.ep0 = t0; pattern.ep1 = t1; pattern.zeroes.add(new PairInt(-2, -1)); pattern.zeroes.add(new PairInt(-1, -2)); pattern.zeroes.add(new PairInt(-1, -3)); pattern.zeroes.add(new PairInt(1, -1)); return pattern; } private Routes findEndPointsDiagPatterns(Set<PairInt> points, Routes routes, DiagSegment segment) { int x0 = segment.p0.getX(); int y0 = segment.p0.getY(); if (segment instanceof ULDiagSegment) { // returns top endpoint of '2', then '1' PairInt[] endPoints = findULDiagTopEndpoints(points, (ULDiagSegment)segment); if (endPoints != null) { if (routes == null) { routes = createRoute(segment, x0, y0); } routes.route1.add(endPoints[0]); routes.ep1End = endPoints[0]; routes.ep0 = endPoints[1]; LinkedHashSet<PairInt> tmp0 = new LinkedHashSet<PairInt>(); tmp0.add(endPoints[1]); tmp0.addAll(routes.route0); routes.route0 = tmp0; return routes; } // returns bottom endpoint of '3', then '0' endPoints = findULDiagBottomEndpoints(points, (ULDiagSegment)segment); if (endPoints != null) { if (routes == null) { routes = createRoute(segment, x0, y0); } routes.route0.add(endPoints[1]); routes.ep0End = endPoints[1]; routes.ep1 = endPoints[0]; LinkedHashSet<PairInt> tmp1 = new LinkedHashSet<PairInt>(); tmp1.add(endPoints[0]); tmp1.addAll(routes.route1); routes.route1 = tmp1; return routes; } return routes; } // else is instance of UUDiagSegment // returns top endpoint of '2', then '1' PairInt[] endPoints = findUUDiagTopEndpoints(points, (UUDiagSegment)segment); if (endPoints != null) { if (routes == null) { routes = createRoute(segment, x0, y0); } routes.route1.add(endPoints[0]); routes.ep1End = endPoints[0]; routes.ep0 = endPoints[1]; LinkedHashSet<PairInt> tmp0 = new LinkedHashSet<PairInt>(); tmp0.add(endPoints[1]); tmp0.addAll(routes.route0); routes.route0 = tmp0; return routes; } // returns bottom endpoint of '3', then '0' endPoints = findUUDiagBottomEndpoints(points, (UUDiagSegment)segment); if (endPoints != null) { if (routes == null) { routes = createRoute(segment, x0, y0); } routes.route0.add(endPoints[1]); routes.ep0End = endPoints[1]; routes.ep1 = endPoints[0]; LinkedHashSet<PairInt> tmp1 = new LinkedHashSet<PairInt>(); tmp1.add(endPoints[0]); tmp1.addAll(routes.route1); routes.route1 = tmp1; return routes; } return routes; } private Set<PairInt> checkForZigZagEndPoints(Set<PairInt> points, Segment segment) { /*Each of the 4 needs at least one neighbor that is not one of the 4 points in the zig zap and all of their neighbors cannot be adjacent to any of the other neighbors.*/ MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); Set<Integer> indexesWithMoreThanOneNeighbor = new HashSet<Integer>(); List<Set<PairInt>> listOfNeighbors = new ArrayList<Set<PairInt>>(); Set<PairInt> segmentPoints = new HashSet<PairInt>(); segmentPoints.add(segment.p0); segmentPoints.add(segment.p1); segmentPoints.add(segment.p2); segmentPoints.add(segment.p3); for (int i = 0; i < 4; ++i) { PairInt p = null; switch(i) { case 0: p = segment.p0; break; case 1: p = segment.p1; break; case 2: p = segment.p2; break; default: p = segment.p3; break; } Set<PairInt> neighbors = curveHelper.findNeighbors(p.getX(), p.getY(), points); neighbors.removeAll(segmentPoints); if (!((neighbors.size() == 1) || (neighbors.size() == 2))) { return null; } if (neighbors.size() > 1) { indexesWithMoreThanOneNeighbor.add( Integer.valueOf(listOfNeighbors.size())); } listOfNeighbors.add(neighbors); } /* for this kind of junction, some points share a neighbor. need to reduce the neighbor lists to unique members */ for (Integer index : indexesWithMoreThanOneNeighbor) { int idx = index.intValue(); Set<PairInt> neighborSet = listOfNeighbors.get(idx); for (int i = 0; i < listOfNeighbors.size(); ++i) { Integer index2 = Integer.valueOf(i); if (indexesWithMoreThanOneNeighbor.contains(index2)) { continue; } PairInt p2 = listOfNeighbors.get(index2.intValue()).iterator().next(); neighborSet.remove(p2); } } // assert that each in list has no members adjacent to any other members // TODO: could use a data structure that uses spatial indexing to make // this faster, but there are not very many points per 4 sets to compare... for (int i = 0; i < listOfNeighbors.size(); ++i) { Set<PairInt> setI = listOfNeighbors.get(i); for (PairInt pI : setI) { for (int j = (i + 1); j < listOfNeighbors.size(); ++j) { Set<PairInt> setJ = listOfNeighbors.get(j); for (PairInt pJ : setJ) { if (areAdjacent(pI, pJ)) { return null; } } } } } // if arrive here, all neighbor sets have at least one point and none // are adjacent to points in a different set. // if there are more than one per set, we only want to keep the // closest to make a clear route with. // TODO: revisit this decision w/ further testing Set<PairInt> output = new HashSet<PairInt>(); for (int i = 0; i < listOfNeighbors.size(); ++i) { Set<PairInt> set = listOfNeighbors.get(i); if (set.size() > 0) { PairInt p = null; switch(i) { case 0: p = segment.p0; break; case 1: p = segment.p1; break; case 2: p = segment.p2; break; default: p = segment.p3; break; } int minDistSq = Integer.MAX_VALUE; PairInt minDistP = null; for (PairInt p2 : set) { int distSq = distSq(p, p2); if (distSq < minDistSq) { minDistSq = distSq; minDistP = p2; } } set.clear(); set.add(minDistP); } output.addAll(set); } return output; } private boolean areAdjacent(PairInt p0, PairInt p1) { int diffX = Math.abs(p0.getX() - p1.getX()); int diffY = Math.abs(p0.getY() - p1.getY()); if ((diffX < 2) && (diffY < 2)) { return true; } return false; } protected void rotatePattern(Pattern pattern, double theta) { double sine = Math.sin(theta); double cosine = Math.cos(theta); for (PairInt p : pattern.zeroes) { int x = p.getX(); int y = p.getY(); int xt = (int)Math.round(((x*cosine) + (y*sine))); int yt = (int)Math.round(((-x*sine) + (y*cosine))); p.setX(xt); p.setY(yt); } for (PairInt p : pattern.ones) { int x = p.getX(); int y = p.getY(); int xt = (int)Math.round(((x*cosine) + (y*sine))); int yt = (int)Math.round(((-x*sine) + (y*cosine))); p.setX(xt); p.setY(yt); } } private Routes createRoute(Segment segment, int x0, int y0) { /* VertSegment R1 R0 /|\ | | | | \|/ . . -2 - 2 1 - -1 - 3 0 - 0 . . 1 -2 -1 0 1 HorizPattern - - - -2 R1--> . 3 2 -1 -->R1 ends . 0 1 0 R0<-- - - - 1 <--R0 starts -1 0 1 UUDiagSegment ULDiagSegment - - -2 2 -2 - 2 1 - - -1 3 1 -1 - - 3 0 - 0 0 0 - - 1 1 -3 -2 -1 0 1 -1 0 1 2 E0 is '1', and route0 E0 is '1', and route0 continues with continues with point '0' point '0' E1 is '3', and route1 E1 is '3', and route1 continues with '2' continues with '2' */ if (segment instanceof VertSegment) { Routes routes = new Routes(); assert(segment.p1.equals(new PairInt(x0, y0 - 1))); assert(segment.p2.equals(new PairInt(x0 - 1, y0 - 1))); assert(segment.p3.equals(new PairInt(x0 - 1, y0))); routes.route0.add(segment.p1); routes.route0.add(segment.p0); routes.route1.add(segment.p3); routes.route1.add(segment.p2); return routes; } else if (segment instanceof HorizSegment) { Routes routes = new Routes(); assert(segment.p1.equals(new PairInt(x0 + 1, y0))); assert(segment.p2.equals(new PairInt(x0 + 1, y0 - 1))); assert(segment.p3.equals(new PairInt(x0, y0 - 1))); routes.route0.add(segment.p1); routes.route0.add(segment.p0); routes.route1.add(segment.p3); routes.route1.add(segment.p2); return routes; } else if ((segment instanceof UUDiagSegment) || (segment instanceof ULDiagSegment)) { Routes routes = new Routes(); routes.route0.add(segment.p1); routes.route0.add(segment.p0); routes.route1.add(segment.p3); routes.route1.add(segment.p2); return routes; } else { throw new IllegalStateException("error in algorithm: " + " segment not handled:" + segment.getClass().getSimpleName()); } } private void addEndpointsForHorizVertPatternForward(final int x0, final int y0, Pattern pattern, final Routes routes, Set<PairInt> endPoints, boolean useVert) { if (endPoints.size() < 2) { throw new IllegalStateException("error in algorithm"); } if ((routes.ep0End != null) || (routes.ep1 != null)) { routes.route0.clear(); routes.route1.clear(); routes.ep0 = null; routes.ep0End = null; routes.ep1 = null; routes.ep1End = null; } //assert(routes.ep0End == null); //assert(routes.ep1 == null); /* endPointsVertPattern1, for example R0 \/ -2 - 2 1 - -1 - 3 0 - 0 - . . - 1 # - # 2 - 3 /\ R1 -2 -1 0 1 endPointsHorizPattern1 - - - -2 R1--> # . 3 2 -1 -->R1 ends - - . 0 1 0 R0<-- # - - - 1 <--R0 starts 2 3 -3 -2 -1 0 1 */ assert(pattern.ep0 != null); PairInt tE1 = new PairInt(x0 + pattern.ep1.getX(), y0 + pattern.ep1.getY()); PairInt tE0 = new PairInt(x0 + pattern.ep0.getX(), y0 + pattern.ep0.getY()); if (!endPoints.contains(tE1) || !endPoints.contains(tE0)) { throw new IllegalStateException("error in algorithm"); } assert(!routes.route0.contains(tE0)); assert(!routes.route1.contains(tE1)); routes.route0.add(tE0); routes.ep0End = tE0; LinkedHashSet<PairInt> tmp1 = new LinkedHashSet<PairInt>(); tmp1.add(tE1); tmp1.addAll(routes.route1); routes.route1 = tmp1; routes.ep1 = tE1; } private void addEndpointsForHorizVertPatternOppos(int x0, int y0, Pattern pattern, Routes routes, Set<PairInt> endPoints, boolean useVert) { if (endPoints.size() < 2) { throw new IllegalStateException("error in algorithm"); } assert(routes.ep0 == null); assert(routes.ep1End == null); /* VertSegment R1 R0 /|\ | | | | \|/ . . -2 - 2 1 - -1 - 3 0 - 0 . . 1 -2 -1 0 1 HorizPattern - - - -2 R1--> . 3 2 -1 -->R1 ends . 0 1 0 R0<-- - - - 1 <--R0 starts -1 0 1 */ PairInt tE1 = new PairInt(x0 + pattern.ep1.getX(), y0 + pattern.ep1.getY()); PairInt tE0 = new PairInt(x0 + pattern.ep0.getX(), y0 + pattern.ep0.getY()); if (!endPoints.contains(tE1) || !endPoints.contains(tE0)) { throw new IllegalStateException("error in algorithm"); } assert(!routes.route0.contains(tE0)); assert(!routes.route1.contains(tE1)); routes.route1.add(tE1); routes.ep1End = tE1; LinkedHashSet<PairInt> tmp0 = new LinkedHashSet<PairInt>(); tmp0.add(tE0); tmp0.addAll(routes.route0); routes.route0 = tmp0; routes.ep0 = tE0; } private int addSegmentToRoutes(Routes routes, Segment segment) { assert(!routes.route0.isEmpty()); assert(!routes.route1.isEmpty()); // if segment is already in routes, return if (routes.route0.contains(segment.p0) && routes.route0.contains(segment.p1) && routes.route1.contains(segment.p2) && routes.route1.contains(segment.p3)) { return 0; } PairInt[] r1FirstLastNodes = getFirstAndLast(routes.route1.iterator()); double p3MinDistSq = Double.MAX_VALUE; int p3MinIdx = -1; double p2MinDistSq = Double.MAX_VALUE; int p2MinIdx = -1; for (int i = 0; i < r1FirstLastNodes.length; ++i) { PairInt r1 = r1FirstLastNodes[i]; int distSq = distSq(segment.p3, r1); if (distSq < p3MinDistSq) { p3MinDistSq = distSq; p3MinIdx = i; } distSq = distSq(segment.p2, r1); if (distSq < p2MinDistSq) { p2MinDistSq = distSq; p2MinIdx = i; } } if (segment instanceof HorizSegment || (segment instanceof ULDiagSegment)) { assert(segment.p3.getX() < segment.p2.getX()); assert(segment.p0.getX() < segment.p1.getX()); } else if (segment instanceof VertSegment || (segment instanceof UUDiagSegment)) { assert(segment.p3.getY() > segment.p2.getY()); assert(segment.p0.getY() > segment.p1.getY()); } assert(p2MinDistSq <= 4); assert(p3MinDistSq <= 4); if ((p2MinDistSq > p3MinDistSq) && (p3MinIdx == 1)) { // append to end of route1 R1:[start stop] p3 p2 //and insert at beginning of route0 R0:[stop start] p0 p1 LinkedHashSet<PairInt> tmp0 = new LinkedHashSet<PairInt>(); tmp0.add(segment.p1); if (p3MinDistSq > 0) { // append p2 routes.route1.add(segment.p3); tmp0.add(segment.p0); } routes.route1.add(segment.p2); tmp0.addAll(routes.route0); routes.route0 = tmp0; } else if ((p2MinDistSq < p3MinDistSq) && (p2MinIdx == 0)) { // insert at beginning of route1 p3 p2 R1:[start stop] // append to end of route0 p0 p1 R0:[stop start] LinkedHashSet<PairInt> tmp1 = new LinkedHashSet<PairInt>(); tmp1.add(segment.p3); if (p2MinDistSq > 0) { tmp1.add(segment.p2); routes.route0.add(segment.p1); } routes.route0.add(segment.p0); tmp1.addAll(routes.route1); routes.route1 = tmp1; } return 1; } protected PairInt[] getFirstAndLast(Iterator<PairInt> iter) { PairInt firstNode = null; PairInt lastNode = null; while (iter.hasNext()) { if (firstNode == null) { firstNode = iter.next(); } else { lastNode = iter.next(); } } return new PairInt[]{firstNode, lastNode}; } protected PairInt[] getSecondToLastAndLast(Iterator<PairInt> iter) { PairInt secondToLastNode = null; PairInt lastNode = null; while (iter.hasNext()) { PairInt n0 = iter.next(); if (iter.hasNext()) { secondToLastNode = n0; lastNode = iter.next(); } else { secondToLastNode = lastNode; lastNode = n0; } } return new PairInt[]{secondToLastNode, lastNode}; } private int addUUDiagSegmentToRoutes(Routes routes, DiagSegment segment) { assert(!routes.route0.isEmpty()); assert(!routes.route1.isEmpty()); /* UUDiagSegment - - -2 - 2 1 - - -1 - - 3 0 - 0 - - 1 -3 -2 -1 0 1 E0 is '1', and route0 continues with point '0' E1 is '3', and route1 continues with '2' */ PairInt[] r0FirstLastNodes = getFirstAndLast(routes.route0.iterator()); double p0MinDistSq = Double.MAX_VALUE; int p0MinIdx = -1; double p1MinDistSq = Double.MAX_VALUE; int p1MinIdx = -1; for (int i = 0; i < r0FirstLastNodes.length; ++i) { PairInt r0 = r0FirstLastNodes[i]; int distSq = distSq(segment.p0, r0); if (distSq < p0MinDistSq) { p0MinDistSq = distSq; p0MinIdx = i; } distSq = distSq(segment.p1, r0); if (distSq < p1MinDistSq) { p1MinDistSq = distSq; p1MinIdx = i; } } if (p1MinDistSq < p0MinDistSq) { /* E0 [*] [*] '1' '0' */ if (p1MinIdx != 1) { throw new IllegalStateException("error in algorithm"); } if (routes.ep0End != null) { throw new IllegalStateException("error in algorithm"); } routes.route0.add(segment.p1); routes.route0.add(segment.p0); } else if (p0MinDistSq < p1MinDistSq) { /* '1' '0' [*] [*] E0end */ if (p0MinIdx != 0) { throw new IllegalStateException("error in algorithm"); } if (routes.ep0 != null) { throw new IllegalStateException("error in algorithm"); } LinkedHashSet<PairInt> tmp = new LinkedHashSet<PairInt>(); tmp.add(segment.p1); tmp.add(segment.p0); tmp.addAll(routes.route0); routes.route0 = tmp; } else { throw new IllegalStateException("error in algorithm"); } PairInt[] r1FirstLastNodes = getFirstAndLast(routes.route1.iterator()); double p2MinDistSq = Double.MAX_VALUE; int p2MinIdx = -1; double p3MinDistSq = Double.MAX_VALUE; int p3MinIdx = -1; for (int i = 0; i < r1FirstLastNodes.length; ++i) { PairInt r1 = r1FirstLastNodes[i]; int distSq = distSq(segment.p2, r1); if (distSq < p2MinDistSq) { p2MinDistSq = distSq; p2MinIdx = i; } distSq = distSq(segment.p3, r1); if (distSq < p3MinDistSq) { p3MinDistSq = distSq; p3MinIdx = i; } } if (p2MinDistSq < p3MinDistSq) { /* E1end [*] [*] '2' '3' */ if (p2MinIdx != 0) { throw new IllegalStateException("error in algorithm"); } if (routes.ep1 != null) { throw new IllegalStateException("error in algorithm"); } LinkedHashSet<PairInt> tmp = new LinkedHashSet<PairInt>(); tmp.add(segment.p3); tmp.add(segment.p2); tmp.addAll(routes.route1); routes.route1 = tmp; } else if (p3MinDistSq < p2MinDistSq) { /* '2' '3' [*] [*] E1 */ if (p3MinIdx != 1) { throw new IllegalStateException("error in algorithm"); } if (routes.ep1End != null) { throw new IllegalStateException("error in algorithm"); } routes.route1.add(segment.p3); routes.route1.add(segment.p2); } else { throw new IllegalStateException("error in algorithm"); } return 1; } private ZigZagSegmentRoutes parseZigZag(Segment segment, Set<PairInt> endPoints) { if (!(segment instanceof ZigZagSegment) && !(segment instanceof ZigZagSegment2)) { throw new IllegalArgumentException( "segment type must be ZigZagSegment or ZigZagSegment2"); } if (endPoints.size() != 4) { throw new IllegalStateException("endPoints must be size 4"); } ZigZagSegmentRoutes routes = null; if (segment instanceof ZigZagSegment) { if (segment.p2.getX() < segment.p1.getX()) { /* E0 2 - -2 - 1 . E0end -1 E1end . 0 - 0 - 3 1 E1 -3 -2 -1 0 1 */ // '1' and '2' on one route and '0' and '3' on another. // add the endpoints before and after routes = new ZigZagSegmentRoutes(); routes.ep1 = findClosestTo(segment.p3, endPoints); routes.route1.add(routes.ep1); routes.route1.add(segment.p3); routes.route1.add(segment.p0); routes.ep1End = findClosestTo(segment.p0, endPoints); routes.route1.add(routes.ep1End); routes.ep0 = findClosestTo(segment.p2, endPoints); routes.route0.add(routes.ep0); routes.route0.add(segment.p2); routes.route0.add(segment.p1); routes.ep0End = findClosestTo(segment.p1, endPoints); routes.route0.add(routes.ep0End); } else { /* E0end - 2 -2 E0 . 1 - -1 - 0 . E1 0 3 - 1 E1end -3 -2 -1 0 1 */ // '1' and '2' on one route and '0' and '3' on another. // add the endpoints before and after routes = new ZigZagSegmentRoutes(); routes.ep0 = findClosestTo(segment.p1, endPoints); routes.route0.add(routes.ep0); routes.route0.add(segment.p1); routes.route0.add(segment.p2); routes.ep0End = findClosestTo(segment.p2, endPoints); routes.route0.add(routes.ep0End); routes.ep1 = findClosestTo(segment.p0, endPoints); routes.route1.add(routes.ep1); routes.route1.add(segment.p0); routes.route1.add(segment.p3); routes.ep1End = findClosestTo(segment.p3, endPoints); routes.route1.add(routes.ep1End); } } else { if (segment.p0.getY() < segment.p1.getY()) { /* E1end E0 . -1 - 0 - 3 0 1 - 2 - 1 E1 . E0end 2 -3 -2 -1 0 1 2 3 */ // '1' and '0' on one route and '2' and '3' on another. // add the endpoints before and after routes = new ZigZagSegmentRoutes(); routes.ep0 = findClosestTo(segment.p3, endPoints); routes.route0.add(routes.ep0); routes.route0.add(segment.p3); routes.route0.add(segment.p2); routes.ep0End = findClosestTo(segment.p2, endPoints); routes.route0.add(routes.ep0End); routes.ep1 = findClosestTo(segment.p1, endPoints); routes.route1.add(routes.ep1); routes.route1.add(segment.p1); routes.route1.add(segment.p0); routes.ep1End = findClosestTo(segment.p0, endPoints); routes.route1.add(routes.ep1End); } else { /* E1end E0 . -2 1 - 2 - -1 - 0 - 3 0 E1 . E0end 1 2 -3 -2 -1 0 1 2 3 */ // '1' and '0' on one route and '2' and '3' on another. // add the endpoints before and after routes = new ZigZagSegmentRoutes(); routes.ep0 = findClosestTo(segment.p2, endPoints); routes.route0.add(routes.ep0); routes.route0.add(segment.p2); routes.route0.add(segment.p3); routes.ep0End = findClosestTo(segment.p3, endPoints); routes.route0.add(routes.ep0End); routes.ep1 = findClosestTo(segment.p0, endPoints); routes.route1.add(routes.ep1); routes.route1.add(segment.p0); routes.route1.add(segment.p1); routes.ep1End = findClosestTo(segment.p1, endPoints); routes.route1.add(routes.ep1End); } } return routes; } private ZigZagSegmentRoutes parseDiagZigZag(Segment segment, Set<PairInt> endPoints) { if (!(segment instanceof DiagZigZagSegment) && !(segment instanceof DiagZigZagSegment2)) { throw new IllegalArgumentException( "segment type must be DiagZigZagSegment or DiagZigZagSegment2"); } if (endPoints.size() != 4) { throw new IllegalStateException("endPoints must be size 4"); } Set<PairInt> cpEndPoints = new HashSet<PairInt>(endPoints); ZigZagSegmentRoutes routes = null; /* first pattern is shown. The others are consistent w/ different locations. E0 -2 E1end 3 1 - -1 - 0 2 E0end 0 E1 - 1 -3 -2 -1 0 1 */ // '1' and '2' on one route and '0' and '3' on another. // add the endpoints before and after routes = new ZigZagSegmentRoutes(); routes.ep1 = findClosestTo(segment.p0, cpEndPoints); routes.route1.add(routes.ep1); routes.route1.add(segment.p0); routes.route1.add(segment.p3); cpEndPoints.remove(routes.ep1); routes.ep1End = findClosestTo(segment.p3, cpEndPoints); routes.route1.add(routes.ep1End); routes.ep0 = findClosestTo(segment.p1, cpEndPoints); routes.route0.add(routes.ep0); routes.route0.add(segment.p1); routes.route0.add(segment.p2); cpEndPoints.remove(routes.ep0); routes.ep0End = findClosestTo(segment.p2, cpEndPoints); routes.route0.add(routes.ep0End); return routes; } private PairInt findClosestTo(PairInt p0, Set<PairInt> points) { PairInt pt = null; int minDistSq = Integer.MAX_VALUE; for (PairInt p : points) { int distSq = distSq(p, p0); if (distSq < minDistSq) { minDistSq = distSq; pt = p; } } return pt; } private void setNullEndpoints(Routes routes) { if (!routes.getRoute0().isEmpty()) { if (routes.getEP0() == null) { routes.ep0 = routes.getRoute0().iterator().next(); } if (routes.getEP0End() == null) { PairInt[] a = getFirstAndLast(routes.getRoute0().iterator()); routes.ep0End = a[1]; } } if (!routes.getRoute1().isEmpty()) { if (routes.getEP1() == null) { routes.ep1 = routes.getRoute1().iterator().next(); } if (routes.getEP1End() == null) { PairInt[] a = getFirstAndLast(routes.getRoute1().iterator()); routes.ep1End = a[1]; } } } private void setNullEndpoints(List<Routes> routesList) { for (Routes routes : routesList) { setNullEndpoints(routes); } } private Segment checkDiagZigZagSegmentPattern(int x, int y, Set<PairInt> points) { Pattern pattern = getDiagZigZagSegmentPattern(); boolean matchesPattern = matchesPattern(x, y, points, pattern); /* 3, 0 are one route and 2, 1 are the other - -2 3 1 - -1 - 0 2 0 - 1 -3 -2 -1 0 1 */ if (matchesPattern) { DiagZigZagSegment segment = new DiagZigZagSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x, y - 1); segment.p2 = new PairInt(x + 1, y); segment.p3 = new PairInt(x - 1, y - 1); return segment; } swapXDirection(pattern); matchesPattern = matchesPattern(x, y, points, pattern); /* 3, 0 are one route and 2, 1 are the other - -2 - 1 3 -1 2 0 - 0 - 1 -3 -2 -1 0 1 */ if (matchesPattern) { DiagZigZagSegment segment = new DiagZigZagSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x, y - 1); segment.p2 = new PairInt(x - 1, y); segment.p3 = new PairInt(x + 1, y - 1); return segment; } return null; } private Segment checkDiagZigZag2SegmentPattern(int x, int y, Set<PairInt> points) { Pattern pattern = getDiagZigZag2SegmentPattern(); boolean matchesPattern = matchesPattern(x, y, points, pattern); /* 3, 0 are one route and 2, 1 are the other -2 - 3 - -1 0 1 0 - 2 - 1 -3 -2 -1 0 1 2 */ if (matchesPattern) { DiagZigZagSegment2 segment = new DiagZigZagSegment2(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x + 1, y); segment.p2 = new PairInt(x, y + 1); segment.p3 = new PairInt(x + 1, y - 1); return segment; } swapYDirection(pattern); matchesPattern = matchesPattern(x, y, points, pattern); /* 3, 0 are one route and 2, 1 are the other -2 - 2 - -1 0 1 0 - 3 - 1 -3 -2 -1 0 1 2 */ if (matchesPattern) { DiagZigZagSegment2 segment = new DiagZigZagSegment2(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x + 1, y); segment.p2 = new PairInt(x, y - 1); segment.p3 = new PairInt(x + 1, y + 1); return segment; } return null; } private void mergeIfAdjacent(List<LinkedList<Segment>> sections) { if (sections.size() < 2) { return; } mergeDiagonalIfAdjacent(sections, UUDiagSegment.class); mergeDiagonalIfAdjacent(sections, ULDiagSegment.class); mergeHorizontalIfAdjacent(sections); mergeVerticalIfAdjacent(sections); //TODO: add logic for diagonal in between horizonal or vertical merges } private void mergeHorizontalIfAdjacent(List<LinkedList<Segment>> sections) { if (sections.size() < 2) { return; } // sorts by each list's first item's p0.x Collections.sort(sections, new HorizSegmentListComparator()); /* using algorithm similar to leftedge. O(N*lg(N)) + O(N) where N is sections.size() sort by p0.x, then append, but only if adjacent and a horizontal segment horizontal s0 [][][] s1 [] s2 [] s3 [] */ List<Integer> remove = new ArrayList<Integer>(); int start = 0; LinkedList<Segment> currentSegments = null; while ((currentSegments == null) && (start < sections.size())) { LinkedList<Segment> list = sections.get(start); assert(!list.isEmpty()); if (list.get(0) instanceof HorizSegment) { currentSegments = list; } start++; } if (currentSegments == null) { return; } for (int i = start; i < sections.size(); ++i) { LinkedList<Segment> segments = sections.get(i); assert(!segments.isEmpty()); if (!(segments.get(0) instanceof HorizSegment)) { // only merging the horizontal segments with this method continue; } boolean csOrderedAscendingX = (currentSegments.get(currentSegments.size() - 1).p0.getX() > currentSegments.get(0).p0.getX()); boolean sOrderedAscendingX = (segments.get(segments.size() - 1).p0.getX() > segments.get(0).p0.getX()); if (sOrderedAscendingX && ((currentSegments.size() == 1) || csOrderedAscendingX)) { Segment currentLastSegment = currentSegments.get(currentSegments.size() - 1); if (!(currentLastSegment instanceof HorizSegment)) { continue; } Segment firstSegment = segments.get(0); if (!(firstSegment instanceof HorizSegment)) { continue; } /* c[0] c[1] c[2] s[0] 3 2 3 2 3 2 3 2 0 1 0 1 0 1 0 1 */ int clP2X = currentLastSegment.p2.getX(); int clP1X = currentLastSegment.p1.getX(); int fP3X = firstSegment.p3.getX(); int fP0X = firstSegment.p0.getX(); if ((((clP2X + 1) == fP3X) && ((clP1X + 1) == fP0X)) || ((clP2X == fP3X) && (clP1X == fP0X)) ) { currentSegments.addAll(segments); remove.add(Integer.valueOf(i)); continue; } /* s[n-1] c[0] c[1] c[2] 3 2 3 2 3 2 3 2 0 1 0 1 0 1 0 1 */ Segment currentFirstSegment = currentSegments.get(0); if (!(currentFirstSegment instanceof HorizSegment)) { continue; } Segment lastSegment = segments.get(segments.size() - 1); if (!(lastSegment instanceof HorizSegment)) { continue; } int clP3X = currentFirstSegment.p3.getX(); int clP0X = currentFirstSegment.p0.getX(); int sP2X = lastSegment.p2.getX(); int sP1X = lastSegment.p1.getX(); if ((((sP2X + 1) == clP3X) && ((sP1X + 1) == clP0X)) || ((sP2X == clP3X) && (sP1X == clP0X))) { LinkedList<Segment> tmp = new LinkedList<Segment>(); tmp.addAll(segments); tmp.addAll(currentSegments); remove.add(Integer.valueOf(i)); currentSegments.clear(); currentSegments.addAll(tmp); } } else if (!sOrderedAscendingX && ((currentSegments.size() == 1) || !csOrderedAscendingX)) { /* c[1] c[0] s[n-1] 3 2 3 2 3 2 0 1 0 1 0 1 */ Segment currentFirstSegment = currentSegments.get(0); if (!(currentFirstSegment instanceof HorizSegment)) { continue; } Segment lastSegment = segments.get(segments.size() - 1); if (!(lastSegment instanceof HorizSegment)) { continue; } int cP2X = currentFirstSegment.p2.getX(); int cP1X = currentFirstSegment.p1.getX(); int sP3X = lastSegment.p3.getX(); int sP0X = lastSegment.p0.getX(); if ((((sP3X + 1) == cP2X) && ((sP0X + 1) == cP1X)) || ((sP3X == cP2X) && (sP0X == cP1X))) { LinkedList<Segment> tmp = new LinkedList<Segment>(); tmp.addAll(segments); tmp.addAll(currentSegments); remove.add(Integer.valueOf(i)); currentSegments.clear(); currentSegments.addAll(tmp); } /* s[0] c[1] c[0] 3 2 3 2 3 2 0 1 0 1 0 1 */ Segment currentLastSegment = currentSegments.get(currentSegments.size() - 1); if (!(currentLastSegment instanceof HorizSegment)) { continue; } Segment firstSegment = segments.get(0); if (!(firstSegment instanceof HorizSegment)) { continue; } int cP3X = currentLastSegment.p3.getX(); int cP0X = currentLastSegment.p0.getX(); int sP2X = firstSegment.p2.getX(); int sP1X = firstSegment.p1.getX(); if ((((sP2X + 1) == cP3X) && ((sP1X + 1) == cP0X)) || ((sP2X == cP3X) && (sP1X == cP0X)) ) { currentSegments.addAll(segments); remove.add(Integer.valueOf(i)); } } else { //TODO: handle merging when segments were assembled with different // directions. preferably, do this at top of method. // the caveat is that a linked list may be composed of items // which are composed of any combination of horizontal, // vertical, and diagonal already ordered by curve point order. } } for (int i = (remove.size() - 1); i > -1; --i) { sections.remove(remove.get(i).intValue()); } } private void mergeVerticalIfAdjacent(List<LinkedList<Segment>> sections) { if (sections.size() < 2) { return; } // sorts by each list's first item's p0.y, descending Collections.sort(sections, new VertSegmentListComparator()); /* using algorithm similar to leftedge. O(N*lg(N)) + O(N) where N is sections.size() sort by p0.y, then append, but only if adjacent and a vertical segment */ List<Integer> remove = new ArrayList<Integer>(); int start = 0; LinkedList<Segment> currentSegments = null; while ((currentSegments == null) && (start < sections.size())) { LinkedList<Segment> list = sections.get(start); assert(!list.isEmpty()); if (list.get(0) instanceof VertSegment) { currentSegments = list; } start++; } if (currentSegments == null) { return; } for (int i = start; i < sections.size(); ++i) { LinkedList<Segment> segments = sections.get(i); assert(!segments.isEmpty()); if (!(segments.get(0) instanceof VertSegment)) { // only merging the vertical segments with this method continue; } boolean csOrderedDescendingY = (currentSegments.get(currentSegments.size() - 1).p0.getY() < currentSegments.get(0).p0.getY()); boolean sOrderedDescendingY = (segments.get(segments.size() - 1).p0.getY() < segments.get(0).p0.getY()); if (sOrderedDescendingY && ((currentSegments.size() == 1) || csOrderedDescendingY)) { // last segment of current Segment currentLastSegment = currentSegments.get(currentSegments.size() - 1); if (!(currentLastSegment instanceof VertSegment)) { continue; } /* 2 1 -3 3 0 s[0] 2 1 -2 3 0 c[1] -1 2 1 0 3 0 c[0] */ int clP1Y = currentLastSegment.p1.getY(); int clP2Y = currentLastSegment.p2.getY(); int fP0Y = segments.get(0).p0.getY(); int fP3Y = segments.get(0).p3.getY(); if ((((clP1Y - 1) == fP0Y) && ((clP2Y - 1) == fP3Y)) || ((clP1Y == fP0Y) && (clP2Y == fP3Y))) { currentSegments.addAll(segments); remove.add(Integer.valueOf(i)); continue; } /* -3 2 1 -2 3 0 c[1] -1 2 1 0 3 0 c[0] 2 1 3 0 s[n-1] */ Segment currentFirstSegment = currentSegments.get(0); if (!(currentFirstSegment instanceof VertSegment)) { continue; } Segment lastSegment = segments.get(segments.size() - 1); if (!(lastSegment instanceof VertSegment)) { continue; } int cP0Y = currentFirstSegment.p0.getY(); int cP3Y = currentFirstSegment.p3.getY(); int sP1Y = lastSegment.p1.getY(); int sP2Y = lastSegment.p2.getY(); if ((((sP2Y - 1) == cP3Y) && ((sP1Y - 1) == cP0Y)) || ((sP2Y == cP3Y) && (sP1Y == cP0Y)) ) { LinkedList<Segment> tmp = new LinkedList<Segment>(); tmp.addAll(segments); tmp.addAll(currentSegments); remove.add(Integer.valueOf(i)); currentSegments.clear(); currentSegments.addAll(tmp); } } else if (!sOrderedDescendingY && ((currentSegments.size() == 1) || !csOrderedDescendingY)) { /* 2 1 -3 3 0 s[n-1] 2 1 -2 3 0 c[0] -1 2 1 0 3 0 c[1] */ Segment currentFirstSegment = currentSegments.get(0); if (!(currentFirstSegment instanceof VertSegment)) { continue; } Segment lastSegment = segments.get(segments.size() - 1); if (!(lastSegment instanceof VertSegment)) { continue; } int cP2Y = currentFirstSegment.p2.getY(); int cP1Y = currentFirstSegment.p1.getY(); int sP3Y = lastSegment.p3.getY(); int sP0Y = lastSegment.p0.getY(); if ((((cP2Y - 1) == sP3Y) && ((cP1Y - 1) == sP0Y)) || ((cP2Y == sP3Y) && (cP1Y == sP0Y))){ LinkedList<Segment> tmp = new LinkedList<Segment>(); tmp.addAll(segments); tmp.addAll(currentSegments); remove.add(Integer.valueOf(i)); currentSegments.clear(); currentSegments.addAll(tmp); continue; } /* -3 2 1 -2 3 0 c[0] -1 2 1 0 3 0 c[1] 2 1 3 0 s[0] */ // last segment of current Segment currentLastSegment = currentSegments.get(currentSegments.size() - 1); if (!(currentLastSegment instanceof VertSegment)) { continue; } Segment firstSegment = segments.get(0); if (!(firstSegment instanceof VertSegment)) { continue; } int clP3Y = currentLastSegment.p3.getY(); int clP0Y = currentLastSegment.p0.getY(); int sP2Y = firstSegment.p2.getY(); int sP1Y = firstSegment.p1.getY(); if ((((sP2Y - 1) == clP3Y) && ((sP1Y - 1) == clP0Y)) || ((sP2Y == clP3Y) && (sP1Y == clP0Y))) { currentSegments.addAll(segments); remove.add(Integer.valueOf(i)); } } else { //TODO: handle merging when segments were assembled with different // directions. preferably, do this at top of method. // the caveat is that a linked list may be composed of items // which are composed of any combination of horizontal, // vertical, and diagonal already ordered by curve point order. } } for (int i = (remove.size() - 1); i > -1; --i) { sections.remove(remove.get(i).intValue()); } } private void mergeDiagonalIfAdjacent(List<LinkedList<Segment>> sections, final Class<? extends DiagSegment> cls) { if (sections.size() < 2) { return; } //NOTE: this one is the same as mergeVertIfAdjacent except for type check // sorts by each list's first item's p0.y, descending Collections.sort(sections, new VertSegmentListComparator()); /* using algorithm similar to leftedge. O(N*lg(N)) + O(N) where N is sections.size() sort by p0.y, then append, but only if adjacent and a UUDiagSegment */ List<Integer> remove = new ArrayList<Integer>(); int start = 0; LinkedList<Segment> currentSegments = null; while ((currentSegments == null) && (start < sections.size())) { LinkedList<Segment> list = sections.get(start); assert(!list.isEmpty()); if (list.get(0).getClass().isAssignableFrom(cls)) { currentSegments = list; } start++; } if (currentSegments == null) { return; } for (int i = start; i < sections.size(); ++i) { LinkedList<Segment> segments = sections.get(i); assert(!segments.isEmpty()); if (!(segments.get(0).getClass().isAssignableFrom(cls))) { continue; } boolean csOrderedDescendingY = (currentSegments.get(currentSegments.size() - 1).p0.getY() < currentSegments.get(0).p0.getY()); boolean sOrderedDescendingY = (segments.get(segments.size() - 1).p0.getY() < segments.get(0).p0.getY()); if (sOrderedDescendingY && ((currentSegments.size() == 1) || csOrderedDescendingY)) { // last segment of current Segment currentLastSegment = currentSegments.get(currentSegments.size() - 1); if (!(currentLastSegment.getClass().isAssignableFrom(cls))) { continue; } /* 2 1 -3 3 0 s[0] 2 1 -2 3 0 c[1] -1 2 1 0 3 0 c[0] */ int clP1Y = currentLastSegment.p1.getY(); int clP2Y = currentLastSegment.p2.getY(); int fP0Y = segments.get(0).p0.getY(); int fP3Y = segments.get(0).p3.getY(); if ((((clP1Y - 1) == fP0Y) && ((clP2Y - 1) == fP3Y)) || ((clP1Y == fP0Y) && (clP2Y == fP3Y))) { currentSegments.addAll(segments); remove.add(Integer.valueOf(i)); continue; } /* -3 2 1 -2 3 0 c[1] -1 2 1 0 3 0 c[0] 2 1 3 0 s[n-1] */ Segment currentFirstSegment = currentSegments.get(0); if (!(currentFirstSegment.getClass().isAssignableFrom(cls))) { continue; } Segment lastSegment = segments.get(segments.size() - 1); if (!(lastSegment.getClass().isAssignableFrom(cls))) { continue; } int cP0Y = currentFirstSegment.p0.getY(); int cP3Y = currentFirstSegment.p3.getY(); int sP1Y = lastSegment.p1.getY(); int sP2Y = lastSegment.p2.getY(); if ((((sP2Y - 1) == cP3Y) && ((sP1Y - 1) == cP0Y)) || ((sP2Y == cP3Y) && (sP1Y == cP0Y)) ) { LinkedList<Segment> tmp = new LinkedList<Segment>(); tmp.addAll(segments); tmp.addAll(currentSegments); remove.add(Integer.valueOf(i)); currentSegments.clear(); currentSegments.addAll(tmp); } } else if (!sOrderedDescendingY && ((currentSegments.size() == 1) || !csOrderedDescendingY)) { /* 2 1 -3 3 0 s[n-1] 2 1 -2 3 0 c[0] -1 2 1 0 3 0 c[1] */ Segment currentFirstSegment = currentSegments.get(0); if (!(currentFirstSegment.getClass().isAssignableFrom(cls))) { continue; } Segment lastSegment = segments.get(segments.size() - 1); if (!(lastSegment.getClass().isAssignableFrom(cls))) { continue; } int cP2Y = currentFirstSegment.p2.getY(); int cP1Y = currentFirstSegment.p1.getY(); int sP3Y = lastSegment.p3.getY(); int sP0Y = lastSegment.p0.getY(); if ((((cP2Y - 1) == sP3Y) && ((cP1Y - 1) == sP0Y)) || ((cP2Y == sP3Y) && (cP1Y == sP0Y))){ LinkedList<Segment> tmp = new LinkedList<Segment>(); tmp.addAll(segments); tmp.addAll(currentSegments); remove.add(Integer.valueOf(i)); currentSegments.clear(); currentSegments.addAll(tmp); continue; } /* -3 2 1 -2 3 0 c[0] -1 2 1 0 3 0 c[1] 2 1 3 0 s[0] */ // last segment of current Segment currentLastSegment = currentSegments.get(currentSegments.size() - 1); if (!(currentLastSegment.getClass().isAssignableFrom(cls))) { continue; } Segment firstSegment = segments.get(0); if (!(firstSegment.getClass().isAssignableFrom(cls))) { continue; } int clP3Y = currentLastSegment.p3.getY(); int clP0Y = currentLastSegment.p0.getY(); int sP2Y = firstSegment.p2.getY(); int sP1Y = firstSegment.p1.getY(); if ((((sP2Y - 1) == clP3Y) && ((sP1Y - 1) == clP0Y)) || ((sP2Y == clP3Y) && (sP1Y == clP0Y))) { currentSegments.addAll(segments); remove.add(Integer.valueOf(i)); } } else { //TODO: handle merging when segments were assembled with different // directions. preferably, do this at top of method. // the caveat is that a linked list may be composed of items // which are composed of any combination of horizontal, // vertical, and diagonal already ordered by curve point order. } } for (int i = (remove.size() - 1); i > -1; --i) { sections.remove(remove.get(i).intValue()); } } private PairInt[] findULDiagTopEndpoints(Set<PairInt> points, ULDiagSegment segment) { // returns top endpoint of '2', then '1' PairInt a = new PairInt(segment.p0.getX(), segment.p0.getY() - 3); PairInt b = new PairInt(segment.p0.getX() + 1, segment.p0.getY() - 3); PairInt c = new PairInt(segment.p0.getX() + 2, segment.p0.getY() - 3); PairInt d = new PairInt(segment.p0.getX() + 2, segment.p0.getY() - 2); PairInt e = new PairInt(segment.p0.getX() + 2, segment.p0.getY() - 1); PairInt f = new PairInt(segment.p0.getX() + 2, segment.p0.getY()); PairInt[] t2 = new PairInt[]{a, b, c, d}; PairInt[] t1 = new PairInt[]{d, e, f}; /* find unique pair from set2={a,b,c,d} and set1={d,e,f} where the pair are not adjacent horizontally or vertically */ Set<PairInt> set2 = new HashSet<PairInt>(); for (PairInt p : t2) { if (points.contains(p)) { set2.add(p); } } if (set2.isEmpty()) { return null; } Set<PairInt> set1 = new HashSet<PairInt>(); for (PairInt p : t1) { if (points.contains(p)) { set1.add(p); } } if (set1.isEmpty()) { return null; } PairInt s2 = null; PairInt s1 = null; int minDistSq = Integer.MAX_VALUE; for (PairInt p2 : set2) { for (PairInt p1 : set1) { if (p2.equals(p1)) { continue; } int diffX = Math.abs(p2.getX() - p1.getX()); int diffY = Math.abs(p2.getY() - p1.getY()); if ((diffX == 0 && diffY == 1) || (diffX == 1 && diffY == 0)) { continue; } int distSq = (diffX * diffX) + (diffY* diffY); if (distSq < minDistSq) { minDistSq = distSq; s2 = p2; s1 = p1; } } } if (s2 != null && s1 != null) { return new PairInt[]{s2, s1}; } return null; } private PairInt[] findULDiagBottomEndpoints(Set<PairInt> points, ULDiagSegment segment) { // returns bottom endpoint of '3', then '0' PairInt a = new PairInt(segment.p0.getX() - 1, segment.p0.getY() - 2); PairInt b = new PairInt(segment.p0.getX() - 1, segment.p0.getY() - 1); PairInt c = new PairInt(segment.p0.getX() - 1, segment.p0.getY()); PairInt d = new PairInt(segment.p0.getX() - 1, segment.p0.getY() + 1); PairInt e = new PairInt(segment.p0.getX(), segment.p0.getY() + 1); PairInt f = new PairInt(segment.p0.getX() + 1, segment.p0.getY() + 1); PairInt[] t3 = new PairInt[]{a, b, c}; PairInt[] t0 = new PairInt[]{c, d, e, f}; /* find unique pair from set3={a,b,c} and set0={c,d,e,f} where the pair are not adjacent horizontally or vertically */ Set<PairInt> set3 = new HashSet<PairInt>(); for (PairInt p : t3) { if (points.contains(p)) { set3.add(p); } } if (set3.isEmpty()) { return null; } Set<PairInt> set0 = new HashSet<PairInt>(); for (PairInt p : t0) { if (points.contains(p)) { set0.add(p); } } if (set0.isEmpty()) { return null; } PairInt s3 = null; PairInt s0 = null; int minDistSq = Integer.MAX_VALUE; for (PairInt p3 : set3) { for (PairInt p0 : set0) { if (p3.equals(p0)) { continue; } int diffX = Math.abs(p3.getX() - p0.getX()); int diffY = Math.abs(p3.getY() - p0.getY()); if ((diffX == 0 && diffY == 1) || (diffX == 1 && diffY == 0)) { continue; } int distSq = (diffX * diffX) + (diffY* diffY); if (distSq < minDistSq) { minDistSq = distSq; s3 = p3; s0 = p0; } } } if (s3 != null && s0 != null) { return new PairInt[]{s3, s0}; } return null; } private PairInt[] findUUDiagTopEndpoints(Set<PairInt> points, UUDiagSegment segment) { // returns top endpoint of '2', then '1' PairInt a = new PairInt(segment.p0.getX() - 3, segment.p0.getY()); PairInt b = new PairInt(segment.p0.getX() - 3, segment.p0.getY() - 1); PairInt c = new PairInt(segment.p0.getX() - 3, segment.p0.getY() - 2); PairInt d = new PairInt(segment.p0.getX() - 2, segment.p0.getY() - 2); PairInt e = new PairInt(segment.p0.getX() - 1, segment.p0.getY() - 2); PairInt f = new PairInt(segment.p0.getX(), segment.p0.getY() - 2); PairInt[] t2 = new PairInt[]{a, b, c, d}; PairInt[] t1 = new PairInt[]{d, e, f}; /* find unique pair from set2={a,b,c,d} and set1={d,e,f} where the pair are not adjacent horizontally or vertically */ Set<PairInt> set2 = new HashSet<PairInt>(); for (PairInt p : t2) { if (points.contains(p)) { set2.add(p); } } if (set2.isEmpty()) { return null; } Set<PairInt> set1 = new HashSet<PairInt>(); for (PairInt p : t1) { if (points.contains(p)) { set1.add(p); } } if (set1.isEmpty()) { return null; } PairInt s2 = null; PairInt s1 = null; int minDistSq = Integer.MAX_VALUE; for (PairInt p2 : set2) { for (PairInt p1 : set1) { if (p2.equals(p1)) { continue; } int diffX = Math.abs(p2.getX() - p1.getX()); int diffY = Math.abs(p2.getY() - p1.getY()); if ((diffX == 0 && diffY == 1) || (diffX == 1 && diffY == 0)) { continue; } int distSq = (diffX * diffX) + (diffY* diffY); if (distSq < minDistSq) { minDistSq = distSq; s2 = p2; s1 = p1; } } } if (s2 != null && s1 != null) { return new PairInt[]{s2, s1}; } return null; } private PairInt[] findUUDiagBottomEndpoints(Set<PairInt> points, UUDiagSegment segment) { // returns bottom endpoint of '3', then '0' PairInt a = new PairInt(segment.p0.getX() - 2, segment.p0.getY() + 1); PairInt b = new PairInt(segment.p0.getX() - 1, segment.p0.getY() + 1); PairInt c = new PairInt(segment.p0.getX(), segment.p0.getY() + 1); PairInt d = new PairInt(segment.p0.getX() + 1, segment.p0.getY() + 1); PairInt e = new PairInt(segment.p0.getX() + 1, segment.p0.getY()); PairInt f = new PairInt(segment.p0.getX() + 1, segment.p0.getY() - 1); PairInt[] t3 = new PairInt[]{a, b, c}; PairInt[] t0 = new PairInt[]{c, d, e, f}; /* find unique pair from set3={a,b,c} and set0={c,d,e,f} where the pair are not adjacent horizontally or vertically */ Set<PairInt> set3 = new HashSet<PairInt>(); for (PairInt p : t3) { if (points.contains(p)) { set3.add(p); } } if (set3.isEmpty()) { return null; } Set<PairInt> set0 = new HashSet<PairInt>(); for (PairInt p : t0) { if (points.contains(p)) { set0.add(p); } } if (set0.isEmpty()) { return null; } PairInt s3 = null; PairInt s0 = null; int minDistSq = Integer.MAX_VALUE; for (PairInt p3 : set3) { for (PairInt p0 : set0) { if (p3.equals(p0)) { continue; } int diffX = Math.abs(p3.getX() - p0.getX()); int diffY = Math.abs(p3.getY() - p0.getY()); if ((diffX == 0 && diffY == 1) || (diffX == 1 && diffY == 0)) { continue; } int distSq = (diffX * diffX) + (diffY* diffY); if (distSq < minDistSq) { minDistSq = distSq; s3 = p3; s0 = p0; } } } if (s3 != null && s0 != null) { return new PairInt[]{s3, s0}; } return null; } /** * check for x or y coordinates being 0. note that it does not include * a check for maximum column or row. * @param segment * @return */ private boolean isOnImageBoundaries(Segment segment) { if (segment.p0.getX() == 0 || segment.p0.getY() == 0) { return true; } if (segment.p1.getX() == 0 || segment.p1.getY() == 0) { return true; } if (segment.p2.getX() == 0 || segment.p2.getY() == 0) { return true; } if (segment.p3.getX() == 0 || segment.p3.getY() == 0) { return true; } return false; } /* may change these classes to have ordered points or to specify the indexes of points that are the connections, that is the '.'s in sketches below. */ public static class Segment { // the 4 points matching the segment as 0, 1, 2, 3 in the subclasses PairInt p0; PairInt p1; PairInt p2; PairInt p3; boolean contains(PairInt p) { if (p0.equals(p)) { return true; } else if (p1.equals(p)) { return true; } else if (p2.equals(p)) { return true; } else if (p3.equals(p)) { return true; } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("p0=").append(p0.toString()) .append(" p1=").append(p1.toString()) .append(" p2=").append(p2.toString()) .append(" p3=").append(p3.toString()); return sb.toString(); } public void filterOutContaining(Set<PairInt> points) { points.remove(p0); points.remove(p1); points.remove(p2); points.remove(p3); } } public static class VertSegment extends Segment { } public static class HorizSegment extends Segment { } public static class DiagSegment extends Segment { } public static class UUDiagSegment extends DiagSegment { } public static class ULDiagSegment extends DiagSegment { } public static class ZigZagSegment extends Segment { } public static class ZigZagSegment2 extends Segment { } public static class DiagZigZagSegment extends Segment { } public static class DiagZigZagSegment2 extends Segment { } public static class Pattern { Set<PairInt> ones; Set<PairInt> zeroes; /* an endpoint in route0. can be null */ PairInt ep0 = null; /* an endpoint in route1. can be null */ PairInt ep1 = null; } protected Pattern getVertSegmentPattern() { /* . . -2 - 2 1 - -1 - 3 0 - 0 . . 1 -2 -1 0 1 */ Pattern pr = new Pattern(); pr.ones = new HashSet<PairInt>(); pr.zeroes = new HashSet<PairInt>(); pr.zeroes.add(new PairInt(-2, 0)); pr.zeroes.add(new PairInt(-2, -1)); pr.zeroes.add(new PairInt(1, 0)); pr.zeroes.add(new PairInt(1, -1)); pr.ones.add(new PairInt(-1, 0)); pr.ones.add(new PairInt(-1, -1)); pr.ones.add(new PairInt(0, -1)); return pr; } protected Pattern getUUDiagSegmentPattern() { Pattern pr = new Pattern(); pr.ones = new HashSet<PairInt>(); pr.zeroes = new HashSet<PairInt>(); pr.zeroes.add(new PairInt(-2, 1)); pr.zeroes.add(new PairInt(-2, 0)); pr.zeroes.add(new PairInt(-1, 1)); pr.zeroes.add(new PairInt(-1, -2)); pr.zeroes.add(new PairInt(0, -1)); pr.zeroes.add(new PairInt(1, 0)); pr.ones.add(new PairInt(-2, -1)); pr.ones.add(new PairInt(-1, 0)); pr.ones.add(new PairInt(-1, -1)); return pr; } protected Pattern getZigZagSegmentPattern() { /* 2 - -2 - 1 -1 0 - 0 - 3 1 -3 -2 -1 0 1 Each of the 4 needs at least one neighbor that is not one of the 4 points in the zig zap and all of their neighbors cannot be adjacent to any of the other neighbors. */ Pattern pr = new Pattern(); pr.ones = new HashSet<PairInt>(); pr.zeroes = new HashSet<PairInt>(); pr.zeroes.add(new PairInt(0, 1)); pr.zeroes.add(new PairInt(0, -1)); pr.zeroes.add(new PairInt(1, 0)); pr.zeroes.add(new PairInt(1, -2)); pr.ones.add(new PairInt(0, -2)); pr.ones.add(new PairInt(1, 1)); pr.ones.add(new PairInt(1, -1)); return pr; } protected Pattern getZigZag2SegmentPattern() { /* . -1 - 0 - 3 0 1 - 2 - 1 . 2 -3 -2 -1 0 1 2 3 Each of the 4 needs at least one neighbor that is not one of the 4 points in the zig zap and all of their neighbors cannot be adjacent to any of the other neighbors. */ Pattern pr = new Pattern(); pr.ones = new HashSet<PairInt>(); pr.zeroes = new HashSet<PairInt>(); pr.zeroes.add(new PairInt(-1, 0)); pr.zeroes.add(new PairInt(0, 1)); pr.zeroes.add(new PairInt(1, 0)); pr.zeroes.add(new PairInt(2, 1)); pr.ones.add(new PairInt(-1, 1)); pr.ones.add(new PairInt(0, 0)); pr.ones.add(new PairInt(0, -1)); pr.ones.add(new PairInt(1, 1)); pr.ones.add(new PairInt(1, 2)); pr.ones.add(new PairInt(2, 0)); return pr; } protected Pattern getDiagZigZagSegmentPattern() { /* 3, 0 are one route and 2, 1 are the other - -2 3 1 - -1 - 0 2 0 - 1 -3 -2 -1 0 1 Each of the 4 needs at least one neighbor that is not one of the 4 points in the zig zap and all of their neighbors cannot be adjacent to any of the other neighbors. */ Pattern pr = new Pattern(); pr.ones = new HashSet<PairInt>(); pr.zeroes = new HashSet<PairInt>(); pr.zeroes.add(new PairInt(-1, 0)); pr.zeroes.add(new PairInt(-1, -2)); pr.zeroes.add(new PairInt(1, 1)); pr.zeroes.add(new PairInt(1, -1)); pr.ones.add(new PairInt(-1, -1)); pr.ones.add(new PairInt(0, -1)); pr.ones.add(new PairInt(1, 0)); return pr; } protected Pattern getDiagZigZag2SegmentPattern() { /* 3, 0 are one route and 2, 1 are the other -2 - 3 - -1 0 1 0 - 2 - 1 -3 -2 -1 0 1 2 Each of the 4 needs at least one neighbor that is not one of the 4 points in the zig zap and all of their neighbors cannot be adjacent to any of the other neighbors. */ Pattern pr = new Pattern(); pr.ones = new HashSet<PairInt>(); pr.zeroes = new HashSet<PairInt>(); pr.zeroes.add(new PairInt(-1, 1)); pr.zeroes.add(new PairInt(0, -1)); pr.zeroes.add(new PairInt(1, 1)); pr.zeroes.add(new PairInt(2, -1)); pr.ones.add(new PairInt(0, 1)); pr.ones.add(new PairInt(1, 0)); pr.ones.add(new PairInt(1, -1)); return pr; } private Segment checkVertHorizSegmentPattern(int x, int y, Set<PairInt> neighbors, boolean useVertical) { if (neighbors.size() < 4) { return null; } /* VertSegment R1 R0 /|\ | | | | \|/ . . -2 - 2 1 - -1 - 3 0 - 0 . . 1 -2 -1 0 1 HorizPattern - - - -2 R1--> . 3 2 -1 -->R1 ends . 0 1 0 R0<-- - - - 1 <--R0 starts -1 0 1 */ Pattern pattern = getVertSegmentPattern(); if (!useVertical) { rotatePattern(pattern, -0.5*Math.PI); } boolean matchesPattern = matchesPattern(x, y, neighbors, pattern); if (matchesPattern) { if (useVertical) { VertSegment segment = new VertSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x, y - 1); segment.p2 = new PairInt(x - 1, y - 1); segment.p3 = new PairInt(x - 1, y); return segment; } else { HorizSegment segment = new HorizSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x + 1, y); segment.p2 = new PairInt(x + 1, y - 1); segment.p3 = new PairInt(x, y - 1); return segment; } } return null; } private Segment checkDiagSegmentPattern(int x, int y, Set<PairInt> points, Set<PairInt> neighbors) { //TODO: when write the section for diagonal large pattern, it has 3 neighbors /*if (neighbors.size() != 3) { return null; }*/ Pattern pattern = getUUDiagSegmentPattern(); boolean matchesPattern = matchesPattern(x, y, points, neighbors, pattern); if (matchesPattern) { UUDiagSegment segment = new UUDiagSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x - 1, y - 1); segment.p2 = new PairInt(x - 2, y - 1); segment.p3 = new PairInt(x - 1, y); return segment; } rotatePattern(pattern, -0.5*Math.PI); matchesPattern = matchesPattern(x, y, points, neighbors, pattern); if (matchesPattern) { ULDiagSegment segment = new ULDiagSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x + 1, y - 1); segment.p2 = new PairInt(x + 1, y - 2); segment.p3 = new PairInt(x, y - 1); return segment; } return null; } private ZigZagSegment checkZigZagSegmentPattern(int x, int y, Set<PairInt> points) { Pattern pattern = getZigZagSegmentPattern(); boolean matchesPattern = matchesPattern(x, y, points, pattern); /* 2 - -2 - 1 -1 0 - 0 - 3 1 -3 -2 -1 0 1 */ if (matchesPattern) { ZigZagSegment segment = new ZigZagSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x + 1, y - 1); segment.p2 = new PairInt(x, y - 2); segment.p3 = new PairInt(x + 1, y + 1); return segment; } swapXDirection(pattern); matchesPattern = matchesPattern(x, y, points, pattern); /* - 2 -2 1 - -1 - 0 0 3 - 1 -3 -2 -1 0 1 */ if (matchesPattern) { ZigZagSegment segment = new ZigZagSegment(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x - 1, y - 1); segment.p2 = new PairInt(x, y - 2); segment.p3 = new PairInt(x - 1, y + 1); return segment; } return null; } private ZigZagSegment2 checkZigZag2SegmentPattern(int x, int y, Set<PairInt> points) { Pattern pattern = getZigZag2SegmentPattern(); boolean matchesPattern = matchesPattern(x, y, points, pattern); /* . -1 - 0 - 3 0 1 - 2 - 1 . 2 -3 -2 -1 0 1 2 3 */ if (matchesPattern) { ZigZagSegment2 segment = new ZigZagSegment2(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x - 1, y + 1); segment.p2 = new PairInt(x + 1, y + 1); segment.p3 = new PairInt(x + 2, y); return segment; } swapYDirection(pattern); matchesPattern = matchesPattern(x, y, points, pattern); /* . -2 1 - 2 - -1 - 0 - 3 0 . 1 2 -3 -2 -1 0 1 2 3 */ if (matchesPattern) { ZigZagSegment2 segment = new ZigZagSegment2(); segment.p0 = new PairInt(x, y); segment.p1 = new PairInt(x - 1, y - 1); segment.p2 = new PairInt(x + 1, y - 1); segment.p3 = new PairInt(x + 2, y); return segment; } return null; } protected int distSq(PairInt p0, PairInt p1) { int diffX = p0.getX() - p1.getX(); int diffY = p0.getY() - p1.getY(); int distSq = (diffX * diffX) + (diffY * diffY); return distSq; } private boolean matchesPattern(final int x, final int y, Set<PairInt> neighbors, Pattern pattern) { for (PairInt p : pattern.zeroes) { PairInt p2 = new PairInt(x + p.getX(), y + p.getY()); if (neighbors.contains(p2)) { return false; } } for (PairInt p : pattern.ones) { PairInt p2 = new PairInt(x + p.getX(), y + p.getY()); if (!neighbors.contains(p2)) { return false; } } return true; } private boolean matchesPattern(final int x, final int y, Set<PairInt> points, Set<PairInt> neighbors, Pattern pattern) { for (PairInt p : pattern.zeroes) { PairInt p2 = new PairInt(x + p.getX(), y + p.getY()); if (neighbors.contains(p2)) { return false; } } for (PairInt p : pattern.ones) { PairInt p2 = new PairInt(x + p.getX(), y + p.getY()); if (!neighbors.contains(p2) && !points.contains(p2)) { return false; } } return true; } /** * route0 and route1 are the two routes in opposite directions for a section * in a closed curve with a junction. route0 and route1 do not cross and are * populated to help populate the curve so that the points are traversed in * opposite directions. */ public static class Routes { PairInt ep0 = null; PairInt ep1 = null; PairInt ep0End = null; PairInt ep1End = null; //route0, route1 need to be searchable but ordered. LinkedHashSet<PairInt> route0 = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> route1 = new LinkedHashSet<PairInt>(); public LinkedHashSet<PairInt> getRoute0() { return route0; } public LinkedHashSet<PairInt> getRoute1() { return route1; } public PairInt getEP0() { return ep0; } public PairInt getEP0End() { return ep0End; } public PairInt getEP1() { return ep1; } public PairInt getEP1End() { return ep1End; } public void applyOffsets(final int xOffset, final int yOffset) { if (ep0 != null) { ep0 = new PairInt(ep0.getX() + xOffset, ep0.getY() + yOffset); } if (ep0End != null) { ep0End = new PairInt(ep0End.getX() + xOffset, ep0End.getY() + yOffset); } if (ep1 != null) { ep1 = new PairInt(ep1.getX() + xOffset, ep1.getY() + yOffset); } if (ep1End != null) { ep1End = new PairInt(ep1End.getX() + xOffset, ep1End.getY() + yOffset); } LinkedHashSet<PairInt> tmp = new LinkedHashSet<PairInt>(); Iterator<PairInt> iter = this.route0.iterator(); while (iter.hasNext()) { PairInt p = iter.next(); tmp.add(new PairInt(p.getX() + xOffset, p.getY() + yOffset)); } route0 = tmp; tmp = new LinkedHashSet<PairInt>(); iter = this.route1.iterator(); while (iter.hasNext()) { PairInt p = iter.next(); tmp.add(new PairInt(p.getX() + xOffset, p.getY() + yOffset)); } route1 = tmp; } } public static class VertSegmentRoutes extends Routes { } public static class HorizSegmentRoutes extends Routes { } public static class UUDiagSegmentRoutes extends Routes { } public static class ZigZagSegmentRoutes extends Routes { } private static class HorizSegmentListComparator implements Comparator<LinkedList<Segment>> { public HorizSegmentListComparator() { } @Override public int compare(LinkedList<Segment> o1, LinkedList<Segment> o2) { if (o1.isEmpty() && o2.isEmpty()) { return 0; } else if (o1.isEmpty() && !o2.isEmpty()) { return 1; } else if (!o1.isEmpty() && o2.isEmpty()) { return -1; } return Integer.compare(o1.get(0).p0.getX(), o2.get(0).p0.getX()); } } private static class VertSegmentListComparator implements Comparator<LinkedList<Segment>> { public VertSegmentListComparator() { } @Override public int compare(LinkedList<Segment> o1, LinkedList<Segment> o2) { if (o1.isEmpty() && o2.isEmpty()) { return 0; } else if (o1.isEmpty() && !o2.isEmpty()) { return 1; } else if (!o1.isEmpty() && o2.isEmpty()) { return -1; } return Integer.compare(o2.get(0).p0.getY(), o1.get(0).p0.getY()); } } }
package cx2x.xcodeml.xelement; import org.w3c.dom.Element; import org.w3c.dom.Node; import cx2x.xcodeml.exception.*; import cx2x.xcodeml.helper.*; /** * The XdoStatement represents the FdoStatement (6.5) element in XcodeML * intermediate representation. * * Elements: ( Var?, indexRange?, body? ) * - Required: * - Var (Xvar) * - indexRange (XindexRange) * - body (Xbody) * Attributes: * - Optional: construct_name (text) * * Can have lineno and file attributes * * @author clementval */ public class XdoStatement extends XenhancedElement implements Xclonable<XdoStatement> { private XloopIterationRange _iterationRange = null; private Xbody _body = null; private String _construct_name = null; /** * Xelement standard ctor. Pass the base element to the base class and read * inner information (elements and attributes). * @param baseElement The root element of the Xelement */ public XdoStatement(Element baseElement){ super(baseElement); readElementInformation(); } /** * Read the inner element information. */ private void readElementInformation(){ findRangeElements(); _body = XelementHelper.findBody(this, false); _construct_name = XelementHelper.getAttributeValue(this, XelementName.ATTR_CONSTRUCT_NAME); } /** * Find the different elements that are included in the iteration range. */ public void findRangeElements(){ Xvar _var = XelementHelper.findVar(this, false); XindexRange _indexRange = XelementHelper.findIndexRange(this, false); if(_var != null && _indexRange != null){ _iterationRange = new XloopIterationRange(_var, _indexRange); } } /** * Apply a new iteration range to the do statement. * @param range The range to be applied. */ public void setNewRange(XloopIterationRange range){ Element body = _body.getBaseElement(); Node newVar = range.getInductionVar().cloneNode(); Node newRange = range.getIndexRange().cloneNode(); baseElement.insertBefore(newVar, body); baseElement.insertBefore(newRange, body); findRangeElements(); } /** * Delete the range elements (induction variable and index range). */ public void deleteRangeElements(){ baseElement.removeChild(_iterationRange.getInductionVar().getBaseElement()); baseElement.removeChild(_iterationRange.getIndexRange().getBaseElement()); } /** * Swap the range elements between two loop statements. * @param otherLoop The loop to swap range elements with this one. */ protected void swapRangeElementsWith(XdoStatement otherLoop){ otherLoop.setNewRange(_iterationRange); setNewRange(otherLoop.getIterationRange()); } /** * Get the do statement iteration range. * @return A XloopIterationRange containing the loop iteration range * information. */ public XloopIterationRange getIterationRange(){ return _iterationRange; } /** * Get the do statement's body. * @return A Xbody object for the do statement. */ public Xbody getBody(){ return _body; } public void appendToBody(XdoStatement otherLoop) throws IllegalTransformationException { XelementHelper.appendBody(_body, otherLoop.getBody()); } /** * Get the induction variable of the do statement. * @return The induction variable as a String value. */ public String getInductionVarValue(){ return _iterationRange.getInductionVar().getValue(); } /** * Get the lower bound value of the do statement. * @return The lower bound value as a String value. */ public String getLowerBoundValue(){ return _iterationRange.getIndexRange().getLowerBound().getValue(); } /** * Get the upper bound value of the do statement. * @return The upper bound value as a String value. */ public String getUpperBoundValue(){ return _iterationRange.getIndexRange().getUpperBound().getValue(); } /** * Get the step value of the do statement. * @return The step value as a String value. */ public String getStepValue(){ return _iterationRange.getIndexRange().getStep().getValue(); } /** * @return A string representation of the iterarion range. */ public String getFormattedRange(){ return _iterationRange.toString(); } /** * Check whether two do statements share the same iteration range. * @param other The do statement to be compared with the current one. * @return True if the two do statements share the same iteration range. False * otherwise. */ public boolean hasSameRangeWith(XdoStatement other){ return _iterationRange.isFullyIdentical(other.getIterationRange()); } /** * Check whether the element has a construct name attribute defined. * @return True the attribute is defined. False otherwise. */ public boolean hasConstructName(){ return _construct_name != null; } /** * Get the construct name attribute value. * @return Construct name value. Null if the attribute is not defined. */ public String getConstructName(){ return _construct_name; } public static XdoStatement create(Xvar induction, XindexRange range, boolean clone, XcodeProgram xcodeml) throws IllegalTransformationException { XdoStatement doStmt = XelementHelper.createEmpty(XdoStatement.class, xcodeml); doStmt.appendToChildren(induction, clone); doStmt.appendToChildren(range, clone); Xbody body = XelementHelper.createEmpty(Xbody.class, xcodeml); doStmt.appendToChildren(body, false); doStmt.readElementInformation(); return doStmt; } /** * Create an empty arrayIndex element in the given program * @param xcodeml The current XcodeProgram in wihch the statement is created. * @param range The iteration range to be applied to the do statement. * @return A new XdoStetement object with an empty body. */ public static XdoStatement createWithEmptyBody(XcodeProgram xcodeml, XloopIterationRange range) { Element element = xcodeml.getDocument().createElement(XelementName.DO_STMT); if(range != null){ element.appendChild(range.getInductionVar().cloneNode()); element.appendChild(range.getIndexRange().cloneNode()); } Element body = xcodeml.getDocument().createElement(XelementName.BODY); element.appendChild(body); return new XdoStatement(element); } @Override public XdoStatement cloneObject() { Node clone = cloneNode(); return new XdoStatement((Element)clone); } }
package me.jarviswang.canomega.frames; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JMenu; import javax.swing.JLabel; import java.util.ArrayList; import java.util.List; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFormattedTextField; import javax.swing.JTextField; import javax.swing.JButton; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormSpecs; import com.jgoodies.forms.layout.RowSpec; import jssc.SerialPortException; import jssc.SerialPortList; import me.jarviswang.canomega.commons.CANMessageListener; import me.jarviswang.canomega.commons.CommonUtils; import me.jarviswang.canomega.commons.CommonUtils.CANProtos; import me.jarviswang.canomega.commons.CommonUtils.KProtos; import me.jarviswang.canomega.commons.CommonUtils.OpenMode; import me.jarviswang.canomega.commons.FirmwareFileFilter; import me.jarviswang.canomega.commons.FuzzMessageListener; import me.jarviswang.canomega.commons.JMessageListener; import me.jarviswang.canomega.commons.KLineMessageListener; import me.jarviswang.canomega.commons.LogFileFilter; import me.jarviswang.canomega.dialogs.AboutDialog; import me.jarviswang.canomega.dialogs.CANFuzzer; import me.jarviswang.canomega.dialogs.FirmUpDialog; import me.jarviswang.canomega.dialogs.PacketDiff; import me.jarviswang.canomega.dialogs.PayloadPlayer; import me.jarviswang.canomega.models.CANMessage; import me.jarviswang.canomega.models.FuzzMessage; import me.jarviswang.canomega.models.JLogMessage; import me.jarviswang.canomega.models.JLogMessage.JMessageType; import me.jarviswang.canomega.models.JLogMessageTableModel; import me.jarviswang.canomega.models.JMessage; import me.jarviswang.canomega.models.KLogMessage; import me.jarviswang.canomega.models.KLogMessage.KMessageType; import me.jarviswang.canomega.models.KLogMessageTableModel; import me.jarviswang.canomega.models.KMessage; import me.jarviswang.canomega.models.LogMessage; import me.jarviswang.canomega.models.LogMessageTableModel; import me.jarviswang.canomega.models.MonitorMessageTableModel; import me.jarviswang.canomega.models.LogMessage.MessageType; import me.jarviswang.canomega.protocols.CANProtocols; import me.jarviswang.canomega.protocols.JProtocols; import me.jarviswang.canomega.protocols.KProtocols; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.JTabbedPane; import javax.swing.DefaultComboBoxModel; import javax.swing.JToggleButton; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import javax.swing.JScrollPane; import javax.swing.SpinnerModel; import javax.swing.JSpinner; import javax.swing.JCheckBox; import javax.swing.JTable; import java.awt.FlowLayout; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import javax.swing.SpinnerNumberModel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.swing.event.ChangeListener; import javax.swing.event.MouseInputListener; import javax.swing.event.ChangeEvent; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.JPopupMenu; import java.awt.Component; import java.awt.event.MouseAdapter; public class MainFrame extends JFrame implements CANMessageListener,FuzzMessageListener,KLineMessageListener,JMessageListener { private JPanel MainPanel; private JTextField tFBaudRate; private JTable Logtable; private JTextField txtId; private JTextField textData7; private JTextField textData6; private JTextField textData5; private JTextField textData4; private JTextField textData3; private JTextField textData2; private JTextField textData1; private JTextField textData0; private CANProtocols CANObj; private JSpinner spinDLC; private JComboBox comboProt; private JCheckBox chckbxRtr; private JButton btnSend; private OpenMode lastMode; private CANProtos lastProto; private JToggleButton tglbtnFollow; private long baseTimestamp = 0L; private JMenuItem mntmPacketDiffTool; private JMenuItem mntmCanFuzzingTool; private PacketDiff difftoolWindow; private final ArrayList<LogMessage> MonitorBuffer = new ArrayList<LogMessage>(); private CANFuzzer FuzzingtoolWindow; private JTextField tffuzzId; private JTable klogTable; private JTextField txtkdata; private JTextField txtkCs; private JComboBox cbkmode; private JButton btnActive; private JButton btnkSend; private KProtocols KObj; private JScrollPane scrollPane_2; private JTable JLogTable; private JLabel lblData_1; private JButton btnJsend; private JTextField jdata; private JLabel lblCrc; private JTextField txtCRC; private JComboBox cbJMode; private JLabel lblMode_1; private byte[] Firmbuffer; private JCheckBox resistorMode; private JMenuItem mntmSaveLog; private JMenuItem mntmPayloadPlayer; private Thread playprocess = null; private static JPopupMenu popupMenu; private JMenuItem mntmCopy; private JMenuItem mntmCopyToSender; private Clipboard clipboard; /** * Launch the application. */ public static void main(String[] args) { try { UIManager.LookAndFeelInfo[] skins = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo localLookAndFeelInfo:skins) { if ("Nimbus".equals(localLookAndFeelInfo.getName())) { UIManager.setLookAndFeel(localLookAndFeelInfo.getClassName()); break; } } } catch (Exception e) { e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { try { MainFrame frame = new MainFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public MainFrame() { setTitle("CAN Omega tools v"+CommonUtils.version); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 848, 640); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); JMenuItem mntmFirmwareUpdate = new JMenuItem("Firmware Update"); mntmFirmwareUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (CommonUtils.state == 0) { JOptionPane.showMessageDialog(MainFrame.this, "Please Connect First.","Error", JOptionPane.ERROR_MESSAGE); } else { MainFrame.this.perfomFirmUp(); } } }); mntmSaveLog = new JMenuItem("Save Log as..."); mntmSaveLog.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { MainFrame.this.SaveLogToFile(); } }); mnFile.add(mntmSaveLog); mnFile.add(mntmFirmwareUpdate); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); mnFile.add(mntmExit); JMenu mnAnalysis = new JMenu("Analysis"); menuBar.add(mnAnalysis); clipboard = this.getToolkit().getSystemClipboard(); mntmPacketDiffTool = new JMenuItem("Packet Diff tool"); mntmPacketDiffTool.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (CommonUtils.state == 0) { JOptionPane.showMessageDialog(MainFrame.this, "Please Connect First.","Error", JOptionPane.ERROR_MESSAGE); } else { MainFrame.this.difftoolWindow.getCloseButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainFrame.this.difftoolWindow.setVisible(false); } }); MainFrame.this.difftoolWindow.setVisible(true); } } }); mnAnalysis.add(mntmPacketDiffTool); mntmPayloadPlayer = new JMenuItem("Payload Player"); mntmPayloadPlayer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PayloadPlayer pp = new PayloadPlayer(); pp.setVisible(true); pp.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (playprocess!=null) { playprocess.interrupt(); playprocess = null; } } }); pp.getStartButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pp.getStartButton().setEnabled(false); try { String encoding="UTF-8"; File logfile = new File(pp.getLogFilePath()); InputStream is = new FileInputStream(logfile); InputStreamReader read = new InputStreamReader(is,encoding); BufferedReader bufferedReader = new BufferedReader(read); String line = null; List<String> lines = new ArrayList<String>(); int line_number = 0; while ((line = bufferedReader.readLine()) !=null) { line_number++; if (line_number==1) { String[] spilt_line = line.split(","); if (spilt_line[0].indexOf("Time")==-1) { JOptionPane.showMessageDialog(pp, "Invalid Log File.","Error", JOptionPane.ERROR_MESSAGE); pp.getStartButton().setEnabled(true); return ; } continue; //ignore first line table header } String[] spilt_line = line.split(","); if (spilt_line[1].equals("IN")) { lines.add("i"+spilt_line[5]); } else { lines.add("o"+spilt_line[5]); } } final List<String> payload = lines; MainFrame.this.baseTimestamp = System.currentTimeMillis(); MonitorMessageTableModel mmtm = (MonitorMessageTableModel) MainFrame.this.difftoolWindow.getmonitorTable().getModel(); mmtm.clear(); MainFrame.this.difftoolWindow.setVisible(true); MainFrame.this.difftoolWindow.getCloseButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainFrame.this.difftoolWindow.setVisible(false); } }); int delaytime = 1000/pp.getSpeed(); playprocess = new Thread(new Runnable() { @Override public void run() { try { for (String l:payload) { CANMessage msg = new CANMessage(l.substring(1)); SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { MainFrame.this.log(new LogMessage(msg, null, l.substring(0,1).equals("i")?MessageType.IN:MessageType.OUT, System.currentTimeMillis() - MainFrame.this.baseTimestamp)); if (pp.isPlaytoCAN() && MainFrame.this.CANObj!=null) { MainFrame.this.CANObj.send(msg); MainFrame.this.log(new LogMessage(msg,null,MessageType.OUT,System.currentTimeMillis() - MainFrame.this.baseTimestamp)); } } }); Thread.sleep(delaytime); } } catch (InterruptedException e) { System.out.println("Stop Play"); return ; } //Finish Play SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { pp.getStartButton().setEnabled(true); } }); } }); playprocess.start(); read.close(); pp.getStopButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { playprocess.interrupt(); pp.getStartButton().setEnabled(true); } }); } catch (FileNotFoundException e1) { JOptionPane.showMessageDialog(pp, "Can't Open File.","Error", JOptionPane.ERROR_MESSAGE); pp.getStartButton().setEnabled(true); } catch (IOException e2) { JOptionPane.showMessageDialog(pp, "Can't Open File.","Error", JOptionPane.ERROR_MESSAGE); pp.getStartButton().setEnabled(true); } } }); } }); mnAnalysis.add(mntmPayloadPlayer); difftoolWindow = new PacketDiff(); difftoolWindow.getPauseButton().addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (!difftoolWindow.getPauseButton().isSelected()) { MonitorMessageTableModel mmtm = (MonitorMessageTableModel) difftoolWindow.getmonitorTable().getModel(); for (LogMessage msg:MainFrame.this.MonitorBuffer) { mmtm.add(msg); } MainFrame.this.MonitorBuffer.clear(); } } }); JMenu mnAttack = new JMenu("Attack"); menuBar.add(mnAttack); mntmCanFuzzingTool = new JMenuItem("CAN fuzzing tool"); tffuzzId = null; mntmCanFuzzingTool.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MainFrame.this.lastMode == OpenMode.LISTENONLY) { JOptionPane.showMessageDialog(MainFrame.this, "Fuzzing tool cannot work in "+MainFrame.this.lastMode+" Mode.","Error", JOptionPane.ERROR_MESSAGE); return ; } if (CommonUtils.state == 0) { JOptionPane.showMessageDialog(MainFrame.this, "Please Connect First.","Error", JOptionPane.ERROR_MESSAGE); } else { FuzzingtoolWindow = new CANFuzzer(MainFrame.this); FuzzingtoolWindow.setCANObj(MainFrame.this.CANObj); if (MainFrame.this.CANObj.getCurrentProto() == CommonUtils.CANProtos.CAN250Kbps_11bits || MainFrame.this.CANObj.getCurrentProto() == CommonUtils.CANProtos.CAN500Kbps_11bits || MainFrame.this.CANObj.getCurrentProto() == CommonUtils.CANProtos.CAN125Kbps_11bits) { FuzzingtoolWindow.settxtId("001"); } else { FuzzingtoolWindow.settxtId("00000001"); } MainFrame.this.CANObj.addFuzzMessageListener(FuzzingtoolWindow); MainFrame.this.tffuzzId = FuzzingtoolWindow.gettfFuzzId(); MainFrame.this.ChangeIdFieldByProtocol(MainFrame.this.CANObj.getCurrentProto()); MainFrame.this.CANObj.addFuzzMessageListener(MainFrame.this); FuzzingtoolWindow.setVisible(true); FuzzingtoolWindow.getCloseButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int resp = JOptionPane.showConfirmDialog(FuzzingtoolWindow, "Sure to stop fuzzing and quit?","Warning", JOptionPane.YES_NO_OPTION); if (resp==0) { MainFrame.this.CANObj.StopFuzzing(); MainFrame.this.CANObj.removeFuzzMessageListener(MainFrame.this); MainFrame.this.CANObj.removeFuzzMessageListener(FuzzingtoolWindow); MainFrame.this.FuzzingtoolWindow.dispose(); MainFrame.this.tffuzzId = null; } } }); FuzzingtoolWindow.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int resp = JOptionPane.showConfirmDialog(FuzzingtoolWindow, "Sure to stop fuzzing and quit?","Warning", JOptionPane.YES_NO_OPTION); if (resp==0) { MainFrame.this.CANObj.StopFuzzing(); MainFrame.this.CANObj.removeFuzzMessageListener(MainFrame.this); MainFrame.this.CANObj.removeFuzzMessageListener(FuzzingtoolWindow); MainFrame.this.FuzzingtoolWindow.dispose(); MainFrame.this.tffuzzId = null; } } }); } } }); mnAttack.add(mntmCanFuzzingTool); JMenu mnHelp = new JMenu("Help"); menuBar.add(mnHelp); JMenuItem mntmAbout = new JMenuItem("About"); mntmAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AboutDialog ad = new AboutDialog(); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); ad.getContentPane().add(buttonPane, BorderLayout.SOUTH); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ad.dispose(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); ad.setVisible(true); } }); mnHelp.add(mntmAbout); MainPanel = new JPanel(); MainPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(MainPanel); MainPanel.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:max(37dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:50dlu"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:max(39dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.PREF_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(24dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:max(62dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:default"), ColumnSpec.decode("max(16dlu;default)"), FormSpecs.GLUE_COLSPEC, ColumnSpec.decode("left:default"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:default"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,}, new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, RowSpec.decode("max(11dlu;default)"), FormSpecs.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:292dlu:grow"),})); JLabel lblSerialPort = new JLabel("SerialPort:"); MainPanel.add(lblSerialPort, "2, 2, left, default"); JComboBox cbSerialPort = new JComboBox(); cbSerialPort.setMaximumRowCount(6); cbSerialPort.setEditable(true); MainPanel.add(cbSerialPort, "4, 2, fill, default"); String OS_Name = System.getProperty("os.name").toUpperCase(); //Obtain devices list on Mac if (OS_Name.indexOf("MAC")>=0 && OS_Name.indexOf("OS")>=0) { File dir = new File("/dev"); File[] files = dir.listFiles(); List<String> device_list = new ArrayList<String>(); for (int i = 0; i<files.length; i++) { if (files[i].getName().indexOf("tty.SLAB_USBtoUART")>=0) { device_list.add(files[i].getPath()); } } String[] port_in_mac = (String[]) ArrayUtils.addAll(SerialPortList.getPortNames(), device_list.toArray()); cbSerialPort.setModel(new DefaultComboBoxModel(port_in_mac)); } else { cbSerialPort.setModel(new DefaultComboBoxModel(SerialPortList.getPortNames())); } JLabel lblBaudrate = new JLabel("BaudRate:"); MainPanel.add(lblBaudrate, "6, 2, left, default"); tFBaudRate = new JTextField(); tFBaudRate.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (tFBaudRate.getText().length()>=7 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (inputkey>57 || inputkey<48) { e.consume(); } } } }); tFBaudRate.setText("115200"); tFBaudRate.setHorizontalAlignment(SwingConstants.LEFT); MainPanel.add(tFBaudRate, "8, 2, center, default"); tFBaudRate.setColumns(9); JLabel lblMode = new JLabel("Mode:"); MainPanel.add(lblMode, "10, 2, left, default"); JComboBox cbMode = new JComboBox(); lastMode = (OpenMode)cbMode.getSelectedItem(); cbMode.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { switch (CommonUtils.state) { case 0: break; case 1: OpenMode newMode = (OpenMode)cbMode.getSelectedItem(); if (newMode==lastMode) { return ; } if (MainFrame.this.CANObj!=null) { boolean res = CANObj.changeConnectMode(CANObj.getCurrentProto(),newMode); if (!res) { JOptionPane.showMessageDialog(MainFrame.this, "Change Connect Mode Failed.","Error", JOptionPane.ERROR_MESSAGE); cbMode.setSelectedItem(MainFrame.this.lastMode); } else { if (newMode == CommonUtils.OpenMode.LISTENONLY) { txtId.setEnabled(false); spinDLC.setEnabled(false); textData7.setEnabled(false); textData6.setEnabled(false); textData5.setEnabled(false); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); //comboProt.setEnabled(false); chckbxRtr.setEnabled(false); btnSend.setEnabled(false); } else { txtId.setEnabled(true); spinDLC.setEnabled(true); MainFrame.this.setFrameState(); comboProt.setEnabled(true); chckbxRtr.setEnabled(true); btnSend.setEnabled(true); } MainFrame.this.log("Changed to "+newMode+" Mode.", MessageType.INFO); lastMode = newMode; } } break; case 2:break; case 3:break; default:break; } } } }); MainPanel.add(cbMode, "12, 2, fill, default"); cbMode.setModel(new DefaultComboBoxModel(CommonUtils.OpenMode.values())); JButton btnConnect = new JButton("Connect"); btnConnect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (btnConnect.getText().equals("Connect")) { String serialport = (String) cbSerialPort.getSelectedItem(); String baudrate = tFBaudRate.getText(); int resp = 0; if (!StringUtils.isNumeric(baudrate)) { JOptionPane.showMessageDialog(MainFrame.this, "Invalid Baudrate.","Error", JOptionPane.ERROR_MESSAGE); return ; } switch (CommonUtils.protoSelected) { case 0: case 1: case 2: if (CANObj == null) { CANObj = new CANProtocols(); } resp = CANObj.connect(serialport, baudrate); if (resp==0) { CANProtos proto = CANObj.getDefaultProtocol(); lastProto = proto; comboProt.setSelectedItem(proto); OpenMode mode = (OpenMode)cbMode.getSelectedItem(); lastMode = mode; CANObj.openCANChannel(proto,mode); btnConnect.setText("Disconnect"); tFBaudRate.setEnabled(false); cbSerialPort.setEnabled(false); if (mode!=CommonUtils.OpenMode.LISTENONLY) { txtId.setEnabled(true); spinDLC.setEnabled(true); MainFrame.this.setFrameState(); comboProt.setEnabled(true); chckbxRtr.setEnabled(true); btnSend.setEnabled(true); txtkdata.setEnabled(true); txtkCs.setEnabled(true); cbkmode.setEnabled(true); btnActive.setEnabled(true); jdata.setEnabled(true); txtCRC.setEnabled(true); cbJMode.setEnabled(true); btnJsend.setEnabled(true); } else { comboProt.setEnabled(true); } int intver = 0; try { intver = Integer.parseInt(CommonUtils.hardwareVersion,16); } catch (Exception ee) { //ignore } if (intver>=0x0110) { resistorMode.setEnabled(true); } CommonUtils.state = 1; CANObj.addMessageListener(MainFrame.this); CANObj.addKLineMessageListener(MainFrame.this); CANObj.addJMessageListener(MainFrame.this); MainFrame.this.log("Connected to CANOmega (FW"+CommonUtils.firmwareVersion+"/HW"+CommonUtils.hardwareVersion+ ", SN: "+CommonUtils.serialNumber+")", MessageType.INFO); if (MainFrame.this.baseTimestamp == 0L) { MainFrame.this.baseTimestamp = System.currentTimeMillis(); } } break; default: JOptionPane.showMessageDialog(MainFrame.this, "Invalid Protocol Selected.","Error", JOptionPane.ERROR_MESSAGE); } if (resp!=0) { switch (resp) { case 1: JOptionPane.showMessageDialog(MainFrame.this, "Port Busy.Open Port Failed.","Error", JOptionPane.ERROR_MESSAGE); break; case 2: try { CommonUtils.serialPort.closePort(); } catch (SerialPortException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JOptionPane.showMessageDialog(MainFrame.this, "Device no Response.Please check your SerialPort/Baudrate.","Error", JOptionPane.ERROR_MESSAGE); break; default: JOptionPane.showMessageDialog(MainFrame.this, "Unknown Error.","Error",JOptionPane.ERROR_MESSAGE); break; } CommonUtils.serialPort = null; } } else { switch (CommonUtils.protoSelected) { case 0: case 1: case 2: if(CANObj!=null) { if (KObj!=null) { KObj.DeActiveKLine(); CANObj.removeKLineMessageListener(MainFrame.this); CANObj.removeJMessageListener(MainFrame.this); KObj = null; } CANObj.closeCANChannel(); CANObj.disconnect(); if (FuzzingtoolWindow!=null) { MainFrame.this.CANObj.removeFuzzMessageListener(MainFrame.this); MainFrame.this.CANObj.removeFuzzMessageListener(FuzzingtoolWindow); MainFrame.this.FuzzingtoolWindow.dispose(); MainFrame.this.tffuzzId = null; } CANObj.removeMessageListener(MainFrame.this); CANObj = null; } btnConnect.setText("Connect"); tFBaudRate.setEnabled(true); cbSerialPort.setEnabled(true); txtId.setEnabled(false); spinDLC.setEnabled(false); textData7.setEnabled(false); textData6.setEnabled(false); textData5.setEnabled(false); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); comboProt.setEnabled(false); chckbxRtr.setEnabled(false); btnSend.setEnabled(false); txtkdata.setEnabled(false); txtkCs.setEnabled(false); cbkmode.setEnabled(false); btnActive.setEnabled(false); btnActive.setText("Activate"); btnkSend.setEnabled(false); jdata.setEnabled(false); txtCRC.setEnabled(false); cbJMode.setEnabled(false); btnJsend.setEnabled(false); resistorMode.setEnabled(false); CommonUtils.state = 0; MainFrame.this.log("Disconnected.", MessageType.INFO); comboProt.setSelectedItem(CommonUtils.CANProtos.CAN500Kbps_11bits); resistorMode.setSelected(false); txtId.setText("001"); break; default: break; } } } }); MainPanel.add(btnConnect, "14, 2"); JButton btnClear = new JButton("Clear"); btnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { LogMessageTableModel ltm = (LogMessageTableModel) MainFrame.this.Logtable.getModel(); MonitorMessageTableModel mmtm = (MonitorMessageTableModel) MainFrame.this.difftoolWindow.getmonitorTable().getModel(); KLogMessageTableModel kltm = (KLogMessageTableModel) MainFrame.this.klogTable.getModel(); JLogMessageTableModel jltm = (JLogMessageTableModel) MainFrame.this.JLogTable.getModel(); ltm.clear(); mmtm.clear(); kltm.clear(); jltm.clear(); MainFrame.this.MonitorBuffer.clear(); MainFrame.this.baseTimestamp = System.currentTimeMillis(); } }); MainPanel.add(btnClear, "17, 2"); tglbtnFollow = new JToggleButton("Follow"); tglbtnFollow.setSelected(true); MainPanel.add(tglbtnFollow, "19, 2"); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int selectedPane = tabbedPane.getSelectedIndex(); CommonUtils.protoSelected = selectedPane; //System.out.println("Select: "+selectedPane); } }); MainPanel.add(tabbedPane, "2, 4, 18, 1"); JPanel panelCAN = new JPanel(); tabbedPane.addTab("CAN", null, panelCAN, null); panelCAN.setLayout(new FormLayout(new ColumnSpec[] { ColumnSpec.decode("88px"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("max(83dlu;default)"), FormSpecs.UNRELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(40dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.GLUE_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,}, new RowSpec[] { RowSpec.decode("fill:400px:grow"), FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("39px"),})); JScrollPane scrollPane = new JScrollPane(); panelCAN.add(scrollPane, "1, 1, 29, 1, fill, fill"); Logtable = new JTable(); Logtable.setModel(new LogMessageTableModel()); final MouseInputListener mouseInputListener = getMouseInputListener(Logtable); Logtable.addMouseListener(mouseInputListener); Logtable.addMouseMotionListener(mouseInputListener); Logtable.getColumnModel().getColumn(0).setPreferredWidth(100); Logtable.getColumnModel().getColumn(1).setPreferredWidth(40); Logtable.getColumnModel().getColumn(2).setPreferredWidth(90); Logtable.getColumnModel().getColumn(3).setPreferredWidth(40); Logtable.getColumnModel().getColumn(4).setPreferredWidth(370); popupMenu = new JPopupMenu(); addPopup(scrollPane, popupMenu); mntmCopy = new JMenuItem("Copy to Clipboard"); mntmCopy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MainFrame.this.Logtable.getSelectedRow()<0) { return ; } String ts = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),0).toString(); String type = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),1).toString(); if (type.toLowerCase().indexOf("receive")>=0) { type = "IN"; } else if (type.toLowerCase().indexOf("send")>=0) { type = "OUT"; } else if (type.toLowerCase().indexOf("info")>=0) { type = "INFO"; } else if (type.toLowerCase().indexOf("error")>=0) { type = "ERROR"; } String id = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),2).toString(); String dlc = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),3).toString(); String data = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),4).toString(); String linestr = ts+"\t"+type+"\t"+id+"\t"+dlc+"\t"+data; StringSelection clipstr = new StringSelection(linestr); MainFrame.this.clipboard.setContents(clipstr, null); } }); popupMenu.add(mntmCopy); mntmCopyToSender = new JMenuItem("Copy to Sender"); mntmCopyToSender.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MainFrame.this.Logtable.getSelectedRow()<0) { return ; } String id_str = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),2).toString(); String id = id_str.substring(0, id_str.length()-1); String dlc = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),3).toString(); String data = MainFrame.this.Logtable.getValueAt(MainFrame.this.Logtable.getSelectedRow(),4).toString(); if (data.indexOf("Remote Transmission Request")>=0) { chckbxRtr.setSelected(true); return ; } else { chckbxRtr.setSelected(false); } String[] split_data = data.split(" "); for (int i = 0; i<8; i++) { switch(i) { case 0: textData7.setText(i<split_data.length?split_data[i]:"00"); break; case 1: textData6.setText(i<split_data.length?split_data[i]:"00"); break; case 2: textData5.setText(i<split_data.length?split_data[i]:"00"); break; case 3: textData4.setText(i<split_data.length?split_data[i]:"00"); break; case 4: textData3.setText(i<split_data.length?split_data[i]:"00"); break; case 5: textData2.setText(i<split_data.length?split_data[i]:"00"); break; case 6: textData1.setText(i<split_data.length?split_data[i]:"00"); break; case 7: textData0.setText(i<split_data.length?split_data[i]:"00"); break; } } byte dlc_data = (byte)(Integer.parseInt(dlc)&0xFF); spinDLC.setValue(dlc_data); txtId.setText(id); } }); popupMenu.add(mntmCopyToSender); scrollPane.setViewportView(Logtable); txtId = new JTextField(); txtId.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { String msgId = txtId.getText(); if (MainFrame.this.lastProto == CommonUtils.CANProtos.CAN250Kbps_11bits || MainFrame.this.lastProto == CommonUtils.CANProtos.CAN500Kbps_11bits || MainFrame.this.lastProto == CommonUtils.CANProtos.CAN125Kbps_11bits) { while (msgId.length() < 3) { msgId = "0" + msgId; } if (msgId.length() > 3) { msgId = msgId.substring(msgId.length()-3); } if (msgId.getBytes()[0]>55) { msgId = "7" + msgId.substring(1); } } else { while (msgId.length() < 8) { msgId = "0" + msgId; } if (msgId.length() > 8) { msgId = msgId.substring(msgId.length()-8); } if (msgId.getBytes()[0]>49) { msgId = "1" + msgId.substring(1); } } txtId.setText(msgId); } }); txtId.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } CANProtos proto = CANObj.getCurrentProto(); if ((proto == CommonUtils.CANProtos.CAN500Kbps_11bits || proto == CommonUtils.CANProtos.CAN250Kbps_11bits || proto == CommonUtils.CANProtos.CAN125Kbps_11bits) && txtId.getText().length()>=8 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); txtId.setEnabled(false); panelCAN.add(txtId, "1, 3, fill, default"); txtId.setColumns(10); txtId.setText("001"); SpinnerModel model = new SpinnerNumberModel(new Byte((byte) 8), new Byte((byte) 0), new Byte((byte) 8), new Byte((byte) 1)); spinDLC = new JSpinner(model); spinDLC.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (chckbxRtr.isSelected()) { return ; } MainFrame.this.setFrameState(); } }); JFormattedTextField spintextField = ((JSpinner.NumberEditor) spinDLC.getEditor()).getTextField(); spintextField.setEditable(false); spinDLC.setEnabled(false); panelCAN.add(spinDLC, "3, 3"); textData7 = new JTextField(); textData7.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData7.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData7.setEnabled(false); panelCAN.add(textData7, "5, 3, fill, default"); textData7.setColumns(2); textData7.setText("11"); textData6 = new JTextField(); textData6.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData6.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData6.setEnabled(false); panelCAN.add(textData6, "7, 3, fill, default"); textData6.setColumns(2); textData6.setText("22"); textData5 = new JTextField(); textData5.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData5.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData5.setEnabled(false); panelCAN.add(textData5, "9, 3, fill, default"); textData5.setColumns(2); textData5.setText("33"); textData4 = new JTextField(); textData4.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData4.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData4.setEnabled(false); panelCAN.add(textData4, "11, 3, fill, default"); textData4.setColumns(2); textData4.setText("44"); textData3 = new JTextField(); textData3.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData3.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData3.setEnabled(false); panelCAN.add(textData3, "13, 3, fill, default"); textData3.setColumns(2); textData3.setText("55"); textData2 = new JTextField(); textData2.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData2.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData2.setEnabled(false); panelCAN.add(textData2, "15, 3, fill, default"); textData2.setColumns(2); textData2.setText("66"); textData1 = new JTextField(); textData1.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData1.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData1.setEnabled(false); panelCAN.add(textData1, "17, 3, fill, default"); textData1.setColumns(2); textData1.setText("77"); textData0 = new JTextField(); textData0.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (textData0.getText().length()>=2 && inputkey!=8) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); textData0.setEnabled(false); panelCAN.add(textData0, "19, 3, fill, default"); textData0.setColumns(2); textData0.setText("88"); comboProt = new JComboBox(); comboProt.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { switch (CommonUtils.state) { case 0: break; case 1: CANProtos newProto = (CANProtos)comboProt.getSelectedItem(); if (newProto==lastProto) { return ; } if (MainFrame.this.CANObj!=null) { boolean res = CANObj.changeConnectMode(newProto,lastMode); if (!res) { JOptionPane.showMessageDialog(MainFrame.this, "Change CAN Protocol Failed.","Error", JOptionPane.ERROR_MESSAGE); comboProt.setSelectedItem(MainFrame.this.lastProto); } else { MainFrame.this.ChangeIdFieldByProtocol(newProto); } } break; default:break; } } } }); comboProt.setEnabled(false); panelCAN.add(comboProt, "21, 3, fill, default"); comboProt.setModel(new DefaultComboBoxModel(CommonUtils.CANProtos.values())); chckbxRtr = new JCheckBox("RTR"); chckbxRtr.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange()==ItemEvent.SELECTED) { textData7.setEnabled(false); textData6.setEnabled(false); textData5.setEnabled(false); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); } if (e.getStateChange()==ItemEvent.DESELECTED) { MainFrame.this.setFrameState(); } } }); chckbxRtr.setEnabled(false); panelCAN.add(chckbxRtr, "23, 3"); btnSend = new JButton("Send"); btnSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MainFrame.this.sendButtonActionPerformed(e); } }); resistorMode = new JCheckBox("120Ω"); resistorMode.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange()==ItemEvent.SELECTED) { if (MainFrame.this.CANObj!=null) { int res = CANObj.ChangeTerminalResistorState(true); if (res != 0) { JOptionPane.showMessageDialog(MainFrame.this, "Set Terminal Resistor State Failed.","Error", JOptionPane.ERROR_MESSAGE); resistorMode.setSelected(false); } else { MainFrame.this.log("Terminal Resistor set to "+"120-Ohms.", MessageType.INFO); } } } if (e.getStateChange()==ItemEvent.DESELECTED) { if (MainFrame.this.CANObj!=null) { int res = CANObj.ChangeTerminalResistorState(false); if (res != 0) { JOptionPane.showMessageDialog(MainFrame.this, "Set Terminal Resistor State Failed.","Error", JOptionPane.ERROR_MESSAGE); resistorMode.setSelected(true); } else { MainFrame.this.log("Terminal Resistor set to "+"Open Circuit.", MessageType.INFO); } } } } }); resistorMode.setEnabled(false); panelCAN.add(resistorMode, "25, 3"); btnSend.setEnabled(false); panelCAN.add(btnSend, "29, 3"); JPanel panelKline = new JPanel(); tabbedPane.addTab("K-Line", null, panelKline, null); panelKline.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(172dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:max(17dlu;default)"), FormSpecs.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("max(76dlu;default)"), FormSpecs.LABEL_COMPONENT_GAP_COLSPEC, ColumnSpec.decode("left:default:grow"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(42dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,}, new RowSpec[] { RowSpec.decode("fill:406px:grow"), FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("max(39px;default)"),})); JScrollPane scrollPane_1 = new JScrollPane(); panelKline.add(scrollPane_1, "1, 1, 15, 1, fill, fill"); klogTable = new JTable(); klogTable.setModel(new KLogMessageTableModel()); klogTable.getColumnModel().getColumn(0).setPreferredWidth(30); klogTable.getColumnModel().getColumn(1).setPreferredWidth(20); klogTable.getColumnModel().getColumn(2).setPreferredWidth(370); scrollPane_1.setViewportView(klogTable); JLabel lblData = new JLabel("Data:"); panelKline.add(lblData, "1, 3, right, default"); txtkdata = new JTextField(); txtkdata.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { String content = txtkdata.getText(); String ok = ""; if (content.length()==0) { return ; } for (int i = 0;i<content.length();i++) { char ch = content.charAt(i); if (((ch>=48 && ch <=57) || (ch>=97 && ch<=102) || (ch>=65 && ch<=70))) { ok = ok.concat(content.substring(i, i+1)); } } if (ok.length()==0) { return ; } if (ok.length()%2!=0) { ok = "0" + ok; } int sum = 0; for (int i=0;i<ok.length();i = i +2) { sum = sum + Integer.parseInt(ok.substring(i, i+2),16); sum = sum%256; } txtkdata.setText(ok); txtkCs.setText(String.format("%02X", sum)); } }); txtkdata.setEnabled(false); txtkdata.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); panelKline.add(txtkdata, "3, 3, fill, default"); txtkdata.setColumns(10); JLabel lblChecksum = new JLabel("Checksum:"); panelKline.add(lblChecksum, "5, 3, right, default"); txtkCs = new JTextField(); txtkCs.setEnabled(false); txtkCs.setEditable(false); panelKline.add(txtkCs, "7, 3, left, default"); txtkCs.setColumns(2); cbkmode = new JComboBox(); cbkmode.setEnabled(false); cbkmode.setModel(new DefaultComboBoxModel(CommonUtils.KProtos.values())); panelKline.add(cbkmode, "9, 3, fill, default"); btnActive = new JButton("Activate"); btnActive.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (btnActive.getText().equals("Activate")) { if (MainFrame.this.KObj==null) { MainFrame.this.KObj = new KProtocols(); MainFrame.this.CANObj.addKLineMessageListener(MainFrame.this.KObj); } if (MainFrame.this.KObj.ActiveKLine((KProtos) MainFrame.this.cbkmode.getSelectedItem())==0) { MainFrame.this.btnActive.setText("DeActivate"); MainFrame.this.btnkSend.setEnabled(true); JOptionPane.showMessageDialog(MainFrame.this,"K Line Activated successfully.","Info", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(MainFrame.this,"K Line Activated Failed.","Error", JOptionPane.ERROR_MESSAGE); } } else { MainFrame.this.KObj.DeActiveKLine(); MainFrame.this.btnActive.setText("Activate"); MainFrame.this.btnkSend.setEnabled(false); JOptionPane.showMessageDialog(MainFrame.this,"K Line Disconnected.","Info", JOptionPane.INFORMATION_MESSAGE); } } }); btnActive.setEnabled(false); panelKline.add(btnActive, "13, 3"); btnkSend = new JButton("Send"); btnkSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String pack2send = "k"; if (true) { pack2send += "k"; String data = txtkdata.getText() + txtkCs.getText(); pack2send += String.format("%02X", data.length()/2); pack2send += data; } KMessage kmsg = new KMessage("k"+pack2send.substring(4)); MainFrame.this.Klog(new KLogMessage(kmsg, KMessageType.OUT, System.currentTimeMillis() - MainFrame.this.baseTimestamp)); System.out.println("K Line send: "+pack2send); MainFrame.this.KObj.SendKLineMessage(pack2send); } }); btnkSend.setEnabled(false); panelKline.add(btnkSend, "15, 3"); JPanel panelSAE = new JPanel(); tabbedPane.addTab("J1850", null, panelSAE, null); panelSAE.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(158dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(18dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(39dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,}, new RowSpec[] { RowSpec.decode("max(250dlu;default):grow"), FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("max(39px;default)"),})); scrollPane_2 = new JScrollPane(); panelSAE.add(scrollPane_2, "1, 1, 15, 1, fill, fill"); JLogTable = new JTable(); JLogTable.setModel(new JLogMessageTableModel()); JLogTable.getColumnModel().getColumn(0).setPreferredWidth(30); JLogTable.getColumnModel().getColumn(1).setPreferredWidth(20); JLogTable.getColumnModel().getColumn(2).setPreferredWidth(370); scrollPane_2.setViewportView(JLogTable); lblData_1 = new JLabel("Data:"); panelSAE.add(lblData_1, "1, 3, right, default"); jdata = new JTextField(); jdata.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { String content = jdata.getText(); String ok = ""; if (content.length()==0) { return ; } for (int i = 0;i<content.length();i++) { char ch = content.charAt(i); if (((ch>=48 && ch <=57) || (ch>=97 && ch<=102) || (ch>=65 && ch<=70))) { ok = ok.concat(content.substring(i, i+1)); } } if (ok.length()==0) { return ; } if (ok.length()%2!=0) { ok = "0" + ok; } int[] dataArray = new int[ok.length()/2]; for (int i=0;i<ok.length();i = i +2) { dataArray[i/2] = Integer.parseInt(ok.substring(i, i+2),16); } int crc = CommonUtils.J1850_CRC(dataArray); jdata.setText(ok); txtCRC.setText(String.format("%02X", crc)); } }); jdata.setEnabled(false); jdata.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int inputkey = e.getKeyChar(); if (CANObj == null) { e.consume(); return ; } if (inputkey == 10 || inputkey == 13) { e.consume(); } else { if (!((inputkey>=48 && inputkey <=57) || (inputkey>=97 && inputkey<=102) || (inputkey>=65 && inputkey<=70))) { e.consume(); } } } }); panelSAE.add(jdata, "3, 3, fill, default"); jdata.setColumns(10); lblCrc = new JLabel("CRC:"); panelSAE.add(lblCrc, "5, 3, right, default"); txtCRC = new JTextField(); txtCRC.setEditable(false); txtCRC.setEnabled(false); panelSAE.add(txtCRC, "7, 3, left, default"); txtCRC.setColumns(2); lblMode_1 = new JLabel("Mode:"); panelSAE.add(lblMode_1, "9, 3, right, default"); cbJMode = new JComboBox(); cbJMode.setEnabled(false); cbJMode.setModel(new DefaultComboBoxModel(CommonUtils.JModes.values())); panelSAE.add(cbJMode, "11, 3, fill, default"); btnJsend = new JButton("Send"); btnJsend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String pack2send = "j"; if (cbJMode.getSelectedItem()==CommonUtils.JModes.VPW) { pack2send += "v"; String data = jdata.getText() + txtCRC.getText(); pack2send += String.format("%02X", data.length()/2); pack2send += data; } else { //PWM Mode pack2send += "p"; String data = jdata.getText() + txtCRC.getText(); pack2send += String.format("%02X", data.length()/2); pack2send += data; } JMessage jmsg = new JMessage("j"+pack2send.substring(4)); MainFrame.this.Jlog(new JLogMessage(jmsg, JMessageType.OUT, System.currentTimeMillis() - MainFrame.this.baseTimestamp)); System.out.println("J1850 send: "+pack2send); JProtocols.SendJ1850Message(pack2send); } }); btnJsend.setEnabled(false); panelSAE.add(btnJsend, "15, 3"); } public void ResetUI() { } public void log(String msg,MessageType type) { LogMessageTableModel ltm = (LogMessageTableModel) this.Logtable.getModel(); ltm.addMessage(new LogMessage(null,msg,type,System.currentTimeMillis())); if (this.tglbtnFollow.isSelected()) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainFrame.this.Logtable.scrollRectToVisible(MainFrame.this.Logtable.getCellRect(ltm.getRowCount() - 1, 0, false)); } }); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } // try { // Thread.sleep(10); // } catch (InterruptedException e) { // e.printStackTrace(); // if (this.tglbtnFollow.isSelected()) { // this.Logtable.scrollRectToVisible(this.Logtable.getCellRect(ltm.getRowCount() - 1, 0, false)); } public void log(LogMessage msg) { LogMessageTableModel lmt = (LogMessageTableModel)this.Logtable.getModel(); lmt.addMessage(msg); if (this.tglbtnFollow.isSelected()) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainFrame.this.Logtable.scrollRectToVisible(MainFrame.this.Logtable.getCellRect(lmt.getRowCount() - 1, 0, false)); } }); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } if ((msg.getType() == MessageType.OUT) || (msg.getType() == MessageType.IN)) { if (this.difftoolWindow.getPauseButton().isSelected()) { this.MonitorBuffer.add(msg); } else { MonitorMessageTableModel mmtm = (MonitorMessageTableModel) difftoolWindow.getmonitorTable().getModel(); mmtm.add(msg); } } } private void sendButtonActionPerformed(ActionEvent e) { if (this.CANObj == null) { return ; } String sendString = ""; String msgId = txtId.getText(); boolean rtr = chckbxRtr.isSelected(); byte DLC = ((Byte)this.spinDLC.getValue()).byteValue(); String data7 = textData7.getText(); String data6 = textData6.getText(); String data5 = textData5.getText(); String data4 = textData4.getText(); String data3 = textData3.getText(); String data2 = textData2.getText(); String data1 = textData1.getText(); String data0 = textData0.getText(); String[] dataArray = new String[]{data7,data6,data5,data4,data3,data2,data1,data0}; if (this.lastProto == CommonUtils.CANProtos.CAN250Kbps_11bits || this.lastProto == CommonUtils.CANProtos.CAN500Kbps_11bits || this.lastProto == CommonUtils.CANProtos.CAN125Kbps_11bits) { if (rtr) { sendString += "r"; } else { sendString += "t"; } while (msgId.length() < 3) { msgId = "0" + msgId; } if (msgId.length() > 3) { msgId = msgId.substring(msgId.length()-3); } if (msgId.getBytes()[0]>55) { msgId = "7" + msgId.substring(1); } } else { if (rtr) { sendString += "R"; } else { sendString += "T"; } while (msgId.length() < 8) { msgId = "0" + msgId; } if (msgId.length() > 8) { msgId = msgId.substring(msgId.length()-8); } if (msgId.getBytes()[0]>49) { msgId = "1" + msgId.substring(1); } } sendString += msgId; sendString += String.valueOf(DLC); if (!rtr) { for (int i = 0; i < DLC; i++) { if (dataArray[i].length()==0) { dataArray[i] = "0"; } if (dataArray[i].length()<2) { sendString = sendString + "0" + dataArray[i]; } else { sendString += dataArray[i]; } } } CANMessage msgsend = new CANMessage(sendString); this.log(new LogMessage(msgsend,null,MessageType.OUT,System.currentTimeMillis() - this.baseTimestamp)); int res = this.CANObj.send(msgsend); System.out.println("Packet sent: "+msgsend); if (res!=0) { log("Send Message Failed!!", MessageType.ERROR); } } public void ChangeIdFieldByProtocol(CANProtos newProto) { if (newProto==lastProto) { return ; } if (newProto == CommonUtils.CANProtos.CAN250Kbps_11bits || newProto == CommonUtils.CANProtos.CAN500Kbps_11bits || newProto == CommonUtils.CANProtos.CAN125Kbps_11bits) { String strId = txtId.getText(); while (strId.length() < 3) { strId = "0" + strId; } if (strId.length() > 3) { strId = strId.substring(strId.length()-3); } if (strId.getBytes()[0]>55) { strId = "7" + strId.substring(1); } txtId.setText(strId); if (this.tffuzzId!=null) { strId = this.tffuzzId.getText(); while (strId.length() < 3) { strId = "0" + strId; } if (strId.length() > 3) { strId = strId.substring(strId.length()-3); } if (strId.getBytes()[0]>55) { strId = "7" + strId.substring(1); } this.tffuzzId.setText(strId); } } else { String strId = txtId.getText(); while (strId.length() < 8) { strId = "0" + strId; } if (strId.length() > 8) { strId = strId.substring(strId.length()-8); } if (strId.getBytes()[0]>49) { strId = "1" + strId.substring(1); } txtId.setText(strId); if (this.tffuzzId!=null) { strId = this.tffuzzId.getText(); while (strId.length() < 8) { strId = "0" + strId; } if (strId.length() > 8) { strId = strId.substring(strId.length()-8); } if (strId.getBytes()[0]>49) { strId = "1" + strId.substring(1); } this.tffuzzId.setText(strId); } } MainFrame.this.log("Changed to "+newProto+" Protocol.", MessageType.INFO); lastProto = newProto; } private void setFrameState() { if (this.CANObj==null) { return ; } int spinvalue = ((Byte)spinDLC.getValue()).byteValue(); boolean rtr = chckbxRtr.isSelected(); if (rtr) { textData7.setEnabled(false); textData6.setEnabled(false); textData5.setEnabled(false); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); return ; } switch (spinvalue) { case 0: textData7.setEnabled(false); textData6.setEnabled(false); textData5.setEnabled(false); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); break; case 1: textData7.setEnabled(true); textData6.setEnabled(false); textData5.setEnabled(false); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); break; case 2: textData7.setEnabled(true); textData6.setEnabled(true); textData5.setEnabled(false); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); break; case 3: textData7.setEnabled(true); textData6.setEnabled(true); textData5.setEnabled(true); textData4.setEnabled(false); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); break; case 4: textData7.setEnabled(true); textData6.setEnabled(true); textData5.setEnabled(true); textData4.setEnabled(true); textData3.setEnabled(false); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); break; case 5: textData7.setEnabled(true); textData6.setEnabled(true); textData5.setEnabled(true); textData4.setEnabled(true); textData3.setEnabled(true); textData2.setEnabled(false); textData1.setEnabled(false); textData0.setEnabled(false); break; case 6: textData7.setEnabled(true); textData6.setEnabled(true); textData5.setEnabled(true); textData4.setEnabled(true); textData3.setEnabled(true); textData2.setEnabled(true); textData1.setEnabled(false); textData0.setEnabled(false); break; case 7: textData7.setEnabled(true); textData6.setEnabled(true); textData5.setEnabled(true); textData4.setEnabled(true); textData3.setEnabled(true); textData2.setEnabled(true); textData1.setEnabled(true); textData0.setEnabled(false); break; case 8: textData7.setEnabled(true); textData6.setEnabled(true); textData5.setEnabled(true); textData4.setEnabled(true); textData3.setEnabled(true); textData2.setEnabled(true); textData1.setEnabled(true); textData0.setEnabled(true); break; default:break; } } public void Klog(KLogMessage msg) { KLogMessageTableModel klmt = (KLogMessageTableModel)this.klogTable.getModel(); klmt.addMessage(msg); if (this.tglbtnFollow.isSelected()) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainFrame.this.klogTable.scrollRectToVisible(MainFrame.this.klogTable.getCellRect(klmt.getRowCount() - 1, 0, false)); } }); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } // try { // Thread.sleep(10); // } catch (InterruptedException e) { // e.printStackTrace(); // if (this.tglbtnFollow.isSelected()) { // this.klogTable.scrollRectToVisible(this.klogTable.getCellRect(klmt.getRowCount() - 1, 0, false)); } public void Jlog(JLogMessage jmsg) { JLogMessageTableModel jlmt = (JLogMessageTableModel)this.JLogTable.getModel(); jlmt.addMessage(jmsg); if (this.tglbtnFollow.isSelected()) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainFrame.this.JLogTable.scrollRectToVisible(MainFrame.this.JLogTable.getCellRect(jlmt.getRowCount() - 1, 0, false)); } }); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } // try { // Thread.sleep(10); // } catch (InterruptedException e) { // e.printStackTrace(); // if (this.tglbtnFollow.isSelected()) { // this.JLogTable.scrollRectToVisible(this.JLogTable.getCellRect(jlmt.getRowCount() - 1, 0, false)); } public void perfomFirmUp() { JFileChooser jfc=new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.FILES_ONLY ); jfc.setDialogTitle("Choose Firmware File"); FirmwareFileFilter ff = new FirmwareFileFilter(); jfc.addChoosableFileFilter(ff); jfc.setFileFilter(ff); int res=jfc.showOpenDialog(this); if (res == JFileChooser.APPROVE_OPTION ) { File firmware = jfc.getSelectedFile(); if (!(firmware.getName().endsWith(".bin"))) { JOptionPane.showMessageDialog(this, "Invalid firmware type.","Error", JOptionPane.ERROR_MESSAGE); return ; } try { InputStream is = new FileInputStream(firmware); int size = is.available(); int padedsize = 0; if (size%1024!=0) { padedsize = (size/1024+1)*1024; } System.out.println("File size:" + size); this.Firmbuffer = new byte[padedsize]; is.read(this.Firmbuffer); is.close(); for (int i = size;i<padedsize;i++) { this.Firmbuffer[i] = 0x1A; } FirmUpDialog fud = new FirmUpDialog(this); fud.setCANObj(this.CANObj); fud.setVisible(true); fud.doFirmwareUpdate(this.Firmbuffer); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "Can't Open File.","Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Can't Open File.","Error", JOptionPane.ERROR_MESSAGE); } } } public void SaveLogToFile() { JFileChooser jfc=new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); jfc.setDialogTitle("Save Log to File..."); LogFileFilter ff = new LogFileFilter(); jfc.addChoosableFileFilter(ff); jfc.setFileFilter(ff); int res=jfc.showOpenDialog(this); if (res == JFileChooser.APPROVE_OPTION ) { File targetfile = jfc.getSelectedFile(); if (!(targetfile.getName().endsWith(".csv"))) { targetfile = new File(targetfile.getAbsolutePath()+".csv"); } try { FileWriter fw = new FileWriter(targetfile); switch (CommonUtils.protoSelected) { case 0: //Save CAN logs.. LogMessageTableModel msgs = (LogMessageTableModel) this.Logtable.getModel(); List<LogMessage> alllogs = msgs.getAllMessages(); String table_head = "Time(ms),Direction,Id,DLC,Data,Send-String\n"; fw.write(table_head); for (LogMessage amsg:alllogs) { if (amsg.getType()==MessageType.IN || amsg.getType()==MessageType.OUT) { String aline = amsg.getTimestamp()+","; aline += amsg.getType()+","; CANMessage canmsg = amsg.getCanmsg(); if (canmsg.isExtended()) { aline += String.format("%08Xh",canmsg.getId()) + ","; } else { aline += String.format("%03Xh",canmsg.getId()) + ","; } aline += Integer.valueOf(canmsg.getData().length) + ","; String str = ""; if (canmsg.isRtr()) { str = "Remote Transmission Request"; } else { byte[] arrayOfByte = canmsg.getData(); for (int i = 0; i < arrayOfByte.length; i++) { if (i > 0) { str = str.concat(" "); } str = str.concat(String.format("%02X", arrayOfByte[i])); } } aline += str + ","; aline += canmsg.toString() + "\n"; fw.write(aline); } } break; case 1: //TODO Save K Line logs.. case 2: //TODO Save J180 Logs.. } fw.close(); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Write File Error!","Error", JOptionPane.ERROR_MESSAGE); } } } private static MouseInputListener getMouseInputListener(final JTable jTable) { return new MouseInputListener() { @Override public void mouseClicked(MouseEvent e) { processEvent(e); } @Override public void mousePressed(MouseEvent e) { processEvent(e); } @Override public void mouseReleased(MouseEvent e) { processEvent(e); if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0 && !e.isControlDown() && !e.isShiftDown()) { popupMenu.show(jTable, e.getX(), e.getY()); // popupMenu.show(tableLyz, e.getX(), e.getY());// } } @Override public void mouseEntered(MouseEvent e) { processEvent(e); } @Override public void mouseExited(MouseEvent e) { processEvent(e); } @Override public void mouseDragged(MouseEvent e) { processEvent(e); } @Override public void mouseMoved(MouseEvent e) { processEvent(e); } private void processEvent(MouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0) { int modifiers = e.getModifiers(); modifiers -= MouseEvent.BUTTON3_MASK; modifiers |= MouseEvent.BUTTON1_MASK; MouseEvent ne = new MouseEvent(e.getComponent(), e.getID(),e.getWhen(), modifiers, e.getX() , e.getY(), e.getClickCount(), false); jTable.dispatchEvent(ne); } } }; } @Override public void receiveCANMessage(CANMessage msg) { this.log(new LogMessage(msg, null, MessageType.IN, System.currentTimeMillis() - this.baseTimestamp)); } @Override public void receiveFuzzMessage(FuzzMessage msg) { this.log(new LogMessage((CANMessage)msg, null, MessageType.OUT, System.currentTimeMillis() - this.baseTimestamp)); } @Override public void finishFuzz() { // ignore } @Override public void receiveKLineMessage(String msg) { if (msg.charAt(0)=='k') { KMessage kmsg = new KMessage(msg); this.Klog(new KLogMessage(kmsg, KMessageType.IN, System.currentTimeMillis() - this.baseTimestamp)); } } @Override public void receiveJMessage(String msg) { JMessage jmsg = new JMessage(msg); this.Jlog(new JLogMessage(jmsg, JMessageType.IN, System.currentTimeMillis() - this.baseTimestamp)); } private static void addPopup(Component component, final JPopupMenu popup) { component.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } private void showMenu(MouseEvent e) { popup.show(e.getComponent(), e.getX(), e.getY()); } }); } }
package invtweaks.forge.asm; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import java.util.Map; @IFMLLoadingPlugin.TransformerExclusions({"invtweaks.forge.asm"}) public class FMLPlugin implements IFMLLoadingPlugin { @Override public String[] getLibraryRequestClass() { return new String[0]; } @Override public String[] getASMTransformerClass() { return new String[] { "invtweaks.forge.asm.ITAccessTransformer", "invtweaks.forge.asm.ContainerTransformer" }; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { } }
package ch.ethz.inf.vs.californium.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ByteArrayUtils { /** * Adds a padding to the given array, such that a new array with the given * length is generated. * * @param array * the array to be padded. * @param value * the padding value. * @param newLength * the new length of the padded array. * @return the array padded with the given value. */ public static byte[] padArray(byte[] array, byte value, int newLength) { int length = array.length; int paddingLength = newLength - length; if (paddingLength < 1) { return array; } else { byte[] padding = new byte[paddingLength]; Arrays.fill(padding, value); return concatenate(array, padding); } } /** * Truncates the given array to the request length. * * @param array * the array to be truncated. * @param newLength * the new length in bytes. * @return the truncated array. */ public static byte[] truncate(byte[] array, int newLength) { if (array.length < newLength) { return array; } else { byte[] truncated = new byte[newLength]; System.arraycopy(array, 0, truncated, 0, newLength); return truncated; } } /** * Concatenates two byte arrays. * * @param a * the first array. * @param b * the second array. * @return the concatenated array. */ public static byte[] concatenate(byte[] a, byte[] b) { int lengthA = a.length; int lengthB = b.length; byte[] concat = new byte[lengthA + lengthB]; System.arraycopy(a, 0, concat, 0, lengthA); System.arraycopy(b, 0, concat, lengthA, lengthB); return concat; } /** * Computes array-wise XOR. * * @param a * the first array. * @param b * the second array. * @return the XOR-ed array. */ public static byte[] xorArrays(byte[] a, byte[] b) { byte[] xor = new byte[a.length]; for (int i = 0; i < a.length; i++) { xor[i] = (byte) (a[i] ^ b[i]); } return xor; } /** * Splits the given array into blocks of given size and adds padding to the * last one, if necessary. * * @param byteArray * the array. * @param blocksize * the block size. * @return a list of blocks of given size. */ public static List<byte[]> splitAndPad(byte[] byteArray, int blocksize) { List<byte[]> blocks = new ArrayList<byte[]>(); int numBlocks = (int) Math.ceil(byteArray.length / (double) blocksize); for (int i = 0; i < numBlocks; i++) { byte[] block = new byte[blocksize]; Arrays.fill(block, (byte) 0x00); if (i + 1 == numBlocks) { // the last block int remainingBytes = byteArray.length - (i * blocksize); System.arraycopy(byteArray, i * blocksize, block, 0, remainingBytes); } else { System.arraycopy(byteArray, i * blocksize, block, 0, blocksize); } blocks.add(block); } return blocks; } /** * Takes a byte array and returns it HEX representation. * * @param byteArray * the byte array. * @return the HEX representation. */ public static String toHexString(byte[] byteArray) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteArray.length; i++) { String value = Integer.toHexString(0xFF & byteArray[i]); if (value.length() < 2) { sb.append("0"); } sb.append(value); if (i < byteArray.length - 1) { sb.append(" "); } } return sb.toString(); } /** * Takes a HEX stream and returns the corresponding byte array. * * @param hexStream * the HEX stream. * @return the byte array. */ public static byte[] hexStreamToByteArray(String hexStream) { int length = hexStream.length(); byte[] data = new byte[length / 2]; for (int i = 0; i < length; i += 2) { data[i / 2] = (byte) ((Character.digit(hexStream.charAt(i), 16) << 4) + Character.digit(hexStream.charAt(i + 1), 16)); } return data; } }
package net.commotionwireless.olsrinfo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Hans-Christoph Steiner * */ public class OlsrInfo { String host = "127.0.0.1"; int port = 2006; public OlsrInfo() { } public OlsrInfo(String sethost) { host = sethost; } public OlsrInfo(String sethost, int setport) { host = sethost; port = setport; } public String[] request(String req) throws IOException { Socket sock = null; BufferedReader in = null; PrintWriter out = null; List<String> retlist = new ArrayList<String>(); try { sock = new Socket(host, port); in = new BufferedReader(new InputStreamReader(sock.getInputStream())); out = new PrintWriter(sock.getOutputStream(), true); } catch (UnknownHostException e) { throw new IOException(); } catch (IOException e) { System.err.println("Couldn't get I/O for socket to " + host + ":" + Integer.toString(port)); } out.println(req); String line; while((line = in.readLine()) != null) { if(! line.equals("")) retlist.add(line); } // the txtinfo plugin drops the connection once it outputs out.close(); in.close(); sock.close(); return retlist.toArray(new String[retlist.size()]); } public String[][] command(String cmd) { String[] data = null; final Set<String> supportedCommands = new HashSet<String>(Arrays.asList( new String[] { "/neigh", "/link", "/route", "/hna", "/mid", "/topo", } )); if(! supportedCommands.contains(cmd)) System.out.println("Unsupported command: " + cmd); try { data = request(cmd); } catch (IOException e) { System.err.println("Couldn't get I/O for socket to " + host + ":" + Integer.toString(port)); } int startpos = -1; for(int i = 0; i < data.length; i++) { if(data[i].startsWith("Table: ")) { startpos = i + 2; break; } } if(startpos >= data.length || startpos == -1) return new String[0][0]; int fields = data[startpos + 1].split("\t").length; String[][] ret = new String[data.length - startpos][fields]; for (int i = 0; i < ret.length; i++) ret[i] = data[i + startpos].split("\t"); return ret; } /** * 2-hop neighbors on the mesh * @return array of per-IP arrays of IP address, SYM, MPR, MPRS, Willingness, and 2 Hop Neighbors */ public String[][] neighbors() { return command("/neigh"); } /** * direct connections on the mesh, i.e. nodes with direct IP connectivity via Ad-hoc * @return array of per-IP arrays of Local IP, Remote IP, Hysteresis, LQ, NLQ, and Cost */ public String[][] links() { return command("/link"); } /** * IP routes to nodes on the mesh * @return array of per-IP arrays of Destination, Gateway IP, Metric, ETX, and Interface */ public String[][] routes() { return command("/route"); } /** * Host and Network Association (for supporting dynamic internet gateways) * @return array of per-IP arrays of Destination and Gateway */ public String[][] hna() { return command("/hna"); } /** * Multiple Interface Declaration * @return array of per-IP arrays of IP address and Aliases */ public String[][] mid() { return command("/mid"); } /** * topology of the whole mesh * @return array of per-IP arrays of Destination IP, Last hop IP, LQ, NLQ, and Cost */ public String[][] topology() { return command("/topo"); } /** * for testing from the command line */ public static void main(String[] args) throws IOException { OlsrInfo txtinfo = new OlsrInfo(); System.out.println("NEIGHBORS for(String[] s : txtinfo.neighbors()) { for(String t : s) System.out.print(t + ","); System.out.println(); } System.out.println("LINKS for(String[] s : txtinfo.links()) { for(String t : s) System.out.print(t + ","); System.out.println(); } System.out.println("ROUTES for(String[] s : txtinfo.routes()) { for(String t : s) System.out.print(t + ","); System.out.println(); } System.out.println("HNA for(String[] s : txtinfo.hna()) { for(String t : s) System.out.print(t + ","); System.out.println(); } System.out.println("MID for(String[] s : txtinfo.mid()) { for(String t : s) System.out.print(t + ","); System.out.println(); } System.out.println("TOPOLOGY for(String[] s : txtinfo.topology()) { for(String t : s) System.out.print(t + ","); System.out.println(); } } }
package net.lucenews.atom; import java.util.*; import javax.xml.parsers.*; import org.w3c.dom.*; public class IntrospectionDocument { private List<Workspace> workspaces; public IntrospectionDocument () { workspaces = new LinkedList<Workspace>(); } public List<Workspace> getWorkspaces () { return workspaces; } public void addWorkspace (Workspace workspace) { workspaces.add( workspace ); } public Document asDocument () throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element service = document.createElement( "service" ); service.setAttribute( "xmlns", "http: service.setAttribute( "xmlns:atom", "http: Iterator<Workspace> workspaces = getWorkspaces().iterator(); while (workspaces.hasNext()) { Workspace workspace = workspaces.next(); service.appendChild( workspace.asElement( document ) ); } document.appendChild( service ); return document; } }
package org.anddev.andengine.entity.shape; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.entity.DynamicEntity; import org.anddev.andengine.opengl.GLHelper; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.vertex.VertexBuffer; /** * @author Nicolas Gramlich * @since 11:51:27 - 13.03.2010 */ public abstract class Shape extends DynamicEntity { // Constants private static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_ONE; private static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; // Fields protected final VertexBuffer mVertexBuffer; protected float mRed = 1; protected float mGreen = 1; protected float mBlue = 1; protected float mAlpha = 1f; protected int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; protected int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; private final ArrayList<IShapeModifier> mShapeModifiers = new ArrayList<IShapeModifier>(); // Constructors public Shape(final float pX, final float pY, final VertexBuffer pVertexBuffer) { super(pX, pY); this.mVertexBuffer = pVertexBuffer; BufferObjectManager.loadBufferObject(this.mVertexBuffer); } // Getter & Setter public float getRed() { return this.mRed; } public float getGreen() { return this.mGreen; } public float getBlue() { return this.mBlue; } public float getAlpha() { return this.mAlpha; } public VertexBuffer getVertexBuffer() { return this.mVertexBuffer; } public void setAlpha(final float pAlpha) { this.mAlpha = pAlpha; } public void setColor(final float pRed, final float pGreen, final float pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; } public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.mAlpha = pAlpha; } public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { this.mSourceBlendFunction = pSourceBlendFunction; this.mDestinationBlendFunction = pDestinationBlendFunction; } public abstract float getWidth(); public abstract float getHeight(); public abstract float getBaseWidth(); public abstract float getBaseHeight(); public float getWidthScaled() { return this.getWidth() * this.mScale; } public float getHeightScaled() { return this.getHeight() * this.mScale; } // Methods for/from SuperClass/Interfaces @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); this.applyShapeModifiers(pSecondsElapsed); } @Override protected void onPositionChanged() { } protected abstract void onUpdateVertexBuffer(); @Override protected void onManagedDraw(final GL10 pGL) { this.onInitDraw(pGL); pGL.glPushMatrix(); this.onApplyVertices(pGL); this.onPreTransformations(pGL); this.onApplyTransformations(pGL); this.onPostTransformations(pGL); this.drawVertices(pGL); pGL.glPopMatrix(); } protected abstract void onPreTransformations(final GL10 pGL); protected abstract void applyOffset(final GL10 pGL); protected abstract void applyTranslation(final GL10 pGL); protected abstract void applyRotation(final GL10 pGL); protected abstract void applyScale(final GL10 pGL); protected abstract void drawVertices(final GL10 pGL); protected abstract void onPostTransformations(final GL10 pGL); @Override public void reset() { super.reset(); this.mRed = 1.0f; this.mGreen = 1.0f; this.mBlue = 1.0f; this.mAlpha = 1.0f; this.mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; this.mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; final ArrayList<IShapeModifier> shapeModifiers = this.mShapeModifiers; for(int i = shapeModifiers.size() - 1; i >= 0; i shapeModifiers.get(i).reset(); } } public abstract boolean contains(final float pX, final float pY); public abstract boolean collidesWith(final Shape pOtherShape); // Methods protected void updateVertexBuffer() { this.onUpdateVertexBuffer(); } public void addShapeModifier(final IShapeModifier pShapeModifier) { this.mShapeModifiers.add(pShapeModifier); } public void removeShapeModifier(final IShapeModifier pShapeModifier) { this.mShapeModifiers.remove(pShapeModifier); } private void applyShapeModifiers(final float pSecondsElapsed) { final ArrayList<IShapeModifier> shapeModifiers = this.mShapeModifiers; final int ShapeModifierCount = shapeModifiers.size(); if(ShapeModifierCount > 0) { for(int i = ShapeModifierCount - 1; i >= 0; i shapeModifiers.get(i).onUpdateShape(pSecondsElapsed, this); } } } protected void onInitDraw(final GL10 pGL) { GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); GLHelper.enableVertexArray(pGL); GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction); } private void onApplyVertices(final GL10 pGL) { if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { final GL11 gl11 = (GL11)pGL; this.mVertexBuffer.selectOnHardware(gl11); GLHelper.vertexZeroPointer(gl11); } else { GLHelper.vertexPointer(pGL, this.getVertexBuffer().getFloatBuffer()); } } protected void onApplyTransformations(final GL10 pGL) { this.applyOffset(pGL); this.applyTranslation(pGL); this.applyRotation(pGL); this.applyScale(pGL); } // Inner and Anonymous Classes }
package org.bouncycastle.math.ec; import java.math.BigInteger; import java.util.Random; public abstract class ECFieldElement implements ECConstants { BigInteger x; protected ECFieldElement(BigInteger x) { this.x = x; } public BigInteger toBigInteger() { return x; } public abstract String getFieldName(); public abstract ECFieldElement add(ECFieldElement b); public abstract ECFieldElement subtract(ECFieldElement b); public abstract ECFieldElement multiply(ECFieldElement b); public abstract ECFieldElement divide(ECFieldElement b); public abstract ECFieldElement negate(); public abstract ECFieldElement square(); public abstract ECFieldElement invert(); public abstract ECFieldElement sqrt(); public static class Fp extends ECFieldElement { BigInteger q; public Fp(BigInteger q, BigInteger x) { super(x); if (x.compareTo(q) >= 0) { throw new IllegalArgumentException("x value too large in field element"); } this.q = q; } /** * return the field name for this field. * * @return the string "Fp". */ public String getFieldName() { return "Fp"; } public BigInteger getQ() { return q; } public ECFieldElement add(ECFieldElement b) { return new Fp(q, x.add(b.x).mod(q)); } public ECFieldElement subtract(ECFieldElement b) { return new Fp(q, x.subtract(b.x).mod(q)); } public ECFieldElement multiply(ECFieldElement b) { return new Fp(q, x.multiply(b.x).mod(q)); } public ECFieldElement divide(ECFieldElement b) { return new Fp(q, x.multiply(b.x.modInverse(q)).mod(q)); } public ECFieldElement negate() { return new Fp(q, x.negate().mod(q)); } public ECFieldElement square() { return new Fp(q, x.multiply(x).mod(q)); } public ECFieldElement invert() { return new Fp(q, x.modInverse(q)); } // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. */ public ECFieldElement sqrt() { if (!q.testBit(0)) { throw new RuntimeException("not done yet"); } // p mod 4 == 3 if (q.testBit(1)) { // z = g^(u+1) + p, p = 4u + 3 ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 BigInteger qMinusOne = q.subtract(ECConstants.ONE); BigInteger legendreExponent = qMinusOne.shiftRight(1); if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) return null; BigInteger u = qMinusOne.shiftRight(2); BigInteger k = u.shiftLeft(1).add(ECConstants.ONE); BigInteger Q = this.x; BigInteger fourQ = Q.shiftLeft(2).mod(q); BigInteger U, V; do { Random rand = new Random(); BigInteger P; do { P = new BigInteger(q.bitLength(), rand); } while (P.compareTo(q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne))); BigInteger[] result = lucasSequence(q, P, Q, k); U = result[0]; V = result[1]; if (V.multiply(V).mod(q).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); //assert V.multiply(V).mod(q).equals(x); return new ECFieldElement.Fp(q, V); } } while (U.equals(ECConstants.ONE) || U.equals(qMinusOne)); return null; // BigInteger qMinusOne = q.subtract(ECConstants.ONE); // BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO); // if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) // return null; // Random rand = new Random(); // BigInteger fourX = x.shiftLeft(2); // BigInteger r; // r = new BigInteger(q.bitLength(), rand); // while (r.compareTo(q) >= 0 // || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne))); // BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR); // BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR); // BigInteger wOne = WOne(r, x, q); // BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q); // BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r); // BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q) // .multiply(x).mod(q) // .multiply(wSum).mod(q); // return new Fp(q, root); } // private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) // if (n.equals(ECConstants.ONE)) // return wOne; // boolean isEven = !n.testBit(0); // n = n.shiftRight(1);//divide(ECConstants.TWO); // if (isEven) // BigInteger w = W(n, wOne, p); // return w.multiply(w).subtract(ECConstants.TWO).mod(p); // BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p); // BigInteger w2 = W(n, wOne, p); // return w1.multiply(w2).subtract(wOne).mod(p); // private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) // return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p); private static BigInteger[] lucasSequence( BigInteger p, BigInteger P, BigInteger Q, BigInteger k) { int n = k.bitLength(); int s = k.getLowestSetBit(); BigInteger Uh = ECConstants.ONE; BigInteger Vl = ECConstants.TWO; BigInteger Vh = P; BigInteger Ql = ECConstants.ONE; BigInteger Qh = ECConstants.ONE; for (int j = n - 1; j >= s + 1; --j) { Ql = Ql.multiply(Qh).mod(p); if (k.testBit(j)) { Qh = Ql.multiply(Q).mod(p); Uh = Uh.multiply(Vh).mod(p); Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); } else { Qh = Ql; Uh = Uh.multiply(Vl).subtract(Ql).mod(p); Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); } } Ql = Ql.multiply(Qh).mod(p); Qh = Ql.multiply(Q).mod(p); Uh = Uh.multiply(Vl).subtract(Ql).mod(p); Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Ql = Ql.multiply(Qh).mod(p); for (int j = 1; j <= s; ++j) { Uh = Uh.multiply(Vl).mod(p); Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); Ql = Ql.multiply(Ql).mod(p); } return new BigInteger[]{ Uh, Vl }; } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof ECFieldElement.Fp)) { return false; } ECFieldElement.Fp o = (ECFieldElement.Fp)other; return q.equals(o.q) && x.equals(o.x); } public int hashCode() { return q.hashCode() ^ x.hashCode(); } } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ public static class F2m extends ECFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen * according to X9.62. GNB is not implemented at present. */ public static final int GNB = 1; /** * Indicates trinomial basis representation (TPB). Number chosen * according to X9.62. */ public static final int TPB = 2; /** * Indicates pentanomial basis representation (PPB). Number chosen * according to X9.62. */ public static final int PPB = 3; /** * TPB or PPB. */ private int representation; /** * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. */ private int m; /** * TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k1; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k2; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k3; /** * Constructor for PPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2m( int m, int k1, int k2, int k3, BigInteger x) { super(x); if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { if (k2 >= k3) { throw new IllegalArgumentException( "k2 must be smaller than k3"); } if (k2 <= 0) { throw new IllegalArgumentException( "k2 must be larger than 0"); } this.representation = PPB; } if (x.signum() < 0) { throw new IllegalArgumentException("x value cannot be negative"); } this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; } /** * Constructor for TPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2m(int m, int k, BigInteger x) { // Set k1 to k, and set k2 and k3 to 0 this(m, k, 0, 0, x); } public String getFieldName() { return "F2m"; } public static void checkFieldElements( ECFieldElement a, ECFieldElement b) { if ((!(a instanceof F2m)) || (!(b instanceof F2m))) { throw new IllegalArgumentException("Field elements are not " + "both instances of ECFieldElement.F2m"); } if ((a.x.signum() < 0) || (b.x.signum() < 0)) { throw new IllegalArgumentException( "x value may not be negative"); } ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) { throw new IllegalArgumentException("Field elements are not " + "elements of the same field F2m"); } if (aF2m.representation != bF2m.representation) { // Should never occur throw new IllegalArgumentException( "One of the field " + "elements are not elements has incorrect representation"); } } /** * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is * the reduction polynomial of <code>this</code>. * @param a The polynomial <code>a(z)</code> to be multiplied by * <code>z mod f(z)</code>. * @return <code>z * a(z) mod f(z)</code> */ private BigInteger multZModF(final BigInteger a) { // Left-shift of a(z) BigInteger az = a.shiftLeft(1); if (az.testBit(this.m)) { // If the coefficient of z^m in a(z) equals 1, reduction // modulo f(z) is performed: Add f(z) to to a(z): // Step 1: Unset mth coeffient of a(z) az = az.clearBit(this.m); // Step 2: Add r(z) to a(z), where r(z) is defined as // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // the non-zero coefficients in r(z) az = az.flipBit(0); az = az.flipBit(this.k1); if (this.representation == PPB) { az = az.flipBit(this.k2); az = az.flipBit(this.k3); } } return az; } public ECFieldElement add(final ECFieldElement b) { // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.x)); } public ECFieldElement subtract(final ECFieldElement b) { // Addition and subtraction are the same in F2m return add(b); } public ECFieldElement multiply(final ECFieldElement b) { // Left-to-right shift-and-add field multiplication in F2m // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // Output: c(z) = a(z) * b(z) mod f(z) // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); final BigInteger az = this.x; BigInteger bz = b.x; BigInteger cz; // Compute c(z) = a(z) * b(z) mod f(z) if (az.testBit(0)) { cz = bz; } else { cz = ECConstants.ZERO; } for (int i = 1; i < this.m; i++) { // b(z) := z * b(z) mod f(z) bz = multZModF(bz); if (az.testBit(i)) { // If the coefficient of x^i in a(z) equals 1, b(z) is added // to c(z) cz = cz.xor(bz); } } return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz); } public ECFieldElement divide(final ECFieldElement b) { // There may be more efficient implementations ECFieldElement bInv = b.invert(); return multiply(bInv); } public ECFieldElement negate() { // -x == x holds for all x in F2m, hence a copy of this is returned return new F2m(this.m, this.k1, this.k2, this.k3, this.x); } public ECFieldElement square() { // Naive implementation, can probably be speeded up using modular // reduction return multiply(this); } public ECFieldElement invert() { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) // u(z) := a(z) BigInteger uz = this.x; if (uz.signum() <= 0) { throw new ArithmeticException("x is zero or negative, " + "inversion is impossible"); } // v(z) := f(z) BigInteger vz = ECConstants.ONE.shiftLeft(m); vz = vz.setBit(0); vz = vz.setBit(this.k1); if (this.representation == PPB) { vz = vz.setBit(this.k2); vz = vz.setBit(this.k3); } // g1(z) := 1, g2(z) := 0 BigInteger g1z = ECConstants.ONE; BigInteger g2z = ECConstants.ZERO; // while u != 1 while (!(uz.equals(ECConstants.ZERO))) { // j := deg(u(z)) - deg(v(z)) int j = uz.bitLength() - vz.bitLength(); // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { final BigInteger uzCopy = uz; uz = vz; vz = uzCopy; final BigInteger g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) uz = uz.xor(vz.shiftLeft(j)); // g1(z) := g1(z) + z^j * g2(z) g1z = g1z.xor(g2z.shiftLeft(j)); // if (g1z.bitLength() > this.m) { // throw new ArithmeticException( // "deg(g1z) >= m, g1z = " + g1z.toString(2)); } return new ECFieldElement.F2m( this.m, this.k1, this.k2, this.k3, g2z); } public ECFieldElement sqrt() { throw new RuntimeException("Not implemented"); } /** * @return the representation of the field * <code>F<sub>2<sup>m</sup></sub></code>, either of * TPB (trinomial * basis representation) or * PPB (pentanomial * basis representation). */ public int getRepresentation() { return this.representation; } /** * @return the degree <code>m</code> of the reduction polynomial * <code>f(z)</code>. */ public int getM() { return this.m; } /** * @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK1() { return this.k1; } /** * @return TPB: Always returns <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK2() { return this.k2; } /** * @return TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK3() { return this.k3; } public String toString() { return this.x.toString(2); } public boolean equals(Object anObject) { if (anObject == this) { return true; } if (!(anObject instanceof ECFieldElement.F2m)) { return false; } ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) && (this.k3 == b.k3) && (this.representation == b.representation) && (this.x.equals(b.x))); } public int hashCode() { return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; } } }
package com.androsz.electricsleepbeta.app; import static com.androsz.electricsleepbeta.util.IntentUtil.shareSleep; import android.content.Intent; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.ViewFlipper; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.androsz.electricsleepbeta.R; import com.androsz.electricsleepbeta.alarmclock.AlarmClock; import com.androsz.electricsleepbeta.content.StartSleepReceiver; import com.androsz.electricsleepbeta.db.SleepSession; import com.androsz.electricsleepbeta.util.MathUtils; import com.androsz.electricsleepbeta.widget.SleepChart; /** * Front-door {@link Activity} that displays high-level features the application * offers to users. */ public class HomeActivity extends HostActivity implements LoaderManager.LoaderCallbacks<Cursor> { /* Warning - these values must remain consistent with activity_home. */ private static final int FLIP_INVISIBLE = 0; private static final int FLIP_NO_RECORDS = 1; private static final int FLIP_RECENT_RECORD = 2; private SleepChart sleepChart; @Override protected int getContentAreaLayoutId() { return R.layout.activity_home; } public void onAlarmsClick(final View v) { startActivity(new Intent(this, AlarmClock.class)); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(false); /* * new AsyncTask<Void, Void, Void>() { * * @Override protected Void doInBackground(Void... params) { final * SharedPreferences userPrefs = getSharedPreferences( * SettingsActivity.PREFERENCES_ENVIRONMENT, Context.MODE_PRIVATE); * final int prefsVersion = * userPrefs.getInt(SettingsActivity.PREFERENCES_ENVIRONMENT, 0); if * (prefsVersion == 0) { startActivity(new Intent(HomeActivity.this, * WelcomeTutorialWizardActivity.class) .putExtra("required", true)); } * else if (WelcomeTutorialWizardActivity * .enforceCalibrationBeforeStartingSleep(HomeActivity.this)) { } return * null; } }.execute(); */ sleepChart = (SleepChart) findViewById(R.id.home_sleep_chart); getSupportLoaderManager().initLoader(0, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(this, SleepSession.CONTENT_URI, null, null, null, SleepSession.START_TIMESTAMP + " DESC"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.menu_home, menu); ensureShareVisibleWhenDataAvailable(menu); return super.onCreateOptionsMenu(menu); } private void ensureShareVisibleWhenDataAvailable(Menu menu) { MenuItem mi = menu.findItem(R.id.menu_item_share_sleep_record); mi.setVisible(mSleepSession != null); // visible only if we have a // sleep session } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_share_sleep_record: if (mSleepSession != null) { shareSleep(mSleepSession, this); return true; } break; case android.R.id.home: return true; } return super.onOptionsItemSelected(item); } public void onHistoryClick(final View v) { startActivity(new Intent(this, HistoryActivity.class)); } @Override public void onLoaderReset(Loader<Cursor> arg0) { mSleepSession = null; // so that share sleep visibility is re-processed. invalidateOptionsMenu(); } private SleepSession mSleepSession; @Override public void onLoadFinished(Loader<Cursor> arg0, final Cursor cursor) { if (cursor == null || cursor.getCount() == 0) { mSleepSession = null; ViewFlipper flipper = (ViewFlipper) findViewById(R.id.content_view_flipper); flipper.setDisplayedChild(FLIP_NO_RECORDS); } else { final TextView avgScoreText = (TextView) findViewById(R.id.value_score_text); final TextView avgDurationText = (TextView) findViewById(R.id.value_duration_text); final TextView avgSpikesText = (TextView) findViewById(R.id.value_spikes_text); final TextView avgFellAsleepText = (TextView) findViewById(R.id.value_fell_asleep_text); cursor.moveToFirst(); mSleepSession = new SleepSession(cursor); try { sleepChart.sync(mSleepSession); } catch (IllegalArgumentException e) { e.printStackTrace(); } final long sleepChartRowId = cursor.getLong(0); sleepChart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent reviewSleepIntent = new Intent( HomeActivity.this, ReviewSleepActivity.class); final Uri data = Uri.withAppendedPath( SleepSession.CONTENT_URI, String.valueOf(sleepChartRowId)); reviewSleepIntent.setData(data); startActivity(reviewSleepIntent); } }); sleepChart.setMinimumHeight(MathUtils .getAbsoluteScreenHeightPx(HomeActivity.this) / 2 - 30); new AsyncTask<Void, Void, Void>() { int avgSleepScore = 0; long avgDuration = 0; int avgSpikes = 0; long avgFellAsleep = 0; @Override protected Void doInBackground(Void... params) { int count = 0; int fellAsleepCount = 0; do { count++; SleepSession sleepRecord = null; try { sleepRecord = new SleepSession(cursor); } catch (final CursorIndexOutOfBoundsException cioobe) { // there are no records! return null; } avgSleepScore += sleepRecord.getSleepScore(); avgDuration += sleepRecord.getDuration(); avgSpikes += sleepRecord.getSpikes(); long timeToFallAsleep = sleepRecord .getTimeToFallAsleep(); if (timeToFallAsleep != SleepSession.DID_NOT_FALL_ASLEEP) { fellAsleepCount++; avgFellAsleep += sleepRecord.getTimeToFallAsleep(); } } while (cursor.moveToNext()); final float invCount = 1.0f / count; final float invFellAsleepCount = 1.0f / fellAsleepCount; avgSleepScore *= invCount; avgDuration *= invCount; avgSpikes *= invCount; avgFellAsleep *= invFellAsleepCount; return null; } @Override protected void onPostExecute(Void result) { avgScoreText.setText(avgSleepScore + "%"); avgDurationText.setText(SleepSession.getTimespanText( avgDuration, getResources())); avgSpikesText.setText(avgSpikes + ""); avgFellAsleepText.setText(SleepSession.getTimespanText( avgFellAsleep, getResources())); super.onPostExecute(result); } }.execute(); ViewFlipper flipper = (ViewFlipper) findViewById(R.id.content_view_flipper); flipper.setDisplayedChild(FLIP_RECENT_RECORD); } // so that share sleep visibility is re-processed. invalidateOptionsMenu(); } public void onSleepClick(final View v) throws Exception { sendBroadcast(new Intent(StartSleepReceiver.START_SLEEP)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.renderer; import org.broad.igv.feature.*; import org.broad.igv.track.RenderContext; import org.broad.igv.track.Track; import org.broad.igv.ui.FontManager; import org.broad.igv.ui.UIConstants; import org.broad.igv.util.SOLIDUtils; import java.awt.*; import java.util.*; /** * @author jrobinso */ public class SequenceRenderer implements Renderer { static Map<Character, Color> nucleotideColors = new HashMap(); static { //nucleotideColors.put('A', new Color(160, 160, 255)); //nucleotideColors.put('C', new Color(255, 140, 75)); //nucleotideColors.put('T', new Color(160, 255, 255)); //nucleotideColors.put('G', new Color(255, 112, 112)); //nucleotideColors.put('N', Color.gray); nucleotideColors.put('A', Color.GREEN); nucleotideColors.put('a', Color.GREEN); nucleotideColors.put('C', Color.BLUE); nucleotideColors.put('c', Color.BLUE); nucleotideColors.put('T', Color.RED); nucleotideColors.put('t', Color.RED); nucleotideColors.put('G', new Color(209, 113, 5)); nucleotideColors.put('g', new Color(209, 113, 5)); nucleotideColors.put('N', Color.gray); nucleotideColors.put('n', Color.gray); } protected TranslatedSequenceDrawer translatedSequenceDrawer; //are we rendering positive or negative strand? protected Strand strand = Strand.POSITIVE; public SequenceRenderer() { translatedSequenceDrawer = new TranslatedSequenceDrawer(); } /** * @param context * @param trackRectangle * @param showColorSpace * @param showTranslation Should we show the translated amino acids? */ public void draw(RenderContext context, Rectangle trackRectangle, boolean showColorSpace, boolean showTranslation) { if (context.getScale() >= 1) { // Zoomed out too far to see sequences. This can happen when in gene list view and one of the frames // is zoomed in but others are not context.getGraphic2DForColor(UIConstants.VERY_LIGHT_GRAY).fill(trackRectangle); } else { double locScale = context.getScale(); double origin = context.getOrigin(); String chr = context.getChr(); String genome = context.getGenomeId(); //The location of the first base that is loaded, which may include padding around what's visible int start = Math.max(0, (int) origin - 1); //The location of the last base that is loaded int end = (int) (origin + trackRectangle.width * locScale) + 1; int firstVisibleNucleotideStart = start; int lastVisibleNucleotideEnd = end; int firstCodonOffset = 0; int lastCodonOffset = 0; //If we're translating, we need to start with the first bp of the first codon, in frame 3, and //end with the last bp of the last codon, in frame 1 if (showTranslation) { firstCodonOffset = 2; start -= firstCodonOffset; lastCodonOffset = 2; end += lastCodonOffset; } byte[] seq = SequenceManager.readSequence(genome, chr, start, end); //The combined height of sequence and (optionally) colorspace bands int untranslatedSequenceHeight = (int) trackRectangle.getHeight(); if (showTranslation) { untranslatedSequenceHeight = showColorSpace ? (int) trackRectangle.getHeight() / 5 * 2 : (int) (trackRectangle.getHeight() / 4); // Draw translated sequence Rectangle translatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y + untranslatedSequenceHeight, (int) trackRectangle.getWidth(), (int) trackRectangle.getHeight() - untranslatedSequenceHeight); translatedSequenceDrawer.draw(context, start, translatedSequenceRect, seq, strand); } //Rectangle containing the sequence and (optionally) colorspace bands Rectangle untranslatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y, (int) trackRectangle.getWidth(), untranslatedSequenceHeight); byte[] seqCS = null; if (showColorSpace) { seqCS = SOLIDUtils.convertToColorSpace(seq); } if (seq != null && seq.length > 0) { int hCS = (showColorSpace ? untranslatedSequenceRect.height / 2 : 0); int yBase = hCS + untranslatedSequenceRect.y + 2; int yCS = untranslatedSequenceRect.y + 2; int dY = (showColorSpace ? hCS : untranslatedSequenceRect.height) - 4; int dX = (int) (1.0 / locScale); // Create a graphics to use Graphics2D g = (Graphics2D) context.getGraphics().create(); //dhmay adding check for adequate track height int fontSize = Math.min(untranslatedSequenceRect.height, Math.min(dX, 12)); if (fontSize >= 8) { Font f = FontManager.getScalableFont(Font.BOLD, fontSize); g.setFont(f); } // Loop through base pair coordinates for (int loc = firstVisibleNucleotideStart; loc < lastVisibleNucleotideEnd; loc++) { int idx = loc - start; int pX0 = (int) ((loc - origin) / locScale); char c = (char) seq[idx]; if (Strand.NEGATIVE.equals(strand)) c = complementChar(c); Color color = nucleotideColors.get(c); if (fontSize >= 8) { if (color == null) { color = Color.black; } g.setColor(color); drawCenteredText(g, new char[]{c}, pX0, yBase + 2, dX, dY - 2); if (showColorSpace) { // draw color space #. Color space is shifted to be between bases as it represents // two bases. g.setColor(Color.black); String cCS = String.valueOf(seqCS[idx]); drawCenteredText(g, cCS.toCharArray(), pX0 - dX / 2, yCS + 2, dX, dY - 2); } } else { int bw = Math.max(1, dX - 1); if (color != null) { g.setColor(color); g.fillRect(pX0, yBase, bw, dY); } } } } } } /** * complement a nucleotide. If not ATGC, return the intput char * * @param inputChar * @return */ protected char complementChar(char inputChar) { switch (inputChar) { case 'A': return 'T'; case 'T': return 'A'; case 'G': return 'C'; case 'C': return 'G'; default: return inputChar; } } private void drawCenteredText(Graphics2D g, char[] chars, int x, int y, int w, int h) { // Get measures needed to center the message FontMetrics fm = g.getFontMetrics(); // How many pixels wide is the string int msg_width = fm.charsWidth(chars, 0, 1); // How far above the baseline can the font go? int ascent = fm.getMaxAscent(); // How far below the baseline? int descent = fm.getMaxDescent(); // Use the string width to find the starting point int msgX = x + w / 2 - msg_width / 2; // Use the vertical height of this font to find // the vertical starting coordinate int msgY = y + h / 2 - descent / 2 + ascent / 2; g.drawChars(chars, 0, 1, msgX, msgY); } public void renderBorder(Track track, RenderContext context, Rectangle rect) { } public void renderAxis(Track track, RenderContext context, Rectangle rect) { } public void setOverlayMode(boolean overlayMode) { } public Color getDefaultColor() { return Color.BLACK; } public Strand getStrand() { return strand; } public void setStrand(Strand strand) { this.strand = strand; } /** * @author Damon May * This class draws three amino acid bands representing the 3-frame translation of one strand * of the associated SequenceTrack */ public static class TranslatedSequenceDrawer { public static final int HEIGHT_PER_BAND = 14; public static final int TOTAL_HEIGHT = 3 * HEIGHT_PER_BAND; //alternating colors for aminoacids public static final Color AA_COLOR_1 = new Color(128, 128, 128); public static final Color AA_COLOR_2 = new Color(170, 170, 170); public static final Color AA_FONT_COLOR = Color.WHITE; //minimum font size for drawing AA characters public static final int MIN_FONT_SIZE = 6; //minimum vertical buffer around AA characters in band public static final int MIN_FONT_VBUFFER = 1; //ideal vertical buffer around AA characters in band public static final int IDEAL_FONT_VBUFFER = 2; protected static final Color STOP_CODON_COLOR = Color.RED; protected static final Color METHIONINE_COLOR = Color.GREEN; protected static final Color NUCLEOTIDE_SEPARATOR_COLOR = new Color(150, 150, 150, 120); /** * @param context * @param start Must be the first base involved in any codon that's even partially visible * @param trackRectangle * @param seq */ public void draw(RenderContext context, int start, Rectangle trackRectangle, byte[] seq, Strand strand) { //each band gets 1/3 of the height, rounded int idealHeightPerBand = trackRectangle.height / 3; //In this situation, band height is more equal if we tweak things a bit if (trackRectangle.height % 3 == 2) idealHeightPerBand++; int minHeightPerBand = Math.min(idealHeightPerBand, trackRectangle.height - (2 * idealHeightPerBand)); double locScale = context.getScale(); double origin = context.getOrigin(); //Figure out the dimensions of a single box containing an aminoacid, at this zoom int oneAcidBoxWidth = getPixelFromChromosomeLocation(context.getChr(), 3, origin, locScale) - getPixelFromChromosomeLocation(context.getChr(), 0, origin, locScale) + 1; int oneAcidBoxMinDimension = Math.min(oneAcidBoxWidth, minHeightPerBand); //Calculate the font size. If that's less than MIN_FONT_SIZE, we won't draw amino acids int fontSize = 0; boolean shouldDrawLetters = false; if (oneAcidBoxMinDimension >= 2 * MIN_FONT_VBUFFER + MIN_FONT_SIZE) { int idealFontSize = oneAcidBoxMinDimension - 2 * IDEAL_FONT_VBUFFER; fontSize = Math.max(idealFontSize, MIN_FONT_SIZE); shouldDrawLetters = true; } boolean shouldDrawNucleotideLines = shouldDrawLetters && oneAcidBoxWidth >= 2.5 * fontSize; Rectangle bandRectangle = new Rectangle(trackRectangle.x, 0, trackRectangle.width, 0); int heightAlreadyUsed = 0; //rf 0 bandRectangle.y = trackRectangle.y; bandRectangle.height = idealHeightPerBand; heightAlreadyUsed += bandRectangle.height; //This set collects the X positions for nucleotide lines, if we choose to draw them. //Technically we could calculate these, but I haven't managed to do that without some wiggle Set<Integer> nucleotideLineXPositions = new HashSet<Integer>(); //only draw nucleotide lines the last time this is called drawOneTranslation(context, start, bandRectangle, 0, shouldDrawLetters, fontSize, nucleotideLineXPositions, seq, strand); //rf 1 bandRectangle.y = trackRectangle.y + heightAlreadyUsed; bandRectangle.height = idealHeightPerBand; heightAlreadyUsed += bandRectangle.height; drawOneTranslation(context, start, bandRectangle, 1, shouldDrawLetters, fontSize, nucleotideLineXPositions, seq, strand); //rf 2 bandRectangle.y = trackRectangle.y + heightAlreadyUsed; bandRectangle.height = trackRectangle.height - heightAlreadyUsed; drawOneTranslation(context, start, bandRectangle, 2, shouldDrawLetters, fontSize, nucleotideLineXPositions, seq, strand); if (shouldDrawNucleotideLines) { Graphics2D graphicsForNucleotideLines = context.getGraphic2DForColor(NUCLEOTIDE_SEPARATOR_COLOR); //use a dashed stroke graphicsForNucleotideLines.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{1, 2}, 0)); int topYCoord = trackRectangle.y - 1; for (int xVal : nucleotideLineXPositions) { if (xVal >= trackRectangle.x && xVal <= trackRectangle.x + trackRectangle.width) graphicsForNucleotideLines.drawLine(xVal, topYCoord, xVal, topYCoord + trackRectangle.height); } } } /** * Draw the band representing a translation of the sequence in one reading frame * * @param context * @param start the index of the first base in seq. Should be the first nucleotide that's in a codon * that's even partially visible, in any frame * @param bandRectangle * @param readingFrame * @param shouldDrawLetters * @param fontSize * @param nucleotideLineXPositions a Set that will accrue all of the x positions that we define here * @param seq nucleotide sequence starting at start * for the beginning and end of aminoacid boxes */ protected void drawOneTranslation(RenderContext context, int start, Rectangle bandRectangle, int readingFrame, boolean shouldDrawLetters, int fontSize, Set<Integer> nucleotideLineXPositions, byte[] seq, Strand strand) { double locScale = context.getScale(); double origin = context.getOrigin(); Graphics2D fontGraphics = (Graphics2D) context.getGraphic2DForColor(AA_FONT_COLOR).create(); //The start location of the first codon that overlaps this region int readingFrameOfFullSeq = start % 3; int indexOfFirstCodonStart = readingFrame - readingFrameOfFullSeq; if (indexOfFirstCodonStart < 0) indexOfFirstCodonStart += 3; if (seq != null && seq.length > 0) { Graphics2D g = (Graphics2D) context.getGraphics().create(); String nucSequence = new String(seq, indexOfFirstCodonStart, seq.length - indexOfFirstCodonStart); java.util.List<AminoAcid> acids = AminoAcidManager.getAminoAcids(nucSequence, strand); // Set the start position of this amino acid. AminoAcidSequence aaSequence = new AminoAcidSequence(strand, start + indexOfFirstCodonStart, acids); if ((aaSequence != null) && aaSequence.hasNonNullSequence()) { //This rectangle holds a single AA glyph. x and width will be updated in the for loop Rectangle aaRect = new Rectangle(0, bandRectangle.y, 1, bandRectangle.height); //start position for this amino acid. Will increment in for loop below int aaSeqStartPosition = aaSequence.getStartPosition(); //calculated oddness or evenness of first amino acid int firstFullAcidIndex = (int) Math.floor((aaSeqStartPosition - readingFrame) / 3); boolean odd = (firstFullAcidIndex % 2) == 1; if (shouldDrawLetters) { Font f = FontManager.getScalableFont(Font.BOLD, fontSize); g.setFont(f); } for (AminoAcid acid : aaSequence.getSequence()) { if (acid != null) { //calculate x pixel boundaries of this AA rectangle int px = getPixelFromChromosomeLocation(context.getChr(), aaSeqStartPosition, origin, locScale); int px2 = getPixelFromChromosomeLocation(context.getChr(), aaSeqStartPosition + 3, origin, locScale); //if x boundaries of this AA overlap the band rectangle if ((px <= bandRectangle.getMaxX()) && (px2 >= bandRectangle.getX())) { aaRect.x = px; aaRect.width = px2 - px; nucleotideLineXPositions.add(aaRect.x); nucleotideLineXPositions.add(aaRect.x + aaRect.width); Graphics2D bgGraphics = context.getGraphic2DForColor(getColorForAminoAcid(acid.getSymbol(), odd)); bgGraphics.fill(aaRect); if (shouldDrawLetters) { String acidString = new String(new char[]{acid.getSymbol()}); GraphicUtils.drawCenteredText(acidString, aaRect, fontGraphics); } } //need to switch oddness whether we displayed the AA or not, //because oddness is calculated from first AA odd = !odd; aaSeqStartPosition += 3; } } } } } protected Color getColorForAminoAcid(char acidSymbol, boolean odd) { switch (acidSymbol) { case 'M': return METHIONINE_COLOR; case 'X': return STOP_CODON_COLOR; default: return odd ? AA_COLOR_1 : AA_COLOR_2; } } protected int getPixelFromChromosomeLocation(String chr, int chromosomeLocation, double origin, double locationScale) { return (int) Math.round((chromosomeLocation - origin) / locationScale); } public Color getDefaultColor() { return Color.BLACK; } } }
package org.jcodings.specific; import org.jcodings.Config; import org.jcodings.ISOEncoding; import org.jcodings.IntHolder; import org.jcodings.constants.CharacterType; public final class ISO8859_5Encoding extends ISOEncoding { protected ISO8859_5Encoding() { super("ISO-8859-5", ISO8859_5CtypeTable, ISO8859_5ToLowerCaseTable, ISO8859_5CaseFoldMap, false); } @Override public int caseMap(IntHolder flagP, byte[] bytes, IntHolder pp, int end, byte[] to, int toP, int toEnd) { int toStart = toP; int flags = flagP.value; while (pp.value < end && toP < toEnd) { int code = bytes[pp.value++] & 0xff; if ((ISO8859_5CtypeTable[code] & CharacterType.BIT_UPPER) != 0 && (flags & (Config.CASE_DOWNCASE | Config.CASE_FOLD)) != 0) { flags |= Config.CASE_MODIFIED; code = LowerCaseTable[code]; } else if ((ISO8859_5CtypeTable[code] & CharacterType.BIT_LOWER) != 0 && (flags & Config.CASE_UPCASE) != 0) { flags |= Config.CASE_MODIFIED; if (0xF1 <= code && code <= 0xFF) { code -= 0x50; } else { code -= 0x20; } } to[toP++] = (byte)code; if ((flags & Config.CASE_TITLECASE) != 0) { flags ^= (Config.CASE_UPCASE | Config.CASE_DOWNCASE | Config.CASE_TITLECASE); } } flagP.value = flags; return toP - toStart; } @Override public int mbcCaseFold(int flag, byte[]bytes, IntHolder pp, int end, byte[]lower) { int p = pp.value; lower[0] = LowerCaseTable[bytes[p] & 0xff]; pp.value++; return 1; } @Override public final byte[]toLowerCaseTable() { return LowerCaseTable; } static final short ISO8859_5CtypeTable[] = { 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x420c, 0x4209, 0x4208, 0x4208, 0x4208, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4284, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x51a0, 0x41a0, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x4008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0284, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x01a0, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x00a0, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x00a0, 0x30e2, 0x30e2 }; static final byte ISO8859_5ToLowerCaseTable[] = new byte[]{ (byte)'\000', (byte)'\001', (byte)'\002', (byte)'\003', (byte)'\004', (byte)'\005', (byte)'\006', (byte)'\007', (byte)'\010', (byte)'\011', (byte)'\012', (byte)'\013', (byte)'\014', (byte)'\015', (byte)'\016', (byte)'\017', (byte)'\020', (byte)'\021', (byte)'\022', (byte)'\023', (byte)'\024', (byte)'\025', (byte)'\026', (byte)'\027', (byte)'\030', (byte)'\031', (byte)'\032', (byte)'\033', (byte)'\034', (byte)'\035', (byte)'\036', (byte)'\037', (byte)'\040', (byte)'\041', (byte)'\042', (byte)'\043', (byte)'\044', (byte)'\045', (byte)'\046', (byte)'\047', (byte)'\050', (byte)'\051', (byte)'\052', (byte)'\053', (byte)'\054', (byte)'\055', (byte)'\056', (byte)'\057', (byte)'\060', (byte)'\061', (byte)'\062', (byte)'\063', (byte)'\064', (byte)'\065', (byte)'\066', (byte)'\067', (byte)'\070', (byte)'\071', (byte)'\072', (byte)'\073', (byte)'\074', (byte)'\075', (byte)'\076', (byte)'\077', (byte)'\100', (byte)'\141', (byte)'\142', (byte)'\143', (byte)'\144', (byte)'\145', (byte)'\146', (byte)'\147', (byte)'\150', (byte)'\151', (byte)'\152', (byte)'\153', (byte)'\154', (byte)'\155', (byte)'\156', (byte)'\157', (byte)'\160', (byte)'\161', (byte)'\162', (byte)'\163', (byte)'\164', (byte)'\165', (byte)'\166', (byte)'\167', (byte)'\170', (byte)'\171', (byte)'\172', (byte)'\133', (byte)'\134', (byte)'\135', (byte)'\136', (byte)'\137', (byte)'\140', (byte)'\141', (byte)'\142', (byte)'\143', (byte)'\144', (byte)'\145', (byte)'\146', (byte)'\147', (byte)'\150', (byte)'\151', (byte)'\152', (byte)'\153', (byte)'\154', (byte)'\155', (byte)'\156', (byte)'\157', (byte)'\160', (byte)'\161', (byte)'\162', (byte)'\163', (byte)'\164', (byte)'\165', (byte)'\166', (byte)'\167', (byte)'\170', (byte)'\171', (byte)'\172', (byte)'\173', (byte)'\174', (byte)'\175', (byte)'\176', (byte)'\177', (byte)'\200', (byte)'\201', (byte)'\202', (byte)'\203', (byte)'\204', (byte)'\205', (byte)'\206', (byte)'\207', (byte)'\210', (byte)'\211', (byte)'\212', (byte)'\213', (byte)'\214', (byte)'\215', (byte)'\216', (byte)'\217', (byte)'\220', (byte)'\221', (byte)'\222', (byte)'\223', (byte)'\224', (byte)'\225', (byte)'\226', (byte)'\227', (byte)'\230', (byte)'\231', (byte)'\232', (byte)'\233', (byte)'\234', (byte)'\235', (byte)'\236', (byte)'\237', (byte)'\240', (byte)'\361', (byte)'\362', (byte)'\363', (byte)'\364', (byte)'\365', (byte)'\366', (byte)'\367', (byte)'\370', (byte)'\371', (byte)'\372', (byte)'\373', (byte)'\374', (byte)'\255', (byte)'\376', (byte)'\377', (byte)'\320', (byte)'\321', (byte)'\322', (byte)'\323', (byte)'\324', (byte)'\325', (byte)'\326', (byte)'\327', (byte)'\330', (byte)'\331', (byte)'\332', (byte)'\333', (byte)'\334', (byte)'\335', (byte)'\336', (byte)'\337', (byte)'\340', (byte)'\341', (byte)'\342', (byte)'\343', (byte)'\344', (byte)'\345', (byte)'\346', (byte)'\347', (byte)'\350', (byte)'\351', (byte)'\352', (byte)'\353', (byte)'\354', (byte)'\355', (byte)'\356', (byte)'\357', (byte)'\320', (byte)'\321', (byte)'\322', (byte)'\323', (byte)'\324', (byte)'\325', (byte)'\326', (byte)'\327', (byte)'\330', (byte)'\331', (byte)'\332', (byte)'\333', (byte)'\334', (byte)'\335', (byte)'\336', (byte)'\337', (byte)'\340', (byte)'\341', (byte)'\342', (byte)'\343', (byte)'\344', (byte)'\345', (byte)'\346', (byte)'\347', (byte)'\350', (byte)'\351', (byte)'\352', (byte)'\353', (byte)'\354', (byte)'\355', (byte)'\356', (byte)'\357', (byte)'\360', (byte)'\361', (byte)'\362', (byte)'\363', (byte)'\364', (byte)'\365', (byte)'\366', (byte)'\367', (byte)'\370', (byte)'\371', (byte)'\372', (byte)'\373', (byte)'\374', (byte)'\375', (byte)'\376', (byte)'\377' }; static final int ISO8859_5CaseFoldMap[][] = { { 0xa1, 0xf1 }, { 0xa2, 0xf2 }, { 0xa3, 0xf3 }, { 0xa4, 0xf4 }, { 0xa5, 0xf5 }, { 0xa6, 0xf6 }, { 0xa7, 0xf7 }, { 0xa8, 0xf8 }, { 0xa9, 0xf9 }, { 0xaa, 0xfa }, { 0xab, 0xfb }, { 0xac, 0xfc }, { 0xae, 0xfe }, { 0xaf, 0xff }, { 0xb0, 0xd0 }, { 0xb1, 0xd1 }, { 0xb2, 0xd2 }, { 0xb3, 0xd3 }, { 0xb4, 0xd4 }, { 0xb5, 0xd5 }, { 0xb6, 0xd6 }, { 0xb7, 0xd7 }, { 0xb8, 0xd8 }, { 0xb9, 0xd9 }, { 0xba, 0xda }, { 0xbb, 0xdb }, { 0xbc, 0xdc }, { 0xbd, 0xdd }, { 0xbe, 0xde }, { 0xbf, 0xdf }, { 0xc0, 0xe0 }, { 0xc1, 0xe1 }, { 0xc2, 0xe2 }, { 0xc3, 0xe3 }, { 0xc4, 0xe4 }, { 0xc5, 0xe5 }, { 0xc6, 0xe6 }, { 0xc7, 0xe7 }, { 0xc8, 0xe8 }, { 0xc9, 0xe9 }, { 0xca, 0xea }, { 0xcb, 0xeb }, { 0xcc, 0xec }, { 0xcd, 0xed }, { 0xce, 0xee }, { 0xcf, 0xef } }; public static final ISO8859_5Encoding INSTANCE = new ISO8859_5Encoding(); }
package com.dmdirc.ui.swing.dialogs.wizard; import com.dmdirc.ui.swing.components.EtchedLineBorder; import com.dmdirc.ui.swing.components.EtchedLineBorder.BorderSide; import com.dmdirc.util.ListenerList; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.Serializable; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import net.miginfocom.swing.MigLayout; /** * Wizard panel. */ public class WizardPanel extends JPanel implements ActionListener, Serializable { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 2; /** Step panel list. */ private final StepLayout steps; /** Wizard title. */ private final String title; /** Wizard. */ private final transient WizardListener wizard; /** Step panel. */ private JPanel stepsPanel; /** Title panel. */ private JLabel titleLabel; /** Current step. */ private int currentStep; /** Prevous step button. */ private JButton prev; /** Next step button. */ private JButton next; /** Progress label. */ private JLabel progressLabel; /** Step Listeners. */ private ListenerList stepListeners; /** * Creates a new instance of WizardPanel. * * @param title Title for the wizard * @param steps Steps for the wizard * @param wizard Wizard to inform of changes */ public WizardPanel(final String title, final List<Step> steps, final WizardListener wizard) { super(); stepListeners = new ListenerList(); this.title = title; this.steps = new StepLayout(); this.wizard = wizard; initComponents(); layoutComponents(); for (Step step : steps) { addStep(step); } } /** Initialises the components. */ private void initComponents() { titleLabel = new JLabel(title); stepsPanel = new JPanel(steps); titleLabel.setFont(titleLabel.getFont(). deriveFont((float) (titleLabel.getFont().getSize() * 1.5))); progressLabel = new JLabel(); next = new JButton(); prev = new JButton("\u00AB Previous"); next.setText("Next \u00BB"); next.addActionListener(this); prev.addActionListener(this); } /** Lays out the components. */ private void layoutComponents() { final JPanel titlePanel = new JPanel(new MigLayout("fill")); titlePanel.add(titleLabel, "growx, wrap"); titlePanel.setBackground(Color.WHITE); titlePanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)); titlePanel.setBorder(new EtchedLineBorder(EtchedBorder.LOWERED, BorderSide.BOTTOM)); final JPanel progressPanel = new JPanel(new MigLayout("fill")); progressPanel.add(progressLabel, "growx"); progressPanel.add(prev, "sg button"); progressPanel.add(next, "sg button"); progressPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.BLACK)); progressPanel.setBorder(new EtchedLineBorder(EtchedBorder.LOWERED, BorderSide.TOP)); setLayout(new MigLayout("fill, wrap 1, ins 0")); add(titlePanel, "growx"); add(stepsPanel, "grow"); add(progressPanel, "growx"); } /** Displays the wizard. */ public void display() { if (!steps.isEmpty()) { steps.first(stepsPanel); currentStep = 0; prev.setEnabled(false); if (steps.size() == 1) { next.setText("Finish"); } updateProgressLabel(); } } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getSource() == next) { nextStep(); } else if (e.getSource() == prev) { prevStep(); } } /** * Adds a step to the wizard. * * @param step Step to add */ public void addStep(final Step step) { stepsPanel.add(step, step.toString()); } /** * Enables or disables the "next step" button. * * @param newValue boolean true to make "next" button enabled, else false */ public void enableNextStep(final boolean newValue) { next.setEnabled(newValue); } /** * Enables or disables the "previous step" button. * * @param newValue boolean true to make "previous" button enabled, else false */ public void enablePreviousStep(final boolean newValue) { prev.setEnabled(newValue); } /** Moves to the next step. */ protected void nextStep() { if ("Next \u00BB".equals(next.getText())) { prev.setEnabled(true); fireStepAboutToBeDisplayed(steps.getStep(currentStep + 1)); steps.next(stepsPanel); fireStepHidden(steps.getStep(currentStep)); currentStep++; if (currentStep == steps.size() - 1) { next.setText("Finish"); } updateProgressLabel(); } else if ("Finish".equals(next.getText())) { fireWizardFinished(); } } /** Moves to the previous step. */ protected void prevStep() { fireStepAboutToBeDisplayed(steps.getStep(currentStep - 1)); steps.previous(stepsPanel); fireStepHidden(steps.getStep(currentStep)); currentStep if (currentStep == 0) { prev.setEnabled(false); } next.setText("Next \u00BB"); updateProgressLabel(); } /** * Returns the step at the specified index. * * @param stepNumber step number * * @return Specified step. */ public Step getStep(final int stepNumber) { return steps.getStep(stepNumber); } /** * Returns the current step. * * @return Current step number */ public int getCurrentStep() { return currentStep; } /** Updates the progress label. */ private void updateProgressLabel() { progressLabel.setText("Step " + (currentStep + 1) + " of " + steps.size()); } /** * Adds a step listener to the list. * * @param listener */ public void addStepListener(final StepListener listener) { synchronized (stepListeners) { stepListeners.add(StepListener.class, listener); } } /** * Removes a step listener from the list. * * @param listener */ public void removeStepListener(final StepListener listener) { synchronized (stepListeners) { stepListeners.remove(StepListener.class, listener); } } /** * Adds a wizard listener to the list. * * @param listener */ public void addWizardListener(final WizardListener listener) { synchronized (stepListeners) { stepListeners.add(WizardListener.class, listener); } } /** * Removes a wizard listener from the list. * * @param listener */ public void removeWizardListener(final WizardListener listener) { synchronized (stepListeners) { stepListeners.remove(WizardListener.class, listener); } } /** * Fires step about to be displayed events. * * @param step Step to be displayed */ private void fireStepAboutToBeDisplayed(final Step step) { synchronized (stepListeners) { List<StepListener> listeners = stepListeners.get(StepListener.class); for (StepListener listener : listeners) { listener.stepAboutToDisplay(step); } } } /** * Fires step hidden events. * * @param step step thats been hidden */ private void fireStepHidden(final Step step) { synchronized (stepListeners) { List<StepListener> listeners = stepListeners.get(StepListener.class); for (StepListener listener : listeners) { listener.stepHidden(step); } } } /** * Fires wizard finished events. */ private void fireWizardFinished() { synchronized (stepListeners) { List<WizardListener> listeners = stepListeners.get(WizardListener.class); for (WizardListener listener : listeners) { System.out.println("finished: " + listener); listener.wizardFinished(); } } } /** * Fires wizard cancelled events. */ protected void fireWizardCancelled() { synchronized (stepListeners) { List<WizardListener> listeners = stepListeners.get(WizardListener.class); for (WizardListener listener : listeners) { System.out.println("cancelled: " + listener); listener.wizardCancelled(); } } } }
package com.ecyrd.jspwiki.attachment; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.io.File; import java.util.Properties; import java.util.Collection; import java.util.Date; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.TranslatorReader; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiPage; import com.ecyrd.jspwiki.WikiProvider; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.PageManager; import com.ecyrd.jspwiki.NoRequiredPropertyException; import com.ecyrd.jspwiki.providers.WikiAttachmentProvider; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.util.ClassUtil; public class AttachmentManager { /** * The property name for defining the attachment provider class name. */ public static final String PROP_PROVIDER = "jspwiki.attachmentProvider"; /** * The maximum size of attachments that can be uploaded. */ public static final String PROP_MAXSIZE = "jspwiki.attachment.maxsize"; static Logger log = Logger.getLogger( AttachmentManager.class ); private WikiAttachmentProvider m_provider; private WikiEngine m_engine; /** * Creates a new AttachmentManager. Note that creation will never fail, * but it's quite likely that attachments do not function. * <p> * <b>DO NOT CREATE</b> an AttachmentManager on your own, unless you really * know what you're doing. Just use WikiEngine.getAttachmentManager() if * you're making a module for JSPWiki. * * @param engine The wikiengine that owns this attachment manager. * @param props A list of properties from which the AttachmentManager will seek * its configuration. Typically this is the "jspwiki.properties". */ // FIXME: Perhaps this should fail somehow. public AttachmentManager( WikiEngine engine, Properties props ) { String classname; m_engine = engine; // If user wants to use a cache, then we'll use the CachingProvider. boolean useCache = "true".equals(props.getProperty( PageManager.PROP_USECACHE )); if( useCache ) { classname = "com.ecyrd.jspwiki.providers.CachingAttachmentProvider"; } else { classname = props.getProperty( PROP_PROVIDER ); } // If no class defined, then will just simply fail. if( classname == null ) { log.info( "No attachment provider defined - disabling attachment support." ); return; } // Create and initialize the provider. try { Class providerclass = ClassUtil.findClass( "com.ecyrd.jspwiki.providers", classname ); m_provider = (WikiAttachmentProvider)providerclass.newInstance(); m_provider.initialize( m_engine, props ); } catch( ClassNotFoundException e ) { log.error( "Attachment provider class not found",e); } catch( InstantiationException e ) { log.error( "Attachment provider could not be created", e ); } catch( IllegalAccessException e ) { log.error( "You may not access the attachment provider class", e ); } catch( NoRequiredPropertyException e ) { log.error( "Attachment provider did not find a property that it needed: "+e.getMessage(), e ); m_provider = null; // No, it did not work. } catch( IOException e ) { log.error( "Attachment provider reports IO error", e ); m_provider = null; } } /** * Returns true, if attachments are enabled and running. */ public boolean attachmentsEnabled() { return m_provider != null; } /** * Gets info on a particular attachment, latest version. * * @param name A full attachment name. * @return Attachment, or null, if no such attachment exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( String name ) throws ProviderException { return getAttachmentInfo( name, WikiProvider.LATEST_VERSION ); } /** * Gets info on a particular attachment with the given version. * * @param name A full attachment name. * @param version A version number. * @return Attachment, or null, if no such attachment or version exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( String name, int version ) throws ProviderException { if( name == null ) { return null; } return getAttachmentInfo( null, name, version ); } /** * Figures out the full attachment name from the context and * attachment name. * * @param context The current WikiContext * @param attachmentname The file name of the attachment. * @return Attachment, or null, if no such attachment exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( WikiContext context, String attachmentname ) throws ProviderException { return getAttachmentInfo( context, attachmentname, WikiProvider.LATEST_VERSION ); } /** * Figures out the full attachment name from the context and * attachment name. * * @param context The current WikiContext * @param attachmentname The file name of the attachment. * @param version A particular version. * @return Attachment, or null, if no such attachment or version exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( WikiContext context, String attachmentname, int version ) throws ProviderException { if( m_provider == null ) { return( null ); } WikiPage currentPage = null; if( context != null ) { currentPage = context.getPage(); } // Figure out the parent page of this attachment. If we can't find it, // we'll assume this refers directly to the attachment. int cutpt = attachmentname.lastIndexOf('/'); if( cutpt != -1 ) { String parentPage = attachmentname.substring(0,cutpt); parentPage = TranslatorReader.cleanLink( parentPage ); attachmentname = attachmentname.substring(cutpt+1); currentPage = m_engine.getPage( parentPage ); } // If the page cannot be determined, we cannot possibly find the // attachments. if( currentPage == null || currentPage.getName().length() == 0 ) { return null; } // System.out.println("Seeking info on "+currentPage+"::"+attachmentname); return m_provider.getAttachmentInfo( currentPage, attachmentname, version ); } /** * Returns the list of attachments associated with a given wiki page. * If there are no attachments, returns an empty Collection. * * @param wikipage The wiki page from which you are seeking attachments for. * @return a valid collection of attachments. */ public Collection listAttachments( WikiPage wikipage ) throws ProviderException { if( m_provider == null ) { return new ArrayList(); } return m_provider.listAttachments( wikipage ); } /** * Returns true, if the page has any attachments at all. This is * a convinience method. * * * @param wikipage The wiki page from which you are seeking attachments for. * @return True, if the page has attachments, else false. */ public boolean hasAttachments( WikiPage wikipage ) { try { return listAttachments( wikipage ).size() > 0; } catch( Exception e ) {} return false; } /** * Finds an attachment from the repository as a stream. * * @param att Attachment * @return An InputStream to read from. May return null, if * attachments are disabled. */ public InputStream getAttachmentStream( Attachment att ) throws IOException, ProviderException { if( m_provider == null ) { return( null ); } return m_provider.getAttachmentData( att ); } /** * Stores an attachment that lives in the given file. * If the attachment did not exist previously, this method * will create it. If it did exist, it stores a new version. * * @param att Attachment to store this under. * @param source A file to read from. * * @throws IOException If writing the attachment failed. * @throws ProviderException If something else went wrong. */ public void storeAttachment( Attachment att, File source ) throws IOException, ProviderException { FileInputStream in = null; try { in = new FileInputStream( source ); storeAttachment( att, in ); } finally { if( in != null ) in.close(); } } /** * Stores an attachment directly from a stream. * If the attachment did not exist previously, this method * will create it. If it did exist, it stores a new version. * * @param att Attachment to store this under. * @param in InputStream from which the attachment contents will be read. * * @throws IOException If writing the attachment failed. * @throws ProviderException If something else went wrong. */ public void storeAttachment( Attachment att, InputStream in ) throws IOException, ProviderException { if( m_provider == null ) { return; } m_provider.putAttachmentData( att, in ); m_engine.getReferenceManager().updateReferences( att.getName(), new java.util.Vector() ); m_engine.updateReferences( new WikiPage( att.getParentName() ) ); } /** * Returns a list of versions of the attachment. * * @param attachmentName A fully qualified name of the attachment. * * @return A list of Attachments. May return null, if attachments are * disabled. * @throws ProviderException If the provider fails for some reason. */ public List getVersionHistory( String attachmentName ) throws ProviderException { if( m_provider == null ) { return( null ); } Attachment att = getAttachmentInfo( (WikiContext)null, attachmentName ); if( att != null ) { return m_provider.getVersionHistory( att ); } return null; } /** * Returns a collection of Attachments, containing each and every attachment * that is in this Wiki. * * @return A collection of attachments. If attachments are disabled, will * return an empty collection. */ public Collection getAllAttachments() throws ProviderException { if( attachmentsEnabled() ) { return m_provider.listAllChanged( new Date(0L) ); } return new ArrayList(); } /** * Returns the current attachment provider. * * @return The current provider. May be null, if attachments are disabled. */ public WikiAttachmentProvider getCurrentProvider() { return m_provider; } /** * Deletes the given attachment version. */ public void deleteVersion( Attachment att ) throws ProviderException { m_provider.deleteVersion( att ); } /** * Deletes all versions of the given attachment. */ public void deleteAttachment( Attachment att ) throws ProviderException { m_provider.deleteAttachment( att ); } }
package org.opencms.ui.login; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.ui.A_CmsUI; import org.opencms.util.CmsFileUtil; import java.util.List; import com.vaadin.shared.ui.combobox.FilteringMode; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CustomComponent; /** * Widget used to allow the user to search and select an organizational unit.<p> */ public class CmsLoginOuSelector extends CustomComponent { /** Serial version id. */ private static final long serialVersionUID = 1L; /** The combo box containing the OU options. */ private ComboBox m_ouSelect = new ComboBox(); /** * Creates a new instance.<P> */ public CmsLoginOuSelector() { m_ouSelect.setWidth("100%"); setCompositionRoot(m_ouSelect); m_ouSelect.setFilteringMode(FilteringMode.CONTAINS); } /** * Gets the selected OU.<p< * * @return the selected OU */ public String getValue() { return (String)m_ouSelect.getValue(); } /** * Initializes the select options.<p> * * @param orgUnits the selectable OUs */ public void initOrgUnits(List<CmsOrganizationalUnit> orgUnits) { if ((orgUnits.size() == 1) && (orgUnits.get(0).getParentFqn() == null)) { setVisible(false); } for (CmsOrganizationalUnit ou : orgUnits) { String key = normalizeOuName(ou.getName()); m_ouSelect.addItem(key); m_ouSelect.setItemCaption(key, ou.getDisplayName(A_CmsUI.get().getLocale())); } } /** * Sets the selected OU.<p> * * @param value the OU to select */ public void setValue(String value) { m_ouSelect.setValue(normalizeOuName(value)); } /** * Normalizes a given OU name.<p> * * @param ou the OU name * @return the normalized version */ String normalizeOuName(String ou) { ou = CmsFileUtil.removeLeadingSeparator(ou); ou = CmsFileUtil.removeTrailingSeparator(ou); return ou; } }
package com.francelabs.datafari.servlets.admin; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import com.francelabs.datafari.constants.CodesReturned; import com.francelabs.datafari.service.db.UserDataService; import com.francelabs.datafari.user.User; /** * Servlet implementation class getAllUsersAndRoles */ @WebServlet("/SearchAdministrator/addUser") public class AddUser extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(AddUser.class.getName()); /** * @see HttpServlet#HttpServlet() */ public AddUser() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final JSONObject jsonResponse = new JSONObject(); request.setCharacterEncoding("utf8"); response.setContentType("application/json"); try { if (request.getParameter(UserDataService.USERNAMECOLUMN) != null && request.getParameter(UserDataService.PASSWORDCOLUMN) != null && request.getParameter(UserDataService.ROLECOLUMN + "[]") != null) { final User user = new User(request.getParameter(UserDataService.USERNAMECOLUMN).toString(), request.getParameter(UserDataService.PASSWORDCOLUMN).toString()); final int code = user.signup(Arrays.asList(request.getParameterValues(UserDataService.ROLECOLUMN + "[]"))); if (code == CodesReturned.ALLOK) { jsonResponse.put("code", CodesReturned.ALLOK).put("statut", "User deleted with success"); } else if (code == CodesReturned.USERALREADYINBASE) { jsonResponse.put("code", CodesReturned.USERALREADYINBASE).put("statut", "User already Signed up"); } else { jsonResponse.put("code", CodesReturned.PROBLEMCONNECTIONDATABASE).put("statut", "Problem with database"); } } else { jsonResponse.put("code", CodesReturned.PROBLEMQUERY).put("statut", "Problem with query"); } } catch (final JSONException e) { logger.error(e); } final PrintWriter out = response.getWriter(); out.print(jsonResponse); } }
package com.github.igotyou.FactoryMod; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.Repairable; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import com.github.igotyou.FactoryMod.FactoryObject.FactoryType; import com.github.igotyou.FactoryMod.interfaces.Properties; import com.github.igotyou.FactoryMod.listeners.FactoryModListener; import com.github.igotyou.FactoryMod.listeners.NoteStackListener; import com.github.igotyou.FactoryMod.listeners.RedstoneListener; import com.github.igotyou.FactoryMod.managers.FactoryModManager; import com.github.igotyou.FactoryMod.properties.NetherFactoryProperties; import com.github.igotyou.FactoryMod.properties.PrintingPressProperties; import com.github.igotyou.FactoryMod.properties.ProductionProperties; import com.github.igotyou.FactoryMod.recipes.ProbabilisticEnchantment; import com.github.igotyou.FactoryMod.recipes.ProductionRecipe; import com.github.igotyou.FactoryMod.utility.ItemList; import com.github.igotyou.FactoryMod.utility.NamedItemStack; public class FactoryModPlugin extends JavaPlugin { FactoryModManager manager; public static HashMap<String, ProductionProperties> productionProperties; public static HashMap<String,ProductionRecipe> productionRecipes; public PrintingPressProperties printingPressProperties; public NetherFactoryProperties netherFactoryProperties; public static final String VERSION = "v1.0"; //Current version of plugin public static final String PLUGIN_NAME = "FactoryMod"; //Name of plugin public static final String PLUGIN_PREFIX = PLUGIN_NAME + " " + VERSION + ": "; public static final String PRODUCTION_SAVES_FILE = "productionSaves"; // The production saves file name public static final int TICKS_PER_SECOND = 20; //The number of ticks per second public static final String PRINTING_PRESSES_SAVE_FILE = "pressSaves"; public static final String NETHER_FACTORY_SAVE_FILE = "netherSaves"; public static boolean DISABLE_PORTALS; public static int NETHER_SCALE; public static boolean ALLOW_REINFORCEMENT_CREATION_ABOVE_TELEPORT_PLATFORM; public static boolean ALLOW_BLOCK_PLACEMENT_ABOVE_TELEPORT_PLATFORM; public static boolean TELEPORT_PLATFORM_INVUNERABLE; public static boolean REGENERATE_TELEPORT_BLOCK_ON_TELEPORT; public static boolean REMOVE_BLOCK_ABOVE_TELEPORT_PLATFORM_ON_TELEPORT; public static String WORLD_NAME; public static String NETHER_NAME; public static int PRODUCER_UPDATE_CYCLE; public static boolean PRODUCTION_ENEABLED; public static int SAVE_CYCLE; public static Material CENTRAL_BLOCK_MATERIAL; public static boolean RETURN_BUILD_MATERIALS; public static boolean CITADEL_ENABLED; public static Material FACTORY_INTERACTION_MATERIAL; public static boolean DESTRUCTIBLE_FACTORIES; public static int NETHER_MARKER_MAX_DISTANCE; public static Material NETHER_FACTORY_TELEPORT_PLATFORM_MATERIAL; public static Material NETHER_FACTORY_MARKER_MATERIAL; public static boolean DISABLE_EXPERIENCE; public static long DISREPAIR_PERIOD; public static long REPAIR_PERIOD; public static boolean REDSTONE_START_ENABLED; public static boolean LEVER_OUTPUT_ENABLED; public static boolean SHOULD_SET_ANVIL_COST; public static int GET_SET_ANVIL_COST; public void onEnable() { plugin = this; //load the config.yml initConfig(); //create the main manager manager = new FactoryModManager(this); //register the events(this should be moved...) registerEvents(); } public void onDisable() { //call the disable method, this will save the data etc. manager.onDisable(); } public void registerEvents() { try { getServer().getPluginManager().registerEvents(new FactoryModListener(manager), this); getServer().getPluginManager().registerEvents(new RedstoneListener(manager, manager.getProductionManager()), this); getServer().getPluginManager().registerEvents(new NoteStackListener(this), this); } catch(Exception e) { e.printStackTrace(); } } public void initConfig() { sendConsoleMessage("Initiaiting FactoryMod Config."); productionProperties = new HashMap<String, ProductionProperties>(); productionRecipes = new HashMap<String,ProductionRecipe>(); FileConfiguration config = getConfig(); if(getConfig().getDefaults().getBoolean("copy_defaults", true)) { saveResource("config.yml",true); } this.saveDefaultConfig(); reloadConfig(); config = getConfig(); //what should the nether scaling be for the nether factorys? NETHER_SCALE = config.getInt("nether_general.nether_scale",8); //Should we Disable regular portals? DISABLE_PORTALS = config.getBoolean("nether_general.disable_portals", true); //Allow reinforcement above nether factory teleport platforms. ALLOW_REINFORCEMENT_CREATION_ABOVE_TELEPORT_PLATFORM = config.getBoolean("nether_general.allow_reinforcement_creation_above_teleport_platform", false); //Allow people to place blocks above nether factory teleport platforms. ALLOW_BLOCK_PLACEMENT_ABOVE_TELEPORT_PLATFORM = config.getBoolean("nether_general.allow_block_placement_above_teleport_platform", false); //Make teleport platforms unbreakable TELEPORT_PLATFORM_INVUNERABLE = config.getBoolean("nether_general.teleport_platform_invunerable",false); //Right before a player get's teleported, should the teleport platform be regenerated? REGENERATE_TELEPORT_BLOCK_ON_TELEPORT = config.getBoolean("nether_general.regenerate_teleport_block_on_teleport", false); //Right before a player get's teleported, should the blocks above the portal be destroyed(ignotes citadel)? REMOVE_BLOCK_ABOVE_TELEPORT_PLATFORM_ON_TELEPORT = config.getBoolean("nether_general.remove_blocks_above_teleport_platform_on_teleport", false); //what's the name of the overworld? WORLD_NAME = config.getString("nether_general.world_name", "world"); //what's the name of the overworld? NETHER_NAME = config.getString("nether_general.nether_name", "world_nether"); //how often should the managers save? SAVE_CYCLE = config.getInt("general.save_cycle",15)*60*20; //what's the material of the center block of factorys? CENTRAL_BLOCK_MATERIAL = Material.getMaterial(config.getString("general.central_block")); //what's the material of the nether portal teleportation platforms? NETHER_FACTORY_TELEPORT_PLATFORM_MATERIAL = Material.getMaterial(config.getString("nether_general.teleport_platform_material_nether_factory")); //what's the material of the marker blocks for nether factorys? NETHER_FACTORY_MARKER_MATERIAL = Material.getMaterial(config.getString("nether_general.marker_material_nether_factory")); //how far from the factory can the marker be? NETHER_MARKER_MAX_DISTANCE = config.getInt("nether_general.marker_max_distance"); //Return the build materials upon destruction of factory. RETURN_BUILD_MATERIALS = config.getBoolean("general.return_build_materials",false); //is citadel enabled? CITADEL_ENABLED = config.getBoolean("general.citadel_enabled",true); //what's the tool that we use to interact with the factorys? FACTORY_INTERACTION_MATERIAL = Material.getMaterial(config.getString("general.factory_interaction_material","STICK")); //If factories are removed upon destruction of their blocks DESTRUCTIBLE_FACTORIES=config.getBoolean("general.destructible_factories",false); //Check if XP drops should be disabled DISABLE_EXPERIENCE=config.getBoolean("general.disable_experience",false); //How frequently factories are updated PRODUCER_UPDATE_CYCLE = config.getInt("production_general.update_cycle",20); //Period of days before a factory is removed after it falls into disrepair DISREPAIR_PERIOD= config.getLong("general.disrepair_period",14)*24*60*60*1000; //The length of time it takes a factory to go to 0% health REPAIR_PERIOD = config.getLong("production_general.repair_period",28)*24*60*60*1000; //Disable recipes which result in the following items //Do we output the running state with a lever? LEVER_OUTPUT_ENABLED = config.getBoolean("general.lever_output_enabled",true); //Do we allow factories to be started with redstone? REDSTONE_START_ENABLED = config.getBoolean("general.redstone_start_enabled",true); //Set anvil repair cost SHOULD_SET_ANVIL_COST = config.getBoolean("general.should_default_anvil_cost", false); GET_SET_ANVIL_COST = config.getInt("general.set_default_anvil_cost", 37); int g = 0; Iterator<String> disabledRecipes=config.getStringList("crafting.disable").iterator(); while(disabledRecipes.hasNext()) { ItemStack recipeItemStack = new ItemStack(Material.getMaterial(disabledRecipes.next())); List<Recipe> tempList = getServer().getRecipesFor(recipeItemStack); for (int itterator = 0; itterator < tempList.size(); itterator ++) { removeRecipe(tempList.get(itterator)); g++; } } //Enable the following recipes ConfigurationSection configCraftingEnable=config.getConfigurationSection("crafting.enable"); for (String recipeName:configCraftingEnable.getKeys(false)) { ConfigurationSection configSection=configCraftingEnable.getConfigurationSection(recipeName); Recipe recipe; List<String> shape=configSection.getStringList("shape"); NamedItemStack output=getItems(configSection.getConfigurationSection("output")).get(0); if(shape.isEmpty()) { ShapelessRecipe shapelessRecipe=new ShapelessRecipe(output); for (ItemStack input:getItems(configSection.getConfigurationSection("inputs"))) { shapelessRecipe.addIngredient(input.getAmount(),input.getType(),input.getDurability()); } recipe=shapelessRecipe; } else { ShapedRecipe shapedRecipe=new ShapedRecipe(output); shapedRecipe.shape(shape.toArray(new String[shape.size()])); for(String inputKey:configSection.getConfigurationSection("inputs").getKeys(false)) { ItemStack input=getItems(configSection.getConfigurationSection("inputs."+inputKey)).get(0); shapedRecipe.setIngredient(inputKey.charAt(0),input.getType(),input.getDurability()); } recipe=shapedRecipe; } Bukkit.addRecipe(recipe); } //Import recipes from config.yml ConfigurationSection configProdRecipes=config.getConfigurationSection("production_recipes"); //Temporary Storage array to store where recipes should point to each other HashMap<ProductionRecipe,ArrayList> outputRecipes=new HashMap<ProductionRecipe,ArrayList>(); Iterator<String> recipeTitles=configProdRecipes.getKeys(false).iterator(); while (recipeTitles.hasNext()) { //Section header in recipe file, also serves as unique identifier for the recipe //All spaces are replaced with udnerscores so they don't disrupt saving format //There should be a check for uniqueness of this identifier... String title=recipeTitles.next(); ConfigurationSection configSection=configProdRecipes.getConfigurationSection(title); title=title.replaceAll(" ","_"); //Display name of the recipe, Deafult of "Default Name" String recipeName = configSection.getString("name","Default Name"); //Production time of the recipe, default of 1 int productionTime=configSection.getInt("production_time",2); //Inputs of the recipe, empty of there are no inputs ItemList<NamedItemStack> inputs = getItems(configSection.getConfigurationSection("inputs")); //Inputs of the recipe, empty of there are no inputs ItemList<NamedItemStack> upgrades = getItems(configSection.getConfigurationSection("upgrades")); //Outputs of the recipe, empty of there are no inputs ItemList<NamedItemStack> outputs = getItems(configSection.getConfigurationSection("outputs")); //Enchantments of the recipe, empty of there are no inputs List<ProbabilisticEnchantment> enchantments=getEnchantments(configSection.getConfigurationSection("enchantments")); //Whether this recipe can only be used once boolean useOnce = configSection.getBoolean("use_once"); ProductionRecipe recipe = new ProductionRecipe(title,recipeName,productionTime,inputs,upgrades,outputs,enchantments,useOnce,new ItemList<NamedItemStack>()); productionRecipes.put(title,recipe); //Store the titles of the recipes that this should point to ArrayList <String> currentOutputRecipes=new ArrayList<String>(); currentOutputRecipes.addAll(configSection.getStringList("output_recipes")); outputRecipes.put(recipe,currentOutputRecipes); } //Once ProductionRecipe objects have been created correctly insert different pointers Iterator<ProductionRecipe> recipeIterator=outputRecipes.keySet().iterator(); while (recipeIterator.hasNext()) { ProductionRecipe recipe=recipeIterator.next(); Iterator<String> outputIterator=outputRecipes.get(recipe).iterator(); while(outputIterator.hasNext()) { recipe.addOutputRecipe(productionRecipes.get(outputIterator.next())); } } //Import factories from config.yml ConfigurationSection configProdFactories=config.getConfigurationSection("production_factories"); Iterator<String> factoryTitles=configProdFactories.getKeys(false).iterator(); while(factoryTitles.hasNext()) { String title=factoryTitles.next(); ConfigurationSection configSection=configProdFactories.getConfigurationSection(title); title=title.replaceAll(" ","_"); String factoryName=configSection.getString("name","Default Name"); //Uses overpowered getItems method for consistency, should always return a list of size=1 //If no fuel is found, default to charcoal ItemList<NamedItemStack> fuel=getItems(configSection.getConfigurationSection("fuel")); if(fuel.isEmpty()) { fuel=new ItemList<NamedItemStack>(); fuel.add(new NamedItemStack(Material.getMaterial("COAL"),1,(short)1,"Charcoal")); } int fuelTime=configSection.getInt("fuel_time",2); ItemList<NamedItemStack> inputs=getItems(configSection.getConfigurationSection("inputs")); ItemList<NamedItemStack> repairs=getItems(configSection.getConfigurationSection("repair_inputs")); List<ProductionRecipe> factoryRecipes=new ArrayList<ProductionRecipe>(); Iterator<String> ouputRecipeIterator=configSection.getStringList("recipes").iterator(); while (ouputRecipeIterator.hasNext()) { factoryRecipes.add(productionRecipes.get(ouputRecipeIterator.next())); } int repair=configSection.getInt("repair_multiple",0); //Create repair recipe productionRecipes.put(title+"REPAIR",new ProductionRecipe(title+"REPAIR","Repair Factory",1,repairs)); factoryRecipes.add(productionRecipes.get(title+"REPAIR")); ProductionProperties productionProperty = new ProductionProperties(inputs, factoryRecipes, fuel, fuelTime, factoryName, repair); productionProperties.put(title, productionProperty); } ConfigurationSection configPrintingPresses=config.getConfigurationSection("printing_presses"); ConfigurationSection configNetherFactory=config.getConfigurationSection("nether_factory"); printingPressProperties = PrintingPressProperties.fromConfig(this, configPrintingPresses); netherFactoryProperties = NetherFactoryProperties.fromConfig(this, configNetherFactory); sendConsoleMessage("Finished initializing FactoryMod Config."); } private List<ProbabilisticEnchantment> getEnchantments(ConfigurationSection configEnchantments) { List<ProbabilisticEnchantment> enchantments=new ArrayList<ProbabilisticEnchantment>(); if(configEnchantments!=null) { Iterator<String> names=configEnchantments.getKeys(false).iterator(); while (names.hasNext()) { String name=names.next(); ConfigurationSection configEnchantment=configEnchantments.getConfigurationSection(name); String type=configEnchantment.getString("type"); if (type!=null) { int level=configEnchantment.getInt("level",1); double probability=configEnchantment.getDouble("probability",1.0); ProbabilisticEnchantment enchantment=new ProbabilisticEnchantment(name,type,level,probability); enchantments.add(enchantment); } } } return enchantments; } private List<PotionEffect> getPotionEffects( ConfigurationSection configurationSection) { List<PotionEffect> potionEffects = new ArrayList<PotionEffect>(); if(configurationSection!=null) { Iterator<String> names=configurationSection.getKeys(false).iterator(); while (names.hasNext()) { String name=names.next(); ConfigurationSection configEffect=configurationSection.getConfigurationSection(name); String type=configEffect.getString("type"); if (type!=null) { PotionEffectType effect = PotionEffectType.getByName(type); if (effect != null) { int duration=configEffect.getInt("duration",200); int amplifier=configEffect.getInt("amplifier",0); potionEffects.add(new PotionEffect(effect, duration, amplifier)); } } } } return potionEffects; } public ItemList<NamedItemStack> getItems(ConfigurationSection configItems) { ItemList<NamedItemStack> items=new ItemList<NamedItemStack>(); if(configItems!=null) { for(String commonName:configItems.getKeys(false)) { ConfigurationSection configItem= configItems.getConfigurationSection(commonName); String materialName=configItem.getString("material"); Material material = Material.getMaterial(materialName); //only proceeds if an acceptable material name was provided if (material == null) { getLogger().severe(configItems.getCurrentPath() + " requires invalid material " + materialName); } else { int amount=configItem.getInt("amount",1); short durability=(short)configItem.getInt("durability",0); int repairCost=(short)configItem.getInt("repair_cost",0); String displayName=configItem.getString("display_name"); String lore=configItem.getString("lore"); List<ProbabilisticEnchantment> compulsoryEnchantments = getEnchantments(configItem.getConfigurationSection("enchantments")); List<ProbabilisticEnchantment> storedEnchantments = getEnchantments(configItem.getConfigurationSection("stored_enchantments")); List<PotionEffect> potionEffects = getPotionEffects(configItem.getConfigurationSection("potion_effects")); items.add(createItemStack(material,amount,durability,displayName,lore,commonName,repairCost,compulsoryEnchantments,storedEnchantments,potionEffects)); } } } return items; } private NamedItemStack createItemStack(Material material,int stackSize,short durability,String name,String loreString,String commonName,int repairCost,List<ProbabilisticEnchantment> compulsoryEnchants,List<ProbabilisticEnchantment> storedEnchants, List<PotionEffect> potionEffects) { NamedItemStack namedItemStack= new NamedItemStack(material, stackSize, durability,commonName); if(name!=null||loreString!=null||compulsoryEnchants.size()>0||storedEnchants.size()>0||potionEffects.size()>0||repairCost > 0) { ItemMeta meta=namedItemStack.getItemMeta(); if (name!=null) meta.setDisplayName(name); if (meta instanceof Repairable && repairCost > 0) ((Repairable) meta).setRepairCost(repairCost); if (loreString!=null) { List<String> lore = new ArrayList<String>(); lore.add(loreString); meta.setLore(lore); } for (ProbabilisticEnchantment enchant : compulsoryEnchants) { meta.addEnchant(enchant.getEnchantment(), enchant.getLevel(), false); } if (meta instanceof EnchantmentStorageMeta) { EnchantmentStorageMeta esm = (EnchantmentStorageMeta) meta; for (ProbabilisticEnchantment enchant : storedEnchants) { esm.addStoredEnchant(enchant.getEnchantment(), enchant.getLevel(), false); } } if (meta instanceof PotionMeta) { PotionMeta pm = (PotionMeta) meta; for (PotionEffect effect : potionEffects) { pm.addCustomEffect(effect, true); } } namedItemStack.setItemMeta(meta); } return namedItemStack; } private void removeRecipe(Recipe removalRecipe) { Iterator<Recipe> itterator = getServer().recipeIterator(); while (itterator.hasNext()) { Recipe recipe = itterator.next(); if (recipe.getResult().getType() == removalRecipe.getResult().getType()) { itterator.remove(); } } } public static Properties getProperties(FactoryType factoryType, String subFactoryType) { switch(factoryType) { case PRODUCTION: return FactoryModPlugin.productionProperties.get(subFactoryType); default: return null; } } public static int getMaxTiers(FactoryType factoryType) { // TODO Auto-generated method stub return 0; } public static void sendConsoleMessage(String message) { Bukkit.getLogger().info(FactoryModPlugin.PLUGIN_PREFIX + message); } public PrintingPressProperties getPrintingPressProperties() { return printingPressProperties; } public NetherFactoryProperties getNetherFactoryProperties() { return netherFactoryProperties; } private static FactoryModPlugin plugin; public static FactoryModPlugin getPlugin(){ return plugin; } }
package org.uct.cs.hough.processors; import org.uct.cs.hough.CircleDetection; import org.uct.cs.hough.reader.ShortImageBuffer; import org.uct.cs.hough.util.Circle; import org.uct.cs.hough.util.CircumferenceProvider; import java.util.ArrayList; import java.util.List; public class HoughFilter { public static List<Circle> identify(ShortImageBuffer edges, float centerThreshold) { int border = CircleDetection.MAX_RADIUS; int height = edges.getHeight(); int heightWithBorder = height + 2*border; int width = edges.getWidth(); int widthWithBorder = width + 2*border; int depth = CircumferenceProvider.getPointlists().size(); // create hough space int[] space = new int[heightWithBorder*widthWithBorder*depth]; int nx,ny,ay,ax,cx,cy,radiusError; for(int y=0;y<height;y++) { ay = y + border; for(int x=0;x<width;x++) { ax = x + border; if (edges.get(y,x) != 0) { for(int r=0;r<depth;r++) { cx = CircleDetection.MIN_RADIUS + r; cy = 0; radiusError = 1-cx; while(cx >= cy) { nx = ax + cx; ny = ay + cy; space[(ny*widthWithBorder + nx)*depth + r]++; nx = ax + cy; ny = ay + cx; space[(ny*widthWithBorder + nx)*depth + r]++; nx = ax - cx; ny = ay + cy; space[(ny*widthWithBorder + nx)*depth + r]++; nx = ax - cy; ny = ay + cx; space[(ny*widthWithBorder + nx)*depth + r]++; nx = ax - cx; ny = ay - cy; space[(ny*widthWithBorder + nx)*depth + r]++; nx = ax - cy; ny = ay - cx; space[(ny*widthWithBorder + nx)*depth + r]++; nx = ax + cx; ny = ay - cy; space[(ny*widthWithBorder + nx)*depth + r]++; nx = ax + cy; ny = ay - cx; space[(ny*widthWithBorder + nx)*depth + r]++; cy++; if (radiusError<0) { radiusError += 2 * cy + 1; } else { cx radiusError += 2 * (cy - cx + 1); } } } } } } // cache circumference lenths float[] cl = new float[depth]; for(int r=0;r<depth;r++) cl[r] = CircumferenceProvider.get(CircleDetection.MIN_RADIUS + r).length; List<Circle> output = new ArrayList<>(); for(int y=0;y<height;y++) { ay = y + border; for(int x=0;x<width;x++) { ax = x + border; for(int r=0;r<depth;r++) { if ((space[(ay*widthWithBorder + ax) *depth + r] / cl[r]) > centerThreshold) { output.add(new Circle(x,y,CircleDetection.MIN_RADIUS + r)); } } } } return output; } }
package com.gracecode.android.gojuon.helper; import android.content.Context; import com.gracecode.android.common.helper.ArrayHelper; import com.gracecode.android.gojuon.dao.Question; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ExamHelper { private static final int DEFAULT_ANSWER_NUM = 4; public static int DEFAULT_QUESTIONS_NUM = 50; private final Context mContext; private int mCurrent = 0; private List<Question> mQuestions = new ArrayList<>(); private List<Question> mAnsweredQuestions = new ArrayList<>(); private List<String[]> mQuestionsScope = new ArrayList<>(); public ExamHelper(Context context) { mContext = context; } private List<String[]> clearEmptyQuestionScope(List<String[]> questions) { for (int i = questions.size() - 1; i >= 0; i if (questions.get(i)[0].length() == 0) { questions.remove(i); } } return questions; } private Question generateOneQuestion(String[] answer) { List<String[]> question = new ArrayList<>(); question.add(answer); fillArrays(question, DEFAULT_ANSWER_NUM); ArrayHelper.shuffle(question); return new Question(question, answer); } public void addQuestionScope(String[][] characters) { mQuestionsScope.addAll(Arrays.asList(characters)); clearEmptyQuestionScope(mQuestionsScope); } private void fillArrays(List<String[]> list, int size) { do { int index = (int) (Math.random() * mQuestionsScope.size()); String[] character = mQuestionsScope.get(index); if (!list.contains(character)) { list.add(character); } } while (list.size() < size); } public void generateRandomQuestions(int num) { if (num > mQuestionsScope.size()) { num = mQuestionsScope.size(); } reset(); ArrayList<String[]> answers = new ArrayList<>(); fillArrays(answers, num); for (int i = 0, size = answers.size(); i < size; i++) { Question question = generateOneQuestion(answers.get(i)); mQuestions.add(question); } } public void generateRandomQuestions() { generateRandomQuestions(DEFAULT_QUESTIONS_NUM); } public boolean addAnsweredQuestion(Question question) { return mAnsweredQuestions.add(question); } public Question seekToQuestion(int position) { mCurrent = position; return mQuestions.get(position); } public Question getNextQuestion() throws RuntimeException { return mQuestions.get(mCurrent++); } public void reset() { mCurrent = 0; mQuestions.clear(); mAnsweredQuestions.clear(); } public List<Question> getWrongQuestions() { List<Question> result = new ArrayList<>(); for (int i = 0; i < mQuestions.size(); i++) { try { Question question = mAnsweredQuestions.get(i); if (!question.isCorrect()) { result.add(question); } } catch (ArrayIndexOutOfBoundsException e) { result.add(mQuestions.get(i)); } } return result; } public int getWrongCount() { return getWrongQuestions().size(); } public int getAnsweredCount() { return mAnsweredQuestions.size(); } public int getTotalCount() { return mQuestions.size(); } public List<Question> getAnsweredQuestions() { return mAnsweredQuestions; } public void setQuestions(List<Question> questions) { this.mQuestions = questions; } }
package com.irccloud.androidnative; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.actionbarsherlock.app.SherlockListFragment; public class BuffersListFragment extends SherlockListFragment { private static final int TYPE_SERVER = 0; private static final int TYPE_CHANNEL = 1; private static final int TYPE_CONVERSATION = 2; private static final int TYPE_ARCHIVES_HEADER = 3; NetworkConnection conn; BufferListAdapter adapter; OnBufferSelectedListener mListener; View view; TextView errorMsg; ListView listView = null; RelativeLayout connecting = null; LinearLayout topUnreadIndicator = null; LinearLayout topUnreadIndicatorColor = null; LinearLayout bottomUnreadIndicator = null; LinearLayout bottomUnreadIndicatorColor = null; String error = null; private Timer countdownTimer = null; int selected_bid = -1; int firstUnreadPosition = -1; int lastUnreadPosition= -1; int firstHighlightPosition = -1; int lastHighlightPosition= -1; SparseBooleanArray mExpandArchives = new SparseBooleanArray(); private static class BufferListEntry implements Serializable { private static final long serialVersionUID = 1848168221883194027L; int cid; int bid; int type; int unread; int highlights; int key; long last_seen_eid; long min_eid; int joined; int archived; String name; String status; } private class BufferListAdapter extends BaseAdapter { ArrayList<BufferListEntry> data; private SherlockListFragment ctx; int progressRow = -1; private class ViewHolder { int type; TextView label; TextView highlights; LinearLayout unread; LinearLayout groupbg; LinearLayout bufferbg; ImageView key; ProgressBar progress; ImageButton addBtn; } public void showProgress(int row) { progressRow = row; notifyDataSetChanged(); } public int positionForBid(int bid) { for(int i = 0; i < data.size(); i++) { BufferListEntry e = data.get(i); if(e.bid == bid) return i; } return -1; } public BufferListAdapter(SherlockListFragment context) { ctx = context; data = new ArrayList<BufferListEntry>(); } public void setItems(ArrayList<BufferListEntry> items) { data = items; } int unreadPositionAbove(int pos) { for(int i = pos-1; i >= 0; i BufferListEntry e = data.get(i); if(e.unread > 0) return i; } return 0; } int unreadPositionBelow(int pos) { for(int i = pos; i < data.size(); i++) { BufferListEntry e = data.get(i); if(e.unread > 0) return i; } return data.size() - 1; } public BufferListEntry buildItem(int cid, int bid, int type, String name, int key, int unread, int highlights, long last_seen_eid, long min_eid, int joined, int archived, String status) { BufferListEntry e = new BufferListEntry(); e.cid = cid; e.bid = bid; e.type = type; e.name = name; e.key = key; e.unread = unread; e.highlights = highlights; e.last_seen_eid = last_seen_eid; e.min_eid = min_eid; e.joined = joined; e.archived = archived; e.status = status; return e; } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { BufferListEntry e = data.get(position); return e.bid; } @SuppressWarnings("deprecation") @Override public View getView(int position, View convertView, ViewGroup parent) { BufferListEntry e = data.get(position); View row = convertView; ViewHolder holder; if(row != null && ((ViewHolder)row.getTag()).type != e.type) row = null; if (row == null) { LayoutInflater inflater = ctx.getLayoutInflater(null); if(e.type == TYPE_SERVER) row = inflater.inflate(R.layout.row_buffergroup, null); else row = inflater.inflate(R.layout.row_buffer, null); holder = new ViewHolder(); holder.label = (TextView) row.findViewById(R.id.label); holder.highlights = (TextView) row.findViewById(R.id.highlights); holder.unread = (LinearLayout) row.findViewById(R.id.unread); holder.groupbg = (LinearLayout) row.findViewById(R.id.groupbg); holder.bufferbg = (LinearLayout) row.findViewById(R.id.bufferbg); holder.key = (ImageView) row.findViewById(R.id.key); holder.progress = (ProgressBar) row.findViewById(R.id.progressBar); holder.addBtn = (ImageButton) row.findViewById(R.id.addBtn); holder.type = e.type; row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } holder.label.setText(e.name); if(e.type == TYPE_ARCHIVES_HEADER) { holder.label.setTypeface(null); holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_archives_heading)); holder.unread.setBackgroundDrawable(null); if(mExpandArchives.get(e.cid, false)) { holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg_archived); holder.bufferbg.setSelected(true); } else { holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg); holder.bufferbg.setSelected(false); } } else if(e.archived == 1 && holder.bufferbg != null) { holder.label.setTypeface(null); holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_archived)); holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg_archived); holder.unread.setBackgroundDrawable(null); } else if((e.type == TYPE_CHANNEL && e.joined == 0) || !e.status.equals("connected_ready")) { holder.label.setTypeface(null); holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_inactive)); holder.unread.setBackgroundDrawable(null); if(holder.bufferbg != null) holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg); } else if(e.unread > 0) { holder.label.setTypeface(null, Typeface.BOLD); holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_unread)); holder.unread.setBackgroundResource(R.drawable.selected_blue); if(holder.bufferbg != null) holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg); } else { holder.label.setTypeface(null); holder.label.setTextColor(getResources().getColorStateList(R.color.row_label)); holder.unread.setBackgroundDrawable(null); if(holder.bufferbg != null) holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg); } if(conn.getState() != NetworkConnection.STATE_CONNECTED) row.setBackgroundResource(R.drawable.disconnected_yellow); else row.setBackgroundResource(R.drawable.bg); if(holder.key != null) { if(e.key > 0) { holder.key.setVisibility(View.VISIBLE); } else { holder.key.setVisibility(View.INVISIBLE); } } if(holder.progress != null) { if(progressRow == position || (e.type == TYPE_SERVER && !(e.status.equals("connected_ready") || e.status.equals("quitting") || e.status.equals("disconnected")))) { if(selected_bid == -1 || progressRow != position) { holder.progress.setVisibility(View.VISIBLE); } else { if(holder.bufferbg != null) holder.bufferbg.setSelected(true); if(holder.groupbg != null) holder.groupbg.setSelected(true); } } else if(e.type != TYPE_ARCHIVES_HEADER) { holder.progress.setVisibility(View.GONE); if(holder.bufferbg != null) holder.bufferbg.setSelected(false); if(holder.groupbg != null) holder.groupbg.setSelected(false); } } if(holder.groupbg != null) { if(e.status.equals("waiting_to_retry") || e.status.equals("pool_unavailable")) { holder.groupbg.setBackgroundResource(R.drawable.operator_bg_red); holder.label.setTextColor(getResources().getColorStateList(R.color.heading_operators)); } else { holder.groupbg.setBackgroundResource(R.drawable.row_buffergroup_bg); } } if(holder.highlights != null) { if(e.highlights > 0) { holder.highlights.setVisibility(View.VISIBLE); holder.highlights.setText("(" + e.highlights + ")"); } else { holder.highlights.setVisibility(View.GONE); holder.highlights.setText(""); } } if(holder.addBtn != null) { holder.addBtn.setTag(e); holder.addBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { BufferListEntry e = (BufferListEntry)v.getTag(); AddChannelFragment newFragment = new AddChannelFragment(); newFragment.setDefaultCid(e.cid); newFragment.show(getActivity().getSupportFragmentManager(), "dialog"); } }); } return row; } } private class RefreshTask extends AsyncTask<Void, Void, Void> { ArrayList<BufferListEntry> entries = new ArrayList<BufferListEntry>(); @Override protected Void doInBackground(Void... params) { ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers(); if(adapter == null) { adapter = new BufferListAdapter(BuffersListFragment.this); } firstUnreadPosition = -1; lastUnreadPosition = -1; firstHighlightPosition = -1; lastHighlightPosition = -1; int position = 0; for(int i = 0; i < servers.size(); i++) { int archiveCount = 0; ServersDataSource.Server s = servers.get(i); ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid); for(int j = 0; j < buffers.size(); j++) { BuffersDataSource.Buffer b = buffers.get(j); if(b.type.equalsIgnoreCase("console")) { int unread = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type); int highlights = EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid); if(s.name.length() == 0) s.name = s.hostname; entries.add(adapter.buildItem(b.cid, b.bid, TYPE_SERVER, s.name, 0, unread, highlights, b.last_seen_eid, b.min_eid, 1, b.archived, s.status)); if(unread > 0 && firstUnreadPosition == -1) firstUnreadPosition = position; if(unread > 0 && (lastUnreadPosition == -1 || lastUnreadPosition < position)) lastUnreadPosition = position; if(highlights > 0 && firstHighlightPosition == -1) firstHighlightPosition = position; if(highlights > 0 && (lastHighlightPosition == -1 || lastHighlightPosition < position)) lastHighlightPosition = position; position++; break; } } for(int j = 0; j < buffers.size(); j++) { BuffersDataSource.Buffer b = buffers.get(j); int type = -1; int key = 0; int joined = 1; if(b.type.equalsIgnoreCase("channel")) { type = TYPE_CHANNEL; ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid); if(c == null) joined = 0; if(c != null && c.mode != null && c.mode.contains("k")) key = 1; } else if(b.type.equalsIgnoreCase("conversation")) type = TYPE_CONVERSATION; if(type > 0 && b.archived == 0) { int unread = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type); int highlights = EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid); if(conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) { try { JSONObject disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread"); if(disabledMap.has(String.valueOf(b.bid)) && disabledMap.getBoolean(String.valueOf(b.bid))) unread = 0; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } entries.add(adapter.buildItem(b.cid, b.bid, type, b.name, key, unread, highlights, b.last_seen_eid, b.min_eid, joined, b.archived, s.status)); if(unread > 0 && firstUnreadPosition == -1) firstUnreadPosition = position; if(unread > 0 && (lastUnreadPosition == -1 || lastUnreadPosition < position)) lastUnreadPosition = position; if(highlights > 0 && firstHighlightPosition == -1) firstHighlightPosition = position; if(highlights > 0 && (lastHighlightPosition == -1 || lastHighlightPosition < position)) lastHighlightPosition = position; position++; } if(type > 0 && b.archived > 0) { archiveCount++; } } if(archiveCount > 0) { entries.add(adapter.buildItem(s.cid, 0, TYPE_ARCHIVES_HEADER, "Archives", 0, 0, 0, 0, 0, 0, 1, s.status)); position++; if(mExpandArchives.get(s.cid, false)) { for(int j = 0; j < buffers.size(); j++) { BuffersDataSource.Buffer b = buffers.get(j); int type = -1; if(b.archived == 1) { if(b.type.equalsIgnoreCase("channel")) type = TYPE_CHANNEL; else if(b.type.equalsIgnoreCase("conversation")) type = TYPE_CONVERSATION; if(type > 0) { entries.add(adapter.buildItem(b.cid, b.bid, type, b.name, 0, 0, 0, b.last_seen_eid, b.min_eid, 0, b.archived, s.status)); position++; } } } } } } return null; } @Override protected void onPostExecute(Void result) { adapter.setItems(entries); if(getListAdapter() == null && entries.size() > 0) setListAdapter(adapter); else adapter.notifyDataSetChanged(); if(entries.size() > 0 && connecting != null) { connecting.setVisibility(View.GONE); } if(listView != null) updateUnreadIndicators(listView.getFirstVisiblePosition(), listView.getLastVisiblePosition()); else //The activity view isn't ready yet, try again new RefreshTask().execute((Void)null); if(selected_bid > 0) adapter.showProgress(adapter.positionForBid(selected_bid)); } } public void setSelectedBid(int bid) { selected_bid = bid; if(adapter != null) adapter.showProgress(adapter.positionForBid(bid)); } private void updateUnreadIndicators(int first, int last) { if(topUnreadIndicator != null) { if(firstUnreadPosition != -1 && first >= firstUnreadPosition) { topUnreadIndicator.setVisibility(View.VISIBLE); topUnreadIndicatorColor.setBackgroundResource(R.drawable.selected_blue); } else { topUnreadIndicator.setVisibility(View.GONE); } if((lastHighlightPosition != -1 && first >= lastHighlightPosition) || (firstHighlightPosition != -1 && first >= firstHighlightPosition)) { topUnreadIndicator.setVisibility(View.VISIBLE); topUnreadIndicatorColor.setBackgroundResource(R.drawable.highlight_red); } } if(bottomUnreadIndicator != null) { if(lastUnreadPosition != -1 && last <= lastUnreadPosition) { bottomUnreadIndicator.setVisibility(View.VISIBLE); bottomUnreadIndicatorColor.setBackgroundResource(R.drawable.selected_blue); } else { bottomUnreadIndicator.setVisibility(View.GONE); } if((firstHighlightPosition != -1 && last <= firstHighlightPosition) || (lastHighlightPosition != -1 && last <= lastHighlightPosition)) { bottomUnreadIndicator.setVisibility(View.VISIBLE); bottomUnreadIndicatorColor.setBackgroundResource(R.drawable.highlight_red); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.bufferslist, null); errorMsg = (TextView)view.findViewById(R.id.errorMsg); connecting = (RelativeLayout)view.findViewById(R.id.connecting); topUnreadIndicator = (LinearLayout)view.findViewById(R.id.topUnreadIndicator); topUnreadIndicator.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int scrollTo = adapter.unreadPositionAbove(getListView().getFirstVisiblePosition()); if(scrollTo > 0) getListView().setSelection(scrollTo-1); else getListView().setSelection(0); updateUnreadIndicators(getListView().getFirstVisiblePosition(), getListView().getLastVisiblePosition()); } }); topUnreadIndicatorColor = (LinearLayout)view.findViewById(R.id.topUnreadIndicatorColor); bottomUnreadIndicator = (LinearLayout)view.findViewById(R.id.bottomUnreadIndicator); bottomUnreadIndicator.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int offset = getListView().getLastVisiblePosition() - getListView().getFirstVisiblePosition(); int scrollTo = adapter.unreadPositionBelow(getListView().getLastVisiblePosition()) - offset + 2; if(scrollTo < adapter.getCount()) getListView().setSelection(scrollTo); else getListView().setSelection(adapter.getCount() - 1); updateUnreadIndicators(getListView().getFirstVisiblePosition(), getListView().getLastVisiblePosition()); } }); bottomUnreadIndicatorColor = (LinearLayout)view.findViewById(R.id.bottomUnreadIndicatorColor); listView = (ListView)view.findViewById(android.R.id.list); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { updateUnreadIndicators(firstVisibleItem, firstVisibleItem+visibleItemCount-1); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } }); if(savedInstanceState != null && savedInstanceState.containsKey("data")) { ArrayList<Integer> expandedArchives = savedInstanceState.getIntegerArrayList("expandedArchives"); Iterator<Integer> i = expandedArchives.iterator(); while(i.hasNext()) { Integer cid = i.next(); mExpandArchives.put(cid, true); } adapter = new BufferListAdapter(this); adapter.setItems((ArrayList<BufferListEntry>) savedInstanceState.getSerializable("data")); setListAdapter(adapter); listView.setSelection(savedInstanceState.getInt("scrollPosition")); if(selected_bid > 0) adapter.showProgress(adapter.positionForBid(selected_bid)); } return view; } @Override public void onSaveInstanceState(Bundle state) { if(adapter != null && adapter.data != null && adapter.data.size() > 0) { ArrayList<Integer> expandedArchives = new ArrayList<Integer>(); ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers(); Iterator<ServersDataSource.Server> i = servers.iterator(); while(i.hasNext()) { ServersDataSource.Server s = i.next(); if(mExpandArchives.get(s.cid, false)) expandedArchives.add(s.cid); } state.putSerializable("data", adapter.data); state.putIntegerArrayList("expandedArchives", expandedArchives); if(listView != null) state.putInt("scrollPosition", listView.getFirstVisiblePosition()); } } public void onResume() { super.onResume(); conn = NetworkConnection.getInstance(); conn.addHandler(mHandler); if(conn.getState() != NetworkConnection.STATE_CONNECTED) { view.setBackgroundResource(R.drawable.disconnected_yellow); } else { view.setBackgroundResource(R.drawable.background_blue); connecting.setVisibility(View.GONE); getListView().setVisibility(View.VISIBLE); } if(adapter != null) adapter.showProgress(-1); new RefreshTask().execute((Void)null); } @Override public void onPause() { super.onPause(); if(conn != null) conn.removeHandler(mHandler); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnBufferSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnBufferSelectedListener"); } } public void onListItemClick(ListView l, View v, int position, long id) { BufferListEntry e = (BufferListEntry)adapter.getItem(position); String type = null; switch(e.type) { case TYPE_ARCHIVES_HEADER: mExpandArchives.put(e.cid, !mExpandArchives.get(e.cid, false)); new RefreshTask().execute((Void)null); return; case TYPE_SERVER: type = "console"; break; case TYPE_CHANNEL: type = "channel"; break; case TYPE_CONVERSATION: type = "conversation"; break; } adapter.showProgress(position); mListener.onBufferSelected(e.cid, e.bid, e.name, e.last_seen_eid, e.min_eid, type, e.joined, e.archived, e.status); } private void updateReconnecting() { if(conn.getReconnectTimestamp() > 0) { String plural = ""; int seconds = (int)((conn.getReconnectTimestamp() - System.currentTimeMillis()) / 1000); if(seconds != 1) plural = "s"; if(seconds < 1) errorMsg.setText("Connecting"); else if(seconds > 10 && error != null) errorMsg.setText(error +"\n\nReconnecting in\n" + seconds + " second" + plural); else errorMsg.setText("Reconnecting in\n" + seconds + " second" + plural); if(countdownTimer != null) countdownTimer.cancel(); countdownTimer = new Timer(); countdownTimer.schedule( new TimerTask(){ public void run() { if(conn.getState() == NetworkConnection.STATE_DISCONNECTED) { mHandler.post(new Runnable() { @Override public void run() { updateReconnecting(); } }); } countdownTimer = null; } }, 1000); } else { errorMsg.setText("Offline"); } } @SuppressLint("HandlerLeak") private final Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case NetworkConnection.EVENT_CONNECTIVITY: if(conn.getState() != NetworkConnection.STATE_CONNECTED) { view.setBackgroundResource(R.drawable.disconnected_yellow); } else { view.setBackgroundResource(R.drawable.background_blue); errorMsg.setText("Loading"); error = null; } if(conn.getState() == NetworkConnection.STATE_CONNECTING) { errorMsg.setText("Connecting"); error = null; } else if(conn.getState() == NetworkConnection.STATE_DISCONNECTED) updateReconnecting(); if(adapter != null) adapter.notifyDataSetChanged(); break; case NetworkConnection.EVENT_FAILURE_MSG: IRCCloudJSONObject o = (IRCCloudJSONObject)msg.obj; if(conn.getState() != NetworkConnection.STATE_CONNECTED) { try { error = o.getString("message"); if(error.equals("temp_unavailable")) error = "Your account is temporarily unavailable"; updateReconnecting(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; default: try { IRCCloudJSONObject o1 = (IRCCloudJSONObject)msg.obj; if(o1.bid() != selected_bid) new RefreshTask().execute((Void)null); } catch (Exception e) { //Not all events return a JSON object new RefreshTask().execute((Void)null); } break; } } }; @SuppressLint("NewApi") public void scrollToTop() { if(listView != null) { if(Build.VERSION.SDK_INT >= 11) listView.smoothScrollToPositionFromTop(0, 0, 200); else listView.setSelection(0); } } public int getConnectingVisibility() { if(connecting != null) return connecting.getVisibility(); else return View.VISIBLE; } public interface OnBufferSelectedListener { public void onBufferSelected(int cid, int bid, String name, long last_seen_eid, long min_eid, String type, int joined, int archived, String status); } }
package com.iskrembilen.quasseldroid.io; import android.content.SharedPreferences; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.util.Pair; import com.iskrembilen.quasseldroid.*; import com.iskrembilen.quasseldroid.Network.ConnectionState; import com.iskrembilen.quasseldroid.exceptions.UnsupportedProtocolException; import com.iskrembilen.quasseldroid.io.CustomTrustManager.NewCertificateException; import com.iskrembilen.quasseldroid.qtcomm.*; import com.iskrembilen.quasseldroid.service.CoreConnService; import com.iskrembilen.quasseldroid.util.MessageUtil; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.security.cert.CertificateException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class CoreConnection { private static final String TAG = CoreConnection.class.getSimpleName(); private Socket socket; private QDataOutputStream outStream; private QDataInputStream inStream; private Map<Integer, Buffer> buffers; private CoreInfo coreInfo; private Map<Integer, Network> networks; private long coreId; private String address; private int port; private String username; private String password; private boolean ssl; CoreConnService service; private Timer heartbeatTimer; private ReadThread readThread; private boolean initComplete; private int initBacklogBuffers; private int networkInitsLeft; private boolean networkInitComplete; private LinkedList<List<QVariant<?>>> packageQueue; private String errorMessage; //Used to create the ID of new channels we join private int maxBufferId = 0; private ExecutorService outputExecutor; public CoreConnection(long coreId, String address, int port, String username, String password, Boolean ssl, CoreConnService parent) { this.coreId = coreId; this.address = address; this.port = port; this.username = username; this.password = password; this.ssl = ssl; this.service = parent; outputExecutor = Executors.newSingleThreadExecutor(); readThread = new ReadThread(); readThread.start(); } /** * Checks whether the core is available. */ public boolean isConnected() { return (socket != null && !socket.isClosed() && readThread.running); } /** * requests the core to set a given buffer as read * @param buffer the buffer id to set as read */ public void requestMarkBufferAsRead(int buffer) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestMarkBufferAsRead", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestRemoveBuffer(int buffer) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestRemoveBuffer", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestTempHideBuffer(int bufferId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferViewConfig", QVariantType.String)); retFunc.add(new QVariant<String>("0", QVariantType.String)); retFunc.add(new QVariant<String>("requestRemoveBuffer", QVariantType.String)); retFunc.add(new QVariant<Integer>(bufferId, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requestRemoveBuffer", e); onDisconnected("Lost connection"); } } public void requestPermHideBuffer(int bufferId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferViewConfig", QVariantType.String)); retFunc.add(new QVariant<String>("0", QVariantType.String)); retFunc.add(new QVariant<String>("requestRemoveBufferPermanently", QVariantType.String)); retFunc.add(new QVariant<Integer>(bufferId, "BufferId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requestRemoveBufferPermanently", e); onDisconnected("Lost connection"); } } public void requestDisconnectNetwork(int networkId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("Network", QVariantType.String)); retFunc.add(new QVariant<String>(Integer.toString(networkId), QVariantType.String)); retFunc.add(new QVariant<String>("requestDisconnect", QVariantType.ByteArray)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestConnectNetwork(int networkId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("Network", QVariantType.String)); retFunc.add(new QVariant<String>(Integer.toString(networkId), QVariantType.String)); retFunc.add(new QVariant<String>("requestConnect", QVariantType.ByteArray)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestSetLastMsgRead(int buffer, int msgid) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestSetLastSeenMsg", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); retFunc.add(new QVariant<Integer>(msgid, "MsgId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } public void requestSetMarkerLine(int buffer, int msgid) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestSetMarkerLine", QVariantType.ByteArray)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); retFunc.add(new QVariant<Integer>(msgid, "MsgId")); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException", e); onDisconnected("Lost connection"); } } /** * Requests to unhide a temporarily hidden buffer */ public void requestUnhideTempHiddenBuffer(int bufferId) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BufferViewConfig", QVariantType.String)); retFunc.add(new QVariant<String>("0", QVariantType.String)); retFunc.add(new QVariant<String>("requestAddBuffer", QVariantType.String)); retFunc.add(new QVariant<Integer>(bufferId, "BufferId")); retFunc.add(new QVariant<Integer>(networks.get(buffers.get(bufferId).getInfo().networkId).getBufferCount(), QVariantType.Int)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requesting backlog", e); onDisconnected("Lost connection"); } } /** * Requests moar backlog for a give buffer * @param buffer Buffer id to request moar for */ public void requestMoreBacklog(int buffer, int amount) { if (buffers.get(buffer).getUnfilteredSize()==0) { requestBacklog(buffer, -1, -1, amount); }else { // Log.e(TAG, "GETTING: "+buffers.get(buffer).getUnfilteredBacklogEntry(0).messageId); requestBacklog(buffer, -1, buffers.get(buffer).getUnfilteredBacklogEntry(0).messageId, amount); } } /** * Requests all backlog from a given message ID until the current. */ private void requestBacklog(int buffer, int firstMsgId) { requestBacklog(buffer, firstMsgId, -1); } /** * Requests backlog between two given message IDs. */ private void requestBacklog(int buffer, int firstMsgId, int lastMsgId) { requestBacklog(buffer, firstMsgId, lastMsgId, -1); } private void requestBacklog(int buffer, int firstMsgId, int lastMsgId, int maxAmount) { List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("BacklogManager", QVariantType.String)); retFunc.add(new QVariant<String>("", QVariantType.String)); retFunc.add(new QVariant<String>("requestBacklog", QVariantType.String)); retFunc.add(new QVariant<Integer>(buffer, "BufferId")); retFunc.add(new QVariant<Integer>(firstMsgId, "MsgId")); retFunc.add(new QVariant<Integer>(lastMsgId, "MsgId")); retFunc.add(new QVariant<Integer>(maxAmount, QVariantType.Int)); retFunc.add(new QVariant<Integer>(0, QVariantType.Int)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while requesting backlog", e); onDisconnected("Lost connection"); } } /** * Sends an IRC message to a given buffer * @param buffer buffer to send to * @param message content of message */ public void sendMessage(int buffer, String message) { if (message.charAt(0) == '/') { String t[] = message.split(" "); message = t[0].toUpperCase(); if (t.length > 1){ StringBuilder tmpMsg = new StringBuilder(message); for (int i=1; i<t.length; i++) { tmpMsg.append(' '); tmpMsg.append(t[i]); } message = tmpMsg.toString(); } } else { message = "/SAY " + message; } List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>(); retFunc.add(new QVariant<Integer>(RequestType.RpcCall.getValue(), QVariantType.Int)); retFunc.add(new QVariant<String>("2sendInput(BufferInfo,QString)", QVariantType.String)); retFunc.add(new QVariant<BufferInfo>(buffers.get(buffer).getInfo(), "BufferInfo")); retFunc.add(new QVariant<String>(message, QVariantType.String)); try { sendQVariantList(retFunc); } catch (IOException e) { Log.e(TAG, "IOException while sending message", e); onDisconnected("Lost connection"); } } /** * Initiates a connection. * @throws EmptyQVariantException * @throws UnsupportedProtocolException */ public void connect() throws UnknownHostException, IOException, GeneralSecurityException, CertificateException, NewCertificateException, EmptyQVariantException, UnsupportedProtocolException { updateInitProgress("Connecting..."); // START CREATE SOCKETS SocketFactory factory = (SocketFactory)SocketFactory.getDefault(); socket = (Socket)factory.createSocket(address, port); socket.setKeepAlive(true); outStream = new QDataOutputStream(socket.getOutputStream()); // END CREATE SOCKETS // START CLIENT INFO updateInitProgress("Sending client info..."); Map<String, QVariant<?>> initial = new HashMap<String, QVariant<?>>(); DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy HH:mm:ss"); Date date = new Date(); initial.put("ClientDate", new QVariant<String>(dateFormat.format(date), QVariantType.String)); initial.put("UseSsl", new QVariant<Boolean>(ssl, QVariantType.Bool)); initial.put("ClientVersion", new QVariant<String>("v0.6.1 (dist-<a href='http://git.quassel-irc.org/?p=quassel.git;a=commit;h=611ebccdb6a2a4a89cf1f565bee7e72bcad13ffb'>611ebcc</a>)", QVariantType.String)); initial.put("UseCompression", new QVariant<Boolean>(false, QVariantType.Bool)); initial.put("MsgType", new QVariant<String>("ClientInit", QVariantType.String)); initial.put("ProtocolVersion", new QVariant<Integer>(10, QVariantType.Int)); sendQVariantMap(initial); // END CLIENT INFO // START CORE INFO updateInitProgress("Getting core info..."); inStream = new QDataInputStream(socket.getInputStream()); Map<String, QVariant<?>> reply = readQVariantMap(); coreInfo = new CoreInfo(); coreInfo.setCoreFeatures((Integer)reply.get("CoreFeatures").getData()); coreInfo.setCoreInfo((String)reply.get("CoreInfo").getData()); coreInfo.setSupportSsl((Boolean)reply.get("SupportSsl").getData()); coreInfo.setCoreDate(new Date((String)reply.get("CoreDate").getData())); coreInfo.setCoreStartTime((GregorianCalendar)reply.get("CoreStartTime").getData()); String coreVersion = (String)reply.get("CoreVersion").getData(); coreVersion = coreVersion.substring(coreVersion.indexOf("v")+1, coreVersion.indexOf(" ")); coreInfo.setCoreVersion(coreVersion); coreInfo.setConfigured((Boolean)reply.get("Configured").getData()); coreInfo.setLoginEnabled((Boolean)reply.get("LoginEnabled").getData()); coreInfo.setMsgType((String)reply.get("MsgType").getData()); coreInfo.setProtocolVersion(((Long)reply.get("ProtocolVersion").getData()).intValue()); coreInfo.setSupportsCompression((Boolean)reply.get("SupportsCompression").getData()); Matcher matcher = Pattern.compile("(\\d+)\\W(\\d+)\\W", Pattern.CASE_INSENSITIVE).matcher(coreInfo.getCoreVersion()); Log.i(TAG, "Core version: " + coreInfo.getCoreVersion()); int version, release; if (matcher.find()) { version = Integer.parseInt(matcher.group(1)); release = Integer.parseInt(matcher.group(2)); } else { throw new UnsupportedProtocolException("Can't match core version: " + coreInfo.getCoreVersion()); } //Check that the protocol version is atleast 10 and the version is above 0.6.0 if(coreInfo.getProtocolVersion()<10 || !(version>0 || (version==0 && release>=6))) throw new UnsupportedProtocolException("Protocol version is old: "+coreInfo.getProtocolVersion()); /*for (String key : reply.keySet()) { System.out.println("\t" + key + " : " + reply.get(key)); }*/ // END CORE INFO // START SSL CONNECTION if (ssl) { Log.d(TAG, "Using ssl"); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager [] { new CustomTrustManager(this) }; sslContext.init(null, trustManagers, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address, port, true); sslSocket.setEnabledProtocols(new String[] {"SSLv3"}); sslSocket.setUseClientMode(true); updateInitProgress("Starting ssl handshake"); sslSocket.startHandshake(); Log.d(TAG, "Ssl handshake complete"); inStream = new QDataInputStream(sslSocket.getInputStream()); outStream = new QDataOutputStream(sslSocket.getOutputStream()); socket = sslSocket; } else { Log.w(TAG, "SSL DISABLED!"); } // FINISHED SSL CONNECTION // START LOGIN updateInitProgress("Logging in..."); Map<String, QVariant<?>> login = new HashMap<String, QVariant<?>>(); login.put("MsgType", new QVariant<String>("ClientLogin", QVariantType.String)); login.put("User", new QVariant<String>(username, QVariantType.String)); login.put("Password", new QVariant<String>(password, QVariantType.String)); sendQVariantMap(login); // FINISH LOGIN // START LOGIN ACK reply = readQVariantMap(); if (!reply.get("MsgType").toString().equals("ClientLoginAck")) throw new GeneralSecurityException("Invalid password?"); // END LOGIN ACK // START SESSION INIT updateInitProgress("Receiving session state..."); reply = readQVariantMap(); /*System.out.println("SESSION INIT: "); for (String key : reply.keySet()) { System.out.println("\t" + key + " : " + reply.get(key)); }*/ Map<String, QVariant<?>> sessionState = (Map<String, QVariant<?>>) reply.get("SessionState").getData(); List<QVariant<?>> networkIds = (List<QVariant<?>>) sessionState.get("NetworkIds").getData(); networks = new HashMap<Integer, Network>(networkIds.size()); for (QVariant<?> networkId: networkIds) { Integer id = (Integer) networkId.getData(); networks.put(id, new Network(id)); } List<QVariant<?>> bufferInfos = (List<QVariant<?>>) sessionState.get("BufferInfos").getData(); buffers = new HashMap<Integer, Buffer>(bufferInfos.size()); QuasselDbHelper dbHelper = new QuasselDbHelper(service.getApplicationContext()); ArrayList<Integer> bufferIds = new ArrayList<Integer>(); for (QVariant<?> bufferInfoQV: bufferInfos) { BufferInfo bufferInfo = (BufferInfo)bufferInfoQV.getData(); Buffer buffer = new Buffer(bufferInfo, dbHelper); buffers.put(bufferInfo.id, buffer); if(bufferInfo.type==BufferInfo.Type.StatusBuffer){ networks.get(bufferInfo.networkId).setStatusBuffer(buffer); }else{ networks.get(bufferInfo.networkId).addBuffer(buffer); } bufferIds.add(bufferInfo.id); } dbHelper.open(); dbHelper.cleanupEvents(bufferIds.toArray(new Integer[bufferIds.size()])); dbHelper.close(); // END SESSION INIT // Now the fun part starts, where we play signal proxy // START SIGNAL PROXY INIT updateInitProgress("Requesting network and buffer information..."); // We must do this here, to get network names early enough networkInitsLeft = 0; networkInitComplete = false; for(Network network: networks.values()) { networkInitsLeft += 1; sendInitRequest("Network", Integer.toString(network.getId())); } sendInitRequest("BufferSyncer", ""); //sendInitRequest("BufferViewManager", ""); this is about where this should be, but don't know what it does sendInitRequest("BufferViewConfig", "0"); SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(service); //Get backlog if user selected a fixed amount if(!options.getBoolean(service.getString(R.string.preference_fetch_to_last_seen), false)) { int backlogAmout = Integer.parseInt(options.getString(service.getString(R.string.preference_initial_backlog_limit), "1")); initBacklogBuffers = 0; for (Buffer buffer:buffers.values()) { initBacklogBuffers += 1; requestMoreBacklog(buffer.getInfo().id, backlogAmout); } } TimerTask sendPingAction = new TimerTask() { public void run() { List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>(); packedFunc.add(new QVariant<Integer>(RequestType.HeartBeat.getValue(), QVariantType.Int)); packedFunc.add(new QVariant<Calendar>(Calendar.getInstance(), QVariantType.Time)); try { sendQVariantList(packedFunc); } catch (IOException e) { Log.e(TAG, "IOException while sending ping", e); onDisconnected("Lost connection"); } } }; heartbeatTimer = new Timer(); heartbeatTimer.schedule(sendPingAction, 30000, 30000); // Send heartbeats every 30 seconds // END SIGNAL PROXY updateInitProgress("Connection established, waiting on networks..."); // Notify the UI we have an open socket Message msg = service.getHandler().obtainMessage(R.id.CONNECTING); msg.sendToTarget(); initComplete = false; } public void closeConnection() { readThread.running = false; //tell the while loop to quit } /** * Disconnect from the core, as best as we can. * */ public synchronized void onDisconnected(String informationMessage) { Log.d(TAG, "Disconnected so closing connection"); errorMessage = informationMessage; closeConnection(); } /** * Type of a given request (should be pretty self-explanatory). */ private enum RequestType { Invalid(0), Sync(1), RpcCall(2), InitRequest(3), InitData(4), HeartBeat(5), HeartBeatReply(6); // Below this line; java sucks. Hard. int value; RequestType(int value){ this.value = value; } public int getValue(){ return value; } public static RequestType getForVal(int val) { for (RequestType type: values()) { if (type.value == val) return type; } return Invalid; } } /** * Convenience function to send a given QVariant. * @param data QVariant to send. */ private synchronized void sendQVariant(QVariant<?> data) throws IOException { outputExecutor.execute(new OutputRunnable(data)); } private class OutputRunnable implements Runnable { private QVariant<?> data; public OutputRunnable(QVariant<?> data) { this.data = data; } @Override public void run() { try { // See how much data we're going to send //TODO sandsmark: there must be a better way to to this then create new streams each time.... ByteArrayOutputStream baos = new ByteArrayOutputStream(); QDataOutputStream bos = new QDataOutputStream(baos); QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, bos, data); // Tell the other end how much data to expect outStream.writeUInt(bos.size(), 32); // Sanity check, check that we can decode our own stuff before sending it off //QDataInputStream bis = new QDataInputStream(new ByteArrayInputStream(baos.toByteArray())); //QMetaTypeRegistry.instance().getTypeForId(QMetaType.Type.QVariant.getValue()).getSerializer().unserialize(bis, DataStreamVersion.Qt_4_2); // Send data QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, outStream, data); bos.close(); baos.close(); } catch (IOException e) { onDisconnected("Lost connection while sending information"); } } } /** * Convenience function to send a given QVariantMap. * @param data the given QVariantMap to send. */ private void sendQVariantMap(Map<String, QVariant<?>> data) throws IOException { QVariant<Map<String, QVariant<?>>> bufstruct = new QVariant<Map<String, QVariant<?>>>(data, QVariantType.Map); sendQVariant(bufstruct); } /** * A convenience function to send a given QVariantList. * @param data The QVariantList to send. */ private void sendQVariantList(List<QVariant<?>> data) throws IOException { QVariant<List<QVariant<?>>> bufstruct = new QVariant<List<QVariant<?>>>(data, QVariantType.List); sendQVariant(bufstruct); } /** * A convenience function to read a QVariantMap. * @throws EmptyQVariantException */ private Map<String, QVariant<?>> readQVariantMap() throws IOException, EmptyQVariantException { // Length of this packet (why do they send this? noone knows!). inStream.readUInt(32); QVariant <Map<String, QVariant<?>>> v = (QVariant <Map<String, QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream); Map<String, QVariant<?>>ret = (Map<String, QVariant<?>>)v.getData(); // System.out.println(ret.toString()); if(!readThread.running) throw new IOException(); //Stops crashing while connecting if we are told to disconnect, so 2 instances are not reading the network return ret; } /** * A convenience function to read a QVariantList. * @throws EmptyQVariantException */ private List<QVariant<?>> readQVariantList() throws IOException, EmptyQVariantException { inStream.readUInt(32); // Length QVariant <List<QVariant<?>>> v = (QVariant <List<QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream); List<QVariant<?>>ret = (List<QVariant<?>>)v.getData(); // System.out.println(ret.toString()); return ret; } /** * Convenience function to request an init of a given object. * @param className The class name of the object we want. * @param objectName The name of the object we want. */ private void sendInitRequest(String className, String objectName) throws IOException { List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>(); packedFunc.add(new QVariant<Integer>(RequestType.InitRequest.getValue(), QVariantType.Int)); packedFunc.add(new QVariant<String>(className, QVariantType.String)); packedFunc.add(new QVariant<String>(objectName, QVariantType.String)); sendQVariantList(packedFunc); } private void updateInitProgress(String message) { Log.i(TAG, message); service.getHandler().obtainMessage(R.id.INIT_PROGRESS, message).sendToTarget(); } private void updateInitDone() { initComplete = true; service.getHandler().obtainMessage(R.id.INIT_DONE).sendToTarget(); } private class ReadThread extends Thread { boolean running = false; CountDownTimer checkAlive = new CountDownTimer(180000, 180000) { @Override public void onTick(long millisUntilFinished) { //Do nothing, no use } @Override public void onFinish() { Log.i(TAG, "Timer finished, disconnection from core"); CoreConnection.this.onDisconnected("Timed out"); } }; public void run() { try { String errorMessage = doRun(); if(errorMessage != null) onDisconnected(errorMessage); } catch (EmptyQVariantException e) { Log.e(TAG, "Protocol error", e); onDisconnected("Protocol error!"); } //Close everything if (heartbeatTimer!=null) { heartbeatTimer.cancel(); // Has this stopped executing now? Nobody knows. } //Close streams and socket try { if (outStream != null) { outStream.flush(); outStream.close(); } } catch (IOException e) { Log.w(TAG, "IOException while closing outStream", e); } try { if(inStream != null) inStream.close(); } catch (IOException e) { Log.w(TAG, "IOException while closing inStream", e); } try { if (socket != null) socket.close(); } catch (IOException e) { Log.w(TAG, "IOException while closing socket", e); } service.getHandler().obtainMessage(R.id.LOST_CONNECTION, errorMessage).sendToTarget(); service = null; } public String doRun() throws EmptyQVariantException { this.running = true; errorMessage = null; packageQueue = new LinkedList<List<QVariant<?>>>(); try { connect(); } catch (UnknownHostException e) { return "Unknown host!"; } catch (UnsupportedProtocolException e) { service.getHandler().obtainMessage(R.id.UNSUPPORTED_PROTOCOL).sendToTarget(); Log.w(TAG, e); closeConnection(); return null; } catch (IOException e) { Log.w(TAG, "Got IOException while connecting"); if(e.getCause() instanceof NewCertificateException) { Log.w(TAG, "Got NewCertificateException while connecting"); service.getHandler().obtainMessage(R.id.NEW_CERTIFICATE, ((NewCertificateException)e.getCause()).hashedCert()).sendToTarget(); closeConnection(); } else if(e.getCause() instanceof CertificateException) { Log.w(TAG, "Got CertificateException while connecting"); service.getHandler().obtainMessage(R.id.INVALID_CERTIFICATE, e.getCause().getMessage()).sendToTarget(); closeConnection(); } else{ e.printStackTrace(); return "IO error while connecting! " + e.getMessage(); } return null; } catch (GeneralSecurityException e) { Log.w(TAG, "Invalid username/password combination"); return "Invalid username/password combination."; } catch (EmptyQVariantException e) { return "IO error while connecting!"; } List<QVariant<?>> packedFunc; final long startWait = System.currentTimeMillis(); while (running) { try { if(networkInitComplete && packageQueue.size() > 0) { Log.e(TAG, "Queue not empty, retrive element"); packedFunc = packageQueue.poll(); } else { packedFunc = readQVariantList(); } //Check if we where told to disconnect while reading qvariantlist if(!running) { break; } //Log.i(TAG, "Slow core is slow: " + (System.currentTimeMillis() - startWait) + "ms"); //We received a package, aka we are not disconnected, restart timer //Log.i(TAG, "Package reviced, reseting countdown"); checkAlive.cancel(); checkAlive.start(); //if network init is not complete and we receive anything but a network init object, queue it if(!networkInitComplete) { if(RequestType.getForVal((Integer)packedFunc.get(0).getData()) != RequestType.InitData || !((String)packedFunc.get(1).getData()).equals("Network")) { Log.e(TAG, "Package not network, queueing it"); packageQueue.add(packedFunc); continue; //Read next packageFunc } } long start = System.currentTimeMillis(); RequestType type = RequestType.getForVal((Integer)packedFunc.remove(0).getData()); String className = "", objectName; /* * Here we handle different calls from the core. */ switch (type) { /* * A heartbeat is a simple request sent with fixed intervals, * to make sure that both ends are still connected (apparently, TCP isn't good enough). * TODO: We should use this, and disconnect automatically when the core has gone away. */ case HeartBeat: Log.d(TAG, "Got heartbeat"); List<QVariant<?>> packet = new LinkedList<QVariant<?>>(); packet.add(new QVariant<Integer>(RequestType.HeartBeatReply.getValue(), QVariantType.Int)); packet.add(new QVariant<Calendar>(Calendar.getInstance(), QVariantType.Time)); try { sendQVariantList(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case HeartBeatReply: Log.d(TAG, "Got heartbeat reply"); if (packedFunc.size() != 0) { Calendar calendarNow = Calendar.getInstance(); Calendar calendarSent = (Calendar) packedFunc.remove(0).getData(); int latency = (int)(calendarNow.getTimeInMillis() - calendarSent.getTimeInMillis()) / 2; Log.d(TAG, "Latency: " + latency); service.getHandler().obtainMessage(R.id.SET_CORE_LATENCY, latency, 0, null).sendToTarget(); } break; /* * This is when the core send us a new object to create. * Since we don't actually create objects, we parse out the fields * in the objects manually. */ case InitData: // The class name and name of the object we are about to create className = (String) packedFunc.remove(0).getData(); objectName = (String) packedFunc.remove(0).getData(); /* * An object representing an IRC network, containing users and channels ("buffers"). */ if (className.equals("Network")) { Log.d(TAG, "InitData: Network"); int networkId = Integer.parseInt(objectName); Network network = networks.get(networkId); Map<String, QVariant<?>> initMap = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); // Store the network name and associated nick for "our" user network.setNick((String) initMap.get("myNick").getData()); network.setName((String) initMap.get("networkName").getData()); network.setLatency((Integer) initMap.get("latency").getData()); network.setServer((String) initMap.get("currentServer").getData()); boolean isConnected = (Boolean)initMap.get("isConnected").getData(); if(isConnected) network.setConnected(true); else network.setConnectionState(ConnectionState.Disconnected); if(network.getStatusBuffer() != null) network.getStatusBuffer().setActive(isConnected); //we got enough info to tell service we are parsing network Log.i(TAG, "Started parsing network " + network.getName()); updateInitProgress("Receiving network: " +network.getName()); // Horribly nested maps Map<String, QVariant<?>> usersAndChans = (Map<String, QVariant<?>>) initMap.get("IrcUsersAndChannels").getData(); Map<String, QVariant<?>> channels = (Map<String, QVariant<?>>) usersAndChans.get("channels").getData(); //Parse out user objects for network Map<String, QVariant<?>> userObjs = (Map<String, QVariant<?>>) usersAndChans.get("users").getData(); ArrayList<IrcUser> ircUsers = new ArrayList<IrcUser>(); HashMap<String, IrcUser> userTempMap = new HashMap<String, IrcUser>(); for (Map.Entry<String, QVariant<?>> element: userObjs.entrySet()) { IrcUser user = new IrcUser(); user.name = element.getKey(); Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) element.getValue().getData(); user.away = (Boolean) map.get("away").getData(); user.awayMessage = (String) map.get("awayMessage").getData(); user.ircOperator = (String) map.get("ircOperator").getData(); user.nick = (String) map.get("nick").getData(); user.channels = (List<String>) map.get("channels").getData(); ircUsers.add(user); userTempMap.put(user.nick, user); } network.setUserList(ircUsers); // Parse out the topics for (QVariant<?> channel: channels.values()) { Map<String, QVariant<?>> chan = (Map<String, QVariant<?>>) channel.getData(); String chanName = (String)chan.get("name").getData(); Map<String, QVariant<?>> userModes = (Map<String, QVariant<?>>) chan.get("UserModes").getData(); String topic = (String)chan.get("topic").getData(); boolean foundChannel = false; for (Buffer buffer: network.getBuffers().getRawBufferList()) { if (buffer.getInfo().name.equalsIgnoreCase(chanName)) { buffer.setTopic(topic); buffer.setActive(true); ArrayList<Pair<IrcUser, String>> usersToAdd = new ArrayList<Pair<IrcUser, String>>(); for(Entry<String, QVariant<?>> nick : userModes.entrySet()) { IrcUser user = userTempMap.get(nick.getKey()); if(user == null) { Log.e(TAG, "Channel has nick that is does not match any user on the network: " + nick); //TODO: WHY THE FUCK IS A USER NULL HERE? HAPPENS ON MY OWN CORE, BUT NOT ON DEBUG CORE CONNECTED TO SAME CHANNEL. QUASSEL BUG? WHAT TO DO ABOUT IT //this sync request did not seem to do anything // sendInitRequest("IrcUser", network.getId()+"/" +nick.getKey()); continue; } usersToAdd.add(new Pair<IrcUser, String>(user, (String)nick.getValue().getData())); } buffer.getUsers().addUsers(usersToAdd); foundChannel = true; break; } } if(!foundChannel) throw new RuntimeException("A channel in a network has no coresponding buffer object " + chanName); } Log.i(TAG, "Sending network " + network.getName() + " to service"); service.getHandler().obtainMessage(R.id.ADD_NETWORK, network).sendToTarget(); //sendInitRequest("BufferSyncer", ""); /*sendInitRequest("BufferViewManager", ""); sendInitRequest("AliasManager", ""); sendInitRequest("NetworkConfig", "GlobalNetworkConfig"); sendInitRequest("IgnoreListManager", "");*/ List<QVariant<?>> reqPackedFunc = new LinkedList<QVariant<?>>(); reqPackedFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariantType.Int)); reqPackedFunc.add(new QVariant<String>("BufferSyncer", QVariantType.String)); reqPackedFunc.add(new QVariant<String>("", QVariantType.String)); reqPackedFunc.add(new QVariant<String>("requestPurgeBufferIds", QVariantType.String)); sendQVariantList(reqPackedFunc); if(!initComplete) { networkInitsLeft -= 1; if(networkInitsLeft <= 0) networkInitComplete = true; } long endWait = System.currentTimeMillis(); Log.w(TAG, "Network parsed, took: "+(endWait-startWait)); /* * An object that is used to synchronize metadata about buffers, * like the last seen message, marker lines, etc. */ } else if (className.equals("BufferSyncer")) { Log.d(TAG, "InitData: BufferSyncer"); // Parse out the last seen messages updateInitProgress("Receiving last seen and marker lines"); List<QVariant<?>> lastSeen = (List<QVariant<?>>) ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("LastSeenMsg").getData(); for (int i=0; i<lastSeen.size(); i+=2) { int bufferId = (Integer)lastSeen.get(i).getData(); int msgId = (Integer)lastSeen.get(i+1).getData(); if (buffers.containsKey(bufferId)){ // We only care for buffers we have open if(PreferenceManager.getDefaultSharedPreferences(service).getBoolean(service.getString(R.string.preference_fetch_to_last_seen), false)) { initBacklogBuffers += 1; requestBacklog(bufferId, msgId); } Message msg = service.getHandler().obtainMessage(R.id.SET_LAST_SEEN_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); }else{ Log.e(TAG, "Getting last seen message for buffer we dont have " +bufferId); } } // Parse out the marker lines for buffers if the core supports them QVariant<?> rawMarkerLines = ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("MarkerLines"); if(rawMarkerLines != null) { List<QVariant<?>> markerLines = (List<QVariant<?>>) rawMarkerLines.getData(); for (int i=0; i<markerLines.size(); i+=2) { int bufferId = (Integer)markerLines.get(i).getData(); int msgId = (Integer)markerLines.get(i+1).getData(); if (buffers.containsKey(bufferId)){ Message msg = service.getHandler().obtainMessage(R.id.SET_MARKERLINE_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); }else{ Log.e(TAG, "Getting markerlinemessage for buffer we dont have " +bufferId); } } }else{ Log.e(TAG, "Marker lines are null in BufferSyncer, should not happen"); } /* * A class representing another user on a given IRC network. */ } else if (className.equals("IrcUser")) { Log.d(TAG, "InitData: IrcUser"); Map<String, QVariant<?>> userMap = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); Bundle bundle = new Bundle(); bundle.putString("awayMessage", (String)userMap.get("awayMessage").getData()); bundle.putSerializable("channels", (ArrayList<String>) userMap.get("channels").getData()); bundle.putBoolean("away", (Boolean)userMap.get("away").getData()); bundle.putString("ircOperator", (String) userMap.get("ircOperator").getData()); bundle.putString("nick", (String) userMap.get("nick").getData()); Message msg = service.getHandler().obtainMessage(R.id.NEW_USER_INFO); int networkId = Integer.parseInt(objectName.split("/", 2)[0]); msg.obj = bundle; msg.arg1 = networkId; msg.sendToTarget(); } else if (className.equals("IrcChannel")) { Log.d(TAG, "InitData: IrcChannel"); // System.out.println(packedFunc.toString() + " Object: "+objectName); // topic, UserModes, password, ChanModes, name //For now only topic seems useful here, rest is added other places Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); String bufferName = (String)map.get("name").getData(); String topic = (String)map.get("topic").getData(); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); for(Buffer buffer : networks.get(networkId).getBuffers().getRawBufferList()) { if(buffer.getInfo().name.equalsIgnoreCase(bufferName)) { Message msg = service.getHandler().obtainMessage(R.id.CHANNEL_TOPIC_CHANGED, networkId, buffer.getInfo().id, topic); msg.sendToTarget(); msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_ACTIVE,buffer.getInfo().id, 0, true); msg.sendToTarget(); break; } } } else if (className.equals("BufferViewConfig")) { Log.d(TAG, "InitData: BufferViewConfig"); Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) packedFunc.remove(0).getData(); List<QVariant<?>> tempList = (List<QVariant<?>>) map.get("TemporarilyRemovedBuffers").getData(); List<QVariant<?>> permList = (List<QVariant<?>>) map.get("RemovedBuffers").getData(); List<QVariant<?>> orderList = (List<QVariant<?>>) map.get("BufferList").getData(); updateInitProgress("Receiving buffer list information"); BufferCollection.orderAlphabetical = (Boolean) map.get("sortAlphabetically").getData(); //TODO: mabye send this in a bulk to the service so it wont sort and shit every time for (QVariant bufferId: tempList) { if (!buffers.containsKey(bufferId.getData())) { Log.e(TAG, "TempList, dont't have buffer: " +bufferId.getData()); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_TEMP_HIDDEN); msg.arg1 = ((Integer) bufferId.getData()); msg.obj = true; msg.sendToTarget(); } for (QVariant bufferId: permList) { if (!buffers.containsKey(bufferId.getData())) { Log.e(TAG, "TempList, dont't have buffer: " +bufferId.getData()); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_PERM_HIDDEN); msg.arg1 = ((Integer) bufferId.getData()); msg.obj = true; msg.sendToTarget(); } int order = 0; for (QVariant bufferId: orderList) { int id = (Integer)bufferId.getData(); if(id > maxBufferId) { maxBufferId = id; } if (!buffers.containsKey(id)) { System.err.println("got buffer info for non-existant buffer id: " + id); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_ORDER); msg.arg1 = id; msg.arg2 = order; //FIXME: DEBUG PISS REMOVE ArrayList<Integer> keysString = new ArrayList<Integer>(); ArrayList<Integer> buffersString = new ArrayList<Integer>(); for(Entry<Integer, Buffer> b : buffers.entrySet()) { keysString.add(b.getKey()); buffersString.add(b.getValue().getInfo().id); } Bundle bundle = new Bundle(); bundle.putIntegerArrayList("keys", keysString); bundle.putIntegerArrayList("buffers", buffersString); msg.obj = bundle; msg.sendToTarget(); order++; } updateInitProgress("Receiving backlog"); } /* * There are several objects that we don't care about (at the moment). */ else { Log.i(TAG, "Unparsed InitData: " + className + "(" + objectName + ")."); } break; /* * Sync requests are sent by the core whenever an object needs to be updated. * Again, we just parse out whatever we need manually */ case Sync: /* See above; parse out information about object, * and additionally a sync function name. */ Object foo = packedFunc.remove(0).getData(); //System.out.println("FUCK" + foo.toString() + " balle " + foo.getClass().getName()); /*if (foo.getClass().getName().equals("java.nio.ReadWriteHeapByteBuffer")) { try { System.out.println("faen i helvete: " + new String(((ByteBuffer)foo).array(), "UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ className = (String)foo; // This is either a byte buffer or a string objectName = (String) packedFunc.remove(0).getData(); String function = packedFunc.remove(0).toString(); /* * The BacklogManager object is responsible for synchronizing backlog * between the core and the client. * * The receiveBacklog function is called in the client with a given (requested) * amount of messages. */ if (className.equals("BacklogManager") && function.equals("receiveBacklog")) { Log.d(TAG, "Sync: BacklogManager -> receiveBacklog"); /* Here we first just dump some unused data; * the buffer id is embedded in the message itself (in a bufferinfo object), * the rest of the arguments aren't used at all, apparently. */ packedFunc.remove(0); // Buffer ID (Integer) packedFunc.remove(0); // first message packedFunc.remove(0); // last message packedFunc.remove(0); // limit to how many messages to fetch packedFunc.remove(0); // additional messages to fetch List<QVariant<?>> data = (List<QVariant<?>>)(packedFunc.remove(0).getData()); Collections.reverse(data); // Apparently, we receive them in the wrong order if(!initComplete) { //We are still initializing backlog for the first time boolean preferenceParseColors = PreferenceManager.getDefaultSharedPreferences(service).getBoolean(service.getString(R.string.preference_colored_text), false); for (QVariant<?> message: data) { IrcMessage msg = (IrcMessage) message.getData(); Buffer buffer = buffers.get(msg.bufferInfo.id); if (buffer == null) { Log.e(TAG, "A message buffer is null:" + msg); continue; } if (!buffer.hasMessage(msg)) { /** * Check if we are highlighted in the message, TODO: Add * support for custom highlight masks */ MessageUtil.checkMessageForHighlight(networks.get(buffer.getInfo().networkId).getNick(), buffer, msg); if(preferenceParseColors) MessageUtil.parseStyleCodes(service, msg); buffer.addBacklogMessage(msg); } else { Log.e(TAG, "Getting message buffer already have " + buffer.getInfo().name); } } initBacklogBuffers -= 1; if(initBacklogBuffers<=0) { updateInitDone(); } } else { // Send our the backlog messages to our listeners //TODO: bundle them up before sending to save message objects for (QVariant<?> message: data) { Message msg = service.getHandler().obtainMessage(R.id.NEW_BACKLOGITEM_TO_SERVICE); msg.obj = message.getData(); msg.sendToTarget(); } } /* * The addIrcUser function in the Network class is called whenever a new * IRC user appears on a given network. */ } else if (className.equals("Network") && function.equals("addIrcUser")) { Log.d(TAG, "Sync: Network -> addIrcUser"); String nick = (String) packedFunc.remove(0).getData(); IrcUser user = new IrcUser(); user.nick = nick.split("!")[0]; //If not done then we can add it right here, if we try to send it we might crash because service don't have the network yet if(!initComplete) { networks.get(Integer.parseInt(objectName)).onUserJoined(user); } else { service.getHandler().obtainMessage(R.id.NEW_USER_ADDED, Integer.parseInt(objectName), 0, user).sendToTarget(); } sendInitRequest("IrcUser", objectName+"/" + nick.split("!")[0]); } else if (className.equals("Network") && function.equals("setConnectionState")) { Log.d(TAG, "Sync: Network -> setConnectionState"); int networkId = Integer.parseInt(objectName); Network.ConnectionState state = ConnectionState.getForValue((Integer)packedFunc.remove(0).getData()); //If network has no status buffer it is the first time we are connecting to it if(state == ConnectionState.Connecting && networks.get(networkId).getStatusBuffer() == null) { //Create the new buffer object for status buffer QuasselDbHelper dbHelper = new QuasselDbHelper(service.getApplicationContext()); BufferInfo info = new BufferInfo(); maxBufferId += 1; info.id = maxBufferId; info.networkId = networkId; info.type = BufferInfo.Type.StatusBuffer; Buffer buffer = new Buffer(info, dbHelper); buffers.put(info.id, buffer); service.getHandler().obtainMessage(R.id.SET_STATUS_BUFFER, networkId, 0, buffer).sendToTarget(); } service.getHandler().obtainMessage(R.id.SET_CONNECTION_STATE, networkId, 0, state).sendToTarget(); } else if (className.equals("Network") && function.equals("addIrcChannel")) { Log.d(TAG, "Sync: Network -> addIrcChannel"); int networkId = Integer.parseInt(objectName); String bufferName = (String) packedFunc.remove(0).getData(); System.out.println(bufferName); boolean hasBuffer = false; for(Buffer buffer : networks.get(networkId).getBuffers().getRawBufferList()) { if(buffer.getInfo().name.equalsIgnoreCase(bufferName)) { hasBuffer = true; } } if(!hasBuffer) { //Create the new buffer object QuasselDbHelper dbHelper = new QuasselDbHelper(service.getApplicationContext()); BufferInfo info = new BufferInfo(); info.name = bufferName; maxBufferId += 1; info.id = maxBufferId; info.networkId = networkId; info.type = BufferInfo.Type.ChannelBuffer; Buffer buffer = new Buffer(info, dbHelper); buffers.put(info.id, buffer); Message msg = service.getHandler().obtainMessage(R.id.NEW_BUFFER_TO_SERVICE, buffer); msg.sendToTarget(); } sendInitRequest("IrcChannel", objectName+"/" + bufferName); } else if (className.equals("Network") && function.equals("setConnected")) { Log.d(TAG, "Sync: Network -> setConnected"); boolean connected = (Boolean) packedFunc.remove(0).getData(); int networkId = Integer.parseInt(objectName); service.getHandler().obtainMessage(R.id.SET_CONNECTED, networkId, 0, connected).sendToTarget(); } else if (className.equals("Network") && function.equals("setMyNick")) { Log.d(TAG, "Sync: Network -> setMyNick"); String nick = (String) packedFunc.remove(0).getData(); int networkId = Integer.parseInt(objectName); service.getHandler().obtainMessage(R.id.SET_MY_NICK, networkId, 0, nick).sendToTarget(); } else if (className.equals("Network") && function.equals("setLatency")) { Log.d(TAG, "Sync: Network -> setLatency"); int networkLatency = (Integer) packedFunc.remove(0).getData(); int networkId = Integer.parseInt(objectName); service.getHandler().obtainMessage(R.id.SET_NETWORK_LATENCY, networkId, networkLatency, null).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("partChannel")) { Log.d(TAG, "Sync: IrcUser -> partChannel"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String userName = tmp[1]; Bundle bundle = new Bundle(); bundle.putString("nick", userName); bundle.putString("buffer", (String)packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.USER_PARTED, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("quit")) { Log.d(TAG, "Sync: IrcUser -> quit"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String userName = tmp[1]; service.getHandler().obtainMessage(R.id.USER_QUIT, networkId, 0, userName).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("setNick")) { Log.d(TAG, "Sync: IrcUser -> setNick"); /* * Does nothing, Why would we need a sync call, when we got a RPC call about renaming the user object */ } else if (className.equals("IrcUser") && function.equals("setServer")) { Log.d(TAG, "Sync: IrcUser -> setServer"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); Bundle bundle = new Bundle(); bundle.putString("nick", tmp[1]); bundle.putString("server", (String) packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.SET_USER_SERVER, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("setAway")) { Log.d(TAG, "Sync: IrcUser -> setAway"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); Bundle bundle = new Bundle(); bundle.putString("nick", tmp[1]); bundle.putBoolean("away", (Boolean) packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.SET_USER_AWAY, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcUser") && function.equals("setRealName")) { Log.d(TAG, "Sync: IrcUser -> setRealName"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); Bundle bundle = new Bundle(); bundle.putString("nick", tmp[1]); bundle.putString("realname", (String) packedFunc.remove(0).getData()); service.getHandler().obtainMessage(R.id.SET_USER_REALNAME, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcChannel") && function.equals("joinIrcUsers")) { Log.d(TAG, "Sync: IrcChannel -> joinIrcUsers"); List<String> nicks = (List<String>)packedFunc.remove(0).getData(); List<String> modes = (List<String>)packedFunc.remove(0).getData(); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String bufferName = tmp[1]; for(int i=0; i<nicks.size();i++) { Bundle bundle = new Bundle(); bundle.putString("nick", nicks.get(i)); bundle.putString("mode", modes.get(i)); bundle.putString("buffername", bufferName); service.getHandler().obtainMessage(R.id.USER_JOINED, networkId, 0, bundle).sendToTarget(); } } else if (className.equals("IrcChannel") && function.equals("addUserMode")) { Log.d(TAG, "Sync: IrcChannel -> addUserMode"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String channel = tmp[1]; String nick = (String) packedFunc.remove(0).getData(); String changedMode = (String) packedFunc.remove(0).getData(); Bundle bundle = new Bundle(); bundle.putString("nick", nick); bundle.putString("mode", changedMode); bundle.putString("channel", channel); service.getHandler().obtainMessage(R.id.USER_ADD_MODE, networkId, 0, bundle).sendToTarget(); } else if (className.equals("IrcChannel") && function.equals("removeUserMode")) { Log.d(TAG, "Sync: IrcChannel -> removeUserMode"); String[] tmp = objectName.split("/", 2); int networkId = Integer.parseInt(tmp[0]); String channel = tmp[1]; String nick = (String) packedFunc.remove(0).getData(); String changedMode = (String) packedFunc.remove(0).getData(); Bundle bundle = new Bundle(); bundle.putString("nick", nick); bundle.putString("mode", changedMode); bundle.putString("channel", channel); service.getHandler().obtainMessage(R.id.USER_REMOVE_MODE, networkId, 0, bundle).sendToTarget(); } else if (className.equals("BufferSyncer") && function.equals("setLastSeenMsg")) { Log.d(TAG, "Sync: BufferSyncer -> setLastSeenMsg"); int bufferId = (Integer) packedFunc.remove(0).getData(); int msgId = (Integer) packedFunc.remove(0).getData(); Message msg = service.getHandler().obtainMessage(R.id.SET_LAST_SEEN_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); } else if (className.equals("BufferSyncer") && function.equals("setMarkerLine")) { Log.d(TAG, "Sync: BufferSyncer -> setMarkerLine"); int bufferId = (Integer) packedFunc.remove(0).getData(); int msgId = (Integer) packedFunc.remove(0).getData(); Message msg = service.getHandler().obtainMessage(R.id.SET_MARKERLINE_TO_SERVICE); msg.arg1 = bufferId; msg.arg2 = msgId; msg.sendToTarget(); /* * markBufferAsRead is called whenever a given buffer is set as read by the core. */ } else if (className.equals("BufferSyncer") && function.equals("markBufferAsRead")) { Log.d(TAG, "Sync: BufferSyncer -> markBufferAsRead"); //TODO: this basicly does shit. So find out if it effects anything and what it should do //int buffer = (Integer) packedFunc.remove(0).getData(); //buffers.get(buffer).setRead(); } else if (className.equals("BufferSyncer") && function.equals("removeBuffer")) { Log.d(TAG, "Sync: BufferSyncer -> removeBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); if(buffers.containsKey(bufferId)) { int networkId = buffers.get(bufferId).getInfo().networkId; buffers.remove(bufferId); service.getHandler().obtainMessage(R.id.REMOVE_BUFFER, networkId, bufferId).sendToTarget(); } } else if (className.equals("BufferSyncer") && function.equals("renameBuffer")) { Log.d(TAG, "Sync: BufferSyncer -> renameBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); String newName = (String) packedFunc.remove(0).getData(); Message msg = service.getHandler().obtainMessage(R.id.RENAME_BUFFER); msg.arg1 = bufferId; msg.arg2 = 0; msg.obj = newName; msg.sendToTarget(); } else if (className.equals("BufferViewConfig") && function.equals("addBuffer")) { Log.d(TAG, "Sync: BufferViewConfig -> addBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); if (!buffers.containsKey(bufferId)) { // System.err.println("got buffer info for non-existant buffer id: " + bufferId); continue; } if(bufferId > maxBufferId) { maxBufferId = bufferId; } if (buffers.get(bufferId).isTemporarilyHidden()) { Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_TEMP_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = false; msg.sendToTarget(); } if (buffers.get(bufferId).isPermanentlyHidden()) { Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_PERM_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = false; msg.sendToTarget(); } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_ORDER); msg.arg1 = bufferId; msg.arg2 = networks.get(buffers.get(bufferId).getInfo().networkId).getBufferCount(); msg.sendToTarget(); } else if (className.equals("BufferViewConfig") && function.equals("removeBuffer")) { Log.d(TAG, "Sync: BufferViewConfig -> removeBuffer"); int bufferId = (Integer) packedFunc.remove(0).getData(); if (!buffers.containsKey(bufferId)) { Log.e(TAG, "Dont't have buffer: " + bufferId); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_TEMP_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = true; msg.sendToTarget(); } else if (className.equals("BufferViewConfig") && function.equals("removeBufferPermanently")) { Log.d(TAG, "Sync: BufferViewConfig -> removeBufferPermanently"); int bufferId = (Integer) packedFunc.remove(0).getData(); if (!buffers.containsKey(bufferId)) { Log.e(TAG, "Dont't have buffer: " + bufferId); continue; } Message msg = service.getHandler().obtainMessage(R.id.SET_BUFFER_PERM_HIDDEN); msg.arg1 = ((Integer) bufferId); msg.obj = true; msg.sendToTarget(); } else { Log.i(TAG, "Unparsed Sync request: " + className + "::" + function); } break; /* * Remote procedure calls are direct calls that are not associated with any objects. */ case RpcCall: // Contains a normalized function signature; see QMetaObject::normalizedSignature, I guess. String functionName = packedFunc.remove(0).toString(); /* * This is called by the core when a new message should be displayed. */ if (functionName.equals("2displayMsg(Message)")) { //Log.d(TAG, "RpcCall: " + "2displayMsg(Message)"); IrcMessage message = (IrcMessage) packedFunc.remove(0).getData(); if (!networks.get(message.bufferInfo.networkId).containsBuffer(message.bufferInfo.id) && message.bufferInfo.type == BufferInfo.Type.QueryBuffer) { // TODO: persist the db connections Buffer buffer = new Buffer(message.bufferInfo, new QuasselDbHelper(service.getApplicationContext())); buffers.put(message.bufferInfo.id, buffer); Message msg = service.getHandler().obtainMessage(R.id.NEW_BUFFER_TO_SERVICE); msg.obj = buffer; msg.sendToTarget(); } Message msg = service.getHandler().obtainMessage(R.id.NEW_MESSAGE_TO_SERVICE); msg.obj = message; msg.sendToTarget(); //11-12 21:48:02.514: I/CoreConnection(277): Unhandled RpcCall: __objectRenamed__ ([IrcUser, 1/Kenji, 1/Kenj1]). } else if(functionName.equals("__objectRenamed__") && ((String)packedFunc.get(0).getData()).equals("IrcUser")) { packedFunc.remove(0); //Drop the "ircUser" String[] tmp = ((String)packedFunc.remove(0).getData()).split("/", 2); int networkId = Integer.parseInt(tmp[0]); String newNick = tmp[1]; tmp = ((String)packedFunc.remove(0).getData()).split("/", 2); String oldNick = tmp[1]; Bundle bundle = new Bundle(); bundle.putString("oldNick", oldNick); bundle.putString("newNick", newNick); service.getHandler().obtainMessage(R.id.USER_CHANGEDNICK, networkId, -1, bundle).sendToTarget(); } else if(functionName.equals("2networkCreated(NetworkId)")) { Log.d(TAG, "RpcCall: " + "2networkCreated(NetworkId)"); int networkId = ((Integer)packedFunc.remove(0).getData()); Network network = new Network(networkId); networks.put(networkId, network); sendInitRequest("Network", Integer.toString(networkId)); } else if(functionName.equals("2networkRemoved(NetworkId)")) { Log.d(TAG, "RpcCall: " + "2networkRemoved(NetworkId)"); int networkId = ((Integer)packedFunc.remove(0).getData()); networks.remove(networkId); service.getHandler().obtainMessage(R.id.NETWORK_REMOVED, networkId, 0).sendToTarget(); } else { Log.i(TAG, "Unhandled RpcCall: " + functionName + " (" + packedFunc + ")."); } break; default: Log.i(TAG, "Unhandled request type: " + type.name()); } long end = System.currentTimeMillis(); if (end-start > 500) { System.err.println("Slow parsing (" + (end-start) + "ms)!: Request type: " + type.name() + " Class name:" + className); } } catch (IOException e) { CoreConnection.this.onDisconnected("Lost connection"); Log.w(TAG, "IO error, lost connection?", e); } } return null; } } public boolean isInitComplete() { return initComplete; } public long getCoreId() { return coreId; } }
package com.servegame.abendstern.tunnelblick.game; public class Flea extends Enemy { private static final float HW = 0.15f, H = 0.275f, LH = 0.1f, L = 0.25f; private static final float[] MODEL = { 1, 1, 1, 0, 0, -HW, 0, 0, 0, +HW, 0, 0, 1, 1, 0.5f, 0, 0, 0, H, 0, 0, 0, H, 0, 1, 1, 1, 0, 0, -HW, 0, 0, 0, 0, 0, -L, 0, 0, 0, -L, 0, -HW, 0, 0, 1, 1, 0.5f, 0, 0, 0, H, 0, 1, 1, 1, 0, 0, -HW, 0, 0, 0, +HW, 0, 0, 0, 0, 0, L, 1, 0, 0, 0, 0, -HW*4/6, 0, 0, 0, -HW*3/6, -LH, 0, 0, -HW*2/6, 0, 0, 0, +HW*4/6, 0, 0, 0, +HW*3/6, -LH, 0, 0, +HW*2/6, 0, 0, 0, -HW*4/6, 0, L/3, 0, -HW*3/6, -LH, L/3, 0, -HW*2/6, 0, L/3, 0, +HW*4/6, 0, L/3, 0, +HW*3/6, -LH, L/3, 0, +HW*2/6, 0, L/3, 0, -HW*4/6, 0, L*2/3, 0, -HW*3/6, -LH, L*2/3, 0, -HW*2/6, 0, L*2/3, 0, +HW*4/6, 0, L*2/3, 0, +HW*3/6, -LH, L*2/3, 0, +HW*2/6, 0, L*2/3, }; static { normalise(MODEL); } private float vz, vy; private static final float GRAVITY = -4.5f; private boolean blocked = false; public Flea(Tunnelblick tb) { super(tb, MODEL, 4); vz = -tb.getPlayer().getSpeed() / 2; vy = 0; } public void update(float et) { vy += GRAVITY*et; //Move to new location. //See how far we moved in the Y direction; if it is less than expected, //maybe jump float newy = y + vy*et; blocked = !moveTo(x, newy, blocked? z : z + vz*et, blocked); if (blocked || newy != y) vy = +2.2f * (float)Math.random(); } protected float getColourR() { return 1; } protected float getColourG() { return 1; } protected float getColourB() { return -0.3f; } protected float getPulseSpeed() { return 22; } protected int getAward() { return 1000; } }
package polyglot.frontend; import java.io.Reader; import polyglot.ast.NodeFactory; import polyglot.frontend.goals.Goal; import polyglot.main.Options; import polyglot.main.Version; import polyglot.types.TypeSystem; import polyglot.util.ErrorQueue; /** * This is an abstract <code>ExtensionInfo</code>. */ public abstract class AbstractExtensionInfo implements ExtensionInfo { protected Compiler compiler; private Options options; protected TypeSystem ts = null; protected NodeFactory nf = null; protected SourceLoader source_loader = null; protected TargetFactory target_factory = null; protected Stats stats; protected Scheduler scheduler; public abstract Goal getCompileGoal(Job job); public abstract String compilerName(); public abstract String defaultFileExtension(); public abstract Version version(); public Options getOptions() { if (this.options == null) { this.options = createOptions(); } return options; } protected Options createOptions() { return new Options(this); } /** Return a Stats object to accumulate and report statistics. */ public Stats getStats() { if (this.stats == null) { this.stats = new Stats(this); } return stats; } public Compiler compiler() { return compiler; } public void initCompiler(Compiler compiler) { this.compiler = compiler; // Register the extension with the compiler. compiler.addExtension(this); // Create the type system and node factory. typeSystem(); nodeFactory(); scheduler(); initTypeSystem(); } protected abstract void initTypeSystem(); /** * Get the file name extension of source files. This is * either the language extension's default file name extension * or the string passed in with the "-sx" command-line option. */ public String[] fileExtensions() { String[] sx = getOptions() == null ? null : getOptions().source_ext; if (sx == null) { sx = defaultFileExtensions(); } if (sx.length == 0) { return defaultFileExtensions(); } return sx; } /** Get the default list of file extensions. */ public String[] defaultFileExtensions() { String ext = defaultFileExtension(); return new String[] { ext }; } /** Get the source file loader object for this extension. */ public SourceLoader sourceLoader() { if (source_loader == null) { source_loader = new SourceLoader(this, getOptions().source_path); } return source_loader; } /** Get the target factory object for this extension. */ public TargetFactory targetFactory() { if (target_factory == null) { target_factory = new TargetFactory(getOptions().output_directory, getOptions().output_ext, getOptions().output_stdout); } return target_factory; } protected abstract Scheduler createScheduler(); public Scheduler scheduler() { if (scheduler == null) { scheduler = createScheduler(); } return scheduler; } /** Create the type system for this extension. */ protected abstract TypeSystem createTypeSystem(); /** Get the type system for this extension. */ public TypeSystem typeSystem() { if (ts == null) { ts = createTypeSystem(); } return ts; } /** Create the node factory for this extension. */ protected abstract NodeFactory createNodeFactory(); /** Get the AST node factory for this extension. */ public NodeFactory nodeFactory() { if (nf == null) { nf = createNodeFactory(); } return nf; } /** * Get the job extension for this language extension. The job * extension is used to extend the <code>Job</code> class * without subtyping. */ public JobExt jobExt() { return null; } /** Get the parser for this language extension. */ public abstract Parser parser(Reader reader, FileSource source, ErrorQueue eq); public String toString() { return getClass().getName(); } }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.util.Scanner; /** * * @author Nick Gaulke Nov 11, 2014 FinalProject * */ public class Game { private static Player player; private static Scanner in; private static String[] argsInternal; /** * @param args * @throws InterruptedException * @throws IOException * @throws ClassNotFoundException */ public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException { argsInternal = args; in = new Scanner(System.in); String os = System.getProperty("os.name"); Process term = null; if(os.charAt(0) == 'W') { term = Runtime.getRuntime().exec("cmd /c start cmd.exe"); } if(os.charAt(0) == 'M') { term = Runtime.getRuntime().exec("/usr/bin/open -a Terminal"); } if(os.charAt(0) == 'L') { term = Runtime.getRuntime().exec("/usr/bin/xterm"); } if(term == null) { System.exit(-1); } System.setOut(new PrintStream(term.getOutputStream())); System.out.println("~~Welcome to Doors~~"); player = Command.start(in, player); if (player == null) { System.out.println("Player is null. This should be impossible."); System.exit(1); } run(); } public static void run() throws InterruptedException, ClassNotFoundException, IOException { while (true) { System.out.print("Loading Doors."); Thread.sleep(1000); System.out.print("."); Thread.sleep(1000); System.out.println("."); Thread.sleep(1000); Doors.show(); in.reset(); Command.doors(in, player); } } /** * @return the player */ public static Player getPlayer() { return player; } /** * Fix for nullPointer when setting the player * * @param name * @param command * @throws InterruptedException * @throws IOException * @throws ClassNotFoundException */ public static void setPlayer(String name, Scanner command) throws InterruptedException, ClassNotFoundException, IOException { player = new Player(name, command); } /** * Loads the player in from a saved .ser file * * @param name * @param command * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ public static Player loadGame(String file) throws ClassNotFoundException, IOException, InterruptedException { File check = new File(System.getProperty("user.dir")+"/door_saves/" + file + ".ser"); if(!check.exists()) { System.out.println("No game file found or game is corrupted."); main(argsInternal); } FileInputStream fileIn = new FileInputStream(System.getProperty("user.dir")+"/door_saves/" + file + ".ser"); ObjectInputStream input = new ObjectInputStream(fileIn); player = (Player) input.readObject(); player.setScanner(in); setPlayer(player); player.resetRandom(); input.close(); fileIn.close(); return player; } /** * * @throws ClassNotFoundException * @throws IOException * @throws InterruptedException */ public static Player pickSaveFile() throws ClassNotFoundException, IOException, InterruptedException { File filepath = new File(System.getProperty("user.dir") + "/door_saves/"); File[] saveGames = filepath.listFiles(); if (saveGames != null && saveGames.length > 0) { System.out.println("Here are the save games to choose from: "); for (File save : saveGames) { System.out.println(" " + save.getName().substring(0, save.getName().length() - 4)); } System.out.println("Please select a game to load."); System.out.print("Command: "); if (in.hasNext()) { String input = in.next(); for (File save : saveGames) { if (input.equalsIgnoreCase(save.getName().substring(0, save.getName().length() - 4))) { return loadGame(save.getName().substring(0, save.getName().length() - 4)); } } if (input.equalsIgnoreCase("help")) { System.out .println("Please enter the name of the file you would like to play."); in.nextLine(); return pickSaveFile(); } else if (input.equalsIgnoreCase("exit") || input.equalsIgnoreCase("quit")) { System.exit(0); } } else { in.nextLine(); return pickSaveFile(); } } else { System.out.println("There are no save games available!"); return Command.start(in, player); } return player; } public static void saveGame() throws IOException { String filepath = System.getProperty("user.dir"); if (!new File(filepath + "/door_saves").exists()) { if (new File(filepath + "/door_saves").mkdir()) { FileOutputStream fileOut = new FileOutputStream(filepath + "/door_saves/" + player.getName() + ".ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(player); System.out.println("Game saved!"); out.close(); fileOut.close(); } else System.out .println("Error creating save folder! Game not saved."); } else { FileOutputStream fileOut = new FileOutputStream(filepath + "/door_saves/" + player.getName() + ".ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(player); System.out.println("Game saved!"); out.close(); fileOut.close(); } } /** * @param player * the player to set */ public static void setPlayer(Player player) { Game.player = player; } }
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static Map<String, String> mapClasses, mapTokens; private static String pathToGrammar, pathToInput; private static ArrayList<String> lines; /* * Main method and driver of the program * @arg[0] Grammar * @arg[1] Input */ public static void main(String[] args) { // Ensure proper input parameters inputValidation(args); // The two file paths (grammar and input file respectively) pathToGrammar = args[0]; pathToInput = args[1]; // Input and scan the grammar file Scanner scannerGrammar = scan(pathToGrammar); // Parse the classes and then the tokens Pattern pattern = parseClasses(scannerGrammar); parseTokens(scannerGrammar, pattern); // TODO - input the input file readInput(scan(pathToInput)); } /* * Take file path and return the scanner */ private static Scanner scan(String path) { Scanner scanner = null; try { scanner = new Scanner(new File(path)); } catch (FileNotFoundException e) { System.err.println("File not found"); System.exit(-1); } return scanner; } /* * Test inputs to ensure validity */ private static void inputValidation(String[] args) { // Must have two argument inputs - grammar and sample input if (args.length != 2) { System.out.println("Invalid parameters. Try:\njava Main <path/to/grammar> <path/to/input>"); System.exit(-1); } } /* * Iterates over the lines of the grammar file for classes (before the line break) */ private static Pattern parseClasses(Scanner scanner) { // HashMap of classes and their class type mapClasses = new HashMap<String, String>(); // Parse for character classes in grammar file Pattern pattern = Pattern.compile("\\$[A-Z-]+"); while(scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.trim().equals("")) { // A blank line means switch to the token parsing break; } Matcher matcher = pattern.matcher(line); matcher.find(); String charClass = matcher.group(0); String rest = removeInitialWhitespace(line.substring(matcher.end())); mapClasses.put(charClass, rest); } // Output all the character classes that we just scanned System.out.println("Character Classes:"); for(String key : mapClasses.keySet()) { System.out.println("{" + key + ", " + mapClasses.get(key) +"}"); } System.out.println(); return pattern; } /* * Iterates over the grammar file after the line break (so for tokens) */ private static void parseTokens(Scanner scanner, Pattern pattern) { // HashMap of tokens and their token type mapTokens = new HashMap<String, String>(); // Parse for character tokens while (scanner.hasNextLine()) { String line = scanner.nextLine(); Matcher matcher = pattern.matcher(line); matcher.find(); String token = matcher.group(0); String rest = removeInitialWhitespace(line.substring(matcher.end())); mapTokens.put(token, rest); } // Output all the character tokens that we just scanned System.out.println("Tokens:"); for(String key : mapTokens.keySet()) { System.out.println("{" + key + ", " + mapTokens.get(key) +"}"); } } /* * Removes all whitespace from a string */ private static String removeInitialWhitespace(String substring) { Pattern initialWhitespace = Pattern.compile("^\\s+"); Matcher whitespaceMatcher = initialWhitespace.matcher(substring); return whitespaceMatcher.replaceAll(""); } private static void readInput(Scanner in) { lines = new ArrayList<String>(); while(in.hasNext()) { lines.add(in.nextLine()); } //Print out Input File System.out.println("\nInput File:"); for(String s:lines) { System.out.println(s); } } }
import java.util.Scanner; public class Main { public static void main(String[] args) { testMode(); // productionMode(); } private static void testMode() { Maze maze = new Maze(23, 21); MazeFactory factory = new MazeFactory(maze); MazeAlgorithm algorithm = new MazeAlgorithm(); factory.generate(3, 2); algorithm.printToFile(maze); algorithm.print(maze); } private static void productionMode() { Scanner in = new Scanner(System.in); int entry; int exit; int width; int height; System.out.println("< Maze dimensions >"); System.out.println("Recommended values: odd numbers greater than 9"); System.out.println("Height: "); height = in.nextInt(); System.out.println("Width: "); width = in.nextInt(); System.out.println("< Entry & Exit >"); System.out.println("Entry: "); entry = in.nextInt(); System.out.println("Exit: "); exit = in.nextInt(); Maze maze = new Maze(width, height); MazeFactory factory = new MazeFactory(maze); MazeAlgorithm algorithm = new MazeAlgorithm(); factory.generate(entry, exit); algorithm.print(maze); } }
public class Main { //COMMAND LINE ARGUMENTS ARE : [0]: 1 [1]: Hi [2]: True public static void main(String[] args) { //prints 'begin' System.out.println("begin"); for (String arg:args) { //print 2 new lines, followed by 'your arg is' and the arg itself System.out.println("\n\nyour arg is: " + arg); // take each arg, parse it to an into, store in int variable num. int num = Integer.parseInt(arg); //if > 0, tell me.. if (num > 0) { System.out.println("The int " + num +" is > 0"); // if < 0, tell me.. }else if (num < 0) { System.out.println("The int" + num + " is <= 0"); // If == 0, tell me.. }else { System.out.println("The int" + num + " IS 0!"); } //Math System.out.println("Lets do some math on "+ num ); int arithmetic = 5 * 2 + (9 % 2 / 3) * 2 - 8; System.out.println("Here is some annoying arithmetic " + "5 * 2 + (9 % 2 / 3) * 2 - 8 = 2"); System.out.println("arithmetic is equal to " + arithmetic); int sum = num + arithmetic; System.out.println("The total sum of num + arithmetic is " + sum); //Switch switch (arg) { case "0": System.out.println(arg + "is your arg"); case "1": System.out.println(arg + " is the loneliest number!"); break; case "2": System.out.println(arg + " for the road"); break; case "3": System.out.println(arg + " to get ready"); break; default: System.out.println(arg + "is a number > 3"); } } for (int i = 0; i < args.length; ++i) { System.out.println("your arg is " + args[i]); } System.out.println("\n\n after enhanced for loop"); int firstarg = Integer.parseInt(args[0]); int secondarg = Integer.parseInt(args[1]); if (firstarg > secondarg){ System.out.println(firstarg +" > "+ secondarg); }else { System.out.println(firstarg +" <= "+ secondarg); } } }
import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Vector; import javax.swing.AbstractListModel; import javax.swing.DefaultComboBoxModel; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class View { public JFrame frmHealthcareManagementSystem; private JTextField textField_usr; private JPasswordField textField_passwd; private JPasswordField passwordFieldPIN; private JTable tableHistoryVisits; private JTable tableVisitsFounded; private JTextField textFieldInsertClinicRue; private JTextField textFieldInsertClinicCity; private JTextField textFieldInsertClinicZipCode; private JTextField textFieldInsertClinicName; private JTable tableClinics; private JTable tableVisitsPatientResults; private CardLayout clfrmHealhcareManagementSystem; private Database db; private JLabel lblWelcomePatient; private ArrayList<Visit> patientVisits; private final String company = "cp02"; private JLabel[][] lbldays; private static final int DAYSR = 6; private static final int DAYSC = 7; private JComboBox<Integer> selectedMonth; private JComboBox<String> comboBoxSelectBookVisitMonth; private JComboBox<String> comboBoxClinicVisitInsertion; private JComboBox<String> comboBoxVisitsYear; private DefaultTableModel visitsHistoryModel; private JButton btnViewVisitsPatient; private CardLayout clpanelVisitPatient; private JPanel panelVisitPatient; private JList<String> listClinics; private ArrayList<String[]> companiesList; private JComboBox<String> comboBoxSelectCompany; private JTextPane txtpnVisitResultInfo; private JLabel lblWelcomeEmployee; private JComboBox<String> comboBoxSelectBookVisitType; private JComboBox<Integer> comboBoxSelectBookVisitDAy; private JButton btnLoginPatient; private JButton btnLoginEmployee; /** * Launch the application. * * @throws ParseException */ public static void main(String[] args) throws ParseException { try { // Set System L&F UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException e) { } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } EventQueue.invokeLater(new Runnable() { public void run() { try { View window = new View(); window.frmHealthcareManagementSystem.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. * * @throws SQLException * @throws ClassNotFoundException */ public View() throws ClassNotFoundException, SQLException { this.db = new Database(); initialize(); } private int getDaysInMonth(int year, int month) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); return cal.getActualMaximum(Calendar.DAY_OF_MONTH); } /** * Initialize the contents of the frame. */ @SuppressWarnings("serial") private void initialize() { frmHealthcareManagementSystem = new JFrame("HEALTHCARE MANAGEMENT SYSTEM"); frmHealthcareManagementSystem .setIconImage(Toolkit.getDefaultToolkit().getImage(View.class.getResource("/img/healthcare-icon.png"))); frmHealthcareManagementSystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmHealthcareManagementSystem.getContentPane().setLayout(new CardLayout(0, 0)); this.clfrmHealhcareManagementSystem = (CardLayout) frmHealthcareManagementSystem.getContentPane().getLayout(); JPanel panelLogin = new JPanel(); frmHealthcareManagementSystem.getContentPane().add(panelLogin, "panelLogin"); panelLogin.setLayout(new BorderLayout(0, 0)); JTabbedPane tabbedPaneLogin = new JTabbedPane(JTabbedPane.TOP); tabbedPaneLogin.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (tabbedPaneLogin.getSelectedIndex() == 0) frmHealthcareManagementSystem.getRootPane().setDefaultButton(btnLoginPatient); else frmHealthcareManagementSystem.getRootPane().setDefaultButton(btnLoginEmployee); } }); panelLogin.add(tabbedPaneLogin, BorderLayout.CENTER); JPanel panelPatientLogin = new JPanel(); tabbedPaneLogin.addTab("Area paziente", null, panelPatientLogin, null); panelPatientLogin.setLayout(new BorderLayout(0, 0)); JPanel panelCenterPatientLogin = new JPanel(); panelCenterPatientLogin.setBorder(new EmptyBorder(0, 20, 0, 0)); panelPatientLogin.add(panelCenterPatientLogin, BorderLayout.WEST); GridBagLayout gbl_panelCenterPatientLogin = new GridBagLayout(); gbl_panelCenterPatientLogin.columnWeights = new double[] { 0.0, 1.0 }; gbl_panelCenterPatientLogin.columnWidths = new int[] { 0, 0 }; gbl_panelCenterPatientLogin.rowHeights = new int[] { 0, 0, 0, 0 }; panelCenterPatientLogin.setLayout(gbl_panelCenterPatientLogin); JLabel lblFiscalCode = new JLabel("Codice Fiscale:"); lblFiscalCode.setHorizontalAlignment(SwingConstants.TRAILING); lblFiscalCode.setAlignmentX(1.0f); GridBagConstraints gbc_lblFiscalCode = new GridBagConstraints(); gbc_lblFiscalCode.anchor = GridBagConstraints.EAST; gbc_lblFiscalCode.fill = GridBagConstraints.VERTICAL; gbc_lblFiscalCode.insets = new Insets(0, 0, 5, 5); gbc_lblFiscalCode.gridx = 0; gbc_lblFiscalCode.gridy = 0; panelCenterPatientLogin.add(lblFiscalCode, gbc_lblFiscalCode); JFormattedTextField formattedTextFieldFiscalCode = new JFormattedTextField("MTBMHM93M51D251I"); // FORMATTARE // CON // SOLO // CARATTERI // ALFA // NUMERICI // MAX // LENGHT GridBagConstraints gbc_formattedTextFieldFiscalCode = new GridBagConstraints(); gbc_formattedTextFieldFiscalCode.insets = new Insets(0, 0, 5, 0); gbc_formattedTextFieldFiscalCode.fill = GridBagConstraints.HORIZONTAL; gbc_formattedTextFieldFiscalCode.gridx = 1; gbc_formattedTextFieldFiscalCode.gridy = 0; panelCenterPatientLogin.add(formattedTextFieldFiscalCode, gbc_formattedTextFieldFiscalCode); JLabel lblPin = new JLabel("PIN:"); lblPin.setHorizontalAlignment(SwingConstants.TRAILING); lblPin.setAlignmentX(1.0f); GridBagConstraints gbc_lblPin = new GridBagConstraints(); gbc_lblPin.anchor = GridBagConstraints.EAST; gbc_lblPin.insets = new Insets(0, 0, 5, 5); gbc_lblPin.fill = GridBagConstraints.VERTICAL; gbc_lblPin.gridx = 0; gbc_lblPin.gridy = 1; panelCenterPatientLogin.add(lblPin, gbc_lblPin); passwordFieldPIN = new JPasswordField(16); GridBagConstraints gbc_passwordFieldPIN = new GridBagConstraints(); gbc_passwordFieldPIN.insets = new Insets(0, 0, 5, 0); gbc_passwordFieldPIN.fill = GridBagConstraints.BOTH; gbc_passwordFieldPIN.gridx = 1; gbc_passwordFieldPIN.gridy = 1; panelCenterPatientLogin.add(passwordFieldPIN, gbc_passwordFieldPIN); btnLoginPatient = new JButton("Login"); frmHealthcareManagementSystem.getRootPane().setDefaultButton(btnLoginPatient); GridBagConstraints gbc_btnLoginPatient = new GridBagConstraints(); gbc_btnLoginPatient.gridx = 1; gbc_btnLoginPatient.gridy = 3; panelCenterPatientLogin.add(btnLoginPatient, gbc_btnLoginPatient); btnLoginPatient.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String fiscalCode = formattedTextFieldFiscalCode.getText(); String passwd = new String(passwordFieldPIN.getPassword()); if (db.checkPatient(fiscalCode, passwd)) { lblWelcomePatient.setText(lblWelcomePatient.getText() + Patient.getInstance().getName() + " " + Patient.getInstance().getSurname()); clfrmHealhcareManagementSystem.show(frmHealthcareManagementSystem.getContentPane(), "panelPatient"); // clean fiscal code and password formattedTextFieldFiscalCode.setText(""); passwordFieldPIN.setText(""); // get years ArrayList<Integer> years = db.getVisitsHistoryYears(fiscalCode); for (Integer y : years) comboBoxVisitsYear.addItem(y.toString()); // fill table (visits history) int i = 1; patientVisits = db.getVisitsHistory(fiscalCode); if (patientVisits != null) { System.out.println("visits is not null " + patientVisits.size()); for (Visit c : patientVisits) { System.out.println("element i"); Vector<Object> row = new Vector<Object>(); row.add(i++); row.add(c.getDate().toString()); row.add(c.getHour()); row.add(c.getServiceName()); row.add(c.getRegime()); row.add(c.getUrgency()); visitsHistoryModel.addRow(row); } } // initialize book visit panel ArrayList<String> services = db.getServices(Patient.getInstance().getHealthcarecompany()); System.out.println(Employee.getInstance().getCompany()); System.out.println(services); for (String s : services) comboBoxSelectBookVisitType.addItem(s); } else { System.out.println("credenziali errate: " + fiscalCode + " " + passwd); JOptionPane.showMessageDialog(null, "Nome utente o password errati o mancanti", "Errore accesso", JOptionPane.WARNING_MESSAGE); } } }); JLabel lblBackGroundImageMainPage = new JLabel(); lblBackGroundImageMainPage.setHorizontalAlignment(SwingConstants.CENTER); lblBackGroundImageMainPage.setIcon(new ImageIcon(View.class.getResource("/img/healthcare-icon.png"))); panelPatientLogin.add(lblBackGroundImageMainPage, BorderLayout.CENTER); JPanel panelEmployeeLogin = new JPanel(); tabbedPaneLogin.addTab("Area dipendente", null, panelEmployeeLogin, null); panelEmployeeLogin.setLayout(new BorderLayout(0, 0)); JPanel panelCenterEmployeeLogin = new JPanel(); panelCenterEmployeeLogin.setBorder(new EmptyBorder(0, 20, 0, 0)); panelEmployeeLogin.add(panelCenterEmployeeLogin, BorderLayout.WEST); GridBagLayout gbl_panelCenterEmployeeLogin = new GridBagLayout(); gbl_panelCenterEmployeeLogin.columnWidths = new int[] { 0, 0, 0 }; gbl_panelCenterEmployeeLogin.rowHeights = new int[] { 0, 0, 0, 0 }; panelCenterEmployeeLogin.setLayout(gbl_panelCenterEmployeeLogin); JLabel lblUsername = new JLabel("Nome utente:"); GridBagConstraints gbc_lblUsername = new GridBagConstraints(); gbc_lblUsername.fill = GridBagConstraints.BOTH; gbc_lblUsername.insets = new Insets(0, 0, 5, 5); gbc_lblUsername.gridx = 0; gbc_lblUsername.gridy = 0; panelCenterEmployeeLogin.add(lblUsername, gbc_lblUsername); lblUsername.setHorizontalAlignment(SwingConstants.TRAILING); lblUsername.setAlignmentX(Component.RIGHT_ALIGNMENT); textField_usr = new JTextField(16); textField_usr.setText("JOBIT0001"); GridBagConstraints gbc_textField_usr = new GridBagConstraints(); gbc_textField_usr.fill = GridBagConstraints.BOTH; gbc_textField_usr.insets = new Insets(0, 0, 5, 5); gbc_textField_usr.gridx = 1; gbc_textField_usr.gridy = 0; panelCenterEmployeeLogin.add(textField_usr, gbc_textField_usr); JLabel lblPassword = new JLabel("Password:"); GridBagConstraints gbc_lblPassword = new GridBagConstraints(); gbc_lblPassword.fill = GridBagConstraints.BOTH; gbc_lblPassword.insets = new Insets(0, 0, 5, 5); gbc_lblPassword.gridx = 0; gbc_lblPassword.gridy = 1; panelCenterEmployeeLogin.add(lblPassword, gbc_lblPassword); lblPassword.setHorizontalAlignment(SwingConstants.TRAILING); lblPassword.setAlignmentX(Component.RIGHT_ALIGNMENT); textField_passwd = new JPasswordField(16); GridBagConstraints gbc_textField_passwd = new GridBagConstraints(); gbc_textField_passwd.insets = new Insets(0, 0, 5, 5); gbc_textField_passwd.fill = GridBagConstraints.BOTH; gbc_textField_passwd.gridx = 1; gbc_textField_passwd.gridy = 1; panelCenterEmployeeLogin.add(textField_passwd, gbc_textField_passwd); btnLoginEmployee = new JButton("Login"); btnLoginEmployee.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String user = textField_usr.getText(); String pass = new String(textField_passwd.getPassword()); if (db.checkEmployee(user, pass)) { lblWelcomeEmployee.setText(lblWelcomeEmployee.getText() + Employee.getInstance().getName() + " " + Employee.getInstance().getSurname()); clfrmHealhcareManagementSystem.show(frmHealthcareManagementSystem.getContentPane(), "panelEmployee"); // add clinics ArrayList<Clinic> clinics = db.getClinics(Employee.getInstance().getCompany()); System.out.println(clinics.size() + " " + Employee.getInstance().getCompany()); for (Clinic c : clinics) comboBoxClinicVisitInsertion.addItem(c.getName()); } else { System.out.println("wrong credentials: " + user + " " + pass); } } }); GridBagConstraints gbc_btnLoginEmployee = new GridBagConstraints(); gbc_btnLoginEmployee.insets = new Insets(0, 0, 0, 5); gbc_btnLoginEmployee.gridx = 1; gbc_btnLoginEmployee.gridy = 3; panelCenterEmployeeLogin.add(btnLoginEmployee, gbc_btnLoginEmployee); JLabel label = new JLabel(); label.setHorizontalAlignment(SwingConstants.CENTER); label.setIcon(new ImageIcon(View.class.getResource("/img/healthcare-icon.png"))); panelEmployeeLogin.add(label, BorderLayout.CENTER); JPanel panelSouthLogin = new JPanel(); panelLogin.add(panelSouthLogin, BorderLayout.SOUTH); JButton btnViewClinicAnd = new JButton("Ambulatori & Servizi"); btnViewClinicAnd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { companiesList = db.getCompanies(); for (String[] o : companiesList) { comboBoxSelectCompany.addItem(o[1]); } clfrmHealhcareManagementSystem.show(frmHealthcareManagementSystem.getContentPane(), "panelClinicsAndServices"); } }); panelSouthLogin.add(btnViewClinicAnd); JPanel panelPatient = new JPanel(); frmHealthcareManagementSystem.getContentPane().add(panelPatient, "panelPatient"); panelPatient.setLayout(new BorderLayout(0, 0)); JPanel panelPatientNorth = new JPanel(); panelPatient.add(panelPatientNorth, BorderLayout.NORTH); panelPatientNorth.setLayout(new BorderLayout(0, 0)); lblWelcomePatient = new JLabel("Benvenuto "); lblWelcomePatient.setHorizontalAlignment(SwingConstants.CENTER); panelPatientNorth.add(lblWelcomePatient, BorderLayout.CENTER); lblWelcomePatient.setFont(new Font("Tahoma", Font.BOLD, 22)); JPanel panelPatientNorthRightLabels = new JPanel(); FlowLayout fl_panelPatientNorthRightLabels = (FlowLayout) panelPatientNorthRightLabels.getLayout(); fl_panelPatientNorthRightLabels.setHgap(10); fl_panelPatientNorthRightLabels.setVgap(10); panelPatientNorth.add(panelPatientNorthRightLabels, BorderLayout.EAST); JLabel lblLogoutPatient = new JLabel("<HTML>\r\n\t<p style=\"color:blue;\"><u>Logout</u></p>\r\n</HTML>"); lblLogoutPatient.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { System.out.println("Patient clicked on Logout"); clfrmHealhcareManagementSystem.show(frmHealthcareManagementSystem.getContentPane(), "panelLogin"); // qui va chiamata una funzione per resettare tutti i parametri // quindi distruggere tutti i pannelli dell'utente loggato. } @Override public void mouseEntered(MouseEvent e) { lblLogoutPatient.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } }); panelPatientNorthRightLabels.add(lblLogoutPatient); lblLogoutPatient.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblLogoutPatient.setHorizontalAlignment(SwingConstants.CENTER); JTabbedPane tabbedPanePatient = new JTabbedPane(JTabbedPane.TOP); panelPatient.add(tabbedPanePatient, BorderLayout.CENTER); panelVisitPatient = new JPanel(); tabbedPanePatient.addTab("Storico prenotazioni", null, panelVisitPatient, null); panelVisitPatient.setLayout(new CardLayout(0, 0)); clpanelVisitPatient = (CardLayout) panelVisitPatient.getLayout(); JPanel panelHistoryVisitPatient = new JPanel(); panelVisitPatient.add(panelHistoryVisitPatient, "panelHistoryVisitPatient"); panelHistoryVisitPatient.setLayout(new BorderLayout(0, 0)); JPanel panelHistoryNorth = new JPanel(); FlowLayout fl_panelHistoryNorth = (FlowLayout) panelHistoryNorth.getLayout(); fl_panelHistoryNorth.setAlignment(FlowLayout.LEFT); panelHistoryVisitPatient.add(panelHistoryNorth, BorderLayout.NORTH); JLabel lblSelectYearPatientVisit = new JLabel("Seleziona anno:"); panelHistoryNorth.add(lblSelectYearPatientVisit); comboBoxVisitsYear = new JComboBox<String>(); panelHistoryNorth.add(comboBoxVisitsYear); JScrollPane scrollPaneHistory = new JScrollPane(); panelHistoryVisitPatient.add(scrollPaneHistory, BorderLayout.CENTER); tableHistoryVisits = new JTable(); tableHistoryVisits.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); visitsHistoryModel = new DefaultTableModel( new String[] { "N\u00B0", "Data", "Ora", "Tipo Visita", "Regime", "Urgenza" }, 0) { @Override public boolean isCellEditable(int row, int column) { return false; } }; tableHistoryVisits.setModel(visitsHistoryModel); tableHistoryVisits.getColumnModel().getColumn(0).setPreferredWidth(25); tableHistoryVisits.getColumnModel().getColumn(0).setMaxWidth(25); tableHistoryVisits.getTableHeader().setReorderingAllowed(false); tableHistoryVisits.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { // do some actions here, for example // print first column value from selected row if (!event.getValueIsAdjusting()) { System.out .println(tableHistoryVisits.getValueAt(tableHistoryVisits.getSelectedRow(), 0).toString()); btnViewVisitsPatient.setEnabled(true); } } }); scrollPaneHistory.setViewportView(tableHistoryVisits); JPanel panelHistoryButtons = new JPanel(); FlowLayout fl_panelHistoryButtons = (FlowLayout) panelHistoryButtons.getLayout(); fl_panelHistoryButtons.setAlignment(FlowLayout.RIGHT); panelHistoryVisitPatient.add(panelHistoryButtons, BorderLayout.SOUTH); btnViewVisitsPatient = new JButton("Visualizza"); btnViewVisitsPatient.setEnabled(false); btnViewVisitsPatient.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clpanelVisitPatient.next(panelVisitPatient); int visitIndex = (int) tableHistoryVisits.getValueAt(tableHistoryVisits.getSelectedRow(), 0) - 1; Visit v = patientVisits.get(visitIndex); txtpnVisitResultInfo .setText(v.toHTML(Patient.getInstance().getName(), Patient.getInstance().getSurname())); // patientVisits } }); panelHistoryButtons.add(btnViewVisitsPatient); JPanel panelVisitResultPatient = new JPanel(); panelVisitPatient.add(panelVisitResultPatient, "panelVisitResultPatient"); panelVisitResultPatient.setLayout(new BorderLayout(0, 0)); JPanel resultVisitSouthpanel = new JPanel(); FlowLayout flowLayout = (FlowLayout) resultVisitSouthpanel.getLayout(); flowLayout.setAlignment(FlowLayout.RIGHT); panelVisitResultPatient.add(resultVisitSouthpanel, BorderLayout.SOUTH); JButton btnBeckToHistory = new JButton("Indietro"); btnBeckToHistory.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clpanelVisitPatient.previous(panelVisitPatient); } }); resultVisitSouthpanel.add(btnBeckToHistory); JButton btnPrintVisitResult = new JButton("Stampa"); btnPrintVisitResult.setHorizontalTextPosition(SwingConstants.CENTER); btnPrintVisitResult.setAlignmentX(Component.CENTER_ALIGNMENT); resultVisitSouthpanel.add(btnPrintVisitResult); txtpnVisitResultInfo = new JTextPane(); txtpnVisitResultInfo.setEditable(false); txtpnVisitResultInfo.setContentType("text/html"); panelVisitResultPatient.add(txtpnVisitResultInfo, BorderLayout.CENTER); JPanel panelBookVisit = new JPanel(); tabbedPanePatient.addTab("Prenotazione visite", null, panelBookVisit, null); panelBookVisit.setLayout(new BorderLayout(0, 0)); JPanel bookVisitCenterPanel = new JPanel(); bookVisitCenterPanel.setBorder(new EmptyBorder(5, 5, 0, 0)); panelBookVisit.add(bookVisitCenterPanel, BorderLayout.CENTER); JLabel lblSelectBookVisitType = new JLabel("Tipo visita:"); lblSelectBookVisitType.setHorizontalAlignment(SwingConstants.RIGHT); comboBoxSelectBookVisitType = new JComboBox<String>(); JLabel lblSelectBookVisitYear = new JLabel("Anno:"); lblSelectBookVisitYear.setHorizontalAlignment(SwingConstants.RIGHT); JComboBox<Integer> comboBoxSelectBookVisitYear = new JComboBox<Integer>(); comboBoxSelectBookVisitYear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // da modificare System.out.println("modified year"); } }); comboBoxSelectBookVisitYear.addItem(Calendar.getInstance().get(Calendar.YEAR)); comboBoxSelectBookVisitYear.addItem(Calendar.getInstance().get(Calendar.YEAR) + 1); JLabel lblSelectBookVisitMonth = new JLabel("Mese:"); comboBoxSelectBookVisitMonth = new JComboBox<String>(); comboBoxSelectBookVisitMonth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // da modificare System.out.println("modified month"); } }); comboBoxSelectBookVisitMonth.setModel(new DefaultComboBoxModel(Month.values())); JLabel lblSelectBookVisitDay = new JLabel("Giorno:"); lblSelectBookVisitDay.setHorizontalAlignment(SwingConstants.RIGHT); comboBoxSelectBookVisitDAy = new JComboBox<Integer>(); comboBoxSelectBookVisitDAy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // da modificare System.out.println("modified day"); } }); comboBoxSelectBookVisitDAy.setEnabled(false); JLabel lblSelectBookVisitHour = new JLabel("Ora:"); JComboBox comboBoxSelectBookVisitHour = new JComboBox(); comboBoxSelectBookVisitHour.setEnabled(false); JLabel lblSelectBookVisitUrgency = new JLabel("Urgenza:"); lblSelectBookVisitUrgency.setHorizontalAlignment(SwingConstants.RIGHT); JComboBox comboBoxSelectBookVisitUrgency = new JComboBox(); comboBoxSelectBookVisitUrgency.setModel(new DefaultComboBoxModel(new String[] { "Bassa", "Medio", "Alta" })); JLabel lblSelectBookVisitRegime = new JLabel("Regime:"); lblSelectBookVisitRegime.setHorizontalAlignment(SwingConstants.RIGHT); JComboBox comboBoxSelectBookVisitRegime = new JComboBox(); JLabel lblAmbultorio = new JLabel("Ambulatorio:"); lblAmbultorio.setHorizontalAlignment(SwingConstants.RIGHT); JComboBox comboBoxSelectBookVisitClinic = new JComboBox(); comboBoxSelectBookVisitClinic.setEnabled(false); GroupLayout gl_bookVisitCenterPanel = new GroupLayout(bookVisitCenterPanel); gl_bookVisitCenterPanel.setHorizontalGroup(gl_bookVisitCenterPanel.createParallelGroup( Alignment.TRAILING) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup().addContainerGap().addGroup( gl_bookVisitCenterPanel.createParallelGroup(Alignment.TRAILING) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup().addGroup( gl_bookVisitCenterPanel .createParallelGroup(Alignment.LEADING, false).addGroup( Alignment.TRAILING, gl_bookVisitCenterPanel.createSequentialGroup().addGap(5) .addComponent(lblSelectBookVisitRegime).addPreferredGap( ComponentPlacement.RELATED) .addComponent(comboBoxSelectBookVisitRegime, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup() .addComponent(lblSelectBookVisitUrgency).addGap(5) .addComponent(comboBoxSelectBookVisitUrgency, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup() .addGroup(gl_bookVisitCenterPanel .createParallelGroup(Alignment.TRAILING, false) .addComponent(lblSelectBookVisitYear, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblSelectBookVisitDay, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_bookVisitCenterPanel .createParallelGroup(Alignment.TRAILING) .addComponent(comboBoxSelectBookVisitYear, 0, 92, Short.MAX_VALUE) .addComponent(comboBoxSelectBookVisitDAy, Alignment.LEADING, 0, 92, Short.MAX_VALUE)))) .addGap(28) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.TRAILING) .addComponent(lblSelectBookVisitMonth) .addComponent(lblSelectBookVisitHour)) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.LEADING, false) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup().addGap(5) .addComponent(comboBoxSelectBookVisitMonth, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED) .addComponent(comboBoxSelectBookVisitHour, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(Alignment.LEADING, gl_bookVisitCenterPanel.createSequentialGroup().addGap(148) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup() .addComponent(lblSelectBookVisitType, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED).addComponent( comboBoxSelectBookVisitType, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup() .addComponent(lblAmbultorio, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(comboBoxSelectBookVisitClinic, 0, 256, Short.MAX_VALUE))))) .addGap(144))); gl_bookVisitCenterPanel .setVerticalGroup( gl_bookVisitCenterPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_bookVisitCenterPanel .createSequentialGroup().addGap( 48) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.BASELINE) .addComponent(comboBoxSelectBookVisitType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSelectBookVisitType)) .addGap(28) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.BASELINE) .addComponent(comboBoxSelectBookVisitClinic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblAmbultorio)) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED, 36, Short.MAX_VALUE) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup() .addGap(3).addComponent(lblSelectBookVisitMonth)) .addComponent(comboBoxSelectBookVisitMonth, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(32)) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup().addGap(39) .addGroup(gl_bookVisitCenterPanel .createParallelGroup(Alignment.BASELINE) .addComponent(lblSelectBookVisitYear).addComponent( comboBoxSelectBookVisitYear, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED))) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.TRAILING) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.BASELINE) .addComponent(comboBoxSelectBookVisitDAy, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSelectBookVisitDay)) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.BASELINE) .addComponent(lblSelectBookVisitHour) .addComponent(comboBoxSelectBookVisitHour, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(35) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_bookVisitCenterPanel.createSequentialGroup().addGap(3) .addComponent(lblSelectBookVisitUrgency)) .addComponent(comboBoxSelectBookVisitUrgency, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(38) .addGroup(gl_bookVisitCenterPanel.createParallelGroup(Alignment.BASELINE) .addComponent(lblSelectBookVisitRegime) .addComponent(comboBoxSelectBookVisitRegime, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(72))); bookVisitCenterPanel.setLayout(gl_bookVisitCenterPanel); JLabel lblLuned = new JLabel("Luned\u00EC"); JLabel lblMarted = new JLabel("Marted\u00EC"); JPanel bookVisitSouthButtonPanel = new JPanel(); bookVisitSouthButtonPanel.setBorder(new LineBorder(Color.LIGHT_GRAY)); FlowLayout fl_bookVisitSouthButtonPanel = (FlowLayout) bookVisitSouthButtonPanel.getLayout(); fl_bookVisitSouthButtonPanel.setAlignment(FlowLayout.RIGHT); panelBookVisit.add(bookVisitSouthButtonPanel, BorderLayout.SOUTH); JButton btnBookVisit = new JButton("Prenota"); btnBookVisit.setEnabled(false); btnBookVisit.setToolTipText("Clicca per prenotare"); bookVisitSouthButtonPanel.add(btnBookVisit); JPanel panelEmployee = new JPanel(); frmHealthcareManagementSystem.getContentPane().add(panelEmployee, "panelEmployee"); panelEmployee.setLayout(new BorderLayout(0, 0)); JTabbedPane tabbedPaneEmployee = new JTabbedPane(JTabbedPane.TOP); panelEmployee.add(tabbedPaneEmployee, BorderLayout.CENTER); JPanel panelInsertVisitInfo = new JPanel(); tabbedPaneEmployee.addTab("Inserisci risultato", null, panelInsertVisitInfo, null); panelInsertVisitInfo.setLayout(new BorderLayout(0, 0)); JPanel panelInfoVisitInsertion = new JPanel(); panelInsertVisitInfo.add(panelInfoVisitInsertion, BorderLayout.CENTER); panelInfoVisitInsertion.setLayout(new BorderLayout(0, 0)); JPanel panelInfovisitInsertionNorth = new JPanel(); FlowLayout fl_panelInfovisitInsertionNorth = (FlowLayout) panelInfovisitInsertionNorth.getLayout(); fl_panelInfovisitInsertionNorth.setAlignment(FlowLayout.LEFT); panelInfoVisitInsertion.add(panelInfovisitInsertionNorth, BorderLayout.NORTH); JLabel lblDateVisitInsertion = new JLabel("Data:"); panelInfovisitInsertionNorth.add(lblDateVisitInsertion); DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); JFormattedTextField formattedTextFieldVisitInsertion = new JFormattedTextField(sdf); formattedTextFieldVisitInsertion.setToolTipText("Inserisci la data della visita nel formato gg/mm/aaaa"); formattedTextFieldVisitInsertion.setColumns(10); panelInfovisitInsertionNorth.add(formattedTextFieldVisitInsertion); JLabel lblClinicVisitInsertion = new JLabel("Ambulatorio:"); panelInfovisitInsertionNorth.add(lblClinicVisitInsertion); comboBoxClinicVisitInsertion = new JComboBox<String>(); comboBoxClinicVisitInsertion.setPreferredSize(new Dimension(150, 27)); comboBoxClinicVisitInsertion.setMaximumRowCount(10); panelInfovisitInsertionNorth.add(comboBoxClinicVisitInsertion); DefaultTableModel employeeInsertVisitModel = new DefaultTableModel( new String[] { "Codice Fiscale", "Tipo visita", "Urgenza", "Ora" }, 0) { @Override public boolean isCellEditable(int row, int column) { return false; } }; JButton btnFindVisits = new JButton("Trova"); btnFindVisits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // free table while (employeeInsertVisitModel.getRowCount() > 0) employeeInsertVisitModel.removeRow(0); String date = formattedTextFieldVisitInsertion.getText(); ArrayList<Visit> visits = null; try { visits = db.getBookedVisits(Employee.getInstance().getCompany(), (String) comboBoxClinicVisitInsertion.getSelectedItem(), new Date(sdf.parse(date).getTime())); } catch (ParseException e1) { formattedTextFieldVisitInsertion.setText(""); JOptionPane.showMessageDialog(null, "Inserire una data valida nel formato gg/MM/aaaa", "Errore data", JOptionPane.WARNING_MESSAGE); } if (visits != null) { System.out.println("visits is not null " + visits.size()); for (Visit c : visits) { System.out.println("element i"); Vector<Object> vector = new Vector<Object>(); vector.add(c.getPatient()); vector.add(c.getServiceName()); vector.add(c.getUrgency()); vector.add(c.getHour()); employeeInsertVisitModel.addRow(vector); } } } }); panelInfovisitInsertionNorth.add(btnFindVisits); JScrollPane scrollPaneInfoVisitInsertionCenter = new JScrollPane(); panelInfoVisitInsertion.add(scrollPaneInfoVisitInsertionCenter, BorderLayout.CENTER); tableVisitsFounded = new JTable(); tableVisitsFounded.setModel(employeeInsertVisitModel); tableVisitsFounded.getTableHeader().setReorderingAllowed(false); scrollPaneInfoVisitInsertionCenter.setViewportView(tableVisitsFounded); JScrollPane scrollPaneInfoVisitInsertionSouth = new JScrollPane(); scrollPaneInfoVisitInsertionSouth.setViewportBorder( new TitledBorder(null, "Risultato visita", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panelInfoVisitInsertion.add(scrollPaneInfoVisitInsertionSouth, BorderLayout.SOUTH); JTextArea textAreaVisitResult = new JTextArea(); textAreaVisitResult.setRows(3); scrollPaneInfoVisitInsertionSouth.setViewportView(textAreaVisitResult); JPanel panelInsertVisitButton = new JPanel(); FlowLayout fl_panelInsertVisitButton = (FlowLayout) panelInsertVisitButton.getLayout(); fl_panelInsertVisitButton.setAlignment(FlowLayout.RIGHT); panelInsertVisitInfo.add(panelInsertVisitButton, BorderLayout.SOUTH); JButton btnInsertNewVisit = new JButton("Inserisci"); btnInsertNewVisit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("clicked inserisci"); } }); btnInsertNewVisit.setEnabled(false); panelInsertVisitButton.add(btnInsertNewVisit); JPanel panelInsertClinicMaster = new JPanel(); tabbedPaneEmployee.addTab("Inserisci ambulatorio", null, panelInsertClinicMaster, null); GridBagLayout gbl_panelInsertClinicMaster = new GridBagLayout(); gbl_panelInsertClinicMaster.columnWidths = new int[] { 579, 0 }; gbl_panelInsertClinicMaster.rowHeights = new int[] { 288, 75, 33, 0 }; gbl_panelInsertClinicMaster.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gbl_panelInsertClinicMaster.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE }; panelInsertClinicMaster.setLayout(gbl_panelInsertClinicMaster); JPanel panelInsertClinic = new JPanel(); GridBagConstraints gbc_panelInsertClinic = new GridBagConstraints(); gbc_panelInsertClinic.anchor = GridBagConstraints.NORTH; gbc_panelInsertClinic.fill = GridBagConstraints.HORIZONTAL; gbc_panelInsertClinic.insets = new Insets(0, 0, 5, 0); gbc_panelInsertClinic.gridx = 0; gbc_panelInsertClinic.gridy = 0; panelInsertClinicMaster.add(panelInsertClinic, gbc_panelInsertClinic); panelInsertClinic.setLayout(new BorderLayout(0, 0)); JPanel panelInsertClinicData = new JPanel(); panelInsertClinic.add(panelInsertClinicData, BorderLayout.WEST); panelInsertClinicData.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Dati", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0))); GridBagLayout gbl_panelInsertClinicData = new GridBagLayout(); gbl_panelInsertClinicData.columnWidths = new int[] { 150, 0 }; gbl_panelInsertClinicData.rowHeights = new int[] { 20, 14, 20, 14, 20, 14, 20, 14, 20, 14, 20, 14, 0 }; gbl_panelInsertClinicData.columnWeights = new double[] { 0.0, Double.MIN_VALUE }; gbl_panelInsertClinicData.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE }; panelInsertClinicData.setLayout(gbl_panelInsertClinicData); JLabel lblInsertClinicName = new JLabel("Nome:"); GridBagConstraints gbc_lblInsertClinicName = new GridBagConstraints(); gbc_lblInsertClinicName.anchor = GridBagConstraints.WEST; gbc_lblInsertClinicName.insets = new Insets(0, 0, 5, 0); gbc_lblInsertClinicName.gridx = 0; gbc_lblInsertClinicName.gridy = 0; panelInsertClinicData.add(lblInsertClinicName, gbc_lblInsertClinicName); textFieldInsertClinicName = new JTextField(); GridBagConstraints gbc_textFieldInsertClinicName = new GridBagConstraints(); gbc_textFieldInsertClinicName.fill = GridBagConstraints.HORIZONTAL; gbc_textFieldInsertClinicName.insets = new Insets(0, 0, 5, 0); gbc_textFieldInsertClinicName.gridx = 0; gbc_textFieldInsertClinicName.gridy = 1; panelInsertClinicData.add(textFieldInsertClinicName, gbc_textFieldInsertClinicName); textFieldInsertClinicName.setColumns(10); JLabel lblInsertClinicRue = new JLabel("Via:"); GridBagConstraints gbc_lblInsertClinicRue = new GridBagConstraints(); gbc_lblInsertClinicRue.anchor = GridBagConstraints.WEST; gbc_lblInsertClinicRue.insets = new Insets(0, 0, 5, 0); gbc_lblInsertClinicRue.gridx = 0; gbc_lblInsertClinicRue.gridy = 2; panelInsertClinicData.add(lblInsertClinicRue, gbc_lblInsertClinicRue); textFieldInsertClinicRue = new JTextField(); GridBagConstraints gbc_textFieldInsertClinicRue = new GridBagConstraints(); gbc_textFieldInsertClinicRue.fill = GridBagConstraints.HORIZONTAL; gbc_textFieldInsertClinicRue.insets = new Insets(0, 0, 5, 0); gbc_textFieldInsertClinicRue.gridx = 0; gbc_textFieldInsertClinicRue.gridy = 3; panelInsertClinicData.add(textFieldInsertClinicRue, gbc_textFieldInsertClinicRue); textFieldInsertClinicRue.setColumns(10); JLabel lblInsertClinicCity = new JLabel("Paese:"); GridBagConstraints gbc_lblInsertClinicCity = new GridBagConstraints(); gbc_lblInsertClinicCity.anchor = GridBagConstraints.WEST; gbc_lblInsertClinicCity.insets = new Insets(0, 0, 5, 0); gbc_lblInsertClinicCity.gridx = 0; gbc_lblInsertClinicCity.gridy = 4; panelInsertClinicData.add(lblInsertClinicCity, gbc_lblInsertClinicCity); textFieldInsertClinicCity = new JTextField(); GridBagConstraints gbc_textFieldInsertClinicCity = new GridBagConstraints(); gbc_textFieldInsertClinicCity.fill = GridBagConstraints.HORIZONTAL; gbc_textFieldInsertClinicCity.insets = new Insets(0, 0, 5, 0); gbc_textFieldInsertClinicCity.gridx = 0; gbc_textFieldInsertClinicCity.gridy = 5; panelInsertClinicData.add(textFieldInsertClinicCity, gbc_textFieldInsertClinicCity); textFieldInsertClinicCity.setColumns(10); JLabel lblInsertClinicZipCode = new JLabel("CAP:"); GridBagConstraints gbc_lblInsertClinicZipCode = new GridBagConstraints(); gbc_lblInsertClinicZipCode.anchor = GridBagConstraints.WEST; gbc_lblInsertClinicZipCode.insets = new Insets(0, 0, 5, 0); gbc_lblInsertClinicZipCode.gridx = 0; gbc_lblInsertClinicZipCode.gridy = 6; panelInsertClinicData.add(lblInsertClinicZipCode, gbc_lblInsertClinicZipCode); textFieldInsertClinicZipCode = new JTextField(); GridBagConstraints gbc_textFieldInsertClinicZipCode = new GridBagConstraints(); gbc_textFieldInsertClinicZipCode.fill = GridBagConstraints.HORIZONTAL; gbc_textFieldInsertClinicZipCode.insets = new Insets(0, 0, 5, 0); gbc_textFieldInsertClinicZipCode.gridx = 0; gbc_textFieldInsertClinicZipCode.gridy = 7; panelInsertClinicData.add(textFieldInsertClinicZipCode, gbc_textFieldInsertClinicZipCode); textFieldInsertClinicZipCode.setColumns(10); JLabel lblInsertClinicProvince = new JLabel("Provincia:"); GridBagConstraints gbc_lblInsertClinicProvince = new GridBagConstraints(); gbc_lblInsertClinicProvince.anchor = GridBagConstraints.WEST; gbc_lblInsertClinicProvince.insets = new Insets(0, 0, 5, 0); gbc_lblInsertClinicProvince.gridx = 0; gbc_lblInsertClinicProvince.gridy = 8; panelInsertClinicData.add(lblInsertClinicProvince, gbc_lblInsertClinicProvince); JComboBox<String> comboBoxInsertClinicProvince = new JComboBox<String>(); GridBagConstraints gbc_comboBoxInsertClinicProvince = new GridBagConstraints(); gbc_comboBoxInsertClinicProvince.fill = GridBagConstraints.HORIZONTAL; gbc_comboBoxInsertClinicProvince.insets = new Insets(0, 0, 5, 0); gbc_comboBoxInsertClinicProvince.gridx = 0; gbc_comboBoxInsertClinicProvince.gridy = 9; panelInsertClinicData.add(comboBoxInsertClinicProvince, gbc_comboBoxInsertClinicProvince); JLabel lblInsertClinicContractDate = new JLabel("Data Contratto:"); GridBagConstraints gbc_lblInsertClinicContractDate = new GridBagConstraints(); gbc_lblInsertClinicContractDate.anchor = GridBagConstraints.WEST; gbc_lblInsertClinicContractDate.insets = new Insets(0, 0, 5, 0); gbc_lblInsertClinicContractDate.gridx = 0; gbc_lblInsertClinicContractDate.gridy = 10; panelInsertClinicData.add(lblInsertClinicContractDate, gbc_lblInsertClinicContractDate); JFormattedTextField formattedTextFieldInsertClinicContractDate = new JFormattedTextField(sdf); GridBagConstraints gbc_formattedTextFieldInsertClinicContractDate = new GridBagConstraints(); gbc_formattedTextFieldInsertClinicContractDate.fill = GridBagConstraints.HORIZONTAL; gbc_formattedTextFieldInsertClinicContractDate.gridx = 0; gbc_formattedTextFieldInsertClinicContractDate.gridy = 11; panelInsertClinicData.add(formattedTextFieldInsertClinicContractDate, gbc_formattedTextFieldInsertClinicContractDate); JScrollPane scrollPaneInsertClinicDescription = new JScrollPane(); panelInsertClinic.add(scrollPaneInsertClinicDescription, BorderLayout.CENTER); scrollPaneInsertClinicDescription .setBorder(new TitledBorder(null, "Descrizione", TitledBorder.LEADING, TitledBorder.TOP, null, null)); JTextArea textAreaInsertClinicDescription = new JTextArea(); scrollPaneInsertClinicDescription.setViewportView(textAreaInsertClinicDescription); JScrollPane scrollPaneViewClinics = new JScrollPane(); GridBagConstraints gbc_scrollPaneViewClinics = new GridBagConstraints(); gbc_scrollPaneViewClinics.insets = new Insets(0, 0, 5, 0); gbc_scrollPaneViewClinics.fill = GridBagConstraints.BOTH; gbc_scrollPaneViewClinics.gridx = 0; gbc_scrollPaneViewClinics.gridy = 1; panelInsertClinicMaster.add(scrollPaneViewClinics, gbc_scrollPaneViewClinics); TableModel insertClinicModel = new DefaultTableModel( new String[] { "Nome", "Via", "Paese", "CAP", "Provincia", "Data contratto", "" }, 0) { @Override public boolean isCellEditable(int row, int column) { return false; } }; tableClinics = new JTable(insertClinicModel); tableClinics.getTableHeader().setReorderingAllowed(false); scrollPaneViewClinics.setViewportView(tableClinics); JPanel panelInsertClinicButton = new JPanel(); GridBagConstraints gbc_panelInsertClinicButton = new GridBagConstraints(); gbc_panelInsertClinicButton.anchor = GridBagConstraints.NORTH; gbc_panelInsertClinicButton.fill = GridBagConstraints.HORIZONTAL; gbc_panelInsertClinicButton.gridx = 0; gbc_panelInsertClinicButton.gridy = 2; panelInsertClinicMaster.add(panelInsertClinicButton, gbc_panelInsertClinicButton); FlowLayout fl_panelInsertClinicButton = (FlowLayout) panelInsertClinicButton.getLayout(); fl_panelInsertClinicButton.setAlignment(FlowLayout.RIGHT); JButton btnInsertClinic = new JButton("Inserisci"); btnInsertClinic.setEnabled(false); panelInsertClinicButton.add(btnInsertClinic); JPanel panelVisitsResultsPerPatientMaster = new JPanel(); tabbedPaneEmployee.addTab("Visualizza visite", null, panelVisitsResultsPerPatientMaster, null); panelVisitsResultsPerPatientMaster.setLayout(new CardLayout(0, 0)); JPanel panelViewVisitPerPatient = new JPanel(); panelVisitsResultsPerPatientMaster.add(panelViewVisitPerPatient, "panelViewVisitPerPatient"); panelViewVisitPerPatient.setLayout(new BorderLayout(0, 0)); JPanel panelViewVisitPerPatientNorth = new JPanel(); FlowLayout fl_panelViewVisitPerPatientNorth = (FlowLayout) panelViewVisitPerPatientNorth.getLayout(); fl_panelViewVisitPerPatientNorth.setAlignment(FlowLayout.LEFT); panelViewVisitPerPatient.add(panelViewVisitPerPatientNorth, BorderLayout.NORTH); JLabel lblPaziente = new JLabel("Codice fiscale paziente:"); panelViewVisitPerPatientNorth.add(lblPaziente); JFormattedTextField searchPatientTextField = new JFormattedTextField(); panelViewVisitPerPatientNorth.add(searchPatientTextField); searchPatientTextField.setColumns(16); DefaultTableModel employeeHistoryModel = new DefaultTableModel( new String[] { "Data", "Ora", "Tipo visita", "Regime", "Urgenza" }, 0) { @Override public boolean isCellEditable(int row, int column) { return false; } }; // visualizza le visite di un paziente JButton btnVisualizza = new JButton("Cerca"); btnVisualizza.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // free table while (employeeHistoryModel.getRowCount() > 0) employeeHistoryModel.removeRow(0); ArrayList<Visit> visits = db.getVisitsHistory(searchPatientTextField.getText()); if (visits != null) { System.out.println("visits is not null " + visits.size()); for (Visit c : visits) { System.out.println("element i"); Vector<Object> vector = new Vector<Object>(); vector.add(c.getDate().toString()); vector.add(c.getHour()); vector.add(c.getServiceName()); vector.add(c.getRegime()); vector.add(c.getUrgency()); employeeHistoryModel.addRow(vector); } } } }); panelViewVisitPerPatientNorth.add(btnVisualizza); JScrollPane scrollPaneViewVisitPerPatient = new JScrollPane(); panelViewVisitPerPatient.add(scrollPaneViewVisitPerPatient, BorderLayout.CENTER); tableVisitsPatientResults = new JTable(); tableVisitsPatientResults.setModel(employeeHistoryModel); scrollPaneViewVisitPerPatient.setViewportView(tableVisitsPatientResults); JPanel panelViewVisitPerPatientSouth = new JPanel(); FlowLayout fl_panelViewVisitPerPatientSouth = (FlowLayout) panelViewVisitPerPatientSouth.getLayout(); fl_panelViewVisitPerPatientSouth.setAlignment(FlowLayout.RIGHT); panelViewVisitPerPatient.add(panelViewVisitPerPatientSouth, BorderLayout.SOUTH); JButton btnDettagli = new JButton("Visualizza"); panelViewVisitPerPatientSouth.add(btnDettagli); JPanel panelViewVisitResultsPerPatient = new JPanel(); panelVisitsResultsPerPatientMaster.add(panelViewVisitResultsPerPatient, "panelViewVisitResultsPerPatient"); panelViewVisitResultsPerPatient.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPanepanelViewVisitResultsPerPatient = new JScrollPane(); panelViewVisitResultsPerPatient.add(scrollPanepanelViewVisitResultsPerPatient, BorderLayout.CENTER); JTextArea textArea = new JTextArea(); scrollPanepanelViewVisitResultsPerPatient.setViewportView(textArea); JPanel panelpanelViewVisitResultsPerPatientSouth = new JPanel(); FlowLayout fl_panelpanelViewVisitResultsPerPatientSouth = (FlowLayout) panelpanelViewVisitResultsPerPatientSouth .getLayout(); fl_panelpanelViewVisitResultsPerPatientSouth.setAlignment(FlowLayout.RIGHT); panelViewVisitResultsPerPatient.add(panelpanelViewVisitResultsPerPatientSouth, BorderLayout.SOUTH); JButton btnBackToViewVisitPerPatient = new JButton("Indietro"); panelpanelViewVisitResultsPerPatientSouth.add(btnBackToViewVisitPerPatient); JButton btnPrintReaultVisitPatient = new JButton("Stampa"); panelpanelViewVisitResultsPerPatientSouth.add(btnPrintReaultVisitPatient); JPanel panelEmployeeNorth = new JPanel(); panelEmployee.add(panelEmployeeNorth, BorderLayout.NORTH); panelEmployeeNorth.setLayout(new BorderLayout(0, 0)); lblWelcomeEmployee = new JLabel("Benvenuto "); lblWelcomeEmployee.setHorizontalAlignment(SwingConstants.CENTER); lblWelcomeEmployee.setFont(new Font("Tahoma", Font.BOLD, 22)); panelEmployeeNorth.add(lblWelcomeEmployee, BorderLayout.CENTER); JPanel panelEmployeeNorthRightLabels = new JPanel(); FlowLayout flowLayout_1 = (FlowLayout) panelEmployeeNorthRightLabels.getLayout(); flowLayout_1.setVgap(10); flowLayout_1.setHgap(10); panelEmployeeNorth.add(panelEmployeeNorthRightLabels, BorderLayout.EAST); JLabel lblLogoutEmployee = new JLabel("<HTML>\r\n\t<p style=\"color:blue;\"><u>Logout</u></p>\r\n</HTML>"); lblLogoutEmployee.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println("Employee clicked on Logout"); clfrmHealhcareManagementSystem.show(frmHealthcareManagementSystem.getContentPane(), "panelLogin"); // qui va chiamata una funzione per resettare tutti i parametri // quindi distruggere tutti i pannelli dell'utente loggato. } @Override public void mouseEntered(MouseEvent e) { lblLogoutEmployee.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } }); lblLogoutEmployee.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblLogoutEmployee.setHorizontalAlignment(SwingConstants.CENTER); panelEmployeeNorthRightLabels.add(lblLogoutEmployee); JPanel panelClinicsAndServices = new JPanel(); frmHealthcareManagementSystem.getContentPane().add(panelClinicsAndServices, "panelClinicsAndServices"); panelClinicsAndServices.setLayout(new BorderLayout(0, 0)); JPanel panelClinicsAndServicesNorth = new JPanel(); // sezione nord, combo box companies FlowLayout fl_panelClinicsAndServicesNorth = (FlowLayout) panelClinicsAndServicesNorth.getLayout(); fl_panelClinicsAndServicesNorth.setAlignment(FlowLayout.LEFT); panelClinicsAndServices.add(panelClinicsAndServicesNorth, BorderLayout.NORTH); JLabel lblSelectCompany = new JLabel("Seleziona azienda:"); panelClinicsAndServicesNorth.add(lblSelectCompany); comboBoxSelectCompany = new JComboBox<String>(); comboBoxSelectCompany.setPreferredSize(new Dimension(150, 27)); listClinics = new JList<String>(); comboBoxSelectCompany.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int comboBoxIndex = comboBoxSelectCompany.getSelectedIndex(); String companyID = companiesList.get(comboBoxIndex)[0]; ArrayList<Clinic> clinics = db.getClinics(companyID); listClinics.setModel(new AbstractListModel<String>() { @Override public String getElementAt(int index) { return clinics.get(index).getName(); } @Override public int getSize() { return clinics.size(); } }); listClinics.setSelectedIndex(0); } }); panelClinicsAndServicesNorth.add(comboBoxSelectCompany); JSplitPane splitPaneClinics = new JSplitPane(); panelClinicsAndServices.add(splitPaneClinics, BorderLayout.CENTER); splitPaneClinics.setResizeWeight(0.3); JPanel ClinicsPanel = new JPanel(); splitPaneClinics.setLeftComponent(ClinicsPanel); ClinicsPanel.setLayout(new BorderLayout(0, 0)); JLabel lblClinics = new JLabel("Ambulatori"); lblClinics.setHorizontalAlignment(SwingConstants.CENTER); ClinicsPanel.add(lblClinics, BorderLayout.NORTH); ClinicsPanel.add(listClinics, BorderLayout.CENTER); JPanel ServicesPanel = new JPanel(); splitPaneClinics.setRightComponent(ServicesPanel); ServicesPanel.setLayout(new BorderLayout(0, 0)); JTextPane txtClinic = new JTextPane(); txtClinic.setContentType("text/html"); listClinics.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int comboBoxIndex = comboBoxSelectCompany.getSelectedIndex(); String companyID = companiesList.get(comboBoxIndex)[0]; // primo // parametro, // ovvero // l'id // della // clinica ArrayList<Clinic> clinics = db.getClinics(companyID); int selectedIndex = listClinics.getSelectedIndex(); if (selectedIndex != -1) { // quando cambio contenuto in // combobox mi ritorna -1 e mi fa // segfault in clinics.get txtClinic.setText(clinics.get(selectedIndex).getCompleteDescription( db.getClinicServices(companyID, clinics.get(selectedIndex).getName()))); ServicesPanel.add(txtClinic, BorderLayout.CENTER); } } }); JPanel panelClinicAndServicesButton = new JPanel(); FlowLayout fl_panelClinicAndServicesButton = (FlowLayout) panelClinicAndServicesButton.getLayout(); fl_panelClinicAndServicesButton.setAlignment(FlowLayout.RIGHT); panelClinicsAndServices.add(panelClinicAndServicesButton, BorderLayout.SOUTH); JButton btnBackToLogin = new JButton("Indietro"); btnBackToLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { clfrmHealhcareManagementSystem.show(frmHealthcareManagementSystem.getContentPane(), "panelLogin"); } }); panelClinicAndServicesButton.add(btnBackToLogin); frmHealthcareManagementSystem.setSize(700, 600); frmHealthcareManagementSystem.setLocationRelativeTo(null); initializeCalendar(); // frame.pack(); // frame.setResizable(false); } private void initializeCalendar() { /* * // DA CAMBIARE IN GRID BAG LAYOUT lbldays = new JLabel[DAYSR][DAYSC]; * System.out.println("qui valentina: "+comboBoxSelectBookVisitMonth. * getSelectedItem()); * * // Get the number of days in that month YearMonth yearMonthObject = * YearMonth.of(2017, 1); int daysInMonth = * yearMonthObject.lengthOfMonth(); //28 * * * // header for(int i = 0; i < 1; i++){ for(int j = 0; j < DAYSC; j++){ * lbldays[i][j] = new JLabel(""+Days.values()[j], * SwingConstants.CENTER); lbldays[i][j].setBorder(new * LineBorder(Color.LIGHT_GRAY)); lbldays[i][j].setOpaque(true); * lbldays[i][j].setBackground(Color.decode("0x87CEEB")); * * GridBagConstraints gbc_lblDays = new GridBagConstraints(); * gbc_lblDays.insets = new Insets(0, 0, 0, 0); gbc_lblDays.gridx = j; * gbc_lblDays.gridy = i; * bookVisitCenterCalendarPanel.add(lbldays[i][j], gbc_lblDays); } } */ /* * // cells int day = 1; for(int i = 1; i < DAYSR; i++){ for(int j = 0; * j < DAYSC ; j++){ if(day > daysInMonth){ lbldays[i][j] = new * JLabel("", SwingConstants.CENTER); lbldays[i][j].setBorder(new * LineBorder(Color.LIGHT_GRAY)); GridBagConstraints gbc_lblDays = new * GridBagConstraints(); gbc_lblDays.insets = new Insets(0, 0, 0, 0); * gbc_lblDays.gridx = j; gbc_lblDays.gridy = i; * bookVisitCenterCalendarPanel.add(lbldays[i][j], gbc_lblDays); } else{ * lbldays[i][j] = new JLabel(""+day++, SwingConstants.CENTER); * lbldays[i][j].setBorder(new LineBorder(Color.LIGHT_GRAY)); * GridBagConstraints gbc_lblDays = new GridBagConstraints(); * gbc_lblDays.insets = new Insets(0, 0, 0, 0); gbc_lblDays.gridx = j; * gbc_lblDays.gridy = i; * bookVisitCenterCalendarPanel.add(lbldays[i][j], gbc_lblDays); } } } */ } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // Modifications: // 2009 May 14: added threshold config change handler for in-line thresholds processing // 2006 Apr 27: added support for pathOutageEnabled // 2006 Apr 17: added path outage processing for nodeDown event // 2003 Nov 11: Merged changes from Rackspace project // 2003 Oct 08: Implemented the poller release function. // 2003 Jan 31: Cleaned up some unused imports. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.poller; import java.lang.reflect.UndeclaredThrowableException; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import java.util.Enumeration; import java.util.concurrent.atomic.AtomicInteger; import javax.sql.DataSource; import org.apache.log4j.Category; import org.apache.log4j.Level; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.config.PollOutagesConfig; import org.opennms.netmgt.config.PollerConfig; import org.opennms.netmgt.config.poller.Package; import org.opennms.netmgt.daemon.AbstractServiceDaemon; import org.opennms.netmgt.eventd.EventIpcManager; import org.opennms.netmgt.model.PollStatus; import org.opennms.netmgt.poller.pollables.DbPollEvent; import org.opennms.netmgt.poller.pollables.PollEvent; import org.opennms.netmgt.poller.pollables.PollableNetwork; import org.opennms.netmgt.poller.pollables.PollableNode; import org.opennms.netmgt.poller.pollables.PollableService; import org.opennms.netmgt.poller.pollables.PollableServiceConfig; import org.opennms.netmgt.poller.pollables.PollableVisitor; import org.opennms.netmgt.poller.pollables.PollableVisitorAdaptor; import org.opennms.netmgt.scheduler.LegacyScheduler; import org.opennms.netmgt.scheduler.Schedule; import org.opennms.netmgt.scheduler.Scheduler; import org.opennms.netmgt.utils.Querier; import org.opennms.netmgt.utils.Updater; public class Poller extends AbstractServiceDaemon { private final static Poller m_singleton = new Poller(); private boolean m_initialized = false; private LegacyScheduler m_scheduler = null; private PollerEventProcessor m_eventProcessor; private PollableNetwork m_network; private QueryManager m_queryManager; private PollerConfig m_pollerConfig; private PollOutagesConfig m_pollOutagesConfig; private EventIpcManager m_eventMgr; private DataSource m_dataSource; public Poller() { super("OpenNMS.Poller"); } /* Getters/Setters used for dependency injection */ public void setDataSource(DataSource dataSource) { m_dataSource = dataSource; } public EventIpcManager getEventManager() { return m_eventMgr; } public void setEventManager(EventIpcManager eventMgr) { m_eventMgr = eventMgr; } public PollerEventProcessor getEventProcessor() { return m_eventProcessor; } public void setEventProcessor(PollerEventProcessor eventProcessor) { m_eventProcessor = eventProcessor; } public PollableNetwork getNetwork() { return m_network; } public void setNetwork(PollableNetwork network) { m_network = network; } public void setQueryManager(QueryManager queryManager) { m_queryManager = queryManager; } public QueryManager getQueryManager() { return m_queryManager; } public PollerConfig getPollerConfig() { return m_pollerConfig; } public void setPollerConfig(PollerConfig pollerConfig) { m_pollerConfig = pollerConfig; } public PollOutagesConfig getPollOutagesConfig() { return m_pollOutagesConfig; } public void setPollOutagesConfig(PollOutagesConfig pollOutagesConfig) { m_pollOutagesConfig = pollOutagesConfig; } public Scheduler getScheduler() { return m_scheduler; } public void setScheduler(LegacyScheduler scheduler) { m_scheduler = scheduler; } protected void onInit() { // serviceUnresponsive behavior enabled/disabled? log().debug("init: serviceUnresponsive behavior: " + (getPollerConfig().serviceUnresponsiveEnabled() ? "enabled" : "disabled")); createScheduler(); try { log().debug("init: Closing outages for unmanaged services"); closeOutagesForUnmanagedServices(); } catch (Exception e) { log().error("init: Failed to close ouates for unmanage services", e); } // Schedule the interfaces currently in the database try { log().debug("start: Scheduling existing interfaces"); scheduleExistingServices(); } catch (Exception sqlE) { log().error("start: Failed to schedule existing interfaces", sqlE); } // Create an event receiver. The receiver will // receive events, process them, creates network // interfaces, and schedulers them. try { log().debug("start: Creating event broadcast event processor"); setEventProcessor(new PollerEventProcessor(this)); } catch (Throwable t) { log().fatal("start: Failed to initialized the broadcast event receiver", t); throw new UndeclaredThrowableException(t); } m_initialized = true; } private void closeOutagesForUnmanagedServices() { Timestamp closeTime = new Timestamp((new java.util.Date()).getTime()); final String DB_CLOSE_OUTAGES_FOR_UNMANAGED_SERVICES = "UPDATE outages set ifregainedservice = ? where outageid in (select outages.outageid from outages, ifservices where ((outages.nodeid = ifservices.nodeid) AND (outages.ipaddr = ifservices.ipaddr) AND (outages.serviceid = ifservices.serviceid) AND ((ifservices.status = 'D') OR (ifservices.status = 'F') OR (ifservices.status = 'U')) AND (outages.ifregainedservice IS NULL)))"; Updater svcUpdater = new Updater(m_dataSource, DB_CLOSE_OUTAGES_FOR_UNMANAGED_SERVICES); svcUpdater.execute(closeTime); final String DB_CLOSE_OUTAGES_FOR_UNMANAGED_INTERFACES = "UPDATE outages set ifregainedservice = ? where outageid in (select outages.outageid from outages, ipinterface where ((outages.nodeid = ipinterface.nodeid) AND (outages.ipaddr = ipinterface.ipaddr) AND ((ipinterface.ismanaged = 'F') OR (ipinterface.ismanaged = 'U')) AND (outages.ifregainedservice IS NULL)))"; Updater ifUpdater = new Updater(m_dataSource, DB_CLOSE_OUTAGES_FOR_UNMANAGED_INTERFACES); ifUpdater.execute(closeTime); } public void closeOutagesForNode(Date closeDate, int eventId, int nodeId) { Timestamp closeTime = new Timestamp(closeDate.getTime()); final String DB_CLOSE_OUTAGES_FOR_NODE = "UPDATE outages set ifregainedservice = ?, svcRegainedEventId = ? where outages.nodeId = ? AND (outages.ifregainedservice IS NULL)"; Updater svcUpdater = new Updater(m_dataSource, DB_CLOSE_OUTAGES_FOR_NODE); svcUpdater.execute(closeTime, new Integer(eventId), new Integer(nodeId)); } public void closeOutagesForInterface(Date closeDate, int eventId, int nodeId, String ipAddr) { Timestamp closeTime = new Timestamp(closeDate.getTime()); final String DB_CLOSE_OUTAGES_FOR_IFACE = "UPDATE outages set ifregainedservice = ?, svcRegainedEventId = ? where outages.nodeId = ? AND outages.ipAddr = ? AND (outages.ifregainedservice IS NULL)"; Updater svcUpdater = new Updater(m_dataSource, DB_CLOSE_OUTAGES_FOR_IFACE); svcUpdater.execute(closeTime, new Integer(eventId), new Integer(nodeId), ipAddr); } public void closeOutagesForService(Date closeDate, int eventId, int nodeId, String ipAddr, String serviceName) { Timestamp closeTime = new Timestamp(closeDate.getTime()); final String DB_CLOSE_OUTAGES_FOR_SERVICE = "UPDATE outages set ifregainedservice = ?, svcRegainedEventId = ? where outageid in (select outages.outageid from outages, service where outages.nodeid = ? AND outages.ipaddr = ? AND outages.serviceid = service.serviceId AND service.servicename = ? AND outages.ifregainedservice IS NULL)"; Updater svcUpdater = new Updater(m_dataSource, DB_CLOSE_OUTAGES_FOR_SERVICE); svcUpdater.execute(closeTime, new Integer(eventId), new Integer(nodeId), ipAddr, serviceName); } private void createScheduler() { Category log = ThreadCategory.getInstance(getClass()); // Create a scheduler try { log.debug("init: Creating poller scheduler"); setScheduler(new LegacyScheduler("Poller", getPollerConfig().getThreads())); } catch (RuntimeException e) { log.fatal("init: Failed to create poller scheduler", e); throw e; } } protected void onStart() { // get the category logger // start the scheduler try { if (log().isDebugEnabled()) log().debug("start: Starting poller scheduler"); getScheduler().start(); } catch (RuntimeException e) { if (log().isEnabledFor(Level.FATAL)) log().fatal("start: Failed to start scheduler", e); throw e; } } protected void onStop() { if(getScheduler()!=null) { getScheduler().stop(); } if(getEventProcessor()!=null) { getEventProcessor().close(); } releaseServiceMonitors(); setScheduler(null); } private void releaseServiceMonitors() { getPollerConfig().releaseAllServiceMonitors(); } protected void onPause() { getScheduler().pause(); } protected void onResume() { getScheduler().resume(); } public static Poller getInstance() { return m_singleton; } public ServiceMonitor getServiceMonitor(String svcName) { return getPollerConfig().getServiceMonitor(svcName); } private void scheduleExistingServices() throws Exception { Category log = ThreadCategory.getInstance(getClass()); scheduleMatchingServices(null); getNetwork().recalculateStatus(); getNetwork().propagateInitialCause(); getNetwork().resetStatusChanged(); // Debug dump pollable network if (log.isDebugEnabled()) { log.debug("scheduleExistingServices: dumping content of pollable network: "); getNetwork().dump(); } } public void scheduleService(final int nodeId, final String nodeLabel, final String ipAddr, final String svcName) { final Category log = ThreadCategory.getInstance(getClass()); try { /* * Do this here so that we can use the treeLock for this node as we * add its service and schedule it */ PollableNode node; synchronized (getNetwork()) { node = getNetwork().getNode(nodeId); if (node == null) { node = getNetwork().createNode(nodeId, nodeLabel); } } final PollableNode svcNode = node; Runnable r = new Runnable() { public void run() { int matchCount = scheduleMatchingServices("ifServices.nodeId = "+nodeId+" AND ifServices.ipAddr = '"+ipAddr+"' AND service.serviceName = '"+svcName+"'"); if (matchCount > 0) { svcNode.recalculateStatus(); svcNode.processStatusChange(new Date()); } else { log.warn("Attempt to schedule service "+nodeId+"/"+ipAddr+"/"+svcName+" found no active service"); } } }; node.withTreeLock(r); } catch (Exception e) { log.error("Unable to schedule service "+nodeId+"/"+ipAddr+"/"+svcName, e); } } private int scheduleMatchingServices(String criteria) { String sql = "SELECT ifServices.nodeId AS nodeId, node.nodeLabel AS nodeLabel, ifServices.ipAddr AS ipAddr, " + "ifServices.serviceId AS serviceId, service.serviceName AS serviceName, ifServices.status as status, " + "outages.svcLostEventId AS svcLostEventId, events.eventUei AS svcLostEventUei, " + "outages.ifLostService AS ifLostService, outages.ifRegainedService AS ifRegainedService " + "FROM ifServices " + "JOIN node ON ifServices.nodeId = node.nodeId " + "JOIN service ON ifServices.serviceId = service.serviceId " + "LEFT OUTER JOIN outages ON " + "ifServices.nodeId = outages.nodeId AND " + "ifServices.ipAddr = outages.ipAddr AND " + "ifServices.serviceId = outages.serviceId AND " + "ifRegainedService IS NULL " + "LEFT OUTER JOIN events ON outages.svcLostEventId = events.eventid " + "WHERE ifServices.status in ('A','N')" + (criteria == null ? "" : " AND "+criteria); final AtomicInteger count = new AtomicInteger(0); Querier querier = new Querier(m_dataSource, sql) { public void processRow(ResultSet rs) throws SQLException { if (scheduleService(rs.getInt("nodeId"), rs.getString("nodeLabel"), rs.getString("ipAddr"), rs.getString("serviceName"), "A".equals(rs.getString("status")), (Number)rs.getObject("svcLostEventId"), rs.getTimestamp("ifLostService"), rs.getString("svcLostEventUei"))) { count.incrementAndGet(); } } }; querier.execute(); return count.get(); } private void updateServiceStatus(int nodeId, String ipAddr, String serviceName, String status) { final String sql = "UPDATE ifservices SET status = ? WHERE id " + " IN (SELECT ifs.id FROM ifservices AS ifs JOIN service AS svc ON ifs.serviceid = svc.serviceid " + " WHERE ifs.nodeId = ? AND ifs.ipAddr = ? AND svc.servicename = ?)"; Updater updater = new Updater(m_dataSource, sql); updater.execute(status, nodeId, ipAddr, serviceName); } private boolean scheduleService(int nodeId, String nodeLabel, String ipAddr, String serviceName, boolean active, Number svcLostEventId, Date date, String svcLostUei) { Category log = ThreadCategory.getInstance(); Package pkg = findPackageForService(ipAddr, serviceName); if (pkg == null && active) { log.warn("Active service "+serviceName+" on "+ipAddr+" not configured for any package. Marking as Not Polled."); updateServiceStatus(nodeId, ipAddr, serviceName, "N"); return false; } else if (pkg != null && !active) { log.info("Active service "+serviceName+" on "+ipAddr+" is now configured for any package. Marking as active."); updateServiceStatus(nodeId, ipAddr, serviceName, "A"); } ServiceMonitor monitor = m_pollerConfig.getServiceMonitor(serviceName); if (monitor == null) { log.info("Could not find service monitor associated with service "+serviceName); return false; } InetAddress addr; try { addr = InetAddress.getByName(ipAddr); } catch (UnknownHostException e) { log.error("Could not convert "+ipAddr+" as an InetAddress "+ipAddr); return false; } PollableService svc = getNetwork().createService(nodeId, nodeLabel, addr, serviceName); PollableServiceConfig pollConfig = new PollableServiceConfig(svc, m_pollerConfig, m_pollOutagesConfig, pkg, getScheduler()); svc.setPollConfig(pollConfig); synchronized(svc) { if (svc.getSchedule() == null) { Schedule schedule = new Schedule(svc, pollConfig, getScheduler()); svc.setSchedule(schedule); } } if (svcLostEventId == null) if (svc.getParent().getStatus().isUnknown()) { svc.updateStatus(PollStatus.up()); } else { svc.updateStatus(svc.getParent().getStatus()); } else { svc.updateStatus(PollStatus.down()); PollEvent cause = new DbPollEvent(svcLostEventId.intValue(), svcLostUei, date); svc.setCause(cause); } svc.schedule(); return true; } private Package findPackageForService(String ipAddr, String serviceName) { Enumeration<Package> en = m_pollerConfig.enumeratePackage(); Package lastPkg = null; while (en.hasMoreElements()) { Package pkg = (Package)en.nextElement(); if (pollableServiceInPackage(ipAddr, serviceName, pkg)) lastPkg = pkg; } return lastPkg; } protected boolean pollableServiceInPackage(String ipAddr, String serviceName, Package pkg) { if (pkg.getRemote()) { log().debug("pollableServiceInPackage: this package: "+pkg.getName()+", is a remote monitor package."); return false; } if (!m_pollerConfig.serviceInPackageAndEnabled(serviceName, pkg)) return false; boolean inPkg = m_pollerConfig.interfaceInPackage(ipAddr, pkg); if (inPkg) return true; if (m_initialized) { m_pollerConfig.rebuildPackageIpListMap(); return m_pollerConfig.interfaceInPackage(ipAddr, pkg); } return false; } public boolean packageIncludesIfAndSvc(Package pkg, String ipAddr, String svcName) { Category log = ThreadCategory.getInstance(); if (!getPollerConfig().serviceInPackageAndEnabled(svcName, pkg)) { if (log.isDebugEnabled()) log.debug("packageIncludesIfAndSvc: address/service: " + ipAddr + "/" + svcName + " not scheduled, service is not enabled or does not exist in package: " + pkg.getName()); return false; } // Is the interface in the package? if (!getPollerConfig().interfaceInPackage(ipAddr, pkg)) { if (m_initialized) { getPollerConfig().rebuildPackageIpListMap(); if (!getPollerConfig().interfaceInPackage(ipAddr, pkg)) { if (log.isDebugEnabled()) log.debug("packageIncludesIfAndSvc: interface " + ipAddr + " gained service " + svcName + ", but the interface was not in package: " + pkg.getName()); return false; } } else { if (log.isDebugEnabled()) log.debug("packageIncludesIfAndSvc: address/service: " + ipAddr + "/" + svcName + " not scheduled, interface does not belong to package: " + pkg.getName()); return false; } } return true; } public void refreshServicePackages() { PollableVisitor visitor = new PollableVisitorAdaptor() { public void visitService(PollableService service) { service.refreshConfig(); } }; getNetwork().visit(visitor); } public void refreshServiceThresholds() { PollableVisitor visitor = new PollableVisitorAdaptor() { public void visitService(PollableService service) { service.refreshThresholds(); } }; getNetwork().visit(visitor); } }
import java.util.*; import java.io.*; import jing.chem.*; import jing.chemParser.*; import jing.param.*; import jing.chemUtil.*; //import bondGroups.*; import jing.rxn.*; import jing.rxnSys.*; import jing.mathTool.*; public class Thermo { //## configuration RMG::RMG public static void main(String[] args) { initializeSystemProperties(); try { FileReader in = new FileReader("sandeep.txt"); BufferedReader data = new BufferedReader(in); Graph g = ChemParser.readChemGraph(data); in.close(); System.out.println(g); ChemGraph chemgraph = ChemGraph.make(g); Species spe = Species.make("molecule",chemgraph); System.out.println("The number of resonance isomers is " + spe.getResonanceIsomersHashSet().size()); System.out.println("The NASA data is \n"+ spe.getNasaThermoData()); System.out.println("ThermoData is \n" + spe.getChemGraph().getThermoData().toString()); //int K = chemgraph.getKekule(); int symm = chemgraph.getSymmetryNumber(); //System.out.println("number of Kekule structures = "+K); System.out.println(" symmetry number = "+symm); Temperature T = new Temperature(298.0,"K"); String chemicalFormula = chemgraph.getChemicalFormula(); System.out.println(chemicalFormula + " H=" + chemgraph.calculateH(T)); // Species species = Species.make(chemicalFormula, chemgraph); // this is equal to System.out.println(species.toString()); // System.out.println(species.toStringWithoutH()); // species.generateResonanceIsomers(); // Iterator rs = species.getResonanceIsomers(); // while (rs.hasNext()){ // ChemGraph cg = (ChemGraph)rs.next(); // Species s = cg.getSpecies(); // String string = s.toStringWithoutH(); // System.out.print(string); // Species species = Species.make(chemicalFormula, chemgraph); // Iterator iterator = species.getResonanceIsomers(); // System.out.println(iterator); } catch (FileNotFoundException e) { System.err.println("File was not found!\n"); } catch(IOException e){ System.err.println("Something wrong with ChemParser.readChemGraph"); } catch(ForbiddenStructureException e){ System.err.println("Something wrong with ChemGraph.make"); } System.out.println("Done!\n"); }; public static void initializeSystemProperties() { String name= "RMG_database"; String workingDir = System.getenv("RMG"); System.setProperty("RMG.workingDirectory", workingDir); // System.setProperty("jing.chem.ChemGraph.forbiddenStructureFile", // workingDir + // "database/forbiddenStructure/forbiddenStructure.txt"); System.setProperty("jing.chem.ChemGraph.forbiddenStructureFile", workingDir + "/databases/"+name+"/forbiddenStructure/ForbiddenStructure.txt"); System.setProperty("jing.chem.ThermoGAGroupLibrary.pathName", workingDir + "/databases/" + name+"/thermo"); System.setProperty("jing.rxn.ReactionTemplateLibrary.pathName", workingDir + "/databases/" + name+"/kinetics/kinetics"); // System.setProperty("jing.rxn.ReactionTemplateLibrary.pathName", // workingDir + "database/kinetics/kinetics"); // System.setProperty("jing.rxnSys.ReactionModelGenerator.conditionFile", // workingDir + "database/condition/condition.txt"); }; }
package c5db.interfaces; import c5db.messages.generated.ModuleType; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.regionserver.HRegion; import org.jetlang.channels.Channel; import java.util.List; /** * Manages the lifecycle of tablets - the individual chunks of tables. Each tablet is * an ordered portion of the key space, and has a distinct lifecycle. This module handles * coordination with other modules. * <p> * Roughly, to bring a tablet online, first a replicator instance must be created for it. Then it * must be bound to the write-ahead-log. Finally the local tablet files must be located, * verified and loaded. */ @DependsOn(ReplicationModule.class) @ModuleTypeBinding(ModuleType.Tablet) public interface TabletModule extends C5Module { public HRegion getTablet(String tabletName); // TODO this interface is not strong enough. Need HRegionInfo etc. public void startTablet(List<Long> peers, String tabletName); public Channel<TabletStateChange> getTabletStateChanges(); public static class TabletStateChange { public final Tablet tablet; public final Tablet.State state; public final Throwable optError; public TabletStateChange(Tablet tablet, Tablet.State state, Throwable optError) { this.tablet = tablet; this.state = state; this.optError = optError; } @Override public String toString() { return "TabletStateChange{" + "tablet=" + tablet + ", state=" + state + ", optError=" + optError + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TabletStateChange that = (TabletStateChange) o; if (optError != null ? !optError.equals(that.optError) : that.optError != null) return false; if (state != that.state) return false; if (!tablet.equals(that.tablet)) return false; return true; } @Override public int hashCode() { int result = tablet.hashCode(); result = 31 * result + state.hashCode(); result = 31 * result + (optError != null ? optError.hashCode() : 0); return result; } } interface Tablet { Channel<TabletStateChange> getStateChangeChannel(); boolean isOpen(); c5db.tablet.Tablet.State getTabletState(); HRegionInfo getRegionInfo(); HTableDescriptor getTableDescriptor(); List<Long> getPeers(); enum State { Initialized, // Initial state, nothing done yet. CreatingReplicator, // Waiting for replication instance to be created Open, // Ready to service requests. Failed, } } }
package de.jungblut.clustering; import gnu.trove.set.hash.TIntHashSet; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.jungblut.distance.DistanceMeasurer; import de.jungblut.math.DoubleVector; /** * "Bottom Up" clustering (agglomerative) using average single linkage * clustering. This average is paired up with the so called "centroid" method. <br/> * Means in normal language: If we merge two points in space with each other, we * look for the nearest neighbour (single linkage, defined by the given distance * measurer). If we found the nearest neighbour, we merge both together by * averaging their coordinates (average single linkage with centroid method). So * if point (1,2) is now nearest neighbour to (5,1) we average and receive (3, * 1.5) for the next clustering level. If we are now in the next clustering * level and say, we found another cluster (10, 14) which is the nearest * neighbour to (3, 1.5). We now merge both again to the next level: ( (10+3)/2, * (14+1.5)/2) = (6,5, 7,75). This goes until we have just have a single cluster * which forms the root of the resulting cluster binary tree. <br/> * Few more details about the algorithm: <br/> * <li>Nearest neighbour search is greedy, which means that even far away merges * are taken into account, if there is no nearest neighbour available anymore. * Therefore one may want to add a distance threshold, and just add those * unrelated clusters to the next level until they find a good clustering or * just ignore them.</li> <br/> * <li>Nearest neighbours are found using exhaustive search: for every * unclustered node in the level, we look through the whole list of clusters to * find the nearest to merge.</li><br/> * <li>If nearest neighbour search was unsuccessful (there was no item to * cluster anymore), the point/vector is added to the next level directly.</li> * * @author thomas.jungblut * */ public final class AgglomerativeClustering { /** * Starts the clustering process. * * @param points the points to cluster on * @param distanceMeasurer the distance measurement to use. * @param verbose if true, costs in each iteration will be printed. * @return a list of lists that contains cluster nodes for each level, where * the zeroth index is the top of the tree and thus only contains a * single clusternode. */ public static List<List<ClusterNode>> cluster(List<DoubleVector> points, DistanceMeasurer distanceMeasurer, boolean verbose) { return cluster(points, distanceMeasurer, Double.MAX_VALUE, verbose); } /** * Starts the clustering process. * * @param points the points to cluster on * @param distanceMeasurer the distance measurement to use. * @param distanceThreshold the threshold to not use a nearest neighbour * anymore and just add it to the next stage. (note that this is * experimental and may lead to infinite loops as this may not * converge to a single root item -> therefore this method is * protected until I find a good solution to detect these stales). * @param verbose if true, costs in each iteration will be printed. * @return a list of lists that contains cluster nodes for each level, where * the zeroth index is the top of the tree and thus only contains a * single clusternode. */ static List<List<ClusterNode>> cluster(List<DoubleVector> points, DistanceMeasurer distanceMeasurer, double distanceThreshold, boolean verbose) { List<List<ClusterNode>> levels = new ArrayList<>(); List<ClusterNode> currentLevel = new ArrayList<>(); // start by translating the bottom to the internal tree linkage structure for (DoubleVector point : points) { currentLevel.add(new ClusterNode(point)); } levels.add(currentLevel); int iteration = 0; while (currentLevel.size() != 1) { List<ClusterNode> nextLevel = new ArrayList<>(); TIntHashSet excludeIndex = new TIntHashSet(); for (int i = 0; i < currentLevel.size(); i++) { // if we had a good match with some other previous node, don't cluster // it again if (excludeIndex.contains(i)) { continue; } excludeIndex.add(i); ClusterNode ci = currentLevel.get(i); // find the nearest, this is greedy and doesn't always find the best // clustering, but is faster then the normal groupwise average linkage. int nearest = -1; double nearestDistance = Double.MAX_VALUE; for (int j = 0; j < currentLevel.size(); j++) { if (!excludeIndex.contains(j)) { ClusterNode cj = currentLevel.get(j); double dist = distanceMeasurer.measureDistance(ci.getMean(), cj.getMean()); if (dist < nearestDistance && dist < distanceThreshold) { nearest = j; nearestDistance = dist; } } } if (nearest >= 0) { // now merge those two cluster nodes and add them to the next level ClusterNode cn = new ClusterNode(ci, currentLevel.get(nearest), nearestDistance); nextLevel.add(cn); excludeIndex.add(nearest); } else { // if there is nothing to cluster against here, add it again for the // next iteration nextLevel.add(ci); } } if (verbose) { System.out.println(iteration + " | Current level contains " + nextLevel.size() + " elements."); } levels.add(nextLevel); currentLevel = nextLevel; iteration++; } Collections.reverse(levels); return levels; } /** * Tree structure for containing information about linkages and distances. * * @author thomas.jungblut * */ public static class ClusterNode { private ClusterNode parent; private ClusterNode left; private ClusterNode right; private final DoubleVector mean; private double splitDistance; /** * Initialize the node with a single vector, mainly used for initializing * the bottom. */ ClusterNode(DoubleVector mean) { this.mean = mean.deepCopy(); this.splitDistance = 0d; } /** * Initialize the node with a two ClusterNodes */ ClusterNode(ClusterNode node1, ClusterNode node2, double distance) { this.mean = (node1.mean.add(node2.mean)).divide(2); this.splitDistance = distance; this.left = node1; this.right = node2; left.parent = this; right.parent = this; } /** * @return the mean between the two children. Used for distance calculations * at merging time. */ public DoubleVector getMean() { return this.mean; } /** * @return the distance between left and right cluster. (Based on their * means). */ public double getSplitDistance() { return this.splitDistance; } /** * @return the parent node, null if root. */ public ClusterNode getParent() { return this.parent; } /** * @return the left child, null if not present. */ public ClusterNode getLeft() { return this.left; } /** * @return the right child, null if not present. */ public ClusterNode getRight() { return this.right; } @Override public String toString() { return "ClusterNode [mean=" + this.mean + "]"; } } }
package lombok.delombok; import static com.sun.tools.javac.code.Flags.*; import static lombok.javac.Javac.*; import static lombok.javac.JavacTreeMaker.TreeTag.treeTag; import static lombok.javac.JavacTreeMaker.TypeTag.typeTag; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import lombok.javac.CommentInfo; import lombok.javac.CommentInfo.EndConnection; import lombok.javac.CommentInfo.StartConnection; import lombok.javac.JavacTreeMaker.TreeTag; import lombok.javac.JavacTreeMaker.TypeTag; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.DocCommentTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayAccess; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCAssert; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCAssignOp; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCBreak; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCConditional; import com.sun.tools.javac.tree.JCTree.JCContinue; import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop; import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; import com.sun.tools.javac.tree.JCTree.JCErroneous; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCForLoop; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCImport; import com.sun.tools.javac.tree.JCTree.JCInstanceOf; import com.sun.tools.javac.tree.JCTree.JCLabeledStatement; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCParens; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCSkip; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCSwitch; import com.sun.tools.javac.tree.JCTree.JCSynchronized; import com.sun.tools.javac.tree.JCTree.JCThrow; import com.sun.tools.javac.tree.JCTree.JCTry; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeCast; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWhileLoop; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.tree.JCTree.LetExpr; import com.sun.tools.javac.tree.JCTree.TypeBoundKind; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.util.Convert; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Position; //import com.sun.tools.javac.code.TypeTags; /** Prints out a tree as an indented Java source program. * * <p><b>This is NOT part of any API supported by Sun Microsystems. If * you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ @SuppressWarnings("all") // Mainly sun code that has other warning settings public class PrettyCommentsPrinter extends JCTree.Visitor { private static final TreeTag PARENS = treeTag("PARENS"); private static final TreeTag IMPORT = treeTag("IMPORT"); private static final TreeTag VARDEF = treeTag("VARDEF"); private static final TreeTag SELECT = treeTag("SELECT"); private static final Map<TreeTag, String> OPERATORS; static { Map<TreeTag, String> map = new HashMap<TreeTag, String>(); map.put(treeTag("POS"), "+"); map.put(treeTag("NEG"), "-"); map.put(treeTag("NOT"), "!"); map.put(treeTag("COMPL"), "~"); map.put(treeTag("PREINC"), "++"); map.put(treeTag("PREDEC"), " map.put(treeTag("POSTINC"), "++"); map.put(treeTag("POSTDEC"), " map.put(treeTag("NULLCHK"), "<*nullchk*>"); map.put(treeTag("OR"), "||"); map.put(treeTag("AND"), "&&"); map.put(treeTag("EQ"), "=="); map.put(treeTag("NE"), "!="); map.put(treeTag("LT"), "<"); map.put(treeTag("GT"), ">"); map.put(treeTag("LE"), "<="); map.put(treeTag("GE"), ">="); map.put(treeTag("BITOR"), "|"); map.put(treeTag("BITXOR"), "^"); map.put(treeTag("BITAND"), "&"); map.put(treeTag("SL"), "<<"); map.put(treeTag("SR"), ">>"); map.put(treeTag("USR"), ">>>"); map.put(treeTag("PLUS"), "+"); map.put(treeTag("MINUS"), "-"); map.put(treeTag("MUL"), "*"); map.put(treeTag("DIV"), "/"); map.put(treeTag("MOD"), "%"); map.put(treeTag("BITOR_ASG"), "|="); map.put(treeTag("BITXOR_ASG"), "^="); map.put(treeTag("BITAND_ASG"), "&="); map.put(treeTag("SL_ASG"), "<<="); map.put(treeTag("SR_ASG"), ">>="); map.put(treeTag("USR_ASG"), ">>>="); map.put(treeTag("PLUS_ASG"), "+="); map.put(treeTag("MINUS_ASG"), "-="); map.put(treeTag("MUL_ASG"), "*="); map.put(treeTag("DIV_ASG"), "/="); map.put(treeTag("MOD_ASG"), "%="); OPERATORS = map; } private List<CommentInfo> comments; private final JCCompilationUnit cu; private boolean onNewLine = true; private boolean aligned = false; private boolean inParams = false; private boolean needsSpace = false; private boolean needsNewLine = false; private boolean needsAlign = false; // Flag for try-with-resources to make them not final and not print the last semicolon. // This flag is set just before printing the vardef and cleared when printing its modifiers. private boolean suppressFinalAndSemicolonsInTry = false; private final FormatPreferences formatPreferences; public PrettyCommentsPrinter(Writer out, JCCompilationUnit cu, List<CommentInfo> comments, FormatPreferences preferences) { this.out = out; this.comments = comments; this.cu = cu; this.formatPreferences = preferences; } private int endPos(JCTree tree) { return getEndPosition(tree, cu); } private void consumeComments(int until) throws IOException { consumeComments(until, null); } private void consumeComments(int until, JCTree tree) throws IOException { boolean prevNewLine = onNewLine; boolean found = false; CommentInfo head = comments.head; while (comments.nonEmpty() && head.pos < until) { printComment(head); comments = comments.tail; head = comments.head; } if (!onNewLine && prevNewLine) { println(); } } private void consumeTrailingComments(int from) throws IOException { boolean prevNewLine = onNewLine; CommentInfo head = comments.head; boolean stop = false; while (comments.nonEmpty() && head.prevEndPos == from && !stop && !(head.start == StartConnection.ON_NEXT_LINE || head.start == StartConnection.START_OF_LINE)) { from = head.endPos; printComment(head); stop = (head.end == EndConnection.ON_NEXT_LINE); comments = comments.tail; head = comments.head; } if (!onNewLine && prevNewLine) { println(); } } private void printComment(CommentInfo comment) throws IOException { prepareComment(comment.start); print(comment.content); switch (comment.end) { case ON_NEXT_LINE: if (!aligned) { needsNewLine = true; needsAlign = true; } break; case AFTER_COMMENT: needsSpace = true; break; case DIRECT_AFTER_COMMENT: // do nothing break; } } private void prepareComment(StartConnection start) throws IOException { switch (start) { case DIRECT_AFTER_PREVIOUS: needsSpace = false; break; case AFTER_PREVIOUS: needsSpace = true; break; case START_OF_LINE: needsNewLine = true; needsAlign = false; break; case ON_NEXT_LINE: if (!aligned) { needsNewLine = true; needsAlign = true; } break; } } /** The output stream on which trees are printed. */ Writer out; /** The current left margin. */ int lmargin = 0; /** The enclosing class name. */ Name enclClassName; /** A hashtable mapping trees to their documentation comments * (can be null) */ Map<JCTree, String> docComments = null; DocCommentTable docTable = null; String getJavadocFor(JCTree node) { if (docComments != null) return docComments.get(node); if (docTable != null) return docTable.getCommentText(node); return null; } /** Align code to be indented to left margin. */ void align() throws IOException { onNewLine = false; aligned = true; needsAlign = false; for (int i = 0; i < lmargin; i++) out.write(formatPreferences.indent()); } /** Increase left margin by indentation width. */ void indent() { lmargin++; } /** Decrease left margin by indentation width. */ void undent() { lmargin } /** Enter a new precedence level. Emit a `(' if new precedence level * is less than precedence level so far. * @param contextPrec The precedence level in force so far. * @param ownPrec The new precedence level. */ void open(int contextPrec, int ownPrec) throws IOException { if (ownPrec < contextPrec) out.write("("); } /** Leave precedence level. Emit a `(' if inner precedence level * is less than precedence level we revert to. * @param contextPrec The precedence level we revert to. * @param ownPrec The inner precedence level. */ void close(int contextPrec, int ownPrec) throws IOException { if (ownPrec < contextPrec) out.write(")"); } /** Print string, replacing all non-ascii character with unicode escapes. */ public void print(Object s) throws IOException { boolean align = needsAlign; if (needsNewLine && !onNewLine) { println(); } if (align && !aligned) { align(); } if (needsSpace && !onNewLine && !aligned) { out.write(' '); } needsSpace = false; out.write(Convert.escapeUnicode(s.toString())); onNewLine = false; aligned = false; } /** Print new line. */ public void println() throws IOException { onNewLine = true; aligned = false; needsNewLine = false; out.write(lineSep); } String lineSep = System.getProperty("line.separator"); /** Exception to propagate IOException through visitXXX methods */ private static class UncheckedIOException extends Error { static final long serialVersionUID = -4032692679158424751L; UncheckedIOException(IOException e) { super(e.getMessage(), e); } } /** Visitor argument: the current precedence level. */ int prec; /** Visitor method: print expression tree. * @param prec The current precedence level. */ public void printExpr(JCTree tree, int prec) throws IOException { int prevPrec = this.prec; try { this.prec = prec; if (tree == null) print("/*missing*/"); else { consumeComments(tree.pos, tree); tree.accept(this); int endPos = endPos(tree); consumeTrailingComments(endPos); } } catch (UncheckedIOException ex) { IOException e = new IOException(ex.getMessage()); e.initCause(ex); throw e; } finally { this.prec = prevPrec; } } /** Derived visitor method: print expression tree at minimum precedence level * for expression. */ public void printExpr(JCTree tree) throws IOException { printExpr(tree, TreeInfo.noPrec); } /** Derived visitor method: print statement tree. */ public void printStat(JCTree tree) throws IOException { if (isEmptyStat(tree)) { // printEmptyStat(); // -- starting in java 7, these get lost, so to be consistent, we never print them. } else { printExpr(tree, TreeInfo.notExpression); } } public void printEmptyStat() throws IOException { print(";"); } public boolean isEmptyStat(JCTree tree) { if (!(tree instanceof JCBlock)) return false; JCBlock block = (JCBlock) tree; return (Position.NOPOS == block.pos) && block.stats.isEmpty(); } /** Derived visitor method: print list of expression trees, separated by given string. * @param sep the separator string */ public <T extends JCTree> void printExprs(List<T> trees, String sep) throws IOException { if (trees.nonEmpty()) { printExpr(trees.head); for (List<T> l = trees.tail; l.nonEmpty(); l = l.tail) { print(sep); printExpr(l.head); } } } /** Derived visitor method: print list of expression trees, separated by commas. */ public <T extends JCTree> void printExprs(List<T> trees) throws IOException { printExprs(trees, ", "); } /** Derived visitor method: print list of statements, each on a separate line. */ public void printStats(List<? extends JCTree> trees) throws IOException { for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) { if (isSuppressed(l.head)) continue; if (!suppressAlignmentForEmptyLines(l.head)) align(); printStat(l.head); println(); } } private boolean suppressAlignmentForEmptyLines(JCTree tree) { return !formatPreferences.fillEmpties() && startsWithNewLine(tree); } private boolean startsWithNewLine(JCTree tree) { return tree instanceof JCMethodDecl || tree instanceof JCClassDecl; } private boolean isSuppressed(JCTree tree) { if (isEmptyStat(tree)) { return true; } if (tree instanceof JCExpressionStatement) { return isNoArgsSuperCall(((JCExpressionStatement)tree).expr); } return false; } /** Print a set of modifiers. */ public void printFlags(long flags) throws IOException { if ((flags & SYNTHETIC) != 0) print("/*synthetic*/ "); if (suppressFinalAndSemicolonsInTry) { flags = flags & ~FINAL; suppressFinalAndSemicolonsInTry = false; } print(TreeInfo.flagNames(flags)); if ((flags & StandardFlags) != 0) print(" "); if ((flags & ANNOTATION) != 0) print("@"); } public void printAnnotations(List<JCAnnotation> trees) throws IOException { for (List<JCAnnotation> l = trees; l.nonEmpty(); l = l.tail) { printStat(l.head); if (inParams) { print(" "); } else { println(); align(); } } } /** Print documentation comment, if it exists * @param tree The tree for which a documentation comment should be printed. */ public void printDocComment(JCTree tree) throws IOException { String dc = getJavadocFor(tree); if (dc == null) return; print("/**"); println(); int pos = 0; int endpos = lineEndPos(dc, pos); boolean atStart = true; while (pos < dc.length()) { String line = dc.substring(pos, endpos); if (line.trim().isEmpty() && atStart) { atStart = false; continue; } atStart = false; align(); print(" *"); if (pos < dc.length() && dc.charAt(pos) > ' ') print(" "); print(dc.substring(pos, endpos)); println(); pos = endpos + 1; endpos = lineEndPos(dc, pos); } align(); print(" */"); println(); align(); } //where static int lineEndPos(String s, int start) { int pos = s.indexOf('\n', start); if (pos < 0) pos = s.length(); return pos; } /** If type parameter list is non-empty, print it enclosed in "<...>" brackets. */ public void printTypeParameters(List<JCTypeParameter> trees) throws IOException { if (trees.nonEmpty()) { print("<"); printExprs(trees); print(">"); } } /** Print a block. */ public void printBlock(List<? extends JCTree> stats, JCTree container) throws IOException { print("{"); println(); indent(); printStats(stats); consumeComments(endPos(container)); undent(); align(); print("}"); } /** Print a block. */ public void printEnumBody(List<JCTree> stats) throws IOException { print("{"); println(); indent(); boolean first = true; for (List<JCTree> l = stats; l.nonEmpty(); l = l.tail) { if (isEnumerator(l.head)) { if (!first) { print(","); println(); } align(); printStat(l.head); first = false; } } print(";"); println(); int x = 0; for (List<JCTree> l = stats; l.nonEmpty(); l = l.tail) { x++; if (!isEnumerator(l.head)) { if (!suppressAlignmentForEmptyLines(l.head)) align(); printStat(l.head); println(); } } undent(); align(); print("}"); } public void printEnumMember(JCVariableDecl tree) throws IOException { printAnnotations(tree.mods.annotations); print(tree.name); if (tree.init instanceof JCNewClass) { JCNewClass constructor = (JCNewClass) tree.init; if (constructor.args != null && constructor.args.nonEmpty()) { print("("); printExprs(constructor.args); print(")"); } if (constructor.def != null && constructor.def.defs != null) { print(" "); printBlock(constructor.def.defs, constructor.def); } } } /** Is the given tree an enumerator definition? */ boolean isEnumerator(JCTree t) { return VARDEF.equals(treeTag(t)) && (((JCVariableDecl) t).mods.flags & ENUM) != 0; } /** Print unit consisting of package clause and import statements in toplevel, * followed by class definition. if class definition == null, * print all definitions in toplevel. * @param tree The toplevel tree * @param cdef The class definition, which is assumed to be part of the * toplevel tree. */ public void printUnit(JCCompilationUnit tree, JCClassDecl cdef) throws IOException { Object dc = getDocComments(tree); loadDocCommentsTable(dc); printDocComment(tree); if (tree.pid != null) { consumeComments(tree.pos, tree); print("package "); printExpr(tree.pid); print(";"); println(); } boolean firstImport = true; for (List<JCTree> l = tree.defs; l.nonEmpty() && (cdef == null || IMPORT.equals(treeTag(l.head))); l = l.tail) { if (IMPORT.equals(treeTag(l.head))) { JCImport imp = (JCImport)l.head; Name name = TreeInfo.name(imp.qualid); if (name == name.table.fromChars(new char[] {'*'}, 0, 1) || cdef == null || isUsed(TreeInfo.symbol(imp.qualid), cdef)) { if (firstImport) { firstImport = false; println(); } printStat(imp); } } else { printStat(l.head); } } if (cdef != null) { printStat(cdef); println(); } } // where @SuppressWarnings("unchecked") private void loadDocCommentsTable(Object dc) { if (dc instanceof Map<?, ?>) this.docComments = (Map) dc; else if (dc instanceof DocCommentTable) this.docTable = (DocCommentTable) dc; } boolean isUsed(final Symbol t, JCTree cdef) { class UsedVisitor extends TreeScanner { public void scan(JCTree tree) { if (tree!=null && !result) tree.accept(this); } boolean result = false; public void visitIdent(JCIdent tree) { if (tree.sym == t) result = true; } } UsedVisitor v = new UsedVisitor(); v.scan(cdef); return v.result; } public void visitTopLevel(JCCompilationUnit tree) { try { printUnit(tree, null); consumeComments(Integer.MAX_VALUE); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitImport(JCImport tree) { try { print("import "); if (tree.staticImport) print("static "); printExpr(tree.qualid); print(";"); println(); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitClassDef(JCClassDecl tree) { try { consumeComments(tree.pos, tree); println(); align(); printDocComment(tree); printAnnotations(tree.mods.annotations); printFlags(tree.mods.flags & ~INTERFACE); Name enclClassNamePrev = enclClassName; enclClassName = tree.name; if ((tree.mods.flags & INTERFACE) != 0) { print("interface " + tree.name); printTypeParameters(tree.typarams); if (tree.implementing.nonEmpty()) { print(" extends "); printExprs(tree.implementing); } } else { if ((tree.mods.flags & ENUM) != 0) print("enum " + tree.name); else print("class " + tree.name); printTypeParameters(tree.typarams); if (getExtendsClause(tree) != null) { print(" extends "); printExpr(getExtendsClause(tree)); } if (tree.implementing.nonEmpty()) { print(" implements "); printExprs(tree.implementing); } } print(" "); // <Added for delombok by Reinier Zwitserloot> if ((tree.mods.flags & INTERFACE) != 0) { removeImplicitModifiersForInterfaceMembers(tree.defs); } // </Added for delombok by Reinier Zwitserloot> if ((tree.mods.flags & ENUM) != 0) { printEnumBody(tree.defs); } else { printBlock(tree.defs, tree); } enclClassName = enclClassNamePrev; } catch (IOException e) { throw new UncheckedIOException(e); } } // Added for delombok by Reinier Zwitserloot private void removeImplicitModifiersForInterfaceMembers(List<JCTree> defs) { for (JCTree def :defs) { if (def instanceof JCVariableDecl) { ((JCVariableDecl) def).mods.flags &= ~(Flags.PUBLIC | Flags.STATIC | Flags.FINAL); } if (def instanceof JCMethodDecl) { ((JCMethodDecl) def).mods.flags &= ~(Flags.PUBLIC | Flags.ABSTRACT); } if (def instanceof JCClassDecl) { ((JCClassDecl) def).mods.flags &= ~(Flags.PUBLIC | Flags.STATIC); } } } public void visitMethodDef(JCMethodDecl tree) { try { boolean isConstructor = tree.name == tree.name.table.fromChars("<init>".toCharArray(), 0, 6); // when producing source output, omit anonymous constructors if (isConstructor && enclClassName == null) return; boolean isGeneratedConstructor = isConstructor && ((tree.mods.flags & Flags.GENERATEDCONSTR) != 0); if (isGeneratedConstructor) return; println(); align(); printDocComment(tree); printExpr(tree.mods); printTypeParameters(tree.typarams); if (tree.typarams != null && tree.typarams.length() > 0) print(" "); if (tree.name == tree.name.table.fromChars("<init>".toCharArray(), 0, 6)) { print(enclClassName != null ? enclClassName : tree.name); } else { printExpr(tree.restype); print(" " + tree.name); } print("("); inParams = true; printExprs(tree.params); inParams = false; print(")"); if (tree.thrown.nonEmpty()) { print(" throws "); printExprs(tree.thrown); } if (tree.defaultValue != null) { print(" default "); print(tree.defaultValue); } if (tree.body != null) { print(" "); printBlock(tree.body.stats, tree.body); } else { print(";"); } } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitVarDef(JCVariableDecl tree) { try { boolean suppressSemi = suppressFinalAndSemicolonsInTry; if (getJavadocFor(tree) != null) { println(); align(); } printDocComment(tree); if ((tree.mods.flags & ENUM) != 0) { printEnumMember(tree); } else { printExpr(tree.mods); if ((tree.mods.flags & VARARGS) != 0) { printExpr(((JCArrayTypeTree) tree.vartype).elemtype); print("... " + tree.name); } else { printExpr(tree.vartype); print(" " + tree.name); } if (tree.init != null) { print(" = "); printExpr(tree.init); } if (prec == TreeInfo.notExpression && !suppressSemi) print(";"); } } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitSkip(JCSkip tree) { try { print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitBlock(JCBlock tree) { try { consumeComments(tree.pos); printFlags(tree.flags); printBlock(tree.stats, tree); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitDoLoop(JCDoWhileLoop tree) { try { print("do "); printStat(tree.body); align(); print(" while "); if (PARENS.equals(treeTag(tree.cond))) { printExpr(tree.cond); } else { print("("); printExpr(tree.cond); print(")"); } print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitWhileLoop(JCWhileLoop tree) { try { print("while "); if (PARENS.equals(treeTag(tree.cond))) { printExpr(tree.cond); } else { print("("); printExpr(tree.cond); print(")"); } print(" "); printStat(tree.body); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitForLoop(JCForLoop tree) { try { print("for ("); if (tree.init.nonEmpty()) { if (VARDEF.equals(treeTag(tree.init.head))) { printExpr(tree.init.head); for (List<JCStatement> l = tree.init.tail; l.nonEmpty(); l = l.tail) { JCVariableDecl vdef = (JCVariableDecl)l.head; print(", " + vdef.name + " = "); printExpr(vdef.init); } } else { printExprs(tree.init); } } print("; "); if (tree.cond != null) printExpr(tree.cond); print("; "); printExprs(tree.step); print(") "); printStat(tree.body); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitForeachLoop(JCEnhancedForLoop tree) { try { print("for ("); printExpr(tree.var); print(" : "); printExpr(tree.expr); print(") "); printStat(tree.body); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitLabelled(JCLabeledStatement tree) { try { print(tree.label + ":"); if (isEmptyStat(tree.body) || tree.body instanceof JCSkip) { print(" ;"); } else if (tree.body instanceof JCBlock) { print(" "); printStat(tree.body); } else { println(); align(); printStat(tree.body); } } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitSwitch(JCSwitch tree) { try { print("switch "); if (PARENS.equals(treeTag(tree.selector))) { printExpr(tree.selector); } else { print("("); printExpr(tree.selector); print(")"); } print(" {"); println(); printStats(tree.cases); align(); print("}"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitCase(JCCase tree) { try { if (tree.pat == null) { print("default"); } else { print("case "); printExpr(tree.pat); } print(": "); println(); indent(); printStats(tree.stats); undent(); align(); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitSynchronized(JCSynchronized tree) { try { print("synchronized "); if (PARENS.equals(treeTag(tree.lock))) { printExpr(tree.lock); } else { print("("); printExpr(tree.lock); print(")"); } print(" "); printStat(tree.body); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitTry(JCTry tree) { try { print("try "); List<?> resources = null; try { Field f = JCTry.class.getField("resources"); resources = (List<?>) f.get(tree); } catch (Exception ignore) { // In JDK6 and down this field does not exist; resources will retain its initializer value which is what we want. } if (resources != null && resources.nonEmpty()) { print("("); int remaining = resources.size(); if (remaining == 1) { JCTree var = (JCTree) resources.get(0); suppressFinalAndSemicolonsInTry = true; printStat(var); print(") "); } else { indent(); indent(); for (Object var0 : resources) { println(); align(); JCTree var = (JCTree) var0; suppressFinalAndSemicolonsInTry = true; printStat(var); remaining if (remaining > 0) print(";"); } print(") "); undent(); undent(); } } printStat(tree.body); for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { printStat(l.head); } if (tree.finalizer != null) { print(" finally "); printStat(tree.finalizer); } } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitCatch(JCCatch tree) { try { print(" catch ("); printExpr(tree.param); print(") "); printStat(tree.body); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitConditional(JCConditional tree) { try { open(prec, TreeInfo.condPrec); printExpr(tree.cond, TreeInfo.condPrec); print(" ? "); printExpr(tree.truepart, TreeInfo.condPrec); print(" : "); printExpr(tree.falsepart, TreeInfo.condPrec); close(prec, TreeInfo.condPrec); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitIf(JCIf tree) { try { print("if "); if (PARENS.equals(treeTag(tree.cond))) { printExpr(tree.cond); } else { print("("); printExpr(tree.cond); print(")"); } print(" "); printStat(tree.thenpart); if (tree.elsepart != null) { print(" else "); printStat(tree.elsepart); } } catch (IOException e) { throw new UncheckedIOException(e); } } private boolean isNoArgsSuperCall(JCExpression expr) { if (!(expr instanceof JCMethodInvocation)) return false; JCMethodInvocation tree = (JCMethodInvocation) expr; if (!tree.typeargs.isEmpty() || !tree.args.isEmpty()) return false; if (!(tree.meth instanceof JCIdent)) return false; return ((JCIdent) tree.meth).name.toString().equals("super"); } public void visitExec(JCExpressionStatement tree) { if (isNoArgsSuperCall(tree.expr)) return; try { printExpr(tree.expr); if (prec == TreeInfo.notExpression) print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitBreak(JCBreak tree) { try { print("break"); if (tree.label != null) print(" " + tree.label); print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitContinue(JCContinue tree) { try { print("continue"); if (tree.label != null) print(" " + tree.label); print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitReturn(JCReturn tree) { try { print("return"); if (tree.expr != null) { print(" "); printExpr(tree.expr); } print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitThrow(JCThrow tree) { try { print("throw "); printExpr(tree.expr); print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitAssert(JCAssert tree) { try { print("assert "); printExpr(tree.cond); if (tree.detail != null) { print(" : "); printExpr(tree.detail); } print(";"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitApply(JCMethodInvocation tree) { try { if (!tree.typeargs.isEmpty()) { if (SELECT.equals(treeTag(tree.meth))) { JCFieldAccess left = (JCFieldAccess)tree.meth; printExpr(left.selected); print(".<"); printExprs(tree.typeargs); print(">" + left.name); } else { print("<"); printExprs(tree.typeargs); print(">"); printExpr(tree.meth); } } else { printExpr(tree.meth); } print("("); printExprs(tree.args); print(")"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitNewClass(JCNewClass tree) { try { if (tree.encl != null) { printExpr(tree.encl); print("."); } print("new "); if (!tree.typeargs.isEmpty()) { print("<"); printExprs(tree.typeargs); print(">"); } printExpr(tree.clazz); print("("); printExprs(tree.args); print(")"); if (tree.def != null) { Name enclClassNamePrev = enclClassName; enclClassName = tree.def.name != null ? tree.def.name : tree.type != null && tree.type.tsym.name != tree.type.tsym.name.table.fromChars(new char[0], 0, 0) ? tree.type.tsym.name : null; if ((tree.def.mods.flags & Flags.ENUM) != 0) print("/*enum*/"); printBlock(tree.def.defs, tree.def); enclClassName = enclClassNamePrev; } } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitNewArray(JCNewArray tree) { try { if (tree.elemtype != null) { print("new "); JCTree elem = tree.elemtype; if (elem instanceof JCArrayTypeTree) printBaseElementType((JCArrayTypeTree) elem); else printExpr(elem); for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { print("["); printExpr(l.head); print("]"); } if (elem instanceof JCArrayTypeTree) printBrackets((JCArrayTypeTree) elem); } if (tree.elems != null) { if (tree.elemtype != null) print("[]"); print("{"); printExprs(tree.elems); print("}"); } } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitParens(JCParens tree) { try { print("("); printExpr(tree.expr); print(")"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitAssign(JCAssign tree) { try { open(prec, TreeInfo.assignPrec); printExpr(tree.lhs, TreeInfo.assignPrec + 1); print(" = "); printExpr(tree.rhs, TreeInfo.assignPrec); close(prec, TreeInfo.assignPrec); } catch (IOException e) { throw new UncheckedIOException(e); } } public String operatorName(TreeTag tag) { String result = OPERATORS.get(tag); if (result == null) throw new Error(); return result; } public void visitAssignop(JCAssignOp tree) { try { open(prec, TreeInfo.assignopPrec); printExpr(tree.lhs, TreeInfo.assignopPrec + 1); String opname = operatorName(treeTag(tree)); print(" " + opname + " "); printExpr(tree.rhs, TreeInfo.assignopPrec); close(prec, TreeInfo.assignopPrec); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitUnary(JCUnary tree) { try { int ownprec = isOwnPrec(tree); String opname = operatorName(treeTag(tree)); open(prec, ownprec); if (isPrefixUnary(tree)) { print(opname); printExpr(tree.arg, ownprec); } else { printExpr(tree.arg, ownprec); print(opname); } close(prec, ownprec); } catch (IOException e) { throw new UncheckedIOException(e); } } private int isOwnPrec(JCExpression tree) { return treeTag(tree).getOperatorPrecedenceLevel(); } private boolean isPrefixUnary(JCUnary tree) { return treeTag(tree).isPrefixUnaryOp(); } public void visitBinary(JCBinary tree) { try { int ownprec = isOwnPrec(tree); String opname = operatorName(treeTag(tree)); open(prec, ownprec); printExpr(tree.lhs, ownprec); print(" " + opname + " "); printExpr(tree.rhs, ownprec + 1); close(prec, ownprec); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitTypeCast(JCTypeCast tree) { try { open(prec, TreeInfo.prefixPrec); print("("); printExpr(tree.clazz); print(")"); printExpr(tree.expr, TreeInfo.prefixPrec); close(prec, TreeInfo.prefixPrec); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitTypeTest(JCInstanceOf tree) { try { open(prec, TreeInfo.ordPrec); printExpr(tree.expr, TreeInfo.ordPrec); print(" instanceof "); printExpr(tree.clazz, TreeInfo.ordPrec + 1); close(prec, TreeInfo.ordPrec); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitIndexed(JCArrayAccess tree) { try { printExpr(tree.indexed, TreeInfo.postfixPrec); print("["); printExpr(tree.index); print("]"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitSelect(JCFieldAccess tree) { try { printExpr(tree.selected, TreeInfo.postfixPrec); print("." + tree.name); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitIdent(JCIdent tree) { try { print(tree.name); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitLiteral(JCLiteral tree) { TypeTag typeTag = typeTag(tree); try { if (CTC_INT.equals(typeTag)) print(tree.value.toString()); else if (CTC_LONG.equals(typeTag)) print(tree.value + "L"); else if (CTC_FLOAT.equals(typeTag)) print(tree.value + "F"); else if (CTC_DOUBLE.equals(typeTag)) print(tree.value.toString()); else if (CTC_CHAR.equals(typeTag)) { print("\'" + Convert.quote(String.valueOf((char)((Number)tree.value).intValue())) + "\'"); } else if (CTC_BOOLEAN.equals(typeTag)) print(((Number)tree.value).intValue() == 1 ? "true" : "false"); else if (CTC_BOT.equals(typeTag)) print("null"); else print("\"" + Convert.quote(tree.value.toString()) + "\""); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitTypeIdent(JCPrimitiveTypeTree tree) { TypeTag typetag = typeTag(tree); try { if (CTC_BYTE.equals(typetag)) print ("byte"); else if (CTC_CHAR.equals(typetag)) print ("char"); else if (CTC_SHORT.equals(typetag)) print ("short"); else if (CTC_INT.equals(typetag)) print ("int"); else if (CTC_LONG.equals(typetag)) print ("long"); else if (CTC_FLOAT.equals(typetag)) print ("float"); else if (CTC_DOUBLE.equals(typetag)) print ("double"); else if (CTC_BOOLEAN.equals(typetag)) print ("boolean"); else if (CTC_VOID.equals(typetag)) print ("void"); else print("error"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitTypeArray(JCArrayTypeTree tree) { try { printBaseElementType(tree); printBrackets(tree); } catch (IOException e) { throw new UncheckedIOException(e); } } // Prints the inner element type of a nested array private void printBaseElementType(JCArrayTypeTree tree) throws IOException { JCTree elem = tree.elemtype; while (elem instanceof JCWildcard) elem = ((JCWildcard) elem).inner; if (elem instanceof JCArrayTypeTree) printBaseElementType((JCArrayTypeTree) elem); else printExpr(elem); } // prints the brackets of a nested array in reverse order private void printBrackets(JCArrayTypeTree tree) throws IOException { JCTree elem; while (true) { elem = tree.elemtype; print("[]"); if (!(elem instanceof JCArrayTypeTree)) break; tree = (JCArrayTypeTree) elem; } } public void visitTypeApply(JCTypeApply tree) { try { printExpr(tree.clazz); print("<"); printExprs(tree.arguments); print(">"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitTypeParameter(JCTypeParameter tree) { try { print(tree.name); if (tree.bounds.nonEmpty()) { print(" extends "); printExprs(tree.bounds, " & "); } } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public void visitWildcard(JCWildcard tree) { try { Object kind = tree.getClass().getField("kind").get(tree); print(kind); if (kind != null && kind.getClass().getSimpleName().equals("TypeBoundKind")) { kind = kind.getClass().getField("kind").get(kind); } if (tree.getKind() != Tree.Kind.UNBOUNDED_WILDCARD) printExpr(tree.inner); } catch (IOException e) { throw new UncheckedIOException(e); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public void visitTypeBoundKind(TypeBoundKind tree) { try { print(String.valueOf(tree.kind)); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitErroneous(JCErroneous tree) { try { print("(ERROR)"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitLetExpr(LetExpr tree) { try { print("(let " + tree.defs + " in " + tree.expr + ")"); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitModifiers(JCModifiers mods) { try { printAnnotations(mods.annotations); printFlags(mods.flags); } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitAnnotation(JCAnnotation tree) { try { print("@"); printExpr(tree.annotationType); if (tree.args.nonEmpty()) { print("("); if (tree.args.length() == 1 && tree.args.get(0) instanceof JCAssign) { JCExpression lhs = ((JCAssign)tree.args.get(0)).lhs; if (lhs instanceof JCIdent && ((JCIdent)lhs).name.toString().equals("value")) tree.args = List.of(((JCAssign)tree.args.get(0)).rhs); } printExprs(tree.args); print(")"); } } catch (IOException e) { throw new UncheckedIOException(e); } } public void visitTree(JCTree tree) { try { String simpleName = tree.getClass().getSimpleName(); if ("JCTypeUnion".equals(simpleName)) { printExprs(readExpressionList(tree, "alternatives"), " | "); return; } else if ("JCTypeIntersection".equals(simpleName)) { printExprs(readExpressionList(tree, "bounds"), " & "); return; } else if ("JCLambda".equals(simpleName)) { visitLambda0(tree); return; } else { print("(UNKNOWN[" + tree.getClass().getSimpleName() + "]: " + tree + ")"); println(); } } catch (IOException e) { throw new UncheckedIOException(e); } } private void visitLambda0(JCTree tree) { try { print("("); @SuppressWarnings("unchecked") List<JCVariableDecl> params = (List<JCVariableDecl>) readTreeList(tree, "params"); boolean explicit = true; try { explicit = readObject(tree, "paramKind").toString().equals("EXPLICIT"); } catch (Exception e) {} if (explicit) { printExprs(params); } else { String sep = ""; for (JCVariableDecl param : params) { print(sep); print(param.name); sep = ", "; } } print(") -> "); printExpr(readTree(tree, "body")); } catch (IOException e) { throw new UncheckedIOException(e); } } private JCTree readTree(JCTree tree, String fieldName) { try { return (JCTree) readObject(tree, fieldName); } catch (Exception e) { return null; } } @SuppressWarnings("unchecked") private List<? extends JCTree> readTreeList(JCTree tree, String fieldName) throws IOException { try { return (List<? extends JCTree>) readObject(tree, fieldName); } catch (Exception e) { return List.nil(); } } @SuppressWarnings("unchecked") private List<JCExpression> readExpressionList(JCTree tree, String fieldName) throws IOException { try { return (List<JCExpression>) readObject(tree, fieldName); } catch (Exception e) { return List.nil(); } } @SuppressWarnings("unchecked") private Object readObject(JCTree tree, String fieldName) throws Exception { try { return tree.getClass().getDeclaredField(fieldName).get(tree); } catch (Exception e) { print("ERROR_READING_FIELD"); throw e; } } }
package ucar.unidata.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.List; /** * A utility class that implements DatedThing */ public class DatedObject implements DatedThing { /** The date */ private Date date; /** The object */ private Object object; /** * Construct this object with just a date * * @param date the date */ public DatedObject(Date date) { this(date, null); } /** * Construct this object with a date and an object * * @param date the date * @param object The object */ public DatedObject(Date date, Object object) { this.date = date; this.object = object; } /** * Select and return the DatedThings taht have dates between the two given dates. * * @param startDate Start date * @param endDate End date * @param datedThings DatedThing-s to look at * * @return List of DatedThing-s that are between the given dates */ public static List select(Date startDate, Date endDate, List datedThings) { if (startDate.getTime() > endDate.getTime()) { Date tmp = startDate; startDate = endDate; endDate = tmp; } long t1 = startDate.getTime(); long t2 = endDate.getTime(); List selected = new ArrayList(); for (int i = 0; i < datedThings.size(); i++) { DatedThing datedThing = (DatedThing) datedThings.get(i); long time = datedThing.getDate().getTime(); if ((time >= t1) && (time <= t2)) { selected.add(datedThing); } } return selected; } /** * Sort the given list of DatedThing-s * * @param datedThings list to sort * @param ascending sort order * * @return sorted list */ public static List sort(List datedThings, final boolean ascending) { Comparator comp = new Comparator() { public int compare(Object o1, Object o2) { DatedThing a1 = (DatedThing) o1; DatedThing a2 = (DatedThing) o2; int result = a1.getDate().compareTo(a2.getDate()); if ( !ascending) { result = -result; } return result; } public boolean equals(Object obj) { return obj == this; } }; Object[] array = datedThings.toArray(); Arrays.sort(array, comp); return Arrays.asList(array); } /** * equals method * * @param o object to check * * @return equals */ public boolean equals(Object o) { if ( !(o instanceof DatedObject)) { return false; } DatedObject that = (DatedObject) o; if ( !this.date.equals(that.date)) { return false; } if (this.object == null) { return that.object == null; } if (that.object == null) { return this.object == null; } return this.object.equals(that.object); } /** * Set the Date property. * * @param value The new value for Date */ public void setDate(Date value) { date = value; } /** * Get the Date property. * * @return The Date */ public Date getDate() { return date; } /** * Set the Object property. * * @param value The new value for Object */ public void setObject(Object value) { object = value; } /** * Get the Object property. * * @return The Object */ public Object getObject() { return object; } /** * to string * * @return to string */ public String toString() { if (object != null) { return date + " " + object; } else { return date.toString(); } } }
package net.sf.cglib.core; import java.io.*; import java.lang.reflect.*; import java.util.*; abstract public class CodeGenerator { private static String debugLocation; private static RuntimePermission DEFINE_CGLIB_CLASS_IN_JAVA_PACKAGE_PERMISSION = new RuntimePermission("defineCGLIBClassInJavaPackage"); private Source source; private ClassLoader classLoader; // TODO: make these package-protected so emitter can access them? private String className; private Class superclass; private Class[] interfaces; private boolean used; static { debugLocation = System.getProperty("cglib.debugLocation"); } protected static class Source { Class type; Map cache; int counter = 1; final Method defineClass = ReflectUtils.findMethod("ClassLoader.defineClass(byte[], int, int)"); public Source(Class type, boolean useCache) { this.type = type; if (useCache) { cache = new WeakHashMap(); } } } private void used() { if (used) { throw new IllegalStateException(getClass().getName() + " has already been used"); } used = true; } protected CodeGenerator(Source source) { this.source = source; } protected void setSuperclass(Class superclass) { this.superclass = superclass; } protected void setInterfaces(Class[] interfaces) { this.interfaces = interfaces; } protected Class getSuperclass() { return superclass; } protected Class[] getInterfaces() { return interfaces; } public void setClassName(String className) { this.className = className; } // TODO: pluggable policy? protected String getClassName() { if (className != null) { return className; } else { // TODO: use package of interface if applicable return ((superclass != null) ? superclass : Object.class).getName() + "$$" + ReflectUtils.getNameWithoutPackage(source.type) + "ByCGLIB$$" + source.counter++; } } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } // TODO: pluggable policy? protected ClassLoader getClassLoader() { ClassLoader t = classLoader; if (t != null) { return t; } if (superclass != null) { t = superclass.getClassLoader(); } if (t != null) { return t; } t = getClass().getClassLoader(); if (t != null) { return t; } throw new IllegalStateException("Cannot determine classloader"); // return Thread.currentThread().getContextClassLoader(); } protected Object create(Object key) { used(); try { Object factory = null; boolean isNew = false; synchronized (source) { ClassLoader loader = getClassLoader(); Map cache2 = null; if (source.cache != null) { cache2 = (Map)source.cache.get(loader); if (cache2 != null) { factory = cache2.get(key); } else { source.cache.put(loader, cache2 = new HashMap()); } } isNew = factory == null; if (isNew) { factory = newFactory(defineClass(source.defineClass, getClassName(), generate(), loader)); if (cache2 != null) { cache2.put(key, factory); } } } return newInstance(factory, isNew); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new CodeGenerationException(e); } catch (Error e) { throw e; } } abstract protected byte[] generate() throws Exception; abstract protected Object newFactory(Class type) throws Exception; abstract protected Object newInstance(Object factory, boolean isNew); private static Class defineClass(Method m, String className, byte[] b, ClassLoader loader) throws Exception { if (debugLocation != null) { File file = new File(new File(debugLocation), className + ".class"); // System.err.println("CGLIB writing " + file); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); out.write(b); out.close(); } m.setAccessible(true); SecurityManager sm = System.getSecurityManager(); if (className != null && className.startsWith("java.") && sm != null) { sm.checkPermission(DEFINE_CGLIB_CLASS_IN_JAVA_PACKAGE_PERMISSION); } // deprecated method in jdk to define classes, used because it // does not throw SecurityException if class name starts with "java." Object[] args = new Object[]{ b, new Integer(0), new Integer(b.length) }; return (Class)m.invoke(loader, args); } }
package dr.evomodel.continuous; import dr.evolution.tree.Tree; import dr.evolution.tree.NodeRef; import dr.xml.*; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeStatistic; import dr.inference.model.Statistic; import dr.geo.math.SphericalPolarCoordinates; import java.util.ArrayList; import java.util.List; /** * @author Marc Suchard * @author Philippe Lemey */ public class TreeDispersionStatistic extends Statistic.Abstract { public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic"; public static final String BOOLEAN_OPTION = "greatCircleDistance"; public TreeDispersionStatistic(String name, TreeModel tree, List<AbstractMultivariateTraitLikelihood> traitLikelihoods, boolean genericOption) { super(name); this.traitLikelihoods = traitLikelihoods; this.genericOption = genericOption; } public int getDimension() { return 1; } /** * @return whatever Philippe wants */ public double getStatisticValue(int dim) { String traitName = traitLikelihoods.get(0).getTraitName(); double treelength = 0; double treeDistance = 0; for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) { TreeModel tree = traitLikelihood.getTreeModel(); for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName); if (node != tree.getRoot()) { double[] parentTrait = traitLikelihood.getTraitForNode(tree, tree.getParent(node), traitName); treelength += tree.getBranchLength(node); if (genericOption) { // Great Circle distance SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(trait[0], trait[1]); SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(parentTrait[0], parentTrait[1]); treeDistance += coord1.distance(coord2); } else { treeDistance += getNativeDistance(trait, parentTrait); } } } } return treeDistance / treelength; } private double getNativeDistance(double[] location1, double[] location2) { return Math.sqrt(Math.pow((location2[0] - location1[0]), 2.0) + Math.pow((location2[1] - location1[1]), 2.0)); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TREE_DISPERSION_STATISTIC; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String name = xo.getAttribute(NAME, xo.getId()); TreeModel tree = (TreeModel) xo.getChild(Tree.class); boolean option = xo.getAttribute(BOOLEAN_OPTION, false); // Default value is false List<AbstractMultivariateTraitLikelihood> traitLikelihoods = new ArrayList<AbstractMultivariateTraitLikelihood>(); for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof AbstractMultivariateTraitLikelihood) { traitLikelihoods.add((AbstractMultivariateTraitLikelihood) xo.getChild(i)); } } return new TreeDispersionStatistic(name, tree, traitLikelihoods, option); }
package edu.jhu.hltcoe.gridsearch.dmv; import gnu.trove.TDoubleArrayList; import ilog.concert.IloException; import ilog.concert.IloLPMatrix; import ilog.concert.IloNumVar; import ilog.concert.IloObjective; import ilog.concert.IloRange; import ilog.cplex.IloCplex; import ilog.cplex.IloCplex.Status; import ilog.cplex.IloCplex.UnknownObjectException; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.jboss.dna.common.statistic.Stopwatch; import edu.jhu.hltcoe.data.DepTreebank; import edu.jhu.hltcoe.gridsearch.LazyBranchAndBoundSolver; import edu.jhu.hltcoe.gridsearch.RelaxStatus; import edu.jhu.hltcoe.gridsearch.RelaxedSolution; import edu.jhu.hltcoe.gridsearch.cpt.CptBounds; import edu.jhu.hltcoe.gridsearch.cpt.CptBoundsDelta; import edu.jhu.hltcoe.gridsearch.cpt.CptBoundsDeltaList; import edu.jhu.hltcoe.gridsearch.cpt.LpSumToOneBuilder; import edu.jhu.hltcoe.gridsearch.cpt.CptBoundsDelta.Lu; import edu.jhu.hltcoe.gridsearch.cpt.CptBoundsDelta.Type; import edu.jhu.hltcoe.gridsearch.cpt.LpSumToOneBuilder.CutCountComputer; import edu.jhu.hltcoe.gridsearch.cpt.LpSumToOneBuilder.LpStoBuilderPrm; import edu.jhu.hltcoe.gridsearch.rlt.Rlt; import edu.jhu.hltcoe.gridsearch.rlt.Rlt.RltPrm; import edu.jhu.hltcoe.gridsearch.rlt.Rlt.VarRltFactorFilter; import edu.jhu.hltcoe.gridsearch.rlt.Rlt.VarRltRowFilter; import edu.jhu.hltcoe.lp.CplexPrm; import edu.jhu.hltcoe.math.Vectors; import edu.jhu.hltcoe.parse.IlpFormulation; import edu.jhu.hltcoe.parse.relax.DmvParseLpBuilder; import edu.jhu.hltcoe.parse.relax.DmvParseLpBuilder.DmvTreeProgram; import edu.jhu.hltcoe.train.DmvTrainCorpus; import edu.jhu.hltcoe.util.CplexUtils; import edu.jhu.hltcoe.util.Pair; import edu.jhu.hltcoe.util.Time; import edu.jhu.hltcoe.util.Utilities; public class DmvRltRelaxation implements DmvRelaxation { public static class DmvRltRelaxPrm { public File tempDir = null; public int maxCutRounds = 1; public boolean objVarFilter = true; public CplexPrm cplexPrm = new CplexPrm(); public RltPrm rltPrm = new RltPrm(); public LpStoBuilderPrm stoPrm = new LpStoBuilderPrm(); public DmvRltRelaxPrm() { cplexPrm.simplexAlgorithm = IloCplex.Algorithm.Dual; } public DmvRltRelaxPrm(File tempDir, int maxCutRounds, CutCountComputer ccc, boolean envelopeOnly) { this(); this.tempDir = tempDir; this.maxCutRounds = maxCutRounds; this.stoPrm.initCutCountComp = ccc; this.rltPrm.envelopeOnly = envelopeOnly; } } private static final Logger log = Logger.getLogger(DmvRltRelaxation.class); private static final double OBJ_VAL_DECREASE_TOLERANCE = 1.0; private static final double INTERNAL_BEST_SCORE = Double.NEGATIVE_INFINITY; private static final double INTERNAL_WORST_SCORE = Double.POSITIVE_INFINITY; private IloCplex cplex; private int numSolves; private Stopwatch simplexTimer; private DmvTrainCorpus corpus; private IndexedDmvModel idm; private CptBounds bounds; private LpProblem mp; private LpSumToOneBuilder sto; private DmvObjective dmvObj; private DmvRltRelaxPrm prm; public DmvRltRelaxation(DmvRltRelaxPrm prm) { this.prm = prm; this.numSolves = 0; this.simplexTimer = new Stopwatch(); this.sto = new LpSumToOneBuilder(prm.stoPrm); } // Copied from DmvDantzigWolfeRelaxation. @Override public void init1(DmvTrainCorpus corpus) { this.corpus = corpus; this.idm = new IndexedDmvModel(this.corpus); this.dmvObj = new DmvObjective(this.corpus); } // Copied from DantzigWolfeRelaxation. @Override public void init2(DmvSolution initFeasSol) { this.cplex = prm.cplexPrm.getIloCplexInstance(); try { buildModel(cplex, initFeasSol); } catch (IloException e) { if (e instanceof ilog.cplex.CpxException) { ilog.cplex.CpxException cpxe = (ilog.cplex.CpxException) e; System.err.println("STATUS CODE: " + cpxe.getStatus()); System.err.println("ERROR MSG: " + cpxe.getMessage()); } throw new RuntimeException(e); } } /** * Convenience class for passing around Master Problem variables */ protected static class LpProblem { public IloObjective objective; public IloNumVar[][] objVars; public IloLPMatrix origMatrix; public Rlt rlt; public DmvTreeProgram pp; } private void buildModel(IloCplex cplex, DmvSolution initFeasSol) throws IloException { this.bounds = new CptBounds(this.idm); mp = new LpProblem(); // Add the LP matrix that will contain all the constraints. mp.origMatrix = cplex.LPMatrix("couplingMatrix"); // Initialize the model parameter variables and constraints. sto.init(cplex, mp.origMatrix, idm, bounds); int numConds = idm.getNumConds(); // Create the model parameters variables. sto.createModelParamVars(); // Add sum-to-one constraints on the model parameters. sto.addModelParamConstraints(); // Add the parsing constraints. DmvParseLpBuilder builder = new DmvParseLpBuilder(cplex, IlpFormulation.FLOW_PROJ_LPRELAX_FCOBJ); mp.pp = builder.buildDmvTreeProgram(corpus); builder.addConsToMatrix(mp.pp, mp.origMatrix); RltPrm rltPrm = prm.rltPrm; if (prm.objVarFilter) { if (rltPrm.rowFilter != null && rltPrm.factorFilter != null) { log.warn("Overriding existing filters"); } // Accept only RLT rows/factors that have a non-zero coefficient for some objective variable. rltPrm.rowFilter = new VarRltRowFilter(getObjVarPairs()); rltPrm.factorFilter = new VarRltFactorFilter(getObjVarCols()); } // Add the RLT constraints. mp.rlt = new Rlt(cplex, mp.origMatrix, rltPrm); IloLPMatrix rltMat = mp.rlt.getRltMatrix(); cplex.add(mp.origMatrix); cplex.add(rltMat); // Create the objective mp.objective = cplex.addMinimize(); // Add the supervised portion to the objective. int[][] totSupFreqCm = idm.getTotSupervisedFreqCm(corpus); for (int c = 0; c < numConds; c++) { for (int m = 0; m < idm.getNumParams(c); m++) { if (totSupFreqCm[c][m] != 0) { // Negate the coefficients since we are minimizing cplex.setLinearCoef(mp.objective, -totSupFreqCm[c][m], sto.modelParamVars[c][m]); } } } // Create the objective variables, adding them to the objective mp.objVars = new IloNumVar[numConds][]; for (int c = 0; c < numConds; c++) { int numParams = idm.getNumParams(c); mp.objVars[c] = new IloNumVar[numParams]; for (int m=0; m<numParams; m++) { // Assign RLT vars to objVars. mp.objVars[c][m] = mp.rlt.getRltVar(sto.modelParamVars[c][m], mp.pp.featCountVars[c][m]); // Negate the coefficients since we are minimizing cplex.setLinearCoef(mp.objective, -1.0, mp.objVars[c][m]); } } } private List<IloNumVar> getObjVarCols() { List<IloNumVar> vars = new ArrayList<IloNumVar>(); for (int c = 0; c < sto.modelParamVars.length; c++) { for (int m = 0; m < sto.modelParamVars[c].length; m++) { vars.add(sto.modelParamVars[c][m]); vars.add(mp.pp.featCountVars[c][m]); } } return vars; } private List<Pair<IloNumVar, IloNumVar>> getObjVarPairs() { List<Pair<IloNumVar, IloNumVar>> pairs = new ArrayList<Pair<IloNumVar, IloNumVar>>(); for (int c = 0; c < sto.modelParamVars.length; c++) { for (int m = 0; m < sto.modelParamVars[c].length; m++) { pairs.add(new Pair<IloNumVar,IloNumVar>(sto.modelParamVars[c][m], mp.pp.featCountVars[c][m])); } } return pairs; } @Override public void addFeasibleSolution(DmvSolution initFeasSol) { // Do nothing. } // Copied from DantzigWolfeRelaxation. @Override public RelaxedSolution solveRelaxation() { return solveRelaxation(LazyBranchAndBoundSolver.WORST_SCORE); } // Copied from DantzigWolfeRelaxation. @Override public RelaxedSolution solveRelaxation(double incumbentScore) { try { numSolves++; // Negate since we're minimizing internally double upperBound = -incumbentScore; Pair<RelaxStatus,Double> pair = runSimplexAlgo(cplex, upperBound); RelaxStatus status = pair.get1(); double lowerBound = pair.get2(); // Negate the objective since we were minimizing double objective = -lowerBound; assert(!Double.isNaN(objective)); // This won't always be true if we are stopping early: // assert(Utilities.lte(objective, 0.0, 1e-7)); if (prm.tempDir != null) { cplex.exportModel(new File(prm.tempDir, "rlt.lp").getAbsolutePath()); } log.info("Solution status: " + status); if (!status.hasSolution()) { return new RelaxedDmvSolution(null, null, objective, status, null, null, Double.NaN); } if (prm.tempDir != null) { cplex.writeSolution(new File(prm.tempDir, "rlt.sol").getAbsolutePath()); } log.info("Lower bound: " + lowerBound); RelaxedSolution relaxSol = extractSolution(status, objective); log.info("True obj for relaxed vars: " + relaxSol.getTrueObjectiveForRelaxedSolution()); return relaxSol; } catch (IloException e) { if (e instanceof ilog.cplex.CpxException) { ilog.cplex.CpxException cpxe = (ilog.cplex.CpxException) e; System.err.println("STATUS CODE: " + cpxe.getStatus()); System.err.println("ERROR MSG: " + cpxe.getMessage()); } throw new RuntimeException(e); } } private Pair<RelaxStatus, Double> runSimplexAlgo(IloCplex cplex2, double upperBound) throws IloException { if (!isFeasible()) { return new Pair<RelaxStatus,Double>(RelaxStatus.Infeasible, INTERNAL_WORST_SCORE); } RelaxStatus status = RelaxStatus.Unknown; TDoubleArrayList cutIterLowerBounds = new TDoubleArrayList(); TDoubleArrayList cutIterObjVals = new TDoubleArrayList(); ArrayList<Status> cutIterStatuses = new ArrayList<Status>(); WarmStart warmStart = null; cutIterLowerBounds.add(INTERNAL_BEST_SCORE); int cut; // Solve the full LP problem for (cut = 0; ;) { if (prm.tempDir != null) { cplex.exportModel(new File(prm.tempDir, "rlt.lp").getAbsolutePath()); } // Solve the master problem if (warmStart != null) { setWarmStart(warmStart); } simplexTimer.start(); cplex.solve(); simplexTimer.stop(); status = RelaxStatus.getForLp(cplex.getStatus()); log.trace("LP solution status: " + cplex.getStatus()); if (status == RelaxStatus.Infeasible) { return new Pair<RelaxStatus,Double>(status, INTERNAL_WORST_SCORE); } if (prm.tempDir != null) { cplex.writeSolution(new File(prm.tempDir, "rlt.sol").getAbsolutePath()); } warmStart = getWarmStart(); double objVal = cplex.getObjValue(); log.trace("Simplex solution value: " + objVal); double prevObjVal = cutIterObjVals.size() > 0 ? cutIterObjVals.get(cutIterObjVals.size() - 1) : INTERNAL_WORST_SCORE; if (objVal > prevObjVal + OBJ_VAL_DECREASE_TOLERANCE) { Status prevStatus = cutIterStatuses.size() > 0 ? cutIterStatuses.get(cutIterObjVals.size() - 1) : Status.Unknown; log.warn(String.format("LP objective should monotonically decrease: prev=%f cur=%f. prevStatus=%s curStatus=%s.", prevObjVal, objVal, prevStatus, cplex.getStatus())); } cutIterObjVals.add(objVal); cutIterStatuses.add(cplex.getStatus()); double lowerBound = objVal; cutIterLowerBounds.add(lowerBound); if (status == RelaxStatus.Feasible) { // TODO: get the dual bound and remove this warning. log.warn("A feasible solution does not currently give a valid bound."); } // Check whether to continue if (lowerBound >= upperBound) { // We can fathom this node status = RelaxStatus.Pruned; break; } else { // Optimal solution found status = RelaxStatus.Optimal; if (cut < prm.maxCutRounds) { log.debug(String.format("Iteration objective values (cut=%d): %s", cut, cutIterObjVals)); int numCutAdded = addCuts(cplex, cut); log.debug("Added cuts " + numCutAdded + ", round " + cut); if (numCutAdded == 0) { // No new cuts are needed log.debug("No more cut rounds needed after " + cut + " rounds"); break; } cut++; } else { // Optimal solution found and no more cut rounds left break; } } } // The lower bound should be strictly increasing, because we add cuts. We still // keep track of the lower bounds in case we terminate early. double lowerBound = Vectors.max(cutIterLowerBounds.toNativeArray()); log.debug("Number of cut rounds: " + cut); log.debug("Final lower bound: " + lowerBound); log.debug(String.format("Iteration objective values (cut=%d): %s", cut, cutIterObjVals)); log.debug("Iteration lower bounds: " + cutIterLowerBounds); log.debug("Avg simplex time(ms) per solve: " + Time.totMs(simplexTimer) / numSolves); log.info(String.format("Summary: #cuts=%d #origCons=%d #rltCons=%d", sto.getNumStoCons(), mp.origMatrix.getNrows(), mp.rlt.getRltMatrix().getNrows())); return new Pair<RelaxStatus,Double>(status, lowerBound); } private int addCuts(IloCplex cplex, int cut) throws UnknownObjectException, IloException { List<Integer> rows = sto.projectModelParamsAndAddCuts(); return mp.rlt.addRows(rows); } // Copied from DmvDantzigWolfeRelaxation. private RelaxedSolution extractSolution(RelaxStatus status, double objective) throws UnknownObjectException, IloException { // Store optimal model parameters double[][] optimalLogProbs = extractRelaxedLogProbs(); // Store optimal feature counts double[][] optimalFeatCounts = getFeatureCounts(); // Store objective values z_{c,m} double[][] objVals = new double[idm.getNumConds()][]; for (int c = 0; c < idm.getNumConds(); c++) { objVals[c] = cplex.getValues(mp.objVars[c]); } // Compute the true quadratic objective given the model // parameters and feature counts found by the relaxation. double trueRelaxObj = dmvObj.computeTrueObjective(optimalLogProbs, optimalFeatCounts); // Store fractional corpus parse RelaxedDepTreebank treebank = extractRelaxedParse(); // Print out proportion of fractional edges log.info("Proportion of fractional arcs: " + treebank.getPropFracArcs()); return new RelaxedDmvSolution(Utilities.copyOf(optimalLogProbs), treebank, objective, status, Utilities .copyOf(optimalFeatCounts), Utilities.copyOf(objVals), trueRelaxObj); } // Copied from DmvDantzigWolfeRelaxation. private double[][] extractRelaxedLogProbs() throws UnknownObjectException, IloException { return sto.extractRelaxedLogProbs(); } private double[][] getFeatureCounts() throws IloException { return CplexUtils.getValues(cplex, mp.pp.featCountVars); } protected RelaxedDepTreebank extractRelaxedParse() throws UnknownObjectException, IloException { RelaxedDepTreebank relaxTreebank = new RelaxedDepTreebank(corpus); relaxTreebank.setFracRoots(CplexUtils.getValues(cplex, mp.pp.arcRoot)); relaxTreebank.setFracChildren(CplexUtils.getValues(cplex, mp.pp.arcChild)); return relaxTreebank; } // Copied from DmvDantzigWolfeRelaxation. private boolean isFeasible() { return bounds.areFeasibleBounds(); } // Copied from DmvDantzigWolfeRelaxation. @Override public double computeTrueObjective(double[][] logProbs, DepTreebank treebank) { return dmvObj.computeTrueObjective(logProbs, treebank); } // Copied from DantzigWolfeRelaxation. @Override public void end() { cplex.end(); } // Copied from DmvDantzigWolfeRelaxation. @Override public void reverseApply(CptBoundsDeltaList deltas) { applyDeltaList(CptBoundsDeltaList.getReverse(deltas)); } // Copied from DmvDantzigWolfeRelaxation. @Override public void forwardApply(CptBoundsDeltaList deltas) { applyDeltaList(deltas); } // Copied from DmvDantzigWolfeRelaxation. private void applyDeltaList(CptBoundsDeltaList deltas) { for (CptBoundsDelta delta : deltas) { applyDelta(delta); } } // Copied (with modifications) from DmvDantzigWolfeRelaxation. private void applyDelta(CptBoundsDelta delta) { try { Type type = delta.getType(); int c = delta.getC(); int m = delta.getM(); double origLb = bounds.getLb(type, c, m); double origUb = bounds.getUb(type, c, m); double newLb = origLb; double newUb = origUb; if (delta.getLu() == Lu.LOWER) { newLb = origLb + delta.getDelta(); } else if (delta.getLu() == Lu.UPPER) { newUb = origUb + delta.getDelta(); } else { throw new IllegalStateException(); } assert newLb <= newUb : String.format("l,u = %f, %f", newLb, newUb); bounds.set(type, c, m, newLb, newUb); if (type == Type.PARAM) { // Updates the bounds of the model parameters sto.updateModelParamBounds(c, m, newLb, newUb); mp.rlt.updateBound(sto.modelParamVars[c][m], delta.getLu()); } else { //TODO: Implement this throw new RuntimeException("not implemented"); } } catch (IloException e) { throw new RuntimeException(e); } } // Copied from DmvDantzigWolfeRelaxation. @Override public CptBounds getBounds() { return bounds; } // Copied from DmvDantzigWolfeRelaxation. @Override public IndexedDmvModel getIdm() { return idm; } // Copied from DmvDantzigWolfeRelaxation. @Override public WarmStart getWarmStart() { try { WarmStart warmStart = new WarmStart(); ArrayList<IloNumVar> numVars = new ArrayList<IloNumVar>(); numVars.addAll(Arrays.asList(mp.origMatrix.getNumVars())); numVars.addAll(Arrays.asList(mp.rlt.getRltMatrix().getNumVars())); ArrayList<IloRange> ranges = new ArrayList<IloRange>(); ranges.addAll(Arrays.asList(mp.origMatrix.getRanges())); ranges.addAll(Arrays.asList(mp.rlt.getRltMatrix().getRanges())); warmStart.numVars = numVars.toArray(new IloNumVar[]{}); warmStart.ranges = ranges.toArray(new IloRange[]{}); warmStart.numVarStatuses = cplex.getBasisStatuses(warmStart.numVars); warmStart.rangeStatuses = cplex.getBasisStatuses(warmStart.ranges); return warmStart; } catch (IloException e) { throw new RuntimeException(e); } } @Override public void setWarmStart(WarmStart warmStart) { try { // Set the basis status of all variables cplex.setBasisStatuses(warmStart.numVars, warmStart.numVarStatuses, warmStart.ranges, warmStart.rangeStatuses); } catch (IloException e) { throw new RuntimeException(e); } } }
package edu.wustl.xipHost.hostControl; import java.awt.Dimension; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.xml.ws.Endpoint; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import org.nema.dicom.wg23.State; import org.openhealthtools.ihe.atna.auditor.IHEAuditor; import org.xmldb.api.base.XMLDBException; import edu.wustl.xipHost.application.Application; import edu.wustl.xipHost.application.ApplicationManager; import edu.wustl.xipHost.application.ApplicationManagerFactory; import edu.wustl.xipHost.application.ApplicationTerminationEvent; import edu.wustl.xipHost.application.ApplicationTerminationListener; import edu.wustl.xipHost.iterator.IterationTarget; import edu.wustl.xipHost.caGrid.GridManager; import edu.wustl.xipHost.caGrid.GridManagerFactory; import edu.wustl.xipHost.dicom.DicomManager; import edu.wustl.xipHost.dicom.DicomManagerFactory; import edu.wustl.xipHost.gui.ConfigPanel; import edu.wustl.xipHost.gui.ExceptionDialog; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.gui.LoginDialog; import edu.wustl.xipHost.worklist.Worklist; import edu.wustl.xipHost.worklist.WorklistFactory; import edu.wustl.xipHost.xds.XDSManager; import edu.wustl.xipHost.xds.XDSManagerFactory; public class HostConfigurator implements ApplicationTerminationListener { final static Logger logger = Logger.getLogger(HostConfigurator.class); Login login = new Login(); File hostTmpDir; File hostOutDir; File hostConfig; HostMainWindow mainWindow; ConfigPanel configPanel = new ConfigPanel(new JFrame()); //ConfigPanel is used to specify tmp and output dirs GridManager gridMgr; DicomManager dicomMgr; ApplicationManager appMgr; XDSManager xdsMgr; File xipApplicationsConfig; public static final String OS = System.getProperty("os.name"); String userName = "xip"; ApplicationTerminationListener applicationTerminationListener; public HostConfigurator(){ applicationTerminationListener = this; } public boolean runHostStartupSequence(){ logger.info("Launching XIP Host. Platform " + OS); hostConfig = new File("./config/xipConfig.xml"); if(loadHostConfigParameters(hostConfig) == false){ new ExceptionDialog("Unable to load Host configuration parameters.", "Ensure host config file config file is valid.", "Host Startup Dialog"); System.exit(0); } if(loadPixelmedSavedImagesFolder(serverConfig) == false){ new ExceptionDialog("Unable to load Pixelmed/HSQLQB configuration parameters.", "Ensure Pixelmed/HSQLQB config file is valid.", "Host DB Startup Dialog"); System.exit(0); } //if config contains displayConfigDialog true -> displayConfigDialog if(getDisplayStartUp()){ displayConfigDialog(); } hostTmpDir = createSubTmpDir(getParentOfTmpDir()); hostOutDir = createSubOutDir(getParentOfOutDir()); prop.setProperty("Application.SavedImagesFolderName", getPixelmedSavedImagesFolder()); try { prop.store(new FileOutputStream(serverConfig), "Updated Application.SavedImagesFolderName"); } catch (FileNotFoundException e1) { System.exit(0); } catch (IOException e1) { System.exit(0); } dicomMgr = DicomManagerFactory.getInstance(); final Properties workstation1Prop = new Properties(); try { workstation1Prop.load(new FileInputStream("./pixelmed-server-hsqldb/workstation1.properties")); } catch (FileNotFoundException e1) { logger.error(e1, e1); System.exit(0); } catch (IOException e1) { logger.error(e1, e1); System.exit(0); } Thread t = new Thread(){ public void run(){ dicomMgr.runDicomStartupSequence("./pixelmed-server-hsqldb/server", workstation1Prop); // Set up default certificates for security. Must be done after starting dicom, but before login. //TODO Move code to the configuration file, read entries from the configuration file, and move files to an XIP location. System.setProperty("javax.net.ssl.keyStore","/MESA/certificates/XIPkeystore.jks"); System.setProperty("javax.net.ssl.keyStorePassword","caBIG2011"); System.setProperty("javax.net.ssl.trustStore","/MESA/runtime/certs-ca-signed/2011_CA_Cert.jks"); System.setProperty("javax.net.ssl.trustStorePassword","connectathon"); System.setProperty("https.ciphersuites","TLS_RSA_WITH_AES_128_CBC_SHA"); //System.setProperty("javax.net.debug","all"); // Set up audit configuration. Must be done before login. // TODO Get URI and possibly other parameters from the config file IHEAuditor.getAuditor().getConfig().setAuditorEnabled(false); if (auditRepositoryURL != ""){ try { IHEAuditor.getAuditor().getConfig().setAuditRepositoryUri(new URI(auditRepositoryURL)); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("URI to auditor improperly formed"); } IHEAuditor.getAuditor().getConfig().setAuditSourceId(aeTitle); IHEAuditor.getAuditor().getConfig().setAuditorEnabled(true); // TODO figure out what should go here, or get from configuration IHEAuditor.getAuditor().getConfig().setAuditEnterpriseSiteId("IHE ERL"); IHEAuditor.getAuditor().getConfig().setHumanRequestor("ltarbox"); IHEAuditor.getAuditor().getConfig().setSystemUserId(userName); IHEAuditor.getAuditor().getConfig().setSystemUserName("Wash. Univ."); } } }; t.start(); logNewUser(); //run GridManagerImpl startup gridMgr = GridManagerFactory.getInstance(); gridMgr.runGridStartupSequence(); //test for gridMgr == null gridMgr.setImportDirectory(hostTmpDir); //run XDSManager startup xdsMgr = XDSManagerFactory.getInstance(); xdsMgr.runStartupSequence(); //run WorkList startup Worklist worklist = WorklistFactory.getInstance(); String path = "./config/worklist.xml"; File xmlWorklistFile = new File(path); worklist.loadWorklist(xmlWorklistFile); appMgr = ApplicationManagerFactory.getInstance(); appMgr.addApplicationTerminationListener(applicationTerminationListener); xipApplicationsConfig = new File("./config/applications.xml"); try { appMgr.loadApplications(xipApplicationsConfig); //Load test applications, RECIST is currently supported on Windows only boolean loadTestApps = false; if(loadTestApps){ loadTestApplications(); } } catch (JDOMException e) { new ExceptionDialog("Unable to load applications.", "Ensure applications xml config file exists and is valid.", "Host Startup Dialog"); System.exit(0); } catch (IOException e) { new ExceptionDialog("Unable to load applications.", "Ensure applications xml config file exists and is valid.", "Host Startup Dialog"); System.exit(0); } //hostOutDir and hostTmpDir are hold in static variables in ApplicationManager appMgr.setOutputDir(hostOutDir); appMgr.setTmpDir(hostTmpDir); //XindiceManager is used to register XMLDB database used to store and manage //XML Native Models XindiceManager xm = XindiceManagerFactory.getInstance(); try { xm.startup(); } catch (XMLDBException e) { //TODO Auto-generated catch block //Q: what to do if Xindice is not launched //1. Go with no native model support or //2. prompt user and exit e.printStackTrace(); } mainWindow = new HostMainWindow(); mainWindow.setUserName(userName); mainWindow.display(); return true; } SAXBuilder builder = new SAXBuilder(); Document document; Element root; String parentOfTmpDir; String parentOfOutDir; Boolean displayStartup; String aeTitle; String dicomStoragePort; String dicomStorageSecurePort; String dicomCommitPort; String dicomCommitSecurePort; String pdqSendFacilityOID; String pdqSendApplicationOID; String auditRepositoryURL; /** * (non-Javadoc) * @see edu.wustl.xipHost.hostControl.HostManager#loadHostConfigParameters() */ public boolean loadHostConfigParameters (File hostConfigFile) { if(hostConfigFile == null){ return false; }else if(!hostConfigFile.exists()){ return false; }else{ try{ document = builder.build(hostConfigFile); root = document.getRootElement(); //path for the parent of TMP directory if(root.getChild("tmpDir") == null){ parentOfTmpDir = ""; }else if(root.getChild("tmpDir").getValue().trim().isEmpty() || new File(root.getChild("tmpDir").getValue()).exists() == false){ parentOfTmpDir = ""; }else{ parentOfTmpDir = root.getChild("tmpDir").getValue(); } if(root.getChild("outputDir") == null){ parentOfOutDir = ""; }else if(root.getChild("outputDir").getValue().trim().isEmpty() || new File(root.getChild("outputDir").getValue()).exists() == false){ parentOfOutDir = ""; }else{ //path for the parent of output directory. //parentOfOutDir used to store data produced by the xip application parentOfOutDir = root.getChild("outputDir").getValue(); } if(root.getChild("displayStartup") == null){ displayStartup = new Boolean(true); }else{ if(root.getChild("displayStartup").getValue().equalsIgnoreCase("true") || root.getChild("displayStartup").getValue().trim().isEmpty() || parentOfTmpDir.isEmpty() || parentOfOutDir.isEmpty() || parentOfTmpDir.equalsIgnoreCase(parentOfOutDir)){ if(parentOfTmpDir.equalsIgnoreCase(parentOfOutDir)){ parentOfTmpDir = ""; parentOfOutDir = ""; } displayStartup = new Boolean(true); }else if (root.getChild("displayStartup").getValue().equalsIgnoreCase("false")){ displayStartup = new Boolean(false); }else{ displayStartup = new Boolean(true); } } if(root.getChild("AETitle") == null){ aeTitle = ""; }else if(root.getChild("AETitle").getValue().trim().isEmpty()){ aeTitle = ""; }else{ aeTitle = root.getChild("AETitle").getValue(); } if(root.getChild("DicomStoragePort") == null){ dicomStoragePort = ""; }else if(root.getChild("DicomStoragePort").getValue().trim().isEmpty()){ dicomStoragePort = ""; }else{ dicomStoragePort = root.getChild("DicomStoragePort").getValue(); } if(root.getChild("DicomStorageSecurePort") == null){ dicomStorageSecurePort = ""; }else if(root.getChild("DicomStorageSecurePort").getValue().trim().isEmpty()){ dicomStorageSecurePort = ""; }else{ dicomStorageSecurePort = root.getChild("DicomStorageSecurePort").getValue(); } if(root.getChild("DicomCommitPort") == null){ dicomCommitPort = ""; }else if(root.getChild("DicomCommitPort").getValue().trim().isEmpty()){ dicomCommitPort = ""; }else{ dicomCommitPort = root.getChild("DicomCommitPort").getValue(); } if(root.getChild("DicomCommitSecurePort") == null){ dicomCommitSecurePort = ""; }else if(root.getChild("DicomCommitSecurePort").getValue().trim().isEmpty()){ dicomCommitSecurePort = ""; }else{ dicomCommitSecurePort = root.getChild("DicomCommitSecurePort").getValue(); } if(root.getChild("AuditRepositoryURL") == null){ auditRepositoryURL = ""; }else if(root.getChild("AuditRepositoryURL").getValue().trim().isEmpty()){ auditRepositoryURL = ""; }else{ auditRepositoryURL = root.getChild("AuditRepositoryURL").getValue(); } if(root.getChild("PdqSendFacilityOID") == null){ pdqSendFacilityOID = ""; }else if(root.getChild("PdqSendFacilityOID").getValue().trim().isEmpty()){ pdqSendFacilityOID = ""; }else{ pdqSendFacilityOID = root.getChild("PdqSendFacilityOID").getValue(); } if(root.getChild("PdqSendApplicationOID") == null){ pdqSendApplicationOID = ""; }else if(root.getChild("PdqSendApplicationOID").getValue().trim().isEmpty()){ pdqSendApplicationOID = ""; }else{ pdqSendApplicationOID = root.getChild("PdqSendApplicationOID").getValue(); } } catch (JDOMException e) { return false; } catch (IOException e) { return false; } } return true; } File serverConfig = new File("./pixelmed-server-hsqldb/workstation1.properties"); Properties prop = new Properties(); String pixelmedSavedImagesFolder; boolean loadPixelmedSavedImagesFolder(File serverConfig){ if(serverConfig == null){return false;} try { prop.load(new FileInputStream(serverConfig)); pixelmedSavedImagesFolder = prop.getProperty("Application.SavedImagesFolderName"); if(new File(pixelmedSavedImagesFolder).exists() == false){ pixelmedSavedImagesFolder = ""; displayStartup = new Boolean(true); } } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } return true; } public String getParentOfOutDir(){ return parentOfOutDir; } public void setParentOfOutDir(String newDir){ parentOfOutDir = newDir; } public String getParentOfTmpDir(){ return parentOfTmpDir; } public File getHostTmpDir(){ return hostTmpDir; } public void setParentOfTmpDir(String newDir){ parentOfTmpDir = newDir; } public String getPixelmedSavedImagesFolder(){ return pixelmedSavedImagesFolder; } public void setPixelmedSavedImagesFolder(String pixelmedDir){ pixelmedSavedImagesFolder = pixelmedDir; } public Boolean getDisplayStartUp(){ return displayStartup; } public void setDisplayStartUp(Boolean display){ displayStartup = display; } public String getUser(){ return userName; } public String getAETitle(){ return aeTitle; } public String getDicomStoragePort(){ return dicomStoragePort; } public void setDicomStoragePort(String dicomStoragePortIn){ dicomStoragePort = dicomStoragePortIn; } public String getDicomStorageSecurePort(){ return dicomStorageSecurePort; } public void setDicomStorageSecurePort(String dicomStorageSecurePortIn){ dicomStorageSecurePort = dicomStorageSecurePortIn; } public String getDicomCommitPort(){ return dicomCommitPort; } public void setDicomCommitPort(String dicomCommitPortIn){ dicomCommitPort = dicomCommitPortIn; } public String getDicomCommitSecurePort(){ return dicomCommitSecurePort; } public void setDicomCommitSecurePort(String dicomCommitSecurePortIn){ dicomCommitSecurePort = dicomCommitSecurePortIn; } public String getAuditRepositoryURL(){ return auditRepositoryURL; } public void setAuditRepositoryURL(String auditRepositoryURLIn){ auditRepositoryURL = auditRepositoryURLIn; } public String getPDQSendFacilityOID(){ return pdqSendFacilityOID; } public void setPDQSendFacilityOIDL(String pdqSendFacilityOIDIn){ pdqSendFacilityOID = pdqSendFacilityOIDIn; } public String getpdqSendApplicationOID(){ return pdqSendApplicationOID; } public void setpdqSendApplicationOID(String pdqSendApplicationOIDIn){ pdqSendApplicationOID = pdqSendApplicationOIDIn; } /** * method creates subdirectory under parent of tmp directory. * Creating sub directory is meant to prevent situations when tmp dirs * would be created directly on system main dir path e.g. C:\ * @return */ File createSubTmpDir(String parentOfTmpDir){ if(parentOfTmpDir == null || parentOfTmpDir.trim().isEmpty()){return null;} try { File tmpFile = Util.create("TmpXIP", ".tmp", new File(parentOfTmpDir)); tmpFile.deleteOnExit(); return tmpFile; } catch (IOException e) { return null; } } /** * method creates subdirectory under parent of output directory. * Creating sub directory is meant to prevent situations when output dirs * would be created directly on system main dir path e.g. C:\ * @return */ File createSubOutDir(String parentOfOutDir){ if(parentOfOutDir == null || parentOfOutDir.trim().isEmpty()){return null;} if(new File(parentOfOutDir).exists() == false){return null;} File outFile = new File(parentOfOutDir, "OutputXIP"); if(!outFile.exists()){ outFile.mkdir(); } return outFile; } void displayConfigDialog(){ configPanel.setParentOfTmpDir(getParentOfTmpDir()); configPanel.setParentOfOutDir(getParentOfOutDir()); configPanel.setPixelmedSavedImagesDir(getPixelmedSavedImagesFolder()); configPanel.setDisplayStartup(getDisplayStartUp()); configPanel.display(); setParentOfTmpDir(configPanel.getParentOfTmpDir()); setParentOfOutDir(configPanel.getParentOfOutDir()); setPixelmedSavedImagesFolder(configPanel.getPixelmedSavedImagesDir()); setDisplayStartUp(configPanel.getDisplayStartup()); } public void storeHostConfigParameters(File hostConfigFile) { root.getChild("tmpDir").setText(parentOfTmpDir); root.getChild("outputDir").setText(parentOfOutDir); root.getChild("displayStartup").setText(displayStartup.toString()); try { FileOutputStream outStream = new FileOutputStream(hostConfigFile); XMLOutputter outToXMLFile = new XMLOutputter(); outToXMLFile.output(document, outStream); outStream.flush(); outStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } List<URL []> EPRs = new ArrayList<URL []>(); int numOfDeplayedServices = 0; Endpoint ep; static HostConfigurator hostConfigurator; public static void main (String [] args){ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Turn off commons loggin for better performance System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog"); DOMConfigurator.configure("log4j.xml"); hostConfigurator = new HostConfigurator(); boolean startupOK = hostConfigurator.runHostStartupSequence(); if(startupOK == false){ logger.fatal("XIPHost startup error. System exits."); System.exit(0); } /*final long MEGABYTE = 1024L * 1024L; System.out.println("Total heap size: " + (Runtime.getRuntime().maxMemory())/MEGABYTE); System.out.println("Used heap size: " + (Runtime.getRuntime().totalMemory())/MEGABYTE); System.out.println("Free heap size: " + (Runtime.getRuntime().freeMemory())/MEGABYTE);*/ } public static HostConfigurator getHostConfigurator(){ return hostConfigurator; } public HostMainWindow getMainWindow(){ return mainWindow; } List<Application> activeApplications = new ArrayList<Application>(); public void runHostShutdownSequence(){ //TODO //Modify runHostShutdownSequence. Hosted application tabs are not removed, host terminates first, or could terminate first before hosted applications have a chance to terminate first //Host can terminate only if no applications are running (verify applications are not running) List<Application> applications = appMgr.getApplications(); synchronized(activeApplications){ for(Application app : applications){ State state = app.getState(); if(state != null && state.equals(State.EXIT) == false ){ activeApplications.add(app); app.shutDown(); } } while(activeApplications.size() != 0){ try { activeApplications.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } logger.info("Shutting down XIP Host."); //Store Host configuration parameters storeHostConfigParameters(hostConfig); List<Application> notValidApplications = appMgr.getNotValidApplications(); List<Application> appsToStore = new ArrayList<Application>(); appsToStore.addAll(applications); appsToStore.addAll(notValidApplications); //Store Applications appMgr.storeApplications(appsToStore, xipApplicationsConfig); //Perform Grid shutdown that includes store grid locations if(gridMgr.runGridShutDownSequence() == false){ new ExceptionDialog("Error when storing grid locations.", "System will save any modifications made to grid locations.", "Host Shutdown Dialog"); } //Clear content of TmpDir but do not delete TmpDir itself File dir = new File(getParentOfTmpDir()); boolean bln = Util.deleteHostTmpFiles(dir); if(bln == false){ new ExceptionDialog("Not all content of Host TMP directory " + hostTmpDir + " was cleared.", "Only subdirs starting with 'TmpXIP' and ending with '.tmp' and their content is deleted.", "Host Shutdown Dialog"); } XindiceManagerFactory.getInstance().shutdown(); //Clear Xindice directory. Ensures all documents and collections are cleared even when application //does not terminate properly Util.delete(new File("./db")); //Run DICOM shutdown sequence //dicomMgr.runDicomShutDownSequence("jdbc:hsqldb:./pixelmed-server-hsqldb/hsqldb/data/ws1db", "sa", ""); logger.info("XIPHost exits. Thank you for using XIP Host."); /*ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); while (root.getParent() != null) { root = root.getParent(); }*/ // Visit each thread group System.exit(0); } @Override public void applicationTerminated(ApplicationTerminationEvent event) { Application application = (Application)event.getSource(); synchronized(activeApplications){ activeApplications.remove(application); activeApplications.notify(); } } public ApplicationTerminationListener getApplicationTerminationListener(){ return applicationTerminationListener; } void loadTestApplications(){ if(OS.contains("Windows")){ if(appMgr.getApplication("TestApp_WG23FileAccess") == null){ try { String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPApplication_WashU_3.bat").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23FileAccess", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "files", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("TestApp_WG23NativeModel") == null){ try{ String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPAppNativeModel.bat").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23NativeModel", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "native", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("RECIST_Adjudicator") == null){ try { String pathExe = new File("../XIPApp/bin/RECISTFollowUpAdjudicator.bat").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("RECIST_Adjudicator", pathExe, "", "", iconFile.getAbsolutePath(), "rendering", true, "files", 1, IterationTarget.SERIES)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }else{ if(appMgr.getApplication("TestApp_WG23FileAccess") == null){ try { String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPApplication_WashU_3.sh").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23FileAccess", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "files", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("TestApp_WG23NativeModel") == null){ try{ String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPAppNativeModel.sh").getCanonicalPath(); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23NativeModel", pathExe, "", "", iconFile.getAbsolutePath(), "analytical", true, "native", 1, IterationTarget.SERIES)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static int adjustForResolution(){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //logger.debug("Sceen size: Width " + screenSize.getWidth() + ", Height " + screenSize.getHeight()); int height = (int)screenSize.getHeight(); int preferredHeight = 600; if (height < 768 && height >= 600 ){ preferredHeight = 350; }else if(height < 1024 && height >= 768 ){ preferredHeight = 470; }else if (height >= 1024 && height < 1200){ preferredHeight = 600 - 100; }else if(height > 1200 && height <= 1440){ preferredHeight = 800; } return preferredHeight; } public void logNewUser(){ LoginDialog loginDialog = new LoginDialog(); loginDialog.setLogin(login); loginDialog.setModal(true); loginDialog.setVisible(true); userName = login.getUserName(); if(mainWindow != null){ HostMainWindow.getHostIconBar().setUserName(userName); } } }
package io.sprint0.cli; import io.sprint0.cli.configuration.ConfigurationStore; import io.sprint0.cli.configuration.StandardInConfigurationProvider; import io.sprint0.cli.jobs.FullScaffoldJob; import io.sprint0.cli.jobs.Job; import io.sprint0.cli.jobs.NoOpJob; import org.apache.commons.cli.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; public class Main { private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private Job.Status jobStatus; private boolean displayedHelp = false; public Main(String[] args) throws ParseException { Map<String, Supplier<Job>> jobLookup = setupJobLookup(); Options options = setupOptions(); CommandLineParser parser = new DefaultParser(); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h") || commandLine.getArgList().isEmpty()) { showHelp(options); return; } ConfigurationStore configurationStore = new ConfigurationStore(); PrintStream out = System.out; //NOSONAR configurationStore.setConfigurationProvider(new StandardInConfigurationProvider(out)); String command = commandLine.getArgList().get(0); if (jobLookup.containsKey(command)) { Job job = jobLookup.get(command).get(); job.setConfigurationStore(configurationStore); jobStatus = job.execute(commandLine); LOGGER.info("Job status : " + jobStatus); } else { showHelp(options); } } public static void main(String[] args) throws Exception { Main main = new Main(args); LOGGER.info("Completing sprint0 : " + main.getJobStatus()); int exitCode = Job.Status.SUCCESS.equals(main.getJobStatus()) ? 0 : 1; System.exit(exitCode); //NOSONAR } private void showHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sprint0", options); displayedHelp = true; } protected Map<String, Supplier<Job>> setupJobLookup() { Map <String, Supplier<Job>> jobLookup = new HashMap<> (); jobLookup.put("scaffold", FullScaffoldJob::new); jobLookup.put("noop", NoOpJob::new); return jobLookup; } private Options setupOptions() { Options options = new Options(); options.addOption(new Option("h", "help", false, "Display Help")); return options; } public Job.Status getJobStatus() { return jobStatus; } public boolean displayedHelp() { return displayedHelp; } }
package som.primitives.threading; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.RecursiveTask; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.source.SourceSection; import som.interpreter.actors.Actor.UncaughtExceptions; import som.interpreter.nodes.nary.BinaryExpressionNode; import som.interpreter.nodes.nary.UnaryExpressionNode; import som.interpreter.objectstorage.ObjectTransitionSafepoint; import som.primitives.Primitive; import som.primitives.arrays.ToArgumentsArrayNode; import som.primitives.arrays.ToArgumentsArrayNodeFactory; import som.vm.VmSettings; import som.vmobjects.SArray; import som.vmobjects.SBlock; import som.vmobjects.SInvokable; import tools.concurrency.ActorExecutionTrace; import tools.concurrency.TracingActivityThread; public final class TaskPrimitives { public static class SomForkJoinTask extends RecursiveTask<Object> { private static final long serialVersionUID = -2145613708553535622L; private final Object[] argArray; SomForkJoinTask(final Object[] argArray) { this.argArray = argArray; assert argArray[0] instanceof SBlock : "First argument of a block needs to be the block object"; } public SInvokable getMehtod() { return ((SBlock) argArray[0]).getMethod(); } @Override protected Object compute() { ObjectTransitionSafepoint.INSTANCE.register(); try { return ((SBlock) argArray[0]).getMethod().getCallTarget().call(argArray); } finally { ObjectTransitionSafepoint.INSTANCE.unregister(); } } } @GenerateNodeFactory @Primitive(primitive = "threadingTaskJoin:") public abstract static class JoinPrim extends UnaryExpressionNode { public JoinPrim(final boolean ew, final SourceSection s) { super(ew, s); } @Specialization @TruffleBoundary public final Object doTask(final SomForkJoinTask task) { Object result = task.join(); if (VmSettings.ACTOR_TRACING) { ActorExecutionTrace.taskJoin(task.getMehtod()); } return result; } } @GenerateNodeFactory @Primitive(primitive = "threadingTaskSpawn:") public abstract static class SpawnPrim extends UnaryExpressionNode { public SpawnPrim(final boolean ew, final SourceSection s) { super(ew, s); } @Specialization @TruffleBoundary public final SomForkJoinTask doSBlock(final SBlock block) { SomForkJoinTask task = new SomForkJoinTask(new Object[] {block}); forkJoinPool.execute(task); if (VmSettings.ACTOR_TRACING) { ActorExecutionTrace.taskSpawn(block.getMethod()); } return task; } } @GenerateNodeFactory @NodeChild(value = "argArr", type = ToArgumentsArrayNode.class, executeWith = {"argument", "receiver"}) @Primitive(primitive = "threadingTaskSpawn:with:", extraChild = ToArgumentsArrayNodeFactory.class) public abstract static class SpawnWithPrim extends BinaryExpressionNode { public SpawnWithPrim(final boolean ew, final SourceSection s) { super(ew, s); } @Specialization public SomForkJoinTask doSBlock(final SBlock block, final SArray somArgArr, final Object[] argArr) { SomForkJoinTask task = new SomForkJoinTask(argArr); forkJoinPool.execute(task); return task; } } private static final class ForkJoinThreadFactor implements ForkJoinWorkerThreadFactory { @Override public ForkJoinWorkerThread newThread(final ForkJoinPool pool) { return new ForkJoinThread(pool); } } private static final class ForkJoinThread extends TracingActivityThread { protected ForkJoinThread(final ForkJoinPool pool) { super(pool); } @Override public long getCurrentMessageId() { return 0; } } private static final ForkJoinPool forkJoinPool = new ForkJoinPool( VmSettings.NUM_THREADS, new ForkJoinThreadFactor(), new UncaughtExceptions(), false); }
package eu.appbucket.monitor.report; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.location.Location; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import eu.appbucket.monitor.Constants; import eu.appbucket.monitor.update.StolenBikeDbHelper; import eu.appbucket.rothar.web.domain.report.ReportData; public class StolenBikeReporter { private static final String DEBUG_TAG = "StolenBikeReporter"; public void report(Context context, int minor, Location location) { int assetId = lookupAssetIdByMajor(context, minor); postReport(context, assetId, location.getLatitude(), location.getLongitude()); } private int lookupAssetIdByMajor(Context context, int minor) { StolenBikeDbHelper dbHelper = new StolenBikeDbHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); String[] projection = { StolenBikeDbHelper.COLUMN_NAME_ASSET_ID }; String selection = StolenBikeDbHelper.COLUMN_NAME_MAJOR + " = ?"; String[] selectionArgs = { Integer.toString(minor)}; Cursor cursor = db.query( // String, String[], String, String[], String, String, String StolenBikeDbHelper.TABLE_NAME, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, // The values for the WHERE clause "", // don't group the rows "", // don't filter by row groups "" // The sort order ); cursor.moveToFirst(); int assetId = cursor.getInt( cursor.getColumnIndexOrThrow(StolenBikeDbHelper.COLUMN_NAME_ASSET_ID) ); Log.d(DEBUG_TAG, "Reporting found asset id: " + assetId); return assetId; } private void postReport(Context context, int assetId, double latitude, double longitude) { ReportData report = new ReportData(); report.setAssetId(assetId); report.setLatitude(latitude); report.setLongitude(longitude); new ReportStoleBikesTask(context).execute(report); } private class ReportStoleBikesTask extends AsyncTask<ReportData, Void, Void> { private static final String DEBUG_TAG = "ReportStoleBikesTask"; private Context context; public ReportStoleBikesTask(Context context) { this.context = context; } @Override protected Void doInBackground(ReportData... report) { /*try { //return postReport(urls[0]); } catch (IOException e) { // return "Can't file the report: "; }*/ return null; } // Given a URL, establishes an HttpUrlConnection and retrieves // the web page content as a InputStream, which it returns as // a string. private String postReport(ReportData report) throws IOException { InputStream is = null; // Only display the first 15000 characters of the retrieved // web page content. int len = 15000; try { URL url = new URL(Constants.SERVER_URL + "/v3/assets/" + report.getAssetId() + "/reports"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(20000 /* milliseconds */); conn.setConnectTimeout(30000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setUseCaches(false); // Starts the query conn.connect(); // TODO: add JSON to the post // int response = conn.getResponseCode(); Log.d(DEBUG_TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } } // Reads an InputStream and converts it to a String. public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); } @Override protected void onPostExecute(String result) { Map<Integer, Integer> stolenBikesAssetIdToMajor = new HashMap<Integer, Integer>(); try { JSONArray jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { JSONObject explrObject = jsonArray.getJSONObject(i); stolenBikesAssetIdToMajor.put(explrObject.getInt("assetId"), explrObject.getInt("minor")); } } catch (JSONException e) { e.printStackTrace(); } cleanStolenBikeData(); storeStolenBikeData(stolenBikesAssetIdToMajor); } private void showToast(Context context, String message) { int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, message, duration); toast.show(); } private void storeStolenBikeData(Map<Integer, Integer> stolenBikes) { StringBuilder toastData = new StringBuilder("Stolen bike ids: "); StolenBikeDbHelper dbHelper = new StolenBikeDbHelper(context); SQLiteDatabase db = dbHelper.getWritableDatabase(); long newRowId; int major; for (int assetId : stolenBikes.keySet()) { major = stolenBikes.get(assetId); ContentValues values = new ContentValues(); values.put(StolenBikeDbHelper.COLUMN_NAME_ASSET_ID, assetId); values.put(StolenBikeDbHelper.COLUMN_NAME_MAJOR, major); newRowId = db.insert( StolenBikeDbHelper.TABLE_NAME, null, values); toastData.append(assetId + "," + major + "["+newRowId+"], "); } showToast(context, toastData.toString()); } private void cleanStolenBikeData() { StolenBikeDbHelper dbHelper = new StolenBikeDbHelper(context); SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete(StolenBikeDbHelper.TABLE_NAME, null, null); } } }
package com.intellij.openapi.ui; import com.intellij.CommonBundle; import com.intellij.icons.AllIcons; import com.intellij.ide.actions.ActionsCollector; import com.intellij.ide.ui.UISettings; import com.intellij.idea.ActionsBundle; import com.intellij.internal.statistic.eventLog.FeatureUsageUiEventsKt; import com.intellij.openapi.Disposable; import com.intellij.openapi.MnemonicHelper; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeGlassPaneUtil; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.ColorUtil; import com.intellij.ui.JBColor; import com.intellij.ui.border.CustomLineBorder; import com.intellij.ui.components.JBOptionButton; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.mac.TouchbarDataKeys; import com.intellij.util.Alarm; import com.intellij.util.TimeoutUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.*; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.plaf.UIResource; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.intellij.openapi.keymap.KeymapUtil.getKeystrokeText; import static com.intellij.util.containers.ContainerUtil.indexOf; import static com.intellij.util.containers.ContainerUtil.newArrayList; @SuppressWarnings({"SSBasedInspection", "MethodMayBeStatic"}) public abstract class DialogWrapper { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.ui.DialogWrapper"); public enum IdeModalityType { IDE, PROJECT, MODELESS; @NotNull public Dialog.ModalityType toAwtModality() { switch (this) { case IDE: return Dialog.ModalityType.APPLICATION_MODAL; case PROJECT: return Dialog.ModalityType.DOCUMENT_MODAL; case MODELESS: return Dialog.ModalityType.MODELESS; } throw new IllegalStateException(toString()); } } /** * The default exit code for "OK" action. */ public static final int OK_EXIT_CODE = 0; /** * The default exit code for "Cancel" action. */ public static final int CANCEL_EXIT_CODE = 1; /** * The default exit code for "Close" action. Equal to cancel. */ public static final int CLOSE_EXIT_CODE = CANCEL_EXIT_CODE; /** * If you use your own custom exit codes you have to start them with * this constant. */ public static final int NEXT_USER_EXIT_CODE = 2; /** * If your action returned by {@code createActions} method has non * {@code null} value for this key, then the button that corresponds to the action will be the * default button for the dialog. It's true if you don't change this behaviour * of {@code createJButtonForAction(Action)} method. */ @NonNls public static final String DEFAULT_ACTION = "DefaultAction"; @NonNls public static final String FOCUSED_ACTION = "FocusedAction"; @NonNls private static final String NO_AUTORESIZE = "NoAutoResizeAndFit"; private static final KeyStroke SHOW_OPTION_KEYSTROKE = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.ALT_MASK | InputEvent.SHIFT_MASK); @NotNull private final DialogWrapperPeer myPeer; private int myExitCode = CANCEL_EXIT_CODE; /** * The shared instance of default border for dialog's content pane. */ public static final Border ourDefaultBorder = new JBEmptyBorder(UIUtil.PANEL_REGULAR_INSETS); private float myHorizontalStretch = 1.0f; private float myVerticalStretch = 1.0f; /** * Defines horizontal alignment of buttons. */ private int myButtonAlignment = SwingConstants.RIGHT; private boolean myCrossClosesWindow = true; protected Action myOKAction; protected Action myCancelAction; protected Action myHelpAction; private final Map<Action, JButton> myButtonMap = new LinkedHashMap<>(); private boolean myClosed = false; protected boolean myPerformAction = false; private Action myYesAction = null; private Action myNoAction = null; protected JCheckBox myCheckBoxDoNotShowDialog; @Nullable private DoNotAskOption myDoNotAsk; protected JComponent myPreferredFocusedComponent; private Computable<Point> myInitialLocationCallback; private Dimension myActualSize = null; private List<ValidationInfo> myInfo = Collections.emptyList(); @NotNull protected final Disposable myDisposable = new Disposable() { @Override public String toString() { return DialogWrapper.this.toString(); } @Override public void dispose() { DialogWrapper.this.dispose(); } }; private final List<JBOptionButton> myOptionsButtons = new ArrayList<>(); private int myCurrentOptionsButtonIndex = -1; private boolean myResizeInProgress = false; private ComponentAdapter myResizeListener; @NotNull protected String getDoNotShowMessage() { return CommonBundle.message("dialog.options.do.not.show"); } public void setDoNotAskOption(@Nullable DoNotAskOption doNotAsk) { myDoNotAsk = doNotAsk; } private NotNullLazyValue<ErrorText> myErrorText; private final Alarm myErrorTextAlarm = new Alarm(); public static final Color BALLOON_WARNING_BORDER = new JBColor(new Color(0xcca869), new Color(0x4e452f)); public static final Color BALLOON_WARNING_BACKGROUND = new JBColor(new Color(0xf9f4ee), new Color(0x594e32)); protected DialogWrapper(@Nullable Project project, boolean canBeParent) { this(project, canBeParent, IdeModalityType.IDE); } protected DialogWrapper(@Nullable Project project, boolean canBeParent, @NotNull IdeModalityType ideModalityType) { this(project, null, canBeParent, ideModalityType); } protected DialogWrapper(@Nullable Project project, @Nullable Component parentComponent, boolean canBeParent, @NotNull IdeModalityType ideModalityType) { myPeer = parentComponent == null ? createPeer(project, canBeParent, project == null ? IdeModalityType.IDE : ideModalityType) : createPeer(parentComponent, canBeParent); final Window window = myPeer.getWindow(); if (window != null) { myResizeListener = new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { if (!myResizeInProgress) { myActualSize = myPeer.getSize(); if (myErrorText != null && myErrorText.isComputed() && myErrorText.getValue().isVisible()) { myActualSize.height -= myErrorText.getValue().getMinimumSize().height; } } } }; window.addComponentListener(myResizeListener); } createDefaultActions(); } protected DialogWrapper(@Nullable Project project) { this(project, true); } protected DialogWrapper(boolean canBeParent) { this((Project)null, canBeParent); } /** * Typically, we should set a parent explicitly. Use WindowManager#suggestParentWindow * method to find out the best parent for your dialog. Exceptions are cases * when we do not have a project to figure out which window * is more suitable as an owner for the dialog. * <p/> * Instead, use {@link DialogWrapper#DialogWrapper(Project, boolean, boolean)} */ @Deprecated protected DialogWrapper(boolean canBeParent, boolean applicationModalIfPossible) { this(null, canBeParent, applicationModalIfPossible); } protected DialogWrapper(Project project, boolean canBeParent, boolean applicationModalIfPossible) { ensureEventDispatchThread(); if (ApplicationManager.getApplication() != null) { myPeer = createPeer( project != null ? WindowManager.getInstance().suggestParentWindow(project) : WindowManager.getInstance().findVisibleFrame() , canBeParent, applicationModalIfPossible); } else { myPeer = createPeer(null, canBeParent, applicationModalIfPossible); } createDefaultActions(); } protected DialogWrapper(@NotNull Component parent, boolean canBeParent) { ensureEventDispatchThread(); myPeer = createPeer(parent, canBeParent); createDefaultActions(); } //validation private final Alarm myValidationAlarm = new Alarm(getValidationThreadToUse(), myDisposable); @NotNull protected Alarm.ThreadToUse getValidationThreadToUse() { return Alarm.ThreadToUse.SWING_THREAD; } private int myValidationDelay = 300; private boolean myDisposed = false; private boolean myValidationStarted = false; private final ErrorPainter myErrorPainter = new ErrorPainter(); private boolean myErrorPainterInstalled = false; /** * Allows to postpone first start of validation * * @return {@code false} if start validation in {@code init()} method */ protected boolean postponeValidation() { return true; } /** * Validates user input and returns {@code null} if everything is fine * or validation description with component where problem has been found. * * @return {@code null} if everything is OK or validation descriptor */ @Nullable protected ValidationInfo doValidate() { return null; } /** * Validates user input and returns {@code List<ValidationInfo>}. * If everything is fine the returned list is empty otherwise * the list contains all invalid fields with error messages. * This method should preferably be used when validating forms with multiply * fields that require validation. * * @return {@code List<ValidationInfo>} of invalid fields. List * is empty if no errors found. */ @NotNull protected List<ValidationInfo> doValidateAll() { ValidationInfo vi = doValidate(); return vi != null ? Collections.singletonList(vi) : Collections.EMPTY_LIST; } public void setValidationDelay(int delay) { myValidationDelay = delay; } private void installErrorPainter() { if (myErrorPainterInstalled) return; myErrorPainterInstalled = true; UIUtil.invokeLaterIfNeeded(() -> IdeGlassPaneUtil.installPainter(getContentPanel(), myErrorPainter, myDisposable)); } private void updateErrorInfo(@NotNull List<ValidationInfo> info) { boolean updateNeeded = Registry.is("ide.inplace.validation.tooltip") ? !myInfo.equals(info) : !myErrorText.getValue().isTextSet(info) /* do not check isComputed, inplace validation by default now */; if (updateNeeded) { SwingUtilities.invokeLater(() -> { if (myDisposed) return; setErrorInfoAll(info); myPeer.getRootPane().getGlassPane().repaint(); getOKAction().setEnabled(info.isEmpty() || info.stream().allMatch(info1 -> info1.okEnabled)); }); } } protected void createDefaultActions() { myOKAction = new OkAction(); myCancelAction = new CancelAction(); myHelpAction = new HelpAction(); } public void setUndecorated(boolean undecorated) { myPeer.setUndecorated(undecorated); } public final void addMouseListener(@NotNull MouseListener listener) { myPeer.addMouseListener(listener); } public final void addMouseListener(@NotNull MouseMotionListener listener) { myPeer.addMouseListener(listener); } public final void addKeyListener(@NotNull KeyListener listener) { myPeer.addKeyListener(listener); } public final void close(int exitCode, boolean isOk) { ensureEventDispatchThread(); if (myClosed) return; myClosed = true; myExitCode = exitCode; Window window = getWindow(); if (window != null && myResizeListener != null) { window.removeComponentListener(myResizeListener); myResizeListener = null; } if (isOk) { processDoNotAskOnOk(exitCode); } else { processDoNotAskOnCancel(); } Disposer.dispose(myDisposable); } public final void close(int exitCode) { logCloseDialogEvent(exitCode); close(exitCode, exitCode != CANCEL_EXIT_CODE); } /** * Creates border for dialog's content pane. By default content * pane has has empty border with {@code (8,12,8,12)} insets. Subclasses can * return {@code null} for no border. * * @return content pane border */ @Nullable protected Border createContentPaneBorder() { if (getStyle() == DialogStyle.COMPACT) { return JBUI.Borders.empty(); } return ourDefaultBorder; } protected static boolean isMoveHelpButtonLeft() { return UIUtil.isUnderAquaBasedLookAndFeel() || UIUtil.isUnderDarcula() || UIUtil.isUnderWin10LookAndFeel(); } private static boolean isRemoveHelpButton() { return !ApplicationInfo.contextHelpAvailable() || SystemInfo.isWindows && (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()) && Registry.is("ide.win.frame.decoration") || Registry.is("ide.remove.help.button.from.dialogs"); } /** * Creates panel located at the south of the content pane. By default that * panel contains dialog's buttons. This default implementation uses {@code createActions()} * and {@code createJButtonForAction(Action)} methods to construct the panel. * * @return south panel */ protected JComponent createSouthPanel() { List<Action> actions = ContainerUtil.filter(createActions(), Condition.NOT_NULL); List<Action> leftSideActions = ContainerUtil.filter(createLeftSideActions(), Condition.NOT_NULL); Action helpAction = getHelpAction(); boolean addHelpToLeftSide = false; if (isRemoveHelpButton()) { actions.remove(helpAction); } else if (isMoveHelpButtonLeft() && actions.remove(helpAction) && !leftSideActions.contains(helpAction)) { addHelpToLeftSide = true; } if (SystemInfo.isMac) { Action macOtherAction = ContainerUtil.find(actions, MacOtherAction.class::isInstance); if (macOtherAction != null) { leftSideActions.add(macOtherAction); actions.remove(macOtherAction); } // move ok action to the right int okNdx = actions.indexOf(getOKAction()); if (okNdx >= 0 && okNdx != actions.size() - 1) { actions.remove(getOKAction()); actions.add(getOKAction()); } // move cancel action to the left of OK action, if present, and to the leftmost position otherwise int cancelNdx = actions.indexOf(getCancelAction()); if (cancelNdx > 0) { actions.remove(getCancelAction()); actions.add(okNdx < 0 ? 0 : actions.size() - 1, getCancelAction()); } } if (!UISettings.getShadowInstance().getAllowMergeButtons()) { actions = flattenOptionsActions(actions); leftSideActions = flattenOptionsActions(leftSideActions); } List<JButton> leftSideButtons = createButtons(leftSideActions); List<JButton> rightSideButtons = createButtons(actions); int index = 0; myButtonMap.clear(); for (JButton button : ContainerUtil.concat(leftSideButtons, rightSideButtons)) { myButtonMap.put(button.getAction(), button); if (button instanceof JBOptionButton) { myOptionsButtons.add((JBOptionButton)button); } TouchbarDataKeys.putDialogButtonDescriptor(button, index++).setMainGroup(index >= leftSideButtons.size()); } return createSouthPanel(leftSideButtons, rightSideButtons, addHelpToLeftSide); } @NotNull protected JButton createHelpButton(Insets insets) { JButton helpButton = new JButton(getHelpAction()); helpButton.putClientProperty("JButton.buttonType", "help"); helpButton.setText(""); helpButton.setMargin(insets); setHelpTooltip(helpButton); return helpButton; } protected void setHelpTooltip(JButton helpButton) { helpButton.setToolTipText(ActionsBundle.actionDescription("HelpTopics")); } @NotNull private static List<Action> flattenOptionsActions(@NotNull List<Action> actions) { List<Action> newActions = new ArrayList<>(); for (Action action : actions) { newActions.add(action); if (action instanceof OptionAction) { ContainerUtil.addAll(newActions, ((OptionAction)action).getOptions()); } } return newActions; } protected boolean shouldAddErrorNearButtons() { return false; } @NotNull protected DialogStyle getStyle() { return DialogStyle.NO_STYLE; } protected boolean toBeShown() { return !myCheckBoxDoNotShowDialog.isSelected(); } public boolean isTypeAheadEnabled() { return false; } @NotNull private List<JButton> createButtons(@NotNull List<Action> actions) { List<JButton> buttons = new ArrayList<>(); for (Action action : actions) { buttons.add(createJButtonForAction(action)); } return buttons; } @NotNull private JPanel createSouthPanel(@NotNull List<JButton> leftSideButtons, @NotNull List<JButton> rightSideButtons, boolean addHelpToLeftSide) { JPanel panel = new JPanel(new BorderLayout()) { @Override public Color getBackground() { final Color bg = UIManager.getColor("DialogWrapper.southPanelBackground"); if (getStyle() == DialogStyle.COMPACT && bg != null) { return bg; } return super.getBackground(); } }; if (myDoNotAsk != null) { myCheckBoxDoNotShowDialog = new JCheckBox(myDoNotAsk.getDoNotShowMessage()); myCheckBoxDoNotShowDialog.setVisible(myDoNotAsk.canBeHidden()); myCheckBoxDoNotShowDialog.setSelected(!myDoNotAsk.isToBeShown()); DialogUtil.registerMnemonic(myCheckBoxDoNotShowDialog, '&'); } JComponent doNotAskCheckbox = createDoNotAskCheckbox(); JPanel lrButtonsPanel = new NonOpaquePanel(new GridBagLayout()); Insets insets = SystemInfo.isMacOSLeopard && UIUtil.isUnderIntelliJLaF() ? JBUI.insets(0, 8) : JBUI.emptyInsets(); if (rightSideButtons.size() > 0 || leftSideButtons.size() > 0) { GridBag bag = new GridBag().setDefaultInsets(insets); if (leftSideButtons.size() > 0) { JPanel buttonsPanel = createButtonsPanel(leftSideButtons); if (rightSideButtons.size() > 0) { buttonsPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20)); // leave some space between button groups } lrButtonsPanel.add(buttonsPanel, bag.next()); } lrButtonsPanel.add(Box.createHorizontalGlue(), bag.next().weightx(1).fillCellHorizontally()); // left strut if (rightSideButtons.size() > 0) { JPanel buttonsPanel = createButtonsPanel(rightSideButtons); if (shouldAddErrorNearButtons()) { lrButtonsPanel.add(myErrorText.getValue(), bag.next()); lrButtonsPanel.add(Box.createHorizontalStrut(10), bag.next()); } lrButtonsPanel.add(buttonsPanel, bag.next()); } if (SwingConstants.CENTER == myButtonAlignment && doNotAskCheckbox == null) { lrButtonsPanel.add(Box.createHorizontalGlue(), bag.next().weightx(1).fillCellHorizontally()); // right strut } } JComponent helpButton = null; if (addHelpToLeftSide) { helpButton = createHelpButton(insets); } JPanel eastPanel = createSouthAdditionalPanel(); if (helpButton != null || doNotAskCheckbox != null || eastPanel != null) { JPanel leftPanel = new JPanel(new BorderLayout()); if (helpButton != null) leftPanel.add(helpButton, BorderLayout.WEST); if (doNotAskCheckbox != null) { doNotAskCheckbox.setBorder(JBUI.Borders.emptyRight(20)); leftPanel.add(doNotAskCheckbox, BorderLayout.CENTER); } if(eastPanel != null) { leftPanel.add(eastPanel, BorderLayout.EAST); } panel.add(leftPanel, BorderLayout.WEST); } panel.add(lrButtonsPanel, BorderLayout.CENTER); if (getStyle() == DialogStyle.COMPACT) { final Color color = UIManager.getColor("DialogWrapper.southPanelDivider"); Border line = new CustomLineBorder(color != null ? color : OnePixelDivider.BACKGROUND, 1, 0, 0, 0); panel.setBorder(new CompoundBorder(line, JBUI.Borders.empty(8, 12))); } else { panel.setBorder(JBUI.Borders.emptyTop(8)); } return panel; } @Nullable protected JComponent createDoNotAskCheckbox() { return myCheckBoxDoNotShowDialog != null && myCheckBoxDoNotShowDialog.isVisible() ? myCheckBoxDoNotShowDialog : null; } private final JBValue BASE_BUTTON_GAP = new JBValue.Float(UIUtil.isUnderWin10LookAndFeel() ? 8 : 12); @NotNull protected JPanel createButtonsPanel(@NotNull List<? extends JButton> buttons) { JPanel buttonsPanel = new NonOpaquePanel(); buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS)); for (int i = 0; i < buttons.size(); i++) { JComponent button = buttons.get(i); Insets insets = button.getInsets(); buttonsPanel.add(button); if (i < buttons.size() - 1) { int gap = UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF() ? BASE_BUTTON_GAP.get() - insets.left - insets.right : JBUI.scale(8); buttonsPanel.add(Box.createRigidArea(new Dimension(gap, 0))); } } return buttonsPanel; } /** * Additional panel in the lower left part of dialog to the left from additional buttons * * @return panel to be shown or null if it's not required */ @Nullable protected JPanel createSouthAdditionalPanel() { return null; } /** * * @param action should be registered to find corresponding JButton * @return button for specified action or null if it's not found */ @Nullable protected JButton getButton(@NotNull Action action) { return myButtonMap.get(action); } /** * Creates {@code JButton} for the specified action. If the button has not {@code null} * value for {@code DialogWrapper.DEFAULT_ACTION} key then the created button will be the * default one for the dialog. * * @param action action for the button * @return button with action specified * @see DialogWrapper#DEFAULT_ACTION */ protected JButton createJButtonForAction(Action action) { JButton button; if (action instanceof OptionAction && UISettings.getShadowInstance().getAllowMergeButtons()) { button = createJOptionsButton((OptionAction)action); } else { button = new JButton(action); } if (SystemInfo.isMac) { button.putClientProperty("JButton.buttonType", "text"); } Pair<Integer, String> pair = extractMnemonic(button.getText()); button.setText(pair.second); int mnemonic = pair.first; final Object value = action.getValue(Action.MNEMONIC_KEY); if (value instanceof Integer) { mnemonic = (Integer)value; } button.setMnemonic(mnemonic); final Object name = action.getValue(Action.NAME); if (mnemonic == KeyEvent.VK_Y && "Yes".equals(name)) { myYesAction = action; } else if (mnemonic == KeyEvent.VK_N && "No".equals(name)) { myNoAction = action; } if (action.getValue(DEFAULT_ACTION) != null) { if (!myPeer.isHeadless()) { getRootPane().setDefaultButton(button); } } if (action.getValue(FOCUSED_ACTION) != null) { myPreferredFocusedComponent = button; } return button; } @NotNull private JButton createJOptionsButton(@NotNull OptionAction action) { JBOptionButton optionButton = new JBOptionButton(action, action.getOptions()); String tooltip = String.format("Show drop-down menu (%s)", getKeystrokeText(SHOW_OPTION_KEYSTROKE)); optionButton.setOptionTooltipText(tooltip); optionButton.setOkToProcessDefaultMnemonics(false); return optionButton; } @NotNull public static Pair<Integer, String> extractMnemonic(@Nullable String text) { if (text == null) return Pair.create(0, null); int mnemonic = 0; StringBuilder plainText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch == '_' || ch == '&') { //noinspection AssignmentToForLoopParameter i++; if (i >= text.length()) { break; } ch = text.charAt(i); if (ch != '_' && ch != '&') { // Mnemonic is case insensitive. int vk = ch; if (vk >= 'a' && vk <= 'z') { vk -= 'a' - 'A'; } mnemonic = vk; } } plainText.append(ch); } return Pair.create(mnemonic, plainText.toString()); } @NotNull protected DialogWrapperPeer createPeer(@NotNull Component parent, final boolean canBeParent) { return DialogWrapperPeerFactory.getInstance().createPeer(this, parent, canBeParent); } /** * Dialogs with no parents are discouraged. * Instead, use e.g. {@link DialogWrapper#createPeer(Window, boolean, boolean)} */ @Deprecated @NotNull protected DialogWrapperPeer createPeer(boolean canBeParent, boolean applicationModalIfPossible) { return createPeer(null, canBeParent, applicationModalIfPossible); } @NotNull protected DialogWrapperPeer createPeer(final Window owner, final boolean canBeParent, final IdeModalityType ideModalityType) { return DialogWrapperPeerFactory.getInstance().createPeer(this, owner, canBeParent, ideModalityType); } @Deprecated @NotNull protected DialogWrapperPeer createPeer(final Window owner, final boolean canBeParent, final boolean applicationModalIfPossible) { return DialogWrapperPeerFactory.getInstance() .createPeer(this, owner, canBeParent, applicationModalIfPossible ? IdeModalityType.IDE : IdeModalityType.PROJECT); } @NotNull protected DialogWrapperPeer createPeer(@Nullable final Project project, final boolean canBeParent, @NotNull IdeModalityType ideModalityType) { return DialogWrapperPeerFactory.getInstance().createPeer(this, project, canBeParent, ideModalityType); } @NotNull protected DialogWrapperPeer createPeer(@Nullable final Project project, final boolean canBeParent) { return DialogWrapperPeerFactory.getInstance().createPeer(this, project, canBeParent); } @Nullable protected JComponent createTitlePane() { return null; } /** * Factory method. It creates the panel located at the * north of the dialog's content pane. The implementation can return {@code null} * value. In this case there will be no input panel. * * @return north panel */ @Nullable protected JComponent createNorthPanel() { return null; } /** * Factory method. It creates panel with dialog options. Options panel is located at the * center of the dialog's content pane. The implementation can return {@code null} * value. In this case there will be no options panel. * * @return center panel */ @Nullable protected abstract JComponent createCenterPanel(); /** * @see Window#toFront() */ public void toFront() { myPeer.toFront(); } /** * @see Window#toBack() */ public void toBack() { myPeer.toBack(); } protected boolean setAutoAdjustable(boolean autoAdjustable) { JRootPane rootPane = getRootPane(); if (rootPane == null) return false; rootPane.putClientProperty(NO_AUTORESIZE, autoAdjustable ? null : Boolean.TRUE); return true; } //true by default public boolean isAutoAdjustable() { JRootPane rootPane = getRootPane(); return rootPane == null || rootPane.getClientProperty(NO_AUTORESIZE) == null; } protected void dispose() { ensureEventDispatchThread(); myErrorTextAlarm.cancelAllRequests(); myValidationAlarm.cancelAllRequests(); myDisposed = true; for (JButton button : myButtonMap.values()) { button.setAction(null); // avoid memory leak via KeyboardManager } myButtonMap.clear(); final JRootPane rootPane = getRootPane(); // if rootPane = null, dialog has already been disposed if (rootPane != null) { unregisterKeyboardActions(rootPane); if (myActualSize != null && isAutoAdjustable()) { setSize(myActualSize.width, myActualSize.height); } myPeer.dispose(); } } public static void cleanupRootPane(@Nullable JRootPane rootPane) { if (rootPane == null) return; // Must be preserved: // Component#appContext, Component#appContext, Container#component // JRootPane#contentPane due to popup recycling & our border styling // Must be cleared: // JComponent#clientProperties, contentPane children RepaintManager.currentManager(rootPane).removeInvalidComponent(rootPane); unregisterKeyboardActions(rootPane); Container contentPane = rootPane.getContentPane(); if (contentPane != null) contentPane.removeAll(); Disposer.clearOwnFields(rootPane, field -> { String clazz = field.getDeclaringClass().getName(); // keep AWT and Swing fields intact, except some if (!clazz.startsWith("java.") && !clazz.startsWith("javax.")) return true; String name = field.getName(); return "clientProperties".equals(name); }); } public static void unregisterKeyboardActions(@Nullable Component rootPane) { int[] flags = {JComponent.WHEN_FOCUSED, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, JComponent.WHEN_IN_FOCUSED_WINDOW}; for (JComponent eachComp : UIUtil.uiTraverser(rootPane).traverse().filter(JComponent.class)) { ActionMap actionMap = eachComp.getActionMap(); if (actionMap == null) continue; for (KeyStroke eachStroke : eachComp.getRegisteredKeyStrokes()) { boolean remove = true; for (int i : flags) { Object key = eachComp.getInputMap(i).get(eachStroke); Action action = key == null ? null : actionMap.get(key); if (action instanceof UIResource) remove = false; } if (remove) eachComp.unregisterKeyboardAction(eachStroke); } } } public static void cleanupWindowListeners(@Nullable Window window) { if (window == null) return; SwingUtilities.invokeLater(() -> { for (WindowListener listener : window.getWindowListeners()) { if (listener.getClass().getName().startsWith("com.intellij.")) { //LOG.warn("Stale listener: " + listener); window.removeWindowListener(listener); } } }); } /** * This method is invoked by default implementation of "Cancel" action. It just closes dialog * with {@code CANCEL_EXIT_CODE}. This is convenient place to override functionality of "Cancel" action. * Note that the method does nothing if "Cancel" action isn't enabled. */ public void doCancelAction() { if (getCancelAction().isEnabled()) { close(CANCEL_EXIT_CODE); } } private void processDoNotAskOnCancel() { if (myDoNotAsk != null) { if (myDoNotAsk.shouldSaveOptionsOnCancel() && myDoNotAsk.canBeHidden()) { myDoNotAsk.setToBeShown(toBeShown(), CANCEL_EXIT_CODE); } } } /** * You can use this method if you want to know by which event this actions got triggered. It is called only if * the cancel action was triggered by some input event, {@code doCancelAction} is called otherwise. * * @param source AWT event * @see #doCancelAction */ public void doCancelAction(AWTEvent source) { recordAction("DialogCancelAction", source); doCancelAction(); } /** * Programmatically perform a "click" of default dialog's button. The method does * nothing if the dialog has no default button. */ public void clickDefaultButton() { JButton button = getRootPane().getDefaultButton(); if (button != null) { button.doClick(); } } /** * This method is invoked by default implementation of "OK" action. It just closes dialog * with {@code OK_EXIT_CODE}. This is convenient place to override functionality of "OK" action. * Note that the method does nothing if "OK" action isn't enabled. */ protected void doOKAction() { if (getOKAction().isEnabled()) { close(OK_EXIT_CODE); } } protected void processDoNotAskOnOk(int exitCode) { if (myDoNotAsk != null) { if (myDoNotAsk.canBeHidden()) { myDoNotAsk.setToBeShown(toBeShown(), exitCode); } } } /** * @return whether the native window cross button closes the window or not. * {@code true} means that cross performs hide or dispose of the dialog. */ public boolean shouldCloseOnCross() { return myCrossClosesWindow; } @NotNull protected Action[] createActions() { Action helpAction = getHelpAction(); return helpAction == myHelpAction && getHelpId() == null ? new Action[]{getOKAction(), getCancelAction()} : new Action[]{getOKAction(), getCancelAction(), helpAction}; } @NotNull protected Action[] createLeftSideActions() { return new Action[0]; } /** * @return default implementation of "OK" action. This action just invokes * {@code doOKAction()} method. * @see #doOKAction */ @NotNull protected Action getOKAction() { return myOKAction; } /** * @return default implementation of "Cancel" action. This action just invokes * {@code doCancelAction()} method. * @see #doCancelAction */ @NotNull protected Action getCancelAction() { return myCancelAction; } /** * @return default implementation of "Help" action. This action just invokes * {@code doHelpAction()} method. * @see #doHelpAction */ @NotNull protected Action getHelpAction() { return myHelpAction; } protected boolean isProgressDialog() { return false; } public final boolean isModalProgress() { return isProgressDialog(); } /** * Returns content pane * * @return content pane * @see JDialog#getContentPane */ public Container getContentPane() { return myPeer.getContentPane(); } /** * @see JDialog#validate */ public void validate() { myPeer.validate(); } /** * @see JDialog#repaint */ public void repaint() { myPeer.repaint(); } /** * Returns key for persisting dialog dimensions. * <p/> * Default implementation returns {@code null} (no persisting). * * @return dimension service key */ @Nullable @NonNls protected String getDimensionServiceKey() { return null; } @Nullable public final String getDimensionKey() { return getDimensionServiceKey(); } public int getExitCode() { return myExitCode; } /** * @return component which should be focused when the dialog appears * on the screen. */ @Nullable public JComponent getPreferredFocusedComponent() { return SystemInfo.isMac ? myPreferredFocusedComponent : null; } /** * @return horizontal stretch of the dialog. It means that the dialog's horizontal size is * the product of horizontal stretch by horizontal size of packed dialog. The default value * is {@code 1.0f} */ public final float getHorizontalStretch() { return myHorizontalStretch; } /** * @return vertical stretch of the dialog. It means that the dialog's vertical size is * the product of vertical stretch by vertical size of packed dialog. The default value * is {@code 1.0f} */ public final float getVerticalStretch() { return myVerticalStretch; } protected final void setHorizontalStretch(float hStretch) { myHorizontalStretch = hStretch; } protected final void setVerticalStretch(float vStretch) { myVerticalStretch = vStretch; } /** * @return window owner * @see Window#getOwner */ public Window getOwner() { return myPeer.getOwner(); } public Window getWindow() { return myPeer.getWindow(); } public JComponent getContentPanel() { return (JComponent)myPeer.getContentPane(); } /** * @return root pane * @see JDialog#getRootPane */ public JRootPane getRootPane() { return myPeer.getRootPane(); } /** * @return dialog size * @see Window#getSize */ public Dimension getSize() { return myPeer.getSize(); } /** * @return dialog title * @see Dialog#getTitle */ public String getTitle() { return myPeer.getTitle(); } @NotNull private ErrorText createErrorText(@NotNull JPanel southSection) { ErrorText errorText = new ErrorText(getErrorTextAlignment()); errorText.setVisible(false); final ComponentAdapter resizeListener = new ComponentAdapter() { private int myHeight; @Override public void componentResized(ComponentEvent event) { int height = !errorText.isVisible() ? 0 : event.getComponent().getHeight(); if (height != myHeight) { myHeight = height; myResizeInProgress = true; errorText.setMinimumSize(new Dimension(0, height)); JRootPane root = myPeer.getRootPane(); if (root != null) { root.validate(); } if (myActualSize != null && !shouldAddErrorNearButtons()) { myPeer.setSize(myActualSize.width, myActualSize.height + height); } errorText.revalidate(); myResizeInProgress = false; } } }; errorText.myLabel.addComponentListener(resizeListener); Disposer.register(myDisposable, new Disposable() { @Override public void dispose() { errorText.myLabel.removeComponentListener(resizeListener); } }); southSection.add(errorText, BorderLayout.CENTER, 0); return errorText; } protected void init() { ensureEventDispatchThread(); final JPanel root = new JPanel(createRootLayout()); // @Override // public void paint(Graphics g) { // if (ApplicationManager.getApplication() != null) { // UISettings.setupAntialiasing(g); // super.paint(g); myPeer.setContentPane(root); final CustomShortcutSet sc = new CustomShortcutSet(SHOW_OPTION_KEYSTROKE); AnAction toggleShowOptions = DumbAwareAction.create(e -> expandNextOptionButton()); toggleShowOptions.registerCustomShortcutSet(sc, root, myDisposable); JComponent titlePane = createTitlePane(); if (titlePane != null) { JPanel northSection = new JPanel(new BorderLayout()); root.add(northSection, BorderLayout.NORTH); northSection.add(titlePane, BorderLayout.CENTER); } JComponent centerSection = new JPanel(new BorderLayout()); root.add(centerSection, BorderLayout.CENTER); final JComponent n = createNorthPanel(); if (n != null) { centerSection.add(n, BorderLayout.NORTH); } final JComponent centerPanel = createCenterPanel(); if (centerPanel != null) { centerSection.add(centerPanel, BorderLayout.CENTER); } boolean isVisualPaddingCompensatedOnComponentLevel = centerPanel == null || centerPanel.getClientProperty("isVisualPaddingCompensatedOnComponentLevel") == null; if (isVisualPaddingCompensatedOnComponentLevel) { // see comment about visual paddings in the MigLayoutBuilder.build root.setBorder(createContentPaneBorder()); } final JPanel southSection = new JPanel(new BorderLayout()); myErrorText = new NotNullLazyValue<ErrorText>() { @NotNull @Override protected ErrorText compute() { return createErrorText(southSection); } }; if (!isVisualPaddingCompensatedOnComponentLevel) { southSection.setBorder(JBUI.Borders.empty(0, 12, 8, 12)); } root.add(southSection, BorderLayout.SOUTH); final JComponent south = createSouthPanel(); if (south != null) { southSection.add(south, BorderLayout.SOUTH); } MnemonicHelper.init(root); if (!postponeValidation()) { startTrackingValidation(); } if (SystemInfo.isWindows) { installEnterHook(root, myDisposable); } myErrorTextAlarm.setActivationComponent(root); } protected int getErrorTextAlignment() { return SwingConstants.LEADING; } @NotNull protected LayoutManager createRootLayout() { return new BorderLayout(); } private static void installEnterHook(JComponent root, Disposable disposable) { new DumbAwareAction() { @Override public void actionPerformed(@NotNull AnActionEvent e) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner instanceof JButton && owner.isEnabled()) { ((JButton)owner).doClick(); } } @Override public void update(@NotNull AnActionEvent e) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); e.getPresentation().setEnabled(owner instanceof JButton && owner.isEnabled()); } }.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), root, disposable); } private void expandNextOptionButton() { if (myCurrentOptionsButtonIndex >= 0) { myOptionsButtons.get(myCurrentOptionsButtonIndex).closePopup(); } myCurrentOptionsButtonIndex = getEnabledIndexCyclic(myOptionsButtons, myCurrentOptionsButtonIndex, true).orElse(-1); if (myCurrentOptionsButtonIndex >= 0) { myOptionsButtons.get(myCurrentOptionsButtonIndex).showPopup(null, true); } } protected void startTrackingValidation() { SwingUtilities.invokeLater(() -> { if (!myValidationStarted && !myDisposed) { myValidationStarted = true; initValidation(); } }); } protected final void initValidation() { myValidationAlarm.cancelAllRequests(); final Runnable validateRequest = () -> { if (myDisposed) return; List<ValidationInfo> result = doValidateAll(); if (!result.isEmpty()) { installErrorPainter(); } myErrorPainter.setValidationInfo(result); updateErrorInfo(result); if (!myDisposed) { initValidation(); } }; if (getValidationThreadToUse() == Alarm.ThreadToUse.SWING_THREAD) { // null if headless JRootPane rootPane = getRootPane(); myValidationAlarm.addRequest(validateRequest, myValidationDelay, ApplicationManager.getApplication() == null ? null : rootPane == null ? ModalityState.current() : ModalityState.stateForComponent(rootPane)); } else { myValidationAlarm.addRequest(validateRequest, myValidationDelay); } } @Deprecated protected boolean isNorthStrictedToPreferredSize() { return true; } @Deprecated protected boolean isCenterStrictedToPreferredSize() { return false; } @Deprecated protected boolean isSouthStrictedToPreferredSize() { return true; } @NotNull protected JComponent createContentPane() { return new JPanel(); } /** * @see Window#pack */ public void pack() { myPeer.pack(); } public Dimension getPreferredSize() { return myPeer.getPreferredSize(); } protected final void setButtonsAlignment(@MagicConstant(intValues = {SwingConstants.CENTER, SwingConstants.RIGHT}) int alignment) { if (SwingConstants.CENTER != alignment && SwingConstants.RIGHT != alignment) { throw new IllegalArgumentException("unknown alignment: " + alignment); } myButtonAlignment = alignment; } /** * Sets margin for command buttons ("OK", "Cancel", "Help"). * * @Deprecated Button margins aren't used anymore. Button style is standardized. * @param insets buttons margin */ @Deprecated public final void setButtonsMargin(@Nullable Insets insets) {} public final void setCrossClosesWindow(boolean crossClosesWindow) { myCrossClosesWindow = crossClosesWindow; } protected final void setCancelButtonIcon(Icon icon) { // Setting icons causes buttons be 'square' style instead of // 'rounded', which is expected by apple users. if (!SystemInfo.isMac) { myCancelAction.putValue(Action.SMALL_ICON, icon); } } protected final void setCancelButtonText(String text) { myCancelAction.putValue(Action.NAME, text); } public void setModal(boolean modal) { myPeer.setModal(modal); } public boolean isModal() { return myPeer.isModal(); } public boolean isOKActionEnabled() { return myOKAction.isEnabled(); } public void setOKActionEnabled(boolean isEnabled) { myOKAction.setEnabled(isEnabled); } protected final void setOKButtonIcon(Icon icon) { // Setting icons causes buttons be 'square' style instead of // 'rounded', which is expected by apple users. if (!SystemInfo.isMac) { myOKAction.putValue(Action.SMALL_ICON, icon); } } /** * @param text action without mnemonic. If mnemonic is set, presentation would be shifted by one to the left * {@link AbstractButton#setText(String)} * {@link AbstractButton#updateDisplayedMnemonicIndex(String, int)} */ protected final void setOKButtonText(String text) { myOKAction.putValue(Action.NAME, text); } protected final void setOKButtonMnemonic(int c) { myOKAction.putValue(Action.MNEMONIC_KEY, c); } protected final void setOKButtonTooltip(String text) { myOKAction.putValue(Action.SHORT_DESCRIPTION, text); } /** Returns the help identifier, or {@code null} if no help is available. */ @Nullable protected String getHelpId() { return null; } protected void doHelpAction() { if (myHelpAction.isEnabled()) { String helpId = getHelpId(); if (helpId != null) { HelpManager.getInstance().invokeHelp(helpId); } else { LOG.error("null topic; dialog=" + this.getClass() + "; action=" + getHelpAction().getClass()); } } } public boolean isOK() { return getExitCode() == OK_EXIT_CODE; } /** * @return {@code true} if and only if visible * @see Component#isVisible */ public boolean isVisible() { return myPeer.isVisible(); } /** * @return {@code true} if and only if showing * @see Window#isShowing */ public boolean isShowing() { return myPeer.isShowing(); } /** * @param width width * @param height height * @see JDialog#setSize */ public void setSize(int width, int height) { myPeer.setSize(width, height); } /** * @param title title * @see JDialog#setTitle */ public void setTitle(@Nls(capitalization = Nls.Capitalization.Title) String title) { myPeer.setTitle(title); } /** * @see JDialog#isResizable */ public void isResizable() { myPeer.isResizable(); } /** * @param resizable is resizable * @see JDialog#setResizable */ public void setResizable(boolean resizable) { myPeer.setResizable(resizable); } /** * @return dialog location * @see JDialog#getLocation */ @NotNull public Point getLocation() { return myPeer.getLocation(); } /** * @param p new dialog location * @see JDialog#setLocation(Point) */ public void setLocation(@NotNull Point p) { myPeer.setLocation(p); } /** * @param x x * @param y y * @see JDialog#setLocation(int, int) */ public void setLocation(int x, int y) { myPeer.setLocation(x, y); } public void centerRelativeToParent() { myPeer.centerInParent(); } public void show() { logShowDialogEvent(); invokeShow(); } public boolean showAndGet() { if (!isModal()) { throw new IllegalStateException("The showAndGet() method is for modal dialogs only"); } show(); return isOK(); } /** * You need this method ONLY for NON-MODAL dialogs. Otherwise, use {@link #show()} or {@link #showAndGet()}. * * @return result callback which set to "Done" on dialog close, and then its {@code getResult()} will contain {@code isOK()} */ @NotNull public AsyncResult<Boolean> showAndGetOk() { if (isModal()) { throw new IllegalStateException("The showAndGetOk() method is for modeless dialogs only"); } return invokeShow(); } @NotNull private AsyncResult<Boolean> invokeShow() { final AsyncResult<Boolean> result = new AsyncResult<>(); ensureEventDispatchThread(); registerKeyboardShortcuts(); final Disposable uiParent = Disposer.get("ui"); if (uiParent != null) { Disposer.register(uiParent, myDisposable); // ensure everything is disposed on app quit } Disposer.register(myDisposable, new Disposable() { @Override public void dispose() { result.setDone(isOK()); } }); myPeer.show(); return result; } /** * @return Location in absolute coordinates which is used when dialog has no dimension service key or no position was stored yet. * Can return null. In that case dialog will be centered relative to its owner. */ @Nullable public Point getInitialLocation() { return myInitialLocationCallback == null ? null : myInitialLocationCallback.compute(); } public void setInitialLocationCallback(@NotNull Computable<Point> callback) { myInitialLocationCallback = callback; } private void registerKeyboardShortcuts() { final JRootPane rootPane = getRootPane(); if (rootPane == null) return; ActionListener cancelKeyboardAction = createCancelAction(); if (cancelKeyboardAction != null) { rootPane .registerKeyboardAction(cancelKeyboardAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); ActionUtil.registerForEveryKeyboardShortcut(getRootPane(), cancelKeyboardAction, CommonShortcuts.getCloseActiveWindow()); } if (!(isRemoveHelpButton() || isProgressDialog())) { ActionListener helpAction = e -> doHelpAction(); ActionUtil.registerForEveryKeyboardShortcut(getRootPane(), helpAction, CommonShortcuts.getContextHelp()); rootPane.registerKeyboardAction(helpAction, KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); } rootPane.registerKeyboardAction(e -> focusButton(false), KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); rootPane.registerKeyboardAction(e -> focusButton(true), KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); if (myYesAction != null) { rootPane.registerKeyboardAction(myYesAction, KeyStroke.getKeyStroke(KeyEvent.VK_Y, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); } if (myNoAction != null) { rootPane.registerKeyboardAction(myNoAction, KeyStroke.getKeyStroke(KeyEvent.VK_N, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); } } /** * * @return null if we should ignore <Esc> for window closing */ @Nullable protected ActionListener createCancelAction() { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!PopupUtil.handleEscKeyEvent()) { doCancelAction(e); } } }; } private void focusButton(boolean next) { List<JButton> buttons = newArrayList(myButtonMap.values()); int focusedIndex = indexOf(buttons, (Condition<? super Component>)Component::hasFocus); if (focusedIndex >= 0) { getEnabledIndexCyclic(buttons, focusedIndex, next).ifPresent(i -> buttons.get(i).requestFocus()); } } @NotNull private static OptionalInt getEnabledIndexCyclic(@NotNull List<? extends Component> components, int currentIndex, boolean next) { assert -1 <= currentIndex && currentIndex <= components.size(); int start = !next && currentIndex == -1 ? components.size() : currentIndex; return IntStream.range(0, components.size()) .map(i -> (next ? start + i + 1 : start + components.size() - i - 1) % components.size()) .filter(i -> components.get(i).isEnabled()) .findFirst(); } public long getTypeAheadTimeoutMs() { return 0L; } public boolean isToDispatchTypeAhead() { return isOK(); } public static boolean isMultipleModalDialogs() { final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (c != null) { final DialogWrapper wrapper = findInstance(c); return wrapper != null && wrapper.getPeer().getCurrentModalEntities().length > 1; } return false; } private void logCloseDialogEvent(int exitCode) { final String dialogId = getLoggedDialogId(); if (StringUtil.isNotEmpty(dialogId)) { FeatureUsageUiEventsKt.getUiEventLogger().logCloseDialog(dialogId, exitCode, getClass()); } } private void logShowDialogEvent() { final String dialogId = getLoggedDialogId(); if (StringUtil.isNotEmpty(dialogId)) { FeatureUsageUiEventsKt.getUiEventLogger().logShowDialog(dialogId, getClass()); } } /** * The ID will be recorded in user event log, it can be used to understand how often this dialog is used. * * @return null if we shouldn't record the dialog. */ @Nullable protected String getLoggedDialogId() { return getClass().getName(); } /** * Base class for dialog wrapper actions that need to ensure that only * one action for the dialog is running. */ protected abstract class DialogWrapperAction extends AbstractAction { /** * The constructor * * @param name the action name (see {@link Action#NAME}) */ protected DialogWrapperAction(@NotNull String name) { super(name); } /** * {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (myClosed) return; if (myPerformAction) return; try { myPerformAction = true; doAction(e); } finally { myPerformAction = false; } } /** * Do actual work for the action. This method is called only if no other action * is performed in parallel (checked using {@link DialogWrapper#myPerformAction}), * and dialog is active (checked using {@link DialogWrapper#myClosed}) * * @param e action */ protected abstract void doAction(ActionEvent e); } protected class OkAction extends DialogWrapperAction { protected OkAction() { super(CommonBundle.getOkButtonText()); putValue(DEFAULT_ACTION, Boolean.TRUE); } @Override protected void doAction(ActionEvent e) { recordAction("DialogOkAction"); List<ValidationInfo> infoList = doValidateAll(); if (!infoList.isEmpty()) { ValidationInfo info = infoList.get(0); if (info.component != null && info.component.isVisible()) { IdeFocusManager.getInstance(null).requestFocus(info.component, true); } if (!Registry.is("ide.inplace.validation.tooltip")) { DialogEarthquakeShaker.shake(getPeer().getWindow()); } startTrackingValidation(); if(infoList.stream().anyMatch(info1 -> !info1.okEnabled)) return; } doOKAction(); } } private void recordAction(String name) { recordAction(name, EventQueue.getCurrentEvent()); } private void recordAction(String name, AWTEvent event) { if (event instanceof KeyEvent && ApplicationManager.getApplication() != null) { String shortcut = getKeystrokeText(KeyStroke.getKeyStrokeForEvent((KeyEvent)event)); ActionsCollector.getInstance().record(name + " " + shortcut, getClass()); } } protected class CancelAction extends DialogWrapperAction { private CancelAction() { super(CommonBundle.getCancelButtonText()); } @Override protected void doAction(ActionEvent e) { doCancelAction(); } } /** * The action that just closes dialog with the specified exit code * (like the default behavior of the actions "Ok" and "Cancel"). */ protected class DialogWrapperExitAction extends DialogWrapperAction { /** * The exit code for the action */ protected final int myExitCode; /** * The constructor * * @param name the action name * @param exitCode the exit code for dialog */ public DialogWrapperExitAction(String name, int exitCode) { super(name); myExitCode = exitCode; } @Override protected void doAction(ActionEvent e) { if (isEnabled()) { close(myExitCode); } } } private class HelpAction extends AbstractAction { private HelpAction() { super(CommonBundle.getHelpButtonText()); } @Override public void actionPerformed(ActionEvent e) { doHelpAction(); } } /** * Don't override this method. It is not final for the API compatibility. * It will not be called by the DialogWrapper's validator. * Use this method only in circumstances when the exact invalid component is hard to * detect or the valid status is based on several fields. In other cases use * <code>{@link #setErrorText(String, JComponent)}</code> method. * @param text the error text to display */ protected void setErrorText(@Nullable final String text) { setErrorText(text, null); } protected void setErrorText(@Nullable final String text, @Nullable final JComponent component) { setErrorInfoAll((text == null) ? Collections.EMPTY_LIST : Collections.singletonList(new ValidationInfo(text, component))); } protected void setErrorInfoAll(@NotNull List<ValidationInfo> info) { if (myInfo.equals(info)) return; Application application = ApplicationManager.getApplication(); boolean headless = application != null && application.isHeadlessEnvironment(); myErrorTextAlarm.cancelAllRequests(); Runnable clearErrorRunnable = () -> { if (myErrorText != null && myErrorText.isComputed()) { myErrorText.getValue().clearError(); } }; if (headless) { clearErrorRunnable.run(); } else { SwingUtilities.invokeLater(clearErrorRunnable); } List<ValidationInfo> corrected = ContainerUtil.filter(myInfo, vi -> !info.contains(vi)); if (Registry.is("ide.inplace.validation.tooltip")) { corrected.stream().filter(vi -> vi.component != null). map(vi -> ComponentValidator.getInstance(vi.component)). forEach(c -> c.ifPresent(vi -> vi.updateInfo(null))); } myInfo = info; if (Registry.is("ide.inplace.validation.tooltip") && !myInfo.isEmpty()) { myInfo.forEach(vi -> { if (vi.component != null) { ComponentValidator v = ComponentValidator.getInstance(vi.component). orElseGet(() -> new ComponentValidator(getDisposable()).installOn(vi.component)); if (v != null) { v.updateInfo(vi); return; } } SwingUtilities.invokeLater(() -> myErrorText.getValue().appendError(vi.message)); }); } else if (!myInfo.isEmpty()) { Runnable updateErrorTextRunnable = () -> { for (ValidationInfo vi: myInfo) { myErrorText.getValue().appendError(vi.message); } }; if (headless) { updateErrorTextRunnable.run(); } else { myErrorTextAlarm.addRequest(updateErrorTextRunnable, 300, null); } } } /** * Check if component is in error state validation-wise */ protected boolean hasErrors(@NotNull JComponent component) { return myInfo.stream().anyMatch(i -> component.equals(i.component) && !i.warning); } private void updateSize() { if (myActualSize == null && (myErrorText == null || !myErrorText.isComputed() || !myErrorText.getValue().isVisible())) { myActualSize = getSize(); } } @Nullable public static DialogWrapper findInstance(Component c) { while (c != null) { if (c instanceof DialogWrapperDialog) { return ((DialogWrapperDialog)c).getDialogWrapper(); } c = c.getParent(); } return null; } @Nullable public static DialogWrapper findInstanceFromFocus() { return findInstance(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); } private void resizeWithAnimation(@NotNull final Dimension size) { //todo[kb]: fix this PITA myResizeInProgress = true; if (!Registry.is("enable.animation.on.dialogs")) { setSize(size.width, size.height); myResizeInProgress = false; return; } new Thread("DialogWrapper resizer") { int time = 200; int steps = 7; @Override public void run() { int step = 0; final Dimension cur = getSize(); int h = (size.height - cur.height) / steps; int w = (size.width - cur.width) / steps; while (step++ < steps) { setSize(cur.width + w * step, cur.height + h * step); TimeoutUtil.sleep(time / steps); } setSize(size.width, size.height); //repaint(); if (myErrorText != null && myErrorText.isComputed() && myErrorText.getValue().shouldBeVisible()) { myErrorText.getValue().setVisible(true); } myResizeInProgress = false; } }.start(); } private static final Color ERROR_FOREGROUND_COLOR = JBColor.namedColor("Label.errorForeground", new JBColor(new Color(0xC7222D), JBColor.RED)); private class ErrorText extends JPanel { private final JLabel myLabel = new JLabel(); private final List<String> errors = new ArrayList<>(); private ErrorText(int horizontalAlignment) { setLayout(new BorderLayout()); myLabel.setBorder(createErrorTextBorder()); myLabel.setHorizontalAlignment(horizontalAlignment); JBScrollPane pane = new JBScrollPane(myLabel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); pane.setBorder(JBUI.Borders.empty()); pane.setBackground(null); pane.getViewport().setBackground(null); pane.setOpaque(false); add(pane, BorderLayout.CENTER); } private Border createErrorTextBorder() { Border border = createContentPaneBorder(); Insets contentInsets = border != null ? border.getBorderInsets(null) : JBUI.emptyInsets(); Insets baseInsets = JBUI.insets(16, 13); //noinspection UseDPIAwareBorders: Insets are already scaled, so use raw version. return new EmptyBorder(baseInsets.top, baseInsets.left > contentInsets.left ? baseInsets.left - contentInsets.left : 0, baseInsets.bottom > contentInsets.bottom ? baseInsets.bottom - contentInsets.bottom : 0, baseInsets.right > contentInsets.right ? baseInsets.right - contentInsets.right : 0); } private void clearError() { errors.clear(); myLabel.setBounds(0, 0, 0, 0); myLabel.setText(""); setVisible(false); updateSize(); } private void appendError(String text) { errors.add(text); myLabel.setBounds(0, 0, 0, 0); StringBuilder sb = new StringBuilder("<html><font color='#" + ColorUtil.toHex(ERROR_FOREGROUND_COLOR) + "'>"); errors.forEach(error -> sb.append("<left>").append(error).append("</left><br/>")); sb.append("</font></html>"); myLabel.setText(sb.toString()); setVisible(true); updateSize(); } private boolean shouldBeVisible() { return !errors.isEmpty(); } private boolean isTextSet(@NotNull List<ValidationInfo> info) { if (info.isEmpty()) { return errors.isEmpty(); } else if (errors.size() == info.size()){ return errors.equals(info.stream().map(i -> i.message).collect(Collectors.toList())); } else { return false; } } } @NotNull public final DialogWrapperPeer getPeer() { return myPeer; } private static void ensureEventDispatchThread() { if (!EventQueue.isDispatchThread()) { throw new IllegalStateException("The DialogWrapper can only be used in event dispatch thread. Current thread: "+Thread.currentThread()); } } @NotNull public final Disposable getDisposable() { return myDisposable; } /** * @see Adapter */ public interface DoNotAskOption { abstract class Adapter implements DoNotAskOption { /** * Save the state of the checkbox in the settings, or perform some other related action. * This method is called right after the dialog is {@link #close(int) closed}. * <br/> * Note that this method won't be called in the case when the dialog is closed by {@link #CANCEL_EXIT_CODE Cancel} * if {@link #shouldSaveOptionsOnCancel() saving the choice on cancel is disabled} (which is by default). * * @param isSelected true if user selected "don't show again". * @param exitCode the {@link #getExitCode() exit code} of the dialog. * @see #shouldSaveOptionsOnCancel() */ public abstract void rememberChoice(boolean isSelected, int exitCode); /** * Tells whether the checkbox should be selected by default or not. * * @return true if the checkbox should be selected by default. */ public boolean isSelectedByDefault() { return false; } @Override public boolean shouldSaveOptionsOnCancel() { return false; } @NotNull @Override public String getDoNotShowMessage() { return CommonBundle.message("dialog.options.do.not.ask"); } @Override public final boolean isToBeShown() { return !isSelectedByDefault(); } @Override public final void setToBeShown(boolean toBeShown, int exitCode) { rememberChoice(!toBeShown, exitCode); } @Override public final boolean canBeHidden() { return true; } } /** * @return default selection state of checkbox (false -> checkbox selected) */ boolean isToBeShown(); /** * @param toBeShown - if dialog should be shown next time (checkbox selected -> false) * @param exitCode of corresponding DialogWrapper */ void setToBeShown(boolean toBeShown, int exitCode); /** * @return true if checkbox should be shown */ boolean canBeHidden(); boolean shouldSaveOptionsOnCancel(); @NotNull String getDoNotShowMessage(); } @NotNull private ErrorPaintingType getErrorPaintingType() { return ErrorPaintingType.SIGN; } private class ErrorPainter extends AbstractPainter { private List<ValidationInfo> info; @Override public void executePaint(Component component, Graphics2D g) { for (ValidationInfo i : info) { if (i.component != null && !(Registry.is("ide.inplace.errors.outline"))) { int w = i.component.getWidth(); int h = i.component.getHeight(); Point p; switch (getErrorPaintingType()) { case DOT: p = SwingUtilities.convertPoint(i.component, 2, h / 2, component); AllIcons.Ide.ErrorPoint.paintIcon(component, g, p.x, p.y); break; case SIGN: p = SwingUtilities.convertPoint(i.component, w, 0, component); AllIcons.General.Error.paintIcon(component, g, p.x - 8, p.y - 8); break; case LINE: p = SwingUtilities.convertPoint(i.component, 0, h, component); Graphics g2 = g.create(); try { //noinspection UseJBColor g2.setColor(new Color(255, 0, 0, 100)); g2.fillRoundRect(p.x, p.y - 2, w, 4, 2, 2); } finally { g2.dispose(); } break; } } } } @Override public boolean needsRepaint() { return true; } private void setValidationInfo(@NotNull List<ValidationInfo> info) { this.info = info; } } private enum ErrorPaintingType {DOT, SIGN, LINE} public enum DialogStyle {NO_STYLE, COMPACT} }
package com.bigcommerce.api; import java.util.Collection; import com.bigcommerce.api.resources.Orders; public class OrderTest { public static void main(String[] args) { String storeUrl = "https://examplestore.com"; String use = "admin"; String apiKey = "akjfalksjflksjflaskdjflasdk"; Store storeApi = new Store(storeUrl, user, apiKey); Orders orders = storeApi.getOrders(); Collection<Order> allOrders = orders.listAll(); for (Order order : orders) { System.out.println("Customer ID:" + order.getCustomerId()); System.out.println("Order ID:" + order.getId()); System.out.println("Order Status:" + order.getStatus()); // List all products associated with an order for (OrderProduct orderProduct : order.getOrderProducts()) { System.out.println("Product ID:" + orderProduct.getId()); System.out.println("Product Name:" + orderProduct.getName()); System.out.println("Product Quantity:" + orderProduct.getQuantity()); } System.out.println(" } } }
package server; import game.PlayerData; import game.PlayerDataList; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * s * * @author bjodet982 */ public class Server implements Runnable { public int PACKAGE_SIZE = 4096; public int TICK_RATE = 1; private DatagramSocket srvSocket; private int srvPort; private ArrayList<InetSocketAddress> usersL; private Map<InetSocketAddress, PlayerData> data; private boolean srvRunning; public Server(int port) { srvPort = port; usersL = new ArrayList<>(); data = new HashMap(); } @Override public void run() { boolean portErr = false; do { try { srvSocket = new DatagramSocket(srvPort); portErr = false; } catch (SocketException ex) { portErr = true; System.out.print("Port already in use! Input a new port: "); srvPort = new Scanner(System.in).nextInt(); } } while (portErr); srvRunning = true; System.out.println("Server starting up on UDP port: " + srvPort); Thread in = new Thread(new Runnable() { @Override public void run() { while (srvRunning) { try { DatagramPacket incomingPacket = new DatagramPacket(new byte[PACKAGE_SIZE], new byte[PACKAGE_SIZE].length); srvSocket.receive(incomingPacket); ByteArrayInputStream in = new ByteArrayInputStream(incomingPacket.getData()); ObjectInputStream is = new ObjectInputStream(in); handleObject((Object) is.readObject(), (InetSocketAddress) incomingPacket.getSocketAddress()); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } } }); in.start(); Thread out = new Thread(new Runnable() { @Override public void run() { while (srvRunning) { Map<InetSocketAddress, PlayerData> plData = data; ArrayList<InetSocketAddress> plList = (ArrayList<InetSocketAddress>) usersL.clone(); for (InetSocketAddress user : plList) { if (plData.get(user) != null && System.currentTimeMillis() - plData.get(user).time >= 5000) { System.out.println(user + " disconnected! :("); usersL.remove(user); plList.remove(user); data.remove(user); usersL.trimToSize(); } } plList = usersL; plData = data; if (plList.size() > 1) { PlayerData[] pdl = new PlayerData[plList.size()]; PlayerData[] pl = new PlayerData[plList.size() - 1]; for (int i = 1; i < plList.size(); i++) { pdl[i - 1] = plData.get(plList.get(i - 1)); pl[i - 1] = plData.get(plList.get(i)); } int i = 0; for (InetSocketAddress s : new ArrayList<>(plList)) { sendObj(new PlayerDataList(pl), s); if (i < plList.size() - 1) { pl[i] = pdl[i]; i++; } } } else if (plList.size() == 1) { sendObj("keepalive", plList.get(0)); System.out.println("Sent keepalive!"); } try { Thread.sleep(1000 / TICK_RATE); } catch (InterruptedException ex) { } } } }); out.start(); } private void sendObj(Object obj, InetSocketAddress s) { ObjectOutputStream os = null; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); os = new ObjectOutputStream(outputStream); os.writeObject(obj); os.flush(); byte[] data = outputStream.toByteArray(); DatagramPacket sendPacket = new DatagramPacket(data, data.length, InetAddress.getByName(s.getHostString()), s.getPort()); if (sendPacket.getLength() >= PACKAGE_SIZE) { PACKAGE_SIZE *= 2; } srvSocket.send(sendPacket); // System.out.println("SIZE: " + sendPacket.getLength()); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } finally { try { os.close(); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } } private void handleObject(Object obj, InetSocketAddress sender) { if (obj instanceof String) { String s = (String) obj; if (s.matches("heartbeat")) { if (!usersL.contains(sender)) { usersL.add(sender); data.put(sender, new PlayerData(-1000, -1000)); System.out.println("New client connected! Address:" + sender); } sendObj("heartbeat-" + PACKAGE_SIZE + "-" + TICK_RATE, sender); System.out.println("Got heartbeat from " + sender + " sent one back <3"); } } else if (obj instanceof PlayerData) { PlayerData rpd = (PlayerData) obj; data.put(sender, rpd); } } /** * @param args the command line arguments */ public static void main(String[] args) { new Server(9010).run(); } }
package packModelo; import java.util.Scanner; public class Jugador extends Usuario { private String nombre; private static Jugador miJugador; private Jugador() { super(); nombre = pedirNombre(); } public static Jugador getJugador() { if (miJugador==null){ miJugador=new Jugador(); } return miJugador; } private String pedirNombre() { String nombre; Scanner sc= new Scanner(System.in); System.out.println("Introduce tu nombre de usuario"); nombre = sc.nextLine(); return nombre; } }
package com.github.nsnjson; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import org.junit.*; import static com.github.nsnjson.format.Format.*; public class DriverTest extends AbstractFormatTest { @Test public void processTestNull() { shouldBeConsistencyWhenGivenNull(getNull(), getNullPresentation()); } @Test public void processTestNumberInt() { NumericNode value = getNumberInt(); shouldBeConsistencyWhenGivenNumber(value, getNumberIntPresentation(value)); } @Test public void processTestNumberLong() { NumericNode value = getNumberLong(); shouldBeConsistencyWhenGivenNumber(value, getNumberLongPresentation(value)); } @Test public void processTestNumberDouble() { NumericNode value = getNumberDouble(); shouldBeConsistencyWhenGivenNumber(value, getNumberDoublePresentation(value)); } @Test public void processTestEmptyString() { TextNode value = getEmptyString(); shouldBeConsistencyWhenGivenString(value, getStringPresentation(value)); } @Test public void processTestString() { TextNode value = getString(); shouldBeConsistencyWhenGivenString(value, getStringPresentation(value)); } @Test public void processTestBooleanTrue() { BooleanNode value = getBooleanTrue(); shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value)); } @Test public void processTestBooleanFalse() { BooleanNode value = getBooleanFalse(); shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value)); } @Test public void processTestEmptyArray() { shouldBeConsistencyWhenGivenArray(getEmptyArray(), getEmptyArrayPresentation()); } @Test public void processTestArray() { ObjectMapper objectMapper = new ObjectMapper(); JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ArrayNode array = objectMapper.createArrayNode(); array.add(getNull()); array.add(numberInt); array.add(numberLong); array.add(numberDouble); array.add(string); array.add(booleanTrue); array.add(booleanFalse); ObjectNode presentationOfNull = objectMapper.createObjectNode(); presentationOfNull.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberInt = objectMapper.createObjectNode(); presentationOfNumberInt.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberInt.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLong = objectMapper.createObjectNode(); presentationOfNumberLong.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLong.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDouble = objectMapper.createObjectNode(); presentationOfNumberDouble.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDouble.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfString = objectMapper.createObjectNode(); presentationOfString.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfString.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrue = objectMapper.createObjectNode(); presentationOfBooleanTrue.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrue.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalse = objectMapper.createObjectNode(); presentationOfBooleanFalse.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalse.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNull); presentationOfArrayItems.add(presentationOfNumberInt); presentationOfArrayItems.add(presentationOfNumberLong); presentationOfArrayItems.add(presentationOfNumberDouble); presentationOfArrayItems.add(presentationOfString); presentationOfArrayItems.add(presentationOfBooleanTrue); presentationOfArrayItems.add(presentationOfBooleanFalse); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_ARRAY); presentation.set(FIELD_VALUE, presentationOfArrayItems); shouldBeConsistencyWhenGivenArray(array, presentation); } @Test public void processTestEmptyObject() { shouldBeConsistencyWhenGivenObject(getEmptyObject(), getEmptyObjectPresentation()); } @Test public void processObject() { ObjectMapper objectMapper = new ObjectMapper(); String nullField = "null_field"; String numberIntField = "int_field"; String numberLongField = "long_field"; String numberDoubleField = "double_field"; String stringField = "string_field"; String booleanTrueField = "true_field"; String booleanFalseField = "false_field"; JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ObjectNode object = objectMapper.createObjectNode(); object.set(nullField, getNull()); object.set(numberIntField, numberInt); object.set(numberLongField, numberLong); object.set(numberDoubleField, numberDouble); object.set(stringField, string); object.set(booleanTrueField, booleanTrue); object.set(booleanFalseField, booleanFalse); ObjectNode presentationOfNullField = objectMapper.createObjectNode(); presentationOfNullField.put(FIELD_NAME, nullField); presentationOfNullField.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberIntField = objectMapper.createObjectNode(); presentationOfNumberIntField.put(FIELD_NAME, numberIntField); presentationOfNumberIntField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberIntField.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLongField = objectMapper.createObjectNode(); presentationOfNumberLongField.put(FIELD_NAME, numberLongField); presentationOfNumberLongField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLongField.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDoubleField = objectMapper.createObjectNode(); presentationOfNumberDoubleField.put(FIELD_NAME, numberDoubleField); presentationOfNumberDoubleField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDoubleField.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfStringField = objectMapper.createObjectNode(); presentationOfStringField.put(FIELD_NAME, stringField); presentationOfStringField.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfStringField.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrueField = objectMapper.createObjectNode(); presentationOfBooleanTrueField.put(FIELD_NAME, booleanTrueField); presentationOfBooleanTrueField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrueField.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalseField = objectMapper.createObjectNode(); presentationOfBooleanFalseField.put(FIELD_NAME, booleanFalseField); presentationOfBooleanFalseField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalseField.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNullField); presentationOfArrayItems.add(presentationOfNumberIntField); presentationOfArrayItems.add(presentationOfNumberLongField); presentationOfArrayItems.add(presentationOfNumberDoubleField); presentationOfArrayItems.add(presentationOfStringField); presentationOfArrayItems.add(presentationOfBooleanTrueField); presentationOfArrayItems.add(presentationOfBooleanFalseField); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_OBJECT); presentation.set(FIELD_VALUE, presentationOfArrayItems); shouldBeConsistencyWhenGivenObject(object, presentation); } private void shouldBeConsistencyWhenGivenNull(NullNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenNumber(NumericNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenString(TextNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenBoolean(BooleanNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenArray(ArrayNode array, ObjectNode presentation) { assertConsistency(array, presentation); } private void shouldBeConsistencyWhenGivenObject(ObjectNode object, ObjectNode presentation) { assertConsistency(object, presentation); } private static void assertConsistency(JsonNode value, ObjectNode presentation) { Assert.assertEquals(value, Driver.decode(Driver.encode(value))); Assert.assertEquals(presentation, Driver.encode(Driver.decode(presentation))); } }
package structure.impl; import monitoring.impl.configs.NonDetConfig; /** * This class represents a simple Quantified Event Automaton (QEA) with the * following characteristics: * <ul> * <li>There is at most one quantified variable * <li>The transitions in the function delta consist of a start state, an event * and a set of end states, no guards or assigns are considered * <li>The QEA can is non-deterministic * </ul> * * @author Helena Cuenca * @author Giles Reger */ public class SimpleNonDetQEA extends SimpleQEA { private int[][][] delta; public SimpleNonDetQEA(int numStates, int numEvents, int initialState, Quantification quantification) { super(numStates, initialState, quantification); delta = new int[numStates + 1][numEvents + 1][]; } /** * Adds a transition to the transition function delta of this QEA * * @param startState * Start state for the transition * @param event * Name of the event * @param endState * End state for the transition */ public void addTransition(int startState, int event, int endState) { if (delta[startState][event] == null) { delta[startState][event] = new int[] { endState }; } else { // Resize end states array int[] newEndStates = new int[delta[startState][event].length + 1]; System.arraycopy(delta[startState][event], 0, newEndStates, 0, delta[startState][event].length); newEndStates[delta[startState][event].length] = endState; delta[startState][event] = newEndStates; } } /** * Adds a set of transitions to the transition function delta of this QEA * * @param startState * Start state for the transition * @param event * Name of the event * @param endStates * Array of end states for the transition */ public void addTransitions(int startState, int event, int[] endStates) { // TODO Most methods addTransition(s) contain the same logic if (delta[startState][event] == null) { delta[startState][event] = endStates; } else { // Resize transitions array int prevTransCount = delta[startState][event].length; int[] newEndStates = new int[prevTransCount + endStates.length]; System.arraycopy(delta[startState][event], 0, newEndStates, 0, delta[startState][event].length); System.arraycopy(endStates, 0, newEndStates, prevTransCount, endStates.length); delta[startState][event] = newEndStates; } } /** * Retrieves the final configuration for a given start configuration and an * event, according to the transition function delta of this QEA * * @param config * Start configuration containing the set of start states * @param event * Name of the event * @return End configuration containing the set of end states */ public NonDetConfig getNextConfig(NonDetConfig config, int event) { if (config.getStates().length == 1) { // Only one state in the start // configuration config.setStates(delta[config.getStates()[0]][event]); } else { // More than one state in the start configuration // Get a reference to the start states int[] startStates = config.getStates(); // Create a boolean array of size equal to the number of states boolean[] endStatesBool = new boolean[delta.length]; // Initialise end states count int endStatesCount = 0; // Iterate over the multiple arrays of end states for (int i = 0; i < startStates.length; i++) { int[] intermEndStates = delta[startStates[i]][event]; if (intermEndStates != null) { // Iterate over the intermediate arrays of end states for (int j = 0; j < intermEndStates.length; j++) { int newEndState = intermEndStates[j]; if (!endStatesBool[newEndState]) { endStatesBool[newEndState] = true; endStatesCount++; } } } } // System.out.println("endStatesBool: "+java.util.Arrays.toString(endStatesBool)); // Remove state 0 if there are other end states // Because state 0 is the failure state, and can be safely removed if (endStatesBool[0] && endStatesCount > 1) { endStatesBool[0] = false; endStatesCount } int[] endStates; // Check if the number of end states is the same as start states if (endStatesCount == startStates.length) { // Same size // Use the same array endStates = startStates; } else { // Different number of start states and end states // Create a new array with the right size endStates = new int[endStatesCount]; } // Populate array of end states int j = 0; for (int i = 0; i < endStatesBool.length; i++) { if (endStatesBool[i]) { endStates[j] = i; j++; } } config.setStates(endStates); } return config; } /** * Determines if the set of states in the specified configuration contains * at least one final state * * @param config * Configuration encapsulating the set of states to be checked * @return <code>true</code> if the set of states in the specified * configuration contains at least one final state; * <code>false</code> otherwise */ public boolean containsFinalState(NonDetConfig config) { for (int i = 0; i < config.getStates().length; i++) { if (isStateFinal(config.getStates()[i])) { return true; } } return false; } @Override public int[] getEventsAlphabet() { int[] a = new int[delta[0].length - 1]; for (int i = 0; i < a.length; i++) { a[i] = i + 1; } return a; } @Override public boolean isDeterministic() { return false; } }
package com.grossbart.jslim; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.Test; import static org.junit.Assert.*; public class JSlimTest { @Test public void basicCompileTest() throws IOException { InputStream in = getClass().getClassLoader().getResourceAsStream("basic.js"); try { String basic = IOUtils.toString(in, "UTF-8"); JSlim slim = new JSlim(); slim.addLib(basic); String funcs[] = slim.getKeptFunctions(); assertEquals(funcs.length, 1); assertEquals(funcs[0], "func1"); } finally { if (in != null) { in.close(); } } } }
package hudson.plugins.git; import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import hudson.EnvVars; import hudson.FilePath; import hudson.Functions; import hudson.Launcher; import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.model.*; import hudson.plugins.git.GitSCM.BuildChooserContextImpl; import hudson.plugins.git.GitSCM.DescriptorImpl; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.browser.GithubWeb; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.impl.*; import hudson.plugins.git.util.BuildChooser; import hudson.plugins.git.util.BuildChooserContext; import hudson.plugins.git.util.BuildChooserContext.ContextCallable; import hudson.plugins.git.util.BuildData; import hudson.plugins.git.util.GitUtils; import hudson.plugins.parameterizedtrigger.BuildTrigger; import hudson.plugins.parameterizedtrigger.ResultCondition; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogSet; import hudson.scm.PollingResult; import hudson.scm.PollingResult.Change; import hudson.scm.SCMRevisionState; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.Permission; import hudson.slaves.DumbSlave; import hudson.slaves.EnvironmentVariablesNodeProperty.Entry; import hudson.tools.ToolLocationNodeProperty; import hudson.tools.ToolProperty; import hudson.triggers.SCMTrigger; import hudson.util.LogTaskListener; import hudson.util.ReflectionUtils; import hudson.util.RingBufferLogHandler; import hudson.util.StreamTaskListener; import jenkins.security.MasterToSlaveCallable; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.jenkinsci.plugins.tokenmacro.TokenMacro; import org.jenkinsci.plugins.gitclient.*; import org.junit.Assume; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.TestExtension; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.text.MessageFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.eclipse.jgit.transport.RemoteConfig; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import jenkins.model.Jenkins; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitSampleRepoRule; /** * Tests for {@link GitSCM}. * @author ishaaq */ public class GitSCMTest extends AbstractGitTestCase { @Rule public GitSampleRepoRule secondRepo = new GitSampleRepoRule(); private CredentialsStore store = null; @BeforeClass public static void setGitDefaults() throws Exception { CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); } @Before public void enableSystemCredentialsProvider() throws Exception { SystemCredentialsProvider.getInstance().setDomainCredentialsMap( Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) { if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) { store = s; break; } } assertThat("The system credentials provider is enabled", store, notNullValue()); } @After public void waitForJenkinsIdle() throws Exception { if (cleanupIsUnreliable()) { rule.waitUntilNoActivityUpTo(5001); } } private StandardCredentials getInvalidCredential() { String username = "bad-user"; String password = "bad-password"; CredentialsScope scope = CredentialsScope.GLOBAL; String id = "username-" + username + "-password-" + password; return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, username, password); } @Test public void manageShouldAccessGlobalConfig() { final String USER = "user"; final String MANAGER = "manager"; Permission jenkinsManage; try { jenkinsManage = getJenkinsManage(); } catch (Exception e) { Assume.assumeTrue("Jenkins baseline is too old for this test (requires Jenkins.MANAGE)", false); return; } rule.jenkins.setSecurityRealm(rule.createDummySecurityRealm()); rule.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() // Read access .grant(Jenkins.READ).everywhere().to(USER) // Read and Manage .grant(Jenkins.READ).everywhere().to(MANAGER) .grant(jenkinsManage).everywhere().to(MANAGER) ); try (ACLContext c = ACL.as(User.getById(USER, true))) { Collection<Descriptor> descriptors = Functions.getSortedDescriptorsForGlobalConfigUnclassified(); assertThat("Global configuration should not be accessible to READ users", descriptors, is(empty())); } try (ACLContext c = ACL.as(User.getById(MANAGER, true))) { Collection<Descriptor> descriptors = Functions.getSortedDescriptorsForGlobalConfigUnclassified(); Optional<Descriptor> found = descriptors.stream().filter(descriptor -> descriptor instanceof GitSCM.DescriptorImpl).findFirst(); assertTrue("Global configuration should be accessible to MANAGE users", found.isPresent()); } } // TODO: remove when Jenkins core baseline is 2.222+ private Permission getJenkinsManage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // Jenkins.MANAGE is available starting from Jenkins 2.222 (https://jenkins.io/changelog/#v2.222). See JEP-223 for more info return (Permission) ReflectionUtils.getPublicProperty(Jenkins.get(), "MANAGE"); } @Test public void trackCredentials() throws Exception { StandardCredentials credential = getInvalidCredential(); store.addCredentials(Domain.global(), credential); Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should not be set before job definition", fingerprint, nullValue()); JenkinsRule.WebClient wc = rule.createWebClient(); HtmlPage page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId()); assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue()); FreeStyleProject project = setupProject("master", credential); fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should not be set before first build", fingerprint, nullValue()); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should be set after first build", fingerprint, notNullValue()); assertThat(fingerprint.getJobs(), hasItem(is(project.getFullName()))); Fingerprint.RangeSet rangeSet = fingerprint.getRangeSet(project); assertThat(rangeSet, notNullValue()); assertThat(rangeSet.includes(project.getLastBuild().getNumber()), is(true)); page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId()); assertThat(page.getElementById("usage-missing"), nullValue()); assertThat(page.getElementById("usage-present"), notNullValue()); assertThat(page.getAnchorByText(project.getFullDisplayName()), notNullValue()); } /** * Basic test - create a GitSCM based project, check it out and build for the first time. * Next test that polling works correctly, make another commit, check that polling finds it, * then build it and finally test the build culprits as well as the contents of the workspace. * @throws Exception on error */ @Test public void testBasic() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test @Issue("JENKINS-56176") public void testBasicRemotePoll() throws Exception { // FreeStyleProject project = setupProject("master", true, false); FreeStyleProject project = setupProject("master", false, null, null, null, true, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; String sha1String = commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // JENKINS-56176 token macro expansion broke when BuildData was no longer updated assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION,length=7}"), is(sha1String.substring(0, 7))); assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION}"), is(sha1String)); assertThat(TokenMacro.expandAll(build2, listener, "$GIT_REVISION"), is(sha1String)); } @Test public void testBranchSpecWithRemotesMaster() throws Exception { FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } /** * This test and testSpecificRefspecsWithoutCloneOption confirm behaviors of * refspecs on initial clone. Without the CloneOption to honor refspec, all * references are cloned, even if they will be later ignored due to the * refspec. With the CloneOption to ignore refspec, the initial clone also * honors the refspec and only retrieves references per the refspec. * @throws Exception on error */ @Test @Issue("JENKINS-31393") public void testSpecificRefspecs() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); /* Set CloneOption to honor refspec on initial clone */ FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setHonorRefspec(true); ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); /* Set CloneOption to honor refspec on initial clone */ FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); CloneOption cloneOptionFoo = new CloneOption(false, null, null); cloneOptionFoo.setHonorRefspec(true); ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionFoo); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // create branch and make initial commit git.checkout().ref("master").branch("foo").execute(); commit(commitFile1, johnDoe, "Commit in foo"); build(projectWithMaster, Result.FAILURE); build(projectWithFoo, Result.SUCCESS, commitFile1); } /** * This test confirms the behaviour of avoiding the second fetch in GitSCM checkout() **/ @Test @Issue("JENKINS-56404") public void testAvoidRedundantFetch() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); /* Without honor refspec on initial clone */ /* Randomly enable shallow clone, should not alter test assertions */ /** * After avoiding the second fetch call in retrieveChanges(), this test verifies there is no data loss by fetching a repository * (git init + git fetch) with a narrow refspec but without CloneOption of honorRefspec = true on initial clone * First fetch -> wide refspec * Second fetch -> narrow refspec (avoided) **/ @Test @Issue("JENKINS-56404") public void testAvoidRedundantFetchWithoutHonorRefSpec() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); /* Without honor refspec on initial clone */ FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); if (random.nextBoolean()) { /* Randomly enable shallow clone, should not alter test assertions */ CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setDepth(1); ((GitSCM) projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); } // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // Add another branch 'foo' git.branch("foo"); git.checkout().branch("foo"); commit(commitFile1, johnDoe, "Commit in foo"); // Build will be success because the initial clone disregards refspec and fetches all branches FreeStyleBuild build = build(projectWithMaster, Result.SUCCESS); FilePath childFile = returnFile(build); if (childFile != null) { // assert that no data is lost by avoidance of second fetch assertThat("master branch was not fetched", childFile.readToString(), containsString("master")); assertThat("foo branch was not fetched", childFile.readToString(), containsString("foo")); } /** * After avoiding the second fetch call in retrieveChanges(), this test verifies there is no data loss by fetching a * repository(git init + git fetch) with a narrow refspec with CloneOption of honorRefspec = true on initial clone * First fetch -> narrow refspec (since refspec is honored on initial clone) * Second fetch -> narrow refspec (avoided) **/ @Test @Issue("JENKINS-56404") public void testAvoidRedundantFetchWithHonorRefSpec() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); String refSpec = "+refs/heads/foo:refs/remotes/foo"; repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", refSpec, null)); /* With honor refspec on initial clone */ FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setHonorRefspec(true); ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // Add another branch 'foo' git.branch("foo"); git.checkout().branch("foo"); commit(commitFile1, johnDoe, "Commit in foo"); // Build will be failure because the initial clone regards refspec and fetches branch 'foo' only. FreeStyleBuild build = build(projectWithMaster, Result.FAILURE); FilePath childFile = returnFile(build); assertNotNull(childFile); // assert that no data is lost by avoidance of second fetch assertThat(childFile.readToString(), not(containsString("master"))); assertThat("foo branch was not fetched", childFile.readToString(), containsString("foo")); assertRedundantFetchIsSkipped(build, refSpec); assertThat(build.getResult(), is(Result.FAILURE)); } @Test @Issue("JENKINS-49757") public void testAvoidRedundantFetchWithNullRefspec() throws Exception { String nullRefspec = null; List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", nullRefspec, null)); /* Without honor refspec on initial clone */ FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); if (random.nextBoolean()) { /* Randomly enable shallow clone, should not alter test assertions */ CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setDepth(1); ((GitSCM) projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); } // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); FreeStyleBuild build = build(projectWithMaster, Result.SUCCESS); /* * When initial clone does not honor the refspec and a custom refspec is used * that is not part of the default refspec, then the second fetch is not * redundant and must not be fetched. * * This example uses the format to reference GitHub pull request 553. Other * formats would apply as well, but the case is illustrated well enough by * using the GitHub pull request as an example of this type of problem. */ @Test @Issue("JENKINS-49757") public void testRetainRedundantFetch() throws Exception { /* Without honor refspec on initial clone */ /* Randomly enable shallow clone, should not alter test assertions */ /* Create a ref for the fake pull in the source repository */ /** * This test and testSpecificRefspecs confirm behaviors of * refspecs on initial clone. Without the CloneOption to honor refspec, all * references are cloned, even if they will be later ignored due to the * refspec. With the CloneOption to ignore refspec, the initial clone also * honors the refspec and only retrieves references per the refspec. * @throws Exception on error */ @Test @Issue("JENKINS-36507") public void testSpecificRefspecsWithoutCloneOption() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // create branch and make initial commit git.branch("foo"); git.checkout().branch("foo"); commit(commitFile1, johnDoe, "Commit in foo"); build(projectWithMaster, Result.SUCCESS); /* If clone refspec had been honored, this would fail */ build(projectWithFoo, Result.SUCCESS, commitFile1); } /** * An empty remote repo URL failed the job as expected but provided * a poor diagnostic message. The fix for JENKINS-38608 improves * the error message to be clear and helpful. This test checks for * that error message. * @throws Exception on error */ @Test @Issue("JENKINS-38608") public void testAddFirstRepositoryWithNullRepoURL() throws Exception{ List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(null, null, null, null)); FreeStyleProject project = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); FreeStyleBuild build = build(project, Result.FAILURE); // Before JENKINS-38608 fix assertThat("Build log reports 'Null value not allowed'", build.getLog(175), not(hasItem("Null value not allowed as an environment variable: GIT_URL"))); // After JENKINS-38608 fix assertThat("Build log did not report empty string in job definition", build.getLog(175), hasItem("FATAL: Git repository URL 1 is an empty string in job definition. Checkout requires a valid repository URL")); } /** * An empty remote repo URL failed the job as expected but provided * a poor diagnostic message. The fix for JENKINS-38608 improves * the error message to be clear and helpful. This test checks for * that error message when the second URL is empty. * @throws Exception on error */ @Test @Issue("JENKINS-38608") public void testAddSecondRepositoryWithNullRepoURL() throws Exception{ String repoURL = "https://example.com/non-empty/repo/url"; List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(repoURL, null, null, null)); repos.add(new UserRemoteConfig(null, null, null, null)); FreeStyleProject project = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); FreeStyleBuild build = build(project, Result.FAILURE); // Before JENKINS-38608 fix assertThat("Build log reports 'Null value not allowed'", build.getLog(175), not(hasItem("Null value not allowed as an environment variable: GIT_URL_2"))); // After JENKINS-38608 fix assertThat("Build log did not report empty string in job definition for URL 2", build.getLog(175), hasItem("FATAL: Git repository URL 2 is an empty string in job definition. Checkout requires a valid repository URL")); } @Test public void testBranchSpecWithRemotesHierarchical() throws Exception { FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null); FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // create hierarchical branch, delete master branch, and build git.branch("rel-1/xy"); git.checkout("rel-1/xy"); git.deleteBranch("master"); build(projectMasterBranch, Result.FAILURE); build(projectHierarchicalBranch, Result.SUCCESS, commitFile1); } @Test public void testBranchSpecUsingTagWithSlash() throws Exception { FreeStyleProject projectMasterBranch = setupProject("path/tag", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1 will be tagged with path/tag"); testRepo.git.tag("path/tag", "tag with a slash in the tag name"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } @Test public void testBasicIncludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } /** * testMergeCommitInExcludedRegionIsIgnored() confirms behavior of excluded regions with merge commits. * This test has excluded and included regions, for files ending with .excluded and .included, * respectively. The git repository is set up so that a non-fast-forward merge commit comes * to master. The newly merged commit is a file ending with .excluded, so it should be ignored. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitInExcludedRegionIsIgnored() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, ".*\\.included"); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "fileToMerge.excluded"; commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // Should return false, because our merge commit falls within the excluded region. assertFalse("Polling should report no changes, because they are in the excluded region.", project.poll(listener).hasChanges()); } /** * testMergeCommitInExcludedDirectoryIsIgnored() confirms behavior of excluded directories with merge commits. * This test has excluded and included directories, named /excluded/ and /included/,respectively. The repository * is set up so that a non-fast-forward merge commit comes to master, and is in the directory /excluded/, * so it should be ignored. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, "included/.*"); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "excluded/should-be-ignored"; commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // Should return false, because our merge commit falls within the excluded directory. assertFalse("Polling should see no changes, because they are in the excluded directory.", project.poll(listener).hasChanges()); } /** * testMergeCommitInIncludedRegionIsProcessed() confirms behavior of included regions with merge commits. * This test has excluded and included regions, for files ending with .excluded and .included, respectively. * The git repository is set up so that a non-fast-forward merge commit comes to master. The newly merged * commit is a file ending with .included, so it should be processed as a new change. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, ".*\\.included"); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "fileToMerge.included"; commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // Should return true, because our commit falls within the included region. assertTrue("Polling should report changes, because they fall within the included region.", project.poll(listener).hasChanges()); } /** * testMergeCommitInIncludedRegionIsProcessed() confirms behavior of included directories with merge commits. * This test has excluded and included directories, named /excluded/ and /included/, respectively. The repository * is set up so that a non-fast-forward merge commit comes to master, and is in the directory /included/, * so it should be processed as a new change. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, "included/.*"); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "included/should-be-processed"; commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // When this test passes, project.poll(listener).hasChanges()) should return // true, because our commit falls within the included region. assertTrue("Polling should report changes, because they are in the included directory.", project.poll(listener).hasChanges()); } /** * testMergeCommitOutsideIncludedRegionIsIgnored() confirms behavior of included regions with merge commits. * This test has an included region defined, for files ending with .included. There is no excluded region * defined. The repository is set up and a non-fast-forward merge commit comes to master. The newly merged commit * is a file ending with .should-be-ignored, thus falling outside of the included region, so it should ignored. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, null, null, ".*\\.included"); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "fileToMerge.should-be-ignored"; commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // Should return false, because our commit falls outside the included region. assertFalse("Polling should ignore the change, because it falls outside the included region.", project.poll(listener).hasChanges()); } /** * testMergeCommitOutsideIncludedDirectoryIsIgnored() confirms behavior of included directories with merge commits. * This test has only an included directory `/included` defined. The git repository is set up so that * a non-fast-forward, but mergeable, commit comes to master. The newly merged commit is outside of the * /included/ directory, so polling should report no changes. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, null, null, "included/.*"); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "directory-to-ignore/file-should-be-ignored"; commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // Should return false, because our commit falls outside of the included directory assertFalse("Polling should ignore the change, because it falls outside the included directory.", project.poll(listener).hasChanges()); } /** * testMergeCommitOutsideExcludedRegionIsProcessed() confirms behavior of excluded regions with merge commits. * This test has an excluded region defined, for files ending with .excluded. There is no included region defined. * The repository is set up so a non-fast-forward merge commit comes to master. The newly merged commit is a file * ending with .should-be-processed, thus falling outside of the excluded region, so it should processed * as a new change. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, null); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "fileToMerge.should-be-processed"; commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // Should return true, because our commit falls outside of the excluded region assertTrue("Polling should process the change, because it falls outside the excluded region.", project.poll(listener).hasChanges()); } /** * testMergeCommitOutsideExcludedDirectoryIsProcessed() confirms behavior of excluded directories with merge commits. * This test has an excluded directory `excluded` defined. There is no `included` directory defined. The repository * is set up so that a non-fast-forward merge commit comes to master. The newly merged commit resides in a * directory of its own, thus falling outside of the excluded directory, so it should processed * as a new change. * * @throws Exception on error */ @Issue({"JENKINS-20389","JENKINS-23606"}) @Test public void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exception { final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, null); final String initialCommit = "initialCommit"; commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master"); build(project, Result.SUCCESS, initialCommit); final String secondCommit = "secondCommit"; commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master"); testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); // Create this new file outside of our excluded directory final String fileToMerge = "directory-to-include/file-should-be-processed"; commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); MergeCommand mergeCommand = testRepo.git.merge(); mergeCommand.setRevisionToMerge(branchSHA); mergeCommand.execute(); // Should return true, because our commit falls outside of the excluded directory assertTrue("SCM polling should process the change, because it falls outside the excluded directory.", project.poll(listener).hasChanges()); } @Test public void testIncludedRegionWithDeeperCommits() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicExcludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, ".*2", null, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } private int findLogLineStartsWith(List<String> buildLog, String initialString) { int logLine = 0; for (String logString : buildLog) { if (logString.startsWith(initialString)) { return logLine; } logLine++; } return -1; } @Test public void testCleanBeforeCheckout() throws Exception { FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); ((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout()); /* First build should not clean, since initial clone is always clean */ final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(p, Result.SUCCESS, commitFile1); assertThat(firstBuild.getLog(50), not(hasItem("Cleaning workspace"))); /* Second build should clean, since first build might have modified the workspace */ final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); final FreeStyleBuild secondBuild = build(p, Result.SUCCESS, commitFile2); List<String> secondLog = secondBuild.getLog(50); assertThat(secondLog, hasItem("Cleaning workspace")); int cleaningLogLine = findLogLineStartsWith(secondLog, "Cleaning workspace"); int fetchingLogLine = findLogLineStartsWith(secondLog, "Fetching upstream changes from "); assertThat("Cleaning should happen before fetch", cleaningLogLine, is(lessThan(fetchingLogLine))); } @Issue("JENKINS-8342") @Test public void testExcludedRegionMultiCommit() throws Exception { // Got 2 projects, each one should only build if changes in its own file FreeStyleProject clientProject = setupProject("master", false, null, ".*serverFile", null, null); FreeStyleProject serverProject = setupProject("master", false, null, ".*clientFile", null, null); String initialCommitFile = "initialFile"; commit(initialCommitFile, johnDoe, "initial commit"); build(clientProject, Result.SUCCESS, initialCommitFile); build(serverProject, Result.SUCCESS, initialCommitFile); assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges()); assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges()); // Got commits on serverFile, so only server project should build. commit("myserverFile", johnDoe, "commit first server file"); assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); // Got commits on both client and serverFile, so both projects should build. commit("myNewserverFile", johnDoe, "commit new server file"); commit("myclientFile", johnDoe, "commit first clientfile"); assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); } /* * With multiple branches specified in the project and having commits from a user * excluded should not build the excluded revisions when another branch changes. */ /* @Issue("JENKINS-8342") @Test public void testMultipleBranchWithExcludedUser() throws Exception { final String branch1 = "Branch1"; final String branch2 = "Branch2"; List<BranchSpec> branches = new ArrayList<BranchSpec>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec(branch1)); branches.add(new BranchSpec(branch2)); final FreeStyleProject project = setupProject(branches, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // create branches here so we can get back to them later... git.branch(branch1); git.branch(branch2); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // Add excluded commit final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertFalse("scm polling detected change in 'master', which should have been excluded", project.poll(listener).hasChanges()); // now jump back... git.checkout(branch1); final String branch1File1 = "branch1File1"; commit(branch1File1, janeDoe, "Branch1 commit number 1"); assertFalse("scm polling detected change in 'Branch1', which should have been excluded", project.poll(listener).hasChanges()); // and the other branch... git.checkout(branch2); final String branch2File1 = "branch2File1"; commit(branch2File1, janeDoe, "Branch2 commit number 1"); assertFalse("scm polling detected change in 'Branch2', which should have been excluded", project.poll(listener).hasChanges()); final String branch2File2 = "branch2File2"; commit(branch2File2, johnDoe, "Branch2 commit number 2"); assertTrue("scm polling should detect changes in 'Branch2' branch", project.poll(listener).hasChanges()); //... and build it... build(project, Result.SUCCESS, branch2File1, branch2File2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // now jump back again... git.checkout(branch1); // Commit excluded after non-excluded commit, should trigger build. final String branch1File2 = "branch1File2"; commit(branch1File2, johnDoe, "Branch1 commit number 2"); final String branch1File3 = "branch1File3"; commit(branch1File3, janeDoe, "Branch1 commit number 3"); assertTrue("scm polling should detect changes in 'Branch1' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, branch1File1, branch1File2, branch1File3); } */ @Test public void testBasicExcludedUser() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, "Jane Doe", null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicInSubdir() throws Exception { FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir")); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, "subdir", Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertEquals("The workspace should have a 'subdir' subdirectory, but does not.", true, build2.getWorkspace().child("subdir").exists()); assertEquals("The 'subdir' subdirectory should contain commitFile2, but does not.", true, build2.getWorkspace().child("subdir").child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicWithAgent() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("HUDSON-7547") @Test public void testBasicWithAgentNoExecutorsOnMaster() throws Exception { FreeStyleProject project = setupSimpleProject("master"); rule.jenkins.setNumExecutors(0); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testAuthorOrCommitterFalse() throws Exception { // Test with authorOrCommitter set to false and make sure we get the committer. FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the committer as the change author with authorOrCommitter==false", janeDoe.getName(), secondCulprits.iterator().next().getFullName()); } @Test public void testAuthorOrCommitterTrue() throws Exception { // Next, test with authorOrCommitter set to true and make sure we get the author. FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the author as the change author with authorOrCommitter==true", johnDoe.getName(), secondCulprits.iterator().next().getFullName()); } @Test public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); //now create and checkout a new branch: git.checkout(Constants.HEAD, "untracked"); //.. and commit to it: final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges()); } private String checkoutString(FreeStyleProject project, String envVar) { return "checkout -f " + getEnvVars(project).get(envVar); } @Test public void testEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); rule.waitForMessage(getEnvVars(project).get(GitSCM.GIT_BRANCH), build1); rule.waitForMessage(checkoutString(project, GitSCM.GIT_COMMIT), build1); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build2); rule.waitForMessage(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build1); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build2); rule.waitForMessage(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build1); } @Issue("HUDSON-7411") @Test public void testNodeEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); DumbSlave agent = rule.createSlave(); setVariables(agent, new Entry("TESTKEY", "agent value")); project.setAssignedLabel(agent.getSelfLabel()); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertEquals("agent value", getEnvVars(project).get("TESTKEY")); } @Test public void testNodeOverrideGit() throws Exception { GitSCM scm = new GitSCM(null); DumbSlave agent = rule.createSlave(); GitTool.DescriptorImpl gitToolDescriptor = rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class); GitTool installation = new GitTool("Default", "/usr/bin/git", null); gitToolDescriptor.setInstallations(installation); String gitExe = scm.getGitExe(agent, TaskListener.NULL); assertEquals("/usr/bin/git", gitExe); ToolLocationNodeProperty nodeGitLocation = new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(gitToolDescriptor, "Default", "C:\\Program Files\\Git\\bin\\git.exe")); agent.setNodeProperties(Collections.singletonList(nodeGitLocation)); gitExe = scm.getGitExe(agent, TaskListener.NULL); assertEquals("C:\\Program Files\\Git\\bin\\git.exe", gitExe); } /* * A previous version of GitSCM would only build against branches, not tags. This test checks that that * regression has been fixed. */ @Test public void testGitSCMCanBuildAgainstTags() throws Exception { final String mytag = "mytag"; FreeStyleProject project = setupSimpleProject(mytag); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // Try again. The first build will leave the repository in a bad state because we // cloned something without even a HEAD - which will mean it will want to re-clone once there is some // actual data. build(project, Result.FAILURE); // fail, because there's nothing to be checked out here //now create and checkout a new branch: final String tmpBranch = "tmp"; git.branch(tmpBranch); git.checkout(tmpBranch); // commit to it final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here // tag it, then delete the tmp branch git.tag(mytag, "mytag initial"); git.checkout("master"); git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, tag "mytag" exists but is // not part of "master" assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now, create tmp branch again against mytag: git.checkout(mytag); git.branch(tmpBranch); // another commit: final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); // now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up: git.tag(mytag, "mytag moved"); git.checkout("master"); git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit: assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile3); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } /* * Not specifying a branch string in the project implies that we should be polling for changes in * all branches. */ @Test public void testMultipleBranchBuild() throws Exception { // empty string will result in a project that tracks against changes in all branches: final FreeStyleProject project = setupSimpleProject(""); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); // create a branch here so we can get back to this point later... final String fork = "fork"; git.branch(fork); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now jump back... git.checkout(fork); // add some commits to the fork branch... final String forkFile1 = "forkFile1"; commit(forkFile1, johnDoe, "Fork commit number 1"); final String forkFile2 = "forkFile2"; commit(forkFile2, johnDoe, "Fork commit number 2"); assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, forkFile1, forkFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } @Test public void testMultipleBranchesWithTags() throws Exception { List<BranchSpec> branchSpecs = Arrays.asList( new BranchSpec("refs/tags/v*"), new BranchSpec("refs/remotes/origin/non-existent")); FreeStyleProject project = setupProject(branchSpecs, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: // Here the changelog is by default empty (because changelog for first commit is always empty commit("commitFileBase", johnDoe, "Initial Commit"); // there are no branches to be build FreeStyleBuild freeStyleBuild = build(project, Result.FAILURE); final String v1 = "v1"; git.tag(v1, "version 1"); assertTrue("v1 tag exists", git.tagExists(v1)); freeStyleBuild = build(project, Result.SUCCESS); assertTrue("change set is empty", freeStyleBuild.getChangeSet().isEmptySet()); commit("file1", johnDoe, "change to file1"); git.tag("none", "latest"); freeStyleBuild = build(project, Result.SUCCESS); ObjectId tag = git.revParse(Constants.R_TAGS + v1); GitSCM scm = (GitSCM)project.getScm(); BuildData buildData = scm.getBuildData(freeStyleBuild); assertEquals("last build matches the v1 tag revision", tag, buildData.lastBuild.getSHA1()); } @Issue("JENKINS-19037") @SuppressWarnings("ResultOfObjectAllocationIgnored") @Test public void testBlankRepositoryName() throws Exception { new GitSCM(null); } @Issue("JENKINS-10060") @Test public void testSubmoduleFixup() throws Exception { File repo = secondRepo.getRoot(); FilePath moduleWs = new FilePath(repo); org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient(); {// first we create a Git repository with submodule moduleRepo.init(); moduleWs.child("a").touch(0); moduleRepo.add("a"); moduleRepo.commit("creating a module"); git.addSubmodule(repo.getAbsolutePath(), "module1"); git.commit("creating a super project"); } // configure two uproject 'u' -> 'd' that's chained together. FreeStyleProject u = createFreeStyleProject(); FreeStyleProject d = createFreeStyleProject(); u.setScm(new GitSCM(workDir.getPath())); u.getPublishersList().add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig(d.getName(), ResultCondition.SUCCESS, new GitRevisionBuildParameters()))); d.setScm(new GitSCM(workDir.getPath())); rule.jenkins.rebuildDependencyGraph(); FreeStyleBuild ub = rule.assertBuildStatusSuccess(u.scheduleBuild2(0)); for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop Thread.sleep(100); FreeStyleBuild db = d.getLastBuild(); assertNotNull("downstream build didn't happen",db); rule.assertBuildStatusSuccess(db); } @Test public void testBuildChooserContext() throws Exception { final FreeStyleProject p = createFreeStyleProject(); final FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); BuildChooserContextImpl c = new BuildChooserContextImpl(p, b, null); c.actOnBuild(new ContextCallable<Run<?,?>, Object>() { public Object invoke(Run param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,b); return null; } }); c.actOnProject(new ContextCallable<Job<?,?>, Object>() { public Object invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,p); return null; } }); DumbSlave agent = rule.createOnlineSlave(); assertEquals(p.toString(), agent.getChannel().call(new BuildChooserContextTestCallable(c))); } private static class BuildChooserContextTestCallable extends MasterToSlaveCallable<String,IOException> { private final BuildChooserContext c; public BuildChooserContextTestCallable(BuildChooserContext c) { this.c = c; } public String call() throws IOException { try { return c.actOnProject(new ContextCallable<Job<?,?>, String>() { public String invoke(Job<?,?> param, VirtualChannel channel) throws IOException, InterruptedException { assertTrue(channel instanceof Channel); assertTrue(Jenkins.getInstanceOrNull()!=null); return param.toString(); } }); } catch (InterruptedException e) { throw new IOException(e); } } } // eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe]) static public void assertCulprits(String assertMsg, Set<User> actual, PersonIdent[] expected) { Collection<String> fullNames = Collections2.transform(actual, new Function<User,String>() { public String apply(User u) { return u.getFullName(); } }); for(PersonIdent p : expected) { assertTrue(assertMsg, fullNames.contains(p.getName())); } } @Test public void testEmailCommitter() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // setup global config GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = (DescriptorImpl) scm.getDescriptor(); assertFalse("Wrong initial value for create account based on e-mail", scm.isCreateAccountBasedOnEmail()); descriptor.setCreateAccountBasedOnEmail(true); assertTrue("Create account based on e-mail not set", scm.isCreateAccountBasedOnEmail()); assertFalse("Wrong initial value for use existing user if same e-mail already found", scm.isUseExistingAccountWithSameEmail()); descriptor.setUseExistingAccountWithSameEmail(true); assertTrue("Use existing user if same e-mail already found is not set", scm.isUseExistingAccountWithSameEmail()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "jeff@doe.com"); commit(commitFile2, jeffDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); User culprit = culprits.iterator().next(); assertEquals("", jeffDoe.getEmailAddress(), culprit.getId()); assertEquals("", jeffDoe.getName(), culprit.getFullName()); rule.assertBuildStatusSuccess(build); } @Issue("JENKINS-59868") @Test public void testNonExistentWorkingDirectoryPoll() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); project.setScm(new GitSCM( ((GitSCM)project.getScm()).getUserRemoteConfigs(), Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, // configure GitSCM with the DisableRemotePoll extension to ensure that polling use the workspace Collections.singletonList(new DisableRemotePoll()))); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); // Empty the workspace directory build1.getWorkspace().deleteRecursive(); // Setup a recorder for polling logs RingBufferLogHandler pollLogHandler = new RingBufferLogHandler(10); Logger pollLogger = Logger.getLogger(GitSCMTest.class.getName()); pollLogger.addHandler(pollLogHandler); TaskListener taskListener = new LogTaskListener(pollLogger, Level.INFO); // Make sure that polling returns BUILD_NOW and properly log the reason FilePath filePath = build1.getWorkspace(); assertThat(project.getScm().compareRemoteRevisionWith(project, new Launcher.LocalLauncher(taskListener), filePath, taskListener, null), is(PollingResult.BUILD_NOW)); assertTrue(pollLogHandler.getView().stream().anyMatch(m -> m.getMessage().contains("[poll] Working Directory does not exist"))); } // Disabled - consistently fails, needs more analysis // @Test public void testFetchFromMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); project.setScm(new GitSCM( remotes, Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList())); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); /* Diagnostic help - for later use */ SCMRevisionState baseline = project.poll(listener).baseline; Change change = project.poll(listener).change; SCMRevisionState remote = project.poll(listener).remote; String assertionMessage = MessageFormat.format("polling incorrectly detected change after build. Baseline: {0}, Change: {1}, Remote: {2}", baseline, change, remote); assertFalse(assertionMessage, project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } private void branchSpecWithMultipleRepositories(String branchName) throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); project.setScm(new GitSCM( remotes, Collections.singletonList(new BranchSpec(branchName)), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList())); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); rule.assertBuildStatusSuccess(build); } @Issue("JENKINS-26268") public void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception { branchSpecWithMultipleRepositories(testRepo.git.revParse("HEAD").getName()); } @Issue("JENKINS-26268") public void testBranchSpecAsRemotesOriginMasterWithMultipleRepositories() throws Exception { branchSpecWithMultipleRepositories("remotes/origin/master"); } @Issue("JENKINS-25639") @Test public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("secondRepo", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); GitSCM gitSCM = new GitSCM( remotes, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(gitSCM); /* Check that polling would force build through * compareRemoteRevisionWith by detecting no last build */ FilePath filePath = new FilePath(new File(".")); assertThat(gitSCM.compareRemoteRevisionWith(project, new Launcher.LocalLauncher(listener), filePath, listener, null), is(PollingResult.BUILD_NOW)); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1"); commit("commitFile2", johnDoe, "Commit number 2"); git = Git.with(listener, new EnvVars()).in(build.getWorkspace()).getClient(); for (RemoteConfig remoteConfig : gitSCM.getRepositories()) { git.fetch_().from(remoteConfig.getURIs().get(0), remoteConfig.getFetchRefSpecs()); } BuildChooser buildChooser = gitSCM.getBuildChooser(); Collection<Revision> candidateRevisions = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertEquals(1, candidateRevisions.size()); gitSCM.setBuildChooser(buildChooser); // Should be a no-op Collection<Revision> candidateRevisions2 = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertThat(candidateRevisions2, is(candidateRevisions)); } private final Random random = new Random(); private boolean useChangelogToBranch = random.nextBoolean(); private void addChangelogToBranchExtension(GitSCM scm) { if (useChangelogToBranch) { /* Changelog should be no different with this enabled or disabled */ ChangelogToBranchOptions changelogOptions = new ChangelogToBranchOptions("origin", "master"); scm.getExtensions().add(new ChangelogToBranch(changelogOptions)); } useChangelogToBranch = !useChangelogToBranch; } @Test public void testMerge() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-20392") @Test public void testMergeChangelog() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: // Here the changelog is by default empty (because changelog for first commit is always empty commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); // Create second commit and run build // Here the changelog should contain exactly this one new commit testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; String commitMessage = "Commit number 2"; commit(commitFile2, johnDoe, commitMessage); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); ChangeLogSet<? extends ChangeLogSet.Entry> changeLog = build2.getChangeSet(); assertEquals("Changelog should contain one item", 1, changeLog.getItems().length); GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0]; assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim()); } @Test public void testMergeWithAgent() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-25191") @Test public void testMultipleMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF))); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); commit("dummyFile", johnDoe, "Initial Commit"); testRepo.git.branch("integration1"); testRepo.git.branch("integration2"); build(project, Result.SUCCESS); final String commitFile = "commitFile"; testRepo.git.checkoutBranch("integration1","master"); commit(commitFile,"abc", johnDoe, "merge conflict with integration2"); testRepo.git.checkoutBranch("integration2","master"); commit(commitFile,"cde", johnDoe, "merge conflict with integration1"); final FreeStyleBuild build = build(project, Result.FAILURE); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailedWithAgent() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeWithMatrixBuild() throws Exception { //Create a matrix project and a couple of axes MatrixProject project = rule.jenkins.createProject(MatrixProject.class, "xyz"); project.setAxes(new AxisList(new Axis("VAR","a","b"))); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testEnvironmentVariableExpansion() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath())); // create initial commit and then run the build against it: commit("a.txt", johnDoe, "Initial Commit"); build(project, Result.SUCCESS, "a.txt"); PollingResult r = project.poll(StreamTaskListener.fromStdout()); assertFalse(r.hasChanges()); commit("b.txt", johnDoe, "Another commit"); r = project.poll(StreamTaskListener.fromStdout()); assertTrue(r.hasChanges()); build(project, Result.SUCCESS, "b.txt"); } @TestExtension("testEnvironmentVariableExpansion") public static class SupplySomeEnvVars extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException { envs.put("CAT",""); } } private List<UserRemoteConfig> createRepoList(String url) { List<UserRemoteConfig> repoList = new ArrayList<>(); repoList.add(new UserRemoteConfig(url, null, null, null)); return repoList; } /* * Makes sure that git browser URL is preserved across config round trip. */ @Issue("JENKINS-22604") @Test public void testConfigRoundtripURLPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/jenkins"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); assertEquals("Wrong key", "git " + url, scm.getKey()); } /* * Makes sure that git extensions are preserved across config round trip. */ @Issue("JENKINS-33695") @Test public void testConfigRoundtripExtensionsPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "git://github.com/jenkinsci/git-plugin.git"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("*/master")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); /* Assert that no extensions are loaded initially */ assertEquals(Collections.emptyList(), scm.getExtensions().toList()); /* Add LocalBranch extension */ LocalBranch localBranchExtension = new LocalBranch("**"); scm.getExtensions().add(localBranchExtension); assertTrue(scm.getExtensions().toList().contains(localBranchExtension)); /* Save the configuration */ rule.configRoundtrip(p); List<GitSCMExtension> extensions = scm.getExtensions().toList();; assertTrue(extensions.contains(localBranchExtension)); assertEquals("Wrong extension count before reload", 1, extensions.size()); /* Reload configuration from disc */ p.doReload(); GitSCM reloadedGit = (GitSCM) p.getScm(); List<GitSCMExtension> reloadedExtensions = reloadedGit.getExtensions().toList(); assertEquals("Wrong extension count after reload", 1, reloadedExtensions.size()); LocalBranch reloadedLocalBranch = (LocalBranch) reloadedExtensions.get(0); assertEquals(localBranchExtension.getLocalBranch(), reloadedLocalBranch.getLocalBranch()); } /* * Makes sure that the configuration form works. */ @Test public void testConfigRoundtrip() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM scm = new GitSCM("https://github.com/jenkinsci/jenkins"); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); } /* * Sample configuration that should result in no extensions at all */ @Test public void testDataCompatibility1() throws Exception { FreeStyleProject p = (FreeStyleProject) rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); assertEquals(0, oldGit.getSubmoduleCfg().size()); assertEquals("git git://github.com/jenkinsci/model-ant-project.git", oldGit.getKey()); assertThat(oldGit.getEffectiveBrowser(), instanceOf(GithubWeb.class)); GithubWeb browser = (GithubWeb) oldGit.getEffectiveBrowser(); assertEquals(browser.getRepoUrl(), "https://github.com/jenkinsci/model-ant-project.git/"); } @Test public void testPleaseDontContinueAnyway() throws Exception { // create an empty repository with some commits testRepo.commit("a","foo",johnDoe, "added"); FreeStyleProject p = createFreeStyleProject(); p.setScm(new GitSCM(testRepo.gitDir.getAbsolutePath())); rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); // this should fail as it fails to fetch p.setScm(new GitSCM("http://localhost:4321/no/such/repository.git")); rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get()); } @Issue("JENKINS-19108") @Test public void testCheckoutToSpecificBranch() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM oldGit = new GitSCM("https://github.com/jenkinsci/model-ant-project.git/"); setupJGit(oldGit); oldGit.getExtensions().add(new LocalBranch("master")); p.setScm(oldGit); FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient(); gc.withRepository(new RepositoryCallback<Void>() { public Void invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException { Ref head = repo.findRef("HEAD"); assertTrue("Detached HEAD",head.isSymbolic()); Ref t = head.getTarget(); assertEquals(t.getName(),"refs/heads/master"); return null; } }); } /** * Verifies that if project specifies LocalBranch with value of "**" * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception on error */ @Test public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("**")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** * Verifies that if project specifies LocalBranch with null value (empty string) * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception on error */ @Test public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /* * Verifies that GIT_LOCAL_BRANCH is not set if LocalBranch extension * is not configured. */ @Test public void testCheckoutSansLocalBranchExtension() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", null, getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /* * Verifies that GIT_CHECKOUT_DIR is set to "checkoutDir" if RelativeTargetDirectory extension * is configured. */ @Test public void testCheckoutRelativeTargetDirectoryExtension() throws Exception { FreeStyleProject project = setupProject("master", false, "checkoutDir"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new RelativeTargetDirectory("checkoutDir")); FreeStyleBuild build1 = build(project, "checkoutDir", Result.SUCCESS, commitFile1); assertEquals("GIT_CHECKOUT_DIR", "checkoutDir", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR)); } /* * Verifies that GIT_CHECKOUT_DIR is not set if RelativeTargetDirectory extension * is not configured. */ @Test public void testCheckoutSansRelativeTargetDirectoryExtension() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_CHECKOUT_DIR", null, getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR)); } @Test public void testCheckoutFailureIsRetryable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); // create lock file to simulate lock collision File lock = new File(build1.getWorkspace().getRemote(), ".git/index.lock"); try { FileUtils.touch(lock); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.waitForMessage("java.io.IOException: Could not checkout", build2); } finally { lock.delete(); } } @Test public void testInitSparseCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("toto"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse(build1.getWorkspace().child("titi").exists()); assertFalse(build1.getWorkspace().child(commitFile2).exists()); } @Test public void testInitSparseCheckoutBis() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testSparseCheckoutAfterNormalCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().add(new SparseCheckoutPaths(Lists.newArrayList(new SparseCheckoutPath("titi")))); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); } @Test public void testNormalCheckoutAfterSparseCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().remove(SparseCheckoutPaths.class); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testInitSparseCheckoutOverAgent() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } @Test @Issue("JENKINS-22009") public void testPolling_environmentValueInBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); // build the project build(project, Result.SUCCESS); assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") public void baseTestPolling_parentHead(List<GitSCMExtension> extensions) throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("**")), false, Collections.<SubmoduleConfig>emptyList(), null, null, extensions); project.setScm(scm); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); git.branch("someBranch"); commit("toto/commitFile2", johnDoe, "Commit number 2"); assertTrue("polling should detect changes",project.poll(listener).hasChanges()); // build the project build(project, Result.SUCCESS); /* Expects 1 build because the build of someBranch incorporates all * the changes from the master branch as well as the changes from someBranch. */ assertEquals("Wrong number of builds", 1, project.getBuilds().size()); assertFalse("polling should not detect changes",project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>emptyList()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead_DisableRemotePoll() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>singletonList(new DisableRemotePoll())); } @Test public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch"))); // Initial commit to master commit("file1", johnDoe, "Initial Commit"); // Create the branches git.branch("trackedbranch"); git.branch("manualbranch"); final StringParameterValue branchParam = new StringParameterValue("MY_BRANCH", "manualbranch"); final Action[] actions = {new ParametersAction(branchParam)}; FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, build); assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); git.checkout("manualbranch"); commit("file2", johnDoe, "Commit to manually build branch"); assertFalse("No changes to tracked branch", project.poll(listener).hasChanges()); git.checkout("trackedbranch"); commit("file3", johnDoe, "Commit to tracked branch"); assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges()); } private final class FakeParametersAction implements EnvironmentContributingAction, Serializable { // Test class for testPolling_environmentValueAsEnvironmentContributingAction test case final ParametersAction m_forwardingAction; public FakeParametersAction(StringParameterValue params) { this.m_forwardingAction = new ParametersAction(params); } @Deprecated public void buildEnvVars(AbstractBuild<?, ?> ab, EnvVars ev) { this.m_forwardingAction.buildEnvVars(ab, ev); } public String getIconFileName() { return this.m_forwardingAction.getIconFileName(); } public String getDisplayName() { return this.m_forwardingAction.getDisplayName(); } public String getUrlName() { return this.m_forwardingAction.getUrlName(); } public List<ParameterValue> getParameters() { return this.m_forwardingAction.getParameters(); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { } private void readObjectNoData() throws ObjectStreamException { } } @Test public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { FreeStyleProject project = createFreeStyleProject(); List<UserRemoteConfig> remoteConfigs = new ArrayList<>(); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null)); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null)); GitSCM scm = new GitSCM(remoteConfigs, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig> emptyList(), null, null, Collections.<GitSCMExtension> emptyList()); project.setScm(scm); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserIdCause()).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); first_build.getWorkspace().deleteContents(); PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null); assertFalse(pollingResult.hasChanges()); } @Issue("JENKINS-24467") @Test public void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); // Initial commit and build commit("toto/commitFile1", johnDoe, "Commit number 1"); String brokenPath = "\\broken/path\\of/doom"; if (!sampleRepo.gitVersionAtLeast(1, 8)) { /* Git 1.7.10.4 fails the first build unless the git-upload-pack * program is available in its PATH. * Later versions of git don't have that problem. */ final String systemPath = System.getenv("PATH"); brokenPath = systemPath + File.pathSeparator + brokenPath; } final StringParameterValue real_param = new StringParameterValue("MY_BRANCH", "master"); final StringParameterValue fake_param = new StringParameterValue("PATH", brokenPath); final Action[] actions = {new ParametersAction(real_param), new FakeParametersAction(fake_param)}; // SECURITY-170 - have to use ParametersDefinitionProperty project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserIdCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); Launcher launcher = workspace.createLauncher(listener); final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener); assertEquals(environment.get("MY_BRANCH"), "master"); assertNotSame("Environment path should not be broken path", environment.get("PATH"), brokenPath); } /** * Tests that builds have the correctly specified Custom SCM names, associated with each build. * @throws Exception on error */ @Ignore("Intermittent failures on stable-3.10 branch and master branch, not on stable-3.9") @Test public void testCustomSCMName() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; final String scmNameString1 = ""; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); // Check unset build SCM Name carries final int buildNumber1 = notifyAndCheckScmName( project, commit1, scmNameString1, 1, git); final String scmNameString2 = "ScmName2"; git.getExtensions().replace(new ScmName(scmNameString2)); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2 (commit1=" + commit1 + ")", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); // Check second set SCM Name final int buildNumber2 = notifyAndCheckScmName( project, commit2, scmNameString2, 2, git, commit1); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); final String scmNameString3 = "ScmName3"; git.getExtensions().replace(new ScmName(scmNameString3)); commit("commitFile3", johnDoe, "Commit number 3"); assertTrue("scm polling should detect commit 3, (commit2=" + commit2 + ",commit1=" + commit1 + ")", project.poll(listener).hasChanges()); final ObjectId commit3 = testRepo.git.revListAll().get(0); // Check third set SCM Name final int buildNumber3 = notifyAndCheckScmName( project, commit3, scmNameString3, 3, git, commit2, commit1); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); commit("commitFile4", johnDoe, "Commit number 4"); assertTrue("scm polling should detect commit 4 (commit3=" + commit3 + ",commit2=" + commit2 + ",commit1=" + commit1 + ")", project.poll(listener).hasChanges()); final ObjectId commit4 = testRepo.git.revListAll().get(0); // Check third set SCM Name still set final int buildNumber4 = notifyAndCheckScmName( project, commit4, scmNameString3, 4, git, commit3, commit2, commit1); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); checkNumberedBuildScmName(project, buildNumber3, scmNameString3, git); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for custom SCM name build data consistency. * @param project project to build * @param commit commit to build * @param expectedScmName Expected SCM name for commit. * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on error */ private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit, String expectedScmName, int ordinal, GitSCM git, ObjectId... priorCommits) throws Exception { String priorCommitIDs = ""; for (ObjectId priorCommit : priorCommits) { priorCommitIDs = priorCommitIDs + " " + priorCommit; } assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final Build build = project.getLastBuild(); final BuildData buildData = git.getBuildData(build); assertEquals("Expected SHA1 != built SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, commit, buildData .getLastBuiltRevision().getSha1()); assertEquals("Expected SHA1 != retrieved SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, commit, buildData.getLastBuild(commit).getSHA1()); assertTrue("Commit " + ordinal + " not marked as built", buildData.hasBeenBuilt(commit)); assertEquals("Wrong SCM Name for commit " + ordinal, expectedScmName, buildData.getScmName()); return build.getNumber(); } private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber, String expectedScmName, GitSCM git) throws Exception { final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber)); assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName()); } /* * Tests that builds have the correctly specified branches, associated with * the commit id, passed with "notifyCommit" URL. */ @Ignore("Intermittent failures on stable-3.10 branch, not on stable-3.9 or master") @Issue("JENKINS-24133") // Flaky test distracting from primary focus // @Test public void testSha1NotificationBranches() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); final GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should detect commit 1", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit1, branchName, 1, git); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit2, branchName, 2, git); notifyAndCheckBranch(project, commit1, branchName, 1, git); } /* A null pointer exception was detected because the plugin failed to * write a branch name to the build data, so there was a SHA1 recorded * in the build data, but no branch name. */ @Test @Deprecated // Testing deprecated buildEnvVars public void testNoNullPointerExceptionWithNullBranch() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch(null, sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.buildEnvVars(build, new EnvVars()); // NPE here before fix applied /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test @Deprecated // Testing deprecated buildEnvVars public void testBuildEnvVarsLocalBranchStarStar() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("**")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test @Deprecated // Testing deprecated buildEnvVars public void testBuildEnvVarsLocalBranchNull() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test @Deprecated // testing deprecated buildEnvVars public void testBuildEnvVarsLocalBranchNotSet() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", null, env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Issue("JENKINS-38241") @Test public void testCommitMessageIsPrintedToLogs() throws Exception { sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=test commit"); FreeStyleProject p = setupSimpleProject("master"); Run<?,?> run = rule.buildAndAssertSuccess(p); TaskListener mockListener = Mockito.mock(TaskListener.class); Mockito.when(mockListener.getLogger()).thenReturn(Mockito.spy(StreamTaskListener.fromStdout().getLogger())); p.getScm().checkout(run, new Launcher.LocalLauncher(listener), new FilePath(run.getRootDir()).child("tmp-" + "master"), mockListener, null, SCMRevisionState.NONE); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); verify(mockListener.getLogger(), atLeastOnce()).println(logCaptor.capture()); List<String> values = logCaptor.getAllValues(); assertThat(values, hasItem("Commit message: \"test commit\"")); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for build data consistency. * @param project project to build * @param commit commit to build * @param expectedBranch branch, that is expected to be built * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on error */ private void notifyAndCheckBranch(FreeStyleProject project, ObjectId commit, String expectedBranch, int ordinal, GitSCM git) throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final BuildData buildData = git.getBuildData(project.getLastBuild()); final Collection<Branch> builtBranches = buildData.lastBuild.getRevision().getBranches(); assertEquals("Commit " + ordinal + " should be built", commit, buildData .getLastBuiltRevision().getSha1()); final String expectedBranchString = "origin/" + expectedBranch; assertFalse("Branches should be detected for the build", builtBranches.isEmpty()); assertEquals(expectedBranch + " branch should be detected", expectedBranchString, builtBranches.iterator().next().getName()); assertEquals(expectedBranchString, getEnvVars(project).get(GitSCM.GIT_BRANCH)); } /** * Method performs commit notification for the last committed SHA1 using * notifyCommit URL. * @param project project to trigger * @return whether the new build has been triggered (<code>true</code>) or * not (<code>false</code>). * @throws Exception on error */ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws Exception { final int initialBuildNumber = project.getLastBuild().getNumber(); final String commit1 = ObjectId.toString(commitId); final String notificationPath = rule.getURL().toExternalForm() + "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1; final URL notifyUrl = new URL(notificationPath); String notifyContent = null; try (final InputStream is = notifyUrl.openStream()) { notifyContent = IOUtils.toString(is, "UTF-8"); } assertThat(notifyContent, containsString("No Git consumers using SCM API plugin for: " + testRepo.gitDir.toString())); if ((project.getLastBuild().getNumber() == initialBuildNumber) && (rule.jenkins.getQueue().isEmpty())) { return false; } else { while (!rule.jenkins.getQueue().isEmpty()) { Thread.sleep(100); } final FreeStyleBuild build = project.getLastBuild(); while (build.isBuilding()) { Thread.sleep(100); } return true; } } private void setupJGit(GitSCM git) { git.gitTool="jgit"; rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.<ToolProperty<?>>emptyList())); } /** We clean the environment, just in case the test is being run from a Jenkins job using this same plugin :). */ @TestExtension public static class CleanEnvironment extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run run, EnvVars envs, TaskListener listener) { envs.remove(GitSCM.GIT_BRANCH); envs.remove(GitSCM.GIT_LOCAL_BRANCH); envs.remove(GitSCM.GIT_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT); } } /** Returns true if test cleanup is not reliable */ private boolean cleanupIsUnreliable() { // Windows cleanup is unreliable on ci.jenkins.io String jobUrl = System.getenv("JOB_URL"); return isWindows() && jobUrl != null && jobUrl.contains("ci.jenkins.io"); } /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { return java.io.File.pathSeparatorChar==';'; } }
package net.dean.jraw.test; import net.dean.jraw.ApiException; import net.dean.jraw.JrawUtils; import net.dean.jraw.RedditClient; import net.dean.jraw.Version; import net.dean.jraw.http.LoggingMode; import net.dean.jraw.http.NetworkException; import net.dean.jraw.http.UserAgent; import net.dean.jraw.http.oauth.Credentials; import net.dean.jraw.managers.AccountManager; import net.dean.jraw.managers.ModerationManager; import net.dean.jraw.models.CommentNode; import net.dean.jraw.models.JsonModel; import net.dean.jraw.models.Listing; import net.dean.jraw.models.Subreddit; import net.dean.jraw.models.meta.JsonProperty; import net.dean.jraw.paginators.UserSubredditsPaginator; import org.testng.Assert; import org.testng.SkipException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.List; /** * This class is the base class of all JRAW test classes. It provides several utility methods. */ public abstract class RedditTest { protected static final RedditClient reddit = new RedditClient(UserAgent.of("desktop", "net.dean.jraw.test", "v" + Version.get().formatted(), "thatJavaNerd")); protected final AccountManager account; protected final ModerationManager moderation; protected RedditTest() { reddit.setLoggingMode(LoggingMode.ON_FAIL); Credentials creds = getCredentials(); if (!reddit.isAuthenticated()) { try { reddit.authenticate(reddit.getOAuthHelper().easyAuth(creds)); } catch (NetworkException | ApiException e) { handle(e); } } this.account = new AccountManager(reddit); this.moderation = new ModerationManager(reddit); } public long epochMillis() { return new Date().getTime(); } protected void handle(Throwable t) { if (t instanceof NetworkException) { NetworkException e = (NetworkException) t; int code = e.getResponse().getStatusCode(); if (code >= 500 && code < 600) throw new SkipException("Received " + code + ", skipping"); } t.printStackTrace(); Assert.fail(t.getMessage() == null ? t.getClass().getName() : t.getMessage(), t); } protected final boolean isRateLimit(ApiException e) { return e.getReason().equals("QUOTA_FILLED") || e.getReason().equals("RATELIMIT"); } protected void handlePostingQuota(ApiException e) { if (!isRateLimit(e)) { Assert.fail(e.getMessage()); } String msg = null; // toUpperCase just in case (no pun intended) String method = getCallingMethod(); switch (e.getReason().toUpperCase()) { case "QUOTA_FILLED": msg = String.format("Skipping %s(), link posting quota has been filled for this user", method); break; case "RATELIMIT": msg = String.format("Skipping %s(), reached ratelimit (%s)", method, e.getExplanation()); break; } if (msg != null) { JrawUtils.logger().error(msg); throw new SkipException(msg); } else { Assert.fail(e.getMessage()); } } protected String getCallingMethod() { StackTraceElement[] elements = Thread.currentThread().getStackTrace(); // [0] = Thread.currentThread().getStackTrace() // [1] = this method // [2] = caller of this method // [3] = Caller of the caller of this method return elements[3].getMethodName(); } protected final <T extends JsonModel> void validateModels(Iterable<T> iterable) { for (T model : iterable) { validateModel(model); } } /** * Validates all of the CommentNode's children's Comments */ protected final void validateModel(CommentNode root) { for (CommentNode node : root.walkTree()) { validateModel(node.getComment()); } } protected final <T extends JsonModel> void validateModel(T model) { Assert.assertNotNull(model); List<Method> jsonInteractionMethods = JsonModel.getJsonProperties(model.getClass()); try { for (Method method : jsonInteractionMethods) { JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class); Object returnVal = null; try { returnVal = method.invoke(model); } catch (InvocationTargetException e) { // InvocationTargetException thrown when the method.invoke() returns null and @JsonInteraction "nullable" // property is false if (e.getCause().getClass().equals(NullPointerException.class) && !jsonProperty.nullable()) { Assert.fail("Non-nullable JsonInteraction method returned null: " + model.getClass().getName() + "." + method.getName() + "()"); } else { // Other reason for InvocationTargetException Throwable cause = e.getCause(); cause.printStackTrace(); Assert.fail(cause.getClass().getName() + ": " + cause.getMessage()); } } if (returnVal != null && returnVal instanceof JsonModel) { validateModel((JsonModel) returnVal); } } } catch (IllegalAccessException e) { handle(e); } } /** * Short for CredentialsUtils.instance().script() */ protected final Credentials getCredentials() { return CredentialsUtils.instance().script(); } /** * Gets a subreddit that the testing user moderates * @return A subreddit */ protected final Subreddit getModeratedSubreddit() { Listing<Subreddit> moderatorOf = new UserSubredditsPaginator(reddit, "moderator").next(); if (moderatorOf.size() == 0) { throw new IllegalStateException("Must be a moderator of at least one subreddit"); } return moderatorOf.get(0); } }
package vexprtest; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import vexpressed.core.ExpressionException; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.concurrent.TimeUnit; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ExpressionBasicTest extends TestBase { @Test public void primitiveVariableResolverReturnsTheSameValueForAnyVarName() { variableResolver = var -> 5; assertEquals(eval("var"), 5); assertEquals(eval("anyvarworksnow"), 5); } @Test public void variableResolverReturnsValueForOneVarName() { variableResolver = var -> var.equals("var") ? 5 : null; assertEquals(eval("var"), 5); assertEquals(eval("var != null"), true); assertEquals(eval("var == null"), false); assertEquals(eval("anyvarworksnow"), null); assertEquals(eval("anyvarworksnow == null"), true); } @Test public void integerLiteralStaysInteger() { assertEquals(eval("5"), 5); } @Test public void tooBigIntegerLiteralConvertedToBigDecimal() { assertEquals(eval("5555555555555"), new BigDecimal("5555555555555")); } @Test public void fpNumberCanStartWithPoint() { assertEquals(eval(".047"), new BigDecimal("0.047")); } @Test public void fpNumberCanContainExponent() { assertEquals(eval("1.47E5"), new BigDecimal("147000")); } @Test public void fpNumberCanContainExplicitlyPositiveExponent() { assertEquals(eval(".47E+3"), new BigDecimal("470")); } @Test public void fpNumberCanContainNegativeExponent() { assertEquals(eval("1.47E-1"), new BigDecimal("0.147")); } @Test public void fpNumberCanEndWithPoint() { assertEquals(eval("3."), new BigDecimal("3")); } @Test public void shortVariableIsConvertedToInteger() { variableResolver = var -> (short) 5; assertEquals(eval("var").getClass(), Integer.class); } @Test public void smallLongIsConvertedToInteger() { variableResolver = var -> 5L; assertEquals(eval("var").getClass(), Integer.class); } @Test public void valueOutOfIntegerRangeIsConvertedToBigDecimal() { variableResolver = var -> 5555555555555L; assertEquals(eval("var").getClass(), BigDecimal.class); } @Test public void fpValueConvertedToBigDecimal() { variableResolver = var -> 5.1; assertEquals(eval("var"), new BigDecimal("5.1")); } @Test public void numbersCanContainUnderscores() { assertEquals(eval("5_0"), 50); assertEquals(eval("5_"), 5); assertEquals(eval("5_.1_"), new BigDecimal("5.1")); assertEquals(eval("5_.1_E1_"), new BigDecimal("51")); // note that _5 is valid variable name, so is _5.5 (dot is part of valid ID) // _5E+1 would resolve _5E variable and add it to 1 } @Test public void booleanVariableStaysBoolean() { variableResolver = var -> true; assertEquals(eval("var"), true); } @Test public void stringVariableStaysString() { variableResolver = var -> "str'val"; assertEquals(eval("var"), "str'val"); } @Test public void stringLiteralEscapedQuoteInterpretedProperly() { assertEquals(eval("'str''val'"), "str'val"); } @Test public void stringConcatenation() { assertEquals(eval("'str' + 'ing'"), "string"); assertEquals(eval("'str' + 47"), "str47"); } @Test public void stringCompare() { variableResolver = var -> "str'val"; assertEquals(eval("var == 'str''val'"), true); } @Test public void booleanLiterals() { assertEquals(eval("true"), true); assertEquals(eval("false"), false); } @Test public void booleanNot() { assertEquals(eval("!true"), false); assertEquals(eval("NOT TRUE"), false); assertEquals(eval("!false"), true); assertEquals(eval("not false"), true); assertEquals(eval("!not true"), true); assertEquals(eval("not!true"), true); assertEquals(eval("! !true"), true); } @Test public void booleanAnd() { assertEquals(eval("true && true"), true); // keyword is case-insensitive assertEquals(eval("TRUE && false"), false); assertEquals(eval("FALSE && true"), false); assertEquals(eval("false && false"), false); } @Test public void booleanOr() { assertEquals(eval("true || true"), true); assertEquals(eval("true || false"), true); assertEquals(eval("false || true"), true); assertEquals(eval("false || false"), false); assertEquals(eval("true OR true"), true); assertEquals(eval("true OR false"), true); assertEquals(eval("false OR true"), true); assertEquals(eval("false OR false"), false); } @DataProvider(name = "test-andor-data") public Object[][] testDataProvider() { return new Object[][] { {false, false, false}, {false, false, true}, {false, true, false}, {false, true, true}, {true, false, false}, {true, false, true}, {true, true, false}, {true, true, true}, }; } @Test(dataProvider = "test-andor-data") public void booleanAndOrCombination(boolean x, boolean y, boolean z) { assertEquals(eval(x + " || " + y + " && " + z), eval(x + " || (" + y + " && " + z + ')')); assertEquals(eval(x + " && " + y + " || " + z), eval("(" + x + " && " + y + ") || " + z)); } @Test public void booleanComparison() { assertEquals(eval("true EQ true"), true); assertEquals(eval("true == false"), false); assertEquals(eval("true > false"), true); assertEquals(eval("true >= false"), true); assertEquals(eval("true <= false"), false); assertEquals(eval("true < false"), false); } @Test public void numberComparison() { assertEquals(eval("5 > 1"), true); assertEquals(eval("1 > 5"), false); assertEquals(eval("5 > 5"), false); assertEquals(eval("5 < 1"), false); assertEquals(eval("1 < 5"), true); assertEquals(eval("5 < 5"), false); assertEquals(eval("+5 < -7"), false); assertEquals(eval("-5 < -(3)"), true); assertEquals(eval("5 == 1"), false); assertEquals(eval("5 == 5"), true); assertEquals(eval("5 != 5"), false); assertEquals(eval("5 != 3"), true); // mixing BigDecimal and Integer on either side assertEquals(eval("5. == 5"), true); assertEquals(eval("5 < 5.1"), true); } @Test public void nullComparison() { assertEquals(eval("null == null"), true); assertEquals(eval("null != null"), false); assertEquals(eval("5 != null"), true); assertEquals(eval("5 == null"), false); assertEquals(eval("null != 5"), true); assertEquals(eval("null == 5"), false); assertEquals(eval("null > null"), false); assertEquals(eval("null < null"), false); assertEquals(eval("null <= null"), false); assertEquals(eval("null >= null"), false); } @Test public void arithmeticOnDates() { variableResolver = val -> LocalDate.of(2016, 2, 29); assertEquals(eval("val + 1"), LocalDate.of(2016, 3, 1)); assertEquals(eval("val + '1d'"), LocalDate.of(2016, 3, 1)); assertEquals(eval("val + '1w'"), LocalDate.of(2016, 3, 7)); assertEquals(eval("val + '1m'"), LocalDate.of(2016, 3, 29)); assertEquals(eval("val + '1y'"), LocalDate.of(2017, 2, 28)); variableResolver = val -> LocalDate.of(2016, 3, 1); assertEquals(eval("val - 1"), LocalDate.of(2016, 2, 29)); assertEquals(eval("val - '1d'"), LocalDate.of(2016, 2, 29)); assertEquals(eval("val - '1w'"), LocalDate.of(2016, 2, 23)); assertEquals(eval("val - '1m'"), LocalDate.of(2016, 2, 1)); assertEquals(eval("val - '1y'"), LocalDate.of(2015, 3, 1)); // combined specification is not supported directly assertThatThrownBy(() -> eval("val + '2w3d'")) .isInstanceOf(ExpressionException.class) .hasMessage("Cannot parse temporal amount: 2w3d"); // only split to more strings assertEquals(eval("val + '2w' + '3d'"), LocalDate.of(2016, 3, 18)); variableResolver = val -> LocalDateTime.of(2016, 3, 1, 12, 47); assertEquals(eval("val + 1"), LocalDateTime.of(2016, 3, 2, 12, 47)); variableResolver = val -> Instant.ofEpochMilli(1000000); assertEquals(eval("val + 1"), Instant.ofEpochMilli(1000000 + TimeUnit.DAYS.toMillis(1))); } @Test public void commentsAreIgnoredProperly() { assertFalse((boolean) eval("true AND false")); assertFalse((boolean) eval("/*true AND*/ false")); assertFalse((boolean) eval("/*true \nAND*/ false")); assertTrue((boolean) eval("true /* AND \nfalse */")); assertTrue((boolean) eval("true // AND false")); assertTrue((boolean) eval("false // AND false\nOR true")); } @Test public void invalidExpressionThrowsException() { assertThatThrownBy(() -> eval("+")) .isInstanceOf(ExpressionException.class) .hasMessageContaining("Expression parse failed at"); } }
package org.pm4j.common.expr; import java.util.HashSet; import java.util.Set; import org.pm4j.common.exception.CheckedExceptionWrapper; import org.pm4j.common.expr.parser.ParseCtxt; import org.pm4j.common.expr.parser.ParseException; /** * Parses a name with its modifier specification. * <p> * Examples: * <pre> * expression without modifier: myVar * expression for a variable: #myVar * expression for something optional (may be null): (o)myVar * expression for a field or getter that may exist: (x)myVar * expression for a field or getter that may exist or may be null: (x,o)myVar.x * expression for an optional variable: (o)#myVar * </pre> * * @author olaf boede */ public class NameWithModifier implements Cloneable { private Set<Modifier> modifiers = new HashSet<Modifier>(); private boolean variable; private String name; public Set<Modifier> getModifiers() { return modifiers; } public boolean isOptional() { return modifiers.contains(Modifier.OPTIONAL); } public boolean isVariable() { return variable; } public void setVariable(boolean variable) { this.variable = variable; } public String getName() { return name; } @Override public NameWithModifier clone() { try { return (NameWithModifier) super.clone(); } catch (CloneNotSupportedException e) { throw new CheckedExceptionWrapper(e); } } public static enum Modifier { OPTIONAL("o") { @Override public void applyModifier(NameWithModifier n) { n.modifiers.add(OPTIONAL); } }, EXISTS_OPTIONALLY("x") { @Override public void applyModifier(NameWithModifier n) { n.modifiers.add(EXISTS_OPTIONALLY); } }, REPEATED("*") { @Override public void applyModifier(NameWithModifier n) { n.modifiers.add(REPEATED); } }; private final String id; private Modifier(String id) { if (id.length() != 1) { throw new IllegalArgumentException("The parse algorithm needs to be extended to support more than one character."); } this.id = id; } public abstract void applyModifier(NameWithModifier n); static Modifier parse(ParseCtxt ctxt) { char ch = ctxt.skipBlanks().readCharAndAdvance(); for (Modifier m : values()) { if (m.id.charAt(0) == ch) { return m; } } throw new ParseException(ctxt, "Unknown modifier '" + ch + "' found."); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (!modifiers.isEmpty()) { sb.append("("); for (Modifier m : Modifier.values()) { if (modifiers.contains(m)) { sb.append(m.id); } } sb.append(")"); } if (variable) { sb.append(' } sb.append(name); return sb.toString(); } /** * Parses a name with modifiers. * <p> * Examples: * <ul> * <li>'myName' - a simple name</li> * <li>'#myVar' - a variable</li> * <li>'(o)myName - an optional name</li> * <li>'(o)#myName - an optional variable</li> * </ul> * * @param ctxt The current parse context. * @return The parsed syntax element. * @throws ParseException if the string at the current parse position is not a name. */ public static NameWithModifier parseNameAndModifier(ParseCtxt ctxt) { NameWithModifier n = new NameWithModifier(); ctxt.skipBlanks(); if (ctxt.isOnChar('(')) { ctxt.readChar('('); boolean done = false; do { Modifier m = Modifier.parse(ctxt); m.applyModifier(n); ctxt.skipBlanks(); switch (ctxt.currentChar()) { case ')': ctxt.readChar(')'); done = true; break; case ',': ctxt.readChar(','); break; default: throw new ParseException(ctxt, "Can't interpret character '" + ctxt.currentChar() + "' in modifier list."); } } while(!done); ctxt.skipBlanks(); } if (ctxt.readOptionalChar(' n.setVariable(true); } n.name = ctxt.skipBlanksAndReadNameString(); if (n.name == null) { throw new ParseException(ctxt, "Missing name string."); } return n; } }
package uk.org.ownage.dmdirc.parser; /** * IRC Parser Error. * * @author Shane Mc Cormack * @version $Id$ */ public class ParserError { /** Error is potentially Fatal, Desync 99% Guarenteed! */ public static final int errFatal = 1; /** Error is not fatal, but is more severe than a warning. */ public static final int errError = 2; /** Error was an unexpected occurance, but shouldn't be anything to worry about. */ public static final int errWarning = 4; /** Error was an exception from elsewhere. */ public static final int errException = 8; /** Store the Error level */ protected int errorLevel = 0; /** Store the Error Information */ protected String errorData = ""; /** Store the Exception object */ protected Exception exceptionInfo = null; /** * Create a new Error. * * @param level Set the error level. * @param data String containing information about the error. */ public ParserError(int level, String data) { errorData = data; errorLevel = level; } /** * Check if this error is considered Fatal. * * @return Returns true for a fatal error, false for a non-fatal error */ public boolean isFatal() { return ((errorLevel & errFatal) == errFatal); } /** * Check if this error is considered an error (less severe than fatal, worse than warning). * * @return Returns true for an "Error" level error, else false. */ public boolean isError() { return ((errorLevel & errError) == errError); } /** * Check if this error is considered a warning * * @return Returns true for a warning, else false. */ public boolean isWarning() { return ((errorLevel & errWarning) == errWarning); } /** * Check if this error was generated from an exception. * * @return Returns true if getException will return an exception. */ public boolean isException() { return ((errorLevel & errException) == errException); } /** * Set the Exception object. * * @param newException The exception object to store */ public void setException(Exception newException) { exceptionInfo = newException; if (!this.isException()) { this.errorLevel = this.errorLevel+errException; } } /** * Get the Exception object. * * @return Returns the exception object */ public Exception getException() { return exceptionInfo; } /** * Get the full ErrorLevel. * * @return Returns the error level */ public int getLevel() { return errorLevel; } /** * Get the Error information. * * @return Returns the error data */ public String getData() { return errorData; } /** * Get SVN Version information * * @return SVN Version String */ public static String getSvnInfo () { return "$Id$"; } } // eof
package com.ee.admob; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import com.ee.core.Logger; import com.ee.core.PluginProtocol; import com.ee.core.internal.JsonUtils; import com.ee.core.internal.MessageBridge; import com.ee.core.internal.MessageHandler; import com.ee.core.internal.Utils; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.reward.RewardItem; import com.google.android.gms.ads.reward.RewardedVideoAd; import com.google.android.gms.ads.reward.RewardedVideoAdListener; import java.util.HashMap; import java.util.Map; public class AdMob implements PluginProtocol, RewardedVideoAdListener { private static final String k__initialize = "AdMob_initialize"; private static final String k__createBannerAd = "AdMob_createBannerAd"; private static final String k__destroyBannerAd = "AdMob_destroyBannerAd"; private static final String k__createNativeAd = "AdMob_createNativeAd"; private static final String k__destroyNativeAd = "AdMob_destroyNativeAd"; private static final String k__createInterstitialAd = "AdMob_createInterstitialAd"; private static final String k__destroyInterstitialAd = "AdMob_destroyInterstitialAd"; private static final String k__hasRewardedVideo = "AdMob_hasRewardedVideo"; private static final String k__loadRewardedVideo = "AdMob_loadRewardedVideo"; private static final String k__showRewardedVideo = "AdMob_showRewardedVideo"; private static final String k__onRewarded = "AdMob_onRewarded"; private static final String k__onFailedToLoad = "AdMob_onFailedToLoad"; private static final String k__onLoaded = "AdMob_onLoaded"; private static final String k__onClosed = "AdMob_onClosed"; private static final String k__ad_id = "ad_id"; private static final String k__ad_size = "ad_size"; private static final Logger _logger = new Logger(AdMob.class.getName()); private Activity _context; private RewardedVideoAd _rewardedVideoAd; private Map<String, AdMobBannerAd> _bannerAds; private Map<String, AdMobInterstitialAd> _interstitialAds; public AdMob(Context context) { Utils.checkMainThread(); _context = (Activity) context; _bannerAds = new HashMap<>(); _interstitialAds = new HashMap<>(); _rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(_context); _rewardedVideoAd.setRewardedVideoAdListener(this); registerHandlers(); } @NonNull @Override public String getPluginName() { return "AdMob"; } @Override public void onStart() { } @Override public void onStop() { } @Override public void onResume() { _rewardedVideoAd.resume(_context); } @Override public void onPause() { _rewardedVideoAd.pause(_context); } @Override public void onDestroy() { Utils.checkMainThread(); deregisterHandlers(); _rewardedVideoAd.destroy(_context); for (String key : _bannerAds.keySet()) { _bannerAds.get(key).destroy(); } _bannerAds.clear(); _bannerAds = null; for (String key : _interstitialAds.keySet()) { _interstitialAds.get(key).destroy(); } _interstitialAds.clear(); _interstitialAds = null; _context = null; } @Override public boolean onActivityResult(int requestCode, int responseCode, Intent data) { return false; } @Override public boolean onBackPressed() { return false; } private void registerHandlers() { Utils.checkMainThread(); MessageBridge bridge = MessageBridge.getInstance(); bridge.registerHandler(new MessageHandler() { @SuppressWarnings("UnnecessaryLocalVariable") @NonNull @Override public String handle(@NonNull String message) { String applicationId = message; initialize(applicationId); return ""; } }, k__initialize); bridge.registerHandler(new MessageHandler() { @NonNull @Override public String handle(@NonNull String message) { Map<String, Object> dict = JsonUtils.convertStringToDictionary(message); assert dict != null; String adId = (String) dict.get(k__ad_id); Integer adSizeIndex = (Integer) dict.get(k__ad_size); AdSize adSize = AdMobBannerAd.adSizeFor(adSizeIndex); return Utils.toString(createBannerAd(adId, adSize)); } }, k__createBannerAd); bridge.registerHandler(new MessageHandler() { @SuppressWarnings("UnnecessaryLocalVariable") @NonNull @Override public String handle(@NonNull String message) { String adId = message; return Utils.toString(destroyBannerAd(adId)); } }, k__destroyBannerAd); bridge.registerHandler(new MessageHandler() { @SuppressWarnings("UnnecessaryLocalVariable") @NonNull @Override public String handle(@NonNull String message) { String placementId = message; return Utils.toString(createInterstitialAd(placementId)); } }, k__createInterstitialAd); bridge.registerHandler(new MessageHandler() { @SuppressWarnings("UnnecessaryLocalVariable") @NonNull @Override public String handle(@NonNull String message) { String placementId = message; return Utils.toString(destroyInterstitialAd(placementId)); } }, k__destroyInterstitialAd); bridge.registerHandler(new MessageHandler() { @NonNull @Override public String handle(@NonNull String message) { return Utils.toString(hasRewardedVideo()); } }, k__hasRewardedVideo); bridge.registerHandler(new MessageHandler() { @SuppressWarnings("UnnecessaryLocalVariable") @NonNull @Override public String handle(@NonNull String message) { String adId = message; loadRewardedVideo(adId); return ""; } }, k__loadRewardedVideo); bridge.registerHandler(new MessageHandler() { @NonNull @Override public String handle(@NonNull String message) { showRewardedVideo(); return ""; } }, k__showRewardedVideo); } private void deregisterHandlers() { Utils.checkMainThread(); MessageBridge bridge = MessageBridge.getInstance(); bridge.deregisterHandler(k__initialize); bridge.deregisterHandler(k__createBannerAd); bridge.deregisterHandler(k__destroyBannerAd); bridge.deregisterHandler(k__createInterstitialAd); bridge.deregisterHandler(k__destroyInterstitialAd); bridge.deregisterHandler(k__hasRewardedVideo); bridge.deregisterHandler(k__loadRewardedVideo); bridge.deregisterHandler(k__showRewardedVideo); } @SuppressWarnings("WeakerAccess") public void initialize(@NonNull String applicationId) { MobileAds.initialize(_context, applicationId); } @SuppressWarnings("WeakerAccess") public boolean createBannerAd(@NonNull String adId, @NonNull AdSize size) { Utils.checkMainThread(); if (_bannerAds.containsKey(adId)) { return false; } AdMobBannerAd ad = new AdMobBannerAd(_context, adId, size); _bannerAds.put(adId, ad); return true; } @SuppressWarnings("WeakerAccess") public boolean destroyBannerAd(@NonNull String adId) { Utils.checkMainThread(); if (!_bannerAds.containsKey(adId)) { return false; } AdMobBannerAd ad = _bannerAds.get(adId); ad.destroy(); _bannerAds.remove(adId); return true; } @SuppressWarnings("WeakerAccess") public boolean createInterstitialAd(@NonNull String adId) { Utils.checkMainThread(); if (_interstitialAds.containsKey(adId)) { return false; } AdMobInterstitialAd ad = new AdMobInterstitialAd(_context, adId); _interstitialAds.put(adId, ad); return true; } @SuppressWarnings("WeakerAccess") public boolean destroyInterstitialAd(@NonNull String adId) { Utils.checkMainThread(); if (!_interstitialAds.containsKey(adId)) { return false; } AdMobInterstitialAd ad = _interstitialAds.get(adId); ad.destroy(); _interstitialAds.remove(adId); return true; } @SuppressWarnings("WeakerAccess") public boolean hasRewardedVideo() { Utils.checkMainThread(); return _rewardedVideoAd.isLoaded(); } @SuppressWarnings("WeakerAccess") public void loadRewardedVideo(@NonNull String adId) { Utils.checkMainThread(); AdRequest request = new AdRequest.Builder().build(); _rewardedVideoAd.loadAd(adId, request); } @SuppressWarnings("WeakerAccess") public void showRewardedVideo() { Utils.checkMainThread(); _rewardedVideoAd.show(); } @Override public void onRewardedVideoAdLoaded() { _logger.info("onRewardedVideoAdLeftApplication"); Utils.checkMainThread(); MessageBridge bridge = MessageBridge.getInstance(); bridge.callCpp(k__onLoaded); } @Override public void onRewardedVideoAdOpened() { _logger.info("onRewardedVideoAdLeftApplication"); Utils.checkMainThread(); } @Override public void onRewardedVideoStarted() { _logger.info("onRewardedVideoAdLeftApplication"); Utils.checkMainThread(); } @Override public void onRewardedVideoAdClosed() { _logger.info("onRewardedVideoAdClosed"); Utils.checkMainThread(); MessageBridge bridge = MessageBridge.getInstance(); bridge.callCpp(k__onClosed); } @Override public void onRewarded(RewardItem rewardItem) { _logger.info("onRewarded"); Utils.checkMainThread(); MessageBridge bridge = MessageBridge.getInstance(); bridge.callCpp(k__onRewarded); } @Override public void onRewardedVideoAdLeftApplication() { _logger.info("onRewardedVideoAdLeftApplication"); Utils.checkMainThread(); } @Override public void onRewardedVideoAdFailedToLoad(int errorCode) { _logger.info("onRewardedVideoAdFailedToLoad: code = " + errorCode); Utils.checkMainThread(); MessageBridge bridge = MessageBridge.getInstance(); bridge.callCpp(k__onFailedToLoad, String.valueOf(errorCode)); } }
package com.opengamma.util.test; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.SortedMap; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import com.google.common.collect.Sets; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.db.DbConnector; import com.opengamma.util.db.DbConnectorFactoryBean; import com.opengamma.util.db.DbDialect; import com.opengamma.util.db.HSQLDbDialect; import com.opengamma.util.db.PostgresDbDialect; import com.opengamma.util.db.SqlServer2008DbDialect; import com.opengamma.util.test.DbTool.TableCreationCallback; import com.opengamma.util.time.DateUtils; /** * Base DB test. */ public abstract class DbTest implements TableCreationCallback { /** Cache. */ protected static Map<String, String> s_databaseTypeVersion = new HashMap<>(); /** Known dialects. */ private static final Map<String, DbDialect> s_dbDialects = new HashMap<>(); static { // initialize the clock DateUtils.initTimeZone(); // setup the known databases addDbDialect("hsqldb", new HSQLDbDialect()); addDbDialect("postgres", new PostgresDbDialect()); addDbDialect("sqlserver2008", new SqlServer2008DbDialect()); } private final String _databaseType; private final String _targetVersion; private final String _createVersion; private volatile DbTool _dbtool; /** * Creates an instance. * * @param databaseType the database type * @param targetVersion the target version * @param createVersion the create version */ protected DbTest(String databaseType, String targetVersion, String createVersion) { ArgumentChecker.notNull(databaseType, "databaseType"); _databaseType = databaseType; _targetVersion = targetVersion; _createVersion = createVersion; } /** * Initializes the DBTool outside the constructor. * This works better with TestNG and Maven, where the constructor is called * even if the test is never run. */ private DbTool ensureDbTool() { if (_dbtool == null) { synchronized (this) { if (_dbtool == null) { ArgumentChecker.notNull(_databaseType, "_databaseType"); _dbtool = DbTestProperties.getDbTool(_databaseType); _dbtool.setJdbcUrl(getDbTool().getTestDatabaseUrl()); _dbtool.addDbScriptDirectories(DbScripts.getSqlScriptDir()); } } } return _dbtool; } /** * Initialize the database to the required version. * This tracks the last initialized version in a static map to avoid duplicate * DB operations on bigger test classes. This might not be such a good idea. */ @BeforeMethod(groups = {TestGroup.UNIT_DB, TestGroup.INTEGRATION}) public void setUp() throws Exception { DbTool dbTool = ensureDbTool(); String prevVersion = s_databaseTypeVersion.get(getDatabaseType()); if ((prevVersion == null) || !prevVersion.equals(getTargetVersion())) { s_databaseTypeVersion.put(getDatabaseType(), getTargetVersion()); dbTool.setTargetVersion(getTargetVersion()); dbTool.setCreateVersion(getCreateVersion()); dbTool.dropTestSchema(); dbTool.createTestSchema(); dbTool.createTestTables(this); } dbTool.clearTestTables(); } @AfterMethod(groups = {TestGroup.UNIT_DB, TestGroup.INTEGRATION}) public void tearDown() throws Exception { DbTool dbTool = _dbtool; if (dbTool != null) { _dbtool.resetTestCatalog(); // avoids locking issues with Derby } } @AfterClass(groups = {TestGroup.UNIT_DB, TestGroup.INTEGRATION}) public void tearDownClass() throws Exception { DbTool dbTool = _dbtool; if (dbTool != null) { _dbtool.close(); } } @AfterSuite(groups = {TestGroup.UNIT_DB, TestGroup.INTEGRATION}) public static void cleanUp() { DbScripts.deleteSqlScriptDir(); } /** * Adds a dialect to the map of known. * * @param dbType the database type, not null * @param dialect the dialect, not null */ public static void addDbDialect(String dbType, DbDialect dialect) { s_dbDialects.put(dbType, dialect); } @DataProvider(name = "localDatabase") public static Object[][] data_localDatabase() { return getParametersForDatabase("hsqldb"); } @DataProvider(name = "databases") public static Object[][] data_databases() { try { return getParameters(); } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } } @DataProvider(name = "databasesVersionsForSeparateMasters") public static Object[][] data_databasesVersionsForSeparateMasters() { return getParametersForSeparateMasters(3); } private static Object[][] getParametersForSeparateMasters(int prevVersionCount) { Collection<String> databaseTypes = getAvailableDatabaseTypes(System.getProperty("test.database.type")); ArrayList<Object[]> parameters = new ArrayList<Object[]>(); for (String databaseType : databaseTypes) { DbScripts scripts = DbScripts.of(DbScripts.getSqlScriptDir(), databaseType); Map<String, SortedMap<Integer, DbScriptPair>> scriptPairs = scripts.getScriptPairs(); for (String schema : scriptPairs.keySet()) { Set<Integer> versions = scriptPairs.get(schema).keySet(); int max = Collections.max(versions); int min = Collections.min(versions); for (int v = max; v >= Math.max(max - prevVersionCount, min); v parameters.add(new Object[]{databaseType, schema, "" + max /*target_version*/, "" + v /*migrate_from_version*/}); } } } Object[][] array = new Object[parameters.size()][]; parameters.toArray(array); return array; } private static Object[][] getParameters() { Collection<String> databaseTypes = getAvailableDatabaseTypes(System.getProperty("test.database.type")); ArrayList<Object[]> parameters = new ArrayList<Object[]>(); for (String databaseType : databaseTypes) { parameters.add(new Object[]{databaseType, "latest"}); } Object[][] array = new Object[parameters.size()][]; parameters.toArray(array); return array; } private static Object[][] getParametersForDatabase(final String databaseType) { ArrayList<Object[]> parameters = new ArrayList<Object[]>(); for (String db : getAvailableDatabaseTypes(databaseType)) { parameters.add(new Object[]{db, "latest"}); } Object[][] array = new Object[parameters.size()][]; parameters.toArray(array); return array; } /** * Not all database drivers are available in some test environments. */ private static Collection<String> getAvailableDatabaseTypes(String databaseType) { Collection<String> databaseTypes; if (databaseType == null) { databaseTypes = Sets.newHashSet(s_dbDialects.keySet()); } else { if (s_dbDialects.containsKey(databaseType) == false) { throw new IllegalArgumentException("Unknown database: " + databaseType); } databaseTypes = Sets.newHashSet(databaseType); } for (Iterator<String> it = databaseTypes.iterator(); it.hasNext(); ) { String dbType = it.next(); DbDialect dbDialect = s_dbDialects.get(dbType); try { Objects.requireNonNull(dbDialect.getJDBCDriverClass()); } catch (RuntimeException | Error ex) { System.err.println("Database driver not available: " + dbDialect); it.remove(); } } return databaseTypes; } public DbTool getDbTool() { return ensureDbTool(); } public String getDatabaseType() { return _databaseType; } public String getCreateVersion() { return _createVersion; } public String getTargetVersion() { return _targetVersion; } public DataSourceTransactionManager getTransactionManager() { return new DataSourceTransactionManager(getDbTool().getDataSource()); } public DbConnector getDbConnector() { DbDialect dbDialect = s_dbDialects.get(getDatabaseType()); if (dbDialect == null) { throw new OpenGammaRuntimeException("config error - no DbDialect setup for " + getDatabaseType()); } DbConnectorFactoryBean factory = new DbConnectorFactoryBean(); factory.setName("DbTest"); factory.setDialect(dbDialect); factory.setDataSource(getDbTool().getDataSource()); factory.setTransactionIsolationLevelName("ISOLATION_READ_COMMITTED"); factory.setTransactionPropagationBehaviorName("PROPAGATION_REQUIRED"); return factory.createObject(); } /** * Override this if you wish to do something with the database while it is in its "upgrading" state - e.g. populate with test data * at a particular version to test the data transformations on the next version upgrades. */ public void tablesCreatedOrUpgraded(final String version, final String prefix) { // No action } @Override public String toString() { return getDatabaseType() + ":" + getTargetVersion(); } }
package gov.nih.nci.cadsr.persist.de; import gov.nih.nci.cadsr.cdecurate.database.SQLHelper; import gov.nih.nci.cadsr.persist.common.BaseVO; import gov.nih.nci.cadsr.persist.common.DBConstants; import gov.nih.nci.cadsr.persist.common.ACBase; import gov.nih.nci.cadsr.persist.exception.DBException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.log4j.Logger; @SuppressWarnings("unchecked") public class Data_Elements_Mgr extends ACBase { private Logger logger = Logger.getLogger(this.getClass()); /** * Inserts a single row of Data Element in data_elements_view table and returns primary key de_IDSEQ * * @param deVO * @param conn * @return * @throws DBException */ public String insert(BaseVO vo, Connection conn) throws DBException { DeVO deVO = (DeVO) vo; PreparedStatement statement = null; String primaryKey = null; // generate de_IDSEQ(primary key) deVO.setDe_IDSEQ(this.generatePrimaryKey(conn)); deVO.setDeleted_ind(DBConstants.RECORD_DELETED_NO); deVO.setDate_created(new java.sql.Timestamp(new java.util.Date().getTime())); try { String sql = "insert into data_elements_view ( de_idseq, version, conte_idseq, preferred_name, vd_idseq, dec_idseq, " + "preferred_definition, asl_name, long_name, latest_version_ind, deleted_ind, " + "date_created, begin_date, created_by, end_date, date_modified, modified_by, change_note, origin) " + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; int column = 0; statement = conn.prepareStatement(sql); statement.setString(++column, deVO.getDe_IDSEQ()); statement.setDouble(++column, deVO.getVersion()); statement.setString(++column, deVO.getConte_IDSEQ()); statement.setString(++column, deVO.getPrefferred_name()); statement.setString(++column, deVO.getVd_IDSEQ()); statement.setString(++column, deVO.getDec_IDSEQ()); statement.setString(++column, deVO.getPrefferred_def()); statement.setString(++column, deVO.getAsl_name()); statement.setString(++column, deVO.getLong_name()); statement.setString(++column, deVO.getLastest_version_ind()); statement.setString(++column, deVO.getDeleted_ind()); statement.setTimestamp(++column, deVO.getDate_created()); statement.setTimestamp(++column, deVO.getBegin_date()); statement.setString(++column, deVO.getCreated_by()); statement.setTimestamp(++column, deVO.getEnd_date()); statement.setTimestamp(++column, deVO.getDate_modified()); statement.setString(++column, deVO.getModified_by()); statement.setString(++column, deVO.getChange_note()); statement.setString(++column, deVO.getOrigin()); int count = statement.executeUpdate(); if (count == 0) { throw new Exception("Unable to insert the record"); } else { primaryKey = deVO.getDe_IDSEQ(); if (logger.isDebugEnabled()) { logger.debug("Inserted DE"); logger.debug("de_IDSEQ(primary key ) } } } catch (Exception e) { logger.error("Error inserting Data Element " + e); errorList.add(DeErrorCodes.API_DE_500); throw new DBException(errorList); } finally { statement = SQLHelper.closePreparedStatement(statement); } return primaryKey; } /** * Updates single row of Data Element * * @param deVO * @param conn * @throws DBException */ public void update(BaseVO vo, Connection conn) throws DBException { DeVO deVO = (DeVO) vo; Statement statement = null; deVO.setDeleted_ind(DBConstants.RECORD_DELETED_NO); deVO.setDate_modified(new java.sql.Timestamp(new java.util.Date().getTime())); // logger.debug("updateClient()"); try { StringBuffer sql = new StringBuffer(); sql.append(" update data_elements_view "); sql.append("set date_modified = timestamp '" + deVO.getDate_modified() +"'"); sql.append(", modified_by = '" + deVO.getModified_by() + "'"); sql.append(", deleted_ind = '" + deVO.getDeleted_ind() + "'"); if (deVO.getConte_IDSEQ() != null) { sql.append(", conte_idseq = '" + deVO.getConte_IDSEQ() + "'"); } if (deVO.getPrefferred_name() != null) { sql.append(", preferred_name = '" + deVO.getPrefferred_name() + "'"); } if (deVO.getVd_IDSEQ() != null) { sql.append(", vd_idseq = '" + deVO.getVd_IDSEQ() + "'"); } if (deVO.getDec_IDSEQ() != null) { sql.append(", dec_idseq = '" + deVO.getDec_IDSEQ() + "'"); } if (deVO.getPrefferred_def() != null) { sql.append(", preferred_definition = '" + deVO.getPrefferred_def().replace("'","\"") + "'"); } if (deVO.getAsl_name() != null) { sql.append(", asl_name = '" + deVO.getAsl_name() + "'"); } if (deVO.getLong_name() != null) { // allow null update if (deVO.getLong_name() == "") { sql.append(", long_name = ''"); } else { sql.append(", long_name = '" + deVO.getLong_name() + "'"); } } if (deVO.getLastest_version_ind() != null) { sql.append(", latest_version_ind = '" + deVO.getLastest_version_ind() + "'"); } if (deVO.getBegin_date() != null){ sql.append(", begin_date = timestamp '" + deVO.getBegin_date() + "'"); }else // allow null updates sql.append(", begin_date = ''"); if (deVO.getEnd_date() != null){ sql.append(", end_date = timestamp '" + deVO.getEnd_date() + "'"); }else // allow null updates sql.append(", end_date = ''"); if (deVO.getChange_note() != null) { // allow null updates if (deVO.getChange_note() == "") { sql.append(", change_note = ''"); } else { sql.append(", change_note = '" + deVO.getChange_note().replace("'","\"") + "'"); } } if (deVO.getOrigin() != null) { // allow null updates if (deVO.getOrigin() == "") { sql.append(", origin= ''"); } else { sql.append(", origin= '" + deVO.getOrigin() + "'"); } } sql.append(" where de_idseq = '" + deVO.getDe_IDSEQ() + "'"); statement = conn.createStatement(); int result = statement.executeUpdate(sql.toString()); if (result == 0) { throw new Exception("Unable to Update"); } } catch (Exception e) { logger.error("Error updating Data Element " + deVO.getDe_IDSEQ() + e); errorList.add(DeErrorCodes.API_DE_501); throw new DBException(errorList); } finally { statement = SQLHelper.closeStatement(statement); } } /** * Deletes single row of Data Element * * @param de_IDSEQ * @param modified_by * @param conn * @throws DBException */ public void delete(String idseq, String modified_by, Connection conn) throws DBException { PreparedStatement statement = null; try { String sql = "update data_elements_view set deleted_ind = ?, modified_by = ?,date_modified = ? where de_idseq = ? "; int column = 0; statement = conn.prepareStatement(sql); statement.setString(++column, DBConstants.RECORD_DELETED_YES); statement.setString(++column, modified_by); statement.setDate(++column, new java.sql.Date(new java.util.Date().getTime())); statement.setString(++column, idseq); int code = statement.executeUpdate(); if (code < 0) { throw new Exception("Unable to delete the DE"); } else { if (logger.isDebugEnabled()) { logger.debug("Deleted DE"); } } } catch (Exception e) { logger.error("Error deleting Data Element " + idseq + e); errorList.add(DeErrorCodes.API_DE_502); throw new DBException(errorList); } finally { statement = SQLHelper.closePreparedStatement(statement); } } /** * Returns the version of a DE based on preferred name and context * * @param preferred_name * @param conte_IDSEQ * @param conn * @return * @throws DBException */ public double getDeVersion(String preferred_name, String conte_IDSEQ, Connection conn) throws DBException { StringBuffer sql = new StringBuffer(); sql.append("select max(version) from data_elements where"); sql.append(" cde_id = ( "); sql.append("select distinct(cde_id) from data_elements "); sql.append("where preferred_name = '").append(preferred_name).append("' and conte_idseq = '").append(conte_IDSEQ).append("' )"); double version = this.getVersion(sql.toString(), conn); return version; } /** * Returns the version of a DE based on deIDSEQ * * @param deIDSEQ * @param conn * @return * @throws DBException */ public double getDeVersionByIdseq(String deIDSEQ, Connection conn) throws DBException { PreparedStatement stmt = null; ResultSet rs = null; double version = 0; try { String sql = "select version from data_elements_view where de_idseq = ?"; stmt = conn.prepareStatement(sql.toString()); stmt.setString(1, deIDSEQ); rs = stmt.executeQuery(); while (rs.next()) { version = rs.getDouble(1); } } catch (SQLException e) { logger.error(DBException.DEFAULT_ERROR_MSG + " in getDeVersionByIdseq() method in Data_Elements_Mgr " + e); errorList.add(DeErrorCodes.API_DE_000); throw new DBException(errorList); } finally { rs = SQLHelper.closeResultSet(rs); stmt = SQLHelper.closePreparedStatement(stmt); } return version; } /** * Returns asl_name(work-flow status) of DE based on the deIDSEQ * * @param deIDSEQ * @param conn * @return * @throws DBException */ public String getDeAslNameByIdseq(String deIDSEQ, Connection conn) throws DBException { PreparedStatement stmt = null; ResultSet rs = null; String aslName = null; try { String sql = "select asl_name from data_elements_view where de_idseq = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deIDSEQ); rs = stmt.executeQuery(); while (rs.next()) { aslName = rs.getString(1); } } catch (SQLException e) { logger.error(DBException.DEFAULT_ERROR_MSG + "in getDeAslNameByIdseq() of Data_Element_Manager class " + e); errorList.add(DeErrorCodes.API_DE_000); throw new DBException(errorList); } finally { rs = SQLHelper.closeResultSet(rs); stmt = SQLHelper.closePreparedStatement(stmt); } return aslName; } /** * Returns DE based on the de_IDSEQ * * @param de_IDSEQ * @param conn * @return * @throws DBException */ public DeVO getDe(String de_IDSEQ, Connection conn) throws DBException { PreparedStatement stmt = null; ResultSet rs = null; DeVO deVO = null; try { String sql = "select * from data_elements_view where de_idseq = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, de_IDSEQ); rs = stmt.executeQuery(); while (rs.next()) { deVO = new DeVO(); deVO.setDe_IDSEQ(rs.getString("DE_IDSEQ")); deVO.setVersion(rs.getDouble("VERSION")); deVO.setConte_IDSEQ(rs.getString("CONTE_IDSEQ")); deVO.setPrefferred_name(rs.getString("PREFERRED_NAME")); deVO.setVd_IDSEQ(rs.getString("VD_IDSEQ")); deVO.setDec_IDSEQ(rs.getString("DEC_IDSEQ")); deVO.setPrefferred_def(rs.getString("PREFERRED_DEFINITION")); deVO.setAsl_name(rs.getString("ASL_NAME")); deVO.setLong_name(rs.getString("LONG_NAME")); deVO.setLastest_version_ind(rs.getString("LATEST_VERSION_IND")); deVO.setDeleted_ind(rs.getString("DELETED_IND")); deVO.setDate_created(rs.getTimestamp("DATE_CREATED")); deVO.setBegin_date(rs.getTimestamp("BEGIN_DATE")); deVO.setCreated_by(rs.getString("CREATED_BY")); deVO.setEnd_date(rs.getTimestamp("END_DATE")); deVO.setDate_modified(rs.getTimestamp("DATE_MODIFIED")); deVO.setModified_by(rs.getString("MODIFIED_BY")); deVO.setChange_note(rs.getString("CHANGE_NOTE")); } } catch (SQLException e) { logger.error(DBException.DEFAULT_ERROR_MSG + " in getDe() method of Data_Elements_Mgr class " + e); throw new DBException("API_DE_000"); } finally { try { rs = SQLHelper.closeResultSet(rs); stmt = SQLHelper.closePreparedStatement(stmt); } catch (Exception e) { } } return deVO; } /** * This method updates so that all other versions have the indicator set to * 'No' if latest_version_indicator = 'yes' * * @param de_IDSEQ * @param conn * @throws DBException */ public void setDeLatestVersionIndicator(String de_IDSEQ, Connection conn) throws DBException { StringBuffer sql = new StringBuffer(); sql.append("update data_elements_view set latest_version_ind = '").append(DBConstants.RECORD_DELETED_NO).append("'"); sql.append(" where de_idseq <> '").append(de_IDSEQ).append("' and cde_id = ( "); sql.append("select cde_id from data_elements_view "); sql.append("where de_idseq = '").append(de_IDSEQ).append("' )"); this.setAcLatesVersionIndicator(sql.toString(), conn); } /** * This method returns the sourceIDSEQ * * @param preferred_name * @param conte_IDSEQ * @param conn * @return * @throws DBException */ public String getSourceIdseq(String preferred_name, String conte_IDSEQ, Connection conn) throws DBException { String sourceIDSEQ = null; StringBuffer sql = new StringBuffer(); double version = this.getDeVersion(preferred_name, conte_IDSEQ, conn); if (version > 0) { sql.append("select de_idseq from data_elements"); sql.append("where (version = '").append(version).append("') and (cde_id = ("); sql.append("select distinct(cde_id) from data_elements "); sql.append("where (preferred_name = '").append(preferred_name) .append("') and (conte_idseq = '").append(conte_IDSEQ) .append("') )"); } return sourceIDSEQ; } }
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.CaNanoLabComparators; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.domain.ProtocolFile; import gov.nih.nci.calab.domain.Protocol; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import org.apache.struts.util.LabelValueBean; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.95 2007-05-14 13:00:50 chenhang Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retrieving all unmasked aliquots for use in views create run, use aliquot * and create aliquot. * * @return a Map between sample name and its associated unmasked aliquots * @throws Exception */ public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots() throws Exception { SortedSet<AliquotBean> aliquots = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>(); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; AliquotBean aliquot = new AliquotBean(StringUtils .convertToString(info[0]), StringUtils .convertToString(info[1]), CaNanoLabConstants.ACTIVE_STATUS); String sampleName = (String) info[2]; if (sampleAliquots.get(sampleName) != null) { aliquots = (SortedSet<AliquotBean>) sampleAliquots .get(sampleName); } else { aliquots = new TreeSet<AliquotBean>( new CaNanoLabComparators.AliquotBeanComparator()); sampleAliquots.put(sampleName, aliquots); } aliquots.add(aliquot); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return sampleAliquots; } /** * * @return a map between sample name and its sample containers * @throws Exception */ public Map<String, SortedSet<ContainerBean>> getAllSampleContainers() throws Exception { SortedSet<ContainerBean> containers = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>(); try { ida.open(); String hqlString = "select container, container.sample.name from SampleContainer container"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; if (!(info[0] instanceof Aliquot)) { ContainerBean container = new ContainerBean( (SampleContainer) info[0]); String sampleName = (String) info[1]; if (sampleContainers.get(sampleName) != null) { containers = (SortedSet<ContainerBean>) sampleContainers .get(sampleName); } else { containers = new TreeSet<ContainerBean>( new CaNanoLabComparators.ContainerBeanComparator()); sampleContainers.put(sampleName, containers); } containers.add(container); } } } catch (Exception e) { logger.error("Error in retrieving all containers", e); throw new RuntimeException("Error in retrieving all containers"); } finally { ida.close(); } return sampleContainers; } /** * Retrieving all sample types. * * @return a list of all sample types */ public List<String> getAllSampleTypes() throws Exception { // Detail here // Retrieve data from Sample_Type table List<String> sampleTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name"; List results = ida.search(hqlString); for (Object obj : results) { sampleTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample types", e); throw new RuntimeException("Error in retrieving all sample types"); } finally { ida.close(); } return sampleTypes; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { List<MeasureUnit> units = getAllMeasureUnits(); List<StorageElement> storageElements = getAllStorageElements(); List<String> quantityUnits = new ArrayList<String>(); List<String> concentrationUnits = new ArrayList<String>(); List<String> volumeUnits = new ArrayList<String>(); List<String> rooms = new ArrayList<String>(); List<String> freezers = new ArrayList<String>(); List<String> shelves = new ArrayList<String>(); List<String> boxes = new ArrayList<String>(); for (MeasureUnit unit : units) { if (unit.getType().equalsIgnoreCase("Quantity")) { quantityUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Volume")) { volumeUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Concentration")) { concentrationUnits.add(unit.getName()); } } for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room") && !rooms.contains(storageElement.getLocation())) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer") && !freezers.contains(storageElement.getLocation())) { freezers.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Shelf") && !shelves.contains(storageElement.getLocation())) { shelves.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Box") && !boxes.contains(storageElement.getLocation())) { boxes.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers, shelves, boxes); return containerInfo; } public List<String> getAllSampleContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample container types", e); throw new RuntimeException( "Error in retrieving all sample container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } public List<String> getAllAliquotContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot container types", e); throw new RuntimeException( "Error in retrieving all aliquot container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } private List<MeasureUnit> getAllMeasureUnits() throws Exception { List<MeasureUnit> units = new ArrayList<MeasureUnit>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit"; List results = ida.search(hqlString); for (Object obj : results) { units.add((MeasureUnit) obj); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return units; } private List<StorageElement> getAllStorageElements() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer', 'Shelf', 'Box') and location!='Other'"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names DELETE */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } Collections.sort(samples, new CaNanoLabComparators.SampleBeanComparator()); return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * * @return a map between assay type and its assays * @throws Exception */ public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays() throws Exception { Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); SortedSet<AssayBean> assays = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); if (assayTypeAssays.get(assay.getAssayType()) != null) { assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay .getAssayType()); } else { assays = new TreeSet<AssayBean>( new CaNanoLabComparators.AssayBeanComparator()); assayTypeAssays.put(assay.getAssayType(), assays); } assays.add(assay); } } catch (Exception e) { // TODO: temp for debuging use. remove later e.printStackTrace(); logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayTypeAssays; } /** * * @return all sample sources */ public List<String> getAllSampleSources() throws Exception { List<String> sampleSources = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select source.organizationName from Source source order by source.organizationName"; List results = ida.search(hqlString); for (Object obj : results) { sampleSources.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return sampleSources; } /** * * @return a map between sample source and samples with unmasked aliquots * @throws Exception */ public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots() throws Exception { Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null"; List results = ida.search(hqlString); SortedSet<SampleBean> samples = null; for (Object obj : results) { SampleBean sample = new SampleBean((Sample) obj); if (sampleSourceSamples.get(sample.getSampleSource()) != null) { // TODO need to make sample source a required field if (sample.getSampleSource().length() > 0) { samples = (SortedSet<SampleBean>) sampleSourceSamples .get(sample.getSampleSource()); } } else { samples = new TreeSet<SampleBean>( new CaNanoLabComparators.SampleBeanComparator()); if (sample.getSampleSource().length() > 0) { sampleSourceSamples.put(sample.getSampleSource(), samples); } } samples.add(sample); } } catch (Exception e) { logger.error( "Error in retrieving sample beans with unmasked aliquots ", e); throw new RuntimeException( "Error in retrieving all sample beans with unmasked aliquots. "); } finally { ida.close(); } return sampleSourceSamples; } public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj : results) { sampleSOPs.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return all methods for creating aliquots */ public List<LabelValueBean> getAliquotCreateMethods() throws Exception { List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'"; List results = ida.search(hqlString); for (Object obj : results) { String sopName = (String) ((Object[]) obj)[0]; String sopURI = (String) ((Object[]) obj)[1]; String sopURL = (sopURI == null) ? "" : sopURI; createMethods.add(new LabelValueBean(sopName, sopURL)); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return createMethods; } /** * * @return all source sample IDs */ public List<String> getAllSourceSampleIds() throws Exception { List<String> sourceSampleIds = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId"; List results = ida.search(hqlString); for (Object obj : results) { sourceSampleIds.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all source sample IDs", e); throw new RuntimeException( "Error in retrieving all source sample IDs"); } finally { ida.close(); } return sourceSampleIds; } public Map<String, SortedSet<String>> getAllParticleTypeParticles() throws Exception { // TODO fill in actual database query. Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); try { ida.open(); // String hqlString = "select particle.type, particle.name from // Nanoparticle particle"; String hqlString = "select particle.type, particle.name from Nanoparticle particle where size(particle.characterizationCollection) = 0"; List results = ida.search(hqlString); SortedSet<String> particleNames = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; String particleType = (String) objArray[0]; String particleName = (String) objArray[1]; if (particleType != null) { // check if the particle already has visibility group // assigned, if yes, do NOT add to the list List<String> groups = userService.getAccessibleGroups( particleName, CaNanoLabConstants.CSM_READ_ROLE); if (groups.size() == 0) { if (particleTypeParticles.get(particleType) != null) { particleNames = (SortedSet<String>) particleTypeParticles .get(particleType); } else { particleNames = new TreeSet<String>( new CaNanoLabComparators.SortableNameComparator()); particleTypeParticles.put(particleType, particleNames); } particleNames.add(particleName); } } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return particleTypeParticles; } /* public String[] getAllParticleFunctions() { String[] functions = new String[] { "Therapeutic", "Targeting", "Diagnostic Imaging", "Diagnostic Reporting" }; return functions; } */ public Map<String, String> getAllParticleFunctions() { Map<String, String> functionsMap=new HashMap<String, String>(); functionsMap.put("Therapeutic", "Therapeutic"); functionsMap.put("Targeting", "Targeting"); functionsMap.put("Diagnostic Imaging", "Imaging"); functionsMap.put("Diagnostic Reporting", "Reporting"); return functionsMap; } public String[] getAllCharacterizationTypes() { String[] charTypes = new String[] { "Physical Characterization", "In Vitro Characterization", "In Vivo Characterization" }; return charTypes; } public String[] getAllDendrimerCores() { String[] cores = new String[] { "Diamine", "Ethyline" }; return cores; } public String[] getAllDendrimerSurfaceGroupNames() throws Exception { SortedSet<String> names = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct surfaceGroup.name from SurfaceGroup surfaceGroup where surfaceGroup.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { names.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Surface Group name."); throw new RuntimeException( "Problem to retrieve all Surface Group name. "); } finally { ida.close(); } names.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_SURFACE_GROUP_NAMES)); names.add(CaNanoLabConstants.OTHER); return (String[]) names.toArray(new String[0]); } public String[] getAllDendrimerBranches() throws Exception { SortedSet<String> branches = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.branch from DendrimerComposition dendrimer where dendrimer.branch is not null"; List results = ida.search(hqlString); for (Object obj : results) { branches.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Branches."); throw new RuntimeException( "Problem to retrieve all Dendrimer Branches. "); } finally { ida.close(); } branches.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_BRANCHES)); branches.add(CaNanoLabConstants.OTHER); return (String[]) branches.toArray(new String[0]); } public String[] getAllDendrimerGenerations() throws Exception { SortedSet<String> generations = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.generation from DendrimerComposition dendrimer where dendrimer.generation is not null "; List results = ida.search(hqlString); for (Object obj : results) { generations.add(obj.toString()); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Generations."); throw new RuntimeException( "Problem to retrieve all Dendrimer Generations. "); } finally { ida.close(); } generations.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_GENERATIONS)); generations.add(CaNanoLabConstants.OTHER); return (String[]) generations.toArray(new String[0]); } public String[] getAllMetalCompositions() { String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" }; return compositions; } public String[] getAllPolymerInitiators() throws Exception { SortedSet<String> initiators = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct polymer.initiator from PolymerComposition polymer where polymer.initiator is not null "; List results = ida.search(hqlString); for (Object obj : results) { initiators.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Polymer Initiator."); throw new RuntimeException( "Problem to retrieve all Polymer Initiator. "); } finally { ida.close(); } initiators.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_POLYMER_INITIATORS)); initiators.add(CaNanoLabConstants.OTHER); return (String[]) initiators.toArray(new String[0]); } public List<String> getAllParticleSources() throws Exception { // TODO fill in db code return getAllSampleSources(); } public String getParticleClassification(String particleType) { String classification = CaNanoLabConstants.PARTICLE_CLASSIFICATION_MAP .get(particleType); return classification; } /** * * @return a map between a characterization type and its child * characterizations. */ public Map<String, String[]> getCharacterizationTypeCharacterizations() { Map<String, String[]> charTypeChars = new HashMap<String, String[]>(); String[] physicalChars = new String[] { CaNanoLabConstants.PHYSICAL_COMPOSITION, CaNanoLabConstants.PHYSICAL_SIZE, CaNanoLabConstants.PHYSICAL_MOLECULAR_WEIGHT, CaNanoLabConstants.PHYSICAL_MORPHOLOGY, CaNanoLabConstants.PHYSICAL_SOLUBILITY, CaNanoLabConstants.PHYSICAL_SURFACE, CaNanoLabConstants.PHYSICAL_PURITY, // CaNanoLabConstants.PHYSICAL_STABILITY, // CaNanoLabConstants.PHYSICAL_FUNCTIONAL, CaNanoLabConstants.PHYSICAL_SHAPE }; charTypeChars.put("physical", physicalChars); String[] toxChars = new String[] { CaNanoLabConstants.TOXICITY_OXIDATIVE_STRESS, CaNanoLabConstants.TOXICITY_ENZYME_FUNCTION }; charTypeChars.put("toxicity", toxChars); String[] cytoToxChars = new String[] { CaNanoLabConstants.CYTOTOXICITY_CELL_VIABILITY, CaNanoLabConstants.CYTOTOXICITY_CASPASE3_ACTIVIATION }; charTypeChars.put("cytoTox", cytoToxChars); String[] bloodContactChars = new String[] { CaNanoLabConstants.BLOODCONTACTTOX_PLATE_AGGREGATION, CaNanoLabConstants.BLOODCONTACTTOX_HEMOLYSIS, CaNanoLabConstants.BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING, CaNanoLabConstants.BLOODCONTACTTOX_COAGULATION }; charTypeChars.put("bloodContactTox", bloodContactChars); String[] immuneCellFuncChars = new String[] { CaNanoLabConstants.IMMUNOCELLFUNCTOX_OXIDATIVE_BURST, CaNanoLabConstants.IMMUNOCELLFUNCTOX_CHEMOTAXIS, CaNanoLabConstants.IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION, CaNanoLabConstants.IMMUNOCELLFUNCTOX_PHAGOCYTOSIS, CaNanoLabConstants.IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION, CaNanoLabConstants.IMMUNOCELLFUNCTOX_CFU_GM, CaNanoLabConstants.IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION, CaNanoLabConstants.IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY }; charTypeChars.put("immuneCellFuncTox", immuneCellFuncChars); // String[] metabolicChars = new String[] { // CaNanoLabConstants.METABOLIC_STABILITY_CYP450, // CaNanoLabConstants.METABOLIC_STABILITY_GLUCURONIDATION_SULPHATION, // CaNanoLabConstants.METABOLIC_STABILITY_ROS }; // charTypeChars.put("metabolicStabilityTox", metabolicChars); return charTypeChars; } public List<LabelValueBean> getAllInstrumentTypeAbbrs() throws Exception { List<LabelValueBean> instrumentTypeAbbrs = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, instrumentType.abbreviation from InstrumentType instrumentType where instrumentType.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) { Object[] objs = (Object[]) obj; String label = ""; if (objs[1] != null) { label = (String) objs[0] + "(" + objs[1] + ")"; } else { label = (String) objs[0]; } instrumentTypeAbbrs.add(new LabelValueBean(label, (String) objs[0])); } } } catch (Exception e) { logger.error("Problem to retrieve all instrumentTypes. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } instrumentTypeAbbrs.add(new LabelValueBean(CaNanoLabConstants.OTHER, CaNanoLabConstants.OTHER)); return instrumentTypeAbbrs; } public Map<String, SortedSet<String>> getAllInstrumentManufacturers() throws Exception { Map<String, SortedSet<String>> instrumentManufacturers = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, manufacturer.name from InstrumentType instrumentType join instrumentType.manufacturerCollection manufacturer "; List results = ida.search(hqlString); SortedSet<String> manufacturers = null; for (Object obj : results) { String instrumentType = ((Object[]) obj)[0].toString(); String manufacturer = ((Object[]) obj)[1].toString(); if (instrumentManufacturers.get(instrumentType) != null) { manufacturers = (SortedSet<String>) instrumentManufacturers .get(instrumentType); } else { manufacturers = new TreeSet<String>(); instrumentManufacturers.put(instrumentType, manufacturers); } manufacturers.add(manufacturer); } List allResult = ida .search("select manufacturer.name from Manufacturer manufacturer where manufacturer.name is not null"); SortedSet<String> allManufacturers = null; allManufacturers = new TreeSet<String>(); for (Object obj : allResult) { String name = (String) obj; allManufacturers.add(name); } instrumentManufacturers.put(CaNanoLabConstants.OTHER, allManufacturers); } catch (Exception e) { logger .error("Problem to retrieve manufacturers for intrument types " + e); throw new RuntimeException( "Problem to retrieve manufacturers for intrument types."); } finally { ida.close(); } return instrumentManufacturers; } public String[] getSizeDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Volume", "Intensity", "Number" }; return graphTypes; } public String[] getMolecularWeightDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Volume", "Mass", "Number" }; return graphTypes; } public String[] getMorphologyDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getShapeDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getStabilityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getPurityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getSolubilityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getAllMorphologyTypes() throws Exception { SortedSet<String> morphologyTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct morphology.type from Morphology morphology"; List results = ida.search(hqlString); for (Object obj : results) { morphologyTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all morphology types."); throw new RuntimeException( "Problem to retrieve all morphology types."); } finally { ida.close(); } morphologyTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_MORPHOLOGY_TYPES)); morphologyTypes.add(CaNanoLabConstants.OTHER); return (String[]) morphologyTypes.toArray(new String[0]); } public String[] getAllShapeTypes() throws Exception { SortedSet<String> shapeTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct shape.type from Shape shape where shape.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { shapeTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all shape types."); throw new RuntimeException("Problem to retrieve all shape types."); } finally { ida.close(); } shapeTypes .addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_SHAPE_TYPES)); shapeTypes.add(CaNanoLabConstants.OTHER); return (String[]) shapeTypes.toArray(new String[0]); } public List<String> getAllProtocolNames() throws Exception { List<String> protocolNames = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocol.name from Protocol protocol where protocol.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { protocolNames.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names."); throw new RuntimeException("Problem to retrieve all protocol names."); } finally { ida.close(); } return protocolNames; } public Map<String, List<String>> getAllProtocolNameVersion() throws Exception{ Map<String, List<String>> nameVersions = new HashMap<String, List<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocolFile, protocolFile.protocol.name from ProtocolFile protocolFile"; List results = ida.search(hqlString); for (Object obj : results) { Object[] array = (Object[])obj; Object key = null; Object value = null; for (int i = 0; i < array.length; i++){ if (array[i] instanceof String){ key = array[i]; } else if (array[i] instanceof ProtocolFile){ value = array[i]; } } if (nameVersions.containsKey(key)){ List<String> localList = nameVersions.get(key); localList.add(((ProtocolFile)value).getVersion()); } else { List<String> localList = new ArrayList<String>(); localList.add(((ProtocolFile)value).getVersion()); nameVersions.put((String)key, localList); } //protocolNames.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names."); throw new RuntimeException("Problem to retrieve all protocol names."); } finally { ida.close(); } return nameVersions; } public List<String> getAllProtocolTypes() throws Exception { List<String> protocolTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct protocol.type from Protocol protocol where protocol.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { protocolTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol types."); throw new RuntimeException("Problem to retrieve all protocol types."); } finally { ida.close(); } return protocolTypes; } public Map<String, List<String>> getAllProtocolNameTypes() throws Exception { Map<String, List<String>> protocolNameTypes = new HashMap<String, List<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocol from Protocol protocol"; List results = ida.search(hqlString); for (Object obj : results) { Protocol protocol = (Protocol)obj; if (protocolNameTypes.containsKey(protocol.getType())){ List<String> list = protocolNameTypes.get(protocol.getType()); list.add(protocol.getName()); } else { List<String> list = new ArrayList<String>(); list.add(protocol.getName()); protocolNameTypes.put(protocol.getType(), list); } //protocolNames.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names and types."); throw new RuntimeException("Problem to retrieve all protocol names and types."); } finally { ida.close(); } return protocolNameTypes; } public String[] getAllStressorTypes() { String[] stressorTypes = new String[] { "Thermal", "PH", "Freeze thaw", "Photo", "Centrifugation", "Lyophilization", "Chemical", "Other" }; return stressorTypes; } public String[] getAllAreaMeasureUnits() { String[] areaUnit = new String[] { "sq nm" }; return areaUnit; } public String[] getAllChargeMeasureUnits() { String[] chargeUnit = new String[] { "a.u", "aC", "Ah", "C", "esu", "Fr", "statC" }; return chargeUnit; } public String[] getAllDensityMeasureUnits() { String[] densityUnits = new String[] { "kg/L" }; return densityUnits; } public String[] getAllControlTypes() { String[] controlTypes = new String[] { " ", "Positive", "Negative" }; return controlTypes; } public String[] getAllConditionTypes() { String[] conditionTypes = new String[] { "Particle Concentration", "Temperature", "Time" }; return conditionTypes; } public Map<String, String[]> getAllAgentTypes() { Map<String, String[]> agentTypes = new HashMap<String, String[]>(); String[] therapeuticsAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Therapeutic", therapeuticsAgentTypes); String[] targetingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Targeting", targetingAgentTypes); String[] imagingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Imaging", imagingAgentTypes); String[] reportingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Reporting", reportingAgentTypes); return agentTypes; } public Map<String, String[]> getAllAgentTargetTypes() { Map<String, String[]> agentTargetTypes = new HashMap<String, String[]>(); String[] targetTypes = new String[] { "Receptor", "Antigen", "Other" }; String[] targetTypes1 = new String[] { "Receptor", "Other" }; String[] targetTypes2 = new String[] { "Other" }; agentTargetTypes.put("Small Molecule", targetTypes2); agentTargetTypes.put("Peptide", targetTypes1); agentTargetTypes.put("Antibody", targetTypes); agentTargetTypes.put("DNA", targetTypes1); agentTargetTypes.put("Probe", targetTypes1); agentTargetTypes.put("Other", targetTypes2); agentTargetTypes.put("Image Contrast Agent", targetTypes2); return agentTargetTypes; } public String[] getAllTimeUnits() { String[] timeUnits = new String[] { "hours", "days", "months" }; return timeUnits; } public String[] getAllTemperatureUnits() { String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; return temperatureUnits; } public String[] getAllConcentrationUnits() { String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul" }; return concentrationUnits; } public Map<String, String[]> getAllConditionUnits() { Map<String, String[]> conditionTypeUnits = new HashMap<String, String[]>(); String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul", }; String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; String[] timeUnits = new String[] { "hours", "days", "months" }; conditionTypeUnits.put("Particle Concentration", concentrationUnits); conditionTypeUnits.put("Time", timeUnits); conditionTypeUnits.put("Temperature", temperatureUnits); return conditionTypeUnits; } public String[] getAllCellLines() throws Exception { SortedSet<String> cellLines = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct cellViability.cellLine, caspase.cellLine from CellViability cellViability, Caspase3Activation caspase"; List results = ida.search(hqlString); for (Object obj : results) { // cellLines.add((String) obj); Object[] objects = (Object[]) obj; for (Object object : objects) { if (object != null) { cellLines.add((String) object); } } } } catch (Exception e) { logger.error("Problem to retrieve all Cell lines."); throw new RuntimeException("Problem to retrieve all Cell lines."); } finally { ida.close(); } cellLines.addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_CELLLINES)); cellLines.add(CaNanoLabConstants.OTHER); return (String[]) cellLines.toArray(new String[0]); } public String[] getAllActivationMethods() { String[] activationMethods = new String[] { "NMR", "MRI", "Radiation", "Ultrasound", "Ultraviolet Light" }; return activationMethods; } public List<LabelValueBean> getAllSpecies() throws Exception { List<LabelValueBean> species = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); species.add(new LabelValueBean("", "")); try { for (int i = 0; i < CaNanoLabConstants.SPECIES_COMMON.length; i++) { String specie = CaNanoLabConstants.SPECIES_COMMON[i]; species.add(new LabelValueBean(specie, specie)); } } catch (Exception e) { logger.error("Problem to retrieve all species. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return species; } public String[] getAllReportTypes() { String[] allReportTypes = new String[] { CaNanoLabConstants.REPORT, CaNanoLabConstants.ASSOCIATED_FILE }; return allReportTypes; } }
package gov.nih.nci.calab.service.security; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.particle.ParticleBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.AuthorizationManager; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.UserProvisioningManager; import gov.nih.nci.security.authentication.helper.EncryptedRDBMSHelper; import gov.nih.nci.security.authorization.domainobjects.Group; import gov.nih.nci.security.authorization.domainobjects.ProtectionElement; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroupRoleContext; import gov.nih.nci.security.authorization.domainobjects.Role; import gov.nih.nci.security.authorization.domainobjects.User; import gov.nih.nci.security.dao.GroupSearchCriteria; import gov.nih.nci.security.dao.ProtectionElementSearchCriteria; import gov.nih.nci.security.dao.ProtectionGroupSearchCriteria; import gov.nih.nci.security.dao.RoleSearchCriteria; import gov.nih.nci.security.dao.SearchCriteria; import gov.nih.nci.security.dao.UserSearchCriteria; import gov.nih.nci.security.exceptions.CSException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpSession; import org.apache.struts.tiles.beans.MenuItem; /** * This class takes care of authentication and authorization of a user and group * * @author Pansu * */ public class UserService { private AuthenticationManager authenticationManager = null; private AuthorizationManager authorizationManager = null; private UserProvisioningManager userManager = null; private String applicationName = null; public UserService(String applicationName) throws CSException { this.applicationName = applicationName; this.authenticationManager = SecurityServiceProvider .getAuthenticationManager(applicationName); this.authorizationManager = SecurityServiceProvider .getAuthorizationManager(applicationName); this.userManager = SecurityServiceProvider .getUserProvisioningManager(applicationName); } public UserBean getUserBean(String userLogin) { User user = authorizationManager.getUser(userLogin); return new UserBean(user); // userManger.getUser(userLoginId); } /** * Check whether the given user is the admin of the application. * * @param user * @return */ public boolean isAdmin(String user) { boolean adminStatus = authorizationManager.checkOwnership(user, applicationName); return adminStatus; } /** * Check whether the given user belongs to the given group. * * @param user * @param groupName * @return * @throws Exception */ public boolean isUserInGroup(UserBean user, String groupName) throws Exception { Set groups = userManager.getGroups(user.getUserId()); for (Object obj : groups) { Group group = (Group) obj; if (group.getGroupName().equalsIgnoreCase(groupName) || group.getGroupName().startsWith(groupName)) { return true; } } return false; } /** * Check whether the given user has the given privilege on the given * protection element * * @param user * @param protectionElementObjectId * @param privilege * @return * @throws CSException */ public boolean checkPermission(UserBean user, String protectionElementObjectId, String privilege) throws CSException { boolean status = false; status = authorizationManager.checkPermission(user.getLoginName(), protectionElementObjectId, privilege); return status; } /** * Check whether the given user has execute privilege on the given * protection element * * @param user * @param protectionElementObjectId * @return * @throws CSException */ public boolean checkExecutePermission(UserBean user, String protectionElementObjectId) throws CSException { return checkPermission(user, protectionElementObjectId, "EXECUTE"); } /** * Check whether the given user has read privilege on the given protection * element * * @param user * @param protectionElementObjectId * @return * @throws CSException */ public boolean checkReadPermission(UserBean user, String protectionElementObjectId) throws CSException { return checkPermission(user, protectionElementObjectId, "READ"); } /** * Check whether user can execute the menuItems in session, each defined as * a protection element using UPT tool. The excluded menuItems are not * checked. * * @param session * @throws CSException */ public void setFilteredMenuItem(HttpSession session) throws CSException { if (session.getAttribute("filteredItems") != null) { return; } List<MenuItem> filteredItems = new ArrayList<MenuItem>(); List<MenuItem> items = new ArrayList<MenuItem>( (List<? extends MenuItem>) session.getAttribute("items")); UserBean user = (UserBean) session.getAttribute("user"); if (user != null) { for (MenuItem item : items) { // make sure change menu item values to lower case since // pre-defined // pes and pgs in the UPT tool are entered as lower case and // CSM API is case sensitive boolean executeStatus = checkExecutePermission(user, item .getValue().toLowerCase()); if (executeStatus) { filteredItems.add(item); } } session.setAttribute("filteredItems", filteredItems); } } /** * Set a new password for the given user login name * * @param loginName * @param newPassword * @throws Exception */ public void updatePassword(String loginName, String newPassword) throws Exception { User user = authorizationManager.getUser(loginName); java.util.Map options = SecurityServiceProvider .getLoginModuleOptions(CalabConstants.CSM_APP_NAME); String encryptedPassword = EncryptedRDBMSHelper.encrypt(newPassword, (String) options.get("hashAlgorithm")); user.setPassword(encryptedPassword); userManager.modifyUser(user); } /** * Get all users in the application * * @return * @throws Exception */ public List<UserBean> getAllUsers() throws Exception { List<UserBean> users = new ArrayList<UserBean>(); User dummy = new User(); dummy.setLoginName("*"); SearchCriteria sc = new UserSearchCriteria(dummy); List results = userManager.getObjects(sc); for (Object obj : results) { User doUser = (User) obj; users.add(new UserBean(doUser)); } return users; } /** * Get all user groups in the application * * @return * @throws Exception */ public List<String> getAllGroups() throws Exception { List<String> groups = new ArrayList<String>(); Group dummy = new Group(); dummy.setGroupName("*"); SearchCriteria sc = new GroupSearchCriteria(dummy); List results = userManager.getObjects(sc); for (Object obj : results) { Group doGroup = (Group) obj; groups.add(doGroup.getGroupName()); } return groups; } /** * Get all user visiblity groups in the application (filtering out all * groups starting with NCL). * * @return * @throws Exception */ public List<String> getAllVisibilityGroups() throws Exception { List<String> groups = getAllGroups(); // filter out the ones starting with NCL List<String> filteredGroups = new ArrayList<String>(); for (String groupName : groups) { if (!groupName.startsWith("NCL")) { filteredGroups.add(groupName); } } return filteredGroups; } public String getApplicationName() { return applicationName; } public AuthenticationManager getAuthenticationManager() { return authenticationManager; } public AuthorizationManager getAuthorizationManager() { return authorizationManager; } public UserProvisioningManager getUserManager() { return userManager; } /** * Get a Group object for the given groupName. * * @param groupName * @return * @throws Exception */ public Group getGroup(String groupName) throws Exception { Group group = new Group(); group.setGroupName(groupName); SearchCriteria sc = new GroupSearchCriteria(group); List results = userManager.getObjects(sc); Group doGroup = null; for (Object obj : results) { doGroup = (Group) obj; break; } return doGroup; } /** * Get a Role object for the given roleName. * * @param roleName * @return * @throws Exception */ public Role getRole(String roleName) throws Exception { Role role = new Role(); role.setName(roleName); SearchCriteria sc = new RoleSearchCriteria(role); List results = userManager.getObjects(sc); Role doRole = null; for (Object obj : results) { doRole = (Role) obj; break; } return doRole; } /** * Get a ProtectionElement object for the given objectId. * * @param objectId * @return * @throws Exception */ public ProtectionElement getProtectionElement(String objectId) throws Exception { ProtectionElement pe = new ProtectionElement(); pe.setObjectId(objectId); pe.setProtectionElementName(objectId); SearchCriteria sc = new ProtectionElementSearchCriteria(pe); List results = userManager.getObjects(sc); ProtectionElement doPE = null; for (Object obj : results) { doPE = (ProtectionElement) obj; break; } if (doPE == null) { authorizationManager.createProtectionElement(pe); return pe; } return doPE; } /** * Get a ProtectionGroup object for the given protectionGroupName. * * @param protectionGroupName * @return * @throws Exception */ public ProtectionGroup getProtectionGroup(String protectionGroupName) throws Exception { ProtectionGroup pg = new ProtectionGroup(); pg.setProtectionGroupName(protectionGroupName); SearchCriteria sc = new ProtectionGroupSearchCriteria(pg); List results = userManager.getObjects(sc); ProtectionGroup doPG = null; for (Object obj : results) { doPG = (ProtectionGroup) obj; break; } if (doPG == null) { userManager.createProtectionGroup(pg); return pg; } return doPG; } /** * Assign a ProtectionElement to a ProtectionGroup if not already assigned. * * @param pe * @param pg * @throws Exception */ public void assignProtectionElementToProtectionGroup(ProtectionElement pe, ProtectionGroup pg) throws Exception { Set<ProtectionGroup> assignedPGs = new HashSet<ProtectionGroup>( (Set<? extends ProtectionGroup>) authorizationManager .getProtectionGroups(pe.getProtectionElementId() .toString())); // check to see if the assignment is already made to ignore CSM // exception. //contains doesn't work because CSM didn't implement hashCode in ProtectionGroup. // if (assignedPGs.contains(pg)) { // return; for(ProtectionGroup aPg: assignedPGs) { if (aPg.equals(pg)) { return; } } authorizationManager.assignProtectionElement(pg .getProtectionGroupName(), pe.getObjectId()); } /** * Assign the given objectName to the given groupName with the given * roleName. Add to existing roles the object has for the group. * * @param objectName * @param groupName * @param roleName * @throws Exception */ public void secureObject(String objectName, String groupName, String roleName) throws Exception { // create protection element ProtectionElement pe = getProtectionElement(objectName); // create protection group ProtectionGroup pg = getProtectionGroup(objectName); // assign protection element to protection group if not already exists assignProtectionElementToProtectionGroup(pe, pg); // get group and role Group group = getGroup(groupName); Role role = getRole(roleName); Set<Role> existingRoles = new HashSet<Role>(); if (group != null && role != null) { // get existing roles and add to it Set contexts = userManager .getProtectionGroupRoleContextForGroup(group.getGroupId() .toString()); for (Object obj : contexts) { ProtectionGroupRoleContext context = (ProtectionGroupRoleContext) obj; if (context.getProtectionGroup().equals(pg)) { existingRoles = new HashSet<Role>( (Set<? extends Role>) context.getRoles()); break; } } existingRoles.add(role); String[] roleIds = new String[existingRoles.size()]; int i = 0; for (Object obj2 : existingRoles) { Role aRole = (Role) obj2; roleIds[i] = aRole.getId().toString(); i++; } userManager.assignGroupRoleToProtectionGroup(pg .getProtectionGroupId().toString(), group.getGroupId() .toString(), roleIds); } else { if (group == null) { throw new CalabException("No such group defined in CSM: " + groupName); } if (role == null) { throw new CalabException("No such role defined in CSM: " + roleName); } } } public List<ParticleBean> getFilteredParticles(UserBean user, List<ParticleBean> particles) throws Exception { List<ParticleBean> filteredParticles = new ArrayList<ParticleBean>(); for (ParticleBean particle : particles) { boolean status = checkReadPermission(user, particle.getSampleName()); if (status) { filteredParticles.add(particle); } } return filteredParticles; } /** * Get a list of groups the given object is assgined to with the given role * * @param objectName * @param roleName * @return * @throws Exception */ public List<String> getAccessibleGroups(String objectName, String roleName) throws Exception { List<String> groups = new ArrayList<String>(); List<String> allGroups = getAllGroups(); Role role = getRole(roleName); for (String groupName : allGroups) { Group group = getGroup(groupName); Set contexts = userManager .getProtectionGroupRoleContextForGroup(group.getGroupId() .toString()); for (Object obj : contexts) { ProtectionGroupRoleContext context = (ProtectionGroupRoleContext) obj; ProtectionGroup pg = context.getProtectionGroup(); Set<Role> roles = new HashSet<Role>( (Set<? extends Role>) context.getRoles()); //contains doesn't work because CSM didn't implement hashCode in Role. // if (pg.getProtectionGroupName().equals(objectName) // && roles.contains(role)) { // groups.add(groupName); if (pg.getProtectionGroupName().equals(objectName)) { for(Role aRole:roles) { if (aRole.equals(role)) { groups.add(groupName); } } } } } return groups; } /** * Remove the group the object is assigned to with the given role. * * @param objectName * @param groupName * @param roleName * @throws Exception */ public void removeAccessibleGroup(String objectName, String groupName, String roleName) throws Exception { Group group = getGroup(groupName); Role role = getRole(roleName); ProtectionGroup pg = getProtectionGroup(objectName); // this method is not implemented in CSM API, try an alternative // userManager.removeGroupRoleFromProtectionGroup(pg // .getProtectionGroupId().toString(), group.getGroupId() // .toString(), new String[] { role.getId().toString() }); // get existing roles. Set contexts = userManager.getProtectionGroupRoleContextForGroup(group .getGroupId().toString()); Set<Role> existingRoles = null; for (Object obj : contexts) { ProtectionGroupRoleContext context = (ProtectionGroupRoleContext) obj; if (context.getProtectionGroup().equals(pg)) { existingRoles = new HashSet<Role>((Set<? extends Role>) context .getRoles()); break; } } // remove role from existing roles //remove doesn't work because CSM didn't implement hashCode for Role //existingRoles.remove(role); Set<Role>updatedRoles=new HashSet<Role>(); for(Role aRole:existingRoles) { if (!aRole.equals(role)) { updatedRoles.add(aRole); } } // reassign the roles. String[] roleIds = new String[updatedRoles.size()]; int i = 0; for (Object obj : updatedRoles) { Role aRole = (Role) obj; roleIds[i] = aRole.getId().toString(); i++; } userManager.assignGroupRoleToProtectionGroup(pg.getProtectionGroupId() .toString(), group.getGroupId().toString(), roleIds); } }
package gov.nih.nci.calab.service.workflow; /** * Generalizes Mask functionality for masking Aliquot, File, etc. * @author doswellj * @param strType Type of Mask (e.g., aliquot, file, run, etc.) * @param strId The id associated to the type * @param strDescription The mask description associated to the mask type and Id. * */ public class MaskService { //This functionality is pending the completed Object Model public void setMask(String strType, String strId, String strDescription) { if (strType.equals("aliquot")) { //TODO Find Aliquot record based on the strID //TODO Set File Status record to "Masked". } if (strType.equals("file")) { //TODO Find File record based on the its strID //TODO Set File Status record to "Masked". } } }
package gov.nih.nci.rembrandt.web.helper; import gov.nih.nci.caintegrator.application.lists.ListSubType; import gov.nih.nci.caintegrator.dto.de.CloneIdentifierDE; import gov.nih.nci.caintegrator.dto.de.GeneIdentifierDE; import gov.nih.nci.caintegrator.dto.de.SNPIdentifierDE; import gov.nih.nci.caintegrator.dto.de.SampleIDDE; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.naming.OperationNotSupportedException; /** * @author sahnih * */ public class ListConvertor { /** * This method converts a string list to GeneIdentifierDE list type based on ListSubType * @param list * @param listSubType * @return */ public static List<GeneIdentifierDE> convertToGeneIdentifierDE(List<String> list,ListSubType listSubType){ List<GeneIdentifierDE> geneIdentifierList = new ArrayList<GeneIdentifierDE>(); switch (listSubType){ case GENESYMBOL: for(String listItem: list){ geneIdentifierList.add(new GeneIdentifierDE.GeneSymbol(listItem)); } break; case GENBANK_ACCESSION_NUMBER: for(String listItem: list){ geneIdentifierList.add(new GeneIdentifierDE.GenBankAccessionNumber(listItem)); } break; case LOCUS_LINK: for(String listItem: list){ geneIdentifierList.add(new GeneIdentifierDE.LocusLink(listItem)); } break; } return geneIdentifierList; } /** * This method converts a string list to CloneIdentifierDE list type based on ListSubType * @param list * @param listSubType * @return */ public static List<CloneIdentifierDE> convertToCloneIdentifierDE(List<String> list,ListSubType listSubType){ List<CloneIdentifierDE> cloneIdentifierDE = new ArrayList<CloneIdentifierDE>(); switch (listSubType){ case IMAGE_CLONE: for(String listItem: list){ cloneIdentifierDE.add(new CloneIdentifierDE.IMAGEClone(listItem)); } break; case AFFY_HGU133PLUS2_PROBE_SET: for(String listItem: list){ cloneIdentifierDE.add(new CloneIdentifierDE.ProbesetID(listItem.toLowerCase())); } break; } return cloneIdentifierDE; } /** * This method converts a string list to SNPIdentifierDE list type based on ListSubType * @param list * @param listSubType * @return */ public static List<SNPIdentifierDE> convertToSNPIdentifierDE(List<String> list,ListSubType listSubType){ List<SNPIdentifierDE> snpIdentifierDE = new ArrayList<SNPIdentifierDE>(); switch (listSubType){ case DBSNP: for(String listItem: list){ snpIdentifierDE.add(new SNPIdentifierDE.DBSNP(listItem)); } break; case AFFY_100K_SNP_PROBE_SET: for(String listItem: list){ snpIdentifierDE.add(new SNPIdentifierDE.SNPProbeSet(listItem)); } break; } return snpIdentifierDE; } public static Collection<SampleIDDE> convertToSampleIDDEs(Collection<String> sampleIDs)throws OperationNotSupportedException{ Collection<SampleIDDE> samplesDEs = new ArrayList<SampleIDDE>(); if(sampleIDs != null){ for(String sampleID: sampleIDs){ samplesDEs.add(new SampleIDDE(sampleID)); } } return samplesDEs; } }
package org.jboss.as.remoting; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.jboss.dmr.ModelNode; /** * Protocols that can be used for a remoting connection * * @author Stuart Douglas */ public enum Protocol { REMOTE("remote"), HTTP_REMOTING("http-remoting"), HTTPS_REMOTING("https-remoting"); private static final Map<String, Protocol> MAP; static { final Map<String, Protocol> map = new HashMap<String, Protocol>(); for (Protocol value : values()) { map.put(value.localName, value); } MAP = map; } public static Protocol forName(String localName) { final Protocol value = localName != null ? MAP.get(localName.toLowerCase(Locale.ENGLISH)) : null; return value == null && localName != null ? Protocol.valueOf(localName.toUpperCase(Locale.ENGLISH)) : value; } private final String localName; Protocol(final String localName) { this.localName = localName; } @Override public String toString() { return localName; } public ModelNode toModelNode() { return new ModelNode().set(toString()); } }
package com.xoba.smr; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.net.URI; import java.util.Formatter; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.codec.binary.Base64; import com.amazonaws.Request; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.handlers.AbstractRequestHandler; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.CreateTagsRequest; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.Tag; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.simpledb.AmazonSimpleDB; import com.amazonaws.services.simpledb.AmazonSimpleDBClient; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.xoba.util.ILogger; import com.xoba.util.LogFactory; import com.xoba.util.MraUtils; public class SimpleMapReduce { private static final ILogger logger = LogFactory.getDefault().create(); public static void launch(Properties config, List<String> inputSplitPrefixes, int machineCount) throws Exception { AWSCredentials aws = create(config); AmazonSimpleDB db = new AmazonSimpleDBClient(aws); AmazonSQS sqs = new AmazonSQSClient(aws); AmazonS3 s3 = new AmazonS3Client(aws); final String mapQueue = config.getProperty(ConfigKey.MAP_QUEUE.toString()); final String reduceQueue = config.getProperty(ConfigKey.REDUCE_QUEUE.toString()); final String dom = config.getProperty(ConfigKey.SIMPLEDB_DOM.toString()); final String mapInputBucket = config.getProperty(ConfigKey.MAP_INPUTS_BUCKET.toString()); final String shuffleBucket = config.getProperty(ConfigKey.SHUFFLE_BUCKET.toString()); final String reduceOutputBucket = config.getProperty(ConfigKey.REDUCE_OUTPUTS_BUCKET.toString()); final int hashCard = new Integer(config.getProperty(ConfigKey.HASH_CARDINALITY.toString())); s3.createBucket(reduceOutputBucket); final long inputSplitCount = inputSplitPrefixes.size(); for (String key : inputSplitPrefixes) { Properties p = new Properties(); p.setProperty("input", "s3://" + mapInputBucket + "/" + key); sqs.sendMessage(new SendMessageRequest(mapQueue, serialize(p))); } SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "splits", "" + inputSplitCount); SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "hashes", "" + hashCard); SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "done", "1"); for (String hash : getAllHashes(hashCard)) { Properties p = new Properties(); p.setProperty("input", "s3://" + shuffleBucket + "/" + hash); sqs.sendMessage(new SendMessageRequest(reduceQueue, serialize(p))); } if (machineCount == 1) { // run locally SMRDriver.main(new String[] { MraUtils.convertToHex(serialize(config).getBytes()) }); } else if (machineCount > 1) { // run in the cloud AmazonEC2 ec2 = new AmazonEC2Client(aws); AmazonInstance ai = AmazonInstance.M2_4XLARGE; String ud = produceUserData(ai, config, new URI(config.getProperty(ConfigKey.RUNNABLE_JARFILE_URI.toString()))); System.out.println(ud); RunInstancesRequest req = new RunInstancesRequest(ai.getDefaultAMI(), machineCount, machineCount); req.setInstanceType(ai.getApiName()); req.setKeyName("mrascratch"); req.setInstanceInitiatedShutdownBehavior("terminate"); req.setUserData(new String(new Base64().encode(ud.getBytes("US-ASCII")))); RunInstancesResult resp = ec2.runInstances(req); logger.debugf("reservation id = %s", resp.getReservation().getReservationId()); labelEc2Instance(ec2, resp, "test"); } } public static void labelEc2Instance(AmazonEC2 ec2, RunInstancesResult resp, String title) throws Exception { int tries = 0; boolean done = false; while (tries++ < 3 && !done) { try { List<String> resources = new LinkedList<String>(); for (Instance i : resp.getReservation().getInstances()) { resources.add(i.getInstanceId()); } List<Tag> tags = new LinkedList<Tag>(); tags.add(new Tag("Name", title)); CreateTagsRequest ctr = new CreateTagsRequest(resources, tags); ec2.createTags(ctr); done = true; logger.debugf("set tag(s)"); } catch (Exception e) { logger.warnf("exception setting tags: %s", e); Thread.sleep(3000); } } } public static String produceUserData(AmazonInstance ai, Properties c, URI jarFileURI) throws Exception { StringWriter sw = new StringWriter(); LinuxLineConventionPrintWriter pw = new LinuxLineConventionPrintWriter(new PrintWriter(sw)); pw.println("#!/bin/sh"); pw.println("cd /root"); pw.println("chmod 777 /mnt"); pw.println("aptitude update"); Set<String> set = new TreeSet<String>(); set.add("openjdk-6-jdk"); set.add("wget"); if (set.size() > 0) { pw.print("aptitude install -y "); Iterator<String> it = set.iterator(); while (it.hasNext()) { String x = it.next(); pw.print(x); if (it.hasNext()) { pw.print(" "); } } pw.println(); } pw.printf("wget %s", jarFileURI); pw.println(); String[] parts = jarFileURI.getPath().split("/"); String jar = parts[parts.length - 1]; pw.printf("java -Xmx%.0fm -jar %s %s", 1000 * 0.8 * ai.getMemoryGB(), jar, MraUtils.convertToHex(serialize(c).getBytes())); pw.println(); pw.println("poweroff"); pw.close(); return sw.toString(); } public static AmazonS3 getS3(AWSCredentials aws) { AmazonS3Client s3 = new AmazonS3Client(aws); s3.addRequestHandler(new AbstractRequestHandler() { @Override public void beforeRequest(Request<?> request) { request.addHeader("x-amz-request-payer", "requester"); } }); return s3; } @SuppressWarnings("unchecked") public static <T> T load(ClassLoader cl, Properties p, ConfigKey c, Class<T> x) throws Exception { T y = (T) cl.loadClass(p.getProperty(c.toString())).newInstance(); logger.debugf("%s -> %s", c, y); return y; } public static String prefixedName(String p, String n) { return p + "-" + n; } public static AWSCredentials create(final Properties p) { return new AWSCredentials() { @Override public String getAWSSecretKey() { return p.getProperty(ConfigKey.AWS_SECRETKEY.toString()); } @Override public String getAWSAccessKeyId() { return p.getProperty(ConfigKey.AWS_KEYID.toString()); } }; } public static SortedSet<String> getAllHashes(long mod) { SortedSet<String> out = new TreeSet<String>(); for (long i = 0; i < mod; i++) { out.add(fmt(i, mod)); } return out; } public static String hash(byte[] key, long mod) { byte[] buf = MraUtils.md5HashBytesToBytes(key); long x = Math.abs(MraUtils.extractLongValue(buf)); return fmt(x % mod, mod); } private static String fmt(long x, long mod) { long places = Math.round(Math.ceil(Math.log10(mod))); if (places == 0) { places = 1; } return new Formatter().format("%0" + places + "d", x).toString(); } public static String serialize(Properties p) throws Exception { StringWriter sw = new StringWriter(); try { p.store(sw, "n/a"); } finally { sw.close(); } return sw.toString(); } public static Properties marshall(String s) throws Exception { Properties p = new Properties(); StringReader sr = new StringReader(s); try { p.load(sr); } finally { sr.close(); } return p; } }
package com.vip.saturn.job.java; import com.vip.saturn.job.SaturnJobExecutionContext; import com.vip.saturn.job.SaturnJobReturn; import com.vip.saturn.job.SaturnSystemErrorGroup; import com.vip.saturn.job.SaturnSystemReturnCode; import com.vip.saturn.job.basic.*; import com.vip.saturn.job.exception.JobException; import com.vip.saturn.job.internal.config.JobConfiguration; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class SaturnJavaJob extends CrondJob { private static Logger log = LoggerFactory.getLogger(SaturnJavaJob.class); private Map<Integer, ShardingItemFutureTask> futureTaskMap; private Object jobBusinessInstance = null; public JavaShardingItemCallable createCallable(String jobName, Integer item, String itemValue, int timeoutSeconds, SaturnExecutionContext shardingContext, AbstractSaturnJob saturnJob) { return new JavaShardingItemCallable(jobName, item, itemValue, timeoutSeconds, shardingContext, saturnJob); } @Override public void init() throws SchedulerException { super.init(); createJobBusinessInstanceIfNecessary(); getJobVersionIfNecessary(); } private void getJobVersionIfNecessary() throws SchedulerException { if (jobBusinessInstance != null) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(saturnExecutorService.getJobClassLoader()); try { String version = (String) jobBusinessInstance.getClass().getMethod("getJobVersion") .invoke(jobBusinessInstance); setJobVersion(version); } catch (Throwable t) { log.error( String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, "error throws during get job version"), t); throw new SchedulerException(t); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } } private void createJobBusinessInstanceIfNecessary() throws SchedulerException { JobConfiguration currentConf = configService.getJobConfiguration(); String jobClassStr = currentConf.getJobClass(); if (jobClassStr != null && !jobClassStr.trim().isEmpty()) { if (jobBusinessInstance == null) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader jobClassLoader = saturnExecutorService.getJobClassLoader(); Thread.currentThread().setContextClassLoader(jobClassLoader); try { Class<?> jobClass = jobClassLoader.loadClass(currentConf.getJobClass()); try { Method getObject = jobClass.getMethod("getObject"); if (getObject != null) { try { jobBusinessInstance = getObject.invoke(null); } catch (Throwable t) { log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, jobClassStr + " getObject error"), t); } } } catch (Exception ex) {// NOSONAR // log.error("",ex); } if (jobBusinessInstance == null) { jobBusinessInstance = jobClass.newInstance(); } SaturnApi saturnApi = new SaturnApi(getNamespace(), executorName); jobClass.getMethod("setSaturnApi", Object.class).invoke(jobBusinessInstance, saturnApi); } catch (Throwable t) { log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, "create job business instance error"), t); throw new SchedulerException(t); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } } if (jobBusinessInstance == null) { throw new SchedulerException("init job business instance failed, the job class is " + jobClassStr); } } @Override protected Map<Integer, SaturnJobReturn> handleJob(final SaturnExecutionContext shardingContext) { final Map<Integer, SaturnJobReturn> retMap = new HashMap<Integer, SaturnJobReturn>(); final String jobName = shardingContext.getJobName(); final int timeoutSeconds = getTimeoutSeconds(); ExecutorService executorService = getExecutorService(); futureTaskMap = new HashMap<Integer, ShardingItemFutureTask>(); String jobParameter = shardingContext.getJobParameter(); // shardingItemParametersKey/Value Map<Integer, String> shardingItemParameters = shardingContext.getShardingItemParameters(); for (final Entry<Integer, String> shardingItem : shardingItemParameters.entrySet()) { final Integer key = shardingItem.getKey(); try { String jobValue = shardingItem.getValue(); final String itemVal = getRealItemValue(jobParameter, jobValue); ShardingItemFutureTask shardingItemFutureTask = new ShardingItemFutureTask( createCallable(jobName, key, itemVal, timeoutSeconds, shardingContext, this), null); Future<?> callFuture = executorService.submit(shardingItemFutureTask); if (timeoutSeconds > 0) { TimeoutSchedulerExecutor.scheduleTimeoutJob(shardingContext.getExecutorName(), timeoutSeconds, shardingItemFutureTask); } shardingItemFutureTask.setCallFuture(callFuture); futureTaskMap.put(key, shardingItemFutureTask); } catch (Throwable t) { log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, t.getMessage()), t); retMap.put(key, new SaturnJobReturn(SaturnSystemReturnCode.SYSTEM_FAIL, t.getMessage(), SaturnSystemErrorGroup.FAIL)); } } for (Entry<Integer, ShardingItemFutureTask> entry : futureTaskMap.entrySet()) { Integer item = entry.getKey(); ShardingItemFutureTask futureTask = entry.getValue(); try { futureTask.getCallFuture().get(); } catch (Exception e) { log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, e.getMessage()), e); retMap.put(item, new SaturnJobReturn(SaturnSystemReturnCode.SYSTEM_FAIL, e.getMessage(), SaturnSystemErrorGroup.FAIL)); continue; } retMap.put(item, futureTask.getCallable().getSaturnJobReturn()); } return retMap; } @Override public void abort() { super.abort(); forceStop(); } @Override public void forceStop() { super.forceStop(); if (futureTaskMap != null) { for (ShardingItemFutureTask shardingItemFutureTask : futureTaskMap.values()) { JavaShardingItemCallable shardingItemCallable = shardingItemFutureTask.getCallable(); Thread currentThread = shardingItemCallable.getCurrentThread(); if (currentThread != null) { try { log.info("[{}] msg=force stop {} - {}", jobName, shardingItemCallable.getJobName(), shardingItemCallable.getItem()); if (shardingItemCallable.forceStop()) { ShardingItemFutureTask.killRunningBusinessThread(shardingItemFutureTask); } } catch (Throwable t) { log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, t.getMessage()), t); } } } } } @Override public SaturnJobReturn doExecution(String jobName, Integer key, String value, SaturnExecutionContext shardingContext, JavaShardingItemCallable callable) throws Throwable { return handleJavaJob(jobName, key, value, shardingContext, callable); } public SaturnJobReturn handleJavaJob(String jobName, Integer key, String value, SaturnExecutionContext shardingContext, JavaShardingItemCallable callable) throws Throwable { String jobClass = shardingContext.getJobConfiguration().getJobClass(); log.info("[{}] msg=Running SaturnJavaJob, jobClass [{}], item [{}]", jobName, jobClass, key); try { if (jobBusinessInstance == null) { throw new JobException("the job business instance is not initialized"); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader jobClassLoader = saturnExecutorService.getJobClassLoader(); Thread.currentThread().setContextClassLoader(jobClassLoader); try { Class<?> saturnJobExecutionContextClazz = jobClassLoader .loadClass(SaturnJobExecutionContext.class.getCanonicalName()); Object ret = jobBusinessInstance.getClass() .getMethod("handleJavaJob", String.class, Integer.class, String.class, saturnJobExecutionContextClazz) .invoke(jobBusinessInstance, jobName, key, value, callable.getContextForJob(jobClassLoader)); SaturnJobReturn saturnJobReturn = (SaturnJobReturn) JavaShardingItemCallable.cloneObject(ret, saturnExecutorService.getExecutorClassLoader()); if (saturnJobReturn != null) { callable.setBusinessReturned(true); } return saturnJobReturn; } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } catch (Exception e) { if (e.getCause() instanceof ThreadDeath) { throw e.getCause(); } String message = logBusinessExceptionIfNecessary(jobName, e); return new SaturnJobReturn(SaturnSystemReturnCode.USER_FAIL, message, SaturnSystemErrorGroup.FAIL); } } public void postTimeout(String jobName, Integer key, String value, SaturnExecutionContext shardingContext, JavaShardingItemCallable callable) { String jobClass = shardingContext.getJobConfiguration().getJobClass(); log.info("[{}] msg=SaturnJavaJob onTimeout, jobClass is {} ", jobName, jobClass); try { if (jobBusinessInstance == null) { throw new JobException("the job business instance is not initialized"); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader jobClassLoader = saturnExecutorService.getJobClassLoader(); Thread.currentThread().setContextClassLoader(jobClassLoader); try { Class<?> saturnJobExecutionContextClazz = jobClassLoader .loadClass(SaturnJobExecutionContext.class.getCanonicalName()); jobBusinessInstance.getClass() .getMethod("onTimeout", String.class, Integer.class, String.class, saturnJobExecutionContextClazz) .invoke(jobBusinessInstance, jobName, key, value, callable.getContextForJob(jobClassLoader)); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } catch (Exception e) { logBusinessExceptionIfNecessary(jobName, e); } } public void beforeTimeout(String jobName, Integer key, String value, SaturnExecutionContext shardingContext, JavaShardingItemCallable callable) { String jobClass = shardingContext.getJobConfiguration().getJobClass(); log.info("[{}] msg=SaturnJavaJob beforeTimeout, jobClass is {} ", jobName, jobClass); try { if (jobBusinessInstance == null) { throw new JobException("the job business instance is not initialized"); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader jobClassLoader = saturnExecutorService.getJobClassLoader(); Thread.currentThread().setContextClassLoader(jobClassLoader); try { Class<?> saturnJobExecutionContextClazz = jobClassLoader .loadClass(SaturnJobExecutionContext.class.getCanonicalName()); jobBusinessInstance.getClass() .getMethod("beforeTimeout", String.class, Integer.class, String.class, saturnJobExecutionContextClazz) .invoke(jobBusinessInstance, jobName, key, value, callable.getContextForJob(jobClassLoader)); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } catch (Exception e) { logBusinessExceptionIfNecessary(jobName, e); } } public void postForceStop(String jobName, Integer key, String value, SaturnExecutionContext shardingContext, JavaShardingItemCallable callable) { String jobClass = shardingContext.getJobConfiguration().getJobClass(); log.info("[{}] msg=SaturnJavaJob postForceStop, jobClass is {} ", jobName, jobClass); try { if (jobBusinessInstance == null) { throw new JobException("the job business instance is not initialized"); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader jobClassLoader = saturnExecutorService.getJobClassLoader(); Thread.currentThread().setContextClassLoader(jobClassLoader); try { Class<?> saturnJobExecutionContextClazz = jobClassLoader .loadClass(SaturnJobExecutionContext.class.getCanonicalName()); jobBusinessInstance.getClass() .getMethod("postForceStop", String.class, Integer.class, String.class, saturnJobExecutionContextClazz) .invoke(jobBusinessInstance, jobName, key, value, callable.getContextForJob(jobClassLoader)); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } catch (Exception e) { logBusinessExceptionIfNecessary(jobName, e); } } @Override public void notifyJobEnabled() { String jobClass = configService.getJobConfiguration().getJobClass(); log.info("[{}] msg=SaturnJavaJob onEnabled, jobClass is {} ", jobName, jobClass); try { if (jobBusinessInstance == null) { throw new JobException("the job business instance is not initialized"); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader jobClassLoader = saturnExecutorService.getJobClassLoader(); Thread.currentThread().setContextClassLoader(jobClassLoader); try { jobBusinessInstance.getClass().getMethod("onEnabled", String.class).invoke(jobBusinessInstance, jobName); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } catch (Exception e) { logBusinessExceptionIfNecessary(jobName, e); } } @Override public void notifyJobDisabled() { String jobClass = configService.getJobConfiguration().getJobClass(); log.info("[{}] msg=SaturnJavaJob onDisabled, jobClass is {} ", jobName, jobClass); try { if (jobBusinessInstance == null) { throw new JobException("the job business instance is not initialized"); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader jobClassLoader = saturnExecutorService.getJobClassLoader(); Thread.currentThread().setContextClassLoader(jobClassLoader); try { jobBusinessInstance.getClass().getMethod("onDisabled", String.class).invoke(jobBusinessInstance, jobName); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } catch (Exception e) { logBusinessExceptionIfNecessary(jobName, e); } } @Override public void onForceStop(int item) { } @Override public void onTimeout(int item) { } @Override public void onNeedRaiseAlarm(int item, String alarmMessage) { // TODO: need to raise alarm by implementor } }
package org.jetbrains.sbt.settings; import com.intellij.execution.ui.DefaultJreSelector; import com.intellij.execution.ui.JrePathEditor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.RawCommandLineEditor; import com.intellij.ui.TitledSeparator; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import javax.swing.*; import java.awt.*; import java.awt.event.ItemEvent; import java.util.Optional; import java.util.ResourceBundle; /** * @author Pavel Fatin */ public class SbtSettingsPane { private JRadioButton myBundledButton; private JRadioButton myCustomButton; private JTextField myMaximumHeapSize; private TextFieldWithBrowseButton myLauncherPath; private RawCommandLineEditor myVmParameters; private JPanel myContentPanel; private JrePathEditor myJrePathEditor; private Project myProject; public SbtSettingsPane(Project project) { myProject = project; $$$setupUI$$$(); myBundledButton.addItemListener(itemEvent -> setLauncherPathEnabled(itemEvent.getStateChange() == ItemEvent.DESELECTED)); myCustomButton.addItemListener(itemEvent -> setLauncherPathEnabled(itemEvent.getStateChange() == ItemEvent.SELECTED)); myBundledButton.setSelected(true); } public void createUIComponents() { myJrePathEditor = new JrePathEditor(DefaultJreSelector.projectSdk(myProject)); } // TODO: this is a workaround to fix SCL-8059 non-working "..." buttons // Investigation needed to find out why path listeners are being removed. public void setPathListeners() { myLauncherPath.addBrowseFolderListener("Choose a Custom Launcher", "Choose sbt-launch.jar", null, FileChooserDescriptorFactory.createSingleLocalFileDescriptor()); } public JPanel getContentPanel() { return myContentPanel; } public void setLauncherPathEnabled(boolean enabled) { myLauncherPath.setEnabled(enabled); } public boolean isCustomLauncher() { return myCustomButton.isSelected(); } public boolean isCustomVM() { return myJrePathEditor.isAlternativeJreSelected(); } public void setCustomLauncherEnabled(boolean enabled) { myBundledButton.setSelected(!enabled); myCustomButton.setSelected(enabled); } public String getLauncherPath() { return myLauncherPath.getText(); } public String getCustomVMPath() { String pathOrName = myJrePathEditor.getJrePathOrName(); return Optional.ofNullable(pathOrName) .flatMap(p -> Optional.ofNullable(ProjectJdkTable.getInstance().findJdk(pathOrName))) .map(Sdk::getHomePath) .orElse(pathOrName); } @SuppressWarnings("unused") public void setLauncherPath(String path) { myLauncherPath.setText(path); } @SuppressWarnings("unused") public void setCustomVMPath(String path, boolean useCustomVM) { // determine name or path based on available sdk's to maintain compatibility with old form data model String pathOrName = ProjectJdkTable.getInstance() .getSdksOfType(JavaSdk.getInstance()) .stream() .filter(sdk -> StringUtil.equals(sdk.getHomePath(), path)) .findFirst() .map(Sdk::getName) .orElse(path); myJrePathEditor.setPathOrName(pathOrName, useCustomVM); } public String getMaximumHeapSize() { return myMaximumHeapSize.getText(); } public void setMaximumHeapSize(String value) { myMaximumHeapSize.setText(value); } public String getVmParameters() { return myVmParameters.getText(); } public void setMyVmParameters(String value) { myVmParameters.setText(value); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { createUIComponents(); myContentPanel = new JPanel(); myContentPanel.setLayout(new GridLayoutManager(6, 2, new Insets(0, 0, 0, 0), -1, -1)); final Spacer spacer1 = new Spacer(); myContentPanel.add(spacer1, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); final TitledSeparator titledSeparator1 = new TitledSeparator(); titledSeparator1.setText(ResourceBundle.getBundle("org/jetbrains/sbt/SbtBundle").getString("sbt.settings.sbtLauncher")); myContentPanel.add(titledSeparator1, new GridConstraints(3, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1)); myContentPanel.add(panel1, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 1, false)); myBundledButton = new JRadioButton(); this.$$$loadButtonText$$$(myBundledButton, ResourceBundle.getBundle("org/jetbrains/sbt/SbtBundle").getString("sbt.settings.bundled")); panel1.add(myBundledButton, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); myCustomButton = new JRadioButton(); this.$$$loadButtonText$$$(myCustomButton, ResourceBundle.getBundle("org/jetbrains/sbt/SbtBundle").getString("sbt.settings.custom.launcher")); panel1.add(myCustomButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); myLauncherPath = new TextFieldWithBrowseButton(); panel1.add(myLauncherPath, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(250, -1), null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); myContentPanel.add(panel2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 1, false)); panel2.add(myJrePathEditor, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(250, -1), null, null, 0, false)); final TitledSeparator titledSeparator2 = new TitledSeparator(); titledSeparator2.setText(ResourceBundle.getBundle("org/jetbrains/sbt/SbtBundle").getString("sbt.settings.jvm")); myContentPanel.add(titledSeparator2, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1)); myContentPanel.add(panel3, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 1, false)); final JLabel label1 = new JLabel(); this.$$$loadLabelText$$$(label1, ResourceBundle.getBundle("org/jetbrains/sbt/SbtBundle").getString("sbt.settings.maxHeapSize")); panel3.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label2 = new JLabel(); this.$$$loadLabelText$$$(label2, ResourceBundle.getBundle("org/jetbrains/sbt/SbtBundle").getString("sbt.settings.vmParams")); panel3.add(label2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); myMaximumHeapSize = new JTextField(); myMaximumHeapSize.setColumns(5); panel3.add(myMaximumHeapSize, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(250, -1), null, 0, false)); myVmParameters = new RawCommandLineEditor(); myVmParameters.setDialogCaption(ResourceBundle.getBundle("org/jetbrains/sbt/SbtBundle").getString("sbt.settings.vmParams")); myVmParameters.setEnabled(true); panel3.add(myVmParameters, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, new Dimension(250, -1), new Dimension(250, -1), null, 0, false)); final Spacer spacer2 = new Spacer(); myContentPanel.add(spacer2, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); label1.setLabelFor(myMaximumHeapSize); ButtonGroup buttonGroup; buttonGroup = new ButtonGroup(); buttonGroup.add(myBundledButton); buttonGroup.add(myCustomButton); } /** * @noinspection ALL */ private void $$$loadLabelText$$$(JLabel component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setDisplayedMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ private void $$$loadButtonText$$$(AbstractButton component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return myContentPanel; } }
package be.fedict.dcat.scrapers; import be.fedict.dcat.helpers.Cache; import be.fedict.dcat.helpers.Storage; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.text.html.HTML; import javax.swing.text.html.HTML.Attribute; import javax.swing.text.html.HTML.Tag; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.openrdf.model.URI; import org.openrdf.model.vocabulary.DCTERMS; import org.openrdf.model.vocabulary.FOAF; import org.openrdf.repository.RepositoryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Statbel "publications" scraper. * * @author Bart Hanssens <bart.hanssens@fedict.be> */ public class HtmlStatbelPubls extends Html { private final Logger logger = LoggerFactory.getLogger(HtmlStatbelPubls.class); public final static String CAT_SELECT = "category_select"; public final static String CAT_CAT = "Statistieken - Download-tabellen"; public final static String LANG_LINK = "blgm_lSwitch"; /** * Get the URL of the page in another language * * @param page * @param lang * @return URL of the page in another language * @throws IOException */ private URL switchLanguage(String page, String lang) throws IOException { URL base = getBase(); Elements lis = Jsoup.parse(page) .getElementsByClass(HtmlStatbelPubls.LANG_LINK); for(Element li : lis) { if (li.text().equals(lang)) { String href = li.attr(HTML.Attribute.HREF.toString()); if (href != null && !href.isEmpty()) { return new URL(base.getProtocol(), base.getHost(), href); } } } return base; } @Override public void generateCatalogInfo(Storage store, URI catalog) throws RepositoryException { super.generateCatalogInfo(store, catalog); store.add(catalog, DCTERMS.TITLE, "Statbel downloads", "en"); } @Override public void generateDatasets(Map<String, String> page, Storage store) throws MalformedURLException, RepositoryException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } /** * Scrape dataset * * @param u * @throws IOException */ private void scrapeDataset(URL u) throws IOException { Cache cache = getCache(); String lang = getDefaultLang(); String page = makeRequest(u); cache.storePage(u, page, lang); for (String l : getAllLangs()) { if (! l.equals(lang)) { URL url = switchLanguage(page, lang); cache.storePage(u, makeRequest(url), lang); } } } /** * Get the list of all the downloads (DCAT Dataset). * * @return List of URLs * @throws IOException */ private List<URL> scrapeDatasetList() throws IOException { List<URL> urls = new ArrayList<>(); URL base = getBase(); String front = makeRequest(base); // Select the correct page from dropdown-list, displaying all items Element select = Jsoup.parse(front).getElementById(HtmlStatbelPubls.CAT_SELECT); Element opt = select.getElementsMatchingOwnText(HtmlStatbelPubls.CAT_CAT).first(); if (opt != null) { URL downloads = new URL(base, opt.val() + "&size=250"); String page = makeRequest(downloads); // Extract links from list Elements rows = Jsoup.parse(page).getElementsByTag(Tag.TD.toString()); for(Element row : rows) { Element link = row.getElementsByTag(Tag.A.toString()).first(); String href = link.attr(Attribute.HREF.toString()); urls.add(new URL(getBase(), href)); } } else { logger.error("Category {} not found", HtmlStatbelPubls.CAT_CAT); } return urls; } /** * Scrape the site. * * @throws IOException */ @Override public void scrape() throws IOException{ logger.info("Start scraping"); Cache cache = getCache(); List<URL> urls = cache.retrieveURLList(); if (urls.isEmpty()) { urls = scrapeDatasetList(); cache.storeURLList(urls); } urls = cache.retrieveURLList(); logger.info("Found {} downloads", String.valueOf(urls.size())); logger.info("Start scraping (waiting between requests)"); int i = 0; for (URL u : urls) { Map<String, String> page = cache.retrievePage(u); if (page.isEmpty()) { sleep(); if (++i % 100 == 0) { logger.info("Download {}...", Integer.toString(i)); } scrapeDataset(u); } } logger.info("Done scraping"); } /** * HTML parser for Statbel publications * * @param caching * @param storage * @param base */ public HtmlStatbelPubls(File caching, File storage, URL base) { super(caching, storage, base); } @Override public void generateDcat(Cache cache, Storage store) throws RepositoryException, MalformedURLException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package info.persistent.react.jscomp; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Resources; import com.google.javascript.jscomp.AbstractCompiler; import com.google.javascript.jscomp.CodePrinter; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.CompilerAccessor; import com.google.javascript.jscomp.CompilerInput; import com.google.javascript.jscomp.DiagnosticType; import com.google.javascript.jscomp.HotSwapCompilerPass; import com.google.javascript.jscomp.JSError; import com.google.javascript.jscomp.JSModule; import com.google.javascript.jscomp.NodeTraversal; import com.google.javascript.jscomp.NodeUtil; import com.google.javascript.jscomp.Result; import com.google.javascript.jscomp.SourceFile; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfoAccessor; import com.google.javascript.rhino.JSDocInfoBuilder; import com.google.javascript.rhino.JSTypeExpression; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; public class ReactCompilerPass implements NodeTraversal.Callback, HotSwapCompilerPass { // Errors static final DiagnosticType REACT_SOURCE_NOT_FOUND = DiagnosticType.error( "REACT_SOURCE_NOT_FOUND", "Could not find the React library source."); static final DiagnosticType CREATE_TYPE_TARGET_INVALID = DiagnosticType.error( "REACT_CREATE_CLASS_TARGET_INVALID", "Unsupported {0}(...) expression."); static final DiagnosticType CREATE_TYPE_SPEC_NOT_VALID = DiagnosticType.error( "REACT_CREATE_TYPE_SPEC_NOT_VALID", "The {0}(...) spec must be an object literal."); static final DiagnosticType CREATE_TYPE_UNEXPECTED_PARAMS = DiagnosticType.error( "REACT_CREATE_TYPE_UNEXPECTED_PARAMS", "The {0}(...) call has too many arguments."); static final DiagnosticType COULD_NOT_DETERMINE_TYPE_NAME = DiagnosticType.error( "REACT_COULD_NOT_DETERMINE_TYPE_NAME", "Could not determine the type name from a {0}(...) call."); static final DiagnosticType MIXINS_UNEXPECTED_TYPE = DiagnosticType.error( "REACT_MIXINS_UNEXPECTED_TYPE", "The \"mixins\" value must be an array literal."); static final DiagnosticType MIXIN_EXPECTED_NAME = DiagnosticType.error( "REACT_MIXIN_EXPECTED_NAME", "The \"mixins\" array literal must contain only mixin names."); static final DiagnosticType MIXIN_UNKNOWN = DiagnosticType.error( "REACT_MIXIN_UNKNOWN", "Could not find a mixin with the name {0}"); static final DiagnosticType CREATE_ELEMENT_UNEXPECTED_PARAMS = DiagnosticType.error( "REACT_CREATE_ELEMENT_UNEXPECTED_PARAMS", "The React.createElement(...) call has too few arguments."); static final DiagnosticType STATICS_UNEXPECTED_TYPE = DiagnosticType.error( "REACT_STATICS_UNEXPECTED_TYPE", "The \"statics\" value must be an object literal."); static final DiagnosticType PURE_RENDER_MIXIN_SHOULD_COMPONENT_UPDATE_OVERRIDE = DiagnosticType.error( "REACT_PURE_RENDER_MIXIN_SHOULD_COMPONENT_UPDATE_OVERRIDE", "{0} uses React.addons.PureRenderMixin, it should not define shouldComponentUpdate."); private static final String REACT_PURE_RENDER_MIXIN_NAME = "React.addons.PureRenderMixin"; private static final String EXTERNS_SOURCE_NAME = "<ReactCompilerPass-externs.js>"; private static final String CREATE_ELEMENT_ALIAS_NAME = "React$createElement"; private static final String CREATE_CLASS_ALIAS_NAME = "React$createClass"; private final Compiler compiler; private final Options options; private boolean stripPropTypes = false; private boolean addReactApiAliases = false; private Node externsRoot; private final Map<String, Node> reactClassesByName = Maps.newHashMap(); private final Map<String, Node> reactClassInterfacePrototypePropsByName = Maps.newHashMap(); private final Map<String, Node> reactMixinsByName = Maps.newHashMap(); private final Map<String, List<Node>> reactMixinsPropTypesByName = Maps.newHashMap(); private final Map<String, Node> reactMixinInterfacePrototypePropsByName = Maps.newHashMap(); // Mixin name -> method name -> JSDoc private final Map<String, Map<String, JSDocInfo>> mixinAbstractMethodJsDocsByName = Maps.newHashMap(); private final Map<String, PropTypesExtractor> propTypesExtractorsByName = Maps.newHashMap(); // Make debugging test failures easier by allowing the processed output to // be inspected. static boolean saveLastOutputForTests = false; static String lastOutputForTests; public static class Options { // TODO: flip default once all known issues are resolved public boolean propTypesTypeChecking = false; // By default React API method names are renamed, since it is assumed that // React is not publicly exposed. public boolean renameReactApi = true; } public ReactCompilerPass(AbstractCompiler compiler) { this(compiler, new Options()); } public ReactCompilerPass(AbstractCompiler compiler, Options options) { this.compiler = (Compiler) compiler; this.options = options; } @Override public void process(Node externs, Node root) { reactClassesByName.clear(); reactClassInterfacePrototypePropsByName.clear(); reactMixinsByName.clear(); reactMixinsPropTypesByName.clear(); reactMixinInterfacePrototypePropsByName.clear(); mixinAbstractMethodJsDocsByName.clear(); propTypesExtractorsByName.clear(); addExterns(); addTypes(root); hotSwapScript(root, null); if (saveLastOutputForTests) { lastOutputForTests = new CodePrinter.Builder(root) .setPrettyPrint(true) .setOutputTypes(true) .setTypeRegistry(compiler.getTypeIRegistry()) .build(); } else { lastOutputForTests = null; } } * /** * * @type {<moduleType>} * * @const * * / * var <moduleName>; */ private void addExternModule(String moduleName, String moduleType, Node root) { Node reactVarNode = IR.var(IR.name(moduleName)); JSDocInfoBuilder jsDocBuilder = new JSDocInfoBuilder(true); jsDocBuilder.recordType(new JSTypeExpression( IR.string(moduleType), EXTERNS_SOURCE_NAME)); jsDocBuilder.recordConstancy(); reactVarNode.setJSDocInfo(jsDocBuilder.build()); root.addChildToBack(reactVarNode); } /** * The compiler isn't aware of the React* symbols that are exported from * React, inform it via an extern. * * TODO(mihai): figure out a way to do this without externs, so that the * symbols can get renamed. */ private void addExterns() { CompilerInput externsInput = CompilerAccessor.getSynthesizedExternsInputAtEnd(compiler); externsRoot = externsInput.getAstRoot(compiler); for (Map.Entry<String, String> entry : React.REACT_MODULES.entrySet()) { String moduleName = entry.getKey(); String moduleType = entry.getValue(); addExternModule(moduleName, moduleType, externsRoot); } if (!options.renameReactApi) { Node typesNode = createTypesNode(); typesNode.useSourceInfoFromForTree(externsRoot); Node typesChildren = typesNode.getFirstChild(); typesNode.removeChildren(); externsRoot.addChildrenToBack(typesChildren); } compiler.reportChangeToEnclosingScope(externsRoot); } /** * Inject React type definitions (if we want these to get renamed, they're * not part of the externs). {@link Compiler#getNodeForCodeInsertion(JSModule)} * is package-private, so we instead add the types to the React source file. */ private void addTypes(Node root) { Node typesNode = null; if (options.renameReactApi) { typesNode = createTypesNode(); } boolean foundReactSource = false; for (Node inputNode : root.children()) { if (inputNode.getToken() == Token.SCRIPT && inputNode.getSourceFileName() != null && React.isReactSourceName(inputNode.getSourceFileName())) { if (typesNode != null) { Node typesChildren = typesNode.getFirstChild(); typesNode.removeChildren(); inputNode.addChildrenToFront(typesChildren); } foundReactSource = true; stripPropTypes = addReactApiAliases = React.isReactMinSourceName( inputNode.getSourceFileName()); if (addReactApiAliases) { // Add an alias of the form: // /** @type {Function} */ // var React$createElement = React.createElement; // Normally React.createElement calls are not renamed at all, due to // React being an extern and createElement showing up in the built-in // browser DOM externs. By adding an alias and then rewriting calls // (see visitReactCreateElement) we allow the compiler to rename the // function used at all the calls. This is most beneficial before // gzip, but when after gzip there is still some benefit. // The Function type is necessary to convince the compiler that we // don't need the "this" type to be defined when calling the alias // (it thinks that React is an instance of the ReactModule type, but // it's actually a static namespace, so we can use unbound functions // from it) Node createElementAliasNode = IR.var( IR.name(CREATE_ELEMENT_ALIAS_NAME), IR.getprop( IR.name("React"), IR.string("createElement"))); JSDocInfoBuilder jsDocBuilder = new JSDocInfoBuilder(true); jsDocBuilder.recordType(new JSTypeExpression( IR.string("Function"), inputNode.getSourceFileName())); createElementAliasNode.setJSDocInfo(jsDocBuilder.build()); inputNode.addChildToBack(createElementAliasNode); // Same thing for React.createClass, which partially gets renamed but // still shows up often enough that shortening it is worthwhile. Node createClassAliasNode = IR.var( IR.name(CREATE_CLASS_ALIAS_NAME), IR.getprop( IR.name("React"), IR.string("createClass"))); jsDocBuilder = new JSDocInfoBuilder(true); jsDocBuilder.recordType(new JSTypeExpression( IR.string("Function"), inputNode.getSourceFileName())); createClassAliasNode.setJSDocInfo(jsDocBuilder.build()); inputNode.addChildToBack(createClassAliasNode); } compiler.reportChangeToEnclosingScope(inputNode); break; } } if (!foundReactSource) { compiler.report(JSError.make(root, REACT_SOURCE_NOT_FOUND)); return; } } /** * Cache parsed types AST across invocations. */ private static Node templateTypesNode = null; /** * Parameter and return types for built-in component methods, so that * implementations may be annotated automatically. */ private static Map<String, JSDocInfo> componentMethodJsDocs = Maps.newHashMap(); private Node createTypesNode() { if (templateTypesNode == null) { String typesJs = React.getTypesJs(); Result previousResult = compiler.getResult(); templateTypesNode = compiler.parse(SourceFile.fromCode(React.TYPES_JS_RESOURCE_PATH, typesJs)); Result result = compiler.getResult(); if ((result.success != previousResult.success && previousResult.success) || result.errors.length > previousResult.errors.length || result.warnings.length > previousResult.warnings.length) { String message = "Could not parse " + React.TYPES_JS_RESOURCE_PATH + "."; if (result.errors.length > 0) { message += "\nErrors: " + Joiner.on(",").join(result.errors); } if (result.warnings.length > 0) { message += "\nWarnings: " + Joiner.on(",").join(result.warnings); } throw new RuntimeException(message); } // Gather ReactComponent prototype methods. NodeTraversal.traverse( compiler, templateTypesNode, new NodeTraversal.AbstractPostOrderCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (!n.isAssign() || !n.getFirstChild().isQualifiedName() || !n.getFirstChild().getQualifiedName().startsWith( "ReactComponent.prototype.") || !n.getLastChild().isFunction()) { return; } componentMethodJsDocs.put( n.getFirstChild().getLastChild().getString(), n.getJSDocInfo()); } }); } return templateTypesNode.cloneTree(); } @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { NodeTraversal.traverse(compiler, scriptRoot, this); // Inline React.createMixin calls, since they're just decorators. for (Node mixinSpecNode : reactMixinsByName.values()) { Node mixinSpecParentNode = mixinSpecNode.getParent(); if (mixinSpecParentNode.isCall() && mixinSpecParentNode.hasMoreThanOneChild() && mixinSpecParentNode.getFirstChild().getQualifiedName().equals( "React.createMixin")) { mixinSpecNode.detachFromParent(); mixinSpecParentNode.getParent().replaceChild( mixinSpecParentNode, mixinSpecNode); compiler.reportChangeToEnclosingScope(mixinSpecNode.getParent()); } } if (addReactApiAliases) { for (Node classSpecNode : reactClassesByName.values()) { Node functionNameNode = classSpecNode.getPrevious(); if (functionNameNode.getToken() == Token.GETPROP) { functionNameNode.replaceWith(IR.name(CREATE_CLASS_ALIAS_NAME)); } } } } @Override public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) { // Don't want React itself to get annotated (the version with addons creates // defines some classes). if (n.getToken() == Token.SCRIPT && n.getSourceFileName() != null && React.isReactSourceName(n.getSourceFileName())) { return false; } return true; } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (isReactCreateClass(n)) { visitReactCreateClass(n); } else if (isReactCreateMixin(n)) { visitReactCreateMixin(n); } else if (visitMixinAbstractMethod(n)) { // Nothing more needs to be done, mixin abstract method processing is // more efficiently done in one function intead of two. } else if (isReactCreateElement(n)) { visitReactCreateElement(t, n); } } private static boolean isReactCreateClass(Node value) { if (value != null && value.isCall()) { return value.getFirstChild().matchesQualifiedName("React.createClass"); } return false; } private void visitReactCreateClass(Node callNode) { visitReactCreateType( callNode, "React.createClass", reactClassesByName, reactClassInterfacePrototypePropsByName); } private static boolean isReactCreateMixin(Node value) { if (value != null && value.isCall()) { return value.getFirstChild().matchesQualifiedName("React.createMixin"); } return false; } private void visitReactCreateMixin(Node callNode) { visitReactCreateType( callNode, "React.createMixin", reactMixinsByName, reactMixinInterfacePrototypePropsByName); } private void visitReactCreateType( Node callNode, String createFuncName, Map<String, Node> typeSpecNodesByName, Map<String, Node> interfacePrototypePropsByName) { if (!validateCreateTypeUsage(callNode)) { compiler.report(JSError.make( callNode, CREATE_TYPE_TARGET_INVALID, createFuncName)); return; } int paramCount = callNode.getChildCount() - 1; if (paramCount > 1) { compiler.report(JSError.make( callNode, CREATE_TYPE_UNEXPECTED_PARAMS, createFuncName)); return; } Node specNode = callNode.getChildAtIndex(1); if (specNode == null || !specNode.isObjectLit()) { compiler.report(JSError.make( specNode, CREATE_TYPE_SPEC_NOT_VALID, createFuncName)); return; } // Mark the call as not having side effects, so that unused components and // mixins can be removed. callNode.setSideEffectFlags(Node.NO_SIDE_EFFECTS); // Turn the React.createClass call into a type definition for the Closure // compiler. Equivalent to generating the following code around the call: // /** // * @interface // * @extends {ReactComponent} // */ // function ComponentInterface() {} // ComponentInterface.prototype = { // render: function() {}, // otherMethod: function() {} // /** // * @typedef {ComponentInterface} // */ // var Component = React.createClass({ // render: function() {...}, // otherMethod: function() {...} // /** // * @typedef {ReactElement.<Component>} // */ // var ComponentElement; // The <type name>Interface type is necessary in order to teach the compiler // about all the methods that are present on the component. Having it as an // interface means that no extra code ends up being generated (and the // existing code is left untouched). The methods in the interface are just // stubs -- they have the same parameters (and JSDoc is copied over, if // any), but the body is empty. // The @typedef is added to the component variable so that user-authored // code can treat that as the type (the interface is an implementation // detail). // The <type name>Element @typedef is designed to make adding types to // elements for that component less verbose. Node callParentNode = callNode.getParent(); String typeName; Node typeAttachNode; if (callParentNode.isName()) { typeName = callParentNode.getQualifiedName(); typeAttachNode = callParentNode.getParent(); } else if (callParentNode.isAssign() && callParentNode.getFirstChild().isGetProp()) { typeName = callParentNode.getFirstChild().getQualifiedName(); typeAttachNode = callParentNode; } else { compiler.report(JSError.make( callParentNode, COULD_NOT_DETERMINE_TYPE_NAME, createFuncName)); return; } String interfaceTypeName = generateInterfaceTypeName(typeName); // For compomnents tagged with @export don't rename their props or public // methods. JSDocInfo jsDocInfo = NodeUtil.getBestJSDocInfo(callNode); boolean isExportedType = jsDocInfo != null && jsDocInfo.isExport(); List<JSTypeExpression> implementedInterfaces = jsDocInfo != null ? jsDocInfo.getImplementedInterfaces() : Collections.<JSTypeExpression>emptyList(); // Add the @typedef JSDocInfoBuilder jsDocBuilder = newJsDocInfoBuilderForNode(typeAttachNode); jsDocBuilder.recordTypedef(new JSTypeExpression( IR.string(interfaceTypeName), callNode.getSourceFileName())); typeAttachNode.setJSDocInfo(jsDocBuilder.build()); // Record the type so that we can later look it up in React.createElement // calls. typeSpecNodesByName.put(typeName, specNode); // Gather methods for the interface definition. Node interfacePrototypeProps = IR.objectlit(); interfacePrototypePropsByName.put(typeName, interfacePrototypeProps); Map<String, JSDocInfo> abstractMethodJsDocsByName = Maps.newHashMap(); Node propTypesNode = null; List<Node> mixinPropTypeKeyNodes = Lists.newArrayList(); Node getDefaultPropsNode = null; Map<String, JSDocInfo> staticsJsDocs = Maps.newHashMap(); List<String> exportedNames = Lists.newArrayList(); boolean usesPureRenderMixin = false; boolean hasShouldComponentUpdate = false; List<Node> componentMethodKeys = Lists.newArrayList(); for (Node key : specNode.children()) { String keyName = key.getString(); if (keyName.equals("mixins")) { Set<String> mixinNames = addMixinsToType( typeName, key, interfacePrototypeProps, staticsJsDocs, mixinPropTypeKeyNodes); usesPureRenderMixin = mixinNames.contains(REACT_PURE_RENDER_MIXIN_NAME); for (String mixinName : mixinNames) { if (mixinAbstractMethodJsDocsByName.containsKey(mixinName)) { abstractMethodJsDocsByName.putAll( mixinAbstractMethodJsDocsByName.get(mixinName)); } } continue; } if (keyName.equals("propTypes")) { propTypesNode = key; continue; } if (keyName.equals("getDefaultProps")) { getDefaultPropsNode = key; } if (keyName.equals("statics")) { if (createFuncName.equals("React.createClass")) { gatherStaticsJsDocs(key, staticsJsDocs); } continue; } if (!key.hasOneChild() || !key.getFirstChild().isFunction()) { continue; } if (keyName.equals("shouldComponentUpdate")) { hasShouldComponentUpdate = true; } Node func = key.getFirstChild(); // If the function is an implementation of a standard component method // (like shouldComponentUpdate), then copy the parameter and return type // from the ReactComponent interface method, so that it gets type checking // (without an explicit @override annotation, which doesn't appear to work // for interface extending interfaces in any case). JSDocInfo componentMethodJsDoc = componentMethodJsDocs.get(keyName); if (componentMethodJsDoc != null) { componentMethodKeys.add(key); mergeInJsDoc(key, func, componentMethodJsDoc); } // Ditto for abstract methods from mixins. JSDocInfo abstractMethodJsDoc = abstractMethodJsDocsByName.get(keyName); if (abstractMethodJsDoc != null) { // Treat mixin methods as component ones too, as far as making the type // used for props more specific. componentMethodKeys.add(key); mergeInJsDoc(key, func, abstractMethodJsDoc); } // Require an explicit @public annotation (we can't use @export since // it's not allowed on object literal keys and we can't easily remove it // while keeping the rest of the JSDoc intact). if (isExportedType && componentMethodJsDoc == null && key.getJSDocInfo() != null && key.getJSDocInfo().getVisibility() == JSDocInfo.Visibility.PUBLIC) { exportedNames.add(keyName); } // Gather method signatures so that we can declare them where the compiler // can see them. addFuncToInterface( keyName, func, interfacePrototypeProps, key.getJSDocInfo()); // Add a @this {<type name>} annotation to all methods in the spec, to // avoid the compiler complaining dangerous use of "this" in a global // context. jsDocBuilder = newJsDocInfoBuilderForNode(key); // TODO: Generate type for statics to use as the "this" type for // getDefaultProps. Node thisTypeNode = keyName.equals("getDefaultProps") ? new Node(Token.STAR) : new Node(Token.BANG, IR.string(typeName)); jsDocBuilder.recordThisType(new JSTypeExpression( thisTypeNode, key.getSourceFileName())); key.setJSDocInfo(jsDocBuilder.build()); } if (usesPureRenderMixin && hasShouldComponentUpdate) { compiler.report(JSError.make( specNode, PURE_RENDER_MIXIN_SHOULD_COMPONENT_UPDATE_OVERRIDE, typeName)); return; } // Remove propTypes that are not tagged with @struct. It would have been // nice to use @preserve, but that is interpreted immediately (as keeping // the comment), so we couldn't get to it. @struct is sort of appropriate, // since the propTypes are going to be used as structs (for reflection // presumably). if (propTypesNode != null && stripPropTypes && (propTypesNode.getJSDocInfo() == null || !propTypesNode.getJSDocInfo().makesStructs())) { propTypesNode.detachFromParent(); } // Add a "<type name>Element" @typedef for the element type of this class. jsDocBuilder = new JSDocInfoBuilder(true); jsDocBuilder.recordTypedef(new JSTypeExpression( createReactElementTypeExpressionNode(typeName), callNode.getSourceFileName())); Node elementTypedefNode = NodeUtil.newQName( compiler, typeName + "Element"); if (elementTypedefNode.isName()) { elementTypedefNode = IR.var(elementTypedefNode); } elementTypedefNode.setJSDocInfo(jsDocBuilder.build()); if (!elementTypedefNode.isVar()) { elementTypedefNode = IR.exprResult(elementTypedefNode); } elementTypedefNode.useSourceInfoFromForTree(callParentNode); Node elementTypedefInsertionPoint = callParentNode.getParent(); elementTypedefInsertionPoint.getParent().addChildAfter( elementTypedefNode, elementTypedefInsertionPoint); // Generate statics property JSDocs, so that the compiler knows about them. if (createFuncName.equals("React.createClass")) { Node staticsInsertionPoint = callParentNode.getParent(); for (Map.Entry<String, JSDocInfo> entry : staticsJsDocs.entrySet()) { String staticName = entry.getKey(); JSDocInfo staticJsDoc = entry.getValue(); Node staticDeclaration = NodeUtil.newQName( compiler, typeName + "." + staticName); staticDeclaration.setJSDocInfo(staticJsDoc); Node staticExprNode = IR.exprResult(staticDeclaration); staticExprNode.useSourceInfoFromForTree(staticsInsertionPoint); staticsInsertionPoint.getParent().addChildAfter( staticExprNode, staticsInsertionPoint); staticsInsertionPoint = staticExprNode; } } // Trim duplicated properties that have accumulated (due to mixins defining // a method and then classes overriding it). Keep the last one since it's // from the class and thus most specific. ListMultimap<String, Node> interfaceKeyNodes = ArrayListMultimap.create(); for (Node interfaceKeyNode = interfacePrototypeProps.getFirstChild(); interfaceKeyNode != null; interfaceKeyNode = interfaceKeyNode.getNext()) { interfaceKeyNodes.put(interfaceKeyNode.getString(), interfaceKeyNode); } for (String key : interfaceKeyNodes.keySet()) { List<Node> keyNodes = interfaceKeyNodes.get(key); if (keyNodes.size() > 1) { for (Node keyNode : keyNodes.subList(0, keyNodes.size() - 1)) { keyNode.detachFromParent(); } } } // Generate the interface definition. Node interfaceTypeFunctionNode = IR.function(IR.name(""), IR.paramList(), IR.block()); Node interfaceTypeNode = NodeUtil.newQNameDeclaration( compiler, interfaceTypeName, interfaceTypeFunctionNode, null); jsDocBuilder = new JSDocInfoBuilder(true); jsDocBuilder.recordInterface(); jsDocBuilder.recordExtendedInterface(new JSTypeExpression( new Node(Token.BANG, IR.string("ReactComponent")), callNode.getSourceFileName())); for (JSTypeExpression implementedInterface : implementedInterfaces) { jsDocBuilder.recordExtendedInterface(implementedInterface); } interfaceTypeFunctionNode.setJSDocInfo(jsDocBuilder.build()); Node interfaceTypeInsertionPoint = callParentNode.getParent(); interfaceTypeInsertionPoint.getParent().addChildBefore( interfaceTypeNode, interfaceTypeInsertionPoint); interfaceTypeInsertionPoint.getParent().addChildAfter( NodeUtil.newQNameDeclaration( compiler, interfaceTypeName + ".prototype", interfacePrototypeProps, null), interfaceTypeNode); // Merge in propTypes from mixins. if (options.propTypesTypeChecking && !mixinPropTypeKeyNodes.isEmpty()) { Set<String> seenPropNames = Sets.newHashSet(); if (propTypesNode == null) { propTypesNode = IR.stringKey("propType", IR.objectlit()); specNode.addChildToBack(propTypesNode); } else { for (Node propTypeKeyNode : propTypesNode.getFirstChild().children()) { seenPropNames.add(propTypeKeyNode.getString()); } } for (Node mixinPropTypeKeyNode : mixinPropTypeKeyNodes) { String propName = mixinPropTypeKeyNode.getString(); if (seenPropNames.contains(propName)) { continue; } seenPropNames.add(propName); propTypesNode.getFirstChild().addChildToBack( mixinPropTypeKeyNode.cloneTree(true)); } } if (propTypesNode != null && PropTypesExtractor.canExtractPropTypes(propTypesNode)) { if (isExportedType) { for (Node propTypeKeyNode : propTypesNode.getFirstChild().children()) { exportedNames.add(propTypeKeyNode.getString()); } } // Save mixin propTypes so that they can be merged into classes that use // them. if (createFuncName.equals("React.createMixin")) { List<Node> propTypeKeyNodes = Lists.newArrayList(); for (Node propTypeKeyNode : propTypesNode.getFirstChild().children()) { // Clone nodes PropTypesExtractor will mutate. if (propTypeKeyNode.getJSDocInfo() != null && propTypeKeyNode.getJSDocInfo().hasType()) { propTypeKeyNodes.add(propTypeKeyNode.cloneTree(true)); } else { propTypeKeyNodes.add(propTypeKeyNode); } } reactMixinsPropTypesByName.put(typeName, propTypeKeyNodes); } if (options.propTypesTypeChecking) { PropTypesExtractor extractor = new PropTypesExtractor( propTypesNode, getDefaultPropsNode, typeName, interfaceTypeName, compiler); extractor.extract(); extractor.insert(elementTypedefInsertionPoint); if (createFuncName.equals("React.createClass")) { extractor.addToComponentMethods(componentMethodKeys); } propTypesExtractorsByName.put(typeName, extractor); } else { PropTypesExtractor.cleanUpPropTypesWhenNotChecking(propTypesNode); } } if (!exportedNames.isEmpty()) { // Synthesize an externs entry of the form // ComponentExports = {propA: 0, propB: 0, publicMethod: 0}; // To disable naming of exported component props and methods. Node exportedNamesObjectLitNode = IR.objectlit(); for (String exportedName : exportedNames) { Node keyNode = IR.stringKey(exportedName, IR.number(0)); exportedNamesObjectLitNode.addChildToBack(keyNode); } Node exportedNamesNode = NodeUtil.newQNameDeclaration( compiler, typeName.replaceAll("\\.", "\\$\\$") + "Exports", exportedNamesObjectLitNode, null); externsRoot.addChildToBack(exportedNamesNode); } } * /** * * @return {number} * * / * Mixin.abstractMixinMethod; */ private boolean visitMixinAbstractMethod(Node value) { if (value == null || !value.isExprResult() || !value.hasOneChild() || !value.getFirstChild().isGetProp()) { return false; } Node getPropNode = value.getFirstChild(); if (!getPropNode.isQualifiedName() || !getPropNode.hasChildren()) { return false; } String mixinName = getPropNode.getFirstChild().getQualifiedName(); Node mixinSpecNode = reactMixinsByName.get(mixinName); if (mixinSpecNode == null) { return false; } String methodName = getPropNode.getLastChild().getString(); JSDocInfo abstractFuncJsDoc = getPropNode.getJSDocInfo(); Node abstractFuncParamList = IR.paramList(); if (abstractFuncJsDoc != null) { for (String parameterName : abstractFuncJsDoc.getParameterNames()) { abstractFuncParamList.addChildToBack(IR.name(parameterName)); } Map<String, JSDocInfo> jsDocsByName = mixinAbstractMethodJsDocsByName.get(mixinName); if (jsDocsByName == null) { jsDocsByName = Maps.newHashMap(); mixinAbstractMethodJsDocsByName.put(mixinName, jsDocsByName); } jsDocsByName.put(methodName, abstractFuncJsDoc); } Node abstractFuncNode = IR.function( IR.name(""), abstractFuncParamList, IR.block()); abstractFuncNode.useSourceInfoFrom(value); if (abstractFuncJsDoc != null) { abstractFuncNode.setJSDocInfo(abstractFuncJsDoc.clone()); } abstractFuncNode.setStaticSourceFile(value.getStaticSourceFile()); Node interfacePrototypeProps = reactMixinInterfacePrototypePropsByName.get(mixinName); addFuncToInterface( methodName, abstractFuncNode, interfacePrototypeProps, getPropNode.getJSDocInfo()); return true; } private Set<String> addMixinsToType( String typeName, Node mixinsNode, Node interfacePrototypeProps, Map<String, JSDocInfo> staticsJsDocs, List<Node> propTypeKeyNodes) { Set<String> mixinNames = Sets.newHashSet(); if (!mixinsNode.hasOneChild() || !mixinsNode.getFirstChild().isArrayLit()) { compiler.report(JSError.make(mixinsNode, MIXINS_UNEXPECTED_TYPE)); return mixinNames; } Node thisTypeNode = new Node(Token.BANG, IR.string(typeName)); for (Node mixinNameNode : mixinsNode.getFirstChild().children()) { if (!mixinNameNode.isQualifiedName()) { compiler.report(JSError.make(mixinNameNode, MIXIN_EXPECTED_NAME)); continue; } String mixinName = mixinNameNode.getQualifiedName(); if (mixinNames.contains(mixinName)) { continue; } mixinNames.add(mixinName); if (mixinName.equals(REACT_PURE_RENDER_MIXIN_NAME)) { // Built-in mixin, there's nothing more that we need to do. continue; } Node mixinSpecNode = reactMixinsByName.get(mixinName); if (mixinSpecNode == null) { compiler.report(JSError.make(mixinNameNode, MIXIN_UNKNOWN, mixinName)); continue; } List<Node> mixinPropTypes = reactMixinsPropTypesByName.get(mixinName); if (mixinPropTypes != null) { propTypeKeyNodes.addAll(mixinPropTypes); } for (Node mixinSpecKey : mixinSpecNode.children()) { String keyName = mixinSpecKey.getString(); if (keyName.equals("mixins")) { mixinNames.addAll(addMixinsToType( typeName, mixinSpecKey, interfacePrototypeProps, staticsJsDocs, propTypeKeyNodes)); continue; } if (keyName.equals("statics")) { gatherStaticsJsDocs(mixinSpecKey, staticsJsDocs); continue; } JSDocInfo mixinSpecKeyJsDoc = mixinSpecKey.getJSDocInfo(); // Private methods should not be exposed. if (mixinSpecKeyJsDoc != null && mixinSpecKeyJsDoc.getVisibility() == JSDocInfo.Visibility.PRIVATE) { continue; } if (mixinSpecKey.hasOneChild() && mixinSpecKey.getFirstChild().isFunction()) { // Ensure that the @this type inside mixin functions refers to the // type we're copying into, not the mixin type. if (mixinSpecKeyJsDoc != null) { // We can't use JSDocInfoBuilder because it will not override the // "this" type if it's already set. mixinSpecKeyJsDoc = mixinSpecKeyJsDoc.clone(); JSDocInfoAccessor.setJSDocInfoThisType( mixinSpecKeyJsDoc, new JSTypeExpression( thisTypeNode, mixinSpecKey.getSourceFileName())); } Node keyNode = addFuncToInterface( keyName, mixinSpecKey.getFirstChild(), interfacePrototypeProps, mixinSpecKeyJsDoc); // Since mixins are effectively copied into the type, their source // file is the type's (allow private methods from mixins to be // called). keyNode.setStaticSourceFile(mixinsNode.getStaticSourceFile()); } } } return mixinNames; } private static Node addFuncToInterface( String name, Node funcNode, Node interfacePrototypeProps, JSDocInfo jsDocInfo) { // Semi-shallow copy (just parameters) so that we don't copy the function // implementation. Node methodNode = funcNode.cloneNode(); for (Node funcChild = funcNode.getFirstChild(); funcChild != null; funcChild = funcChild.getNext()) { if (funcChild.isParamList()) { Node methodParamList = new Node(Token.PARAM_LIST); for (Node paramNode : funcChild.children()) { // Don't include parameter default values on the interface. They're // not needed and they confuse the compiler (since they'll end up // getting transpiled, and thus the interface method body will not // be empty). if (paramNode.isDefaultValue()) { paramNode = paramNode.getFirstChild(); } methodParamList.addChildToBack(paramNode.cloneTree()); } methodNode.addChildToBack(methodParamList); } else { methodNode.addChildToBack(funcChild.cloneNode()); } } Node keyNode = IR.stringKey(name, methodNode); keyNode.useSourceInfoFrom(funcNode); keyNode.setStaticSourceFile(funcNode.getStaticSourceFile()); if (jsDocInfo != null) { keyNode.setJSDocInfo(jsDocInfo.clone()); } interfacePrototypeProps.addChildToBack(keyNode); return keyNode; } private void gatherStaticsJsDocs( Node staticsNode, Map<String, JSDocInfo> staticsJsDocs) { if (!staticsNode.hasOneChild() || !staticsNode.getFirstChild().isObjectLit()) { compiler.report(JSError.make(staticsNode, STATICS_UNEXPECTED_TYPE)); return; } for (Node staticKeyNode : staticsNode.getFirstChild().children()) { String staticName = staticKeyNode.getString(); JSDocInfo staticJsDoc = staticKeyNode.getJSDocInfo(); if (staticJsDoc == null) { // We need to have some kind of JSDoc so that the CheckSideEffects pass // doesn't flag this as useless code. // TODO: synthesize type based on value if it's a simple constant // like a function or number. staticJsDoc = new JSDocInfoBuilder(true).build(true); } else { staticJsDoc = staticJsDoc.clone(); } staticsJsDocs.put(staticName, staticJsDoc); } } private static void mergeInJsDoc(Node key, Node func, JSDocInfo jsDoc) { List<String> funcParamNames = Lists.newArrayList(); for (Node param : NodeUtil.getFunctionParameters(func).children()) { if (param.isName()) { funcParamNames.add(param.getString()); } } JSDocInfoBuilder jsDocBuilder = newJsDocInfoBuilderForNode(key); if (!funcParamNames.isEmpty()) { for (String parameterName : jsDoc.getParameterNames()) { JSTypeExpression parameterType = jsDoc.getParameterType(parameterName); // Use the parameter names in the implementation, not the original parameterName = funcParamNames.remove(0); jsDocBuilder.recordParameter(parameterName, parameterType); if (funcParamNames.isEmpty()) { break; } } } if (jsDoc.hasReturnType()) { jsDocBuilder.recordReturnType(jsDoc.getReturnType()); } for (String templateTypeName : jsDoc.getTemplateTypeNames()) { jsDocBuilder.recordTemplateTypeName(templateTypeName); } for (Map.Entry<String, Node> entry : jsDoc.getTypeTransformations().entrySet()) { jsDocBuilder.recordTypeTransformation(entry.getKey(), entry.getValue()); } key.setJSDocInfo(jsDocBuilder.build()); } private boolean validateCreateTypeUsage(Node n) { // There are only two valid usage patterns for of React.create{Class|Mixin}: // var ClassName = React.create{Class|Mixin}({...}) // namespace.ClassName = React.create{Class|Mixin}({...}) Node parent = n.getParent(); switch (parent.getToken()) { case NAME: return true; case ASSIGN: return n == parent.getLastChild() && parent.getParent().isExprResult(); } return false; } private void visitReactCreateElement(NodeTraversal t, Node callNode) { int paramCount = callNode.getChildCount() - 1; if (paramCount == 0) { compiler.report(JSError.make(callNode, CREATE_ELEMENT_UNEXPECTED_PARAMS)); return; } if (addReactApiAliases) { // If we're adding aliases that means we're doing an optimized build, so // there's no need for extra type checks. Node functionNameNode = callNode.getFirstChild(); if (functionNameNode.getToken() == Token.GETPROP) { functionNameNode.replaceWith(IR.name(CREATE_ELEMENT_ALIAS_NAME)); } return; } if (callNode.getParent().getToken() == Token.CAST) { // There's already a cast around the call, there's no need to add another. return; } // Add casts of the form /** @type {!ReactElement.<type name>} */ around // React.createElement calls, so that the return value of React.render will // have the correct type (for string types assume that it's a // ReactDOMElement). // It's too expensive to know what the type parameter node actually refers // to, so instead we assume that it directly references the type (this is // the most common case, especially with JSX). This means that we will not // add type annotations for cases such as: // var typeAlias = SomeType; // React.createElement(typeAlias); Node typeNode = callNode.getChildAtIndex(1); Node elementTypeExpressionNode; if (typeNode.isString()) { elementTypeExpressionNode = IR.string("ReactDOMElement"); } else { String typeName = typeNode.getQualifiedName(); if (!reactClassesByName.containsKey(typeName)) { return; } elementTypeExpressionNode = createReactElementTypeExpressionNode(typeName); PropTypesExtractor propTypesExtractor = propTypesExtractorsByName.get(typeName); if (propTypesExtractor != null) { propTypesExtractor.visitReactCreateElement(callNode); } } JSDocInfoBuilder jsDocBuilder = new JSDocInfoBuilder(true); jsDocBuilder.recordType(new JSTypeExpression( new Node(Token.BANG, elementTypeExpressionNode), callNode.getSourceFileName())); JSDocInfo jsDoc = jsDocBuilder.build(); Node callNodePrevious = callNode.getPrevious(); Node callNodeParent = callNode.getParent(); callNode.detach(); Node castNode = IR.cast(callNode, jsDoc); castNode.useSourceInfoFrom(callNode); if (callNodePrevious != null) { callNodeParent.addChildAfter(castNode, callNodePrevious); } else { callNodeParent.addChildToFront(castNode); } } private static boolean isReactCreateElement(Node value) { if (value != null && value.isCall()) { return value.getFirstChild().matchesQualifiedName("React.createElement"); } return false; } /** * Creates the equivalent to ReactElement.<!typeName> */ private static Node createReactElementTypeExpressionNode(String typeName) { Node blockNode = IR.block(); blockNode.addChildToFront(new Node(Token.BANG, IR.string(typeName))); Node typeNode = IR.string("ReactElement"); typeNode.addChildToFront(blockNode); return typeNode; } private static JSDocInfoBuilder newJsDocInfoBuilderForNode(Node node) { JSDocInfo existing = node.getJSDocInfo(); if (existing == null) { return new JSDocInfoBuilder(true); } return JSDocInfoBuilder.copyFrom(existing); } PropTypesExtractor getPropTypesExtractor(String typeName) { return propTypesExtractorsByName.get(typeName); } /** * Generates the type name for the interface that we generate for a component. * Normally of the form <ComponentName>Interface, but for nested components, * we avoid putting the interface as a nested property, since the compiler * appears to have trouble removing it in that case. That is, given: * * const ns = {}; * ns.Comp = React.createClass(...); * ns.Comp.Inner = React.createClass(...); * * We generate interface names ns.CompInterface and ns.Comp_InnerInterface; */ private String generateInterfaceTypeName(String typeName) { String[] typeNameParts = typeName.split("\\."); String typeNamePrefix = ""; for (int i = 0; i < typeNameParts.length; i++) { String prefixCandidate = typeNamePrefix.isEmpty() ? typeNameParts[i] : typeNamePrefix + "." + typeNameParts[i]; if (reactClassesByName.containsKey(prefixCandidate)) { for (; i < typeNameParts.length; i++) { typeNamePrefix += "_" + typeNameParts[i]; } break; } else { typeNamePrefix = prefixCandidate; } } return typeNamePrefix + "Interface"; } }
package org.xins.common.spec; import java.io.IOException; import java.io.Reader; import java.util.List; import java.util.Map; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.collections.ChainedMap; import org.xins.common.text.ParseException; import org.xins.common.xml.Element; import org.xins.common.xml.ElementParser; /** * Specification of a error code (also known as result code). * * @version $Revision$ $Date$ * @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>) * * @since XINS 1.3.0 */ public final class ErrorCodeSpec extends Object { // Class functions // Class fields // Constructor public ErrorCodeSpec(String name, Class reference, String baseURL) throws InvalidSpecificationException { MandatoryArgumentChecker.check("name", name, "reference", reference, "baseURL", baseURL); _errorCodeName = name; try { Reader reader = APISpec.getReader(baseURL, name + ".rcd"); parseErrorCode(reader, reference); } catch (IOException ioe) { throw new InvalidSpecificationException("[ErrorCode: " + name + "] Cannot read error code.", ioe); } } // Fields /** * Name of the function. */ private final String _errorCodeName; /** * Description of the function. */ private String _description; /** * The output parameters of the function. */ private Map _outputParameters = new ChainedMap(); /** * The output data section elements of the function. */ private Map _outputDataSectionElements; // Methods /** * Gets the name of the error code. * * @return * The name of the error code, never <code>null</code>. */ public String getName() { return _errorCodeName; } /** * Gets the description of the error code. * * @return * The description of the error code, never <code>null</code>. */ public String getDescription() { return _description; } public ParameterSpec getOutputParameter(String parameterName) throws EntityNotFoundException, IllegalArgumentException { MandatoryArgumentChecker.check("parameterName", parameterName); ParameterSpec parameter = (ParameterSpec) _outputParameters.get(parameterName); if (parameter == null) { throw new EntityNotFoundException("Output parameter \"" + parameterName + "\" not found in the error code \"" + _errorCodeName +"\"."); } return parameter; } /** * Gets the output parameter specifications defined in the error code. * The key is the name of the parameter, the value is the {@link ParameterSpec} object. * * @return * The output parameters specifications, never <code>null</code>. */ public Map getOutputParameters() { return _outputParameters; } public DataSectionElementSpec getOutputDataSectionElement(String elementName) throws EntityNotFoundException, IllegalArgumentException { MandatoryArgumentChecker.check("elementName", elementName); DataSectionElementSpec element = (DataSectionElementSpec) _outputDataSectionElements.get(elementName); if (element == null) { throw new EntityNotFoundException("Output data section element \"" + elementName + "\" not found in the error code \"" + _errorCodeName +"\"."); } return element; } /** * Gets the specification of the elements of the output data section. * The key is the name of the element, the value is the {@link DataSectionElementSpec} object. * * @return * The specification of the output data section, never <code>null</code>. */ public Map getOutputDataSectionElements() { return _outputDataSectionElements; } private void parseErrorCode(Reader reader, Class reference) throws IllegalArgumentException, IOException, InvalidSpecificationException { MandatoryArgumentChecker.check("reader", reader, "reference", reference); ElementParser parser = new ElementParser(); Element errorCode = null; try { errorCode = parser.parse(reader); } catch (ParseException pe) { throw new InvalidSpecificationException("[ErrorCode: " + _errorCodeName + "] Cannot parse error code.", pe); } // Get the result from the parsed error code specification. List descriptionElementList = errorCode.getChildElements("description"); if (descriptionElementList.isEmpty()) { throw new InvalidSpecificationException("[ErrorCode: " + _errorCodeName + "] No definition specified."); } Element descriptionElement = (Element) errorCode.getChildElements("description").get(0); _description = descriptionElement.getText(); List output = errorCode.getChildElements("output"); if (output.size() > 0) { // Output parameters Element outputElement = (Element) output.get(0); _outputParameters = FunctionSpec.parseParameters(reference, outputElement); // Data section List dataSections = outputElement.getChildElements("data"); if (dataSections.size() > 0) { Element dataSection = (Element) dataSections.get(0); _outputDataSectionElements = FunctionSpec.parseDataSectionElements(reference, dataSection, dataSection); } } } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.samskivert.io.PersistenceException; import com.samskivert.jdbc.depot.annotation.Computed; import com.samskivert.jdbc.depot.annotation.Entity; import com.samskivert.jdbc.depot.annotation.FullTextIndex; import com.samskivert.jdbc.depot.annotation.GeneratedValue; import com.samskivert.jdbc.depot.annotation.Id; import com.samskivert.jdbc.depot.annotation.Index; import com.samskivert.jdbc.depot.annotation.TableGenerator; import com.samskivert.jdbc.depot.annotation.Transient; import com.samskivert.jdbc.depot.annotation.UniqueConstraint; import com.samskivert.jdbc.ColumnDefinition; import com.samskivert.jdbc.DatabaseLiaison; import com.samskivert.util.ArrayUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T extends PersistentRecord> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pClass, PersistenceContext context) { _pClass = pClass; Entity entity = pClass.getAnnotation(Entity.class); // see if this is a computed entity _computed = pClass.getAnnotation(Computed.class); if (_computed == null) { // if not, this class has a corresponding SQL table _tableName = _pClass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); // see if there are Entity values specified if (entity != null) { if (entity.name().length() > 0) { _tableName = entity.name(); } } } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pClass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } boolean seenIdentityGenerator = false; // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pClass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.log(Level.WARNING, "Failed to read schema version " + "[class=" + _pClass + "].", e); } } // the field must be public, non-static and non-transient if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller fm = FieldMarshaller.createMarshaller(field); _fields.put(field.getName(), fm); fields.add(field.getName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller>(); } _pkColumns.add(fm); } // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // check if this field is auto-generated GeneratedValue gv = fm.getGeneratedValue(); if (gv != null) { // we can only do this on numeric fields Class<?> ftype = field.getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column: " + field.getName()); } switch(gv.strategy()) { case AUTO: case IDENTITY: if (seenIdentityGenerator) { throw new IllegalArgumentException( "Persistent records can have at most one AUTO/IDENTITY generator."); } _valueGenerators.put(field.getName(), new IdentityValueGenerator(gv, this, fm)); seenIdentityGenerator = true; break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _valueGenerators.put( field.getName(), new TableValueGenerator(generator, gv, this, fm)); break; } } } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); // now check for @Entity annotations on the entire superclass chain Class<?> iterClass = pClass; do { entity = iterClass.getAnnotation(Entity.class); if (entity != null) { for (UniqueConstraint constraint : entity.uniqueConstraints()) { String[] conFields = constraint.fieldNames(); Set<String> colSet = new HashSet<String>(); for (int ii = 0; ii < conFields.length; ii ++) { FieldMarshaller fm = _fields.get(conFields[ii]); if (fm == null) { throw new IllegalArgumentException( "Unknown unique constraint field: " + conFields[ii]); } colSet.add(fm.getColumnName()); } _uniqueConstraints.add(colSet); } for (Index index : entity.indices()) { if (_indexes.containsKey(index.name())) { continue; } _indexes.put(index.name(), index); } // if there are FTS indexes in the Table, map those out here for future use for (FullTextIndex fti : entity.fullTextIndexes()) { if (_fullTextIndexes.containsKey(fti.name())) { continue; } _fullTextIndexes.put(fti.name(), fti); } } iterClass = iterClass.getSuperclass(); } while (PersistentRecord.class.isAssignableFrom(iterClass) && !PersistentRecord.class.equals(iterClass)); } /** * Returns the persistent class this is object is a marshaller for. */ public Class<T> getPersistentClass () { return _pClass; } /** * Returns the @Computed annotation definition of this entity, or null if none. */ public Computed getComputed () { return _computed; } /** * Returns the name of the table in which persistent instances of our class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns all the persistent fields of our class, in definition order. */ public String[] getFieldNames () { return _allFields; } /** * Returns all the persistent fields that correspond to concrete table columns. */ public String[] getColumnFieldNames () { return _columnFields; } public FullTextIndex getFullTextIndex (String name) { FullTextIndex fti = _fullTextIndexes.get(name); if (fti == null) { throw new IllegalStateException("Persistent class missing full text index " + "[class=" + _pClass + ", index=" + name + "]"); } return fti; } /** * Returns the {@link FieldMarshaller} for a named field on our persistent class. */ public FieldMarshaller getFieldMarshaller (String fieldName) { return _fields.get(fieldName); } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns the {@link ValueGenerator} objects used to automatically generate field values for * us when a new record is inserted. */ public Iterable<ValueGenerator> getValueGenerators () { return _valueGenerators.values(); } /** * Return the names of the columns that constitute the primary key of our associated persistent * record. */ public String[] getPrimaryKeyFields () { String[] pkcols = new String[_pkColumns.size()]; for (int ii = 0; ii < pkcols.length; ii ++) { pkcols[ii] = _pkColumns.get(ii).getField().getName(); } return pkcols; } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. An exception is thrown if some of the fields are null and * some are not, or if the object does not declare a primary key. */ public Key<T> getPrimaryKey (Object object) { return getPrimaryKey(object, true); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. If some of the fields are null and some are not, an * exception is thrown. If the object does not declare a primary key and the second argument is * true, this method throws an exception; if it's false, the method returns null. */ public Key<T> getPrimaryKey (Object object, boolean requireKey) { if (!hasPrimaryKey()) { if (requireKey) { throw new UnsupportedOperationException( _pClass.getName() + " does not define a primary key"); } return null; } try { Comparable[] values = new Comparable[_pkColumns.size()]; int nulls = 0; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); if ((values[ii] = (Comparable)field.getField().get(object)) == null) { nulls++; } } // make sure the keys are all null or all non-null if (nulls == 0) { return makePrimaryKey(values); } else if (nulls == values.length) { return null; } // throw an informative error message StringBuilder keys = new StringBuilder(); for (int ii = 0; ii < _pkColumns.size(); ii++) { keys.append(", ").append(_pkColumns.get(ii).getField().getName()); keys.append("=").append(values[ii]); } throw new IllegalArgumentException("Primary key fields are mixed null and non-null " + "[class=" + _pClass.getName() + keys + "]."); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key<T> makePrimaryKey (Comparable... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } String[] fields = new String[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { fields[ii] = _pkColumns.get(ii).getField().getName(); } return new Key<T>(_pClass, fields, values); } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied result set. */ public Key<T> makePrimaryKey (ResultSet rs) throws SQLException { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } Comparable[] values = new Comparable[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { Object keyValue = _pkColumns.get(ii).getFromSet(rs); if (!(keyValue instanceof Comparable)) { throw new IllegalArgumentException("Key field must be Comparable [field=" + _pkColumns.get(ii).getColumnName() + "]"); } values[ii] = (Comparable) keyValue; } return makePrimaryKey(values); } /** * Returns true if this marshaller has been initialized ({@link #init} has been called), its * migrations run and it is ready for operation. False otherwise. */ public boolean isInitialized () { return _initialized; } /** * Creates a persistent object from the supplied result set. The result set must have come from * a query provided by {@link #createQuery}. */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = new HashSet<String>(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pClass.newInstance(); for (FieldMarshaller fm : _fields.values()) { if (!fields.contains(fm.getColumnName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException("ResultSet missing field: " + fm.getField().getName()); } fm.writeToObject(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [class=" + _pClass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Go through the registered {@link ValueGenerator}s for our persistent object and run the * ones that match the current postFactum phase, filling in the fields on the supplied object * while we go. This method used to generate a key; that is now a separate step. * * The return value is only non-empty for the !postFactum phase, in which case it is a set * of field names that are associated with {@link IdentityValueGenerator}, because these need * special handling in the INSERT (specifically, 'DEFAULT' must be supplied as a value in * the eventual SQL). */ public Set<String> generateFieldValues ( Connection conn, DatabaseLiaison liaison, Object po, boolean postFactum) { Set<String> idFields = new HashSet<String>(); for (ValueGenerator vg : _valueGenerators.values()) { if (!postFactum && vg instanceof IdentityValueGenerator) { idFields.add(vg.getFieldMarshaller().getField().getName()); } if (vg.isPostFactum() != postFactum) { continue; } try { int nextValue = vg.nextGeneratedValue(conn, liaison); vg.getFieldMarshaller().getField().set(po, nextValue); } catch (Exception e) { throw new IllegalStateException( "Failed to assign primary key [type=" + _pClass + "]", e); } } return idFields; } /** * This is called by the persistence context to register a migration for the entity managed by * this marshaller. */ protected void registerMigration (EntityMigration migration) { _migrations.add(migration); } /** * Initializes the table used by this marshaller. This is called automatically by the {@link * PersistenceContext} the first time an entity is used. If the table does not exist, it will * be created. If the schema version specified by the persistent object is newer than the * database schema, it will be migrated. */ protected void init (final PersistenceContext ctx) throws PersistenceException { if (_initialized) { // sanity check throw new IllegalStateException( "Cannot re-initialize marshaller [type=" + _pClass + "]."); } _initialized = true; final SQLBuilder builder = ctx.getSQLBuilder(new DepotTypes(ctx, _pClass)); // perform the context-sensitive initialization of the field marshallers for (FieldMarshaller fm : _fields.values()) { fm.init(builder); } // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new String[_allFields.length]; ColumnDefinition[] declarations = new ColumnDefinition[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { FieldMarshaller fm = _fields.get(_allFields[ii]); // include all persistent non-computed fields ColumnDefinition colDef = fm.getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; declarations[jj] = colDef; jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); declarations = ArrayUtil.splice(declarations, jj); // if we did not find a schema version field, complain if (_schemaVersion < 0) { log.warning("Unable to read " + _pClass.getName() + "." + SCHEMA_VERSION_FIELD + ". Schema migration disabled."); } // check to see if our schema version table exists, create it if not ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.createTableIfMissing( conn, SCHEMA_VERSION_TABLE, new String[] { "persistentClass", "version" }, new ColumnDefinition[] { new ColumnDefinition("VARCHAR(255)", false, true, null), new ColumnDefinition("INTEGER", false, false, null) }, null, new String[] { "persistentClass" }); return 0; } }); // fetch all relevant information regarding our table from the database TableMetaData metaData = TableMetaData.load(ctx, getTableName()); // if the table does not exist, create it if (!metaData.tableExists) { final ColumnDefinition[] fDeclarations = declarations; final String[][] uniqueConCols = new String[_uniqueConstraints.size()][]; int kk = 0; for (Set<String> colSet : _uniqueConstraints) { uniqueConCols[kk++] = colSet.toArray(new String[colSet.size()]); } final Iterable<Index> indexen = _indexes.values(); ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { // create the table String[] primaryKeyColumns = null; if (_pkColumns != null) { primaryKeyColumns = new String[_pkColumns.size()]; for (int ii = 0; ii < primaryKeyColumns.length; ii ++) { primaryKeyColumns[ii] = _pkColumns.get(ii).getColumnName(); } } liaison.createTableIfMissing( conn, getTableName(), fieldsToColumns(_columnFields), fDeclarations, uniqueConCols, primaryKeyColumns); // add its indexen for (Index idx : indexen) { liaison.addIndexToTable( conn, getTableName(), fieldsToColumns(idx.fields()), getTableName() + "_" + idx.name(), idx.unique()); } // initialize our value generators for (ValueGenerator vg : _valueGenerators.values()) { vg.init(conn, liaison); } // and its full text search indexes for (FullTextIndex fti : _fullTextIndexes.values()) { builder.addFullTextSearch(conn, DepotMarshaller.this, fti); } updateVersion(conn, liaison, _schemaVersion); return 0; } }); // and we're done return; } // if the table exists, see if should attempt automatic schema migration if (_schemaVersion < 0) { // nope, versioning disabled verifySchemasMatch(metaData, ctx, builder); return; } // make sure the versions match int currentVersion = ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { String query = " select " + liaison.columnSQL("version") + " from " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " where " + liaison.columnSQL("persistentClass") + " = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery(query); return (rs.next()) ? rs.getInt(1) : 1; } finally { stmt.close(); } } }); if (currentVersion >= _schemaVersion) { verifySchemasMatch(metaData, ctx, builder); return; } // otherwise try to migrate the schema log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); if (_migrations.size() > 0) { // run our pre-default-migrations for (EntityMigration migration : _migrations) { if (migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // we don't know what the pre-migrations did so we have to re-read metadata metaData = TableMetaData.load(ctx, getTableName()); } // this is a little silly, but we need a copy for name disambiguation later Set<String> indicesCopy = new HashSet<String>(metaData.indexColumns.keySet()); // add any missing columns for (String fname : _columnFields) { final FieldMarshaller fmarsh = _fields.get(fname); if (metaData.tableColumns.remove(fmarsh.getColumnName())) { continue; } // otherwise add the column final ColumnDefinition coldef = fmarsh.getColumnDefinition(); log.info("Adding column to " + getTableName() + ": " + fmarsh.getColumnName()); ctx.invoke(new Modifier.Simple() { protected String createQuery (DatabaseLiaison liaison) { return "alter table " + liaison.tableSQL(getTableName()) + " add column " + liaison.columnSQL(fmarsh.getColumnName()) + " " + liaison.expandDefinition(coldef); } }); // if the column is a TIMESTAMP or DATETIME column, we need to run a special query to // update all existing rows to the current time because MySQL annoyingly assigns // TIMESTAMP columns a value of "0000-00-00 00:00:00" regardless of whether we // explicitly provide a "DEFAULT" value for the column or not, and DATETIME columns // cannot accept CURRENT_TIME or NOW() defaults at all. if (coldef.getType().equalsIgnoreCase("timestamp") || coldef.getType().equalsIgnoreCase("datetime")) { log.info("Assigning current time to " + fmarsh.getColumnName() + "."); ctx.invoke(new Modifier.Simple() { protected String createQuery (DatabaseLiaison liaison) { // TODO: is NOW() standard SQL? return "update " + liaison.tableSQL(getTableName()) + " set " + liaison.columnSQL(fmarsh.getColumnName()) + " = NOW()"; } }); } } // add or remove the primary key as needed if (hasPrimaryKey() && metaData.pkName == null) { log.info("Adding primary key."); ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addPrimaryKey( conn, getTableName(), fieldsToColumns(getPrimaryKeyFields())); return 0; } }); } else if (!hasPrimaryKey() && metaData.pkName != null) { final String pkName = metaData.pkName; log.info("Dropping primary key: " + pkName); ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.dropPrimaryKey(conn, getTableName(), pkName); return 0; } }); } // add any named indices that exist on the record but not yet on the table for (final Index index : _indexes.values()) { final String ixName = getTableName() + "_" + index.name(); if (metaData.indexColumns.containsKey(ixName)) { // this index already exists metaData.indexColumns.remove(ixName); continue; } // but this is a new, named index, so we create it ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addIndexToTable( conn, getTableName(), fieldsToColumns(index.fields()), ixName, index.unique()); return 0; } }); } // now check if there are any @Entity(uniqueConstraints) that need to be created Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(metaData.indexColumns.values()); // unique constraints are unordered and may be unnamed, so we view them only as column sets for (Set<String> colSet : _uniqueConstraints) { if (uniqueIndices.contains(colSet)) { // the table already contains precisely this column set continue; } // else build the new constraint; we'll name it after one of its columns, adding _N // to resolve any possible ambiguities, because using all the column names in the // index name may exceed the maximum length of an SQL identifier String indexName = colSet.iterator().next(); if (indicesCopy.contains(indexName)) { int num = 1; indexName += "_"; while (indicesCopy.contains(indexName + num)) { num ++; } indexName += num; } final String[] colArr = colSet.toArray(new String[colSet.size()]); final String fName = indexName; ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addIndexToTable(conn, getTableName(), colArr, fName, true); return 0; } }); } // next we create any full text search indexes that exist on the record but not in the // table, first step being to do a dialect-sensitive enumeration of existing indexes Set<String> tableFts = new HashSet<String>(); builder.getFtsIndexes(metaData.tableColumns, metaData.indexColumns.keySet(), tableFts); // then iterate over what should be there for (final FullTextIndex recordFts : _fullTextIndexes.values()) { if (tableFts.contains(recordFts.name())) { // the table already contains this one continue; } // but not this one, so let's create it ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { builder.addFullTextSearch(conn, DepotMarshaller.this, recordFts); return 0; } }); } // we do not auto-remove columns but rather require that EntityMigration.Drop records be // registered by hand to avoid accidentally causing the loss of data // we don't auto-remove indices either because we'd have to sort out the potentially // complex origins of an index (which might be because of a @Unique column or maybe the // index was hand defined in a @Column clause) // run our post-default-migrations for (EntityMigration migration : _migrations) { if (!migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // last of all (re-)initialize our value generators, since one might've been added if (_valueGenerators.size() > 0) { ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { for (ValueGenerator vg : _valueGenerators.values()) { vg.init(conn, liaison); } return 0; } }); } // record our new version in the database ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { updateVersion(conn, liaison, _schemaVersion); return 0; } }); } // translate an array of field names to an array of column names protected String[] fieldsToColumns (String[] fields) { String[] columns = new String[fields.length]; for (int ii = 0; ii < columns.length; ii ++) { FieldMarshaller<?> fm = _fields.get(fields[ii]); if (fm == null) { throw new IllegalArgumentException( "Unknown field on record [field=" + fields[ii] + ", class=" + _pClass + "]"); } columns[ii] = fm.getColumnName(); } return columns; } /** * Checks that there are no database columns for which we no longer have Java fields. */ protected void verifySchemasMatch ( TableMetaData meta, PersistenceContext ctx, SQLBuilder builder) throws PersistenceException { for (String fname : _columnFields) { FieldMarshaller fmarsh = _fields.get(fname); meta.tableColumns.remove(fmarsh.getColumnName()); } for (String column : meta.tableColumns) { if (builder.isPrivateColumn(column)) { continue; } log.warning(getTableName() + " contains stale column '" + column + "'."); } } protected void updateVersion (Connection conn, DatabaseLiaison liaison, int version) throws SQLException { String update = "update " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " set " + liaison.columnSQL("version") + " = " + version + " where " + liaison.columnSQL("persistentClass") + " = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { if (stmt.executeUpdate(update) == 0) { String insert = "insert into " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " values('" + getTableName() + "', " + version + ")"; stmt.executeUpdate(insert); } } finally { stmt.close(); } } protected static class TableMetaData { public boolean tableExists; public Set<String> tableColumns = new HashSet<String>(); public Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>(); public String pkName; public Set<String> pkColumns = new HashSet<String>(); public static TableMetaData load (PersistenceContext ctx, final String tableName) throws PersistenceException { return ctx.invoke(new Query.TrivialQuery<TableMetaData>() { public TableMetaData invoke (Connection conn, DatabaseLiaison dl) throws SQLException { return new TableMetaData(conn.getMetaData(), tableName); } }); } public TableMetaData (DatabaseMetaData meta, String tableName) throws SQLException { tableExists = meta.getTables("", "", tableName, null).next(); if (!tableExists) { return; } ResultSet rs = meta.getColumns(null, null, tableName, "%"); while (rs.next()) { tableColumns.add(rs.getString("COLUMN_NAME")); } rs = meta.getIndexInfo(null, null, tableName, false, false); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); Set<String> set = indexColumns.get(indexName); if (rs.getBoolean("NON_UNIQUE")) { // not a unique index: just make sure there's an entry in the keyset if (set == null) { indexColumns.put(indexName, null); } } else { // for unique indices we collect the column names if (set == null) { set = new HashSet<String>(); indexColumns.put(indexName, set); } set.add(rs.getString("COLUMN_NAME")); } } rs = meta.getPrimaryKeys(null, null, tableName); while (rs.next()) { pkName = rs.getString("PK_NAME"); pkColumns.add(rs.getString("COLUMN_NAME")); } } } /** The persistent object class that we manage. */ protected Class<T> _pClass; /** The name of our persistent object table. */ protected String _tableName; /** The @Computed annotation of this entity, or null. */ protected Computed _computed; /** A mapping of field names to value generators for that field. */ protected Map<String, ValueGenerator> _valueGenerators = new HashMap<String, ValueGenerator>(); /** A field marshaller for each persistent field in our object. */ protected Map<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>(); /** The field marshallers for our persistent object's primary key columns or null if it did not * define a primary key. */ protected ArrayList<FieldMarshaller> _pkColumns; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** The indexes defined in @Entity annotations for this record. */ protected Map<String, Index> _indexes = new HashMap<String, Index>(); /** The unique constraints defined in @Entity annotations for this record. */ protected Set<Set<String>> _uniqueConstraints = new HashSet<Set<String>>(); protected Map<String, FullTextIndex> _fullTextIndexes = new HashMap<String, FullTextIndex>(); /** The version of our persistent object schema as specified in the class definition. */ protected int _schemaVersion = -1; /** Indicates that we have been initialized (created or migrated our tables). */ protected boolean _initialized; /** A list of hand registered entity migrations to run prior to doing the default migration. */ protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>(); /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.logging.Level; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.TableGenerator; import javax.persistence.Transient; import com.samskivert.jdbc.JDBCUtil; import com.samskivert.jdbc.depot.expression.ColumnExpression; import com.samskivert.util.ArrayUtil; import com.samskivert.util.ListUtil; import com.samskivert.util.StringUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pclass, PersistenceContext context) { _pclass = pclass; // determine our table name _tableName = _pclass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pclass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pclass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if ((mods & Modifier.STATIC) != 0 && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.log(Level.WARNING, "Failed to read schema version " + "[class=" + _pclass + "].", e); } } // the field must be public, non-static and non-transient if (((mods & Modifier.PUBLIC) == 0) || ((mods & Modifier.STATIC) != 0) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller fm = FieldMarshaller.createMarshaller(field); _fields.put(fm.getColumnName(), fm); fields.add(fm.getColumnName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller>(); } _pkColumns.add(fm); // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } } } // if the entity defines a single-columnar primary key, figure out if we will be generating // values for it if (_pkColumns != null) { GeneratedValue gv = null; FieldMarshaller keyField = null; // loop over fields to see if there's a @GeneratedValue at all for (FieldMarshaller field : _pkColumns) { gv = field.getGeneratedValue(); if (gv != null) { keyField = field; break; } } if (keyField != null) { // and if there is, make sure we've a single-column id if (_pkColumns.size() > 1) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on multiple-column @Id's"); } // the primary key must be numeric if we are to auto-assign it Class<?> ftype = keyField.getField().getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column"); } switch(gv.strategy()) { case AUTO: case IDENTITY: _keyGenerator = new IdentityKeyGenerator(); break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _keyGenerator = new TableKeyGenerator(generator); break; } } } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); // figure out the list of fields that correspond to actual table columns and create the SQL // used to create and migrate our table _columnFields = new String[_allFields.length]; _columnDefinitions = new String[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { // include all persistent non-computed fields String colDef = _fields.get(_allFields[ii]).getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; _columnDefinitions[jj] = colDef; jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); _columnDefinitions = ArrayUtil.splice(_columnDefinitions, jj); // add the primary key, if we have one if (hasPrimaryKey()) { String[] indices = new String[_pkColumns.size()]; for (int ii = 0; ii < indices.length; ii ++) { indices[ii] = _pkColumns.get(ii).getColumnName(); } _columnDefinitions = ArrayUtil.append( _columnDefinitions, "PRIMARY KEY (" + StringUtil.join(indices, ", ") + ")"); } _postamble = ""; // TODO: add annotations for the postamble // if we did not find a schema version field, complain if (_schemaVersion < 0) { log.warning("Unable to read " + _pclass.getName() + "." + SCHEMA_VERSION_FIELD + ". Schema migration disabled."); } } /** * Returns the name of the table in which persistence instances of this class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns a key configured with the primary key of the supplied object. Throws an exception * if the persistent object did not declare a primary key. */ public Key getPrimaryKey (Object object) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } try { Comparable[] values = new Comparable[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); values[ii] = (Comparable) field.getField().get(object); } return makePrimaryKey(values); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key makePrimaryKey (Comparable... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } if (values.length != _pkColumns.size()) { throw new IllegalArgumentException( "Argument count (" + values.length + ") must match primary key size (" + _pkColumns.size() + ")"); } ColumnExpression[] columns = new ColumnExpression[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); columns[ii] = new ColumnExpression(_pclass, field.getColumnName()); } return new Key(columns, values); } /** * Initializes the table used by this marshaller. If the table does not exist, it will be * created. If the schema version specified by the persistent object is newer than the database * schema, it will be migrated. */ public void init (Connection conn) throws SQLException { // check to see if our schema version table exists, create it if not JDBCUtil.createTableIfMissing(conn, SCHEMA_VERSION_TABLE, new String[] { "persistentClass VARCHAR(255) NOT NULL", "version INTEGER NOT NULL" }, ""); // now create the table for our persistent class if it does not exist if (!JDBCUtil.tableExists(conn, getTableName())) { log.fine("Creating table " + getTableName() + " (" + StringUtil.join(_columnDefinitions, ", ") + ") " + _postamble); JDBCUtil.createTableIfMissing(conn, getTableName(), _columnDefinitions, _postamble); updateVersion(conn, 1); } // if we have a key generator, initialize that too if (_keyGenerator != null) { _keyGenerator.init(conn); } // if schema versioning is disabled, stop now if (_schemaVersion < 0) { return; } // make sure the versions match int currentVersion = readVersion(conn); if (currentVersion == _schemaVersion) { return; } log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); // otherwise try to migrate the schema; doing column additions magically and running any // registered hand-migrations DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getColumns(null, null, getTableName(), "%"); HashSet<String> columns = new HashSet<String>(); while (rs.next()) { columns.add(rs.getString("COLUMN_NAME")); } for (String fname : _columnFields) { FieldMarshaller fmarsh = _fields.get(fname); if (columns.contains(fmarsh.getColumnName())) { continue; } // otherwise add the column String coldef = fmarsh.getColumnDefinition(); String query = "alter table " + getTableName() + " add column " + coldef; // try to add it to the appropriate spot int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName()); if (fidx == 0) { query += " first"; } else { query += " after " + _allFields[fidx-1]; } log.info("Adding column to " + getTableName() + ": " + coldef); Statement stmt = conn.createStatement(); try { stmt.executeUpdate(query); } finally { stmt.close(); } } // TODO: run any registered hand migrations updateVersion(conn, _schemaVersion); } /** * Creates a persistent object from the supplied result set. The result set must have come from * a query provided by {@link #createQuery}. */ public T createObject (ResultSet rs) throws SQLException { try { T po = (T)_pclass.newInstance(); for (FieldMarshaller fm : _fields.values()) { fm.getValue(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will insert the supplied persistent object into the database. */ public PreparedStatement createInsert (Connection conn, Object po) throws SQLException { try { StringBuilder insert = new StringBuilder(); insert.append("insert into ").append(getTableName()); insert.append(" (").append(StringUtil.join(_columnFields, ",")); insert.append(")").append(" values("); for (int ii = 0; ii < _columnFields.length; ii++) { if (ii > 0) { insert.append(", "); } insert.append("?"); } insert.append(")"); // TODO: handle primary key, nullable fields specially? PreparedStatement pstmt = conn.prepareStatement(insert.toString()); int idx = 0; for (String field : _columnFields) { _fields.get(field).setValue(po, pstmt, ++idx); } return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Fills in the primary key just assigned to the supplied persistence object by the execution * of the results of {@link #createInsert}. * * @return the newly assigned primary key or null if the object does not use primary keys or * this is not the right time to assign the key. */ public Key assignPrimaryKey (Connection conn, Object po, boolean postFactum) throws SQLException { // if we have no primary key or no generator, then we're done if (!hasPrimaryKey() || _keyGenerator == null) { return null; } // run this generator either before or after the actual insertion if (_keyGenerator.isPostFactum() != postFactum) { return null; } try { int nextValue = _keyGenerator.nextGeneratedValue(conn); _pkColumns.get(0).getField().set(po, nextValue); return makePrimaryKey(nextValue); } catch (Exception e) { String errmsg = "Failed to assign primary key [type=" + _pclass + "]"; throw (SQLException) new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the supplied persistent object using the supplied key. */ public PreparedStatement createUpdate (Connection conn, Object po, Key key) throws SQLException { return createUpdate(conn, po, key, _columnFields); } /** * Creates a statement that will update the supplied persistent object * using the supplied key. */ public PreparedStatement createUpdate ( Connection conn, Object po, Key key, String[] modifiedFields) throws SQLException { StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } update.append(" where "); key.appendClause(null, update); try { PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (String field : modifiedFields) { _fields.get(field).setValue(po, pstmt, ++idx); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object " + "[pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the specified set of fields for all persistent objects * that match the supplied key. */ public PreparedStatement createPartialUpdate ( Connection conn, Key key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } update.append(" where "); key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (Object value : modifiedValues) { // TODO: use the field marshaller? pstmt.setObject(++idx, value); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } /** * Creates a statement that will delete all rows matching the supplied key. */ public PreparedStatement createDelete (Connection conn, Key key) throws SQLException { StringBuilder query = new StringBuilder("delete from " + getTableName() + " where "); key.appendClause(null, query); PreparedStatement pstmt = conn.prepareStatement(query.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * Creates a statement that will update the specified set of fields, using the supplied literal * SQL values, for all persistent objects that match the supplied key. */ public PreparedStatement createLiteralUpdate ( Connection conn, Key key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); for (int ii = 0; ii < modifiedFields.length; ii++) { if (ii > 0) { update.append(", "); } update.append(modifiedFields[ii]).append(" = "); update.append(modifiedValues[ii]); } update.append(" where "); key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); key.bindArguments(pstmt, 1); return pstmt; } protected void updateVersion (Connection conn, int version) throws SQLException { String update = "update " + SCHEMA_VERSION_TABLE + " set version = " + version + " where persistentClass = '" + getTableName() + "'"; String insert = "insert into " + SCHEMA_VERSION_TABLE + " values('" + getTableName() + "', " + version + ")"; Statement stmt = conn.createStatement(); try { if (stmt.executeUpdate(update) == 0) { stmt.executeUpdate(insert); } } finally { stmt.close(); } } protected int readVersion (Connection conn) throws SQLException { String query = "select version from " + SCHEMA_VERSION_TABLE + " where persistentClass = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery(query); return (rs.next()) ? rs.getInt(1) : 1; } finally { stmt.close(); } } /** The persistent object class that we manage. */ protected Class<T> _pclass; /** The name of our persistent object table. */ protected String _tableName; /** A field marshaller for each persistent field in our object. */ protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>(); /** The field marshallers for our persistent object's primary key columns * or null if it did not define a primary key. */ protected ArrayList<FieldMarshaller> _pkColumns; /** The generator to use for auto-generating primary key values, or null. */ protected KeyGenerator _keyGenerator; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** The version of our persistent object schema as specified in the class * definition. */ protected int _schemaVersion = -1; /** Used when creating and migrating our table schema. */ protected String[] _columnDefinitions; /** Used when creating and migrating our table schema. */ protected String _postamble; /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; }
package com.sun.facelets.el; import java.util.HashMap; import java.util.Map; import javax.el.ELException; import javax.el.ValueExpression; import javax.el.VariableMapper; /** * Utility class for wrapping another VariableMapper with a new context, * represented by a {@link java.util.Map Map}. Modifications occur to the Map * instance, but resolve against the wrapped VariableMapper if the Map doesn't * contain the ValueExpression requested. * * @author Jacob Hookom * @version $Id: VariableMapperWrapper.java,v 1.3 2006/12/19 04:33:59 jhook Exp $ */ public final class VariableMapperWrapper extends VariableMapper { private final VariableMapper target; private Map vars; public VariableMapperWrapper(VariableMapper orig) { super(); this.target = orig; } /** * First tries to resolve agains the inner Map, then the wrapped * ValueExpression. * * @see javax.el.VariableMapper#resolveVariable(java.lang.String) */ public ValueExpression resolveVariable(String variable) { ValueExpression ve = null; try { if (this.vars != null) { ve = (ValueExpression) this.vars.get(variable); } if (ve == null) { return this.target.resolveVariable(variable); } return ve; } catch (StackOverflowError e) { throw new ELException("Could not Resolve Variable [Overflow]: " + variable, e); } } /** * Set the ValueExpression on the inner Map instance. * * @see javax.el.VariableMapper#setVariable(java.lang.String, * javax.el.ValueExpression) */ public ValueExpression setVariable(String variable, ValueExpression expression) { if (this.vars == null) { this.vars = new HashMap(); } return (ValueExpression) this.vars.put(variable, expression); } }
package io.compgen.cgpipe.parser.variable; import io.compgen.cgpipe.exceptions.MethodCallException; import io.compgen.cgpipe.exceptions.MethodNotFoundException; import io.compgen.cgpipe.exceptions.VarTypeException; import io.compgen.common.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class VarList extends VarValue { protected List<VarValue> vals = new ArrayList<VarValue>(); public VarList() { super(null); } public VarList(VarValue[] vals) throws VarTypeException { super(null); for (VarValue val: vals) { add(val); } } public VarList(List<VarValue> vals) throws VarTypeException { super(null); for (VarValue val: vals) { add(val); } } public String toString() { return StringUtils.join(" ", vals); } public boolean isList() { return true; } public VarValue add(VarValue val) throws VarTypeException { for (VarValue v: val.iterate()) { vals.add(v); } return this; } public VarValue mul(VarValue val) throws VarTypeException { if (val.getClass().equals(VarInt.class)) { long len = ((VarInt)val).toInt(); List<VarValue> tmp = new ArrayList<VarValue>(); for (long i=0; i<len; i++) { for (VarValue v: vals) { tmp.add(v); } } return new VarList(tmp); } throw new VarTypeException("Invalid operation"); } public Iterable<VarValue> iterate() { return Collections.unmodifiableList(vals); } public int sizeInner() { return vals.size(); } public VarValue sliceInner(int start, int end) throws VarTypeException { if (end-start == 1) { return vals.get(start); } return new VarList(this.vals.subList(start, end)); } public VarValue call(String method, VarValue[] args) throws MethodNotFoundException, MethodCallException { try { return super.call(method, args); } catch (MethodNotFoundException e1) { if (method.equals("length")) { if (args.length != 0) { throw new MethodCallException("Bad or missing argument! length()"); } return new VarInt(((List<VarValue>)vals).size()); } else if (method.equals("join")) { if (args.length != 1) { throw new MethodCallException("Bad or missing argument! join(str)"); } String s = ""; for (VarValue val: vals) { if (!s.equals("")) { s += args[0].toString(); } s += val.toString(); } return new VarString(s); } throw new MethodNotFoundException("Method not found: "+method+" list="+this); } } }
package com.weblyzard.api.datatype; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Comparator; import javax.xml.bind.DatatypeConverter; import javax.xml.bind.annotation.adapters.XmlAdapter; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.weblyzard.api.serialize.json.MD5DigestDeserializer; import com.weblyzard.api.serialize.json.MD5DigestSerializer; /** * A performance and memory optimized representation of MD5Digests. * * @author albert.weichselbraun@htwchur.ch */ @JsonSerialize(using = MD5DigestSerializer.class) @JsonDeserialize(using = MD5DigestDeserializer.class) public class MD5Digest extends XmlAdapter<String, MD5Digest> implements Serializable, Comparator<MD5Digest>, Comparable<MD5Digest> { private static final long serialVersionUID = 1L; private long low; private long high; public MD5Digest(byte[] m) { high = fromBytes(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7]); low = fromBytes(m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]); } public MD5Digest() {} public static MD5Digest fromHexDigest(String hexString) { byte[] messageDigest = DatatypeConverter.parseHexBinary(hexString); return new MD5Digest(messageDigest); } public static MD5Digest fromText(String text) { return new MD5Digest(getMessageDigest().digest(text.getBytes())); } @Override public int hashCode() { return (int) (low ^ (low >>> 32) ^ high ^ (high >>> 32)); } @Override public boolean equals(Object o) { if (!(o instanceof MD5Digest)) { return false; } MD5Digest m = (MD5Digest) o; return low == m.low && high == m.high; } @Override public String toString() { return String.format("%016X%016X", high, low).toLowerCase(); } public static MessageDigest getMessageDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // MD5 is supported according to the JVM specification // this case can never happen... throw new RuntimeException("The MD5 message digest is not supported by the JVM."); } } @Override public MD5Digest unmarshal(String s) throws Exception { return (s == null || s.isEmpty()) ? null : MD5Digest.fromHexDigest(s); } @Override public String marshal(MD5Digest digest) throws Exception { return digest == null ? "" : digest.toString(); } private static long fromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24 | (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL); } @Override public int compare(MD5Digest d1, MD5Digest d2) { if (d1.high > d2.high) { return 1; } else if (d1.high < d2.high) { return -1; } if (d1.low > d2.low) { return 1; } else if (d1.low < d2.low) { return -1; } return 0; } @Override public int compareTo(MD5Digest o) { return compare(this, o); } }
package org.apache.commons.lang; import java.util.Random; /** * <p>Common random <code>String</code> manipulation routines.</p> * * <p>Originally from the GenerationJava Core library.</p> * * @author <a href="mailto:bayard@generationjava.com">Henri Yandell</a> * @author <a href="mailto:steven@caswell.name">Steven Caswell</a> * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> * @version $Id: RandomStringUtils.java,v 1.3 2002/09/18 19:52:26 bayard Exp $ */ public class RandomStringUtils { /** * Random object used by random method. This has to be not local * to the random method so as to not return the same value in the * same millisecond. */ private static final Random RANDOM = new Random(); /** * Prevent construction of RandomStringUtils instances */ public RandomStringUtils() { } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of all characters. * * @param count length of random string to create * @return the random string */ public static String random(int count) { return random(count, false, false); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of characters whose * ASCII value is between 32 and 127 . * * @param count length of random string to create * @return the random string */ public static String randomAscii(int count) { return random(count, 32, 127, false, false); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of alphabetic * characters. * * @param count length of random string to create * @return the random string */ public static String randomAlphabetic(int count) { return random(count, true, false); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of alpha-numeric * characters. * * @param count length of random string to create * @return the random string */ public static String randomAlphanumeric(int count) { return random(count, true, true); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of numeric * characters. * * @param count length of random string to create * @return the random string */ public static String randomNumeric(int count) { return random(count, false, true); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of alpha-numeric * characters as indicated by the arguments. * * @param count length of random string to create * @param letters if <code>true</code>, generated string will include * alphabetic characters * @param numbers if <code>true</code>, generatd string will include * numeric characters * @return the random string */ public static String random(int count, boolean letters, boolean numbers) { return random(count, 0, 0, letters, numbers); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of alpha-numeric * characters as indicated by the arguments. * * @param count length of random string to create * @param start int position in set of chars to start at * @param end int position in set of chars to end before * @param letters if <code>true</code>, generated string will include * alphabetic characters * @param numbers if <code>true</code>, generatd string will include * numeric characters * @return the random string */ public static String random(int count, int start, int end, boolean letters, boolean numbers) { return random(count, start, end, letters, numbers, null); } /** * Creates a random string based on a variety of options. * * @param count int length of random string to create * @param start int position in set of chars to start at * @param end int position in set of chars to end before * @param letters boolean only allow letters? * @param numbers boolean only allow numbers? * @param set char[] set of chars to choose randoms from. * If null, then it will use the set of all chars. * @return the random string */ public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] set) { if( (start == 0) && (end == 0) ) { end = (int)'z'; start = (int)' '; if(!letters && !numbers) { start = 0; end = Integer.MAX_VALUE; } } StringBuffer buffer = new StringBuffer(); int gap = end - start; while(count char ch; if(set == null) { ch = (char)(RANDOM.nextInt(gap) + start); } else { ch = set[RANDOM.nextInt(gap) + start]; } if( (letters && numbers && Character.isLetterOrDigit(ch)) || (letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers) ) { buffer.append( ch ); } else { count++; } } return buffer.toString(); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of characters * specified. * * @param count int length of random string to create * @param set String containing the set of characters to use * @return the random string */ public static String random(int count, String set) { return random(count, set.toCharArray()); } /** * Creates a random string whose length is the number of characters * specified. Characters will be chosen from the set of characters * specified. * * @param count int length of random string to create * @param set character array containing the set of characters to use * @return the random string */ public static String random(int count, char[] set) { return random(count, 0, set.length - 1, false, false, set); } }
package org.apache.velocity.test; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Hashtable; import java.util.HashMap; import java.util.Vector; import org.apache.velocity.VelocityContext; import org.apache.velocity.Template; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.test.provider.TestProvider; import org.apache.velocity.util.StringUtils; import org.apache.velocity.app.FieldMethodizer; import junit.framework.TestCase; /** * Easily add test cases which evaluate templates and check their output. * * NOTE: * This class DOES NOT extend RuntimeTestCase because the VelocityTestSuite * already initializes the Velocity runtime and adds the template * test cases. Having this class extend RuntimeTestCase causes the * Runtime to be initialized twice which is not good. I only discovered * this after a couple hours of wondering why all the properties * being setup were ending up as Vectors. At first I thought it * was a problem with the Configuration class, but the Runtime * was being initialized twice: so the first time the property * is seen it's stored as a String, the second time it's seen * the Configuration class makes a Vector with both Strings. * As a result all the getBoolean(property) calls were failing because * the Configurations class was trying to create a Boolean from * a Vector which doesn't really work that well. I have learned * my lesson and now have to add some code to make sure the * Runtime isn't initialized more then once :-) * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @version $Id: TemplateTestCase.java,v 1.27 2001/03/13 00:02:56 dlr Exp $ */ public class TemplateTestCase extends TestCase implements TemplateTestBase { /** * The base file name of the template and comparison file (i.e. array for * array.vm and array.cmp). */ protected String baseFileName; private TestProvider provider; private ArrayList al; private Hashtable h; private VelocityContext context; private VelocityContext context1; private VelocityContext context2; private Vector vec; /** * Creates a new instance. * * @param baseFileName The base name of the template and comparison file to * use (i.e. array for array.vm and array.cmp). */ public TemplateTestCase (String baseFileName) { super(getTestCaseName(baseFileName)); this.baseFileName = baseFileName; } public static junit.framework.Test suite() { return new TemplateTestSuite(); } /** * Sets up the test. */ protected void setUp () { provider = new TestProvider(); al = provider.getCustomers(); h = new Hashtable(); h.put("Bar", "this is from a hashtable!"); h.put("Foo", "this is from a hashtable too!"); /* * lets set up a vector of objects to test late introspection. See ASTMethod.java */ vec = new Vector(); vec.addElement(new String("string1")); vec.addElement(new String("string2")); /* * set up 3 chained contexts, and add our data * throught the 3 of them. */ context2 = new VelocityContext(); context1 = new VelocityContext( context2 ); context = new VelocityContext( context1 ); context.put("provider", provider); context1.put("name", "jason"); context2.put("providers", provider.getCustomers2()); context.put("list", al); context1.put("hashtable", h); context2.put("hashmap", new HashMap()); context2.put("search", provider.getSearch()); context.put("relatedSearches", provider.getRelSearches()); context1.put("searchResults", provider.getRelSearches()); context2.put("stringarray", provider.getArray()); context.put("vector", vec ); context.put("mystring", new String()); context.put("runtime", new FieldMethodizer( "org.apache.velocity.runtime.Runtime" )); context.put("fmprov", new FieldMethodizer( provider )); context.put("Floog", "floogie woogie"); /* * we want to make sure we test all types of iterative objects * in #foreach() */ Object[] oarr = { "a","b","c","d" } ; context.put( "collection", vec ); context2.put("iterator", vec.iterator()); context1.put("map", h ); context.put("obarr", oarr ); } /** * Runs the test. */ public void runTest () { try { Template template = Runtime.getTemplate (getFileName(null, baseFileName, TMPL_FILE_EXT)); assureResultsDirectoryExists(); /* get the file to write to */ FileOutputStream fos = new FileOutputStream (getFileName( RESULT_DIR, baseFileName, RESULT_FILE_EXT)); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); /* process the template */ template.merge( context, writer); /* close the file */ writer.flush(); writer.close(); if (!isMatch()) { fail("Processed template did not match expected output"); } } catch (Exception e) { fail(e.getMessage()); } } /** * Concatenates the file name parts together appropriately. * * @return The full path to the file. */ private static String getFileName (String dir, String base, String ext) { StringBuffer buf = new StringBuffer(); if (dir != null) { buf.append(dir).append('/'); } buf.append(base).append('.').append(ext); return buf.toString(); } /** * Assures that the results directory exists. If the results directory * cannot be created, fails the test. */ private static void assureResultsDirectoryExists () { File resultDir = new File(RESULT_DIR); if (!resultDir.exists()) { Runtime.info("Template results directory does not exist"); if (resultDir.mkdirs()) { Runtime.info("Created template results directory"); } else { String errMsg = "Unable to create template results directory"; Runtime.warn(errMsg); fail(errMsg); } } } /** * Turns a base file name into a test case name. * * @param s The base file name. * @return The test case name. */ private static final String getTestCaseName (String s) { StringBuffer name = new StringBuffer(); name.append(Character.toTitleCase(s.charAt(0))); name.append(s.substring(1, s.length()).toLowerCase()); return name.toString(); } /** * Returns whether the processed template matches the content of the * provided comparison file. * * @return Whether the output matches the contents of the comparison file. * * @exception Exception Test failure condition. */ protected boolean isMatch () throws Exception { String result = StringUtils.fileContentsToString (getFileName(RESULT_DIR, baseFileName, RESULT_FILE_EXT)); String compare = StringUtils.fileContentsToString (getFileName(COMPARE_DIR, baseFileName, CMP_FILE_EXT)); return result.equals(compare); } /** * Performs cleanup activities for this test case. */ protected void tearDown () throws Exception { /* No op. */ } }
package org.apache.velocity.test; import java.io.*; import java.util.ArrayList; import java.util.Hashtable; import junit.framework.*; import org.apache.velocity.Context; import org.apache.velocity.Template; import org.apache.velocity.test.provider.TestProvider; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.io.FastWriter; /** * Easily add test cases which evaluate templates and check their output. * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @version $Id: TemplateTestCase.java,v 1.6 2000/10/23 22:19:37 dlr Exp $ */ public class TemplateTestCase extends BaseTestCase { /** * VTL file extension. */ private static final String TMPL_FILE_EXT = "vm"; /** * Comparison file extension. */ private static final String CMP_FILE_EXT = "cmp"; /** * Comparison file extension. */ private static final String RESULT_FILE_EXT = "res"; /** * Results relative to the build directory. */ private static final String RESULT_DIR = "../test/templates/results/"; /** * The base file name of the template and comparison file (i.e. array for * array.vm and array.cmp). */ protected String baseFileName; /** * The writer used to output evaluated templates. */ private FastWriter writer; private TestProvider provider; private ArrayList al; private Hashtable h; private Context context; /** * Creates a new instance. * * @param baseFileName The base name of the template and comparison file to * use (i.e. array for array.vm and array.cmp). */ public TemplateTestCase (String baseFileName) { super(getTestCaseName(baseFileName)); this.baseFileName = baseFileName; } /** * Sets up the test. */ protected void setUp () { provider = new TestProvider(); al = provider.getCustomers(); h = new Hashtable(); h.put("Bar", "this is from a hashtable!"); context = new Context(); context.put("provider", provider); context.put("name", "jason"); context.put("providers", provider.getCustomers2()); context.put("list", al); context.put("hashtable", h); context.put("search", provider.getSearch()); context.put("relatedSearches", provider.getRelSearches()); context.put("searchResults", provider.getRelSearches()); } /** * Runs the test. */ public void runTest () { try { StringBuffer buf = new StringBuffer(); buf.append(baseFileName).append('.').append(TMPL_FILE_EXT); Template template = Runtime.getTemplate(buf.toString()); template.merge(context, getWriter( new FileOutputStream( RESULT_DIR + baseFileName + "." + RESULT_FILE_EXT))); if (!isMatch()) { fail("Processed template did not match expected output"); } } catch (Exception e) { fail(e.getMessage()); } } /** * Turns a base file name into a test case name. * * @param s The base file name. * @return The test case name. */ private static final String getTestCaseName (String s) { StringBuffer name = new StringBuffer(); name.append(Character.toTitleCase(s.charAt(0))); name.append(s.substring(1, s.length()).toLowerCase()); return name.toString(); } /** * Get the containing <code>TestSuite</code>. * * @return The <code>TestSuite</code> to run. */ public static junit.framework.Test suite () { return BaseTestCase.suite(); } /** * Returns whether the processed template matches the content of the * provided comparison file. * * @return Whether the output matches the contents of the comparison file. * * @exception Exception Test failure condition. */ protected boolean isMatch () throws Exception { // TODO: Implement matching. return true; } /** * Performs cleanup activities for this test case. */ protected void tearDown () { try { closeWriter(); } catch (IOException e) { fail(e.getMessage()); } } /** * Returns a <code>FastWriter</code> instance. * * @param out The output stream for the writer to write to. If * <code>null</code>, defaults to <code>System.out</code>. * @return The writer. */ protected Writer getWriter (OutputStream out) throws UnsupportedEncodingException, IOException { if (writer == null) { if (out == null) { out = System.out; } writer = new FastWriter (out, Runtime.getString(Runtime.TEMPLATE_ENCODING)); writer.setAsciiHack (Runtime.getBoolean(Runtime.TEMPLATE_ASCIIHACK)); } return writer; } /** * Closes the writer (if it has been opened). */ protected void closeWriter () throws IOException { if (writer != null) { writer.flush(); writer.close(); } } }
package io.spine.cli; import com.google.common.annotations.VisibleForTesting; import static com.google.common.base.Preconditions.checkNotNull; /** * A command-line application. * * <p>Contains the elements that are common for the entire application, e.g. {@link Screen}. */ public final class Application { private Screen screen; /** Prevents instantiation of this class from outside. */ private Application() { } /** * Obtains {@link Screen} of the application. * * @return the screen */ public Screen screen() { return screen; } /** * Initializes the application with the specified screen. * * @param screen the screen to use */ public void init(Screen screen) { if (this.screen != null) { throw new IllegalStateException("Application is already initialized, " + "this function should be called only once."); } else { this.screen = checkNotNull(screen); } } @VisibleForTesting public void setScreen(Screen screen) { this.screen = screen; } /** * Obtains the application instance. * * @return the singleton instance */ public static Application getInstance() { return Singleton.INSTANCE.value; } private enum Singleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Application value = new Application(); } }
package org.dellroad.stuff.vaadin; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.util.AbstractInMemoryContainer; import com.vaadin.data.util.DefaultItemSorter; import com.vaadin.data.util.filter.SimpleStringFilter; import com.vaadin.data.util.filter.UnsupportedFilterException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Simple read-only, in-memory {@link Container} implementation where each {@link Item} is backed by a Java object. * * <p> * The exposed properties are defined via {@link PropertyDef}s, and a {@link PropertyExtractor} is used to * actually extract the property values from each underlying object. * * @param <T> the type of the Java objects that back each {@link Item} in the container * @see SimpleItem * @see SimpleProperty */ @SuppressWarnings("serial") public class SimpleContainer<T> extends AbstractInMemoryContainer<Integer, String, SimpleItem<T>> implements Container.Filterable, Container.SimpleFilterable, Container.Sortable { private final HashMap<String, PropertyDef<?>> propertyMap = new HashMap<String, PropertyDef<?>>(); private final PropertyExtractor<? super T> propertyExtractor; private ArrayList<T> items = new ArrayList<T>(0); // Constructor public SimpleContainer(PropertyExtractor<? super T> propertyExtractor, Collection<? extends PropertyDef<?>> propertyDefs) { if (propertyExtractor == null) throw new IllegalArgumentException("null extractor"); this.propertyExtractor = propertyExtractor; this.setProperties(propertyDefs); this.setItemSorter(new SimpleItemSorter()); } // Public methods public void setProperties(Collection<? extends PropertyDef<?>> propertyDefs) { if (propertyDefs == null) throw new IllegalArgumentException("null propertyDefs"); this.propertyMap.clear(); for (PropertyDef<?> propertyDef : propertyDefs) this.propertyMap.put(propertyDef.getName(), propertyDef); this.fireContainerPropertySetChange(); } public void load(Iterable<? extends T> contents) { // Sanity check if (contents == null) throw new IllegalArgumentException("null contents"); // Bulk load and register items with id's 0, 1, 2, ... this.items = new ArrayList<T>(); int index = 0; for (T obj : contents) { if (obj == null) throw new IllegalArgumentException("null item in contents at index " + this.items.size()); SimpleItem<T> item = new SimpleItem<T>(obj, this.propertyMap, this.propertyExtractor); this.internalAddItemAtEnd(index++, item, false); this.items.add(obj); } // Apply filters this.filterAll(); // Notify subclass this.afterReload(); // Fire event this.fireItemSetChange(); } /** * Return the number of items in this container. This includes items that have been filtered out. */ public int size() { return this.getAllItemIds().size(); } /** * Get the underlying Java object corresponding to the given item ID. * This method ignores any filtering (i.e., filtered-out objects are still accessible). * * @param itemId item ID * @return the corresponding Java object, or null if not found */ public T getJavaObject(int index) { if (index < 0 || index >= this.items.size()) return null; return this.items.get(index); } public Integer getItemIdFor(Object object) { if (object == null) throw new IllegalArgumentException("null object"); for (int i = 0; i < this.items.size(); i++) { if (this.items.get(i) == object) return i; } return null; } // Container and superclass required methods @Override public Set<String> getContainerPropertyIds() { return Collections.unmodifiableSet(this.propertyMap.keySet()); } @Override public Property getContainerProperty(Object itemId, Object propertyId) { // TODO: VAADIN7 SimpleItem<T> entityItem = this.getItem(itemId); if (entityItem == null) return null; return entityItem.getItemProperty(propertyId); } @Override public Class<?> getType(Object propertyId) { PropertyDef<?> propertyDef = this.propertyMap.get(propertyId); return propertyDef != null ? propertyDef.getType() : null; } @Override public SimpleItem<T> getUnfilteredItem(Object itemId) { if (!(itemId instanceof Integer)) return null; int index = (Integer)itemId; if (index < 0 || index >= this.items.size()) return null; return new SimpleItem<T>(this.items.get(index), this.propertyMap, this.propertyExtractor); } // Subclass methods /** * Subclass hook invoked after each reload but prior to invoking {@link #fireItemSetChange}. * * <p> * The implementation in {@link SimpleContainer} does nothing. */ protected void afterReload() { } // Container methods @Override public void sort(Object[] propertyId, boolean[] ascending) { super.sortContainer(propertyId, ascending); } @Override public void addContainerFilter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix) { try { this.addFilter(new SimpleStringFilter(propertyId, filterString, ignoreCase, onlyMatchPrefix)); } catch (UnsupportedFilterException e) { // the filter instance created here is always valid for in-memory containers throw new RuntimeException("unexpected exception", e); } } @Override public void removeAllContainerFilters() { this.removeAllFilters(); } @Override public void removeContainerFilters(Object propertyId) { this.removeFilters(propertyId); } @Override public void addContainerFilter(Filter filter) { this.addFilter(filter); } @Override public void removeContainerFilter(Filter filter) { this.removeFilter(filter); } @Override public Collection<?> getSortableContainerPropertyIds() { ArrayList<String> propertyIds = new ArrayList<String>(this.propertyMap.size()); for (Map.Entry<String, PropertyDef<?>> entry : this.propertyMap.entrySet()) { if (entry.getValue().isSortable()) propertyIds.add(entry.getKey()); } return propertyIds; } // ItemSorter class /** * {@link ItemSorter} implementation used by {@link SimpleContainer}. */ private class SimpleItemSorter extends DefaultItemSorter { @Override @SuppressWarnings("unchecked") protected int compareProperty(Object propertyId, boolean ascending, Item item1, Item item2) { PropertyDef<?> propertyDef = SimpleContainer.this.propertyMap.get(propertyId); if (propertyDef == null || !propertyDef.isSortable()) return super.compareProperty(propertyId, ascending, item1, item2); int diff = this.sort(propertyDef, item1, item2); return ascending ? diff : -diff; } // This method exists only to allow the generic parameter <V> to be bound private <V> int sort(PropertyDef<V> propertyDef, Item item1, Item item2) { return propertyDef.sort(propertyDef.read(item1), propertyDef.read(item2)); } } }
package org.smoothbuild.task.exec; import static org.smoothbuild.io.cache.CacheModule.RESULTS_DIR; import static org.smoothbuild.io.cache.CacheModule.VALUE_DB_DIR; import static org.smoothbuild.io.cache.hash.HashCodes.toPath; import static org.smoothbuild.io.fs.base.Path.path; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import org.smoothbuild.io.fs.SmoothDir; import org.smoothbuild.io.fs.base.FileSystem; import org.smoothbuild.io.fs.base.Path; import org.smoothbuild.lang.function.base.Function; import org.smoothbuild.lang.function.base.Name; import org.smoothbuild.lang.function.value.File; import org.smoothbuild.lang.function.value.FileSet; import org.smoothbuild.lang.function.value.Hashed; import org.smoothbuild.lang.function.value.StringSet; import org.smoothbuild.lang.function.value.StringValue; import org.smoothbuild.lang.function.value.Value; import org.smoothbuild.message.base.CodeLocation; import org.smoothbuild.message.base.Message; import org.smoothbuild.message.base.MessageType; import org.smoothbuild.message.listen.ErrorMessageException; import org.smoothbuild.task.base.Result; import org.smoothbuild.task.base.Task; import org.smoothbuild.task.base.Taskable; import org.smoothbuild.util.Empty; import com.google.common.collect.Maps; public class ArtifactBuilder { private final TaskGenerator taskGenerator; private final FileSystem smoothFileSystem; private final Map<Name, Result> artifacts; @Inject public ArtifactBuilder(TaskGenerator taskGenerator, @SmoothDir FileSystem smoothFileSystem) { this.taskGenerator = taskGenerator; this.smoothFileSystem = smoothFileSystem; this.artifacts = Maps.newHashMap(); } public void addArtifact(Function function) { Name name = function.name(); Result result = taskGenerator.generateTask(new TaskableCall(function)); artifacts.put(name, result); } public void runBuild() { try { for (Entry<Name, Result> artifact : artifacts.entrySet()) { Name name = artifact.getKey(); Value value = artifact.getValue().result(); store(name, value); } } catch (BuildInterruptedException e) { // Nothing to do. Just quit the build process. } } private void store(Name name, Value value) { Path artifactPath = RESULTS_DIR.append(path(name.value())); if (value instanceof File) { storeFile(artifactPath, (File) value); } else if (value instanceof FileSet) { storeFileSet(artifactPath, (FileSet) value); } else if (value instanceof StringValue) { storeString(artifactPath, (StringValue) value); } else if (value instanceof StringSet) { storeStringSet(artifactPath, (StringSet) value); } else { throw new ErrorMessageException(new Message(MessageType.FATAL, "Bug in smooth binary.\nUnknown value type " + value.getClass().getName())); } } private void storeFile(Path artifactPath, File file) { Path targetPath = targetPath(file.content()); smoothFileSystem.delete(artifactPath); smoothFileSystem.createLink(artifactPath, targetPath); } private void storeFileSet(Path artifactPath, FileSet fileSet) { smoothFileSystem.delete(artifactPath); for (File file : fileSet) { Path linkPath = artifactPath.append(file.path()); Path targetPath = targetPath(file.content()); smoothFileSystem.createLink(linkPath, targetPath); } } private void storeString(Path artifactPath, StringValue string) { Path targetPath = targetPath(string); smoothFileSystem.delete(artifactPath); smoothFileSystem.createLink(artifactPath, targetPath); } private void storeStringSet(Path artifactPath, StringSet stringSet) { smoothFileSystem.delete(artifactPath); int i = 0; for (StringValue string : stringSet) { Path filePath = path(Integer.valueOf(i).toString()); Path linkPath = artifactPath.append(filePath); Path targetPath = targetPath(string); smoothFileSystem.createLink(linkPath, targetPath); i++; } } private static Path targetPath(Hashed hashed) { return VALUE_DB_DIR.append(toPath(hashed.hash())); } private static class TaskableCall implements Taskable { private final Function function; public TaskableCall(Function function) { this.function = function; } @Override public Task generateTask(TaskGenerator taskGenerator) { CodeLocation ignoredCodeLocation = null; return function.generateTask(taskGenerator, Empty.stringTaskResultMap(), ignoredCodeLocation); } } }
package org.tensorics.core.tensor; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; /** * Default Implementation of {@link Tensor}. * <p> * By constraint of creation it holds a map of {@link Position} of certain type to values of type T, such that ALL * Positions contains the same number and type of coordinates. Number and type of coordinates can be accessed and * explored via {@link Shape}. * <p> * There is a special type of Tensor that has ZERO dimensiality. Can be obtained via factory method. * <p> * {@link ImmutableTensor} is immutable. * <p> * The toString() method does not print all the tensor entries. * * @author agorzaws, kfuchsbe * @param <T> type of values in Tensor. */ @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.TooManyMethods" }) public class ImmutableTensor<T> implements Tensor<T> { private static final int TOSTRING_BUFFER_SIZE = 64; private static final int POSITION_TO_DISPLAY = 10; private final Map<Position, Tensor.Entry<T>> entries; // NOSONAR private final Shape shape; // NOSONAR private final Context context; // NOSONAR /** * Package-private constructor to be called from builder * * @param builder to be used when {@link ImmutableTensor} is created. */ ImmutableTensor(Builder<T> builder) { this.entries = builder.createEntries(); this.shape = Shape.viewOf(builder.getDimensions(), this.entries.keySet()); this.context = builder.getContext(); } /** * Returns a builder for an {@link ImmutableTensor}. As argument it takes set of class of coordinates which * represent the dimensions of the tensor. * * @param dimensions a set of classes that can later be used as coordinates for the tensor entries. * @return a builder for {@link ImmutableTensor} * @param <T> type of values in Tensor. */ public static final <T> Builder<T> builder(Set<? extends Class<?>> dimensions) { return new Builder<T>(dimensions); } /** * Returns a builder for an {@link ImmutableTensor}. The dimensions (classes of coordinates) of the future tensor * have to be given as arguments here. * * @param dimensions the dimensions of the tensor to create * @return a builder for an immutable tensor * @param <T> the type of values of the tensor */ public static final <T> Builder<T> builder(Class<?>... dimensions) { return builder(ImmutableSet.copyOf(dimensions)); } /** * Creates a tensor from the given map, where the map has to contain the positions as keys and the values as values. * * @param dimensions the desired dimensions of the tensor. This has to be consistent with the position - keys in the * map. * @param map the map from which to construct a tensor * @return a new immutable tensor */ public static final <T> Tensor<T> fromMap(Set<? extends Class<?>> dimensions, Map<Position, T> map) { Builder<T> builder = builder(dimensions); for (Map.Entry<Position, T> entry : map.entrySet()) { builder.at(entry.getKey()).put(entry.getValue()); } return builder.build(); } /** * Returns the builder that can create special tensor of dimension size equal ZERO. * * @param value to be used. * @return a builder for {@link ImmutableTensor} * @param <T> type of values in Tensor. */ public static final <T> Tensor<T> zeroDimensionalOf(T value) { Builder<T> builder = builder(Collections.<Class<?>> emptySet()); builder.at(Position.empty()).put(value); return builder.build(); } /** * Creates an immutable copy of the given tensor. * * @param tensor the tensor whose element to copy * @return new immutable Tensor */ public static final <T> Tensor<T> copyOf(Tensor<T> tensor) { Builder<T> builder = builder(tensor.shape().dimensionSet()); builder.putAll(tensor.entrySet()); builder.setTensorContext(tensor.context()); return builder.build(); } /** * Returns a builder for an {@link ImmutableTensor} which is initiliased with the given {@link ImmutableTensor}. * * @param tensor a Tensor with which the {@link Builder} is initialized * @return a {@link Builder} for an {@link ImmutableTensor} * @param <T> type of values in Tensor. */ public static <T> Builder<T> builderFrom(Tensor<T> tensor) { Builder<T> builder = builder(tensor.shape().dimensionSet()); builder.putAll(tensor.entrySet()); return builder; } @Override public T get(Position position) { return findEntryOrThrow(position).getValue(); } @Override public Context context() { return context; } @Override public Set<Tensor.Entry<T>> entrySet() { return new HashSet<>(this.entries.values()); } @Override @SafeVarargs public final T get(Object... coordinates) { return get(Position.of(coordinates)); } @Override public Shape shape() { return this.shape; } private Tensor.Entry<T> findEntryOrThrow(Position position) { Tensor.Entry<T> entry = findEntryOrNull(position); if (entry == null) { throw new NoSuchElementException("Entry for position '" + position + "' is not contained in this tensor."); } return entry; } private Tensor.Entry<T> findEntryOrNull(Position position) { return this.entries.get(position); } /** * A builder for an immutable tensor. * * @author kfuchsbe * @param <S> the type of the values to be added */ public static final class Builder<S> extends AbstractTensorBuilder<S> { private final ImmutableMap.Builder<Position, Entry<S>> entries = ImmutableMap.builder(); Builder(Set<? extends Class<?>> dimensions) { super(dimensions); } /** * Builds an {@link ImmutableTensor} from all elements put before. * * @return an {@link ImmutableTensor}. */ @Override public ImmutableTensor<S> build() { return new ImmutableTensor<S>(this); } protected Map<Position, Tensor.Entry<S>> createEntries() { return this.entries.build(); } @Override protected void putItAt(S value, Position position) { this.entries.put(position, new ImmutableEntry<>(position, value)); } } /** * When printing the tensor content output is automatically not larger then N ant the beginning and N at the end of * the Tensor entries. */ @Override public String toString() { StringBuffer buffer = new StringBuffer(TOSTRING_BUFFER_SIZE); int totalSize = this.shape.positionSet().size(); int index = 1; for (Position position : this.shape.positionSet()) { if (index < POSITION_TO_DISPLAY || index > totalSize - POSITION_TO_DISPLAY) { buffer.append(position + "=(" + get(position) + "), "); } else if (index == POSITION_TO_DISPLAY) { buffer.append(".. [" + (totalSize - 2 * POSITION_TO_DISPLAY) + " skipped entries] .. , "); } index++; } if (buffer.length() > 1) { buffer.setLength(buffer.length() - 2); } return Coordinates.dimensionsWithoutClassPath(this) + ", Content:{" + buffer + "}"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((context == null) ? 0 : context.hashCode()); result = prime * result + ((entries == null) ? 0 : entries.hashCode()); result = prime * result + ((shape == null) ? 0 : shape.hashCode()); return result; } @Override @SuppressWarnings("PMD.NPathComplexity") public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ImmutableTensor<?> other = (ImmutableTensor<?>) obj; if (context == null) { if (other.context != null) { return false; } } else if (!context.equals(other.context)) { return false; } if (entries == null) { if (other.entries != null) { return false; } } else if (!entries.equals(other.entries)) { return false; } if (shape == null) { if (other.shape != null) { return false; } } else if (!shape.equals(other.shape)) { return false; } return true; } }
package io.rouz.task; import com.google.auto.value.AutoValue; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * {@link AutoValue} implementation of {@link TaskId} */ @AutoValue abstract class TaskIds implements TaskId, Serializable { abstract List<Object> args(); static TaskId create(String name, Object... args) { return new AutoValue_TaskIds( name, name.hashCode() * 1000003 ^ Objects.hash(args), Arrays.asList(args)); } @Override public String toString() { return String.format("%s(%s)#%08x", name(), argsString(), hash()); } private String argsString() { return args().stream() .map(Object::toString) .collect(Collectors.joining(",")); } }
package krasa.grepconsole.grep; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.util.xmlb.annotations.Transient; import krasa.grepconsole.model.Profile; import krasa.grepconsole.plugin.GrepProjectComponent; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.lang.ref.WeakReference; import java.util.*; public class PinnedGrepConsolesState { private static final Logger LOG = Logger.getInstance(PinnedGrepConsolesState.class); public static int MAX_SIZE = 100; @Transient private List<WeakReference<OpenGrepConsoleAction.PinAction>> actions = new ArrayList<>(); private Map<RunConfigurationRef, Pins> map = new LinkedHashMap<>(); public static PinnedGrepConsolesState getInstance(Project project) { return GrepProjectComponent.getInstance(project).getPinnedGreps(); } public void register(OpenGrepConsoleAction.PinAction pinAction, Profile profile) { actions.add(new WeakReference<>(pinAction)); if (profile.isAlwaysPinGrepConsoles()) { pin(pinAction); } } public boolean isPinned(OpenGrepConsoleAction.PinAction pinAction) { String consoleUUID = pinAction.getConsoleUUID(); RunConfigurationRef key = pinAction.getRunConfigurationRef(); Pins pins = map.get(key); if (pins != null) { for (Pin pin : pins.pins) { if (pin.consoleUUID.equals(consoleUUID)) { return true; } } } return false; } public void pin(OpenGrepConsoleAction.PinAction pinAction) { if (LOG.isDebugEnabled()) { LOG.debug(">pin " + "pinAction = [" + pinAction + "]"); } update(pinAction.getRunConfigurationRef(), pinAction.getParentConsoleUUID(), pinAction.getConsoleUUID(), pinAction.getModel(), pinAction.getContentType(), true); } public void update(@NotNull RunConfigurationRef runContentDescriptor, String parentConsoleUUID, @NotNull String consoleUUID, @NotNull GrepModel grepModel, String contentType, boolean add) { if (LOG.isDebugEnabled()) { LOG.debug(">update " + "runContentDescriptor = [" + runContentDescriptor + "], parentConsoleUUID = [" + parentConsoleUUID + "], consoleUUID = [" + consoleUUID + "], grepModel = [" + grepModel + "], contentType = [" + contentType + "], add = [" + add + "]"); } Pins pins = map.get(runContentDescriptor); if (LOG.isDebugEnabled()) { LOG.debug("#update found: " + pins); } if (pins == null) { if (add) { map.put(runContentDescriptor, new Pins(parentConsoleUUID, consoleUUID, contentType, grepModel)); clean(); } } else { boolean updated = false; for (Pin pin : pins.pins) { if (pin.consoleUUID.equals(consoleUUID)) { LOG.debug("#update grepModel updated for pin=" + pin); pin.grepModel = grepModel; updated = true; } } if (!updated && add) { Pin e = new Pin(parentConsoleUUID, consoleUUID, contentType, grepModel); if (LOG.isDebugEnabled()) { LOG.debug("#update adding new pin =" + e); } pins.pins.add(e); } } } private void clean() { if (isFull()) { Iterator<RunConfigurationRef> iterator = map.keySet().iterator(); while (iterator.hasNext()) { if (!isFull()) { break; } iterator.next(); iterator.remove(); } } } private boolean isFull() { return map.size() > MAX_SIZE; } public void unpin(OpenGrepConsoleAction.PinAction pinAction) { if (LOG.isDebugEnabled()) { LOG.debug(">unpin " + "pinAction = [" + pinAction + "]"); } String consoleUUID = pinAction.getConsoleUUID(); Pins pins = map.get(pinAction.getRunConfigurationRef()); if (LOG.isDebugEnabled()) { LOG.debug("found pins =" + pins); } if (pins != null) { for (Iterator<Pin> iterator = pins.pins.iterator(); iterator.hasNext(); ) { Pin pin = iterator.next(); if (pin.consoleUUID.equals(consoleUUID)) { if (LOG.isDebugEnabled()) { LOG.debug("removing pin =" + pin); } iterator.remove(); } else if (pin.parentConsoleUUID != null && pin.parentConsoleUUID.equals(consoleUUID)) { if (LOG.isDebugEnabled()) { LOG.debug("removing pin =" + pin); } iterator.remove(); } } } refresh(); } private void refresh() { for (Iterator<WeakReference<OpenGrepConsoleAction.PinAction>> iterator = actions.iterator(); iterator.hasNext(); ) { WeakReference<OpenGrepConsoleAction.PinAction> listener = iterator.next(); OpenGrepConsoleAction.PinAction pinAction = listener.get(); if (pinAction == null) { iterator.remove(); } else { pinAction.refreshPinStatus(this); } } } public Pins getPins(RunConfigurationRef key) { if (LOG.isDebugEnabled()) { LOG.debug(">getPins " + "key = [" + key + "]"); } Pins pins = map.get(key); if (LOG.isDebugEnabled()) { LOG.debug("<getPins " + "pins = [" + pins + "]"); } return pins; } public static class Pins { private List<Pin> pins = new ArrayList<>(); public Pins(@Nullable String parentConsoleUUID, @NotNull String consoleUUID, String contentType, @NotNull GrepModel grepModel) { pins.add(new Pin(parentConsoleUUID, consoleUUID, contentType, grepModel)); } public Pins() { } public void setPins(List<Pin> pins) { this.pins = pins; } public List<Pin> getPins() { return pins; } @Override public String toString() { return "Pins{" + "pins=" + pins + '}'; } } /** * TODO add profileId */ public static class Pin { @Nullable private String parentConsoleUUID; private String consoleUUID; private String contentType; private GrepModel grepModel; public Pin() { } public Pin(@Nullable String parentConsoleUUID, @NotNull String consoleUUID, String contentType, @NotNull GrepModel grepModel) { this.parentConsoleUUID = parentConsoleUUID; this.consoleUUID = consoleUUID; this.contentType = contentType; this.grepModel = grepModel; } public void setGrepModel(@NotNull GrepModel grepModel) { this.grepModel = grepModel; } public void setParentConsoleUUID(@Nullable String parentConsoleUUID) { this.parentConsoleUUID = parentConsoleUUID; } public void setConsoleUUID(@NotNull String consoleUUID) { this.consoleUUID = consoleUUID; } @Nullable public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } @Nullable public String getParentConsoleUUID() { return parentConsoleUUID; } public String getConsoleUUID() { return consoleUUID; } public GrepModel getGrepModel() { return grepModel; } @Override public String toString() { return "Pin{" + "parentConsoleUUID='" + parentConsoleUUID + '\'' + ", consoleUUID='" + consoleUUID + '\'' + ", contentType='" + contentType + '\'' + ", grepModel=" + grepModel + '}'; } } public static class RunConfigurationRef { private String name; @Nullable private String icon; public RunConfigurationRef() { } @NotNull static protected RunConfigurationRef toKey(RunContentDescriptor runContentDescriptor) { return new RunConfigurationRef( runContentDescriptor.getDisplayName(), runContentDescriptor.getIcon()); } public String getName() { return name; } public void setName(@NotNull String name) { this.name = name; } @Nullable public String getIcon() { return icon; } public void setIcon(@Nullable String icon) { this.icon = icon; } public RunConfigurationRef(@NotNull String name, @Nullable Icon icon) { this.name = name; if (icon != null) { String iconPath = icon.toString(); String iconName = StringUtils.substringAfterLast(iconPath, "/"); if (!StringUtils.isEmpty(iconName)) { iconPath = iconName; } this.icon = iconPath; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RunConfigurationRef that = (RunConfigurationRef) o; if (name != null ? !name.equals(that.name) : that.name != null) return false; return icon != null ? icon.equals(that.icon) : that.icon == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (icon != null ? icon.hashCode() : 0); return result; } @Override public String toString() { return "RunConfigurationRef{" + "name='" + name + '\'' + ", icon='" + icon + '\'' + '}'; } } public Map<RunConfigurationRef, Pins> getMap() { return map; } public void setMap(Map<RunConfigurationRef, Pins> map) { this.map = map; } }