answer
stringlengths
17
10.2M
package org.scijava.io; import java.io.IOException; import org.scijava.event.EventService; import org.scijava.io.event.DataOpenedEvent; import org.scijava.io.event.DataSavedEvent; import org.scijava.log.LogService; import org.scijava.plugin.AbstractHandlerService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.service.Service; /** * Default implementation of {@link IOService}. * * @author Curtis Rueden */ @Plugin(type = Service.class) public final class DefaultIOService extends AbstractHandlerService<String, IOPlugin<?>> implements IOService { @Parameter private LogService log; @Parameter private EventService eventService; // -- IOService methods -- @Override public IOPlugin<?> getOpener(final String source) { for (final IOPlugin<?> handler : getInstances()) { if (handler.supportsOpen(source)) return handler; } return null; } @Override public <D> IOPlugin<D> getSaver(final D data, final String destination) { for (final IOPlugin<?> handler : getInstances()) { if (handler.supportsSave(data, destination)) { @SuppressWarnings("unchecked") final IOPlugin<D> typedHandler = (IOPlugin<D>) handler; return typedHandler; } } return null; } @Override public Object open(final String source) throws IOException { final IOPlugin<?> opener = getOpener(source); if (opener == null) return null; // no appropriate IOPlugin final Object data = opener.open(source); if (data == null) return null; // IOPlugin returned no data; canceled? eventService.publish(new DataOpenedEvent(source, data)); return data; } @Override public void save(final Object data, final String destination) throws IOException { final IOPlugin<Object> saver = getSaver(data, destination); if (saver != null) { saver.save(data, destination); } eventService.publish(new DataSavedEvent(destination, data)); } // -- HandlerService methods -- @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Class<IOPlugin<?>> getPluginType() { return (Class) IOPlugin.class; } @Override public Class<String> getType() { return String.class; } }
package org.vivoweb.webapp.util; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.dao.VClassDao; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; public class ModelUtils { private static final Log log = LogFactory.getLog(ModelUtils.class.getName()); private static final String processPropertyURI = "http://vivoweb.org/ontology/core#roleRealizedIn"; private static final String processPropertyInverseURI = "http://vivoweb.org/ontology/core#realizedRole"; private static final String nonProcessPropertyURI = "http://vivoweb.org/ontology/core#roleContributesTo"; private static final String nonProcessPropertyInverseURI = "http://vivoweb.org/ontology/core#ContributingRole"; private static Set<String> processClass = new HashSet<String>(); static { processClass.add("http://vivoweb.org/ontology/core#Process"); processClass.add("http://purl.org/NET/c4dm/event.owl#Event"); processClass.add("http://vivoweb.org/ontology/core#EventSeries"); } /* * Given a class URI that represents the type of entity that a Role * is in (in, in any of its senses) this method returns the URIs of * the properties that should use used to relate the Role to the entity. * * Note: we may want to change the implementation of this method * to check whether the target class has both a parent that is a * BFO Process and a parent that is not a BFO Process and issue * a warning if so. */ public static ObjectProperty getPropertyForRoleInClass(String classURI, WebappDaoFactory wadf) { if (classURI == null) { log.error("input classURI is null"); return null; } if (wadf == null) { log.error("input WebappDaoFactory is null"); return null; } VClassDao vcd = wadf.getVClassDao(); List<String> superClassURIs = vcd.getSuperClassURIs(classURI, false); Iterator<String> iter = superClassURIs.iterator(); ObjectProperty op = new ObjectProperty(); boolean isBFOProcess = false; while (iter.hasNext()) { String superClassURI = iter.next(); if (processClass.contains(superClassURI)) { isBFOProcess = true; break; } } if (isBFOProcess) { op.setURI(processPropertyURI); op.setURIInverse(processPropertyInverseURI); } else { op.setURI(nonProcessPropertyURI); op.setURIInverse(nonProcessPropertyInverseURI); } return op; } }
package net.bull.javamelody; import java.io.IOException; import java.io.Writer; import java.text.DecimalFormat; import java.text.MessageFormat; import java.util.List; class HtmlJavaInformationsReport { // constantes pour l'affichage d'une barre avec pourcentage private static final double MIN_VALUE = 0; private static final double MAX_VALUE = 100; private static final int PARTIAL_BLOCKS = 5; private static final int FULL_BLOCKS = 10; private static final double UNIT_SIZE = (MAX_VALUE - MIN_VALUE) / (FULL_BLOCKS * PARTIAL_BLOCKS); private static int uniqueByPageSequence; private final boolean noDatabase = Parameters.isNoDatabase(); private final DecimalFormat integerFormat = I18N.createIntegerFormat(); private final DecimalFormat decimalFormat = I18N.createPercentFormat(); private final List<JavaInformations> javaInformationsList; private final Period period; private final Writer writer; HtmlJavaInformationsReport(List<JavaInformations> javaInformationsList, Period period, Writer writer) { super(); assert javaInformationsList != null && !javaInformationsList.isEmpty(); assert period != null; assert writer != null; this.javaInformationsList = javaInformationsList; this.period = period; this.writer = writer; } void toHtml() throws IOException { for (final JavaInformations javaInformations : javaInformationsList) { writeSummary(javaInformations); } if (!noDatabase) { write("<br/><br/>"); } if (javaInformationsList.get(0).getSessionCount() >= 0) { write("<br/>"); } if (javaInformationsList.get(0).getSystemLoadAverage() >= 0) { write("<br/>"); } writeln("<br/><br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); writeShowHideLink("detailsJava", "#Details#"); writeln("<br/><br/>"); writeln("<div id='detailsJava' style='display: none;'>"); final boolean repeatHost = javaInformationsList.size() > 1; for (final JavaInformations javaInformations : javaInformationsList) { writeDetails(javaInformations, repeatHost); } writeln("</div>"); } private void writeSummary(JavaInformations javaInformations) throws IOException { final String lineEnd = "</td></tr>"; final String columnAndLineEnd = "</td><td>" + lineEnd; writeln("<table align='left' border='0' cellspacing='0' cellpadding='2' summary='#Informations_systemes#'>"); writeln("<tr><td>#Host#: </td><td><b>" + javaInformations.getHost() + "</b>" + lineEnd); final MemoryInformations memoryInformations = javaInformations.getMemoryInformations(); final long usedMemory = memoryInformations.getUsedMemory(); final long maxMemory = memoryInformations.getMaxMemory(); write("<tr><td>#memoire_utilisee#: </td><td>"); writeGraph("usedMemory", integerFormat.format(usedMemory / 1024 / 1024)); writeln(" #Mo# / " + integerFormat.format(maxMemory / 1024 / 1024) + " #Mo#&nbsp;&nbsp;&nbsp;</td><td>"); writeln(toBar(100d * usedMemory / maxMemory)); writeln(lineEnd); if (javaInformations.getSessionCount() >= 0) { write("<tr><td>#nb_sessions_http#: </td><td>"); writeGraph("httpSessions", integerFormat.format(javaInformations.getSessionCount())); writeln(columnAndLineEnd); } write("<tr><td>#nb_threads_actifs#<br/>(#Requetes_http_en_cours#): </td><td>"); writeGraph("activeThreads", integerFormat.format(javaInformations.getActiveThreadCount())); writeln(columnAndLineEnd); if (!noDatabase) { write("<tr><td>#nb_connexions_actives#: </td><td>"); writeGraph("activeConnections", integerFormat.format(javaInformations .getActiveConnectionCount())); writeln(columnAndLineEnd); final int usedConnectionCount = javaInformations.getUsedConnectionCount(); final int maxConnectionCount = javaInformations.getMaxConnectionCount(); write("<tr><td>#nb_connexions_utilisees#<br/>(#ouvertes#): </td><td>"); writeGraph("usedConnections", integerFormat.format(usedConnectionCount)); if (maxConnectionCount >= 0) { writeln(" / " + integerFormat.format(maxConnectionCount) + "&nbsp;&nbsp;&nbsp;</td><td>"); writeln(toBar(100d * usedConnectionCount / maxConnectionCount)); } writeln(lineEnd); } if (javaInformations.getSystemLoadAverage() >= 0) { write("<tr><td>#Charge_systeme#</td><td>"); writeGraph("systemLoad", decimalFormat.format(javaInformations.getSystemLoadAverage())); writeln(columnAndLineEnd); } writeln("</table>"); } private void writeDetails(JavaInformations javaInformations, boolean repeatHost) throws IOException { final String columnEnd = "</td></tr>"; writeln("<table align='left' border='0' cellspacing='0' cellpadding='2' summary='#Details_systeme#'>"); if (repeatHost) { writeln("<tr><td>#Host#: </td><td><b>" + javaInformations.getHost() + "</b>" + columnEnd); } writeln("<tr><td>#OS#: </td><td>" + javaInformations.getOS() + " (" + javaInformations.getAvailableProcessors() + " #coeurs#)" + columnEnd); writeln("<tr><td>#Java#: </td><td>" + javaInformations.getJavaVersion() + columnEnd); writeln("<tr><td>#JVM#: </td><td>" + javaInformations.getJvmVersion() + columnEnd); writeln("<tr><td>#PID#: </td><td>" + javaInformations.getPID() + columnEnd); final long unixOpenFileDescriptorCount = javaInformations.getUnixOpenFileDescriptorCount(); if (unixOpenFileDescriptorCount >= 0) { final long unixMaxFileDescriptorCount = javaInformations .getUnixMaxFileDescriptorCount(); write("<tr><td>#nb_fichiers#</td><td>"); writeGraph("fileDescriptors", integerFormat.format(unixOpenFileDescriptorCount)); writeln(" / " + integerFormat.format(unixMaxFileDescriptorCount) + "&nbsp;&nbsp;&nbsp;"); writeln(toBar(100d * unixOpenFileDescriptorCount / unixMaxFileDescriptorCount)); writeln(columnEnd); } if (javaInformations.getServerInfo() != null) { writeln("<tr><td>#Serveur#: </td><td>" + javaInformations.getServerInfo() + columnEnd); writeln("<tr><td>#Contexte_webapp#: </td><td>" + javaInformations.getContextPath() + columnEnd); } writeln("<tr><td>#Demarrage#: </td><td>" + I18N.createDateAndTimeFormat().format(javaInformations.getStartDate()) + columnEnd); writeln("<tr><td valign='top'>#Arguments_JVM#: </td><td>" + replaceEolWithBr(javaInformations.getJvmArguments()) + columnEnd); writeMemoryInformations(javaInformations.getMemoryInformations()); if (javaInformations.getFreeDiskSpaceInTemp() >= 0) { writeln("<tr><td>#Free_disk_space#: </td><td>" + integerFormat.format(javaInformations.getFreeDiskSpaceInTemp() / 1024 / 1024) + " #Mo# " + columnEnd); } if (!noDatabase && javaInformations.getDataBaseVersion() != null) { writeln("<tr><td valign='top'>#Base_de_donnees#: </td><td>" + replaceEolWithBr(javaInformations.getDataBaseVersion()).replaceAll("[&]", "&amp;") + columnEnd); } if (javaInformations.getTomcatDataSourceDetails() != null) { writeln("<tr><td valign='top'>#DataSource_jdbc#: </td><td>" + replaceEolWithBr(javaInformations.getTomcatDataSourceDetails()) + "<a href='http://commons.apache.org/dbcp/apidocs/org/apache/commons/dbcp/BasicDataSource.html'" + " target='_blank'>DataSource reference</a>" + columnEnd); } if (javaInformations.isDependenciesEnabled()) { writeln("<tr><td valign='top'>#Dependencies#: </td><td>"); writeDependencies(javaInformations); writeln(columnEnd); } writeln("</table>"); } private void writeMemoryInformations(MemoryInformations memoryInformations) throws IOException { final String columnEnd = "</td></tr>"; writeln("<tr><td valign='top'>#Gestion_memoire#: </td><td>" + replaceEolWithBr(memoryInformations.getMemoryDetails()).replace(" Mo", " + columnEnd); final long usedPermGen = memoryInformations.getUsedPermGen(); if (usedPermGen > 0) { final long maxPermGen = memoryInformations.getMaxPermGen(); writeln("<tr><td>#Memoire_Perm_Gen#: </td><td>" + integerFormat.format(usedPermGen / 1024 / 1024) + " if (maxPermGen >= 0) { writeln(" / " + integerFormat.format(maxPermGen / 1024 / 1024) + " #Mo#&nbsp;&nbsp;&nbsp;"); writeln(toBar(100d * usedPermGen / maxPermGen)); } writeln(columnEnd); } } private void writeDependencies(JavaInformations javaInformations) throws IOException { final int nbDependencies = javaInformations.getDependenciesList().size(); writeln(I18N.getFormattedString("nb_dependencies", nbDependencies)); if (nbDependencies > 0) { uniqueByPageSequence++; writeln(" ; &nbsp;&nbsp;&nbsp;"); writeShowHideLink("detailsDependencies" + uniqueByPageSequence, "#Details#"); if (javaInformations.doesPomXmlExists() && Boolean.parseBoolean(Parameters .getParameter(Parameter.SYSTEM_ACTIONS_ENABLED))) { writeln("&nbsp;&nbsp;&nbsp;<a href='?part=pom.xml&amp;period=" + period.getCode() + "' class='noPrint'><img src='?resource=xml.png' width='14' height='14' alt=\"#pom.xml#\"/> #pom.xml#</a>"); } writeln("<br/>"); writeln("<div id='detailsDependencies" + uniqueByPageSequence + "' style='display: none;'>"); writeln(replaceEolWithBr(javaInformations.getDependencies())); writeln("</div>"); } } private void writeGraph(String graph, String value) throws IOException { if (javaInformationsList.size() > 1) { write(value); return; } write("<a class='tooltip' href='?part=graph&amp;graph="); write(graph); write("&amp;period="); write(period.getCode()); write("'"); // sans les charger tous au chargement de la page. write(" onmouseover=\"document.getElementById('"); final String id = "id" + graph; write(id); write("').src='?graph="); write(graph); write("&amp;period="); write(period.getCode()); write("&amp;width=100&amp;height=50'; this.onmouseover=null;\" >"); // avant mouseover on prend une image qui sera mise en cache write("<em><img src='?resource=systeminfo.png' id='"); write(id); write("' alt='graph'/></em>"); // writer.write pour ne pas gérer de traductions si le nom contient ' writer.write(value); write("</a>"); } private static String toBar(double percentValue) { // NOPMD final double myPercent = Math.max(Math.min(percentValue, 100d), 0d); final StringBuilder sb = new StringBuilder(); final String body = "<img src=''?resource=bar/rb_{0}.gif'' alt=''+'' title=''" + I18N.createPercentFormat().format(myPercent) + "%'' />"; final int fullBlockCount = (int) Math.floor(myPercent / (UNIT_SIZE * PARTIAL_BLOCKS)); final int partialBlockIndex = (int) Math.floor((myPercent - fullBlockCount * UNIT_SIZE * PARTIAL_BLOCKS) / UNIT_SIZE); sb.append(MessageFormat.format(body, fullBlockCount > 0 || partialBlockIndex > 0 ? "a" : "a0")); final String fullBody = MessageFormat.format(body, PARTIAL_BLOCKS); for (int i = 0; i < fullBlockCount; i++) { sb.append(fullBody); } if (partialBlockIndex > 0) { final String partialBody = MessageFormat.format(body, partialBlockIndex); sb.append(partialBody); } final int emptyBlocks = FULL_BLOCKS - fullBlockCount - (partialBlockIndex > 0 ? 1 : 0); if (emptyBlocks > 0) { final String emptyBody = MessageFormat.format(body, 0); for (int i = 0; i < emptyBlocks; i++) { sb.append(emptyBody); } } sb.append(MessageFormat.format(body, fullBlockCount == FULL_BLOCKS ? "b" : "b0")); return sb.toString(); } private static String replaceEolWithBr(String string) { return string.replaceAll("[\n]", "<br/>"); } private void writeShowHideLink(String idToShow, String label) throws IOException { writeln("<a href=\"javascript:showHide('" + idToShow + "');\" class='noPrint'><img id='" + idToShow + "Img' src='?resource=bullets/plus.png' alt=''/> " + label + "</a>"); } private void write(String html) throws IOException { I18N.writeTo(html, writer); } private void writeln(String html) throws IOException { I18N.writelnTo(html, writer); } }
package pl.pwr.hiervis; import java.awt.Toolkit; import java.io.File; import java.lang.reflect.Field; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.UnsupportedLookAndFeelException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import basic_hierarchy.interfaces.Hierarchy; import basic_hierarchy.reader.GeneratedCSVReader; import pl.pwr.hiervis.core.HVConfig; import pl.pwr.hiervis.core.HVContext; import pl.pwr.hiervis.core.HierarchyStatistics; import pl.pwr.hiervis.ui.VisualizerFrame; import pl.pwr.hiervis.util.CmdLineParser; import pl.pwr.hiervis.util.SwingUIUtils; import pl.pwr.hiervis.visualisation.HierarchyProcessor; public final class HierarchyVisualizer { private static final Logger log = LogManager.getLogger( HierarchyVisualizer.class ); public static final String APP_NAME = "Hierarchy Visualizer"; private HierarchyVisualizer() { // Static class -- disallow instantiation. throw new RuntimeException( "Attempted to instantiate a static class: " + getClass().getName() ); } public static void main( String[] args ) { HVContext context = new HVContext(); // Check if the program can access its own folder if ( new File( "." ).exists() == false ) { log.error( "Failed to access current working directory." ); SwingUIUtils.showErrorDialog( "Program was unable to access the current working directory.\n\n" + "Make sure that you're not trying to run the program from inside of a zip archive.\n" + "Also, instead of double-clicking on hv.jar, try to launch start.bat/start.sh" ); System.exit( 0 ); } if ( args != null && args.length > 0 ) { log.info( "Args list is not empty -- running in CLI mode." ); executeCLI( context, args ); } else { log.info( "Args list is empty -- running in GUI mode." ); executeGUI( context ); } } private static void executeCLI( HVContext context, String[] args ) { try { CmdLineParser parser = new CmdLineParser(); context.setConfig( parser.parse( args, context.getConfig() ) ); } catch ( Exception e ) { log.error( e ); } HVConfig config = context.getConfig(); Hierarchy inputData = null; if ( config.getInputDataFilePath().getFileName().endsWith( ".csv" ) ) { inputData = new GeneratedCSVReader().load( config.getInputDataFilePath().toString(), config.hasInstanceNameAttribute(), config.hasClassAttribute(), false ); } else { log.error( "Unrecognised extension of input file: '%s', only *.csv files are supported.%n", config.getInputDataFilePath().getFileName() ); System.exit( 1 ); } // TODO: Correct handling of stats String statsFilePath = config.getOutputFolder() + File.separator + config.getInputDataFilePath().getFileName(); statsFilePath = statsFilePath.substring( 0, statsFilePath.lastIndexOf( "." ) ) + "_hieraryStatistics.csv"; HierarchyStatistics stats = new HierarchyStatistics( inputData, statsFilePath ); // TODO: Visualizations saved to images if ( !config.hasSkipVisualisations() ) { HierarchyProcessor vis = new HierarchyProcessor(); try { // vis.process( context, stats ); } catch ( Exception e ) { log.error( e ); } } } private static void executeGUI( HVContext ctx ) { HVConfig config = ctx.getConfig(); // Attempt to set the application's Look and Feel boolean successLAF = false; String prefLAF = config.getPreferredLookAndFeel(); if ( prefLAF != null && !prefLAF.isEmpty() ) { try { // Try to use the user's preferred LAF, if we find it. for ( LookAndFeelInfo info : UIManager.getInstalledLookAndFeels() ) { if ( info.getName().equals( config.getPreferredLookAndFeel() ) ) { UIManager.setLookAndFeel( info.getClassName() ); successLAF = true; break; } } } catch ( ClassNotFoundException | UnsupportedLookAndFeelException e ) { log.error( "Could not find a matching LAF for name '%s'. Falling back to system default.%n", config.getPreferredLookAndFeel() ); } catch ( Exception ex ) { log.error( "Error occurred while setting preferred LAF: %s", ex ); } if ( !successLAF ) { log.info( "Could not find a matching LAF for name '%s'. Falling back to system default.%n", config.getPreferredLookAndFeel() ); } } if ( !successLAF ) { // If the preferred L&F is not available, try to fall back to system default. try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); } catch ( Exception ex ) { // If THAT failed, fall back to cross-platform, ie. default Swing look. log.info( "Could not set system default LAF. Falling back to cross-platform LAF.%n" ); try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() ); } catch ( Exception exc ) { // Never happens. log.error( "Error occurred while setting cross-platform LAF: %s", exc ); } } // Set the preferred LAF to the current one, so that we don't have to look it up again, // and so that the correct LAF is selected in the config dialog. config.setPreferredLookAndFeel( UIManager.getLookAndFeel().getName() ); } try { // Due to some internal workings of Swing, default sounds are not played for non-default LAFs. // Details: stackoverflow.com/questions/12128231/12156617#12156617 Object[] cueList = (Object[])UIManager.get( "AuditoryCues.cueList" ); UIManager.put( "AuditoryCues.playList", cueList ); } catch ( Exception e ) { log.error( "Error occurred while setting auditory cues list: %s", e ); } // Attempt to set the application name so that it displays correctly on all platforms. // Mac System.setProperty( "com.apple.mrj.application.apple.menu.about.name", APP_NAME ); System.setProperty( "apple.awt.application.name", APP_NAME ); // Linux try { Toolkit xToolkit = Toolkit.getDefaultToolkit(); Field awtAppClassNameField = xToolkit.getClass().getDeclaredField( "awtAppClassName" ); awtAppClassNameField.setAccessible( true ); awtAppClassNameField.set( xToolkit, APP_NAME ); } catch ( Exception e ) { log.trace( "Failed to set app name via toolkit reflection." ); } // Ensure all popups are triggered from the event dispatch thread. SwingUtilities.invokeLater( new Runnable() { public void run() { initGUI( ctx ); } } ); } private static void initGUI( HVContext ctx ) { VisualizerFrame frame = new VisualizerFrame( ctx ); frame.setVisible( true ); } }
package com.design; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class KnightTest { @Test public void createKnightTrueTest() { Knight knight = new KnightBuilder().withName("Sir Arthur").withArmor(true).withShield(true).withSword(true).withKnife(true).build(); assertNotNull(knight); assertEquals("Sir Arthur", knight.getName()); assertEquals(true, knight.isKnightArmor()); assertEquals(true, knight.isShield()); assertEquals(true, knight.isSword()); assertEquals(true, knight.isKnife()); } @Test public void createKnightFalseTest() { Knight knight = new KnightBuilder().withName("Sir Arthur").build(); assertNotNull(knight); assertEquals("Sir Arthur", knight.getName()); assertEquals(false, knight.isKnightArmor()); assertEquals(false, knight.isShield()); assertEquals(false, knight.isSword()); assertEquals(false, knight.isKnife()); } @Test public void createKnightArmorTest() { Knight knight = new KnightBuilder().withArmor(true).build(); assertNotNull(knight); assertEquals(true, knight.isKnightArmor()); assertEquals(false, knight.isShield()); assertEquals(false, knight.isSword()); assertEquals(false, knight.isKnife()); } @Test public void createKnightShieldTest() { Knight knight = new KnightBuilder().withShield(true).build(); assertNotNull(knight); assertEquals(false, knight.isKnightArmor()); assertEquals(true, knight.isShield()); assertEquals(false, knight.isSword()); assertEquals(false, knight.isKnife()); } @Test public void createKnightSwordTest() { Knight knight = new KnightBuilder().withSword(true).build(); assertNotNull(knight); assertEquals(false, knight.isKnightArmor()); assertEquals(false, knight.isShield()); assertEquals(true, knight.isSword()); assertEquals(false, knight.isKnife()); } @Test public void createKnightKnifeTest() { Knight knight = new KnightBuilder().withKnife(true).build(); assertNotNull(knight); assertEquals(false, knight.isKnightArmor()); assertEquals(false, knight.isShield()); assertEquals(false, knight.isSword()); assertEquals(true, knight.isKnife()); } }
package org.rti.webgenome.service.io; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.log4j.Logger; import org.rti.webgenome.core.WebGenomeSystemException; import org.rti.webgenome.domain.Array; import org.rti.webgenome.domain.ArrayDatum; import org.rti.webgenome.domain.BioAssay; import org.rti.webgenome.domain.ChromosomeArrayData; import org.rti.webgenome.domain.DataContainingBioAssay; import org.rti.webgenome.domain.DataFileMetaData; import org.rti.webgenome.domain.DataSerializedBioAssay; import org.rti.webgenome.domain.DataSourceProperties; import org.rti.webgenome.domain.Experiment; import org.rti.webgenome.domain.RectangularTextFileFormat; import org.rti.webgenome.domain.ShoppingCart; import org.rti.webgenome.domain.UploadDataSourceProperties; import org.rti.webgenome.domain.ZipEntryMetaData; import org.rti.webgenome.domain.ZipFileMetaData; import org.rti.webgenome.graphics.util.ColorChooser; import org.rti.webgenome.service.analysis.SerializedDataTransformer; import org.rti.webgenome.service.util.IdGenerator; import org.rti.webgenome.service.util.SerializedChromosomeArrayDataGetter; import org.rti.webgenome.util.FileUtils; import org.rti.webgenome.util.IOUtils; /** * Facade class for performing IO of data files. Normally * clients will only interact with this class for IO. * @author dhall */ public class IOService { // STATICS /** * Size of buffer array used for streaming uploaded * bits to a file. */ private static final int BUFFER_SIZE = 1000000; //1MB /** * File name extension used for files saved in the * working directory. */ private static final String FILE_EXTENSION = ".smd"; /** Logger. */ private static final Logger LOGGER = Logger.getLogger(IOService.class); /** Name of manifest file in a JAR archive. */ private static final String JAR_MANIFEST_FILE_NAME = "MANIFEST.MF"; // ATTRIBUTES /** Working directory for parsing data. */ private final File workingDir; /** * Generates unique file names for uploaded files in the * <code>workingDir</code> directory. */ private final UniqueFileNameGenerator fileNameGenerator; /** Data file manager. */ private final DataFileManager dataFileManager; /** Generator of primary key values for experiments. */ private IdGenerator experimentIdGenerator = null; /** Generator of primary key values for bioassays. */ private IdGenerator bioAssayIdGenerator = null; // S E T T E R S /** * Set generator for bioassay primary key values. * @param bioassayIdGenerator Generator of IDs */ public void setBioAssayIdGenerator( final IdGenerator bioassayIdGenerator) { this.bioAssayIdGenerator = bioassayIdGenerator; } /** * Set generator for experiment primary key values. * @param experimentIdGenerator Generator of IDs */ public void setExperimentIdGenerator( final IdGenerator experimentIdGenerator) { this.experimentIdGenerator = experimentIdGenerator; } // CONSTRUCTORS /** * Constructor. * @param workingDirPath Path to working directory used * for parsing data. * @param dataFileManager Manages serialization/deserialization * of array data */ public IOService(final String workingDirPath, final DataFileManager dataFileManager) { this.workingDir = new File(workingDirPath); if (!this.workingDir.exists()) { try { LOGGER.info("Creating directory for file uploads: " + workingDirPath); FileUtils.createDirectory(workingDirPath); } catch (Exception e) { throw new WebGenomeSystemException( "Error creating file upload directory", e); } } if (!this.workingDir.isDirectory()) { throw new IllegalArgumentException( "Working directory path does not reference a " + "real directory"); } this.fileNameGenerator = new UniqueFileNameGenerator( this.workingDir, FILE_EXTENSION); this.dataFileManager = dataFileManager; } // BUSINESS METHODS /** * Upload data from given input stream into a new file in * the working directory. * @param in Upload inputstream. * @return File containing uploaded data. The name of this * file will be a randomly-generated unique file name. */ public File upload(final InputStream in) { // Buffer for uploading byte[] buffer = new byte[BUFFER_SIZE]; // Generate file for holding uploaded data String fname = this.fileNameGenerator.next(); String path = this.workingDir.getAbsolutePath() + File.separator + fname; File file = new File(path); // Stream data into file OutputStream out = null; try { out = new FileOutputStream(file); int bytesRead = in.read(buffer); while (bytesRead > 0) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer); } out.flush(); } catch (Exception e) { throw new WebGenomeSystemException("Error uploading file", e); } finally { IOUtils.close(out); } return file; } /** * Upload and extract individual data files from ZIP file. Individual * files will be stored locally. The original ZIP file will not. * @param in Input stream to ZIP file. * @param zipFileName Zip file name on remote system. * @param format Rectangular data file format * @return Metadata for zip data. */ public ZipFileMetaData uploadZipFile(final InputStream in, final String zipFileName, final RectangularTextFileFormat format) { // Stream ZIP file to disk File zipFile = this.upload(in); // Instantiate zip file metadata ZipFileMetaData meta = new ZipFileMetaData(zipFileName); meta.setFileFormat(format); // Extract zip entry files ZipInputStream zipIn = null; try { zipIn = new ZipInputStream( new FileInputStream(zipFile)); ZipEntry zipEntry = zipIn.getNextEntry(); while (zipEntry != null) { if (this.probableDataFile(zipEntry)) { File zipEntryFile = this.upload(zipIn); ZipEntryMetaData zeMeta = new ZipEntryMetaData( zipEntryFile, zipEntry.getName()); meta.add(zeMeta); RectangularFileReader reader = new RectangularFileReader(zipEntryFile); // validate if (!reader.validate()){ meta.setErrorFileName(zipEntry.getName()); return meta; } reader.setDelimiter(format.getDelimiter()); zeMeta.setColumnHeadings(reader.getColumnHeadings()); } zipEntry = zipIn.getNextEntry(); } } catch (Exception e) { throw new WebGenomeSystemException("Error extracint ZIP file", e); } finally { IOUtils.close(zipIn); } // Delete ZIP file if (!zipFile.delete()) { LOGGER.warn("Unable to delete ZIP file"); } return meta; } /** * Determine if given ZIP file entry likely represents a data * containing file. * @param zipEntry ZIP file entry * @return T/F */ private boolean probableDataFile(final ZipEntry zipEntry) { return !zipEntry.isDirectory() && zipEntry.getName().indexOf(JAR_MANIFEST_FILE_NAME) < 0; } /** * Delete file with given name form working directory. * @param fileName Name of file to delete (not absolute path). */ public void delete(final String fileName) { String path = this.workingDir.getAbsolutePath() + File.separator + fileName; File file = new File(path); if (file.exists() && file.isFile()) { LOGGER.info("Deleting serialized data file '" + file.getAbsolutePath() + "'"); if (!file.delete()) { LOGGER.warn("Unable to delete uploaded file '" + path + "'"); } } } /** * Delete data files. * @param fNames Names of data files */ public void deleteDataFiles(final Collection<String> fNames) { for (String fName : fNames) { this.delete(fName); } } /** * Load SMD format data from named file and put in shopping cart. * @param upload Upload data source properties * @param shoppingCart Shopping cart * @return New experiment that was added to shopping cart. * Clients should not subquently add this experiment object to * the cart. It has already been added. * @throws SmdFormatException If file does not contain * valid SMD format data */ public Experiment loadSmdData(final UploadDataSourceProperties upload, final ShoppingCart shoppingCart) throws SmdFormatException { Experiment experiment = new Experiment(upload.getExperimentName()); experiment.setOrganism(upload.getOrganism()); experiment.setId(this.experimentIdGenerator.nextId()); experiment.setQuantitationType(upload.getQuantitationType()); experiment.setQuantitationTypeLabel(upload.getQuantitationTypeLabel()); File reporterFile = null; String reporterNameColName = null; RectangularTextFileFormat format = null; if (upload.getReporterLocalFileName() == null) { Set<DataFileMetaData> meta = upload.getDataFileMetaData(); if (meta == null || meta.size() < 1) { throw new IllegalArgumentException("No data file specified"); } DataFileMetaData firstMeta = meta.iterator().next(); reporterFile = this.getWorkingFile( firstMeta.getLocalFileName()); reporterNameColName = firstMeta.getReporterNameColumnName(); format = firstMeta.getFormat(); } else { reporterFile = this.getWorkingFile( upload.getReporterLocalFileName()); reporterNameColName = upload.getReporterFileReporterNameColumnName(); format = upload.getReporterFileFormat(); } SmdFileReader reader = new SmdFileReader(reporterFile, reporterNameColName, upload.getChromosomeColumnName(), upload.getPositionColumnName(), upload.getPositionUnits(), format); Array array = this.dataFileManager.serializeReporters(reader); for (DataFileMetaData meta : upload.getDataFileMetaData()) { File dataFile = this.getWorkingFile(meta.getLocalFileName()); this.dataFileManager.convertSmdData(reader, experiment, dataFile, meta, upload.getOrganism(), array); } experiment.setDataSourceProperties(upload); ColorChooser colorChooser = shoppingCart.getBioassayColorChooser(); for (BioAssay ba : experiment.getBioAssays()) { ba.setId(this.bioAssayIdGenerator.nextId()); ba.setColor(colorChooser.nextColor()); } shoppingCart.add(experiment); return experiment; } /** * Delete all serialized data files associated with * given experiment. * @param exp An experiment */ public void deleteDataFiles(final Experiment exp) { if (!exp.dataInMemory()) { // If data originated from file upload, there // will be one reporter file for upload which // will not be used by any other data. Thus, // it should be deleted. Also delete temp // upload file. boolean deleteReporters = false; DataSourceProperties props = exp.getDataSourceProperties(); if (props instanceof UploadDataSourceProperties) { deleteReporters = true; UploadDataSourceProperties uProps = (UploadDataSourceProperties) props; this.delete(uProps.getReporterLocalFileName()); for (DataFileMetaData meta : uProps.getDataFileMetaData()) { this.delete(meta.getLocalFileName()); } } // Delete files and possibly reporters this.dataFileManager.deleteDataFiles(exp, deleteReporters); } } /** * Delete all reporter data files associated with array. * @param array Array from which to delete */ public void deleteDataFiles(final Array array) { for (String fName : array.getChromosomeReportersFileNames().values()) { this.dataFileManager.deleteDataFile(fName); } } /** * Convert any enclosed <code>DataContainingBioAssay</code> * objects to <code>DataSerializedBioAssay</code> objects. * @param experiment An experiment */ public void convertBioAssays(final Experiment experiment) { Iterator<BioAssay> it = experiment.getBioAssays().iterator(); Collection<BioAssay> newBioAssays = new ArrayList<BioAssay>(); while (it.hasNext()) { BioAssay bioAssay = it.next(); if (bioAssay instanceof DataContainingBioAssay) { DataSerializedBioAssay serBioAssay = this.newDataSerializedBioAssay( (DataContainingBioAssay) bioAssay); it.remove(); newBioAssays.add(serBioAssay); } } experiment.getBioAssays().addAll(newBioAssays); } /** * Convert given data containing bioassay into a * data serialized equivalent. * @param dcBioAssay Data containing bioassay * @return Data serialized bioassay */ private DataSerializedBioAssay newDataSerializedBioAssay( final DataContainingBioAssay dcBioAssay) { DataSerializedBioAssay dsBioAssay = new DataSerializedBioAssay(); dsBioAssay.bulkSetNonDataProperties(dcBioAssay); Collection<Short> chroms = dcBioAssay.getChromosomes(); for (Short chrom : chroms) { ChromosomeArrayData cad = dcBioAssay.getChromosomeArrayData(chrom); this.dataFileManager.saveChromosomeArrayData(dsBioAssay, cad); } return dsBioAssay; } /** * Get a serialized data transformer that is configured to * use the same data file directory as this. * @return Serialized data transformer. */ public SerializedDataTransformer getSerializedDataTransformer() { return new SerializedDataTransformer(this.dataFileManager); } /** * Get a serialized chromosome array data getter that is * configured to use the same data file directory as this. * @return Serialized chromosome array data getter */ public SerializedChromosomeArrayDataGetter getSerializedChromosomeArrayDataGetter() { return new SerializedChromosomeArrayDataGetter(this.dataFileManager); } /** * Get all column headings from given file. * @param fileName Name of file in working directory. This is * not an absolute path. * @param format File format * @return Column headings */ public Set<String> getColumnHeadings(final String fileName, final RectangularTextFileFormat format) { Set<String> cols = new HashSet<String>(); File file = this.getWorkingFile(fileName); if (!file.exists() || !file.isFile()) { throw new WebGenomeSystemException( "Cannot get headings from file '" + fileName + "'."); } RectangularFileReader reader = new RectangularFileReader(file); reader.setDelimiter(format.getDelimiter()); cols.addAll(reader.getColumnHeadings()); return cols; } /** * Get all column headings from given data files. * @param dataFileMetaData Metadata on data files * @return Union of all column headings */ public Set<String> getColumnHeadings( final Collection<DataFileMetaData> dataFileMetaData) { Set<String> cols = new HashSet<String>(); for (DataFileMetaData meta : dataFileMetaData) { String fileName = meta.getLocalFileName(); cols.addAll(this.getColumnHeadings(fileName, meta.getFormat())); } return cols; } /** * Get file referenced by given file name, which is in * {@code workingDir}. * @param fileName Name of file (not absolute path) * @return Working file */ public File getWorkingFile(final String fileName) { String path = this.workingDir.getAbsolutePath() + "/" + fileName; return new File(path); } /** * Create unique file name into working directory and writes bioassya raw data * into delimiter separated rectangular file. * * @param arrDatums * @return * @throws Exception */ public String writeBioAssayRawData(final List<ArrayDatum> arrDatums) throws Exception{ // craete unique file name String fullFileName = this.workingDir.getAbsolutePath() + "/" + fileNameGenerator.next(); // write bioassay data into the file File f = new File(fullFileName); RectangularFileWriter rfw = new RectangularFileWriter(arrDatums); // return the file name return fullFileName; } }
package tigase.jaxmpp.core.client.xmpp.modules.vcard; import java.io.Serializable; import java.util.List; import tigase.jaxmpp.core.client.xml.DefaultElement; import tigase.jaxmpp.core.client.xml.Element; import tigase.jaxmpp.core.client.xml.XMLException; public class VCard implements Serializable { private static final long serialVersionUID = 1L; private static void add(Element vcard, String name, String value) throws XMLException { if (value != null) vcard.addChild(new DefaultElement(name, value, null)); } private static void add(Element vcard, String name, String[] childNames, String[] values) throws XMLException { Element x = new DefaultElement(name); vcard.addChild(x); for (int i = 0; i < childNames.length; i++) { x.addChild(new DefaultElement(childNames[i], values[i], null)); } } private static String getChildValue(Element it, String string) throws XMLException { List<Element> l = it.getChildren(string); if (l == null || l.size() == 0) return null; return l.get(0).getValue(); } private static boolean match(final Element it, final String elemName, final String... children) throws XMLException { if (!elemName.equals(it.getName())) return false; for (String string : children) { List<Element> l = it.getChildren(string); if (l == null || l.size() == 0) return false; } return true; } private String bday; private String description; private String fullName; private String homeAddressCtry; private String homeAddressLocality; private String homeAddressPCode; private String homeAddressRegion; private String homeAddressStreet; private String homeEmail; private String homeTelFax; private String homeTelMsg; private String homeTelVoice; private String jabberID; private String nameFamily; private String nameGiven; private String nameMiddle; private String nickName; private String orgName; private String orgUnit; private String photoType; private String photoVal; private String role; private String title; private String url; private String workAddressCtry; private String workAddressLocality; private String workAddressPCode; private String workAddressRegion; private String workAddressStreet; private String workEmail; private String workTelFax; private String workTelMsg; private String workTelVoice; public String getBday() { return bday; } public String getDescription() { return description; } public String getFullName() { return fullName; } public String getHomeAddressCtry() { return homeAddressCtry; } public String getHomeAddressLocality() { return homeAddressLocality; } public String getHomeAddressPCode() { return homeAddressPCode; } public String getHomeAddressRegion() { return homeAddressRegion; } public String getHomeAddressStreet() { return homeAddressStreet; } public String getHomeEmail() { return homeEmail; } public String getHomeTelFax() { return homeTelFax; } public String getHomeTelMsg() { return homeTelMsg; } public String getHomeTelVoice() { return homeTelVoice; } public String getJabberID() { return jabberID; } public String getNameFamily() { return nameFamily; } public String getNameGiven() { return nameGiven; } public String getNameMiddle() { return nameMiddle; } public String getNickName() { return nickName; } public String getOrgName() { return orgName; } public String getOrgUnit() { return orgUnit; } public String getPhotoType() { return photoType; } public String getPhotoVal() { return photoVal; } public String getRole() { return role; } public String getTitle() { return title; } public String getUrl() { return url; } public String getWorkAddressCtry() { return workAddressCtry; } public String getWorkAddressLocality() { return workAddressLocality; } public String getWorkAddressPCode() { return workAddressPCode; } public String getWorkAddressRegion() { return workAddressRegion; } public String getWorkAddressStreet() { return workAddressStreet; } public String getWorkEmail() { return workEmail; } public String getWorkTelFax() { return workTelFax; } public String getWorkTelMsg() { return workTelMsg; } public String getWorkTelVoice() { return workTelVoice; } void loadData(final Element element) throws XMLException { if (!element.getName().equals("vCard") || !element.getXMLNS().equals("vcard-temp")) throw new RuntimeException("Element isn't correct <vCard xmlns='vcard-temp'> vcard element"); for (final Element it : element.getChildren()) { if (match(it, "EMAIL", "WORK")) { this.workEmail = getChildValue(it, "USERID"); } else if (match(it, "EMAIL", "HOME")) { this.homeEmail = getChildValue(it, "USERID"); } else if (match(it, "ADR", "HOME")) { for (Element e : it.getChildren()) { if ("STREET".equals(e.getName())) { this.homeAddressStreet = e.getValue(); } else if ("LOCALITY".equals(e.getName())) { this.homeAddressLocality = e.getValue(); } else if ("REGION".equals(e.getName())) { this.homeAddressRegion = e.getValue(); } else if ("PCODE".equals(e.getName())) { this.homeAddressPCode = e.getValue(); } else if ("CTRY".equals(e.getName())) { this.homeAddressCtry = e.getValue(); } } } else if (match(it, "ADR", "WORK")) { for (Element e : it.getChildren()) { if ("STREET".equals(e.getName())) { this.workAddressStreet = e.getValue(); } else if ("LOCALITY".equals(e.getName())) { this.workAddressLocality = e.getValue(); } else if ("REGION".equals(e.getName())) { this.workAddressRegion = e.getValue(); } else if ("PCODE".equals(e.getName())) { this.workAddressPCode = e.getValue(); } else if ("CTRY".equals(e.getName())) { this.workAddressCtry = e.getValue(); } } } else if (match(it, "TEL", "WORK", "VOICE")) { this.workTelVoice = getChildValue(it, "NUMBER"); } else if (match(it, "TEL", "WORK", "FAX")) { this.workTelFax = getChildValue(it, "NUMBER"); } else if (match(it, "TEL", "WORK", "MSG")) { this.workTelMsg = getChildValue(it, "NUMBER"); } else if (match(it, "TEL", "HOME", "VOICE")) { this.homeTelVoice = getChildValue(it, "NUMBER"); } else if (match(it, "TEL", "HOME", "FAX")) { this.homeTelFax = getChildValue(it, "NUMBER"); } else if (match(it, "TEL", "HOME", "MSG")) { this.homeTelMsg = getChildValue(it, "NUMBER"); } else if ("FN".equals(it.getName())) { this.fullName = it.getValue(); } else if ("N".equals(it.getName())) { for (Element pit : it.getChildren()) { if ("FAMILY".equals(pit.getName())) { this.nameFamily = pit.getValue(); } else if ("GIVEN".equals(pit.getName())) { this.nameGiven = pit.getValue(); } else if ("MIDDLE".equals(pit.getName())) { this.nameMiddle = pit.getValue(); } } } else if ("NICKNAME".equals(it.getName())) { this.nickName = it.getValue(); } else if ("URL".equals(it.getName())) { this.url = it.getValue(); } else if ("BDAY".equals(it.getName())) { this.bday = it.getValue(); } else if ("ORG".equals(it.getName())) { for (Element pit : it.getChildren()) { if ("ORGNAME".equals(pit.getName())) { this.orgName = pit.getValue(); } else if ("ORGUNIT".equals(pit.getName())) { this.orgUnit = pit.getValue(); } } } else if ("TITLE".equals(it.getName())) { this.title = it.getValue(); } else if ("ROLE".equals(it.getName())) { this.role = it.getValue(); } else if ("JABBERID".equals(it.getName())) { this.jabberID = it.getValue(); } else if ("DESC".equals(it.getName())) { this.description = it.getValue(); } else if ("PHOTO".equals(it.getName())) { for (Element pit : it.getChildren()) { if ("TYPE".equals(pit.getName())) { this.photoType = pit.getValue(); } else if ("BINVAL".equals(pit.getName())) { this.photoVal = pit.getValue(); if (this.photoVal != null) this.photoVal = this.photoVal.replace("\n", "").trim(); } } } } } public Element makeElement() throws XMLException { Element vcard = new DefaultElement("vCard", null, "vcard-temp"); add(vcard, "FN", this.fullName); add(vcard, "N", new String[] { "FAMILY", "GIVEN", "MIDDLE" }, new String[] { this.nameFamily, this.nameGiven, this.nameMiddle }); add(vcard, "NICKNAME", this.nickName); add(vcard, "URL", this.url); add(vcard, "BDAY", this.bday); add(vcard, "ORG", new String[] { "ORGNAME", "ORGUNIT" }, new String[] { this.orgName, this.orgUnit }); add(vcard, "TITLE", this.title); add(vcard, "ROLE", this.role); add(vcard, "TEL", new String[] { "WORK", "VOICE", "NUMBER" }, new String[] { null, null, this.workTelVoice }); add(vcard, "TEL", new String[] { "WORK", "FAX", "NUMBER" }, new String[] { null, null, this.workTelFax }); add(vcard, "TEL", new String[] { "WORK", "MSG", "NUMBER" }, new String[] { null, null, this.workTelMsg }); add(vcard, "ADR", new String[] { "WORK", "STREET", "LOCALITY", "REGION", "PCODE", "CTRY" }, new String[] { null, this.workAddressStreet, this.workAddressLocality, this.workAddressRegion, this.workAddressPCode, this.workAddressCtry }); add(vcard, "TEL", new String[] { "HOME", "VOICE", "NUMBER" }, new String[] { null, null, this.homeTelVoice }); add(vcard, "TEL", new String[] { "HOME", "FAX", "NUMBER" }, new String[] { null, null, this.homeTelFax }); add(vcard, "TEL", new String[] { "HOME", "MSG", "NUMBER" }, new String[] { null, null, this.homeTelMsg }); add(vcard, "ADR", new String[] { "HOME", "STREET", "LOCALITY", "REGION", "PCODE", "CTRY" }, new String[] { null, this.homeAddressStreet, this.homeAddressLocality, this.homeAddressRegion, this.homeAddressPCode, this.homeAddressCtry }); add(vcard, "JABBERID", this.jabberID); add(vcard, "DESC", this.description); add(vcard, "EMAIL", new String[] { "HOME", "USERID" }, new String[] { null, this.homeEmail }); add(vcard, "EMAIL", new String[] { "WORK", "USERID" }, new String[] { null, this.workEmail }); add(vcard, "PHOTO", new String[] { "TYPR", "BINVAL" }, new String[] { this.photoType, this.photoVal }); return vcard; } public void setBday(String bday) { this.bday = bday; } public void setDescription(String description) { this.description = description; } public void setFullName(String fullName) { this.fullName = fullName; } public void setHomeAddressCtry(String homeAddressCtry) { this.homeAddressCtry = homeAddressCtry; } public void setHomeAddressLocality(String homeAddressLocality) { this.homeAddressLocality = homeAddressLocality; } public void setHomeAddressPCode(String homeAddressPCode) { this.homeAddressPCode = homeAddressPCode; } public void setHomeAddressRegion(String homeAddressRegion) { this.homeAddressRegion = homeAddressRegion; } public void setHomeAddressStreet(String homeAddressStreet) { this.homeAddressStreet = homeAddressStreet; } public void setHomeEmail(String homeEmail) { this.homeEmail = homeEmail; } public void setHomeTelFax(String homeTelFax) { this.homeTelFax = homeTelFax; } public void setHomeTelMsg(String homeTelMsg) { this.homeTelMsg = homeTelMsg; } public void setHomeTelVoice(String homeTelVoice) { this.homeTelVoice = homeTelVoice; } public void setJabberID(String jabberID) { this.jabberID = jabberID; } public void setNameFamily(String nameFamily) { this.nameFamily = nameFamily; } public void setNameGiven(String nameGiven) { this.nameGiven = nameGiven; } public void setNameMiddle(String nameMiddle) { this.nameMiddle = nameMiddle; } public void setNickName(String nickName) { this.nickName = nickName; } public void setOrgName(String orgName) { this.orgName = orgName; } public void setOrgUnit(String orgUnit) { this.orgUnit = orgUnit; } public void setPhotoType(String photoType) { this.photoType = photoType; } public void setPhotoVal(String photoVal) { this.photoVal = photoVal; } public void setRole(String role) { this.role = role; } public void setTitle(String title) { this.title = title; } public void setUrl(String url) { this.url = url; } public void setWorkAddressCtry(String workAddressCtry) { this.workAddressCtry = workAddressCtry; } public void setWorkAddressLocality(String workAddressLocality) { this.workAddressLocality = workAddressLocality; } public void setWorkAddressPCode(String workAddressPCode) { this.workAddressPCode = workAddressPCode; } public void setWorkAddressRegion(String workAddressRegion) { this.workAddressRegion = workAddressRegion; } public void setWorkAddressStreet(String workAddressStreet) { this.workAddressStreet = workAddressStreet; } public void setWorkEmail(String workEmail) { this.workEmail = workEmail; } public void setWorkTelFax(String workTelFax) { this.workTelFax = workTelFax; } public void setWorkTelMsg(String workTelMsg) { this.workTelMsg = workTelMsg; } public void setWorkTelVoice(String workTelVoice) { this.workTelVoice = workTelVoice; } }
package org.smoothbuild.io.util; import static com.google.common.base.Preconditions.checkState; import static org.smoothbuild.io.fs.base.Path.path; import static org.smoothbuild.io.fs.base.RecursivePathsIterator.recursivePathsIterator; import java.io.IOException; import org.smoothbuild.io.fs.base.FileSystem; import org.smoothbuild.io.fs.base.Path; import org.smoothbuild.io.fs.base.PathIterator; import org.smoothbuild.lang.value.Array; import org.smoothbuild.lang.value.ArrayBuilder; import org.smoothbuild.lang.value.Blob; import org.smoothbuild.lang.value.SString; import org.smoothbuild.lang.value.Struct; import org.smoothbuild.task.exec.Container; import okio.BufferedSink; import okio.BufferedSource; import okio.Source; public class TempDir { private final Container container; private final FileSystem fileSystem; private final Path rootPath; private boolean isDestroyed; public TempDir(Container container, FileSystem fileSystem, Path rootPath) { this.container = container; this.fileSystem = fileSystem; this.rootPath = rootPath; this.isDestroyed = false; } public String rootOsPath() { return rootPath.toJPath().toString(); } public String asOsPath(Path path) { return rootPath.append(path).toJPath().toString(); } public void destroy() throws IOException { fileSystem.delete(rootPath); isDestroyed = true; } public void writeFiles(Array files) throws IOException { assertNotDestroyed(); writeFilesImpl(files); } private void writeFilesImpl(Array files) throws IOException { for (Struct file : files.asIterable(Struct.class)) { writeFileImpl(file); } } public void writeFile(Struct file) throws IOException { assertNotDestroyed(); writeFileImpl(file); } private void writeFileImpl(Struct file) throws IOException { Path path = path(((SString) file.get("path")).data()); Blob content = (Blob) file.get("content"); try (BufferedSink sink = fileSystem.sink(rootPath.append(path)); Source source = content.source()) { sink.writeAll(source); } } public Array readFiles() throws IOException { assertNotDestroyed(); return readFilesImpl(); } private Array readFilesImpl() throws IOException { ArrayBuilder arrayBuilder = container.create().arrayBuilder(container.types().file()); for (PathIterator it = recursivePathsIterator(fileSystem, rootPath); it.hasNext();) { Path path = it.next(); Blob content = readContentImpl(path); Struct file = container.create().file(container.create().string(path.value()), content); arrayBuilder.add(file); } return arrayBuilder.build(); } public Blob readContent(Path path) throws IOException { assertNotDestroyed(); return readContentImpl(path); } private Blob readContentImpl(Path path) throws IOException { try (BufferedSource source = fileSystem.source(rootPath.append(path))) { return container.create().blob(sink -> sink.writeAll(source)); } } private void assertNotDestroyed() { checkState(!isDestroyed, "This TempDir is destroyed."); } }
package com.jme3.anim; import com.jme3.anim.tween.Tween; import com.jme3.anim.tween.Tweens; import com.jme3.anim.tween.action.*; import com.jme3.export.*; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.control.AbstractControl; import com.jme3.util.clone.Cloner; import java.io.IOException; import java.util.*; public class AnimComposer extends AbstractControl { private Map<String, AnimClip> animClipMap = new HashMap<>(); private Action currentAction; private Map<String, Action> actions = new HashMap<>(); private float globalSpeed = 1f; private float time; /** * Retrieve an animation from the list of animations. * * @param name The name of the animation to retrieve. * @return The animation corresponding to the given name, or null, if no * such named animation exists. */ public AnimClip getAnimClip(String name) { return animClipMap.get(name); } /** * Adds an animation to be available for playing to this * <code>AnimControl</code>. * * @param anim The animation to add. */ public void addAnimClip(AnimClip anim) { animClipMap.put(anim.getName(), anim); } /** * Remove an animation so that it is no longer available for playing. * * @param anim The animation to remove. */ public void removeAnimClip(AnimClip anim) { if (!animClipMap.containsKey(anim.getName())) { throw new IllegalArgumentException("Given animation does not exist " + "in this AnimControl"); } animClipMap.remove(anim.getName()); } public Action setCurrentAction(String name) { currentAction = action(name); time = 0; return currentAction; } public Action action(String name) { Action action = actions.get(name); if (action == null) { action = makeAction(name); actions.put(name, action); } return action; } public Action makeAction(String name) { Action action; AnimClip clip = animClipMap.get(name); if (clip == null) { throw new IllegalArgumentException("Cannot find clip named " + name); } action = new ClipAction(clip); return action; } public BaseAction actionSequence(String name, Tween... tweens) { BaseAction action = new BaseAction(Tweens.sequence(tweens)); actions.put(name, action); return action; } public BlendAction actionBlended(String name, BlendSpace blendSpace, String... clips) { BlendableAction[] acts = new BlendableAction[clips.length]; for (int i = 0; i < acts.length; i++) { BlendableAction ba = (BlendableAction) makeAction(clips[i]); acts[i] = ba; } BlendAction action = new BlendAction(blendSpace, acts); actions.put(name, action); return action; } public void reset() { currentAction = null; time = 0; } public Collection<AnimClip> getAnimClips() { return Collections.unmodifiableCollection(animClipMap.values()); } public Collection<String> getAnimClipsNames() { return Collections.unmodifiableCollection(animClipMap.keySet()); } @Override protected void controlUpdate(float tpf) { if (currentAction != null) { time += tpf; boolean running = currentAction.interpolate(time * globalSpeed); if (!running) { time = 0; } } } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } public float getGlobalSpeed() { return globalSpeed; } public void setGlobalSpeed(float globalSpeed) { this.globalSpeed = globalSpeed; } @Override public Object jmeClone() { try { AnimComposer clone = (AnimComposer) super.clone(); return clone; } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } @Override public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); Map<String, AnimClip> clips = new HashMap<>(); for (String key : animClipMap.keySet()) { clips.put(key, cloner.clone(animClipMap.get(key))); } Map<String, Action> act = new HashMap<>(); for (String key : actions.keySet()) { act.put(key, cloner.clone(actions.get(key))); } actions = act; animClipMap = clips; } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); animClipMap = (Map<String, AnimClip>) ic.readStringSavableMap("animClipMap", new HashMap<String, AnimClip>()); } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); oc.writeStringSavableMap(animClipMap, "animClipMap", new HashMap<String, AnimClip>()); } }
package org.takes.facets.fork; import java.util.Locale; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Media type. * * <p>The class is immutable and thread-safe. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 0.6 * @see org.takes.facets.fork.FkTypes */ @ToString @EqualsAndHashCode(of = { "high", "low" }) final class MediaType implements Comparable<MediaType> { /** * Priority. */ private final transient Double priority; /** * High part. */ private final transient String high; /** * Low part. */ private final transient String low; /** * Ctor. * @param text Text to parse */ MediaType(final String text) { final String[] parts = text.split(";", 2); if (parts.length > 1) { final String num = parts[1].replaceAll("[^0-9\\.]", ""); if (num.isEmpty()) { this.priority = 0.0d; } else { this.priority = Double.parseDouble(num); } } else { this.priority = 1.0d; } final String[] sectors = parts[0] .toLowerCase(Locale.ENGLISH).split("/", 2); this.high = sectors[0]; if (sectors.length > 1) { this.low = sectors[1].trim(); } else { this.low = ""; } } @Override public int compareTo(final MediaType type) { int cmp = this.priority.compareTo(type.priority); if (cmp == 0) { cmp = this.high.compareTo(type.high); if (cmp == 0) { cmp = this.low.compareTo(type.low); } } return cmp; } /** * Matches. * @param type Another type * @return TRUE if matches * @checkstyle BooleanExpressionComplexityCheck (10 lines) */ public boolean matches(final MediaType type) { final String star = "*"; return (this.high.equals(star) || type.high.equals(star) || this.high.equals(type.high)) && (this.low.equals(star) || type.low.equals(star) || this.low.equals(type.low)); } }
package org.jpos.q2.qbean; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.iso.ISOUtil; import org.jpos.q2.Q2; import org.jpos.q2.QBeanSupport; import org.jpos.util.Loggeable; import org.jpos.util.Logger; import org.jpos.util.NameRegistrar; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadMXBean; import java.net.InetAddress; import java.nio.charset.Charset; /** * Periodically dumps Thread and memory usage * * @author apr@cs.com.uy * @version $Id$ * @see Logger */ public class SystemMonitor extends QBeanSupport implements Runnable, SystemMonitorMBean, Loggeable { private long sleepTime = 60 * 60 * 1000; private long delay = 0; private boolean detailRequired = false; private Thread me = null; private static final int MB = 1024*1024; private String[] scripts; private String frozenDump; public void startService() { try { log.info("Starting SystemMonitor"); me = new Thread(this,"SystemMonitor"); me.start(); } catch (Exception e) { log.warn("error starting service", e); } } public void stopService() { log.info("Stopping SystemMonitor"); if (me != null) me.interrupt(); } public synchronized void setSleepTime(long sleepTime) { this.sleepTime = sleepTime; setModified(true); if (me != null) me.interrupt(); } public synchronized long getSleepTime() { return sleepTime; } public synchronized void setDetailRequired(boolean detail) { this.detailRequired = detail; setModified(true); if (me != null) me.interrupt(); } public synchronized boolean getDetailRequired() { return detailRequired; } void dumpThreads(ThreadGroup g, PrintStream p, String indent) { Thread[] list = new Thread[g.activeCount() + 5]; int nthreads = g.enumerate(list); for (int i = 0; i < nthreads; i++) p.println(indent + list[i]); } public void showThreadGroup(ThreadGroup g, PrintStream p, String indent) { if (g.getParent() != null) showThreadGroup(g.getParent(), p, indent + " "); else dumpThreads(g, p, indent + " "); } public void run() { while (running()) { log.info(this); frozenDump = null; try { long expected = System.currentTimeMillis() + sleepTime; Thread.sleep(sleepTime); delay = System.currentTimeMillis() - expected; } catch (InterruptedException e) { } } } public void dump (PrintStream p, String indent) { if (frozenDump == null) frozenDump = generateFrozenDump(indent); p.print(frozenDump); } @Override public void setConfiguration(Configuration cfg) throws ConfigurationException { super.setConfiguration(cfg); scripts = cfg.getAll("script"); } private SecurityManager getSecurityManager() { return System.getSecurityManager(); } private boolean hasSecurityManager() { return getSecurityManager() != null; } private Runtime getRuntimeInstance() { return Runtime.getRuntime(); } private long getServerUptimeAsMillisecond() { return getServer().getUptime(); } private String getInstanceIdAsString() { return getServer().getInstanceId().toString(); } private String getRevision() { return Q2.getRevision(); } private String getLocalHost () { try { return InetAddress.getLocalHost().toString(); } catch (Exception e) { return e.getMessage(); } } private String generateFrozenDump(String indent) { RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream p = new PrintStream(baos); String newIndent = indent + " "; Runtime r = getRuntimeInstance(); p.printf ("%s OS: %s%n", indent, System.getProperty("os.name")); p.printf ("%s process name: %s%n", indent, runtimeMXBean.getName()); p.printf ("%s host: %s%n", indent, getLocalHost()); p.printf ("%s version: %s (%s)%n", indent, Q2.getVersion(), getRevision()); p.printf ("%s instance: %s%n", indent, getInstanceIdAsString()); p.printf ("%s uptime: %s%n", indent, ISOUtil.millisToString(getServerUptimeAsMillisecond())); p.printf ("%s processors: %d%n", indent, r.availableProcessors()); p.printf ("%s drift : %d%n", indent, delay); p.printf ("%smemory(t/u/f): %d/%d/%d%n", indent, r.totalMemory()/MB, (r.totalMemory() - r.freeMemory())/MB, r.freeMemory()/MB); p.printf("%s encoding: %s%n", indent, Charset.defaultCharset()); if (hasSecurityManager()) p.printf("%s sec-manager: %s%n", indent, getSecurityManager()); p.printf("%s thread count: %d%n", indent, mxBean.getThreadCount()); p.printf("%s peak threads: %d%n", indent, mxBean.getPeakThreadCount()); p.printf("%s user threads: %d%n", indent, Thread.activeCount()); showThreadGroup(Thread.currentThread().getThreadGroup(), p, newIndent); NameRegistrar.getInstance().dump(p, indent, detailRequired); for (String s : scripts) { p.printf("%s%s:%n", indent, s); exec(s, p, newIndent); } return baos.toString(); } private void exec (String script, PrintStream ps, String indent) { try { Process p = Runtime.getRuntime().exec(script); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()) ); String line; while ((line = in.readLine()) != null) { ps.printf("%s%s%n", indent, line); } } catch (Exception e) { e.printStackTrace(ps); } } }
package ru.shutoff.cgstarter; import android.app.ActivityManager; import android.app.UiModeManager; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.preference.PreferenceManager; import android.telephony.SmsMessage; import android.widget.Toast; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CarMonitor extends BroadcastReceiver { static private final String START = "ru.shutoff.cgstarter.START"; static private final String FIRE = "com.twofortyfouram.locale.intent.action.FIRE_SETTING"; private CountDownTimer power_timer; private CountDownTimer power_kill_timer; private CountDownTimer dock_kill_timer; SensorManager sensorManager; Sensor sensorAccelerometer; Sensor sensorMagnetic; SensorEventListener sensorEventListener; float[] gravity; float[] magnetic; float[] orientation; @Override public void onReceive(final Context context, Intent intent) { if (intent == null) return; String action = intent.getAction(); if (action == null) return; if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) && action.equals(UiModeManager.ACTION_ENTER_CAR_MODE)) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); if (preferences.getBoolean(State.CAR_MODE, false)) { setCarMode(context, true); abortBroadcast(); } } if (action.equals(Intent.ACTION_DOCK_EVENT)) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); if (preferences.getBoolean(State.CAR_MODE, false)) { int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, -1); setCarMode(context, (dockState == Intent.EXTRA_DOCK_STATE_CAR)); abortBroadcast(); } } if (action.equals("android.provider.Telephony.SMS_RECEIVED")) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); if (!preferences.getBoolean(State.SHOW_SMS, false)) return; Object[] pduArray = (Object[]) intent.getExtras().get("pdus"); SmsMessage[] messages = new SmsMessage[pduArray.length]; for (int i = 0; i < pduArray.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]); } final String sms_from = messages[0].getOriginatingAddress(); StringBuilder bodyText = new StringBuilder(); for (SmsMessage m : messages) { bodyText.append(m.getMessageBody()); } final String body = bodyText.toString(); Pattern pattern = Pattern.compile("([0-9]{1,2}\\.[0-9]{4,7})[^0-9]+([0-9]{1,2}\\.[0-9]{4,7})"); Matcher matcher = pattern.matcher(body); if (!matcher.find()) return; Intent i = new Intent(context, SmsDialog.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(State.LATITUDE, matcher.group(1)); i.putExtra(State.LONGITUDE, matcher.group(2)); i.putExtra(State.INFO, sms_from); i.putExtra(State.TEXT, body); context.startActivity(i); } if (action.equals(Intent.ACTION_POWER_CONNECTED)) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String interval = preferences.getString(State.POWER_TIME, ""); if (State.inInterval(interval)) { orientation = null; if (preferences.getBoolean(State.VERTICAL, true)) { if (sensorEventListener == null) { sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); if (sensorAccelerometer == null) sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); if (sensorMagnetic == null) sensorMagnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); if (sensorEventListener == null) { sensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) magnetic = event.values; if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) gravity = event.values; if ((gravity == null) || (magnetic == null)) return; float[] R = new float[9]; float[] I = new float[9]; if (!SensorManager.getRotationMatrix(R, I, gravity, magnetic)) return; if (orientation == null) orientation = new float[3]; SensorManager.getOrientation(R, orientation); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; sensorManager.registerListener(sensorEventListener, sensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, sensorMagnetic, SensorManager.SENSOR_DELAY_NORMAL); } } } power_timer = new CountDownTimer(2000, 2000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { power_timer = null; if (sensorEventListener != null) { sensorManager.unregisterListener(sensorEventListener); sensorEventListener = null; } if (orientation != null) { if ((Math.abs(orientation[1]) + Math.abs(orientation[2])) < 1) { orientation = null; return; } orientation = null; } if (!OnExitService.isRunCG(context)) { Intent run = new Intent(context, MainActivity.class); run.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(run); } power_timer = null; } }; power_timer.start(); } if (power_kill_timer != null) { power_kill_timer.cancel(); power_kill_timer = null; } } if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) { if (power_timer != null) { power_timer.cancel(); power_timer = null; } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); if (preferences.getBoolean(State.KILL_POWER, false)) { power_kill_timer = new CountDownTimer(2000, 2000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { power_kill_timer = null; OnExitService.force_exit = true; killCG(context); } }; power_kill_timer.start(); } } if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) { BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String devices = preferences.getString(State.BT_DEVICES, ""); if (devices.equals("")) return; SharedPreferences.Editor ed = preferences.edit(); ed.putString(State.BT_DEVICES, devices + ";" + device.getAddress()); ed.commit(); } if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) { BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); OnExitService.turnOffBT(context, device.getAddress()); } if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) { OnExitService.call_number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); Pattern pattern = Pattern.compile("([0-9]{1,2}\\.[0-9]{4,7})[^0-9]+([0-9]{1,2}\\.[0-9]{4,7})"); Matcher matcher = pattern.matcher(OnExitService.call_number); if (!matcher.find()) return; Intent i = new Intent(context, SmsDialog.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(State.LATITUDE, matcher.group(1)); i.putExtra(State.LONGITUDE, matcher.group(2)); i.putExtra(State.INFO, R.string.go); i.putExtra(State.TEXT, OnExitService.call_number); context.startActivity(i); abortBroadcast(); } if (action.equals(FIRE)) { Bundle data = intent.getBundleExtra(EditActivity.EXTRA_BUNDLE); try { String route = data.get(State.ROUTE).toString(); String points = data.get(State.POINTS).toString(); startCG(context, route, points); } catch (Exception ex) { // ignore } } if (action.equals(START)) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String route = intent.getStringExtra("ROUTE"); String route_points = intent.getStringExtra("POINTS"); if (route == null) route = ""; if (route_points == null) route_points = ""; int n_route = intent.getIntExtra("ROUTE", 0); if (n_route > 0) { State.Point[] points = State.get(preferences); if (n_route > points.length) return; State.Point p = points[n_route - 1]; if ((p.lat.equals("")) && (p.lng.equals(""))) return; route = p.lat + "|" + p.lng; route_points = p.points; } else if (n_route < 0) { MainActivity.removeRoute(context); route = ""; } startCG(context, route, route_points); } } static void startCG(Context context, String route, String route_points) { if (route.equals("-")) { MainActivity.removeRoute(context); } else if (!route.equals("")) { MainActivity.createRoute(context, route, route_points); } if (!MainActivity.setState(context, new State.OnBadGPS() { @Override public void gps_message(Context context) { Toast toast = Toast.makeText(context, context.getString(R.string.no_gps_title), Toast.LENGTH_SHORT); toast.show(); } })) { MainActivity.setState(context, null); } Intent run = context.getPackageManager().getLaunchIntentForPackage(State.CG_PACKAGE); if (run == null) { Toast toast = Toast.makeText(context, context.getString(R.string.no_cg), Toast.LENGTH_SHORT); toast.show(); return; } context.startActivity(run); Intent service = new Intent(context, OnExitService.class); service.setAction(OnExitService.START); context.startService(service); } void setCarMode(final Context context, boolean newMode) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); boolean curMode = preferences.getBoolean(State.CAR_STATE, false); if (curMode != newMode) { SharedPreferences.Editor ed = preferences.edit(); ed.putBoolean(State.CAR_STATE, newMode); ed.commit(); if (newMode) { if (!OnExitService.isRunCG(context)) { Intent run = new Intent(context, MainActivity.class); run.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(run); ed.commit(); } if (dock_kill_timer != null) { dock_kill_timer.cancel(); dock_kill_timer = null; } } else { if (preferences.getBoolean(State.KILL_CAR, false)) { dock_kill_timer = new CountDownTimer(2000, 2000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { dock_kill_timer = null; OnExitService.force_exit = true; killCG(context); } }; dock_kill_timer.start(); } } } } static void killCG(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses(); if (procInfos == null) return; int i; for (i = 0; i < procInfos.size(); i++) { ActivityManager.RunningAppProcessInfo proc = procInfos.get(i); if (proc.processName.equals(State.CG_PACKAGE)) { State.doRoot(context, "kill " + proc.pid); } } } }
package infinispan; import java.io.Console; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.AsyncContext; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p> * A simple asynchronous servlet taking advantage of features added in 3.0. * </p> * * <p> * The servlet is registered and mapped to /AsynchronousServlet using the {@link WebServlet} annotation. The * {@link LongRunningService} is injected by CDI. * </p> * * <p> * It shows how to detach the execution of a long-running task from the request processing thread, so the thread is free * to serve other client requests. The long-running tasks are executed using a dedicated thread pool and create the * client response asynchronously using the {@link AsyncContext}. * </p> * * <p> * A long-running task in this context does not refer to a computation intensive task executed on the same machine but * could for example be contacting a third-party service that has limited resources or only allows for a limited number * of concurrent connections. Moving the calls to this service into a separate and smaller sized thread pool ensures * that less threads will be busy interacting with the long-running service and that more requests can be served that do * not depend on this service. * </p> * * @author Christian Sadilek <csadilek@redhat.com> */ @SuppressWarnings("serial") @WebServlet(value = "/test" ) public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) { // Here the request is put in asynchronous mode response.setContentType("text/html"); // Actual logic goes here. PrintWriter out=null; try { out = response.getWriter(); FootballManager manager = new FootballManager(); manager.printTeams(out); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println("<h1>Called Servlet</h1>"); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jme3.gde.modelimporter; import com.jme3.asset.AssetKey; import com.jme3.gde.core.assets.AssetData; import com.jme3.gde.core.assets.ProjectAssetManager; import com.jme3.gde.core.scene.OffScenePanel; import com.jme3.math.Vector3f; import com.jme3.scene.Spatial; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import java.util.logging.Level; import javax.swing.JPanel; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.WizardDescriptor; import org.openide.filesystems.FileObject; import org.openide.util.Exceptions; @SuppressWarnings({"unchecked", "serial"}) public final class ModelImporterVisualPanel3 extends JPanel { private static final Logger logger = Logger.getLogger(ModelImporterVisualPanel3.class.getName()); private ModelImporterWizardPanel3 panel; private OffScenePanel offPanel; private ProjectAssetManager manager; private AssetData data; private AssetKey mainKey; private Spatial currentModel; private List<FileObject> assets; private List<AssetKey> assetKeys; private List<AssetKey> failedKeys; /** * Creates new form ModelImporterVisualPanel1 */ public ModelImporterVisualPanel3(ModelImporterWizardPanel3 panel) { initComponents(); this.panel = panel; offPanel = new OffScenePanel(320, 320); jPanel1.add(offPanel); } @Override public String getName() { return "Preview Model"; } public void loadSettings(WizardDescriptor wiz) { logger.log(Level.INFO, "Start offview panel"); offPanel.startPreview(); jList1.setListData(new Object[0]); jList2.setListData(new Object[0]); manager = (ProjectAssetManager) wiz.getProperty("manager"); mainKey = (AssetKey) wiz.getProperty("mainkey"); data = (AssetData) wiz.getProperty("assetdata"); loadModel(); if (currentModel != null) { logger.log(Level.INFO, "Attaching model {0}", currentModel); offPanel.attach(currentModel); } else { jList2.setListData(new Object[]{mainKey}); } } public void applySettings(WizardDescriptor wiz) { UberAssetLocator.setFindMode(false); wiz.putProperty("assetfiles", assets); wiz.putProperty("assetlist", assetKeys); wiz.putProperty("failedlist", failedKeys); wiz.putProperty("model", currentModel); if (currentModel != null) { logger.log(Level.INFO, "Detaching model {0}", currentModel); offPanel.detach(currentModel); } logger.log(Level.INFO, "Stop offview panel"); offPanel.stopPreview(); } public boolean checkValid() { return currentModel != null; } private void loadModel() { assets = null; assetKeys = null; failedKeys = null; manager.registerLocator(manager.getAssetFolderName(), UberAssetLocator.class); try { currentModel = (Spatial) data.loadAsset(); if (currentModel != null) { assetKeys = data.getAssetKeyList(); failedKeys = data.getFailedList(); assets = data.getAssetList(); //TODO:workaround for manually found assets not being added for some reason... //Should be reported in located assets callback of assetmanager.. for (Iterator<UberAssetLocator.UberAssetInfo> it = UberAssetLocator.getLocatedList().iterator(); it.hasNext();) { logger.log(Level.WARNING, "Applying workaround, adding manually located assets to asset success list!"); UberAssetLocator.UberAssetInfo uberAssetInfo = it.next(); if(!assetKeys.contains(uberAssetInfo.getKey())){ assetKeys.add(uberAssetInfo.getKey()); assets.add(uberAssetInfo.getFileObject()); } } jList1.setListData(assetKeys.toArray()); jList2.setListData(failedKeys.toArray()); if (failedKeys.size() > 0) { statusLabel.setText(org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.statusLabel.text_missing")); infoTextArea.setText(org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.infoTextArea.text_missing")); } else { statusLabel.setText(org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.statusLabel.text_good")); infoTextArea.setText(org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.infoTextArea.text_good")); } } else { statusLabel.setText(org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.statusLabel.text_failed")); infoTextArea.setText(org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.infoTextArea.text_failed")); } } catch (Exception e) { statusLabel.setText("Error importing file"); NotifyDescriptor.Message msg = new NotifyDescriptor.Message( "Error importing file!\n" + "(" + e + ")", NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notifyLater(msg); Exceptions.printStackTrace(e); } manager.unregisterLocator(manager.getAssetFolderName(), UberAssetLocator.class); panel.fireChangeEvent(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jToolBar1 = new javax.swing.JToolBar(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jSeparator1 = new javax.swing.JToolBar.Separator(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList(); jScrollPane3 = new javax.swing.JScrollPane(); jList2 = new javax.swing.JList(); statusLabel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); infoTextArea = new javax.swing.JTextArea(); jPanel1.setPreferredSize(new java.awt.Dimension(320, 320)); jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS)); jToolBar1.setFloatable(false); jToolBar1.setRollover(true); org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.jButton1.text")); // NOI18N jButton1.setFocusable(false); jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jToolBar1.add(jButton1); org.openide.awt.Mnemonics.setLocalizedText(jButton2, org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.jButton2.text")); // NOI18N jButton2.setFocusable(false); jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jToolBar1.add(jButton2); jToolBar1.add(jSeparator1); org.openide.awt.Mnemonics.setLocalizedText(jButton3, org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.jButton3.text")); // NOI18N jButton3.setFocusable(false); jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jToolBar1.add(jButton3); org.openide.awt.Mnemonics.setLocalizedText(jButton4, org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.jButton4.text")); // NOI18N jButton4.setFocusable(false); jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jToolBar1.add(jButton4); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 220, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); jToolBar1.add(jPanel3); org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.jLabel2.text")); // NOI18N jList1.setModel(new javax.swing.AbstractListModel() { String[] strings = { "No assets loaded" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane2.setViewportView(jList1); jScrollPane3.setViewportView(jList2); statusLabel.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(statusLabel, org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.statusLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.jLabel1.text_1")); // NOI18N infoTextArea.setColumns(20); infoTextArea.setEditable(false); infoTextArea.setLineWrap(true); infoTextArea.setRows(5); infoTextArea.setText(org.openide.util.NbBundle.getMessage(ModelImporterVisualPanel3.class, "ModelImporterVisualPanel3.infoTextArea.text_1")); // NOI18N infoTextArea.setWrapStyleWord(true); infoTextArea.setDisabledTextColor(new java.awt.Color(0, 0, 0)); jScrollPane1.setViewportView(infoTextArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3)) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed offPanel.zoomCamera(-.1f); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed offPanel.zoomCamera(.1f); }//GEN-LAST:event_jButton1ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed offPanel.rotateCamera(Vector3f.UNIT_Y, .1f); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed offPanel.rotateCamera(Vector3f.UNIT_Y, -.1f); }//GEN-LAST:event_jButton4ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea infoTextArea; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JList jList1; private javax.swing.JList jList2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JToolBar.Separator jSeparator1; private javax.swing.JToolBar jToolBar1; private javax.swing.JLabel statusLabel; // End of variables declaration//GEN-END:variables }
package seedu.doist.model.task; import seedu.doist.commons.exceptions.IllegalValueException; /** * Represents a task's priority in the to-do list * Guarantees: immutable; is valid as declared in {@link #isValidPriority(String)} * Default value is NORMAL if not set by user. */ public class Priority { public static final String EXAMPLE = "HIGH"; public static final String MESSAGE_PRIORITY_CONSTRAINTS = "Task priority should be 'NORMAL', " + "'IMPORTANT' or 'VERY IMPORTANT'"; public static final PriorityLevel DEFAULT_PRIORITY = PriorityLevel.NORMAL; public enum PriorityLevel { NORMAL("Normal"), IMPORTANT("Important"), VERY_IMPORTANT("Very Important"); private String strValue; PriorityLevel(String value) { this.strValue = value; } @Override public String toString() { return this.strValue; } } public final PriorityLevel priority; /** * If no parameters are given, it is set to default priority */ public Priority() { this.priority = DEFAULT_PRIORITY; } public Priority(String priority) throws IllegalValueException { final String processedPriority = processPriorityString(priority); if (!isValidPriority(processedPriority)) { throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS); } this.priority = PriorityLevel.valueOf(processedPriority); } public PriorityLevel getPriorityLevel() { return priority; } /** * Returns true if a given string is a valid priority */ public static boolean isValidPriority(String priority) { return priority.equals(PriorityLevel.VERY_IMPORTANT.name()) || priority.equals(PriorityLevel.IMPORTANT.name()) || priority.equals(PriorityLevel.NORMAL.name()); } /** * Process string to remove trailing whitespace, spaces and * change all characters to upper case so that it will be a * valid priority string * @returns string of the processed priority string */ public static String processPriorityString(String priority) { String processedPriority = priority.trim(); processedPriority = processedPriority.replaceAll(" ", "_"); processedPriority = processedPriority.toUpperCase(); return processedPriority; } @Override public String toString() { return priority.toString(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Priority // instanceof handles nulls && this.priority.equals((((Priority) other).priority))); // state check } @Override public int hashCode() { return priority.toString().hashCode(); } }
package jsystem.utils; import java.util.logging.Formatter; import java.util.logging.LogRecord; import java.util.Date; import java.text.MessageFormat; import java.io.StringWriter; import java.io.PrintWriter; /** * The BasicFormatter is used as the default formatar of messages to the java * logger. * * @author guy.arieli * */ public class BasicFormatter extends Formatter { Date dat = new Date(); private final static String format = "{0,date} {0,time}"; private MessageFormat formatter; private Object args[] = new Object[1]; private String lineSeparator = System.getProperty("user.dir"); private static long sessionStartTime = System.currentTimeMillis(); public String format(LogRecord record) { StringBuffer sb = new StringBuffer(); dat.setTime(record.getMillis()); args[0] = dat; StringBuffer text = new StringBuffer(); if (formatter == null) { formatter = new MessageFormat(format); } formatter.format(args, text, null); sb.append(text); sb.append(" ("); sb.append(System.currentTimeMillis() - sessionStartTime); sb.append(") "); if (record.getSourceClassName() != null) { sb.append(StringUtils.getClassName(record.getSourceClassName())); } else { sb.append(StringUtils.getClassName(record.getLoggerName())); } if (record.getSourceMethodName() != null) { sb.append(" "); sb.append(record.getSourceMethodName()); } // sb.append(lineSeparator); sb.append(" "); String message = formatMessage(record); sb.append(record.getLevel().getLocalizedName()); sb.append(": "); sb.append(message); sb.append(lineSeparator); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception ex) { } } return sb.toString(); } }
package sm.tools.veda_client; import java.util.Date; import java.util.HashMap; import java.util.Set; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class Individual { private static int _as_json = 1; private static int _as_struct = 2; private int type_of_data = _as_json; private JSONObject js_src; private HashMap<String, Resources> data = null; private String uri; public String toString () { return "@:" + uri + " " + data.toString(); } public String[] getPredicates() { if (type_of_data == _as_json) getResources("@"); return data.keySet().toArray(new String[0]); } public Resources addProperty(String field_name, Date _data) { Resources res; if (type_of_data == _as_json) getResources("@"); res = data.get(field_name); if (res == null) { res = new Resources(); data.put(field_name, res); } res.add(_data); return res; } public Resources addProperty(String field_name, String value, int type) { Resources res = null; if (type_of_data == _as_json) getResources("@"); res = data.get(field_name); if (res != null) for (Resource rc : res.resources) if (rc.data.equals(value) && rc.type == type) return res; if (res == null) { res = new Resources(); data.put(field_name, res); } res.add(new Resource(value, type)); return res; } public Resources addProperty(String field_name, String value, String lang) { Resources res; if (type_of_data == _as_json) getResources("@"); res = data.get(field_name); if (res != null) for (Resource rc : res.resources) if (rc.data.equals(value) && rc.type == Type._String) return res; if (res == null) { res = new Resources(); data.put(field_name, res); } res.add(new Resource(value, Type._String, lang)); return res; } public Resources addProperty(String field_name, Resources rsz) { Resources res; if (type_of_data == _as_json) getResources("@"); res = data.get(field_name); if (res == null) { res = new Resources(); data.put(field_name, res); } for (Resource rs : rsz.resources) { res.add(rs); } return res; } public Resources addProperty(String field_name, Resource rs) { Resources res; if (type_of_data == _as_json) getResources("@"); res = data.get(field_name); if (res == null) { res = new Resources(); data.put(field_name, res); } res.add(rs); return res; } public Resources setProperty(String field_name, Resource rs) { Resources res = new Resources(); if (type_of_data == _as_json) getResources("@"); res.add(rs); data.put(field_name, res); return res; } public Resources setProperty(String field_name, Resources rsz) { if (type_of_data == _as_json) getResources("@"); data.put(field_name, rsz); return rsz; } public void removeProperty(String field_name) { if (type_of_data == _as_json) getResources("@"); data.remove(field_name); return; } public Individual() { type_of_data = _as_struct; data = new HashMap<String, Resources>(); } public Individual(JSONObject src) { js_src = src; type_of_data = _as_json; } public String getUri() { if (type_of_data == _as_json) return getValue("@"); if (type_of_data == _as_struct) return uri; return null; } public void setUri(String uri) { this.uri = uri; } public Resources getResources(String field_name) { Resources res = null; if (type_of_data == _as_json) { type_of_data = _as_struct; res = new Resources(); data = new HashMap<String, Resources>(); Set<String> keys = js_src.keySet(); for (String key : keys) { if (key.equals("@")) uri = (String) js_src.get(key); else { Resource rs = null; JSONArray code_objz = (JSONArray) js_src.get(key); if (code_objz != null) { for (int idx = 0; idx < code_objz.size(); idx++) { // JSONObject vobj = (JSONObject)code_objz.get(idx); String value; int type = 0; JSONObject jsval = (JSONObject) (code_objz.get(idx)); value = jsval.get("data").toString(); String stype = jsval.get("type").toString(); Object olang = jsval.get("lang"); String lang = "NONE"; if (olang != null) lang = olang.toString(); if (stype.equals("Boolean")) type = Type._Bool; else if (stype.equals("String")) type = Type._String; else if (stype.equals("Uri")) type = Type._Uri; else if (stype.equals("Datetime")) type = Type._Datetime; else if (stype.equals("Integer")) type = Type._Integer; else if (stype.equals("Decimal")) type = Type._Decimal; else type = 0; rs = new Resource(value, type, lang); addProperty(key, rs); res.add(rs); } } } // if (oo instanceof String) } } res = data.get(field_name); return res; } public String getValue(String field_name) { String res = null; if (type_of_data == _as_json) { Object oo = js_src.get(field_name); if (oo instanceof String) return (String) js_src.get(field_name); JSONArray code_obj = (JSONArray) js_src.get(field_name); if (code_obj != null) { String code = (String) ((JSONObject) (code_obj.get(0))).get("data"); if (code != null) { return code; } } } if (type_of_data == _as_struct) { } return res; } public String toJsonStr() { if (type_of_data == _as_json) getResources("@"); StringBuffer sb = new StringBuffer(); for (String key : data.keySet()) { Resources rcs = data.get(key); util.serializeResources(sb, key, rcs); } return sb.toString(); } }
package tigase.net; import java.io.IOException; import java.net.*; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import tigase.util.DNSEntry; /** * Describe class ConnectionOpenThread here. * * * Created: Wed Jan 25 23:51:28 2006 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class ConnectionOpenThread implements Runnable { private static final Logger log = Logger.getLogger(ConnectionOpenThread.class.getName()); private static ConnectionOpenThread acceptThread = null; public static final long def_5222_throttling = 200; /** Field description */ public static final long def_5223_throttling = 50; /** Field description */ public static final long def_5280_throttling = 1000; /** Field description */ public static final long def_5269_throttling = 100; /** Field description */ public static Map<Integer, PortThrottlingData> throttling = new ConcurrentHashMap<Integer, PortThrottlingData>(10); protected long accept_counter = 0; private Selector selector = null; private boolean stopping = false; private Timer timer = null; private ConcurrentLinkedQueue<ConnectionOpenListener> waiting = new ConcurrentLinkedQueue<ConnectionOpenListener>(); /** * Creates a new <code>ConnectionOpenThread</code> instance. * */ private ConnectionOpenThread() { timer = new Timer("Connections open timer", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { for (PortThrottlingData portData : throttling.values()) { portData.lastSecondConnections = 0; } } }, 1000, 1000); try { selector = Selector.open(); } catch (Exception e) { log.log(Level.SEVERE, "Server I/O error, can't continue my work.", e); stopping = true; } // end of try-catch } /** * Method description * * * @return */ public static ConnectionOpenThread getInstance() { // Long new_throttling = Long.getLong("new-connections-throttling"); // if (new_throttling != null) { // throttling = new_throttling; // log.log(Level.WARNING, "New connections throttling set to: {0}", throttling); if (acceptThread == null) { acceptThread = new ConnectionOpenThread(); Thread thrd = new Thread(acceptThread); thrd.setName("ConnectionOpenThread"); thrd.start(); if (log.isLoggable(Level.FINER)) { log.finer("ConnectionOpenThread started."); } } // end of if (acceptThread == null) return acceptThread; } /** * Method description * * * @param al */ public void addConnectionOpenListener(ConnectionOpenListener al) { waiting.offer(al); selector.wakeup(); } /** * Method description * * * @param al */ public void removeConnectionOpenListener(ConnectionOpenListener al) { for (SelectionKey key : selector.keys()) { if (al == key.attachment()) { try { key.cancel(); SelectableChannel channel = key.channel(); channel.close(); } catch (Exception e) { log.log(Level.WARNING, "Exception during removing connection listener.", e); } break; } } } /** * Method description * */ @Override public void run() { while ( !stopping) { try { selector.select(); // Set<SelectionKey> selected_keys = selector.selectedKeys(); // for (SelectionKey sk : selected_keys) { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); SocketChannel sc = null; if ((sk.readyOps() & SelectionKey.OP_ACCEPT) != 0) { ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel(); sc = nextReady.accept(); if (log.isLoggable(Level.FINEST)) { log.finest("OP_ACCEPT"); } PortThrottlingData port_throttling = throttling.get(nextReady.socket().getLocalPort()); if (port_throttling != null) { ++port_throttling.lastSecondConnections; if (port_throttling.lastSecondConnections > port_throttling.throttling) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "New connections throttling level exceeded, closing: {0}", sc); } sc.close(); sc = null; } } else { // Hm, this should not happen actually log.log(Level.WARNING, "Throttling not configured for port: {0}", nextReady.socket().getLocalPort()); } } // end of if (sk.readyOps() & SelectionKey.OP_ACCEPT) if ((sk.readyOps() & SelectionKey.OP_CONNECT) != 0) { sk.cancel(); sc = (SocketChannel) sk.channel(); if (log.isLoggable(Level.FINEST)) { log.finest("OP_CONNECT"); } } // end of if (sk.readyOps() & SelectionKey.OP_ACCEPT) if (sc != null) { // We have to catch exception here as sometimes socket is closed // or connection is broken before we start configuring it here // then whatever we do on the socket it throws an exception try { sc.configureBlocking(false); sc.socket().setSoLinger(false, 0); sc.socket().setReuseAddress(true); if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Registered new client socket: {0}", sc); } ConnectionOpenListener al = (ConnectionOpenListener) sk.attachment(); sc.socket().setTrafficClass(al.getTrafficClass()); sc.socket().setReceiveBufferSize(al.getReceiveBufferSize()); al.accept(sc); } catch (java.net.SocketException e) { log.log(Level.INFO, "Socket closed instantly after it had been opened?", e); ConnectionOpenListener al = (ConnectionOpenListener) sk.attachment(); al.accept(sc); } } else { log.warning("Can't obtain socket channel from selection key."); } // end of if (sc != null) else ++accept_counter; } addAllWaiting(); } catch (IOException e) { log.log(Level.SEVERE, "Server I/O error.", e); // stopping = true; } // end of catch catch (Exception e) { log.log(Level.SEVERE, "Other service exception.", e); // stopping = true; } // end of catch } } /** * Method description * */ public void start() { Thread t = new Thread(this); t.setName("ConnectionOpenThread"); t.start(); } /** * Method description * */ public void stop() { stopping = true; selector.wakeup(); } private void addAllWaiting() throws IOException { ConnectionOpenListener al = null; while ((al = waiting.poll()) != null) { try { addPort(al); } catch (Exception e) { log.log(Level.WARNING, "Error: creating connection for: " + al, e); } // end of try-catch } // end of for () } private void addISA(InetSocketAddress isa, ConnectionOpenListener al) throws IOException { switch (al.getConnectionType()) { case accept : long port_throttling = getThrottlingForPort(isa.getPort()); throttling.put(isa.getPort(), new PortThrottlingData(port_throttling)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Setting up throttling for the port {0} to {1} connections per second.", new Object[] { isa.getPort(), port_throttling }); } if (log.isLoggable(Level.FINEST)) { log.finest("Setting up 'accept' channel..."); } ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().setReceiveBufferSize(al.getReceiveBufferSize()); ssc.configureBlocking(false); ssc.socket().bind(isa); ssc.register(selector, SelectionKey.OP_ACCEPT, al); break; case connect : if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Setting up ''connect'' channel for: {0}/{1}", new Object[] { isa.getAddress(), isa.getPort() }); } SocketChannel sc = SocketChannel.open(); sc.socket().setReceiveBufferSize(al.getReceiveBufferSize()); sc.socket().setTrafficClass(al.getTrafficClass()); sc.configureBlocking(false); sc.connect(isa); sc.register(selector, SelectionKey.OP_CONNECT, al); break; default : log.log(Level.WARNING, "Unknown connection type: {0}", al.getConnectionType()); break; } // end of switch (al.getConnectionType()) } private void addPort(ConnectionOpenListener al) throws IOException { if (al.getConnectionType() == ConnectionType.connect && al.getRemoteAddress() != null) { addISA(al.getRemoteAddress(), al); } else if ((al.getIfcs() == null) || (al.getIfcs().length == 0) || al.getIfcs()[0].equals("ifc") || al.getIfcs()[0].equals("*")) { addISA(new InetSocketAddress(al.getPort()), al); } else { for (String ifc : al.getIfcs()) { addISA(new InetSocketAddress(ifc, al.getPort()), al); } // end of for () } // end of if (ip == null || ip.equals("")) else } private long getThrottlingForPort(int port) { long result = def_5222_throttling; switch (port) { case 5223 : result = def_5223_throttling; break; case 5269 : result = def_5269_throttling; break; case 5280 : result = def_5280_throttling; break; } String throttling_prop = System.getProperty("new-connections-throttling"); if (throttling_prop != null) { String[] all_ports_thr = throttling_prop.split(","); for (String port_thr : all_ports_thr) { String[] port_thr_ar = port_thr.split(":"); if (port_thr_ar.length == 2) { try { int port_no = Integer.parseInt(port_thr_ar[0]); if (port_no == port) { return Long.parseLong(port_thr_ar[1]); } } catch (Exception e) { // bad configuration log.log(Level.WARNING, "Connections throttling configuration error, bad format, " + "check the documentation for a correct syntax, " + "port throttling config: {0}", port_thr); } } else { // bad configuration log.log(Level.WARNING, "Connections throttling configuration error, bad format, " + "check the documentation for a correct syntax, " + "port throttling config: {0}", port_thr); } } } return result; } private class PortThrottlingData { /** Field description */ protected long lastSecondConnections = 0; /** Field description */ protected long throttling; /** * Constructs ... * * * @param throttling_prop */ private PortThrottlingData(long throttling_prop) { throttling = throttling_prop; } } } // ConnectionOpenThread //~ Formatted in Sun Code Convention
package ui.components; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; /** * a central place to specify keyboard shortcuts * * Classes that currently have keyboard shortcut code: * ui.components.NavigableListView * ui.issuecolumn.ColumnControl * ui.issuepanel.IssuePanel * ui.MenuControl * * Utility Class: * util.KeyPress */ public class KeyboardShortcuts { // ui.issuepanel.IssuePanel public static final KeyCombination BOX_TO_LIST = new KeyCodeCombination(KeyCode.DOWN, KeyCombination.CONTROL_DOWN); public static final KeyCombination LIST_TO_BOX = new KeyCodeCombination(KeyCode.UP, KeyCombination.CONTROL_DOWN); public static final KeyCombination MAXIMIZE_WINDOW = new KeyCodeCombination(KeyCode.X, KeyCombination.CONTROL_DOWN); public static final KeyCombination MINIMIZE_WINDOW = new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN); public static final KeyCombination DEFAULT_SIZE_WINDOW = new KeyCodeCombination(KeyCode.D, KeyCombination.CONTROL_DOWN); public static final KeyCode MARK_AS_READ = KeyCode.E; public static final KeyCode MARK_AS_UNREAD = KeyCode.U; public static final KeyCode REFRESH = KeyCode.F5; public static final KeyCode SHOW_DOCS = KeyCode.F1; public static final KeyCode GOTO_MODIFIER = KeyCode.G; public static final KeyCode SHOW_LABELS = KeyCode.L; public static final KeyCode SHOW_ISSUES = KeyCode.I; public static final KeyCode SHOW_MILESTONES = KeyCode.M; public static final KeyCode SHOW_PULL_REQUESTS = KeyCode.P; public static final KeyCode SHOW_HELP = KeyCode.H; public static final KeyCode SHOW_KEYBOARD_SHORTCUTS = KeyCode.K; public static final KeyCode SHOW_CONTRIBUTORS = KeyCode.D; public static final KeyCode SCROLL_TO_TOP = KeyCode.U; public static final KeyCode SCROLL_TO_BOTTOM = KeyCode.N; public static final KeyCode SCROLL_UP = KeyCode.J; public static final KeyCode SCROLL_DOWN = KeyCode.K; // TODO decouple manage/show labels/milestones? public static final KeyCode NEW_COMMENT = KeyCode.C; public static final KeyCode MANAGE_LABELS = KeyCode.L; public static final KeyCode MANAGE_ASSIGNEES = KeyCode.A; public static final KeyCode MANAGE_MILESTONE = KeyCode.M; public static final KeyCode DOUBLE_PRESS = KeyCode.SPACE; //ui.issuecolumn.ColumnControl public static final KeyCode LEFT_PANEL = KeyCode.D; public static final KeyCode RIGHT_PANEL = KeyCode.F; // ui.components.NavigableListView && ui.issuepanel.IssuePanel public static final KeyCode UP_ISSUE = KeyCode.T; public static final KeyCode DOWN_ISSUE = KeyCode.V; // ui.MenuControl public static final KeyCombination NEW_ISSUE = new KeyCodeCombination(KeyCode.I, KeyCombination.CONTROL_DOWN); public static final KeyCombination NEW_LABEL = new KeyCodeCombination(KeyCode.L, KeyCombination.CONTROL_DOWN); public static final KeyCombination NEW_MILESTONE = new KeyCodeCombination(KeyCode.M, KeyCombination.CONTROL_DOWN); public static final KeyCombination CREATE_LEFT_PANEL = new KeyCodeCombination(KeyCode.P, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN); public static final KeyCombination CREATE_RIGHT_PANEL = new KeyCodeCombination(KeyCode.P, KeyCombination.CONTROL_DOWN); public static final KeyCombination CLOSE_PANEL = new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN); }
import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.List; import java.util.ArrayList; /** * This class defines a simple embedded SQL utility class that is designed to * work with PostgreSQL JDBC drivers. * */ public class Messenger { // reference to physical database connection. private Connection _connection = null; // handling the keyboard inputs through a BufferedReader // This variable can be global for convenience. static BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); /** * Creates a new instance of Messenger * * @param hostname the MySQL or PostgreSQL server hostname * @param database the name of the database * @param username the user name used to login to the database * @param password the user login password * @throws java.sql.SQLException when failed to make a connection. */ public Messenger (String dbname, String dbport, String user, String passwd) throws SQLException { System.out.print("Connecting to database..."); try{ // constructs the connection URL String url = "jdbc:postgresql://localhost:" + dbport + "/" + dbname; System.out.println ("Connection URL: " + url + "\n"); // obtain a physical connection this._connection = DriverManager.getConnection(url, user, passwd); System.out.println("Done"); }catch (Exception e){ System.err.println("Error - Unable to Connect to Database: " + e.getMessage() ); System.out.println("Make sure you started postgres on this machine"); System.exit(-1); }//end catch }//end Messenger /** * Method to execute an update SQL statement. Update SQL instructions * includes CREATE, INSERT, UPDATE, DELETE, and DROP. * * @param sql the input SQL string * @throws java.sql.SQLException when update failed */ public void executeUpdate (String sql) throws SQLException { // creates a statement object Statement stmt = this._connection.createStatement (); // issues the update instruction stmt.executeUpdate (sql); // close the instruction stmt.close (); }//end executeUpdate /** * Method to execute an input query SQL instruction (i.e. SELECT). This * method issues the query to the DBMS and outputs the results to * standard out. * * @param query the input query string * @return the number of rows returned * @throws java.sql.SQLException when failed to execute the query */ public int executeQueryAndPrintResult (String query) throws SQLException { // creates a statement object Statement stmt = this._connection.createStatement (); // issues the query instruction ResultSet rs = stmt.executeQuery (query); /* ** obtains the metadata object for the returned result set. The metadata ** contains row and column info. */ ResultSetMetaData rsmd = rs.getMetaData (); int numCol = rsmd.getColumnCount (); int rowCount = 0; // iterates through the result set and output them to standard out. boolean outputHeader = true; while (rs.next()){ if(outputHeader){ for(int i = 1; i <= numCol; i++){ System.out.print(rsmd.getColumnName(i) + "\t"); } System.out.println(); outputHeader = false; } for (int i=1; i<=numCol; ++i) System.out.print (rs.getString (i) + "\t"); System.out.println (); ++rowCount; }//end while stmt.close (); return rowCount; }//end executeQuery /** * Method to execute an input query SQL instruction (i.e. SELECT). This * method issues the query to the DBMS and returns the results as * a list of records. Each record in turn is a list of attribute values * * @param query the input query string * @return the query result as a list of records * @throws java.sql.SQLException when failed to execute the query */ public List<List<String>> executeQueryAndReturnResult (String query) throws SQLException { // creates a statement object Statement stmt = this._connection.createStatement (); // issues the query instruction ResultSet rs = stmt.executeQuery (query); /* ** obtains the metadata object for the returned result set. The metadata ** contains row and column info. */ ResultSetMetaData rsmd = rs.getMetaData (); int numCol = rsmd.getColumnCount (); int rowCount = 0; // iterates through the result set and saves the data returned by the query. boolean outputHeader = false; List<List<String>> result = new ArrayList<List<String>>(); while (rs.next()){ List<String> record = new ArrayList<String>(); for (int i=1; i<=numCol; ++i) record.add(rs.getString (i)); result.add(record); }//end while stmt.close (); return result; }//end executeQueryAndReturnResult /** * Method to execute an input query SQL instruction (i.e. SELECT). This * method issues the query to the DBMS and returns the number of results * * @param query the input query string * @return the number of rows returned * @throws java.sql.SQLException when failed to execute the query */ public int executeQuery (String query) throws SQLException { // creates a statement object Statement stmt = this._connection.createStatement (); // issues the query instruction ResultSet rs = stmt.executeQuery (query); int rowCount = 0; // iterates through the result set and count nuber of results. if(rs.next()){ rowCount++; }//end while stmt.close (); return rowCount; } /** * Method to fetch the last value from sequence. This * method issues the query to the DBMS and returns the current * value of sequence used for autogenerated keys * * @param sequence name of the DB sequence * @return current value of a sequence * @throws java.sql.SQLException when failed to execute the query */ public int getCurrSeqVal(String sequence) throws SQLException { Statement stmt = this._connection.createStatement (); ResultSet rs = stmt.executeQuery (String.format("Select currval('%s')", sequence)); if (rs.next()) return rs.getInt(1); return -1; } /** * Method to close the physical connection if it is open. */ public void cleanup(){ try{ if (this._connection != null){ this._connection.close (); }//end if }catch (SQLException e){ // ignored. }//end try }//end cleanup /** * The main execution method * * @param args the command line arguments this inclues the <mysql|pgsql> <login file> */ public static void main (String[] args) { if (args.length != 3) { System.err.println ( "Usage: " + "java [-classpath <classpath>] " + Messenger.class.getName () + " <dbname> <port> <user>"); return; }//end if Greeting(); Messenger esql = null; try{ // use postgres JDBC driver. Class.forName ("org.postgresql.Driver").newInstance (); // instantiate the Messenger object and creates a physical // connection. String dbname = args[0]; String dbport = args[1]; String user = args[2]; esql = new Messenger (dbname, dbport, user, ""); boolean keepon = true; while(keepon) { // These are sample SQL statements System.out.println("MAIN MENU"); System.out.println(" System.out.println("1. Create user"); System.out.println("2. Log in"); System.out.println("9. < EXIT"); String authorisedUser = null; switch (readChoice()){ case 1: CreateUser(esql); break; case 2: authorisedUser = LogIn(esql); break; case 9: keepon = false; break; default : System.out.println("Unrecognized choice!"); break; }//end switch if (authorisedUser != null) { boolean usermenu = true; while(usermenu) { System.out.println("MAIN MENU"); System.out.println(" System.out.println("1. Add to contact list"); System.out.println("2. Browse contact list"); System.out.println("3. Write a new message"); System.out.println("........................."); System.out.println("9. Log out"); switch (readChoice()){ case 1: AddToContact(esql); break; case 2: ListContacts(esql); break; case 3: NewMessage(esql); break; case 9: usermenu = false; break; default : System.out.println("Unrecognized choice!"); break; } } } }//end while }catch(Exception e) { System.err.println (e.getMessage ()); }finally{ // make sure to cleanup the created table and close the connection. try{ if(esql != null) { System.out.print("Disconnecting from database..."); esql.cleanup (); System.out.println("Done\n\nBye !"); }//end if }catch (Exception e) { // ignored. }//end try }//end try }//end main public static void Greeting(){ System.out.println( "\n\n*******************************************************\n" + " User Interface \n" + "*******************************************************\n"); }//end Greeting /* * Reads the users choice given from the keyboard * @int **/ public static int readChoice() { int input; // returns only if a correct value is given. do { System.out.print("Please make your choice: "); try { // read the integer, parse it and break. input = Integer.parseInt(in.readLine()); break; }catch (Exception e) { System.out.println("Your input is invalid!"); continue; }//end try }while (true); return input; }//end readChoice /* * Creates a new user with privided login, passowrd and phoneNum * An empty block and contact list would be generated and associated with a user **/ public static void CreateUser(Messenger esql){ try{ System.out.print("\tEnter user login: "); String login = in.readLine(); System.out.print("\tEnter user password: "); String password = in.readLine(); System.out.print("\tEnter user phone: "); String phone = in.readLine(); //Creating empty contact\block lists for a user esql.executeUpdate("INSERT INTO USER_LIST(list_type) VALUES ('block')"); int block_id = esql.getCurrSeqVal("user_list_list_id_seq"); esql.executeUpdate("INSERT INTO USER_LIST(list_type) VALUES ('contact')"); int contact_id = esql.getCurrSeqVal("user_list_list_id_seq"); String query = String.format("INSERT INTO USR (phoneNum, login, password, block_list, contact_list) VALUES ('%s','%s','%s',%s,%s)", phone, login, password, block_id, contact_id); esql.executeUpdate(query); System.out.println ("User successfully created!"); }catch(Exception e){ System.err.println (e.getMessage ()); } }//end /* * Check log in credentials for an existing user * @return User login or null is the user does not exist **/ public static String LogIn(Messenger esql){ try{ System.out.print("\tEnter user login: "); String login = in.readLine(); System.out.print("\tEnter user password: "); String password = in.readLine(); String query = String.format("SELECT * FROM Usr WHERE login = '%s' AND password = '%s'", login, password); int userNum = esql.executeQuery(query); if (userNum > 0) return login; return null; }catch(Exception e){ System.err.println (e.getMessage ()); return null; } }//end public static void AddToContact(Messenger esql){ try{ esql.executeUpdate(query); }catch(Exception e){ System.err.println (e.getMessage ()); } }//end public static void ListContacts(Messenger esql){ // Your code goes here. }//end public static void NewMessage(Messenger esql){ // Your code goes here. }//end public static void Query6(Messenger esql){ // Your code goes here. }//end Query6 }//end Messenger
package simcity.BRestaurant.gui; import simcity.PersonAgent; import simcity.interfaces.*; import simcity.BRestaurant.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.ArrayList; public class BAnimationPanel extends JPanel implements ActionListener { private final int WINDOWX = 575; private final int WINDOWY = 325; private final int x=50; private final int y=150; private final int height=50; private final int width=50; private Image bufferImage; private Dimension bufferSize; private BRestaurantGui gui; private List<BGui> guis = new ArrayList<BGui>(); public BAnimationPanel() { this.gui=gui; setSize(WINDOWX, WINDOWY); setVisible(true); bufferSize = this.getSize(); Timer timer = new Timer(5, this ); timer.start(); } public void actionPerformed(ActionEvent e) { repaint(); //Will have paintComponent called } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; //Clear the screen by painting a rectangle the size of the frame g2.setColor(getBackground()); g2.fillRect(0, 0, WINDOWX, WINDOWY ); //Here is the table g2.setColor(Color.ORANGE); g2.fillRect(x, y, height, width);//200 and 250 need to be table params g2.setColor(Color.ORANGE); g2.fillRect(200, 150, height, width); g2.setColor(Color.ORANGE); g2.fillRect(350, 150, height, width); g2.setColor(Color.BLUE); g2.fillRect(50, 300, 100, 30); g2.setColor(Color.RED); g2.fillRect(300, 300, 30, 30); g2.setColor(Color.RED); g2.fillRect(265, 300, 30, 30); g2.setColor(Color.RED); g2.fillRect(335, 300, 30, 30); for(BGui gui : guis) { if (gui.isPresent()) { gui.updatePosition(); } } for(BGui gui : guis) { if (gui.isPresent()) { gui.draw(g2); } } } public void addGui(BCustomerGui gui) { guis.add(gui); } public void addGui(BHostGui gui) { guis.add(gui); } }
// @formatter:off package javafx.collections; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.function.Predicate; import javafx.beans.Observable; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; /** * A list that allows listeners to track changes when they occur. * * @see ListChangeListener * @see ListChangeListener.Change * @param <E> the list element type * @since JavaFX 2.0 */ @SuppressWarnings("all") public interface ObservableList<E> extends List<E>, Observable, ObservableListExt<E> { /** * Add a listener to this observable list. * @param listener the listener for listening to the list changes */ public void addListener(ListChangeListener<? super E> listener); /** * Tries to removed a listener from this observable list. If the listener is not * attached to this list, nothing happens. * @param listener a listener to remove */ public void removeListener(ListChangeListener<? super E> listener); /** * A convenient method for var-arg adding of elements. * @param elements the elements to add * @return true (as specified by Collection.add(E)) */ @SuppressWarnings("unchecked") public boolean addAll(E... elements); /** * Clears the ObservableList and add all the elements passed as var-args. * @param elements the elements to set * @return true (as specified by Collection.add(E)) * @throws NullPointerException if the specified arguments contain one or more null elements */ @SuppressWarnings("unchecked") public boolean setAll(E... elements); /** * Clears the ObservableList and add all elements from the collection. * @param col the collection with elements that will be added to this observableArrayList * @return true (as specified by Collection.add(E)) * @throws NullPointerException if the specified collection contains one or more null elements */ public boolean setAll(Collection<? extends E> col); /** * A convenient method for var-arg usage of removaAll method. * @param elements the elements to be removed * @return true if list changed as a result of this call */ @SuppressWarnings("unchecked") public boolean removeAll(E... elements); /** * A convenient method for var-arg usage of retain method. * @param elements the elements to be retained * @return true if list changed as a result of this call */ @SuppressWarnings("unchecked") public boolean retainAll(E... elements); public void remove(int from, int to); /** * Creates a {@link FilteredList} wrapper of this list using * the specified predicate. * @param predicate the predicate to use * @return new {@code FilteredList} * @since JavaFX 8.0 */ public default FilteredList<E> filtered(Predicate<E> predicate) { return new FilteredList<>(this, predicate); } /** * Creates a {@link SortedList} wrapper of this list using * the specified comparator. * @param comparator the comparator to use or null for the natural order * @return new {@code SortedList} * @since JavaFX 8.0 */ public default SortedList<E> sorted(Comparator<E> comparator) { return new SortedList<>(this, comparator); } /** * Creates a {@link SortedList} wrapper of this list with the natural * ordering. * @return new {@code SortedList} * @since JavaFX 8.0 */ public default SortedList<E> sorted() { return sorted(null); } }
package org.haxe.lime; import android.app.Activity; import android.content.Context; import android.graphics.PixelFormat; import android.opengl.GLSurfaceView; import android.os.Build; import android.os.SystemClock; import android.text.InputType; import android.util.AttributeSet; import android.util.Log; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; ::if (ANDROID_TARGET_SDK_VERSION > 11)::import android.view.InputDevice;::end:: import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.MotionEvent; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.opengles.GL10; import java.util.Timer; import java.util.TimerTask; class MainView extends GLSurfaceView { static final int etTouchBegin = 15; static final int etTouchMove = 16; static final int etTouchEnd = 17; static final int etTouchTap = 18; static final int resTerminate = -1; boolean isPollImminent; Activity mActivity; static MainView mRefreshView; Timer mTimer = new Timer (); int mTimerID = 0; TimerTask pendingTimer; Runnable pollMe; boolean renderPending = false; public MainView (Context context, Activity inActivity) { super (context); isPollImminent = false; final MainView me = this; pollMe = new Runnable () { @Override public void run () { me.onPoll (); } }; int eglVersion = 1; if (::WIN_ALLOW_SHADERS:: || ::WIN_REQUIRE_SHADERS::) { EGL10 egl = (EGL10)EGLContext.getEGL (); EGLDisplay display = egl.eglGetDisplay (EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize (display, version); EGLConfig[] v2_configs = new EGLConfig[1]; int[] num_config = new int[1]; int[] attrs = { EGL10.EGL_RENDERABLE_TYPE, ::if DEFINE_LIME_FORCE_GLES1::1::else::4::end:: /*EGL_OPENGL_ES2_BIT*/, EGL10.EGL_NONE }; egl.eglChooseConfig (display, attrs, v2_configs, 1, num_config); if (num_config[0]==1) { eglVersion = ::if DEFINE_LIME_FORCE_GLES1::1::else::2::end::; setEGLContextClientVersion (::if DEFINE_LIME_FORCE_GLES1::1::else::2::end::); } } final int renderType = (eglVersion == 1 ? 0x01 : 0x04); setEGLConfigChooser (new EGLConfigChooser () { public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) { int depth = ::if WIN_DEPTH_BUFFER::16::else::0::end::; int stencil = ::if WIN_STENCIL_BUFFER::8::else::0::end::; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; if (::WIN_ANTIALIASING:: > 1) { int[] attrs = { EGL10.EGL_DEPTH_SIZE, depth, EGL10.EGL_STENCIL_SIZE, stencil, EGL10.EGL_SAMPLE_BUFFERS, 1 /* true */, EGL10.EGL_SAMPLES, ::WIN_ANTIALIASING::, EGL10.EGL_RENDERABLE_TYPE, renderType, EGL10.EGL_NONE }; egl.eglChooseConfig (display, attrs, configs, 1, num_config); if (num_config[0] == 1) { return configs[0]; } if (::WIN_ANTIALIASING:: > 2) { int[] attrs_aa2 = { EGL10.EGL_DEPTH_SIZE, depth, EGL10.EGL_STENCIL_SIZE, stencil, EGL10.EGL_SAMPLE_BUFFERS, 1 /* true */, EGL10.EGL_SAMPLES, 2, EGL10.EGL_RENDERABLE_TYPE, renderType, EGL10.EGL_NONE }; egl.eglChooseConfig (display, attrs_aa2, configs, 1, num_config); if (num_config[0] == 1) { return configs[0]; } } final int EGL_COVERAGE_BUFFERS_NV = 0x30E0; final int EGL_COVERAGE_SAMPLES_NV = 0x30E1; int[] attrs_aanv = { EGL10.EGL_DEPTH_SIZE, depth, EGL10.EGL_STENCIL_SIZE, stencil, EGL_COVERAGE_BUFFERS_NV, 1 /* true */, EGL_COVERAGE_SAMPLES_NV, 2, // always 5 in practice on tegra 2 EGL10.EGL_RENDERABLE_TYPE, renderType, EGL10.EGL_NONE }; egl.eglChooseConfig (display, attrs_aanv, configs, 1, num_config); if (num_config[0] == 1) { return configs[0]; } } int[] attrs1 = { EGL10.EGL_DEPTH_SIZE, depth, EGL10.EGL_STENCIL_SIZE, stencil, EGL10.EGL_RENDERABLE_TYPE, renderType, EGL10.EGL_NONE }; egl.eglChooseConfig (display, attrs1, configs, 1, num_config); if (num_config[0] == 1) { return configs[0]; } int[] attrs2 = { EGL10.EGL_NONE }; egl.eglChooseConfig (display, attrs2, configs, 1, num_config); if (num_config[0] == 1) { return configs[0]; } return null; } }); mActivity = inActivity; mRefreshView = this; setFocusable (true); setFocusableInTouchMode (true); setRenderer (new Renderer (this)); setRenderMode (GLSurfaceView.RENDERMODE_WHEN_DIRTY); } // Haxe Thread public void HandleResult (int inCode) { if (inCode == resTerminate) { mActivity.finish (); return; } double wake = Lime.getNextWake (); int delayMS = (int)(wake * 1000); if (renderPending && delayMS < 5) { delayMS = 5; } if (delayMS <= 1) { queuePoll (); } else { if (pendingTimer != null) { pendingTimer.cancel (); } final MainView me = this; pendingTimer = new TimerTask () { @Override public void run () { me.queuePoll (); } }; mTimer.schedule (pendingTimer, delayMS); } } @Override public InputConnection onCreateInputConnection (EditorInfo outAttrs) { BaseInputConnection inputConnection = new BaseInputConnection (this, false) { @Override public boolean deleteSurroundingText (int beforeLength, int afterLength) { ::if (ANDROID_TARGET_SDK_VERSION > 15):: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (beforeLength == 1 && afterLength == 0) { final long time = SystemClock.uptimeMillis (); super.sendKeyEvent (new KeyEvent (time, time, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); super.sendKeyEvent (new KeyEvent (SystemClock.uptimeMillis(), time, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); return true; } } ::end:: return super.deleteSurroundingText (beforeLength, afterLength); } }; return inputConnection; } ::if (ANDROID_TARGET_SDK_VERSION > 11)::@Override public boolean onGenericMotionEvent (MotionEvent event) { if ((event.getSource () & InputDevice.SOURCE_CLASS_JOYSTICK) != 0 && event.getAction () == MotionEvent.ACTION_MOVE) { final MainView me = this; final InputDevice device = event.getDevice (); final int deviceId = event.getDeviceId (); int[] axisList = { android.view.MotionEvent.AXIS_X, android.view.MotionEvent.AXIS_Y, android.view.MotionEvent.AXIS_Z, android.view.MotionEvent.AXIS_RX, android.view.MotionEvent.AXIS_RY, android.view.MotionEvent.AXIS_RZ, android.view.MotionEvent.AXIS_HAT_X, android.view.MotionEvent.AXIS_HAT_Y, android.view.MotionEvent.AXIS_LTRIGGER, android.view.MotionEvent.AXIS_RTRIGGER }; for (int i = 0; i < axisList.length; i++) { final int axis = axisList[i]; final InputDevice.MotionRange range = device.getMotionRange (axis, event.getSource ()); if (range != null) { final float value = event.getAxisValue (axis); queueEvent (new Runnable () { public void run () { me.HandleResult (Lime.onJoyMotion (deviceId, axis, ((value - range.getMin ()) / (range.getRange ())) * 65535 - 32768)); } }); } } return true; } return super.onGenericMotionEvent (event); }::end:: @Override public boolean onKeyDown (final int inKeyCode, KeyEvent event) { final MainView me = this; ::if (ANDROID_TARGET_SDK_VERSION > 11)::if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && (event.isGamepadButton (inKeyCode) || (inKeyCode >= 19 && inKeyCode <= 22))) { if (event.getRepeatCount () == 0) { final int deviceId = event.getDeviceId (); queueEvent (new Runnable () { public void run () { me.HandleResult (Lime.onJoyChange (deviceId, inKeyCode, true)); } }); } return true; }::end:: final int keyCode = translateKeyCode (inKeyCode, event); final int charCode = translateCharCode (inKeyCode, event); if (keyCode != 0) { queueEvent (new Runnable () { public void run () { me.HandleResult (Lime.onKeyChange (keyCode, charCode, true)); } }); return true; } return super.onKeyDown (inKeyCode, event); } @Override public boolean onKeyUp (final int inKeyCode, KeyEvent event) { final MainView me = this; ::if (ANDROID_TARGET_SDK_VERSION > 11)::if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && (event.isGamepadButton (inKeyCode) || (inKeyCode >= 19 && inKeyCode <= 22))) { if (event.getRepeatCount () == 0) { final int deviceId = event.getDeviceId (); queueEvent (new Runnable () { public void run () { me.HandleResult (Lime.onJoyChange (deviceId, inKeyCode, false)); } }); } return true; }::end:: final int keyCode = translateKeyCode (inKeyCode, event); final int charCode = translateCharCode (inKeyCode, event); if (keyCode != 0) { queueEvent (new Runnable () { public void run () { me.HandleResult (Lime.onKeyChange (keyCode, charCode, false)); } }); return true; } return super.onKeyUp (inKeyCode, event); } // Haxe Thread void onPoll () { isPollImminent = false; HandleResult (Lime.onPoll ()); } @Override public boolean onTouchEvent (final MotionEvent ev) { final MainView me = this; final int action = ev.getAction (); int type = -1; switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: type = etTouchBegin; break; case MotionEvent.ACTION_POINTER_DOWN: type = etTouchBegin; break; case MotionEvent.ACTION_MOVE: type = etTouchMove; break; case MotionEvent.ACTION_UP: type = etTouchEnd; break; case MotionEvent.ACTION_POINTER_UP: type = etTouchEnd; break; case MotionEvent.ACTION_CANCEL: type = etTouchEnd; break; } int idx = (action & MotionEvent.ACTION_POINTER_ID_MASK) >> (MotionEvent.ACTION_POINTER_ID_SHIFT); final int t = type; for (int i = 0; i < ev.getPointerCount (); i++) { final int id = ev.getPointerId (i); final float x = ev.getX (i); final float y = ev.getY (i); final float sizeX = ev.getSize (i); final float sizeY = ev.getSize (i); if (type == etTouchMove || i == idx) { queueEvent (new Runnable () { public void run () { me.HandleResult (Lime.onTouch (t, x, y, id, sizeX, sizeY)); } }); } } return true; } @Override public boolean onTrackballEvent (final MotionEvent ev) { final MainView me = this; queueEvent (new Runnable () { public void run() { float x = ev.getX (); float y = ev.getY (); me.HandleResult (Lime.onTrackball (x, y)); } }); return false; } // GUI/Timer Thread void queuePoll () { if (!isPollImminent) { isPollImminent = true; queueEvent (pollMe); } } static public void renderNow () { //Called directly from C++ mRefreshView.renderPending = true; mRefreshView.requestRender (); } void sendActivity (final int inActivity) { queueEvent (new Runnable () { public void run () { Lime.onActivity (inActivity); } }); } public int translateCharCode (int inCode, KeyEvent event) { int result = event.getUnicodeChar (event.getMetaState ()); if (result == KeyCharacterMap.COMBINING_ACCENT) { //TODO return 0; } switch (inCode) { case 66: case 160: return 13; // enter case 111: return 27; // escape case 67: return 8; // backspace case 61: return 9; // tab case 62: return 32; // space case 112: return 127; // delete } return result; } public int translateKeyCode (int inCode, KeyEvent event) { switch (inCode) { case KeyEvent.KEYCODE_BACK: return 27; /* Fake Escape */ case KeyEvent.KEYCODE_MENU: return 0x01000012; /* Fake MENU */ case KeyEvent.KEYCODE_DEL: return 8; // These will be ignored by the app and passed to the default handler case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: ::if (ANDROID_TARGET_SDK_VERSION > 10)::case KeyEvent.KEYCODE_VOLUME_MUTE:::end:: return 0; } if (inCode >= 7 && inCode <= 16) { return inCode + 41; } else if (inCode >= 29 && inCode <= 54) { return inCode + 36; } else if (inCode >= 131 && inCode <= 142) { return inCode - 19; // F1-F12 } else if (inCode >= 144 && inCode <= 153) { return inCode - 96; } switch (inCode) { case 66: case 160: return 13; // enter case 111: return 27; // escape case 67: return 8; // backspace case 61: return 9; // tab case 62: return 32; // space case 69: case 156: return 189; case 70: case 161: return 187; case 71: return 219; case 72: return 221; case 73: return 220; case 74: return 186; case 75: return 222; case 68: return 192; case 55: case 159: return 188; case 56: case 158: return 190; case 76: return 191; case 115: return 20; // caps lock case 116: return 145; // scroll lock case 121: return 19; // pause/break case 124: return 45; // insert case 122: return 36; // home case 92: return 34; // page down case 93: return 33; // page up case 112: return 46; // delete case 123: return 35; // end case 22: return 39; // right arrow case 21: return 37; // left arrow case 20: return 40; // down arrow case 19: return 38; // up arrow case 143: return 144; // num lock case 113: case 114: return 17; // ctrl case 59: case 60: return 16; // shift case 57: case 58: return 18; // alt } return inCode; } private static class Renderer implements GLSurfaceView.Renderer { MainView mMainView; public Renderer (MainView inView) { mMainView = inView; } public void onDrawFrame (GL10 gl) { mMainView.renderPending = false; mMainView.HandleResult (Lime.onRender ()); Sound.checkSoundCompletion (); } public void onSurfaceChanged (GL10 gl, int width, int height) { mMainView.HandleResult (Lime.onResize (width, height)); } public void onSurfaceCreated (GL10 gl, EGLConfig config) { } } }
package smartsockets.direct; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.Map; import org.apache.log4j.Logger; import smartsockets.Properties; import smartsockets.util.NetworkUtils; import smartsockets.util.STUN; import smartsockets.util.TypedProperties; import smartsockets.util.UPNP; /** * This class implements a socket factory with support for multi-homes machines, * port ranges, external address discovery, UPNP port forwarding, NIO-style * socket creation, clustering and connection address order preference. * * This socket factory always tries to set up a direct connection between * machines. As a result, there are many scenarios possible in which it will not * be able to connect. It is a good basis for other, 'smarter' socket factories * however. * * @author Jason Maassen * @version 1.0 Jan 10, 2006 * @since 1.0 */ public class DirectSocketFactory { protected static Logger logger = ibis.util.GetLogger .getLogger("smartsockets.direct"); private static DirectSocketFactory defaultFactory; private final int DEFAULT_TIMEOUT; private final TypedProperties properties; private final boolean USE_NIO; private final boolean ALLOW_UPNP; private final boolean ALLOW_UPNP_PORT_FORWARDING; private final int inputBufferSize; private final int outputBufferSize; private IPAddressSet completeAddress; private IPAddressSet localAddress; private InetAddress externalNATAddress; private boolean haveOnlyLocalAddresses = false; private String myNATAddress; private PortRange portRange; private NetworkPreference preference; private DirectSocketFactory(TypedProperties p) { properties = p; DEFAULT_TIMEOUT = p.getIntProperty(Properties.TIMEOUT, 5000); ALLOW_UPNP = p.booleanProperty(Properties.UPNP, false); if (!ALLOW_UPNP) { ALLOW_UPNP_PORT_FORWARDING = false; } else { ALLOW_UPNP_PORT_FORWARDING = p.booleanProperty(Properties.UPNP_PORT_FORWARDING, false); } USE_NIO = p.booleanProperty(Properties.NIO, false); inputBufferSize = p.getIntProperty(Properties.IN_BUF_SIZE, 0); outputBufferSize = p.getIntProperty(Properties.OUT_BUF_SIZE, 0); localAddress = IPAddressSet.getLocalHost(); if (!localAddress.containsGlobalAddress()) { haveOnlyLocalAddresses = true; getExternalAddress(p); if (externalNATAddress != null) { completeAddress = IPAddressSet.merge(localAddress, externalNATAddress); } else { completeAddress = localAddress; } } else { completeAddress = localAddress; } portRange = new PortRange(p); preference = NetworkPreference.getPreference(completeAddress, p); preference.sort(completeAddress.getAddresses(), true); if (logger.isDebugEnabled()) { logger.info("Local address: " + completeAddress); } } private void applyMask(byte[] mask, byte[] address) { for (int i = 0; i < address.length; i++) { address[i] &= mask[i]; } } /** * This method tries to find which of the local addresses is part of the NAT * network. Useful when multiple local networks exist. */ private void getNATAddress() { if (ALLOW_UPNP) { if (logger.isDebugEnabled()) { logger.debug("Using UPNP to find my NAT'ed network"); } // First get the netmask and an address in the range returned by // the NAT box. byte[] mask = UPNP.getSubnetMask(); InetAddress[] range = UPNP.getAddressRange(); if (mask == null || range == null) { return; } // Get a local address from the NAT box (not necc. our own). byte[] nw = range[0].getAddress(); if (mask.length != nw.length) { return; } // Determine the network address. applyMask(mask, nw); // Now compare all local addresses to the network address. InetAddress[] ads = localAddress.getAddresses(); for (int i = 0; i < ads.length; i++) { byte[] tmp = ads[i].getAddress(); if (tmp.length == mask.length) { applyMask(mask, tmp); if (Arrays.equals(nw, tmp)) { // Found and address that matches, so remember it... myNATAddress = NetworkUtils.ipToString(ads[i]); break; } } } if (logger.isDebugEnabled()) { logger.debug("UPNP result: " + myNATAddress); } } } /** * This method tries to find a global address that is valid for this * machine. When an address is found, it it stored in the externalAddress * field. */ private void getExternalAddress(TypedProperties p) { // Check if externalAddress is already known if (externalNATAddress != null) { return; } if (logger.isDebugEnabled()) { logger.debug("Checking properties for external address..."); } externalNATAddress = getExternalAddressProperty(p); if (logger.isDebugEnabled()) { logger.debug("Properties lookup result: " + externalNATAddress); } if (externalNATAddress != null) { return; } if (p.booleanProperty(Properties.STUN, false)) { if (logger.isDebugEnabled()) { logger.debug("Using STUN to find external address..."); } String [] servers = p.getStringList(Properties.STUN_SERVERS, ",", null); externalNATAddress = STUN.getExternalAddress(servers); if (logger.isDebugEnabled()) { logger.debug("STUN lookup result: " + externalNATAddress); } } if (ALLOW_UPNP) { // Try to obtain the global IP address by using UPNP. if (logger.isDebugEnabled()) { logger.debug("Using UPNP to find external address..."); } externalNATAddress = UPNP.getExternalAddress(); if (logger.isDebugEnabled()) { logger.debug("UPNP lookup result: " + externalNATAddress); } } } /** * This method retrieves the 'ibis.connect.external_address' property, which * contains a String representation of an InetAddress. If the property is * not set or the value could not be parsed, null is returned. * * @return an InetAddress or null */ private InetAddress getExternalAddressProperty(TypedProperties p) { InetAddress result = null; String tmp = p.getProperty(Properties.EXTERNAL_MANUAL); if (tmp != null) { try { result = InetAddress.getByName(tmp); } catch (UnknownHostException e) { logger.warn("Failed to parse property \"" + Properties.EXTERNAL_MANUAL + "\""); } } return result; } private Socket createUnboundSocket() throws IOException { Socket s = null; if (USE_NIO) { SocketChannel channel = SocketChannel.open(); s = channel.socket(); } else { s = new Socket(); } s.setReuseAddress(true); return s; } private ServerSocket createUnboundServerSocket() throws IOException { if (USE_NIO) { ServerSocketChannel channel = ServerSocketChannel.open(); return channel.socket(); } else { return new ServerSocket(); } } private DirectSocket attemptConnection(SocketAddressSet sas, InetSocketAddress target, int timeout, int localPort, boolean mayBlock) { // We never want to block, so ensure that timeout > 0 if (timeout == 0 && !mayBlock) { timeout = DEFAULT_TIMEOUT; } Socket s = null; try { if (logger.isInfoEnabled()) { logger.info("Attempting connection to " + sas.toString() + " using network " + NetworkUtils.ipToString(target.getAddress()) + ":" + target.getPort()); } s = createUnboundSocket(); if (logger.isInfoEnabled()) { logger.info("Unbound socket created"); } if (localPort > 0) { s.bind(new InetSocketAddress(localPort)); } s.connect(target, timeout); s.setSoTimeout(10000); // Check if we are talking to the right machine... OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); DataOutputStream dout = new DataOutputStream(out); dout.writeUTF(sas.toString()); dout.flush(); int result = in.read(); if (result == DirectServerSocket.ACCEPT) { if (logger.isInfoEnabled()) { logger.info("Succesfully connected to " + sas.toString() + " using network " + NetworkUtils.ipToString(target.getAddress()) + ":" + target.getPort()); } s.setSoTimeout(0); DirectSocket r = new DirectSocket(s, in, dout); tuneSocket(r); return r; } else { logger.warn("Got connecting to wrong machine: " + sas.toString() + " using network " + NetworkUtils.ipToString(target.getAddress()) + ":" + target.getPort() + " will retry!"); try { in.close(); } catch (Exception e2) { // ignore } try { out.close(); } catch (Exception e2) { // ignore } try { s.close(); } catch (Exception e2) { // ignore } return null; } } catch (Throwable e) { // if (logger.isInfoEnabled()) { logger.warn("Failed to connect to " + NetworkUtils.ipToString(target.getAddress()) + ":" + target.getPort(), e); try { s.close(); } catch (Exception e2) { // ignore } return null; } } private DirectServerSocket createServerSocket(int port, int backlog, boolean portForwarding, boolean forwardingMayFail, boolean sameExternalPort) throws IOException { if (port == 0) { port = portRange.getPort(); } ServerSocket ss = createUnboundServerSocket(); ss.bind(new InetSocketAddress(port), backlog); SocketAddressSet local = new SocketAddressSet(completeAddress, ss.getLocalPort()); DirectServerSocket smss = new DirectServerSocket(local, ss); if (!(haveOnlyLocalAddresses && portForwarding)) { // We are not behind a NAT box or the user doesn't want port // forwarding, so just return the server socket if (logger.isDebugEnabled()) { logger.debug("Created server socket on: " + smss); } return smss; } // We only have a local address, and the user wants to try port // forwarding. Check if we are allowed to do so in the first place... if (!ALLOW_UPNP_PORT_FORWARDING) { // We are not allowed to do port forwarding. Check if this is OK by // the user. if (forwardingMayFail) { // It's OK, so return the socket. if (logger.isDebugEnabled()) { logger.debug("Port forwarding not allowed for: " + smss); } return smss; } // The user does not want the serversocket if it's not forwarded, so // close it and throw an exception. logger.warn("Port not allowed for: " + smss); try { ss.close(); } catch (Throwable t) { // ignore } throw new IOException("Port forwarding not allowed!"); } // Try to do port forwarding! if (port == 0) { port = ss.getLocalPort(); } try { int ePort = sameExternalPort ? port : 0; ePort = UPNP.addPortMapping(port, ePort, myNATAddress, 0, "TCP"); smss.addExternalAddress( new SocketAddressSet(externalNATAddress, ePort)); } catch (Exception e) { logger.warn("Port forwarding failed for: " + local + " " + e); if (!forwardingMayFail) { // User doesn't want the port forwarding to fail, so close the // server socket and throw an exception. try { ss.close(); } catch (Throwable t) { // ignore } throw new IOException("Port forwarding failed: " + e); } } if (logger.isDebugEnabled()) { logger.debug("Created server socket on: " + smss); } return smss; } /** * Configures a socket according to user-specified properties. Currently, * the input buffer size and output buffer size can be set using the system * properties "ibis.util.socketfactory.InputBufferSize" and * "ibis.util.socketfactory.OutputBufferSize". * * @param s * the socket to be configured * * @exception IOException * when the configation has failed for some reason. */ protected void tuneSocket(DirectSocket s) throws IOException { if (inputBufferSize != 0) { s.setReceiveBufferSize(inputBufferSize); } if (outputBufferSize != 0) { s.setSendBufferSize(outputBufferSize); } s.setTcpNoDelay(true); } /** * Retrieves a boolean property from a Map, using a given key. * - If the map is null or the property does not exist, the default value * is returned. - If the property exists but has no value true is returned. - * If the property exists and has a value equal to "true", "yes", "on" or * "1", true is returned. - Otherwise, false is returned. * * @param prop * the map * @param key * the name of the property * @param def * the default value * @return boolean result */ private boolean getProperty(Map prop, String key, boolean def) { if (prop != null && prop.containsKey(key)) { String value = (String) prop.get(key); if (value != null) { return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("1"); } return true; } return def; } public IPAddressSet getLocalAddress() { return completeAddress; } public static void close(DirectSocket s, OutputStream o, InputStream i) { if (o != null) { try { o.close(); } catch (Exception e) { // ignore } } if (i != null) { try { i.close(); } catch (Exception e) { // ignore } } if (s != null) { try { s.close(); } catch (Exception e) { // ignore } } } /* * (non-Javadoc) * * @see smartnet.factories.ClientServerSocketFactory#createClientSocket(smartnet.IbisSocketAddress, * int, java.util.Map) */ public DirectSocket createSocket(SocketAddressSet target, int timeout, Map properties) throws IOException { return createSocket(target, timeout, 0, properties); } /* * (non-Javadoc) * * @see smartnet.factories.ClientServerSocketFactory#createClientSocket(smartnet.IbisSocketAddress, * int, java.util.Map) */ public DirectSocket createSocket(SocketAddressSet target, int timeout, int localPort, Map properties) throws IOException { if (timeout < 0) { timeout = DEFAULT_TIMEOUT; } InetSocketAddress[] sas = target.getSocketAddresses(); // Select the addresses we want from the target set. Some may be removed // thanks to the cluster configuration. sas = preference.sort(sas, false); if (sas.length == 1) { long time = System.currentTimeMillis(); // only one socket left, so allow sleeping for ever... DirectSocket result = attemptConnection(target, sas[0], timeout, localPort, true); time = System.currentTimeMillis() -time; if (logger.isInfoEnabled()) { logger.info("Connection setup took: " + time + " ms."); } if (result != null) { return result; } throw new ConnectException("Connection setup failed"); } // else, we must try them all, so the connection attempt must return at // some point, even if timeout == 0 int partialTimeout = timeout / sas.length; while (true) { for (int i = 0; i < sas.length; i++) { long time = System.currentTimeMillis(); InetSocketAddress sa = sas[i]; DirectSocket result = attemptConnection(target, sa, partialTimeout, localPort, false); time = System.currentTimeMillis() -time; if (logger.isInfoEnabled()) { logger.info("Connection setup took: " + time + " ms."); } if (result != null) { return result; } } if (timeout > 0) { // Enough tries so, throw exception throw new ConnectException("Connection setup failed"); } // else, the user wants us to keep trying! } } /* * (non-Javadoc) * * @see smartnet.factories.ClientServerSocketFactory#createServerSocket(int, * int, java.util.Map) */ public DirectServerSocket createServerSocket(int port, int backlog, Map prop) throws IOException { boolean forwardMayFail = true; boolean sameExternalPort = true; boolean portForwarding = getProperty(prop, "PortForwarding", false); if (portForwarding) { forwardMayFail = getProperty(prop, "ForwardingMayFail", true); sameExternalPort = getProperty(prop, "SameExternalPort", true); } return createServerSocket(port, backlog, portForwarding, forwardMayFail, sameExternalPort); } /* * public IbisSocket createBrokeredSocket(InputStream in, OutputStream out, * boolean hintIsServer, Map properties) throws IOException { * * IbisSocket s = null; * * if (hintIsServer) { IbisServerSocket server = createServerSocket(0, 1, * properties); * * DataOutputStream dos = new DataOutputStream(new * BufferedOutputStream(out)); * * dos.writeUTF(server.getLocalSocketAddress().toString()); dos.flush(); * * s = server.accept(); tuneSocket(s); * } else { DataInputStream di = new DataInputStream(new * BufferedInputStream(in)); * * String tmp = di.readUTF(); * * MachineAddress address = null; * * try { address = new MachineAddress(tmp); } catch(Exception e) { throw new * Error("EEK, could not create an IbisSocketAddress " + " from " + tmp, e); } * * s = createClientSocket(address, 0, properties); } * * return s; } */ /** * Returns if an address originated at this process. * * @return boolean indicating if the address is local. */ public boolean isLocalAddress(IPAddressSet a) { return (a.equals(completeAddress)); } /** * Returns a custom instance of a DirectSocketFactory. * * @return PlainSocketFactory */ public static DirectSocketFactory getSocketFactory(TypedProperties p) { return new DirectSocketFactory(p); } /** * Returns the default instance of a DirectSocketFactory. * * @return PlainSocketFactory */ public static DirectSocketFactory getSocketFactory() { if (defaultFactory == null) { defaultFactory = new DirectSocketFactory(Properties.getDefaultProperties()); } return defaultFactory; } }
package org.ccnx.ccn.io.content; import java.io.IOException; import java.io.InvalidObjectException; import java.util.Arrays; import java.util.EnumSet; import java.util.HashSet; import java.util.logging.Level; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.CCNInterestListener; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.config.ConfigurationException; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.CCNFlowControl; import org.ccnx.ccn.impl.CCNFlowControl.SaveType; import org.ccnx.ccn.impl.CCNFlowControl.Shape; import org.ccnx.ccn.impl.repo.RepositoryFlowControl; import org.ccnx.ccn.impl.security.crypto.ContentKeys; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.impl.support.Tuple; import org.ccnx.ccn.io.CCNInputStream; import org.ccnx.ccn.io.CCNVersionedInputStream; import org.ccnx.ccn.io.CCNVersionedOutputStream; import org.ccnx.ccn.io.ErrorStateException; import org.ccnx.ccn.io.LinkCycleException; import org.ccnx.ccn.io.NoMatchingContentFoundException; import org.ccnx.ccn.io.CCNAbstractInputStream.FlagTypes; import org.ccnx.ccn.io.content.Link.LinkObject; import org.ccnx.ccn.profiles.SegmentationProfile; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.profiles.versioning.VersionNumber; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.KeyLocator; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.SignedInfo.ContentType; /** * Extends a NetworkObject to add specifics for using a CCN-based backing store. Each time * the object is saved creates a new CCN version. Readers can open a specific version or * not specify a version, in which case the latest available version is read. Defaults * allow for saving data to a repository or directly to the network. * * Need to support four use models: * dimension 1: synchronous - ask for and block, the latest version or a specific version * dimension 2: asynchronous - ask for and get in the background, the latest version or a specific * version * When possible, keep track of the latest version known so that the latest version queries * can attempt to do better than that. Start by using only in the background load case, as until * something comes back we can keep using the old one and the propensity for blocking is high. * * Support for subclasses or users specifying different flow controllers with * different behavior. Build in support for either the simplest standard flow * controller, or a standard repository-backed flow controller. * * These objects attempt to maintain a CCN copy of the current state of their data. In descriptions * below, an object that is "dirty" is one whose data has been modified locally, but not yet * saved to the network. * * While CCNNetworkObject could be used directly, it almost never is; it is usually * more effective to define a subclass specialized to save/retrieve a specific object * type. * * Updates, 12/09: Move to creating a flow controller in the write constructor if * one isn't passed in. Read constructors still lazily create flow controllers on * first write (tradeoff); preemptive construction (and registering for interests) * can be achieved by calling the setupSave() method which creates a flow controller * if one hasn't been created already. Move to a strong default of saving * to a repository, unless overridden by the subclass itself. Change of repository/raw * nature can be made with the setRawSave() and setRepositorySave() methods. * * TODO: Note that the CCNNetworkObject class hierarchy currently has a plethora of constructors. * It is also missing some important functionality -- encryption, the ability to specify * freshness, and so on. Expect new constructors to deal with the latter deficiencies, and * a cleanup of the constructor architecture overall in the near term. */ public abstract class CCNNetworkObject<E> extends NetworkObject<E> implements CCNInterestListener { protected static final byte [] GONE_OUTPUT = "GONE".getBytes(); /** * Unversioned "base" name. */ protected ContentName _baseName; /** * The most recent version we have read/written. */ protected byte [] _currentVersionComponent; /** * Cached versioned name. */ protected ContentName _currentVersionName; /** * Flag to indicate whether content has been explicitly marked as GONE * in the latest version we know about. Use an explicit flag to separate from * the option for valid null content, or content that has not yet been updated. */ protected boolean _isGone = false; /** * The first segment for the stored data */ protected ContentObject _firstSegment = null; /** * If the name we started with was actually a link, detect that, store the link, * and dereference it to get the content. Call updateLink() to update the link * itself, and if updated, to update the dereferenced value. * * If the initial link is a link, recursion should push that into the link of * this LinkObject, and read its data. If that is a link, it should push again -- * this should chain through links till we reach an object of the desired type, * or blow up. (It won't handle encrypted links, though; we may need to distinguish * between ENCR and ENCRL. Having encrypted links would be handy, to send people * off in random directions. But it matters a lot to be able to tell if the decryption * is a LINK or not.) * * Writing linked objects is better done by separately writing the object and * the link, as it gives you more control over what is happening. If you attempt * to save this object, it may break the link (as the link may link to the particular * version retrieved). You can use this inner link object to manually update the link * to the target; but there are no good defaults about how to update the data. So * you need to specify the new link value yourself. For now we don't prevent users * from getting their data and their links de-syncrhonized. */ protected LinkObject _dereferencedLink; protected PublisherPublicKeyDigest _currentPublisher; protected KeyLocator _currentPublisherKeyLocator; protected CCNHandle _handle; protected CCNFlowControl _flowControl; protected boolean _disableFlowControlRequest = false; protected PublisherPublicKeyDigest _publisher; // publisher we write under, if null, use handle defaults protected KeyLocator _keyLocator; // locator to find publisher key protected SaveType _saveType = null; // what kind of flow controller to make if we don't have one protected Integer _freshnessSeconds = null; // if we want to set short freshness protected ContentKeys _keys; protected ContentVerifier _verifier; /** * Controls ongoing update. */ Interest _currentInterest = null; boolean _continuousUpdates = false; HashSet<UpdateListener> _updateListeners = null; /** * Basic write constructor. This will set the object's internal data but it will not save it * until save() is called. Unless overridden by the subclass, will default to save to * a repository. Can be changed to save directly to the network using setRawSave(). * If a subclass sets the default behavior to raw saves, this can be overridden on a * specific instance using setRepositorySave(). * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param name Name under which to save object. * @param data Data to save. * @param handle CCNHandle to use for network operations. If null, a new one is created using CCNHandle#open(). * @throws IOException If there is an error setting up network backing store. */ public CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentName name, E data, SaveType saveType, CCNHandle handle) throws IOException { this(type, contentIsMutable, name, data, saveType, null, null, handle); } /** * Basic write constructor. This will set the object's internal data but it will not save it * until save() is called. Unless overridden by the subclass, will default to save to * a repository. Can be changed to save directly to the network using setRawSave(). * If a subclass sets the default behavior to raw saves, this can be overridden on a * specific instance using setRepositorySave(). * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param name Name under which to save object. * @param data Data to save. * @param raw If true, saves to network by default, if false, saves to repository by default. * @param publisher The key to use to sign this data, or our default if null. * @param locator The key locator to use to let others know where to get our key. * @param handle CCNHandle to use for network operations. If null, a new one is created using CCNHandle#open(). * @throws IOException If there is an error setting up network backing store. */ public CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentName name, E data, SaveType saveType, PublisherPublicKeyDigest publisher, KeyLocator locator, CCNHandle handle) throws IOException { super(type, contentIsMutable, data); if (null == handle) { try { handle = CCNHandle.open(); } catch (ConfigurationException e) { throw new IllegalArgumentException("handle null, and cannot create one: " + e.getMessage(), e); } } _handle = handle; _verifier = handle.defaultVerifier(); _baseName = name; _publisher = publisher; _keyLocator = locator; _saveType = saveType; // Make our flow controller and register interests for our base name, if we have one. // Otherwise, create flow controller when we need one. if (null != name) { createFlowController(); } } /** * Specialized constructor, allowing subclasses to override default flow controller * (and hence backing store) behavior. * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param name Name under which to save object. * @param data Data to save. * @param publisher The key to use to sign this data, or our default if null. * @param locator The key locator to use to let others know where to get our key. * @param flowControl Flow controller to use. A single flow controller object * is used for all this instance's writes, we use underlying streams to call * CCNFlowControl#startWrite(ContentName, Shape) on each save. Calls to * setRawSave() and setRepositorySave() will replace this flow controller * with a raw or repository flow controller, and should not be used with * this type of object (which obviously cares about what flow controller to use). * @throws IOException If there is an error setting up network backing store. */ protected CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentName name, E data, PublisherPublicKeyDigest publisher, KeyLocator locator, CCNFlowControl flowControl) throws IOException { super(type, contentIsMutable, data); _baseName = name; _publisher = publisher; _keyLocator = locator; if (null == flowControl) { throw new IOException("FlowControl cannot be null!"); } _flowControl = flowControl; _handle = _flowControl.getHandle(); _saveType = _flowControl.saveType(); _verifier = _handle.defaultVerifier(); // Register interests for our base name, if we have one. if (null != name) { flowControl.addNameSpace(name); } } /** * Read constructor. Will try to pull latest version of this object, or a specific * named version if specified in the name. If read times out, will leave object in * its uninitialized state. * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param name Name from which to read the object. If versioned, will read that specific * version. If unversioned, will attempt to read the latest version available. * @param handle CCNHandle to use for network operations. If null, a new one is created using CCNHandle#open(). * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentName name, CCNHandle handle) throws ContentDecodingException, IOException { this(type, contentIsMutable, name, (PublisherPublicKeyDigest)null, handle); } /** * Read constructor. Will try to pull latest version of this object, or a specific * named version if specified in the name. If read times out, will leave object in * its uninitialized state. * * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param name Name from which to read the object. If versioned, will read that specific * version. If unversioned, will attempt to read the latest version available. * @param publisher Particular publisher we require to have signed the content, or null for any publisher. * @param flowControl Flow controller to use. A single flow controller object * is used for all this instance's writes, we use underlying streams to call * CCNFlowControl#startWrite(ContentName, Shape) on each save. * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ protected CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentName name, PublisherPublicKeyDigest publisher, CCNFlowControl flowControl) throws ContentDecodingException, IOException { super(type, contentIsMutable); if (null == flowControl) { throw new IOException("FlowControl cannot be null!"); } _flowControl = flowControl; _handle = _flowControl.getHandle(); _saveType = _flowControl.saveType(); _verifier = _handle.defaultVerifier(); update(name, publisher); } /** * Read constructor. Will try to pull latest version of this object, or a specific * named version if specified in the name. If read times out, will leave object in * its uninitialized state. * * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param name Name from which to read the object. If versioned, will read that specific * version. If unversioned, will attempt to read the latest version available. * @param publisher Particular publisher we require to have signed the content, or null for any publisher. * @param handle CCNHandle to use for network operations. If null, a new one is created using CCNHandle#open(). * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentName name, PublisherPublicKeyDigest publisher, CCNHandle handle) throws ContentDecodingException, IOException { super(type, contentIsMutable); if (null == handle) { try { handle = CCNHandle.open(); } catch (ConfigurationException e) { throw new IllegalArgumentException("handle null, and cannot create one: " + e.getMessage(), e); } } _handle = handle; _verifier = handle.defaultVerifier(); _baseName = name; update(name, publisher); } /** * Read constructor if you already have a segment of the object. Used by streams. * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param firstSegment First segment of the object, retrieved by other means. * @param raw If true, defaults to raw network writes, if false, repository writes. * @param handle CCNHandle to use for network operations. If null, a new one is created using CCNHandle#open(). * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentObject firstSegment, CCNHandle handle) throws ContentDecodingException, IOException { super(type, contentIsMutable); if (null == handle) { try { handle = CCNHandle.open(); } catch (ConfigurationException e) { throw new IllegalArgumentException("handle null, and cannot create one: " + e.getMessage(), e); } } _handle = handle; _verifier = handle.defaultVerifier(); update(firstSegment); } /** * Read constructor if you already have a segment of the object. Used by streams. * @param type Wrapped class type. * @param contentIsMutable is the wrapped class type mutable or not * @param firstSegment First segment of the object, retrieved by other means. * @param flowControl Flow controller to use. A single flow controller object * is used for all this instance's writes, we use underlying streams to call * CCNFlowControl#startWrite(ContentName, Shape) on each save. * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ protected CCNNetworkObject(Class<E> type, boolean contentIsMutable, ContentObject firstSegment, CCNFlowControl flowControl) throws ContentDecodingException, IOException { super(type, contentIsMutable); if (null == flowControl) throw new IllegalArgumentException("flowControl cannot be null!"); _flowControl = flowControl; _handle = _flowControl.getHandle(); _saveType = _flowControl.saveType(); _verifier = _handle.defaultVerifier(); update(firstSegment); } /** * Copy constructor. Handle it piece by piece, though it means * updating this whenever the structure changes (rare). */ protected CCNNetworkObject(Class<E> type, CCNNetworkObject<? extends E> other) { super(type, other); _baseName = other._baseName; _currentVersionComponent = other._currentVersionComponent; _currentVersionName = other._currentVersionName; _isGone = other._isGone; _currentPublisher = other._currentPublisher; _currentPublisherKeyLocator = other._currentPublisherKeyLocator; _handle = other._handle; _flowControl = other._flowControl; _disableFlowControlRequest = other._disableFlowControlRequest; _publisher = other._publisher; _keyLocator = other._keyLocator; _saveType = other._saveType; _keys = (null != other._keys) ? other._keys.clone() : null; _firstSegment = other._firstSegment; _verifier = other._verifier; // Do not copy update behavior. Even if other one is updating, we won't // pick that up. Have to kick off manually. } /** * Maximize laziness of flow controller creation, to make it easiest for client code to * decide how to store this object. * When we create the flow controller, we add the base name namespace, so it will respond * to requests for latest version. Create them immediately in write constructors, * when we have a strong expectation that we will save data, if we have a namespace * to start listening on. Otherwise wait till we are going to write. * @return * @throws IOException */ protected synchronized void createFlowController() throws IOException { if (null == _flowControl) { if (null == _saveType) { Log.finer("Not creating flow controller yet, no saveType set."); return; } switch (_saveType) { case RAW: _flowControl = new CCNFlowControl(_handle); break; case REPOSITORY: _flowControl = new RepositoryFlowControl(_handle); break; case LOCALREPOSITORY: _flowControl = new RepositoryFlowControl(_handle, true); break; default: throw new IOException("Unknown save type: " + _saveType); } if (_disableFlowControlRequest) _flowControl.disable(); // Have to register the version root. If we just register this specific version, we won't // see any shorter interests -- i.e. for get latest version. _flowControl.addNameSpace(_baseName); if (Log.isLoggable(Level.INFO)) Log.info("Created " + _saveType + " flow controller, for prefix {0}, save type " + _flowControl.saveType(), _baseName); } } /** * Get the flow controller associated with this object * @return the flow controller or null if not assigned */ public CCNFlowControl getFlowControl() { return _flowControl; } /** * Get timeout associated with this object * @return */ public long getTimeout() { return _flowControl.getTimeout(); } /** * Start listening to interests on our base name, if we aren't already. * @throws IOException */ public synchronized void setupSave(SaveType saveType) throws IOException { setSaveType(saveType); setupSave(); } public synchronized void setupSave() throws IOException { if (null != _flowControl) { if (null != _baseName) { _flowControl.addNameSpace(_baseName); } return; } createFlowController(); } /** * Finalizer. Somewhat dangerous, but currently best way to close * lingering open registrations. Can't close the handle, till we ref count. */ @Override protected void finalize() throws Throwable { try { close(); // close the object, canceling interests and listeners. } finally { super.finalize(); } } /** * Close flow controller, remove listeners. Have to call setupSave to save with this object again, * re-add listeners. * @return */ public synchronized void close() { cancelInterest(); clearListeners(); if (null != _flowControl) { _flowControl.close(); } } public SaveType saveType() { return _saveType; } /** * Used by subclasses to specify a mandatory save type in * read constructors. Only works on objects whose flow * controller has not yet been set, to not override * manually-set FC's. */ protected void setSaveType(SaveType saveType) throws IOException { if (null == _flowControl) { _saveType = saveType; } else if (saveType != _saveType){ throw new IOException("Cannot change save type, flow controller already set!"); } } /** * If you want to set the lifetime of objects saved with this instance. * @param freshnessSeconds If null, will unset any freshness seconds (will * write objects that stay in cache till forced out); if a value will constrain * how long objects will stay in cache. */ public void setFreshnessSeconds(Integer freshnessSeconds) { _freshnessSeconds = freshnessSeconds; } /** * Override point where subclasses can modify each input stream before * it is read. Subclasses should at least set the flags using getInputStreamFlags, * or call super.setInputStreamProperties. */ protected void setInputStreamProperties(CCNInputStream inputStream) { // default -- just set any flags inputStream.setFlags(getInputStreamFlags()); } /** * Override point where subclasses can specify set of flags on input stream * at point it is read or where necessary created. * @return */ protected EnumSet<FlagTypes> getInputStreamFlags() { return null; } /** * Allow verifier to be specified. Could put this in the constructors; though they * are already complicated enough. If not set, the default verifier for the key manager * used by the object's handle is used. * @param verifier the verifier to use. Cannot be null. */ public void setVerifier(ContentVerifier verifier) { if (null != verifier) _verifier = verifier; } /** * Attempts to find a version after the latest one we have, or times out. If * it times out, it simply leaves the object unchanged. * @return returns true if it found an update, false if not * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public boolean update(long timeout) throws ContentDecodingException, IOException { if (null == _baseName) { throw new IllegalStateException("Cannot retrieve an object without giving a name!"); } // Look for first segment of version after ours, or first version if we have none. ContentObject firstSegment = VersioningProfile.getFirstBlockOfLatestVersion(getVersionedName(), null, null, timeout, _handle.defaultVerifier(), _handle); if (null != firstSegment) { return update(firstSegment); } return false; } /** * The regular update does a call to do multi-hop get latest version -- i.e. it will try * multiple times to find the latest version of a piece of content, even if interposed caches * have something older. While that's great when you really need the latest, sometimes you are * happy with the latest available version available in your local ccnd cache; or you really * know there is only one version available and you don't want to try multiple times (and incur * a timeout) in an attempt to get a later version that does not exist. This call, updateAny, * claims to get "any" version available. In reality, it will do a single-hop latest version; * i.e. if there are two versions say in your local ccnd cache (or repo with nothing in the ccnd * cache), it will pull the later one. But * it won't move beyond those to find a newer version available at a writer, or to find a later * version in the repo than one in the ccnd cache. Use this if you know there is only one version * of something, or you want a fast path to the latest version where it really doesn't have to * be the "absolute" latest. * * Like all update methods, it will start from the version you've got -- so it is guaranteed to find * something after the current version this object knows about (if it has already found something), * and to time out and return false if there isn't anything later. */ public boolean updateAny(long timeout) throws ContentDecodingException, IOException { if (null == _baseName) { throw new IllegalStateException("Cannot retrieve an object without giving a name!"); } // Look for first segment of version after ours, or first version if we have none. ContentObject firstSegment = VersioningProfile.getFirstBlockOfAnyLaterVersion(getVersionedName(), null, null, timeout, _verifier, _handle); if (null != firstSegment) { return update(firstSegment); } return false; } public boolean updateAny() throws ContentDecodingException, IOException { return updateAny(SystemConfiguration.getDefaultTimeout()); } /** * Calls update(long) with the default timeout SystemConfiguration.getDefaultTimeout(). * @return see update(long). * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public boolean update() throws ContentDecodingException, IOException { return update(SystemConfiguration.getDefaultTimeout()); } /** * Load data into object. If name is versioned, load that version. If * name is not versioned, look for latest version. * @param name Name of object to read. * @param publisher Desired publisher, or null for any. * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public boolean update(ContentName name, PublisherPublicKeyDigest publisher) throws ContentDecodingException, IOException { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "Updating object to {0}.", name); CCNVersionedInputStream is = new CCNVersionedInputStream(name, publisher, _handle); return update(is); } /** * Load a stream starting with a specific object. * @param object * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public boolean update(ContentObject object) throws ContentDecodingException, IOException { CCNInputStream is = new CCNInputStream(object, getInputStreamFlags(), _handle); setInputStreamProperties(is); is.seek(0); // in case it wasn't the first segment return update(is); } /** * Updates the object from a CCNInputStream or one of its subclasses. Used predominantly * by internal methods, most clients should use update() or update(long). Exposed for * special-purpose use and experimentation. * @param inputStream Stream to read object from. * @return true if an update found, false if not. * @throws ContentDecodingException if there is a problem decoding the object. * @throws IOException if there is an error setting up network backing store. */ public synchronized boolean update(CCNInputStream inputStream) throws ContentDecodingException, IOException { // Allow subclasses to modify input stream processing prior to first read. setInputStreamProperties(inputStream); Tuple<ContentName, byte []> nameAndVersion = null; try { if (inputStream.isGone()) { if (Log.isLoggable(Log.FAC_IO, Level.FINE)) Log.fine(Log.FAC_IO, "Reading from GONE stream: {0}", inputStream.getBaseName()); _data = null; // This will have a final version and a segment nameAndVersion = VersioningProfile.cutTerminalVersion(inputStream.deletionInformation().name()); _currentPublisher = inputStream.deletionInformation().signedInfo().getPublisherKeyID(); _currentPublisherKeyLocator = inputStream.deletionInformation().signedInfo().getKeyLocator(); _available = true; _isGone = true; _isDirty = false; _lastSaved = digestContent(); } else { super.update(inputStream); nameAndVersion = VersioningProfile.cutTerminalVersion(inputStream.getBaseName()); _currentPublisher = inputStream.publisher(); _currentPublisherKeyLocator = inputStream.publisherKeyLocator(); _isGone = false; } _firstSegment = inputStream.getFirstSegment(); // preserve first segment } catch (NoMatchingContentFoundException nme) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "NoMatchingContentFoundException in update from input stream {0}, timed out before data was available.", inputStream.getBaseName()); nameAndVersion = VersioningProfile.cutTerminalVersion(inputStream.getBaseName()); _baseName = nameAndVersion.first(); // used to fire off an updateInBackground here, to hopefully get a second // chance on scooping up the content. But that seemed likely to confuse // people and leave the object in an undetermined state. So allow caller // to manage that themselves. // not an error state, merely a not ready state. return false; } catch (LinkCycleException lce) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "Link cycle exception: {0}", lce.getMessage()); setError(lce); throw lce; } _baseName = nameAndVersion.first(); _currentVersionComponent = nameAndVersion.second(); _currentVersionName = null; // cached if used _dereferencedLink = inputStream.getDereferencedLink(); // gets stack of links used, if any clearError(); // Signal readers. newVersionAvailable(false); return true; } /** * Update this object in the background -- asynchronously. This call updates the * object a single time, after the first update (the requested version or the * latest version), the object will not self-update again unless requested. * To use, create an object using a write constructor, setting the data field * to null. Then call updateInBackground() to retrieve the object's data asynchronously. * To wait on data arrival, call either waitForData() or wait() on the object itself. * @throws IOException */ public void updateInBackground() throws IOException { updateInBackground(false); } /** * Update this object in the background -- asynchronously. * To use, create an object using a write constructor, setting the data field * to null. Then call updateInBackground() to retrieve the object's data asynchronously. * To wait for an update to arrive, call wait() on this object itself. * @param continuousUpdates If true, updates the * object continuously to the latest version available, a single time if it is false. * @throws IOException */ public void updateInBackground(boolean continuousUpdates) throws IOException { if (null == _baseName) { throw new IllegalStateException("Cannot retrieve an object without giving a name!"); } // Look for latest version. updateInBackground(getVersionedName(), continuousUpdates, null); } public void updateInBackground(ContentName latestVersionKnown, boolean continuousUpdates) throws IOException { updateInBackground(latestVersionKnown, continuousUpdates, null); } public void updateInBackground(boolean continuousUpdates, UpdateListener listener) throws IOException { updateInBackground(getVersionedName(), continuousUpdates, listener); } /** * Update this object in the background -- asynchronously. * To use, create an object using a write constructor, setting the data field * to null. Then call updateInBackground() to retrieve the object's data asynchronously. * To wait for an update to arrive, call wait() on this object itself. * @param latestVersionKnown the name of the latest version we know of, or an unversioned * name if no version known * @param continuousUpdates If true, updates the * object continuously to the latest version available, a single time if it is false. * @throws IOException */ public synchronized void updateInBackground(ContentName latestVersionKnown, boolean continuousUpdates, UpdateListener listener) throws IOException { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: getting latest version after {0} in background.", latestVersionKnown); cancelInterest(); if (null != listener) { addListener(listener); } _continuousUpdates = continuousUpdates; _currentInterest = VersioningProfile.firstBlockLatestVersionInterest(latestVersionKnown, null); if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: initial interest: {0}", _currentInterest); _handle.expressInterest(_currentInterest, this); } /** * Cancel an outstanding updateInBackground(). */ public synchronized void cancelInterest() { _continuousUpdates = false; if (null != _currentInterest) { _handle.cancelInterest(_currentInterest, this); } } public synchronized void addListener(UpdateListener listener) { if (null == _updateListeners) { _updateListeners = new HashSet<UpdateListener>(); } else if (_updateListeners.contains(listener)) { return; // don't re-add } _updateListeners.add(listener); } /** * Does this object already have this listener. Uses Object.equals * for comparison; so will only say yes if it has this *exact* listener * instance already registered. * @param listener * @return */ public synchronized boolean hasListener(UpdateListener listener) { if (null == _updateListeners) { return false; } return (_updateListeners.contains(listener)); } public void removeListener(UpdateListener listener) { if (null == _updateListeners) return; synchronized (this) { _updateListeners.remove(listener); } } public void clearListeners() { if (null == _updateListeners) return; synchronized(_updateListeners) { _updateListeners.clear(); } } /** * Save to existing name, if content is dirty. Update version. * This is the default form of save -- if the object has been told to use * a repository backing store, by either giving it a repository flow controller, * calling saveToRepository() on it for its first save, or specifying false * to a constructor that allows a raw argument, it will save to a repository. * Otherwise will perform a raw save. * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ public boolean save() throws ContentEncodingException, IOException { return saveInternal(null, false, null); } /** * Method for CCNFilterListeners to save an object in response to an Interest * callback. An Interest has already been received, so the object can output * one ContentObject as soon as one is ready. Ideally this Interest will have * been received on the CCNHandle the object is using for output. If the object * is not dirty, it will not be saved, and the Interest will not be consumed. * If the Interest does not match this object, the Interest will not be consumed; * it is up to the caller to ensure that the Interest would be matched by writing * this object. (If the Interest doesn't match, no initial block will be output * even if the object is saved; the object will wait for matching Interests prior * to writing its blocks.) */ public boolean save(Interest outstandingInterest) throws ContentEncodingException, IOException { return saveInternal(null, false, outstandingInterest); } /** * Save to existing name, if content is dirty. Saves to specified version. * This is the default form of save -- if the object has been told to use * a repository backing store, by either giving it a repository flow controller, * calling saveToRepository() on it for its first save, or specifying false * to a constructor that allows a raw argument, it will save to a repository. * Otherwise will perform a raw save. * @param version Version to save to. * @return true if object was saved, false if it was not (if it was not dirty). * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ public boolean save(CCNTime version) throws ContentEncodingException, IOException { return saveInternal(version, false, null); } /** * Save to existing name, if content is dirty. Saves to specified version. * Method for CCNFilterListeners to save an object in response to an Interest * callback. An Interest has already been received, so the object can output * one ContentObject as soon as one is ready. Ideally this Interest will have * been received on the CCNHandle the object is using for output. If the object * is not dirty, it will not be saved, and the Interest will not be consumed. * If the Interest does not match this object, the Interest will not be consumed; * it is up to the caller to ensure that the Interest would be matched by writing * this object. (If the Interest doesn't match, no initial block will be output * even if the object is saved; the object will wait for matching Interests prior * to writing its blocks.) */ public boolean save(CCNTime version, Interest outstandingInterest) throws ContentEncodingException, IOException { return saveInternal(version, false, outstandingInterest); } /** * Save content to specific version. Internal form that performs actual save. * @param version If version is non-null, assume that is the desired * version. If not, set version based on current time. * @param gone Are we saving this content as gone or not. * @return return Returns true if it saved data, false if it thought data was not dirty and didn't * save. * TODO allow freshness specification * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ protected synchronized boolean saveInternal(CCNTime version, boolean gone, Interest outstandingInterest) throws ContentEncodingException, IOException { if (null == _baseName) { throw new IllegalStateException("Cannot save an object without giving it a name!"); } // move object to this name // need to make sure we get back the actual name we're using, // even if output stream does automatic versioning // probably need to refactor save behavior -- right now, internalWriteObject // either writes the object or not; we need to only make a new name if we do // write the object, and figure out if that's happened. Also need to make // parent behavior just write, put the dirty check higher in the state. if (!gone && !isDirty()) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "Object not dirty. Not saving."); return false; } if (!gone && (null == _data)) { // skip some of the prep steps that have side effects rather than getting this exception later from superclass throw new InvalidObjectException("No data to save!"); } // Create the flow controller, if we haven't already. createFlowController(); // This is the point at which we care if we don't have a flow controller if (null == _flowControl) { throw new IOException("Cannot create flow controller! Specified save type is " + _saveType + "!"); } // Handle versioning ourselves to make name handling easier. VOS should respect it. // We might have been handed a _baseName that was versioned. For most general behavior, // have to treat it as a normal name and that we are supposed to put our own version // underneath it. To save as a specific version, need to use save(version). ContentName name = _baseName; if (null != version) { name = VersioningProfile.addVersion(_baseName, version); } else { name = VersioningProfile.addVersion(_baseName); } // DKS if we add the versioned name, we don't handle get latest version. // We re-add the baseName here in case an update has changed it. // TODO -- perhaps disallow updates for unrelated names. _flowControl.addNameSpace(_baseName); if (!gone) { // CCNVersionedOutputStream will version an unversioned name. // If it gets a versioned name, will respect it. // This will call startWrite on the flow controller. // Note that we must use the flow controller given to us as opposed to letting // the OutputStream create its own. This is because there may be dependencies from the // caller on the specific flow controller - the known case is the flow controller is a // CCNFlowServer which requires that the flow controller retain its objects after writing // them. A standard FC would cause the objects to be lost. CCNVersionedOutputStream cos = new CCNVersionedOutputStream(name, _keyLocator, _publisher, contentType(), _keys, _flowControl); cos.setFreshnessSeconds(_freshnessSeconds); if (null != outstandingInterest) { cos.addOutstandingInterest(outstandingInterest); } save(cos); // superclass stream save. calls flush but not close on a wrapping // digest stream; want to make sure we end up with a single non-MHT signed // segment and no header on small objects cos.close(); // Grab digest and segment number after close because for short objects there may not be // a segment generated until the close _firstSegment = cos.getFirstSegment(); } else { // saving object as gone, currently this is always one empty segment so we don't use an OutputStream ContentName segmentedName = SegmentationProfile.segmentName(name, SegmentationProfile.BASE_SEGMENT ); byte [] empty = new byte[0]; byte [] finalBlockID = SegmentationProfile.getSegmentNumberNameComponent(SegmentationProfile.BASE_SEGMENT); ContentObject goneObject = ContentObject.buildContentObject(segmentedName, ContentType.GONE, empty, _publisher, _keyLocator, null, finalBlockID); // The segmenter in the stream does an addNameSpace of the versioned name. Right now // this not only adds the prefix (ignored) but triggers the repo start write. _flowControl.addNameSpace(name); _flowControl.startWrite(name, Shape.STREAM); // Streams take care of this for the non-gone case. _flowControl.put(goneObject); _firstSegment = goneObject; _flowControl.beforeClose(); _flowControl.afterClose(); _lastSaved = GONE_OUTPUT; } _currentPublisher = _firstSegment.signedInfo().getPublisherKeyID(); _currentPublisherKeyLocator = _firstSegment.signedInfo().getKeyLocator(); _currentVersionComponent = name.lastComponent(); _currentVersionName = name; setDirty(false); _available = true; // We have completed our save and don't know when or if another save may occur so don't keep // ourselves registered with ccnd. That could cause interests to be unnecessarily or incorrectly // forwarded to us during the dormant period. _flowControl.removeNameSpace(_baseName); newVersionAvailable(true); if (Log.isLoggable(Log.FAC_IO, Level.FINEST)) Log.finest(Log.FAC_IO, "Saved object {0} publisher {1} key locator {2}", name, _currentPublisher, _currentPublisherKeyLocator); return true; } /** * Convenience method to the data and save it in a single operation. * @param data new data for object, set with setData * @return * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ public boolean save(E data) throws ContentEncodingException, IOException { return save(null, data); } /** * Convenience method to the data and save it as a particular version in a single operation. * @param version the desired version * @param data new data for object, set with setData * @return * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ public synchronized boolean save(CCNTime version, E data) throws ContentEncodingException, IOException { setData(data); return save(version); } /** * Deprecated; use either object defaults or setRepositorySave() to indicate writes * should go to a repository, then call save() to write. * If raw=true or DEFAULT_RAW=true specified, this must be the first call to save made * for this object to force repository storage (overriding default). * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ @Deprecated public synchronized boolean saveToRepository(CCNTime version) throws ContentEncodingException, IOException { if (null == _baseName) { throw new IllegalStateException("Cannot save an object without giving it a name!"); } setSaveType(SaveType.REPOSITORY); return save(version); } /** * Deprecated; use either object defaults or setRepositorySave() to indicate writes * should go to a repository, then call save() to write. * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ @Deprecated public boolean saveToRepository() throws ContentEncodingException, IOException { return saveToRepository((CCNTime)null); } /** * Deprecated; use either object defaults or setRepositorySave() to indicate writes * should go to a repository, then call save() to write. * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ @Deprecated public boolean saveToRepository(E data) throws ContentEncodingException, IOException { return saveToRepository(null, data); } /** * Deprecated; use either object defaults or setRepositorySave() to indicate writes * should go to a repository, then call save() to write. * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ @Deprecated public synchronized boolean saveToRepository(CCNTime version, E data) throws ContentEncodingException, IOException { setData(data); return saveToRepository(version); } /** * Save this object as GONE. Intended to mark the latest version, rather * than a specific version as GONE. So for now, require that name handed in * is *not* already versioned; throw an IOException if it is. * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ public synchronized boolean saveAsGone() throws ContentEncodingException, IOException { return saveAsGone(null); } /** * For use by CCNFilterListeners, saves a GONE object and emits an initial * block in response to an already-received Interest. * Save this object as GONE. Intended to mark the latest version, rather * than a specific version as GONE. So for now, require that name handed in * is *not* already versioned; throw an IOException if it is. * @throws IOException */ public synchronized boolean saveAsGone(Interest outstandingInterest) throws ContentEncodingException, IOException { if (null == _baseName) { throw new IllegalStateException("Cannot save an object without giving it a name!"); } _data = null; _isGone = true; setDirty(true); return saveInternal(null, true, outstandingInterest); } /** * Deprecated; use either object defaults or setRepositorySave() to indicate writes * should go to a repository, then call save() to write. * If raw=true or DEFAULT_RAW=true specified, this must be the first call to save made * for this object. * @throws ContentEncodingException if there is an error encoding the content * @throws IOException if there is an error reading the content from the network */ @Deprecated public synchronized boolean saveToRepositoryAsGone() throws ContentEncodingException, IOException { setSaveType(SaveType.REPOSITORY); return saveAsGone(); } /** * Turn off flow control for this object. Warning - calling this risks packet drops. It should only * be used for tests or other special circumstances in which * you "know what you are doing". */ public synchronized void disableFlowControl() { if (null != _flowControl) _flowControl.disable(); _disableFlowControlRequest = true; } /** * Used to signal waiters and listeners that a new version is available. * @param wasSave is a new version available because we were saved, or because * we found a new version on the network? */ protected void newVersionAvailable(boolean wasSave) { if (Log.isLoggable(Log.FAC_IO, Level.FINER)) { Log.finer(Log.FAC_IO, "newVersionAvailable: New version of object available: {0}", getVersionedName()); } // by default signal all waiters this.notifyAll(); // and any registered listeners if (null != _updateListeners) { for (UpdateListener listener : _updateListeners) { listener.newVersionAvailable(this, wasSave); } } } /** * Will return immediately if this object already has data, otherwise * will wait indefinitely for the initial data to appear. */ public void waitForData() { if (available()) return; synchronized (this) { while (!available()) { try { wait(); } catch (InterruptedException e) { } } } } /** * Will wait for data to arrive. Callers should use * available() to determine whether data has arrived or not. * If data already available, will return immediately (in other * words, this is only useful to wait for the first update to * an object, or to ensure that it has data). To wait for later * updates, call wait() on the object itself. * @param timeout In milliseconds. If 0, will wait forever (if data does not arrive). */ public void waitForData(long timeout) { if (available()) return; synchronized (this) { long startTime = System.currentTimeMillis(); boolean keepTrying = true; while (!available() && keepTrying) { // deal with spontaneous returns from wait() try { long waitTime = timeout - (System.currentTimeMillis() - startTime); if (waitTime > 0) wait(waitTime); else keepTrying = false; } catch (InterruptedException ie) {} } } } public boolean isGone() { return _isGone; } @Override protected byte [] digestContent() throws IOException { if (isGone()) { return GONE_OUTPUT; } return super.digestContent(); } @Override protected synchronized E data() throws ContentNotReadyException, ContentGoneException, ErrorStateException { if (isGone()) { throw new ContentGoneException("Content is gone!"); } return super.data(); } @Override public synchronized void setData(E newData) { _isGone = false; // clear gone, even if we're setting to null; only saveAsGone can set as gone super.setData(newData); } public synchronized CCNTime getVersion() throws IOException { if (isSaved()) return VersioningProfile.getVersionComponentAsTimestamp(getVersionComponent()); return null; } public synchronized VersionNumber getVersionNumber() throws IOException { if (isSaved()) return new VersionNumber(getVersionComponent()); return null; } public synchronized ContentName getBaseName() { return _baseName; } public CCNHandle getHandle() { return _handle; } public synchronized byte [] getVersionComponent() throws IOException { if (isSaved()) return _currentVersionComponent; return null; } /** * Returns the first segment number for this object. * @return The index of the first segment of stream data or null if no segments generated yet. */ public Long firstSegmentNumber() { if (null != _firstSegment) { return SegmentationProfile.getSegmentNumber(_firstSegment.name()); } else { return null; } } /** * Returns the digest of the first segment of this object which may be used * to help identify object instance unambiguously. * * @return The digest of the first segment of this object if available, null otherwise */ public byte[] getFirstDigest() { // Do not attempt to force update here to leave control over whether reading // or writing with the object creator. The return value may be null if the // object is not in a state of having a first segment if (null != _firstSegment) { return _firstSegment.digest(); } else { return null; } } /** * Returns the first segment of this object. */ public ContentObject getFirstSegment() { return _firstSegment; } /** * If we traversed a link to get this object, make it available. */ public synchronized LinkObject getDereferencedLink() { return _dereferencedLink; } /** * Use only if you know what you are doing. */ public synchronized void setDereferencedLink(LinkObject dereferencedLink) { _dereferencedLink = dereferencedLink; } /** * Add a LinkObject to the stack we had to dereference to get here. */ public synchronized void pushDereferencedLink(LinkObject dereferencedLink) { if (null == dereferencedLink) { return; } if (null != _dereferencedLink) { if (null != dereferencedLink.getDereferencedLink()) { if (Log.isLoggable(Log.FAC_IO, Level.WARNING)) { Log.warning(Log.FAC_IO, "Merging two link stacks -- {0} already has a dereferenced link from {1}. Behavior unpredictable.", dereferencedLink.getVersionedName(), dereferencedLink.getDereferencedLink().getVersionedName()); } } dereferencedLink.pushDereferencedLink(_dereferencedLink); } setDereferencedLink(dereferencedLink); } /** * If the object has been saved or read from the network, returns the (cached) versioned * name. Otherwise returns the base name. * @return */ public synchronized ContentName getVersionedName() { try { if (isSaved()) { if ((null == _currentVersionName) && (null != _currentVersionComponent)) // cache; only read lock necessary _currentVersionName = new ContentName(_baseName, _currentVersionComponent); return _currentVersionName; } return getBaseName(); } catch (IOException e) { if (Log.isLoggable(Log.FAC_IO, Level.WARNING)) Log.warning(Log.FAC_IO, "Invalid state for object {0}, cannot get current version name: {1}", getBaseName(), e); return getBaseName(); } } public synchronized PublisherPublicKeyDigest getContentPublisher() throws IOException { if (isSaved()) return _currentPublisher; return null; } public synchronized KeyLocator getPublisherKeyLocator() throws IOException { if (isSaved()) return _currentPublisherKeyLocator; return null; } /** * Change the publisher information we use when we sign commits to this object. * Takes effect on the next save(). Useful for objects created with a read constructor, * but who want to override default publisher information. * @param signingKey indicates the identity we want to use to sign future writes to this * object. If null, will default to key manager's (user's) default key. * @param locator the key locator (key lookup location) information to attach to future * writes to this object. If null, will be the default value associated with the * chosen signing key. */ public synchronized void setOurPublisherInformation(PublisherPublicKeyDigest publisherIdentity, KeyLocator keyLocator) { _publisher = publisherIdentity; _keyLocator = keyLocator; } public synchronized Interest handleContent(ContentObject co, Interest interest) { try { boolean hasNewVersion = false; byte [][] excludes = null; try { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent: " + _currentInterest + " retrieved " + co.name()); if (VersioningProfile.startsWithLaterVersionOf(co.name(), _currentInterest.name())) { // OK, we have something that is a later version of our desired object. // We're not sure it's actually the first content segment. hasNewVersion = true; if (VersioningProfile.isVersionedFirstSegment(_currentInterest.name(), co, null)) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: Background updating of {0}, got first segment: {1}", getVersionedName(), co.name()); // Streams assume caller has verified. So we verify here. // TODO add support for settable verifiers if (!_verifier.verify(co)) { if (Log.isLoggable(Log.FAC_SIGNING, Level.WARNING)) { Log.warning(Log.FAC_SIGNING, "CCNNetworkObject: content object received from background update did not verify! Ignoring object: {0}", co.fullName()); } hasNewVersion = false; // TODO -- exclude this one by digest, otherwise we're going // to get it back! For now, just copy the top-level part of GLV // behavior and exclude this version component. This isn't the right // answer, malicious objects can exclude new versions. But it's not clear // if the right answer is to do full gLV here and let that machinery // handle things, pulling potentially multiple objects in a callback, // or we just have to wait for issue #100011, and the ability to selectively // exclude content digests. excludes = new byte [][]{co.name().component(_currentInterest.name().count())}; if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent: got content for {0} that doesn't verify ({1}), excluding bogus version {2} as temporary workaround FIX WHEN POSSIBLE", _currentInterest.name(), co.fullName(), ContentName.componentPrintURI(excludes[0])); } else { update(co); } } else { // Have something that is not the first segment, like a repo write or a later segment. Go back // for first segment. ContentName latestVersionName = co.name().cut(_currentInterest.name().count() + 1); if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent (network object): Have version information, now querying first segment of {0}", latestVersionName); // This should verify the first segment when we get it. update(latestVersionName, co.signedInfo().getPublisherKeyID()); } } else { excludes = new byte [][]{co.name().component(_currentInterest.name().count() - 1)}; if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent: got content for {0} that doesn't match: {1}", _currentInterest.name(), co.name()); } } catch (IOException ex) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: Exception {0}: {1} attempting to update based on object : {2}", ex.getClass().getName(), ex.getMessage(), co.name()); // alright, that one didn't work, try to go on. } if (hasNewVersion) { if (_continuousUpdates) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent: got a new version, continuous updates, calling updateInBackground recursively then returning null."); updateInBackground(true); } else { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent: got a new version, not continuous updates, returning null."); _continuousUpdates = false; } // the updates above call newVersionAvailable return null; // implicit cancel of interest } else { if (null != excludes) { _currentInterest.exclude().add(excludes); } if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent: no new version, returning new interest for expression: {0}", _currentInterest); return _currentInterest; } } catch (IOException ex) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "updateInBackground: handleContent: Exception {0}: {1} attempting to request further updates : {2}", ex.getClass().getName(), ex.getMessage(), _currentInterest); return null; } } /** * Subclasses that need to write an object of a particular type can override. * DKS TODO -- verify type on read, modulo that ENCR overrides everything. * @return */ public ContentType contentType() { return ContentType.DATA; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((_baseName == null) ? 0 : _baseName.hashCode()); result = prime * result + ((_currentPublisher == null) ? 0 : _currentPublisher .hashCode()); result = prime * result + Arrays.hashCode(_currentVersionComponent); return result; } @SuppressWarnings("unchecked") // cast to obj<E> @Override public boolean equals(Object obj) { // should hold read lock? if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CCNNetworkObject<E> other = (CCNNetworkObject<E>) obj; if (_baseName == null) { if (other._baseName != null) return false; } else if (!_baseName.equals(other._baseName)) return false; if (_currentPublisher == null) { if (other._currentPublisher != null) return false; } else if (!_currentPublisher.equals(other._currentPublisher)) return false; if (!Arrays.equals(_currentVersionComponent, other._currentVersionComponent)) return false; return true; } @Override public String toString() { try { if (isSaved()) { return getVersionedName() + ": " + (isGone() ? "GONE" : "\nData:" + data()) + "\n Publisher: " + getContentPublisher() + "\n Publisher KeyLocator: " + getPublisherKeyLocator() + "\n"; } else if (available()) { return getBaseName() + " (unsaved): " + data(); } else { return getBaseName() + " (unsaved, no data)"; } } catch (IOException e) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "Unexpected exception retrieving object information: {0}", e); return getBaseName() + ": unexpected exception " + e; } } }
package org.frc1675; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { // For example to map the left and right motors, you could define the // following variables to use with your drivetrain subsystem. // public static final int leftMotor = 1; // public static final int rightMotor = 2; // If you are using multiple modules, make sure to define both the port // number and the module. For example you with a rangefinder: // public static final int rangefinderPort = 1; // public static final int rangefinderModule = 1; //motors public static final int FRONT_LEFT_DRIVE_MOTOR = 1; public static final int FRONT_RIGHT_DRIVE_MOTOR = 3; public static final int BACK_LEFT_DRIVE_MOTOR = 2; public static final int BACK_RIGHT_DRIVE_MOTOR = 4; public static final double FRONT_LEFT_DRIVE_POLARITY = 1.0; public static final double FRONT_RIGHT_DRIVE_POLARITY = -1.0; public static final double BACK_LEFT_DRIVE_POLARITY = 1.0; public static final double BACK_RIGHT_DRIVE_POLARITY = -1.0; public static final int SHOOTER_MOTOR = 5; //relays public static final int COMPRESSOR_SPIKE = 2; //sensors public static final int FRONT_LEFT_ENCODER_A = 1; public static final int FRONT_LEFT_ENCODER_B = 2; public static final int FRONT_RIGHT_ENCODER_A = 3; public static final int FRONT_RIGHT_ENCODER_B = 4; public static final int HIGH_PRESSURE_SWITCH = 5; public static final int LIGHTS_BIT_ONE = 8; public static final int LIGHTS_BIT_TWO = 9; public static final int LIGHTS_BIT_THREE = 10; //solenoids public static final int CLIMBER_EXTEND = 5; public static final int CLIMBER_RETRACT = 1; public static final int DUMPER_EXTEND = 6; public static final int DUMPER_RETRACT = 2; public static final int FOOT_EXTEND = 7; public static final int FOOT_RETRACT = 3; public static final int DUMPER_ANGLE_EXTEND = 8; public static final int DUMPER_ANGLE_RETRACT = 4; public static final double SOLENOID_ACTIVE_TIME = 0.1; //seconds public static final double DUMP_TIME = 1.7; //seconds //controllers and other stuff public static final int DRIVER_CONTROLLER = 1; public static final int OPERATOR_CONTROLLER = 2; public static final double DEADZONE_RADIUS = 0.15; //analog card public static final int PRESSURE_SENSOR = 4; public static final int DRIVE_GYRO = 2; public static final double VOLTS_PER_DEGREES_PER_SECONDS = 0.007; public static final double DRIVE_WHEEL_DIAMETER = 6; public static final double TANK_RAMP_TIME = .25; public static final double DRIVE_ENCODER_TICKS_PER_REV = 360.0; //PIDs public static final double GYRO_P = .004; public static final double GYRO_I = 0.0; public static final double GYRO_D = 0.0; public static final double ENCODER_P = .01; public static final double ENCODER_I = 0.0; public static final double ENCODER_D = 0.0; public static final int SHOOTER_MOTOR_ONE = 5; public static final int SHOOTER_MOTOR_TWO = 6; //light routines public static final int LIGHTS_OFF = 0; public static final int LIGHTS_EXTENDING = 1; public static final int LIGHTS_RETRACTING = 2; public static final int LIGHTS_SPAZZ_OUT = 3; }
package org.jcurvefever; public class Boot { public static void main(String[] args) { System.out.println("Hello World!"); } }
package org.loklak; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.eclipse.jetty.util.log.Log; import org.elasticsearch.search.sort.SortOrder; import org.loklak.api.client.HelloClient; import org.loklak.api.client.PushClient; import org.loklak.api.server.SuggestServlet; import org.loklak.data.DAO; import org.loklak.data.MessageEntry; import org.loklak.data.QueryEntry; import org.loklak.data.Timeline; import org.loklak.data.UserEntry; import org.loklak.harvester.TwitterAPI; import org.loklak.http.ClientConnection; import org.loklak.tools.DateParser; import org.loklak.tools.OS; import twitter4j.TwitterException; /** * The caretaker class is a concurrent thread which does peer-to-peer operations * and data transmission asynchronously. */ public class Caretaker extends Thread { private static final Random random = new Random(System.currentTimeMillis()); private boolean shallRun = true; public final static long startupTime = System.currentTimeMillis(); public final static long upgradeWait = DateParser.DAY_MILLIS; // 1 day public static long upgradeTime = startupTime + upgradeWait; public static BlockingQueue<Timeline> pushToBackendTimeline = new LinkedBlockingQueue<Timeline>(); public static BlockingQueue<Timeline> receivedFromPushTimeline = new LinkedBlockingQueue<Timeline>(); /** * ask the thread to shut down */ public void shutdown() { this.shallRun = false; this.interrupt(); Log.getLog().info("catched caretaker termination signal"); } @Override public void run() { // send a message to other peers that I am alive String[] remote = DAO.getConfig("backend", new String[0], ","); HelloClient.propagate(remote, (int) DAO.getConfig("port.http", 9000), (int) DAO.getConfig("port.https", 9443), (String) DAO.getConfig("peername", "anonymous")); // work loop while (this.shallRun) try { if (System.currentTimeMillis() > upgradeTime) { // increase the upgrade time to prevent that the peer runs amok (re-tries the attempt all the time) when upgrade fails for any reason upgradeTime = upgradeTime + upgradeWait; // do an upgrade DAO.log("UPGRADE: starting an upgrade"); upgrade(); DAO.log("UPGRADE: started an upgrade"); } // clear caches if (SuggestServlet.cache.size() > 100) SuggestServlet.cache.clear(); // dump timelines submitted by the peers long dumpstart = System.currentTimeMillis(); int[] newandknown = scheduledTimelineStorage(); long dumpfinish = System.currentTimeMillis(); if (newandknown[0] > 0 || newandknown[1] > 0) { DAO.log("dumped timelines from push api: " + newandknown[0] + " new, " + newandknown[1] + " known, storage time: " + (dumpfinish - dumpstart) + " ms"); } if (dumpfinish - dumpstart < 3000) { // sleep a bit to prevent that the DoS limit fires at backend server try {Thread.sleep(3000 - (dumpfinish - dumpstart));} catch (InterruptedException e) {} } DAO.log("connection pool: " + ClientConnection.cm.getTotalStats().toString()); // peer-to-peer operation Timeline tl = takeTimelineMin(pushToBackendTimeline, Timeline.Order.CREATED_AT, 200); if (!this.shallRun) break; if (tl != null && tl.size() > 0 && remote.length > 0) { // transmit the timeline long start = System.currentTimeMillis(); boolean success = PushClient.push(remote, tl); if (success) { DAO.log("success pushing " + tl.size() + " messages to backend in 1st attempt in " + (System.currentTimeMillis() - start) + " ms"); } if (!success) { // we should try again.. but not an infinite number because then // our timeline in RAM would fill up our RAM creating a memory leak retrylook: for (int retry = 0; retry < 5; retry++) { // give back-end time to recover try {Thread.sleep(3000 + retry * 3000);} catch (InterruptedException e) {} start = System.currentTimeMillis(); if (PushClient.push(remote, tl)) { DAO.log("success pushing " + tl.size() + " messages to backend in " + (retry + 2) + ". attempt in " + (System.currentTimeMillis() - start) + " ms"); success = true; break retrylook; } } if (!success) DAO.log("failed pushing " + tl.size() + " messages to backend"); } } // scan dump input directory to import files try { DAO.importAccountDumps(); DAO.importMessageDumps(); } catch (IOException e1) { e1.printStackTrace(); } // run some harvesting steps if (DAO.getConfig("retrieval.forbackend.enabled", false) && (DAO.getConfig("backend", "").length() > 0)) { for (int i = 0; i < 10; i++) { int count = Harvester.harvest(); if (count == -1) break; try {Thread.sleep(random.nextInt(200));} catch (InterruptedException e) {} } } // run some crawl steps for (int i = 0; i < 10; i++) { if (Crawler.process() == 0) break; // this may produce tweets for the timeline push try {Thread.sleep(random.nextInt(200));} catch (InterruptedException e) {} } // run searches if (DAO.getConfig("retrieval.queries.enabled", false)) { // execute some queries again: look out in the suggest database for queries with outdated due-time in field retrieval_next List<QueryEntry> queryList = DAO.SearchLocalQueries("", 10, "retrieval_next", "date", SortOrder.ASC, null, new Date(), "retrieval_next"); for (QueryEntry qe: queryList) { if (!acceptQuery4Retrieval(qe.getQuery())) { DAO.deleteQuery(qe.getQuery(), qe.getSourceType()); continue; } Timeline t = DAO.scrapeTwitter(null, qe.getQuery(), Timeline.Order.CREATED_AT, qe.getTimezoneOffset(), false, 10000, true); DAO.log("retrieval of " + t.size() + " new messages for q = \"" + qe.getQuery() + "\""); DAO.announceNewUserId(t); try {Thread.sleep(random.nextInt(200));} catch (InterruptedException e) {} } } // retrieve user data Set<Number> ids = DAO.getNewUserIdsChunk(); if (ids != null && DAO.getConfig("retrieval.user.enabled", false) && TwitterAPI.getAppTwitterFactory() != null) { try { TwitterAPI.getScreenName(ids, 10000, false); } catch (IOException | TwitterException e) { for (Number n: ids) DAO.announceNewUserId(n); // push back unread values if (e instanceof TwitterException) try {Thread.sleep(10000);} catch (InterruptedException ee) {} } } // heal the latency to give peers with out-dated information a new chance DAO.healLatency(0.95f); } catch (Throwable e) { Log.getLog().warn("CARETAKER THREAD", e); } Log.getLog().info("caretaker terminated"); } public static boolean acceptQuery4Retrieval(String q) { return q.length() > 1 && q.length() <=16 && q.indexOf(':') < 0; } /** * loklak upgrades itself if this is called */ public static void upgrade() { final File upgradeScript = new File(DAO.bin_dir.getAbsolutePath().replaceAll(" ", "\\ "), "upgrade.sh"); try { List<String> rsp = OS.execSynchronous(upgradeScript.getAbsolutePath()); for (String s: rsp) DAO.log("UPGRADE: " + s); } catch (IOException e) { DAO.log("UPGRADE failed: " + e.getMessage()); e.printStackTrace(); } } private int[] scheduledTimelineStorage() { Timeline tl; int newMessages = 0, knownMessages = 0; while (!receivedFromPushTimeline.isEmpty() && (tl = receivedFromPushTimeline.poll()) != null) { for (MessageEntry me: tl) { me.enrich(); // we enrich here again because the remote peer may have done this with an outdated version or not at all boolean stored = DAO.writeMessage(me, tl.getUser(me), true, true, true); if (stored) newMessages++; else knownMessages++; } } return new int[]{newMessages, knownMessages}; } public static void storeTimelineScheduler(Timeline tl) { try { receivedFromPushTimeline.put(tl); } catch (InterruptedException e) { e.printStackTrace(); } } public static void transmitTimelineToBackend(Timeline tl) { if (DAO.getConfig("backend", new String[0], ",").length > 0) pushToBackendTimeline.add(tl); } public static void transmitMessage(final MessageEntry tweet, final UserEntry user) { if (DAO.getConfig("backend", new String[0], ",").length <= 0) return; Timeline tl = pushToBackendTimeline.poll(); if (tl == null) tl = new Timeline(Timeline.Order.CREATED_AT); tl.add(tweet, user); pushToBackendTimeline.add(tl); } /** * if the given list of timelines contain at least the wanted minimum size of messages, they are flushed from the queue * and combined into a new timeline * @param dumptl * @param order * @param minsize * @return */ public static Timeline takeTimelineMin(final BlockingQueue<Timeline> dumptl, final Timeline.Order order, final int minsize) { int c = 0; for (Timeline tl: dumptl) c += tl.size(); if (c < minsize) return new Timeline(order); // now flush the timeline queue completely Timeline tl = new Timeline(order); try { while (dumptl.size() > 0) { Timeline tl0 = dumptl.take(); if (tl0 == null) return tl; tl.putAll(tl0); } return tl; } catch (InterruptedException e) { return tl; } } }
package org.apache.cordova.firebase; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.app.Notification; import android.text.TextUtils; import android.content.ContentResolver; import android.graphics.Color; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.util.Map; import java.util.Random; public class FirebasePluginMessagingService extends FirebaseMessagingService { private static final String TAG = "FirebasePlugin"; /** * Get a string from resources without importing the .R package * @param name Resource Name * @return Resource */ private String getStringResource(String name) { return this.getString( this.getResources().getIdentifier( name, "string", this.getPackageName())); } /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { // [START_EXCLUDE] // There are two types of messages data messages and notification messages. Data messages are handled // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app // is in the foreground. When the app is in the background an automatically generated notification is displayed. // When the user taps on the notification they are returned to the app. Messages containing both notification // and data payloads are treated as notification messages. The Firebase console always sends notification // [END_EXCLUDE] // TODO(developer): Handle FCM messages here. String title; String text; String id; String sound = null; String lights = null; Map<String, String> data = remoteMessage.getData(); if (remoteMessage.getNotification() != null) { title = remoteMessage.getNotification().getTitle(); text = remoteMessage.getNotification().getBody(); id = remoteMessage.getMessageId(); } else { title = data.get("title"); text = data.get("text"); id = data.get("id"); sound = data.get("sound"); lights = data.get("lights"); //String containing hex ARGB color, miliseconds on, miliseconds off, example: '#FFFF00FF,1000,3000' if(TextUtils.isEmpty(text)) text = data.get("body"); } if(TextUtils.isEmpty(id)){ Random rand = new Random(); int n = rand.nextInt(50) + 1; id = Integer.toString(n); } Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message id: " + id); Log.d(TAG, "Notification Message Title: " + title); Log.d(TAG, "Notification Message Body/Text: " + text); Log.d(TAG, "Notification Message Sound: " + sound); Log.d(TAG, "Notification Message Lights: " + lights); // TODO: Add option to developer to configure if show notification when app on foreground if (!TextUtils.isEmpty(text) || !TextUtils.isEmpty(title) || (!data.isEmpty())) { boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback()) && (!TextUtils.isEmpty(text) || !TextUtils.isEmpty(title)); sendNotification(id, title, text, data, showNotification, sound, lights); } } private void sendNotification(String id, String title, String messageBody, Map<String, String> data, boolean showNotification, String sound, String lights) { Bundle bundle = new Bundle(); for (String key : data.keySet()) { bundle.putString(key, data.get(key)); } if (showNotification) { Intent intent = new Intent(this, OnNotificationOpenReceiver.class); intent.putExtras(bundle); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT); String channelId = this.getStringResource("default_notification_channel_id"); String channelName = this.getStringResource("default_notification_channel_name"); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setContentTitle(title) .setContentText(messageBody) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody)) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); int resID = getResources().getIdentifier("notification_icon", "drawable", getPackageName()); if (resID != 0) { notificationBuilder.setSmallIcon(resID); } else { notificationBuilder.setSmallIcon(getApplicationInfo().icon); } if (sound != null) { Log.d(TAG, "sound before path is: " + sound); Uri soundPath = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/" + sound); Log.d(TAG, "Parsed sound is: " + soundPath.toString()); notificationBuilder.setSound(soundPath); } else { Log.d(TAG, "Sound was null "); } if(lights != null) { try { String[] lightsComponents = lights.replaceAll("\\s","").split(","); if(lightsComponents.length == 3) { int lightArgb = Color.parseColor(lightsComponents[0]); int lightOnMs = Integer.parseInt(lightsComponents[1]); int lightOffMs = Integer.parseInt(lightsComponents[2]); notificationBuilder.setLights(lightArgb, lightOnMs, lightOffMs); } }catch(Exception e){} } if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { int accentID = getResources().getIdentifier("accent", "color", getPackageName()); notificationBuilder.setColor(getResources().getColor(accentID, null)); } Notification notification = notificationBuilder.build(); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){ int iconID = android.R.id.icon; int notiID = getResources().getIdentifier("notification_big", "drawable", getPackageName()); if (notification.contentView != null) { notification.contentView.setImageViewResource(iconID, notiID); } } NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } notificationManager.notify(id.hashCode(), notification); } else { bundle.putBoolean("tap", false); bundle.putString("title", title); bundle.putString("body", messageBody); FirebasePlugin.sendNotification(bundle); } } }
package misc; import lombok.Getter; import java.awt.Dimension; public enum BlockSize { S6(6), S8(8), S10(10); /** The block size. */ @Getter private final Dimension blockSize; BlockSize(final int size) { if (size < 1) { throw new IllegalArgumentException("The size cannot be < 1."); } blockSize = new Dimension(size, size); } }
package com.airbnb.android.airmapview; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.text.TextUtils; /** * Use this class to request an AirMapView builder. */ public class DefaultAirMapViewBuilder { private boolean isGooglePlayServicesAvailable; private Context context; /** * Default {@link DefaultAirMapViewBuilder} constructor. * * @param context The application context. */ public DefaultAirMapViewBuilder(Context context) { this(GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS); this.context = context; } /** * @param isGooglePlayServicesAvailable Whether or not Google Play services is available on the * device. If you set this to true and it is not available, * bad things can happen. */ public DefaultAirMapViewBuilder(boolean isGooglePlayServicesAvailable) { this.isGooglePlayServicesAvailable = isGooglePlayServicesAvailable; } /** * Returns the first/default supported AirMapView implementation in order of preference, as * defined by {@link AirMapViewTypes}. */ public AirMapViewBuilder builder() { if (isGooglePlayServicesAvailable) { return new NativeAirMapViewBuilder(); } return getWebMapViewBuilder(); } /** * Returns the AirMapView implementation as requested by the mapType argument. Use this method if * you need to request a specific AirMapView implementation that is not necessarily the preferred * type. For example, you can use it to explicit request a web-based map implementation. * * @param mapType Map type for the requested AirMapView implementation. * @return An {@link AirMapViewBuilder} for the requested {@link AirMapViewTypes} mapType. */ public AirMapViewBuilder builder(AirMapViewTypes mapType) { switch (mapType) { case NATIVE: if (isGooglePlayServicesAvailable) { return new NativeAirMapViewBuilder(); } break; case WEB: return getWebMapViewBuilder(); } throw new UnsupportedOperationException("Requested map type is not supported"); } /** * Decides what the Map Web provider should be used and generates a builder for it. * * @return The AirMapViewBuilder for the selected Map Web provider. */ public AirMapViewBuilder getWebMapViewBuilder() { if (context != null) { try { ApplicationInfo ai = context.getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = ai.metaData; String accessToken = bundle.getString("com.mapbox.ACCESS_TOKEN"); String mapId = bundle.getString("com.mapbox.MAP_ID"); if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(mapId)) { return new MapboxWebMapViewBuilder(accessToken, mapId); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } return new WebAirMapViewBuilder(); } }
package com.github.aleksandrsavosh.simplestore; import android.app.Application; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.github.aleksandrsavosh.simplestore.exception.CreateException; import com.github.aleksandrsavosh.simplestore.exception.DataNotFoundException; import com.github.aleksandrsavosh.simplestore.exception.ReadException; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.*; public class SimpleStoreUtil { public static String getTableName(Class... clazzes){ TreeSet<String> names = new TreeSet<String>(); for(Class clazz : clazzes) { names.add(clazz.getSimpleName().toUpperCase()); } StringBuilder builder = new StringBuilder(); Iterator<String> it = names.iterator(); while (it.hasNext()){ String name = it.next(); builder.append(name); if(it.hasNext()){ builder.append("_"); } } return builder.toString(); } public static String getCreateTableQuery(Class<? extends Base> clazz) { final String lineSeparator = System.getProperty("line.separator"); Set<Field> fields = ReflectionUtil.getFields(clazz, Const.fields); fields.addAll(ReflectionUtil.getFields(clazz, Const.dataFields)); Iterator<Field> it = fields.iterator(); StringBuilder sb = new StringBuilder(lineSeparator + "CREATE TABLE " + getTableName(clazz) + " ( " + lineSeparator + "_id INTEGER primary key not null, " + lineSeparator + "cloudId TEXT, " + lineSeparator + "createdAt INTEGER, " + lineSeparator + "updatedAt INTEGER" + (it.hasNext()?", ":" ") + lineSeparator ); while(it.hasNext()){ Field field = it.next(); String name = field.getName(); String type; if(field.getType().equals(Integer.class) || field.getType().equals(Date.class) || field.getType().equals(Long.class)){ type = "INTEGER"; } else if(field.getType().equals(String.class)) { type = "TEXT"; } else if(field.getType().equals(byte[].class)) { type = "TEXT"; } else { throw new RuntimeException("Not supported type"); } sb.append(name + " " + type + " " + (it.hasNext()?", ":"") + lineSeparator); } sb.append(") "); return sb.toString(); } public static String getCreateRelationTableQuery(Class<? extends Base>... clazzes) { final String lineSeparator = System.getProperty("line.separator"); StringBuilder sb = new StringBuilder(lineSeparator + "CREATE TABLE IF NOT EXISTS" + getTableName(clazzes) + " ( " + lineSeparator + "_id INTEGER primary key not null, " + lineSeparator); for(int i = 0; i < clazzes.length; i++){ sb.append(getRelationTableColumn(clazzes[i]) + " INTEGER not null"); if(i + 1 == clazzes.length){ sb.append(lineSeparator); } else { sb.append(", " + lineSeparator); } } sb.append(")"); return sb.toString(); } public static String[] getRelationTableColumns(Class<? extends Base>... clazzes){ List<String> columns = new ArrayList<String>(); for(Class clazz : clazzes){ columns.add(getRelationTableColumn(clazz)); } return columns.toArray(new String[columns.size()]); } public static String getRelationTableColumn(Class clazz){ return clazz.getSimpleName().toLowerCase() + "_id"; } public static List<Base> getModelChildrenObjects(Base model) throws IllegalAccessException { List<Base> result = new ArrayList<Base>(); Class clazz = model.getClass(); for(Field field : ReflectionUtil.getFields(clazz, new HashSet<Class>(){{ addAll(Const.modelClasses); }})){ field.setAccessible(true); Base child = (Base) field.get(model); if(child != null){ result.add(child); } } for(Field field : ReflectionUtil.getFields(clazz, Const.collections)){// one to many field.setAccessible(true); Object collection = field.get(model); if(collection != null && collection instanceof Collection) { result.addAll((Collection<Base>) collection); } } return result; } public static <Model extends Base> String[] getColumns(Class<Model> clazz) { List<String> result = new ArrayList<String>(); result.add("_id"); result.add("cloudId"); result.add("createdAt"); result.add("updatedAt"); for(Field field : ReflectionUtil.getFields(clazz, Const.fields)){ result.add(field.getName()); } for(Field field : ReflectionUtil.getFields(clazz, Const.dataFields)){ result.add(field.getName()); } return result.toArray(new String[result.size()]); } /** * get columns where exists data file names */ public static String[] getDataColumns(Class clazz) { List<String> list = new ArrayList<String>(); for(Field field : ReflectionUtil.getFields(clazz, Const.dataFields)){ list.add(field.getName()); } return list.toArray(new String[list.size()]); } public static <Model extends Base> Model getModel(Cursor cursor, Class<? extends Base> clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, ReadException { Model model = (Model) clazz.getConstructor().newInstance(); model.setLocalId(cursor.getLong(cursor.getColumnIndex("_id"))); model.setCloudId(cursor.getString(cursor.getColumnIndex("cloudId"))); model.setCreatedAt(new java.sql.Date(cursor.getLong(cursor.getColumnIndex("createdAt")))); model.setUpdatedAt(new java.sql.Date(cursor.getLong(cursor.getColumnIndex("updatedAt")))); for(Field field : ReflectionUtil.getFields(clazz, Const.fields)){ field.setAccessible(true); Class type = field.getType(); if(type.equals(Integer.class)){ field.set(model, cursor.getInt(cursor.getColumnIndex(field.getName()))); } if(type.equals(Long.class)){ field.set(model, cursor.getLong(cursor.getColumnIndex(field.getName()))); } if(type.equals(String.class)){ field.set(model, cursor.getString(cursor.getColumnIndex(field.getName()))); } if(type.equals(Date.class)){ Date date = new java.sql.Date(cursor.getLong(cursor.getColumnIndex(field.getName()))); field.set(model, date); } } for(Field field : ReflectionUtil.getFields(clazz, Const.dataFields)){ field.setAccessible(true); String fileName = cursor.getString(cursor.getColumnIndex(field.getName())); if(fileName != null && fileName.length() > 0) { field.set(model, readFile(fileName)); } } return model; } public static <Model extends Base> ContentValues getContentValuesForUpdate(Model model) throws IllegalAccessException { ContentValues contentValues = getContentValuesForCreate(model); contentValues.remove("createdAt"); return contentValues; } public static <Model extends Base> ContentValues getContentValuesForCreate(final Model model) throws IllegalAccessException { ContentValues values = new ContentValues(); String cloudId = model.getCloudId(); if(cloudId == null){ values.putNull("cloudId"); } Date createdAt = model.getCreatedAt(); if(createdAt == null){ createdAt = new Date(); model.setCreatedAt(createdAt); } values.put("createdAt", createdAt.getTime()); Date updatedAt = model.getUpdatedAt(); if(updatedAt == null){ updatedAt = new Date(); model.setUpdatedAt(updatedAt); } values.put("updatedAt", updatedAt.getTime()); Set<Field> fields = ReflectionUtil.getFields(model.getClass(), Const.fields); for(Field field : fields){ field.setAccessible(true); String name = field.getName(); Object data = field.get(model); if(data == null){ values.putNull(name); continue; } if(data instanceof String){ values.put(name, (String) data); } if(data instanceof Integer){ values.put(name, (Integer) data); } if(data instanceof Long){ values.put(name, (Long) data); } if(data instanceof Date){ values.put(name, ((Date) data).getTime()); } } return values; } // public static ContentValues getContentValuesForRelationClasses(Base... classes) { // ContentValues contentValues = new ContentValues(); // for(Base base : classes){ // contentValues.put(base.getClass().getSimpleName() + "_id", base.getLocalId()); // return contentValues; public static ContentValues getContentValuesForRelationClasses(Long id, Class clazz, Long subId, Class subClazz) { ContentValues contentValues = new ContentValues(); contentValues.put(getRelationTableColumn(clazz), id); contentValues.put(getRelationTableColumn(subClazz), subId); return contentValues; } public static ContentValues getContentValuesForRelationClasses(Long id, Class clazz, Collection<Long> subIds, Class subClazz) { ContentValues contentValues = new ContentValues(); contentValues.put(getRelationTableColumn(clazz), id); for(Long subId : subIds) { contentValues.put(getRelationTableColumn(subClazz), subId); } return contentValues; } public static List<String> getAllRelationTableNames(SQLiteDatabase db, Class clazz){ String tableName = getTableName(clazz); //get all table names Cursor c = db.rawQuery( "SELECT name FROM sqlite_master " + "WHERE type='table' " + "and name like '%" + tableName + "%' " + "and name <> '" + tableName + "'", null); List<String> list = new ArrayList<String>(); //drop all tables if (c.moveToFirst()) { while ( !c.isAfterLast() ) { list.add(c.getString(0)); c.moveToNext(); } } c.close(); return list; } public static List<String> getTableNames(SQLiteDatabase db){ //get all table names Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null); List<String> list = new ArrayList<String>(); //drop all tables if (c.moveToFirst()) { while ( !c.isAfterLast() ) { list.add(c.getString(0)); c.moveToNext(); } } c.close(); return list; } /** * Get table data * @return list of lists where list.get(0) its column names */ public static List<List<String>> getTableData(SQLiteDatabase db, String table){ Cursor c = db.rawQuery("select * from " + table, null); List<List<String>> result = new ArrayList<List<String>>(); List<String> columnNames = new ArrayList<String>(Arrays.asList(c.getColumnNames())); result.add(columnNames); while(c.moveToNext()){ List<String> data = new ArrayList<String>(); for(int i = 0; i < columnNames.size(); i++){ String name = columnNames.get(i); int index = c.getColumnIndex(name); data.add(c.getString(index)); } result.add(data); } c.close(); return result; } public static String getSelectionFilter(KeyValue... keyValues) { StringBuilder builder = new StringBuilder(); for(int i = 0; i < keyValues.length; i++){ builder.append(keyValues[i].key); builder.append("=?"); if(i + 1 != keyValues.length){ builder.append(" and "); } } return builder.toString(); } public static String[] getSelectionFilterArguments(KeyValue... keyValues) { List<String> list = new ArrayList<String>(); for(int i = 0; i < keyValues.length; i++){ list.add(keyValues[i].value.toString()); } return list.toArray(new String[list.size()]); } public static void closeNoThrow(Closeable... closeables){ for(Closeable c : closeables){ try { if(c != null) { c.close(); } } catch (IOException e) { LogUtil.toLog("Close resource exception", e); } } } public static String createFile(byte[] bytes, String fileName) throws CreateException { Context context = SimpleStoreManager.instance.context; FileOutputStream outputStream = null; try { outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); outputStream.write(bytes); } catch (Exception e) { throw new CreateException(e); } finally { closeNoThrow(outputStream); } return fileName; } private static byte[] readFile(String fileName) throws ReadException { Context context = SimpleStoreManager.instance.context; File file = new File(context.getFilesDir(), fileName); if(!file.exists()){ throw new DataNotFoundException("File not found"); } byte[] result = new byte[(int) file.length()]; FileInputStream inputStream = null; DataInputStream dataInputStream = null; try { inputStream = context.openFileInput(fileName); dataInputStream = new DataInputStream(inputStream); dataInputStream.readFully(result); } catch (Exception e) { throw new ReadException(e); } finally { closeNoThrow(inputStream, dataInputStream); } return result; } /** * generate file name */ public static String getFileName(Class clazz, Field field) { return clazz.getSimpleName() + "_" + field.getName() + "_" + System.nanoTime(); } public static void deleteFile(String fileName) { Context context = SimpleStoreManager.instance.context; File file = new File(context.getFilesDir(), fileName); if(file.exists()){ file.delete(); } } static class A extends Base { } static class B extends Base { } static class C extends Base { private Integer integer; String str; public Date dat; A a = new A(); List<B> bs = new ArrayList<B>(){{ add(new B()); add(new B()); add(new B()); }}; } public static void main(String[] args) throws IllegalAccessException { Const.modelClasses = new HashSet<Class>(){{ add(A.class); add(B.class); add(C.class); }}; System.out.println(getModelChildrenObjects(new C()).size()); System.out.println(getCreateTableQuery(C.class)); System.out.println(getCreateRelationTableQuery(C.class, A.class)); System.out.println(getCreateRelationTableQuery(A.class, C.class)); System.out.println(Arrays.asList(getColumns(C.class))); } }
package liquibase.change.core; import liquibase.change.*; import liquibase.database.Database; import liquibase.snapshot.SnapshotGeneratorFactory; import liquibase.statement.SqlStatement; import liquibase.statement.core.AddUniqueConstraintStatement; import liquibase.structure.core.Column; import liquibase.structure.core.UniqueConstraint; /** * Adds a unique constraint to an existing column. */ @DatabaseChange(name="addUniqueConstraint", description = "Adds a unique constrant to an existing column or set of columns.", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "column") public class AddUniqueConstraintChange extends AbstractChange { private String catalogName; private String schemaName; private String tableName; private String columnNames; private String constraintName; private String tablespace; private Boolean deferrable; private Boolean initiallyDeferred; private Boolean disabled; private Boolean clustered; private String forIndexName; private String forIndexSchemaName; private String forIndexCatalogName; @DatabaseChangeProperty(mustEqualExisting ="column.relation.catalog", since = "3.0") public String getCatalogName() { return catalogName; } public void setCatalogName(String catalogName) { this.catalogName = catalogName; } @DatabaseChangeProperty(mustEqualExisting ="column.relation.schema") public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } @DatabaseChangeProperty(mustEqualExisting = "column.relation", description = "Name of the table to create the unique constraint on") public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } @DatabaseChangeProperty(mustEqualExisting = "column", description = "Name of the column(s) to create the unique constraint on. Comma separated if multiple") public String getColumnNames() { return columnNames; } public void setColumnNames(String columnNames) { this.columnNames = columnNames; } @DatabaseChangeProperty(description = "Name of the unique constraint") public String getConstraintName() { return constraintName; } public void setConstraintName(String constraintName) { this.constraintName = constraintName; } @DatabaseChangeProperty(description = "'Tablespace' to create the index in. Corresponds to file group in mssql") public String getTablespace() { return tablespace; } public void setTablespace(String tablespace) { this.tablespace = tablespace; } public Boolean getDeferrable() { return deferrable; } public void setDeferrable(Boolean deferrable) { this.deferrable = deferrable; } public Boolean getInitiallyDeferred() { return initiallyDeferred; } public void setInitiallyDeferred(Boolean initiallyDeferred) { this.initiallyDeferred = initiallyDeferred; } public Boolean getDisabled() { return disabled; } public void setDisabled(Boolean disabled) { this.disabled = disabled; } public Boolean getClustered() { return clustered; } public void setClustered(Boolean clustered) { this.clustered = clustered; } public String getForIndexName() { return forIndexName; } public void setForIndexName(String forIndexName) { this.forIndexName = forIndexName; } public String getForIndexSchemaName() { return forIndexSchemaName; } public void setForIndexSchemaName(String forIndexSchemaName) { this.forIndexSchemaName = forIndexSchemaName; } public String getForIndexCatalogName() { return forIndexCatalogName; } public void setForIndexCatalogName(String forIndexCatalogName) { this.forIndexCatalogName = forIndexCatalogName; } @Override public SqlStatement[] generateStatements(Database database) { //todo if (database instanceof SQLiteDatabase) { // // return special statements for SQLite databases // return generateStatementsForSQLiteDatabase(database); boolean deferrable = false; if (getDeferrable() != null) { deferrable = getDeferrable(); } boolean initiallyDeferred = false; if (getInitiallyDeferred() != null) { initiallyDeferred = getInitiallyDeferred(); } boolean disabled = false; if (getDisabled() != null) { disabled = getDisabled(); } boolean clustered = false; if (getClustered() != null) { clustered = getClustered(); } AddUniqueConstraintStatement statement = new AddUniqueConstraintStatement(getCatalogName(), getSchemaName(), getTableName(), ColumnConfig.arrayFromNames(getColumnNames()), getConstraintName()); statement.setTablespace(getTablespace()) .setDeferrable(deferrable) .setInitiallyDeferred(initiallyDeferred) .setDisabled(disabled) .setClustered(clustered); statement.setForIndexName(getForIndexName()); statement.setForIndexSchemaName(getForIndexSchemaName()); statement.setForIndexCatalogName(getForIndexCatalogName()); return new SqlStatement[] { statement }; } @Override public ChangeStatus checkStatus(Database database) { ChangeStatus result = new ChangeStatus(); try { UniqueConstraint example = new UniqueConstraint(getConstraintName(), getCatalogName(), getSchemaName(), getTableName(), Column.arrayFromNames(getColumnNames())); UniqueConstraint snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database); result.assertComplete(snapshot != null, "Unique constraint does not exist"); return result; } catch (Exception e) { return result.unknown(e); } } // private SqlStatement[] generateStatementsForSQLiteDatabase(Database database) { // // SQLite does not support this ALTER TABLE operation until now. // // This is a small work around... // List<SqlStatement> statements = new ArrayList<SqlStatement>(); // // define alter table logic // AlterTableVisitor rename_alter_visitor = new AlterTableVisitor() { // public ColumnConfig[] getColumnsToAdd() { // return new ColumnConfig[0]; // public boolean copyThisColumn(ColumnConfig column) { // return true; // public boolean createThisColumn(ColumnConfig column) { // String[] split_columns = getColumnNames().split("[ ]*,[ ]*"); // for (String split_column:split_columns) { // if (column.getName().equals(split_column)) { // column.getConstraints().setUnique(true); // return true; // public boolean createThisIndex(Index index) { // return true; // try { // // alter table // statements.addAll(SQLiteDatabase.getAlterTableStatements( // rename_alter_visitor, // database,getCatalogName(), getSchemaName(),getTableName())); // } catch (Exception e) { // e.printStackTrace(); // return statements.toArray(new SqlStatement[statements.size()]); @Override public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } @Override protected Change[] createInverses() { DropUniqueConstraintChange inverse = new DropUniqueConstraintChange(); inverse.setSchemaName(getSchemaName()); inverse.setTableName(getTableName()); inverse.setConstraintName(getConstraintName()); inverse.setUniqueColumns(getColumnNames()); return new Change[]{ inverse, }; } @Override public String getSerializedObjectNamespace() { return STANDARD_CHANGELOG_NAMESPACE; } }
package org.rdv.rbnb; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.rdv.data.DataChannel; import com.rbnb.sapi.ChannelTree; /** * A class to describe a channel containing data and the metadata associated with it. * * @author Jason P. Hanley * @since 1.1 */ public class Channel extends DataChannel { private Map<String, String> metadata; /** * Construct a channel with a name and assigning the mime type and * unit as metadata. * * @param node The channel tree metadata node * @param userMetadata The user metadata string (tab or comma delimited) * @since 1.3 */ public Channel(ChannelTree.Node node, String userMetadata) { super(node.getFullName()); metadata = new HashMap<String, String>(); String mime = node.getMime(); if (mime == null) { String channelName = getName(); if (channelName.endsWith(".jpg")) { mime = "image/jpeg"; } else if (channelName.contains("_Log/")) { mime = "text/plain"; } else { mime = "application/octet-stream"; } } metadata.put("mime", mime); metadata.put("start", Double.toString(node.getStart())); metadata.put("duration", Double.toString(node.getDuration())); metadata.put("size", Integer.toString(node.getSize())); if (userMetadata.length() > 0) { String[] userMetadataTokens = userMetadata.split("\t|,"); for (int j = 0; j < userMetadataTokens.length; j++) { String[] tokens = userMetadataTokens[j].split("="); if (tokens.length == 2) { metadata.put(tokens[0].trim(), tokens[1].trim()); } } } } /** * Get the short name of the channel. * * This is the part after the final forward slash (/). * * @return the short name of the channel * @since 1.1 */ public String getShortName() { return getName().substring(getName().lastIndexOf("/") + 1); } /** * Get the parent of the channel. * * This is the part before the final forward slash (/). * * @return the parent of the channel * @since 1.1 */ public String getParent() { return getName().substring(0, getName().lastIndexOf("/")); } /** * Return the metatadata string associated with the given key. * * @param key the key corresponding to the desired metadata string * @return the metadata string or null if the key was not found * @since 1.3 */ public String getMetadata(String key) { return (String) metadata.get(key); } /** * Return a string with the channel name and all metadata. * * @return a string representation of the channel and its metadata */ public String toString() { StringBuilder string = new StringBuilder(getName()); if (metadata.size() > 0) { string.append(": "); Set keys = metadata.keySet(); Iterator it = keys.iterator(); while (it.hasNext()) { String key = (String) it.next(); string.append(key + "=" + metadata.get(key)); if (it.hasNext()) { string.append(", "); } } } return string.toString(); } }
package tools.devnull.boteco.message; 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.function.Consumer; import java.util.function.Function; /** * A default implementation of a command extracted by a {@link CommandExtractor}. */ public class ExtractedCommand implements MessageCommand { private final IncomeMessage incomeMessage; private final String name; private final String rawArguments; private final Map<Class<?>, Function<String, ?>> functions; private final Map<String, Runnable> actions; private Consumer<String> defaultAction = (string) -> { }; public ExtractedCommand(IncomeMessage incomeMessage, String name, String rawArguments) { this.incomeMessage = incomeMessage; this.name = name; this.rawArguments = rawArguments; this.functions = new HashMap<>(); this.actions = new HashMap<>(); this.functions.put(String.class, Function.identity()); this.functions.put(Integer.class, Integer::parseInt); this.functions.put(int.class, Integer::parseInt); this.functions.put(Long.class, Long::parseLong); this.functions.put(long.class, Long::parseLong); this.functions.put(Double.class, Double::parseDouble); this.functions.put(double.class, Double::parseDouble); this.functions.put(List.class, string -> string.isEmpty() ? Collections.emptyList() : new ArrayList<>(Arrays.asList(string.split("\\s+"))) ); } @Override public String name() { return name; } @Override public <T> T as(Class<T> type) { return convert(rawArguments, type); } private <T> T convert(String string, Class<T> type) { Function<String, ?> function = functions.get(type); if (function == null) { function = new MessageCommandConverter<>(this.incomeMessage, type); } return (T) function.apply(string); } @Override public <T> MessageCommand on(String actionName, Class<T> parameterType, Consumer<T> consumer) { this.actions.put(actionName, () -> consumer.accept(convert(resolveParameterString(rawArguments), parameterType))); return this; } private String resolveParameterString(String string) { return string.contains(" ") ? string.replaceFirst("\\S+\\s", "").trim() : ""; } @Override public MessageCommand on(String actionName, Consumer<String> action) { return on(actionName, String.class, action); } @Override public MessageCommand on(String actionName, Runnable action) { this.actions.put(actionName, action); return this; } @Override public void orElse(Consumer<String> action) { this.defaultAction = action; execute(); } @Override public void orElseReturn(String message) { orElse((string) -> this.incomeMessage.reply(message)); execute(); } @Override public void execute() { String actionName = rawArguments.split("\\s+")[0]; if (this.actions.containsKey(actionName)) { this.actions.get(actionName).run(); } else { this.defaultAction.accept(rawArguments); } } }
package controllers; import io.mangoo.annotations.FilterWith; import io.mangoo.filters.AuthenticationFilter; import io.mangoo.filters.oauth.OAuthCallbackFilter; import io.mangoo.filters.oauth.OAuthLoginFilter; import io.mangoo.routing.Response; import io.mangoo.routing.bindings.Authentication; import io.mangoo.routing.bindings.Form; import io.mangoo.utils.CodecUtils; public class AuthenticationController { private static final String SECRET = "MyVoiceIsMySecret"; @FilterWith(AuthenticationFilter.class) public Response notauthenticated(Authentication authentication) { return Response.withOk() .andTextBody(authentication.getAuthenticatedUser()); } @FilterWith(OAuthLoginFilter.class) public Response login() { return Response.withOk().andEmptyBody(); } @FilterWith(OAuthCallbackFilter.class) public Response authenticate(Authentication authentication) { if (authentication.hasAuthenticatedUser()) { authentication.validLogin(authentication.getAuthenticatedUser(), "bar", CodecUtils.hexJBcrypt("bar")); return Response.withRedirect("/authenticationrequired"); } return Response.withOk().andEmptyBody(); } public Response doLogin(Authentication authentication) { authentication.validLogin("foo", "bar", CodecUtils.hexJBcrypt("bar")); return Response.withRedirect("/authenticationrequired"); } public Response doLoginTwoFactor(Authentication authentication) { authentication.validLogin("foo", "bar", CodecUtils.hexJBcrypt("bar")); authentication.twoFactorAuthentication(true); return Response.withRedirect("/"); } public Response factorize(Form form, Authentication authentication) { if (authentication.hasAuthenticatedUser() && authentication.validSecondFactor(SECRET, form.getInteger("twofactor").orElse(0))) { return Response.withRedirect("/authenticationrequired"); } return Response.withRedirect("/"); } public Response logout(Authentication authentication) { authentication.logout(); return Response.withOk().andEmptyBody(); } }
package org.apache.maven.plugin; import org.codehaus.plexus.compiler.Compiler; import org.codehaus.plexus.compiler.CompilerError; import org.codehaus.plexus.compiler.javac.JavacCompiler; import java.io.File; import java.util.Iterator; import java.util.List; /** * @goal test:compile * * @description Compiles test sources * * @prereq compiler:compile * * @parameter * name="sourceDirectory" * type="String" * required="true" * validator="" * expression="#project.build.unitTestSourceDirectory" * description="" * @parameter * name="outputDirectory" * type="String" * required="true" * validator="" * expression="#project.build.testOutput" * description="" * @parameter * name="classpathElements" * type="String[]" * required="true" * validator="" * expression="#project.classpathElements" * description="" * * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> * @version $Id$ * @todo use compile source roots and not the pom.build.sourceDirectory so that any * sort of preprocessing and/or source generation can be taken into consideration. */ public class TestCompilerMojo extends CompilerMojo { }
package org.apache.maven.plugin; import org.apache.maven.model.Resource; import org.codehaus.plexus.util.FileUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * * @author <a href="michal.maczka@dimatics.com">Michal Maczka</a> * @version $Id$ * * maven.jar.manifest.extensions.add * maven.jar.includes * maven.jar.excludes * maven.jar.index * maven.jar.compress * maven.remote.group * * @todo separate this into a resources plugin and jar plugin so that the resource * copying can be used as part of testing, right now the resources are being copied * directly into the JAR, need to make them available to testing. */ public class ResourcesPlugin { private String outputDirectory; private List resources; public void execute() throws Exception { for ( Iterator i = getJarResources( resources ).iterator(); i.hasNext(); ) { ResourceEntry resourceEntry = (ResourceEntry) i.next(); File destinationFile = new File( outputDirectory, resourceEntry.getDestination() ); if ( !destinationFile.getParentFile().exists() ) { destinationFile.getParentFile().mkdirs(); } fileCopy( resourceEntry.getSource(), destinationFile.getPath() ); } } private List getJarResources( List resources ) throws Exception { List resourceEntries = new ArrayList(); for ( Iterator i = resources.iterator(); i.hasNext(); ) { Resource resource = (Resource) i.next(); String targetPath = resource.getTargetPath(); File resourceDirectory = new File( resource.getDirectory() ); if ( !resourceDirectory.exists() ) { continue; } // If we only have a directory then we want to include // everything we can find within that path. String includes; if ( resource.getIncludes().size() > 0 ) { includes = listToString( resource.getIncludes() ); } else { includes = "**/**"; } List files = FileUtils.getFileNames( resourceDirectory, includes, listToString( resource.getExcludes() ), false ); for ( Iterator j = files.iterator(); j.hasNext(); ) { String name = (String) j.next(); String entryName = name; if ( targetPath != null ) { entryName = targetPath + "/" + name; } ResourceEntry je = new ResourceEntry( new File( resource.getDirectory(), name ).getPath(), entryName ); resourceEntries.add( je ); } } return resourceEntries; } private String listToString( List list ) { StringBuffer sb = new StringBuffer(); for ( int i = 0; i < list.size(); i++ ) { sb.append( list.get( i ) ); if ( i != list.size() - 1 ) { sb.append( "," ); } } return sb.toString(); } public static String fileRead( String fileName ) throws IOException { StringBuffer buf = new StringBuffer(); FileInputStream in = new FileInputStream( fileName ); int count; byte[] b = new byte[512]; while ( ( count = in.read( b ) ) > 0 ) // blocking read { buf.append( new String( b, 0, count ) ); } in.close(); return buf.toString(); } public static void fileWrite( String fileName, String data ) throws Exception { FileOutputStream out = new FileOutputStream( fileName ); out.write( data.getBytes() ); out.close(); } public static void fileCopy( String inFileName, String outFileName ) throws Exception { String content = fileRead( inFileName ); fileWrite( outFileName, content ); } class ResourceEntry { private String source; private String destination; public ResourceEntry( String source, String entry ) { this.source = source; this.destination = entry; } public String getSource() { return source; } public String getDestination() { return destination; } } }
package com.tqdev.metrics.jdbc; import static org.assertj.core.api.Assertions.assertThat; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import org.junit.Before; import org.junit.Test; /** * The Class InstrumentedDataSourceTest. */ public class InstrumentedDataSourceTest extends InstrumentedDataSourceTestBase { /** * Initialize by resetting the metric registry. */ @Before public void initialize() { registry.reset(); } @Test public void shouldMeasurePreparedStatement() throws SQLException { PreparedStatement statements[] = { dataSource.getConnection().prepareStatement("select"), dataSource.getConnection().prepareStatement("select", 1), dataSource.getConnection().prepareStatement("select", new int[] {}), dataSource.getConnection().prepareStatement("select", new String[] {}), dataSource.getConnection().prepareStatement("select", 1, 1), dataSource.getConnection().prepareStatement("select", 1, 1, 1) }; for (PreparedStatement statement : statements) { statement.execute(); statement.executeQuery(); statement.executeUpdate(); statement.executeLargeUpdate(); statement.addBatch(); statement.executeBatch(); statement.executeLargeBatch(); } assertThat(registry.get("jdbc.Statement.Invocations", "select")).isEqualTo(1L * 6 * statements.length); assertThat(registry.get("jdbc.Statement.Durations", "select")).isEqualTo(123456789L * 6 * statements.length); } @Test public void shouldMeasureCallableStatement() throws SQLException { CallableStatement statements[] = { dataSource.getConnection().prepareCall("select"), dataSource.getConnection().prepareCall("select", 1, 1), dataSource.getConnection().prepareCall("select", 1, 1, 1) }; for (CallableStatement statement : statements) { statement.execute(); statement.executeQuery(); statement.executeUpdate(); statement.executeLargeUpdate(); statement.addBatch(); statement.executeBatch(); statement.executeLargeBatch(); } assertThat(registry.get("jdbc.Statement.Invocations", "select")).isEqualTo(1L * 6 * statements.length); assertThat(registry.get("jdbc.Statement.Durations", "select")).isEqualTo(123456789L * 6 * statements.length); } @Test public void shouldMeasureStatement() throws SQLException { Statement statements[] = { dataSource.getConnection().createStatement(), dataSource.getConnection().createStatement(1, 1), dataSource.getConnection().createStatement(1, 1, 1) }; for (Statement statement : statements) { statement.execute("select"); statement.execute("select", 1); statement.execute("select", new int[] {}); statement.execute("select", new String[] {}); statement.executeQuery("select"); statement.executeUpdate("select"); statement.executeUpdate("select", 1); statement.executeUpdate("select", new int[] {}); statement.executeUpdate("select", new String[] {}); statement.executeLargeUpdate("select"); statement.executeLargeUpdate("select", 1); statement.executeLargeUpdate("select", new int[] {}); statement.executeLargeUpdate("select", new String[] {}); statement.addBatch("select"); statement.executeBatch(); statement.executeLargeBatch(); } assertThat(registry.get("jdbc.Statement.Invocations", "select")).isEqualTo(1L * 15 * statements.length); assertThat(registry.get("jdbc.Statement.Durations", "select")).isEqualTo(123456789L * 15 * statements.length); } }
package com.github.dreamhead.moco.parser.model; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.github.dreamhead.moco.Moco; import com.github.dreamhead.moco.MocoEventAction; import com.github.dreamhead.moco.resource.ContentResource; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import static com.github.dreamhead.moco.Moco.post; import static com.google.common.base.Optional.absent; import static com.google.common.base.Optional.of; @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public final class PostSetting { private TextContainer url; private TextContainer content; private Object json; public MocoEventAction createAction() { Optional<ContentResource> postContent = postContent(); if (postContent.isPresent()) { return post(this.url.asResource(), postContent.get()); } throw new IllegalArgumentException("content or json should be setup for post event"); } private Optional<ContentResource> postContent() { if (content != null) { return of(content.asResource()); } if (json != null) { return of(Moco.json(json)); } return absent(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("url", url) .add("content", content) .add("json", json) .toString(); } }
package org.cytoscape.model.internal; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import org.cytoscape.event.CyEventHelper; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkTableManager; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyTable; import org.cytoscape.model.CyTableFactory; import org.cytoscape.model.SavePolicy; import org.cytoscape.model.CyTableFactory.InitialTableSize; import org.cytoscape.model.SUIDFactory; import org.cytoscape.model.events.ColumnCreatedListener; import org.cytoscape.model.events.NetworkAddedEvent; import org.cytoscape.model.events.NetworkAddedListener; import org.cytoscape.model.events.RowsSetListener; import org.cytoscape.model.subnetwork.CyRootNetwork; import org.cytoscape.model.subnetwork.CySubNetwork; import org.cytoscape.service.util.CyServiceRegistrar; /** * A full implementation of CyRootNetwork. This implementation adds the support * for addNodes/addEdges that is missing from SimpleNetwork and provides support * for subnetworks. */ public final class CyRootNetworkImpl extends DefaultTablesNetwork implements CyRootNetwork { private final long suid; private SavePolicy savePolicy; private final List<CySubNetwork> subNetworks; private CySubNetwork base; private final CyTableManagerImpl tableMgr; private final CyNetworkTableManager networkTableMgr; private final CyTableFactory tableFactory; private final boolean publicTables; private final VirtualColumnAdder columnAdder; private final NameSetListener nameSetListener; private final InteractionSetListener interactionSetListener; private final NetworkAddedListenerDelegator networkAddedListenerDelegator; private final NetworkNameSetListener networkNameSetListener; private final CyServiceRegistrar serviceRegistrar; private int nextNodeIndex; private int nextEdgeIndex; public CyRootNetworkImpl(final CyEventHelper eh, final CyTableManagerImpl tableMgr, final CyNetworkTableManager networkTableMgr, final CyTableFactory tableFactory, final CyServiceRegistrar serviceRegistrar, final boolean publicTables, final SavePolicy savePolicy) { super(SUIDFactory.getNextSUID(), networkTableMgr, tableFactory,publicTables,0,eh); assert(savePolicy != null); this.tableMgr = tableMgr; this.networkTableMgr = networkTableMgr; this.tableFactory = tableFactory; this.serviceRegistrar = serviceRegistrar; this.publicTables = publicTables; this.savePolicy = savePolicy; suid = super.getSUID(); subNetworks = new ArrayList<CySubNetwork>(); nextNodeIndex = 0; nextEdgeIndex = 0; createRootNetworkTables(); initTables(this, (SharedTableFacade)(networkTableMgr.getTable(this, CyNetwork.class, CyRootNetwork.SHARED_DEFAULT_ATTRS)), (SharedTableFacade)(networkTableMgr.getTable(this, CyNode.class, CyRootNetwork.SHARED_DEFAULT_ATTRS)), (SharedTableFacade)(networkTableMgr.getTable(this, CyEdge.class, CyRootNetwork.SHARED_DEFAULT_ATTRS)) ); setRootNetworkTablePrivacy(); getRow(this).set(CyNetwork.NAME, ""); columnAdder = new VirtualColumnAdder(); serviceRegistrar.registerService(columnAdder, ColumnCreatedListener.class, new Properties()); nameSetListener = new NameSetListener(); serviceRegistrar.registerService(nameSetListener, RowsSetListener.class, new Properties()); interactionSetListener = new InteractionSetListener(); serviceRegistrar.registerService(interactionSetListener, RowsSetListener.class, new Properties()); networkAddedListenerDelegator = new NetworkAddedListenerDelegator(); serviceRegistrar.registerService(networkAddedListenerDelegator, NetworkAddedListener.class, new Properties()); networkNameSetListener = new NetworkNameSetListener(this); serviceRegistrar.registerService(networkNameSetListener, RowsSetListener.class, new Properties()); serviceRegistrar.registerService(networkNameSetListener, NetworkAddedListener.class, new Properties()); registerAllTables(networkTableMgr.getTables(this, CyNetwork.class).values()); registerAllTables(networkTableMgr.getTables(this, CyNode.class).values()); registerAllTables(networkTableMgr.getTables(this, CyEdge.class).values()); base = addSubNetwork(); } @Override public void dispose() { Map<String, CyTable> tableMap; serviceRegistrar.unregisterAllServices(columnAdder); serviceRegistrar.unregisterAllServices(nameSetListener); serviceRegistrar.unregisterAllServices(interactionSetListener); serviceRegistrar.unregisterAllServices(networkAddedListenerDelegator); serviceRegistrar.unregisterAllServices(networkNameSetListener); for (CySubNetwork network : subNetworks) { network.dispose(); } tableMap = networkTableMgr.getTables(this, CyNetwork.class); for (CyTable table : tableMap.values()) { tableMgr.deleteTableInternal(table.getSUID(), true); } tableMap = networkTableMgr.getTables(this, CyNode.class); for (CyTable table : tableMap.values()) { tableMgr.deleteTableInternal(table.getSUID(), true); } tableMap = networkTableMgr.getTables(this, CyEdge.class); for (CyTable table : tableMap.values()) { tableMgr.deleteTableInternal(table.getSUID(), true); } networkTableMgr.removeAllTables(this); } // Simply register all tables to the table manager private void registerAllTables(Collection<CyTable> tables) { for (final CyTable table : tables) tableMgr.addTable(table); } private void setRootNetworkTablePrivacy(){ this.getDefaultEdgeTable().setPublic(false); this.getDefaultNetworkTable().setPublic(false); this.getDefaultNodeTable().setPublic(false); } private void createRootNetworkTables() { final CyTable rawEdgeSharedTable = tableFactory.createTable(suid + " shared edge", CyIdentifiable.SUID, Long.class, false /*all root tables are private*/, false, getInitialTableSize(subNetworks.size())); final CyTable edgeSharedTable = new SharedTableFacade(rawEdgeSharedTable,this,CyEdge.class,networkTableMgr); edgeSharedTable.setPublic(false /*all root tables are private*/); networkTableMgr.setTable(this, CyEdge.class, CyRootNetwork.SHARED_ATTRS, rawEdgeSharedTable); networkTableMgr.setTable(this, CyEdge.class, CyRootNetwork.SHARED_DEFAULT_ATTRS, edgeSharedTable); edgeSharedTable.createColumn(CyRootNetwork.SHARED_NAME, String.class, true); edgeSharedTable.createColumn(CyRootNetwork.SHARED_INTERACTION, String.class, true); final CyTable rawNetworkSharedTable = tableFactory.createTable(suid + " shared network", CyIdentifiable.SUID, Long.class, false /*all root tables are private*/, false, InitialTableSize.SMALL); final CyTable networkSharedTable = new SharedTableFacade(rawNetworkSharedTable,this,CyNetwork.class,networkTableMgr); networkSharedTable.setPublic(false /*all root tables are private*/); networkTableMgr.setTable(this, CyNetwork.class, CyRootNetwork.SHARED_ATTRS, rawNetworkSharedTable); networkTableMgr.setTable(this, CyNetwork.class, CyRootNetwork.SHARED_DEFAULT_ATTRS, networkSharedTable); networkSharedTable.createColumn(CyRootNetwork.SHARED_NAME, String.class, true); final CyTable rawNodeSharedTable = tableFactory.createTable(suid + " shared node", CyIdentifiable.SUID, Long.class, false /*all root tables are private*/, false, getInitialTableSize(subNetworks.size())); final CyTable nodeSharedTable = new SharedTableFacade(rawNodeSharedTable,this,CyNode.class,networkTableMgr); nodeSharedTable.setPublic(false /*all root tables are private*/); networkTableMgr.setTable(this, CyNode.class, CyRootNetwork.SHARED_ATTRS, rawNodeSharedTable); networkTableMgr.setTable(this, CyNode.class, CyRootNetwork.SHARED_DEFAULT_ATTRS, nodeSharedTable); nodeSharedTable.createColumn(CyRootNetwork.SHARED_NAME, String.class, true); } private void linkDefaultTables(CyTable sharedTable, CyTable localTable) { // Add all columns from source table as virtual columns in target table. // localTable.addVirtualColumns(sharedTable, CyIdentifiable.SUID, true); // Now add a listener for column created events to add // virtual columns to any subsequent source columns added. // columnAdder.addInterestedTables(sharedTable,localTable); // Another listener tracks changes to the NAME column in local tables nameSetListener.addInterestedTables(localTable, sharedTable); } @Override public CyNode addNode() { final CyNode node; synchronized (this) { node = new CyNodeImpl( SUIDFactory.getNextSUID(), getNextNodeIndex(), eventHelper ); addNodeInternal( node ); } return node; } @Override public synchronized boolean removeNodes(final Collection<CyNode> nodes) { for ( CySubNetwork sub : subNetworks ) { sub.removeNodes(nodes); if (nodes != null && sub instanceof CySubNetworkImpl) ((CySubNetworkImpl) sub).removeRows(nodes, CyNode.class); } // Do we want to do this????? this.removeRows(nodes, CyNode.class); return removeNodesInternal(nodes); } @Override public CyEdge addEdge(final CyNode s, final CyNode t, final boolean directed) { final CyEdge edge; synchronized (this) { edge = new CyEdgeImpl(SUIDFactory.getNextSUID(), s, t, directed, getNextEdgeIndex()); addEdgeInternal(s,t, directed, edge); } return edge; } @Override public synchronized boolean removeEdges(final Collection<CyEdge> edges) { for ( CySubNetwork sub : subNetworks ) { sub.removeEdges(edges); if (edges != null && sub instanceof CySubNetworkImpl) ((CySubNetworkImpl) sub).removeRows(edges, CyEdge.class); } return removeEdgesInternal(edges); } @Override public CySubNetwork addSubNetwork(final Iterable<CyNode> nodes, final Iterable<CyEdge> edges) { return addSubNetwork(nodes, edges, savePolicy); } @Override public CySubNetwork addSubNetwork(final Iterable<CyNode> nodes, final Iterable<CyEdge> edges, final SavePolicy policy) { // Only addSubNetwork() modifies the internal state of CyRootNetworkImpl (this object), // so because it's synchronized, we don't need to synchronize this method. final CySubNetwork sub = addSubNetwork(policy); if (nodes != null) for (CyNode n : nodes) sub.addNode(n); if (edges != null) for (CyEdge e : edges) sub.addEdge(e); return sub; } @Override public synchronized CySubNetwork addSubNetwork() { return addSubNetwork(savePolicy); } @Override public synchronized CySubNetwork addSubNetwork(SavePolicy policy) { if (policy == null) policy = savePolicy; if (savePolicy == SavePolicy.DO_NOT_SAVE && policy != savePolicy) throw new IllegalArgumentException("Cannot create subnetwork with \"" + policy + "\" save policy, because this root network's policy is \"DO_NOT_SAVE\"."); // Subnetwork's ID final long newSUID = SUIDFactory.getNextSUID(); final CySubNetworkImpl sub = new CySubNetworkImpl(this, newSUID, eventHelper, tableMgr, networkTableMgr, tableFactory, publicTables, subNetworks.size(), policy); networkAddedListenerDelegator.addListener(sub); subNetworks.add(sub); nameSetListener.addInterestedTables(sub.getDefaultNetworkTable(),networkTableMgr.getTable(this, CyNetwork.class, CyRootNetwork.SHARED_DEFAULT_ATTRS)); nameSetListener.addInterestedTables(sub.getDefaultNodeTable(),networkTableMgr.getTable(this, CyNode.class, CyRootNetwork.SHARED_DEFAULT_ATTRS)); nameSetListener.addInterestedTables(sub.getDefaultEdgeTable(),networkTableMgr.getTable(this, CyEdge.class, CyRootNetwork.SHARED_DEFAULT_ATTRS)); interactionSetListener.addInterestedTables(sub.getDefaultEdgeTable(), networkTableMgr.getTable(this, CyEdge.class, CyRootNetwork.SHARED_DEFAULT_ATTRS)); return sub; } @Override public synchronized void removeSubNetwork(final CySubNetwork sub) { if (sub == null) return; if (!subNetworks.contains(sub)) throw new IllegalArgumentException("Subnetwork not a member of this RootNetwork " + sub); if (sub.equals(base)) { if (subNetworks.size() == 1) throw new IllegalArgumentException( "Can't remove base network from RootNetwork because it's the only subnetwork"); // Chose another base network CySubNetwork oldBase = base; for (CySubNetwork n : subNetworks) { if (!n.equals(oldBase)) { base = n; // Better if the new base network is one that can be saved if (n.getSavePolicy() == SavePolicy.SESSION_FILE) break; } } } // clean up pointers for nodes in subnetwork sub.removeNodes(sub.getNodeList()); Map<String, CyTable> tableMap; tableMap = networkTableMgr.getTables(sub, CyNetwork.class); for (CyTable table : tableMap.values()) { tableMgr.deleteTableInternal(table.getSUID(), true); } tableMap = networkTableMgr.getTables(sub, CyNode.class); for (CyTable table : tableMap.values()) { tableMgr.deleteTableInternal(table.getSUID(), true); } tableMap = networkTableMgr.getTables(sub, CyEdge.class); for (CyTable table : tableMap.values()) { tableMgr.deleteTableInternal(table.getSUID(), true); } subNetworks.remove(sub); sub.dispose(); } @Override public List<CySubNetwork> getSubNetworkList() { return Collections.synchronizedList(subNetworks); } @Override public CySubNetwork getBaseNetwork() { return base; } @Override public CyTable getSharedNetworkTable() { return networkTableMgr.getTable(this, CyNetwork.class, CyRootNetwork.SHARED_DEFAULT_ATTRS); } @Override public CyTable getSharedNodeTable() { return networkTableMgr.getTable(this, CyNode.class, CyRootNetwork.SHARED_DEFAULT_ATTRS); } @Override public CyTable getSharedEdgeTable() { return networkTableMgr.getTable(this, CyEdge.class, CyRootNetwork.SHARED_DEFAULT_ATTRS); } @Override public synchronized boolean containsNetwork(final CyNetwork net) { return subNetworks.contains(net); } @Override public SavePolicy getSavePolicy() { return savePolicy; } @Override public boolean equals(final Object o) { if (!(o instanceof CyRootNetworkImpl)) return false; return super.equals(o); } @Override public String toString() { String name = null; try { name = getRow(this).get(NAME, String.class); } catch (NullPointerException e) { name = "(unavailable)"; } return name; } private synchronized int getNextNodeIndex() { return nextNodeIndex++; } private synchronized int getNextEdgeIndex() { return nextEdgeIndex++; } private class NetworkAddedListenerDelegator implements NetworkAddedListener { List<WeakReference<NetworkAddedListener>> listeners = new ArrayList<WeakReference<NetworkAddedListener>>(); public void addListener(NetworkAddedListener l) { listeners.add(new WeakReference<NetworkAddedListener>(l)); } public void handleEvent(NetworkAddedEvent e) { for (WeakReference<NetworkAddedListener> ref : listeners) { final NetworkAddedListener l = ref.get(); if ( l != null ) l.handleEvent(e); } } } }
package eu.scape_project.watch.interfaces; import java.util.List; import java.util.Map; import eu.scape_project.watch.domain.Entity; import eu.scape_project.watch.domain.Property; import eu.scape_project.watch.domain.PropertyValue; import eu.scape_project.watch.utils.ConfigParameter; import eu.scape_project.watch.utils.exceptions.InvalidParameterException; import eu.scape_project.watch.utils.exceptions.PluginException; /** * An adaptor plugin interface that each source adaptor has to implement. It * provides the basic agreement between Scout's core and the adaptors. In * general, the adaptors act like iterators over their own source. It is up to * the specific implementation to decide, whether the values will fetched at * once and cached or fetched on demand. * * @author Petar Petrov <me@petarpetrov.org> * */ public interface AdaptorPluginInterface extends PluginInterface { /** * Retrieves a list with {@link ConfigParameter} objects needed/supported by * this plugin. Note the not all config parameters have to be requried ( * {@link ConfigParameter#isRequired()} ) * * @return the list with the parameters. */ List<ConfigParameter> getParameters(); /** * Returns a pre-polulated map with the configuration of this plugin. The keys * are the config parameters and the values are the config values. The plugin * can provide default values, but is not expected to. * * @return the config of the plugin. */ Map<String, String> getParameterValues(); /** * Sets the config parameters. * * @param values * sets the values. * @throws InvalidParameterException * if some required parameters are not provided, or other problems * occur. */ void setParameterValues(Map<String, String> values) throws InvalidParameterException; /** * To be removed in version 0.0.4. Executes this plugin and returns a specific * {@link ResultInterface} implementation. The execution has to be done * according to the current parameter setting. * * @param config * the configuration map. Determines what should be fetched upon * execution. * @return the result of the execution. * @throws PluginException * if an error occurs. */ @Deprecated ResultInterface execute(Map<Entity, List<Property>> config) throws PluginException; /** * To be removed in version 0.0.4. Fetches all information that this adaptor * can obtain from the source. To be used carefully as this can be a lot of * data that is transfered over the network. Consider using a push adaptor. * * @return the result of the operation. * @throws PluginException * if an error occurrs. */ @Deprecated ResultInterface execute() throws PluginException; /** * Checks with the source whether there is more info to be fetched. If there * is the method returns true, false otherwise. Note that the method might * call the source and even fetch and chache some results. * * @return true if there are more results to be fetched, false otherwise. * @throws PluginException * if an error occurs. */ boolean hasNext() throws PluginException; /** * This method retrieves the next measurement result ( {@link PropertyValue}, * {@link Property}, {@link Entity} ). This method might return null. It is in * the clients responsibility of this class to make sure that there is a next * result by calling the {@link AdaptorPluginInterface#hasNext()} method. * * @return the result. * @see ResultInterface */ ResultInterface next(); /** * This method retrieves the id of an adaptor plugin. For each adaptor plugin * instance there will be a unique id created. * @return adaptor plugin id */ String getId(); }
package com.haulmont.cuba.gui.data.impl; import com.haulmont.chile.core.model.Instance; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.utils.InstanceUtils; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.entity.Versioned; import com.haulmont.cuba.gui.TemplateHelper; import com.haulmont.cuba.gui.UserSessionClient; import com.haulmont.cuba.gui.data.*; import com.haulmont.cuba.gui.xml.ParametersHelper; import org.apache.commons.lang.ObjectUtils; import java.util.*; public class AbstractCollectionDatasource<T extends Entity, K> extends DatasourceImpl<T> { protected String query; protected ParametersHelper.ParameterInfo[] queryParameters; public AbstractCollectionDatasource(DsContext dsContext, DataService dataservice, String id, MetaClass metaClass, String viewName) { super(dsContext, dataservice, id, metaClass, viewName); } @Override public CommitMode getCommitMode() { return CommitMode.DATASTORE; } @Override public synchronized void setItem(T item) { if (State.VALID.equals(state)) { Object prevItem = this.item; final MetaClass metaClass = getMetaClass(); final Class javaClass = metaClass.getJavaClass(); if (!ObjectUtils.equals(prevItem, item) || (Versioned.class.isAssignableFrom(javaClass)) && !ObjectUtils.equals( prevItem == null ? null : ((Versioned) prevItem).getVersion(), item == null ? null : ((Versioned) item).getVersion())) { if (this.item != null) { detatchListener((Instance) this.item); } if (item instanceof Instance) { final MetaClass aClass = ((Instance) item).getMetaClass(); if (!aClass.equals(this.metaClass)) { throw new IllegalStateException(String.format("Invalid item metaClass")); } attachListener((Instance) item); } this.item = item; forceItemChanged(prevItem); } } } public String getQuery() { return query; } public synchronized void setQuery(String query) { if (!ObjectUtils.equals(this.query, query)) { this.query = query; invalidate(); queryParameters = ParametersHelper.parseQuery(query); for (ParametersHelper.ParameterInfo info : queryParameters) { final ParametersHelper.ParameterInfo.Type type = info.getType(); if (ParametersHelper.ParameterInfo.Type.DATASOURCE.equals(type)) { final String path = info.getPath(); final String[] strings = path.split("\\."); String source = strings[0]; final String property; if (strings.length > 1) { final List<String> list = Arrays.asList(strings); final List<String> valuePath = list.subList(1, list.size()); property = InstanceUtils.formatValuePath(valuePath.toArray(new String[valuePath.size()])); } else { property = null; } final Datasource ds = dsContext.get(source); if (ds != null) { dsContext.regirterDependency(this, ds, property); } else { ((DsContextImplementation) dsContext).addLazyTask(new DsContextImplementation.LazyTask() { public void execute(DsContext context) { final String[] strings = path.split("\\."); String source = strings[0]; final Datasource ds = dsContext.get(source); if (ds != null) { dsContext.regirterDependency(AbstractCollectionDatasource.this, ds, property); } } }); } } } } } protected Map<String, Object> getQueryParameters(Map<String, Object> params) { final Map<String, Object> map = new HashMap<String, Object>(); for (ParametersHelper.ParameterInfo info : queryParameters) { String name = info.getFlatName(); final String path = info.getPath(); final String[] elements = path.split("\\."); switch (info.getType()) { case DATASOURCE: { final Datasource datasource = dsContext.get(elements[0]); if (State.VALID.equals(datasource.getState())) { final Entity item = datasource.getItem(); if (elements.length > 1) { final List<String> list = Arrays.asList(elements); final List<String> valuePath = list.subList(1, list.size()); final String propertyName = InstanceUtils.formatValuePath(valuePath.toArray(new String[valuePath.size()])); map.put(name, InstanceUtils.getValueEx((Instance) item, propertyName)); } else { map.put(name, item); } } else { map.put(name, null); } break; } case PARAM: { final Object value = dsContext.getWindowContext() == null ? null : dsContext.getWindowContext().getParameterValue(path); map.put(name, value); break; } case COMPONENT: { final Object value = dsContext.getWindowContext() == null ? null : dsContext.getWindowContext().getValue(path); map.put(name, value); break; } case SESSION: { final Object value; if ("userId".equals(name)) value = UserSessionClient.getUserSession().getUserId(); else value = UserSessionClient.getUserSession().getAttribute(path); map.put(name, value); break; } case CUSTOM: { map.put(name, params.get(info.getName())); break; } default: { throw new UnsupportedOperationException("Unsupported parameter type: " + info.getType()); } } } return map; } protected String getJPQLQuery(String query, Map<String, Object> parameterValues) { for (ParametersHelper.ParameterInfo info : queryParameters) { final String paramName = info.getName(); final String jpaParamName = info.getFlatName(); query = query.replaceAll(paramName.replaceAll("\\$", "\\\\\\$"), jpaParamName); } query = TemplateHelper.processTemplate(query, parameterValues); return query; } protected void forceCollectionChanged(CollectionDatasourceListener.CollectionOperation operation) { for (DatasourceListener dsListener : new ArrayList<DatasourceListener>(dsListeners)) { if (dsListener instanceof CollectionDatasourceListener) { ((CollectionDatasourceListener) dsListener).collectionChanged(this, operation); } } } }
package markehme.factionsplus.Cmds; import markehme.factionsplus.FactionsPlus; import markehme.factionsplus.FactionsPlusTemplates; import markehme.factionsplus.MCore.LConf; import markehme.factionsplus.config.OldConfig; import markehme.factionsplus.util.FPPerm; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.massivecraft.factions.Rel; import com.massivecraft.factions.cmd.req.ReqFactionsEnabled; import com.massivecraft.factions.entity.UPlayer; import com.massivecraft.mcore.cmd.req.ReqHasPerm; import com.massivecraft.mcore.cmd.req.ReqIsPlayer; import com.massivecraft.mcore.util.Txt; public class CmdFactionNeed extends FPCommand { public CmdFactionNeed() { this.aliases.add("need"); this.fpidentifier = "need"; this.errorOnToManyArgs = false; this.addRequirements(ReqFactionsEnabled.get()); this.addRequirements(ReqIsPlayer.get()); this.addRequirements(ReqHasPerm.get(FPPerm.NEED.node)); this.setHelp(LConf.get().cmdDescFactionNeed); this.setDesc(LConf.get().cmdDescFactionNeed); } @Override public void performfp() { if(usender.hasFaction()) { msg(Txt.parse(LConf.get().factionNeedAlreadyHaveFaction)); return; } // TODO: Move this into a thread // TODO: Cooldown? // TODO: Allow certain Factions to ignore these messages ( /f needs ignore | /f needs listen ) int i = 0; for(Player p : Bukkit.getServer().getOnlinePlayers()) { if(UPlayer.get(p).getRole() == Rel.LEADER || UPlayer.get(p).getRole() == Rel.OFFICER) { if(!FactionsPlus.permission.has(p, "factionsplus.ignoreneeds")) { i++; p.sendMessage(Txt.parse(LConf.get().factionNeedNotification, sender.getName(), sender.getName())); } } } if(i == 0) { // Notify the player that no one received the need request msg(Txt.parse(LConf.get().factionNeedClarifyNoneSent)); } else { // Notify player that they received the need request msg(Txt.parse(LConf.get().factionNeedClarifySent)); } } }
package com.haulmont.cuba.gui.xml.layout.loaders; import com.haulmont.bali.util.Dom4j; import com.haulmont.bali.util.ReflectionHelper; import com.haulmont.cuba.core.global.MessageProvider; import com.haulmont.cuba.core.global.Scripting; import com.haulmont.cuba.core.global.ScriptingProvider; import com.haulmont.cuba.gui.AppConfig; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.xml.layout.ComponentsFactory; import com.haulmont.cuba.gui.xml.layout.LayoutLoaderConfig; import groovy.lang.Binding; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.dom4j.Element; import java.util.*; public class AccessControlLoader extends ContainerLoader { private static final Set<String> enabledActions = new HashSet<String>() {{ add("excel"); add("windowclose"); add("cancel"); }}; /** * If actionId contains <key> then action.caption will be replaced with message <value> * key - string, containing in action Id * value - message name. */ private static final HashMap<String, String> renamingActions = new HashMap<String, String>(){{ put("edit","actions.View"); }}; public AccessControlLoader(Context context, LayoutLoaderConfig config, ComponentsFactory factory) { super(context, config, factory); } public Component loadComponent(ComponentsFactory factory, Element element, Component parent) throws InstantiationException, IllegalAccessException { AccessControl accessControl = factory.createComponent(element.getName()); final AbstractAccessData data; String paramName = element.attributeValue("param"); if (paramName != null) { AbstractAccessData d = (AbstractAccessData) context.getParams().get(paramName); if (d == null) { String dataClassName = element.attributeValue("data"); if (dataClassName == null) throw new IllegalStateException("Can not instantiate AccessData: no 'data' attribute"); Class dataClass = ScriptingProvider.loadClass(dataClassName); if (dataClass == null) throw new IllegalStateException("Class not found: " + dataClassName); try { data = (AbstractAccessData) ReflectionHelper.newInstance(dataClass, context.getParams()); context.getParams().put(paramName, data); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } else { data = d; } } else { data = null; } final boolean visible = loadConditions(element, data, "visible"); final boolean editable = loadConditions(element, data, "editable"); Collection<Component> components; if (visible) { components = loadSubComponents(parent, element, "editable", "visible"); for (Component component : components) { applyToComponent(component, editable, data, components); if (component instanceof Component.Container) { Collection<Component> content = ((Component.Container) component).getComponents(); for (Component c : content) { applyToComponent(c, editable, data, content); } } } } else { components = Collections.EMPTY_LIST; } accessControl.setRealComponents(components); return accessControl; } protected void applyToComponent(Component component, boolean editable, AbstractAccessData data, Collection<Component> components) { if (component instanceof Component.Editable && !editable) { ((Component.Editable) component).setEditable(false); } if ((component instanceof Button || component instanceof PopupButton) && !editable) { context.addPostInitTask(new AccessControlLoaderPostInitTask(component)); } if (component instanceof Component.HasButtonsPanel && !editable) { ButtonsPanel buttonsPanel = ((Component.HasButtonsPanel) component).getButtonsPanel(); if (buttonsPanel != null) { Collection<Component> buttons = new ArrayList<Component>(buttonsPanel.getButtons()); for (Component button : buttons) { applyToComponent(button, editable, data, buttons); } } } if (data != null) { data.visitComponent(component, components); } } private boolean loadConditions(Element element, Object accessData, String access) { Element accessElement = element.element(access); if (accessElement == null) return true; if (accessData != null) { String property = accessElement.attributeValue("property"); if (!StringUtils.isBlank(property)) { Boolean value; try { value = ReflectionHelper.invokeMethod(accessData, "get" + StringUtils.capitalize(property)); } catch (NoSuchMethodException e) { try { value = ReflectionHelper.invokeMethod(accessData, "is" + StringUtils.capitalize(property)); } catch (NoSuchMethodException e1) { throw new RuntimeException(e1); } } return BooleanUtils.isTrue(value); } } String script = accessElement.getText(); if (!StringUtils.isBlank(script)) { return BooleanUtils.isTrue( ScriptingProvider.<Boolean>evaluateGroovy(script, context.getBinding())); } else { String scriptName = accessElement.attributeValue("script"); if (!StringUtils.isBlank(scriptName)) { Binding binding = new Binding(); for (Map.Entry<String, Object> entry : context.getParams().entrySet()) { String name = entry.getKey().replace('$', '_'); binding.setVariable(name, entry.getValue()); } for (Element paramElem : Dom4j.elements(accessElement, "param")) { String paramName = paramElem.attributeValue("name"); String paramValue = paramElem.getText(); binding.setVariable(paramName, paramValue); } return BooleanUtils.isTrue( ScriptingProvider.<Boolean>runGroovyScript(scriptName, binding)); } } return true; } private static class AccessControlLoaderPostInitTask implements PostInitTask { private final Component component; public AccessControlLoaderPostInitTask(Component component) { this.component = component; } public void execute(Context context, IFrame window) { final String messagesPackage = AppConfig.getMessagesPack(); component.setEnabled(false); if (component instanceof Component.ActionOwner) { Action action = ((Component.ActionOwner) component).getAction(); if (action != null) { if (renamingActions.containsKey(action.getId().toLowerCase())) { action.setEnabled(true); ((Button) component).setCaption(MessageProvider.getMessage(messagesPackage, renamingActions.get(action.getId().toLowerCase()))); } else if (enabledActions.contains(action.getId().toLowerCase())) { action.setEnabled(true); } else { action.setEnabled(false); } } } } } }
package me.coley.recaf.ui.component; import java.util.Collections; import java.util.Optional; import org.controlsfx.control.PropertySheet.Item; import org.controlsfx.property.editor.PropertyEditor; import org.fxmisc.richtext.CodeArea; import org.fxmisc.richtext.LineNumberFactory; import org.fxmisc.richtext.model.TwoDimensional.Bias; import org.fxmisc.richtext.model.TwoDimensional.Position; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.image.Image; import javafx.scene.input.MouseButton; import javafx.scene.layout.HBox; import jregex.Matcher; import jregex.Pattern; import me.coley.recaf.Input; import me.coley.recaf.Logging; import me.coley.recaf.bytecode.Asm; import me.coley.recaf.bytecode.search.Parameter; import me.coley.recaf.event.*; import me.coley.recaf.parse.CodeInfo; import me.coley.recaf.parse.MemberNode; import me.coley.recaf.ui.*; import me.coley.recaf.util.*; import me.coley.event.Bus; import me.coley.event.Listener; import me.coley.memcompiler.Compiler; import me.coley.memcompiler.JavaXCompiler; /** * Item for decompiling classes / methods. * * @author Matt */ public class DecompileItem implements Item { //@formatter:off private static final String[] KEYWORDS = new String[] { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while" }; private static final String KEYWORD_PATTERN = "\\b(" + String.join("|", KEYWORDS) + ")\\b"; private static final String STRING_PATTERN = "\"([^\"\\\\]|\\\\.)*\""; private static final String CONST_HEX_PATTERN = "(0[xX][0-9a-fA-F]+)+"; private static final String CONST_VAL_PATTERN = "(\\b([\\d._]*[\\d])\\b)+|(true|false|null)"; private static final String CONST_PATTERN = CONST_HEX_PATTERN + "|" + CONST_VAL_PATTERN; private static final String COMMENT_SINGLE_PATTERN = " private static final String COMMENT_MULTI_SINGLE_PATTERN = "/[*](.|\n|\r)+?\\*/"; private static final String COMMENT_MULTI_JAVADOC_PATTERN = "/[*]{2}(.|\n|\r)+?\\*/"; private static final String ANNOTATION_PATTERN = "\\B(@[\\w]+)\\b"; private static final Pattern PATTERN = new Pattern( "({COMMENTDOC}" + COMMENT_MULTI_JAVADOC_PATTERN + ")" + "|({COMMENTMULTI}" + COMMENT_MULTI_SINGLE_PATTERN + ")" + "|({COMMENTLINE}" + COMMENT_SINGLE_PATTERN + ")" + "|({KEYWORD}" + KEYWORD_PATTERN + ")" + "|({STRING}" + STRING_PATTERN + ")" + "|({ANNOTATION}" + ANNOTATION_PATTERN + ")" + "|({CONSTPATTERN}" + CONST_PATTERN + ")"); //@formatter:on /** * Class to decompile. */ private final ClassNode cn; /** * Optional: Method to decompile. If not {@code null} then only this method * is decompiled. */ private final MethodNode mn; public DecompileItem(ClassNode cn) { this(cn, null); } public DecompileItem(ClassNode cn, MethodNode mn) { this.mn = mn; this.cn = cn; } /** * Create new stage with decompiled text. */ public void decompile() { // Create decompilation area CFRPipeline pipe = new CFRPipeline(cn, mn); FxDecompile code = new FxDecompile(pipe); code.show(); } /** * Currently unused since recompiling from method-only decompile is already * unsupported <i>(for now)</i>. * * @param cn * Node to extract method from. * @return ClassNode containing only the {@link #mn target method}. */ @SuppressWarnings("unused") private ClassNode strip(ClassNode cn) { ClassNode copy = new ClassNode(); copy.visit(cn.version, cn.access, cn.name, cn.signature, cn.superName, cn.interfaces.stream().toArray(String[]::new)); copy.methods.add(mn); return copy; } /* boiler-plate for displaying button that opens the stage. */ @Override public Optional<Class<? extends PropertyEditor<?>>> getPropertyEditorClass() { return JavaFX.optional(DecompileButton.class); } @Override public Class<?> getType() { return Object.class; } @Override public String getCategory() { return Lang.get("ui.bean.class"); } @Override public String getName() { return Lang.get("ui.bean.class.decompile.name"); } @Override public String getDescription() { return Lang.get("ui.bean.class.decompile.desc"); } @Override public Object getValue() { return null; } @Override public void setValue(Object value) {} @Override public Optional<ObservableValue<? extends Object>> getObservableValue() { return JavaFX.optionalObserved(null); } public class FxDecompile extends FxCode { /** * Code analysis results of the current decompiled code. */ private CodeInfo info; /** * Title postfix. */ private final String postfix; /** * Flag marking ability to use the recompilation functions. */ private boolean canCompile; /** * Current context menu instance. */ private ContextMenu ctx; /** * Selected item. */ private Object selection; /** * CFR decompiler pipeline. */ private CFRPipeline cfrPipe; public FxDecompile(CFRPipeline pipe) { super(pipe.decompile()); this.postfix = pipe.getTitlePostfix(); this.cfrPipe = pipe; } @Override protected void setupCodePane(String initialText) { // Setup info BEFORE anything else. this.info = new CodeInfo(cn, this); // setup code-pane super.setupCodePane(initialText); // Add line numbers. code.setParagraphGraphicFactory(LineNumberFactory.get(code)); // Setup context menu ctx = new ContextMenu(); ctx.getStyleClass().add("code-context-menu"); code.setContextMenu(ctx); // Add caret listener, updates what is currently selected. // This data will be used to populate the context menu. code.caretPositionProperty().addListener((obs, old, cur) -> { if (info.hasRegions()) { Position pos = code.offsetToPosition(cur, Bias.Backward); int line = pos.getMajor() + 1; int column = pos.getMinor() + 1; info.updateContextMenu(line, column); } }); code.setOnMouseClicked(value -> { if (value.getButton() == MouseButton.SECONDARY) { // Context menu's code is UGLY, but it will look nice... // Worth it. ctx.getItems().clear(); HBox box = new HBox(); if (canCompile) { // Add recompile option if supported box.getChildren().add(FormatFactory.raw(Lang.get("ui.bean.class.recompile.name"))); ctx.getItems().add(new ActionMenuItem("", box, () -> recompile(code))); } // Add other options if there is a selected item. if (selection == null) return; box = new HBox(); // Verify that the selection is in the Input. // If so, allow the user to quickly jump to its definition. boolean allowEdit = true; if (selection instanceof ClassNode) { String owner = ((ClassNode) selection).name; allowEdit = Input.get().classes.contains(owner); } else if (selection instanceof MemberNode) { String owner = ((MemberNode) selection).getOwner().name; allowEdit = Input.get().classes.contains(owner); } if (allowEdit) { if (selection instanceof ClassNode) { ClassNode cn = (ClassNode) selection; box.getChildren().add(Icons.getClassExtended(cn.access)); box.getChildren().add(FormatFactory.raw(" " + Lang.get("misc.edit") + " ")); box.getChildren().add(FormatFactory.type(Type.getType("L" + cn.name + ";"))); ctx.getItems().add(new ActionMenuItem("", box, () -> Bus.post(new ClassOpenEvent(cn)))); } else if (selection instanceof MemberNode) { MemberNode mn = (MemberNode) selection; Type type = Type.getType(mn.getDesc()); box.getChildren().add(Icons.getMember(mn.getAccess(), mn.isMethod())); box.getChildren().add(FormatFactory.raw(" " + Lang.get("misc.edit") + " ")); if (mn.isMethod()) { HBox typeBox = FormatFactory.typeMethod(type); Node retTypeNode = typeBox.getChildren().remove(typeBox.getChildren().size() - 1); box.getChildren().add(retTypeNode); box.getChildren().add(FormatFactory.raw(" ")); box.getChildren().add(FormatFactory.name(mn.getName())); box.getChildren().add(typeBox); ctx.getItems().add(new ActionMenuItem("", box, () -> Bus.post(new MethodOpenEvent(mn.getOwner(), mn.getMethod(), null)))); } else { box.getChildren().add(FormatFactory.type(type)); box.getChildren().add(FormatFactory.raw(" ")); box.getChildren().add(FormatFactory.name(mn.getName())); ctx.getItems().add(new ActionMenuItem("", box, () -> Bus.post(new FieldOpenEvent(mn.getOwner(), mn .getField(), null)))); } } } // Reference search box = new HBox(); box.getChildren().add(FormatFactory.raw(Lang.get("ui.edit.method.search"))); if (selection instanceof ClassNode) { ClassNode owner = (ClassNode) selection; ctx.getItems().add(new ActionMenuItem("", box, () -> FxSearch.open(Parameter.references(owner.name, null, null)))); } else if (selection instanceof MemberNode) { MemberNode mn = (MemberNode) selection; ClassNode owner = mn.getOwner(); ctx.getItems().add(new ActionMenuItem("", box, () -> FxSearch.open(Parameter.references(owner.name, mn .getName(), mn.getDesc())))); } } }); // Different functionality depending on if an entire class is being // analyzed or if its just a single method. if (mn == null) { // Allow recompilation if user is running on a JDK and is // working on // an entire class. if (Misc.canCompile()) { code.setEditable(true); canCompile = true; } else { Logging.info("Recompilation unsupported. Did not detect proper JDK classes."); } } else { // If we're focusing on a single method then allow the code to // be updated as the user redefines the code. Bus.subscribe(this); setOnCloseRequest(e -> { // Remove subscriptions on close Bus.unsubscribe(this); }); } } @Listener private void onClassDirty(ClassDirtyEvent event) { // Skip over class changes that aren't of the current class if (!event.getNode().name.equals(cn.name)) return; // While this will cause decompilation to be executed even on edits // that may not affect the output, making a MethodDirtyEvent will // require introducing a large amount of ugly boilerplate code. So // for the sake of keeping the spaghetti down, this minor // inefficiency is fine. Threads.run(() -> { String text = cfrPipe.decompile(); Threads.runFx(() -> { code.clear(); code.appendText(text); }); }); } @Override protected String createTitle() { return Lang.get("ui.bean.class.decompile.name") + ": " + postfix; } @Override protected Image createIcon() { return Icons.CL_CLASS; } @Override protected Pattern createPattern() { return PATTERN; } @Override protected String getStyleClass(Matcher matcher) { //@formatter:off return matcher.group("STRING") != null ? "string" : matcher.group("KEYWORD") != null ? "keyword" : matcher.group("COMMENTDOC") != null ? "comment-javadoc" : matcher.group("COMMENTMULTI") != null ? "comment-multi" : matcher.group("COMMENTLINE") != null ? "comment-line" : matcher.group("CONSTPATTERN") != null ? "const" : matcher.group("ANNOTATION") != null ? "annotation" : null; //@formatter:on } /** * Uses the decompiled code to recompile. */ private void recompile(CodeArea codeText) { try { String srcText = codeText.getText(); // TODO: For dependencies in agent-mode the jar/classes // should be fetched from the class-path. Compiler compiler = new JavaXCompiler(); if (Input.get().input != null) { compiler.setClassPath(Collections.singletonList(Input.get().input.getAbsolutePath())); } else { // TODO: Add instrumented classpath } compiler.getDebug().sourceName = true; compiler.getDebug().lineNumbers = true; compiler.getDebug().variables = true; compiler.addUnit(cn.name.replace("/", "."), srcText); if (mn != null) { Logging.error("Single-method recompilation unsupported, please decompile the full class"); return; } compiler.setCompileListener(msg -> Logging.error(msg.toString())); if (!compiler.compile()) { Logging.error("Could not recompile!"); return; } // Iterate over compiled units. This will include inner classes // and the like. for (String unit : compiler.getUnitNames()) { byte[] code = compiler.getUnitCode(unit); ClassNode newValue = Asm.getNode(code); Input.get().getClasses().put(cn.name, newValue); Logging.info("Recompiled '" + cn.name + "' - size:" + code.length, 1); Bus.post(new ClassRecompileEvent(cn, newValue)); } } catch (Exception e) { Logging.error(e); } } @Override protected void onCodeChange(String code) { if (mn == null) { info.update(code); } } /** * Called when the user's caret moves into the range of a recognized * type. * * @param cn * Type recognized. */ public void updateSelection(ClassNode cn) { selection = cn; } /** * Called when the user's caret moves into the range of a recognized * member. * * @param mn * Member recognized. */ public void updateSelection(MemberNode mn) { selection = mn; } /** * Reset selected item. */ public void resetSelection() { selection = null; if (!canCompile) { code.setContextMenu(null); } } } /** * Button to pop up decopilation window. * * @author Matt */ public static class DecompileButton implements PropertyEditor<Object> { private final DecompileItem item; public DecompileButton(Item item) { this.item = (DecompileItem) item; } @Override public Node getEditor() { Button button = new Button(Lang.get("ui.bean.class.decompile.name")); button.setOnAction(e -> item.decompile()); return button; } @Override public Object getValue() { return null; } @Override public void setValue(Object value) {} } }
package net.anotheria.moskito.core.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.TimerTask; import org.apache.commons.lang.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.anotheria.moskito.core.accumulation.Accumulators; import net.anotheria.moskito.core.predefined.OSStats; import net.anotheria.moskito.core.producers.IStats; import net.anotheria.moskito.core.producers.IStatsProducer; import net.anotheria.moskito.core.registry.ProducerRegistryFactory; /** * Builtin producer for values supplied by jmx for the operation system. * * @author lrosenberg */ public class BuiltInOSProducer extends AbstractBuiltInProducer implements IStatsProducer, BuiltInProducer { /** * Associated stats. */ private OSStats stats; /** * Stats container */ private List<IStats> statsList; /** * The monitored pool. */ private OperatingSystemMXBean mxBean; /** * Name of the mxbean class. */ private static final String clazzname = "com.sun.management.UnixOperatingSystemMXBean"; /** * Resolved class of the mx bean. */ private Class<?> clazz; /** The Constant BITS_TO_BYTES_FACTOR. */ private static final int BITS_TO_BYTES_FACTOR = 1024; /** * If true indicates. */ private final boolean isUnixOS = SystemUtils.IS_OS_UNIX; private final boolean isWindowsOS = SystemUtils.IS_OS_WINDOWS; /** * Logger. */ private static Logger log = LoggerFactory.getLogger(BuiltInOSProducer.class); public BuiltInOSProducer() { mxBean = ManagementFactory.getOperatingSystemMXBean(); statsList = new ArrayList<IStats>(1); stats = new OSStats(); statsList.add(stats); try { clazz = Class.forName(clazzname); } catch (ClassNotFoundException e) { log.warn("Couldn't find unix version of os class: " + clazzname + ", osstats won't operate properly - " + e.getMessage()); } if (!isUnixOS) { log.warn("Couldn't find unix version of os class: " + clazzname + ", osstats won't operate properly for all stats. Current type is: " + mxBean.getClass().getName()); } BuiltinUpdater.addTask(new TimerTask() { @Override public void run() { readMbean(); } }); ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(this); Accumulators.setupCPUAccumulators(); } @Override public String getCategory() { return "os"; } @Override public String getProducerId() { return "OS"; } @Override public List<IStats> getStats() { return statsList; } /** * Reads the management bean and extracts monitored data on regular base. */ private void readMbean() { if (clazz == null) { return; } try { if (isUnixOS) { long openFiles = getValue("OpenFileDescriptorCount"); long maxOpenFiles = getValue("MaxFileDescriptorCount"); long freePhysicalMemorySize = getValue("FreePhysicalMemorySize"); long totalPhysicalMemorySize = getValue("TotalPhysicalMemorySize"); long processTime = getValue("ProcessCpuTime"); double processCPULoad = getDoubleValue("ProcessCpuLoad"); double systemCPULoad = getDoubleValue("SystemCpuLoad"); long processors = getValue("AvailableProcessors"); stats.update((int) openFiles, (int) maxOpenFiles, freePhysicalMemorySize, totalPhysicalMemorySize, processTime, (int) processors, processCPULoad, systemCPULoad); } else if (isWindowsOS) { long processors = getValue("AvailableProcessors"); double systemCPULoad = readWindowsCPULoad(); long totalPhysicalMemorySize = readWindowsTotalMemory(); long freePhysicalMemorySize = readWindowsFreeMemory(); stats.update(-1, -1, freePhysicalMemorySize, totalPhysicalMemorySize, -1, (int) processors, -1, systemCPULoad); } else { long processors = getValue("AvailableProcessors"); stats.update(-1, -1, -1, -1, -1, (int) processors, -1, -1); } } catch (Exception e) { log.warn("Couldn't read value due to", e); } } private long getValue(String name) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method m = clazz.getMethod("get" + name); if (name.equals("AvailableProcessors")) return (Integer) m.invoke(mxBean); Long result = (Long) m.invoke(mxBean); return result; } private double getDoubleValue(String name) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method m = clazz.getMethod("get" + name); Double result = (Double) m.invoke(mxBean); return result; } public static void main(String[] a) { new BuiltInOSProducer(); } private static long readWindowsTotalMemory() { Long result = 0L; try { String[] command = "wmic OS get TotalVisibleMemorySize /Value".split(" "); String line = executeMemoryInfoProcess(command); // Output should be something like 'TotalVisibleMemorySize=8225260' result = Long.parseLong(line.substring(line.indexOf("=") + 1)) * BITS_TO_BYTES_FACTOR; // convert it to bytes } catch (Exception e) { log.error("unable to get TotalVisibleMemorySize from wmic", e); } return result.longValue(); } private static long readWindowsFreeMemory() { Long result = 0L; try { String[] command = "wmic OS get FreePhysicalMemory /Value".split(" "); String line = executeMemoryInfoProcess(command); // Output should be something like 'FreePhysicalMemory=8225260' result = Long.parseLong(line.substring(line.indexOf("=") + 1)) * BITS_TO_BYTES_FACTOR; // convert it to bytes } catch (Exception e) { log.error("unable to get FreePhysicalMemory from wmic", e); } return result.longValue(); } private static double readWindowsCPULoad() { Double result = 0d; try { String[] command = "wmic cpu get LoadPercentage /Value".split(" "); String line = executeMemoryInfoProcess(command); // Output should be something like 'LoadPercentage=27' result = Double.parseDouble(line.substring(line.indexOf("=") + 1)); } catch (Exception e) { log.error("unable to get LoadPercentage from wmic", e); } return result.doubleValue(); } private static String executeMemoryInfoProcess(String... command) throws IOException { ProcessBuilder procBuilder = new ProcessBuilder(command); Process process = procBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { String line; while ((line = br.readLine()) != null) { if (line.trim().isEmpty()) { continue; } return line; } } catch (IOException e1) { throw e1; } finally { br.close(); } throw new IOException("Could not read memory process output for command " + command); } }
package com.ebay.web.cors; import java.util.Enumeration; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; public class TestConfigs { public static final String HTTPS_WWW_APACHE_ORG = "https: public static final String HTTP_TOMCAT_APACHE_ORG = "http://tomcat.apache.org"; public static final String EXPOSED_HEADERS = "X-CUSTOM-HEADER"; /** * Any origin */ public static final String ANY_ORIGIN = "*"; public static FilterConfig getDefaultFilterConfig() { final String allowedHttpHeaders = CORSConfiguration.DEFAULT_ALLOWED_HTTP_HEADERS; final String allowedHttpMethods = CORSConfiguration.DEFAULT_ALLOWED_HTTP_METHODS; final String allowedOrigins = CORSConfiguration.DEFAULT_ALLOWED_ORIGINS; final String exposedHeaders = CORSConfiguration.DEFAULT_EXPOSED_HEADERS; final String supportCredentials = CORSConfiguration.DEFAULT_SUPPORTS_CREDENTIALS; final String preflightMaxAge = CORSConfiguration.DEFAULT_PREFLIGHT_MAXAGE; return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods, allowedOrigins, exposedHeaders, supportCredentials, preflightMaxAge); } public static FilterConfig getFilterConfigAnyOriginAndSupportsCredentials() { final String allowedHttpHeaders = CORSConfiguration.DEFAULT_ALLOWED_HTTP_HEADERS; final String allowedHttpMethods = CORSConfiguration.DEFAULT_ALLOWED_HTTP_METHODS; final String allowedOrigins = CORSConfiguration.DEFAULT_ALLOWED_ORIGINS; final String exposedHeaders = CORSConfiguration.DEFAULT_EXPOSED_HEADERS; final String supportCredentials = "true"; final String preflightMaxAge = CORSConfiguration.DEFAULT_PREFLIGHT_MAXAGE; return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods, allowedOrigins, exposedHeaders, supportCredentials, preflightMaxAge); } public static FilterConfig getFilterConfigWithExposedHeaders() { final String allowedHttpHeaders = CORSConfiguration.DEFAULT_ALLOWED_HTTP_HEADERS; final String allowedHttpMethods = CORSConfiguration.DEFAULT_ALLOWED_HTTP_METHODS; final String allowedOrigins = CORSConfiguration.DEFAULT_ALLOWED_ORIGINS; final String exposedHeaders = EXPOSED_HEADERS; final String supportCredentials = CORSConfiguration.DEFAULT_SUPPORTS_CREDENTIALS; final String preflightMaxAge = CORSConfiguration.DEFAULT_PREFLIGHT_MAXAGE; return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods, allowedOrigins, exposedHeaders, supportCredentials, preflightMaxAge); } public static FilterConfig getSecureFilterConfig() { final String allowedHttpHeaders = CORSConfiguration.DEFAULT_ALLOWED_HTTP_HEADERS; final String allowedHttpMethods = CORSConfiguration.DEFAULT_ALLOWED_HTTP_METHODS+",PUT"; final String allowedOrigins = HTTPS_WWW_APACHE_ORG; final String exposedHeaders = CORSConfiguration.DEFAULT_EXPOSED_HEADERS; final String supportCredentials = "true"; final String preflightMaxAge = CORSConfiguration.DEFAULT_PREFLIGHT_MAXAGE; return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods, allowedOrigins, exposedHeaders, supportCredentials, preflightMaxAge); } public static FilterConfig getSpecificOriginFilterConfig() { final String allowedOrigins = HTTPS_WWW_APACHE_ORG + "," + HTTP_TOMCAT_APACHE_ORG; final String allowedHttpHeaders = CORSConfiguration.DEFAULT_ALLOWED_HTTP_HEADERS; final String allowedHttpMethods = CORSConfiguration.DEFAULT_ALLOWED_HTTP_METHODS + ",PUT"; final String exposedHeaders = CORSConfiguration.DEFAULT_EXPOSED_HEADERS; final String supportCredentials = CORSConfiguration.DEFAULT_SUPPORTS_CREDENTIALS; final String preflightMaxAge = CORSConfiguration.DEFAULT_PREFLIGHT_MAXAGE; return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods, allowedOrigins, exposedHeaders, supportCredentials, preflightMaxAge); } public static FilterConfig getFilterConfigInvalidMaxPreflightAge() { final String allowedHttpHeaders = CORSConfiguration.DEFAULT_ALLOWED_HTTP_HEADERS; final String allowedHttpMethods = CORSConfiguration.DEFAULT_ALLOWED_HTTP_METHODS; final String allowedOrigins = CORSConfiguration.DEFAULT_ALLOWED_ORIGINS; final String exposedHeaders = CORSConfiguration.DEFAULT_EXPOSED_HEADERS; final String supportCredentials = CORSConfiguration.DEFAULT_SUPPORTS_CREDENTIALS; final String preflightMaxAge = "abc"; return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods, allowedOrigins, exposedHeaders, supportCredentials, preflightMaxAge); } public static FilterConfig getEmptyFilterConfig() { final String allowedHttpHeaders = ""; final String allowedHttpMethods = ""; final String allowedOrigins = ""; final String exposedHeaders = ""; final String supportCredentials = ""; final String preflightMaxAge = ""; return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods, allowedOrigins, exposedHeaders, supportCredentials, preflightMaxAge); } private static FilterConfig generateFilterConfig( final String allowedHttpHeaders, final String allowedHttpMethods, final String allowedOrigins, final String exposedHeaders, final String supportCredentials, final String preflightMaxAge) { FilterConfig filterConfig = new FilterConfig() { public String getFilterName() { return "cors-filter"; } public ServletContext getServletContext() { return null; } public String getInitParameter(String name) { if (CORSConfiguration.PARAM_CORS_ALLOWED_HEADERS .equalsIgnoreCase(name)) { return allowedHttpHeaders; } else if (CORSConfiguration.PARAM_CORS_ALLOWED_METHODS .equalsIgnoreCase(name)) { return allowedHttpMethods; } else if (CORSConfiguration.PARAM_CORS_ALLOWED_ORIGINS .equalsIgnoreCase(name)) { return allowedOrigins; } else if (CORSConfiguration.PARAM_CORS_EXPOSED_HEADERS .equalsIgnoreCase(name)) { return exposedHeaders; } else if (CORSConfiguration.PARAM_CORS_SUPPORT_CREDENTIALS .equalsIgnoreCase(name)) { return supportCredentials; } else if (CORSConfiguration.PARAM_CORS_PREFLIGHT_MAXAGE .equalsIgnoreCase(name)) { return preflightMaxAge; } return null; } @SuppressWarnings("rawtypes") public Enumeration getInitParameterNames() { return null; } }; return filterConfig; } }
package org.kie.api.runtime.rule; import org.kie.api.definition.rule.Rule; import java.util.List; public interface Match { /** * * @return * The Rule that was activated. */ public Rule getRule(); /** * * @return * The matched FactHandles for this Match */ public List< ? extends FactHandle> getFactHandles(); /** * Returns the list of objects that make the tuple that created * this Match. The objects are in the proper tuple order. * * @return */ public List<Object> getObjects(); /** * Returns the list of declaration identifiers that are bound to the * tuple that created this Match. * * @return */ public List<String> getDeclarationIds(); /** * Returns the bound declaration value for the given declaration identifier. * * @param declarationId * @return */ public Object getDeclarationValue(String declarationId); }
package com.github.nsnjson; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.*; public class DriverTest extends AbstractFormatTest { @Test public void shouldBeConsistencyWhenGivenNull() { assertConsistency(getNull()); } @Test public void shouldBeConsistencyWhenGivenNumberIsInt() { assertConsistency(getNumberInt()); } @Test public void shouldBeConsistencyWhenGivenNumberIsLong() { assertConsistency(getNumberLong()); } @Test public void shouldBeConsistencyWhenGivenNumberIsDouble() { assertConsistency(getNumberDouble()); } @Test public void shouldBeConsistencyWhenGivenStringIsEmpty() { assertConsistency(getEmptyString()); } @Test public void shouldBeConsistencyWhenGivenString() { assertConsistency(getString()); } @Test public void shouldBeConsistencyWhenGivenBooleanIsTrue() { assertConsistency(getBooleanTrue()); } @Test public void shouldBeConsistencyWhenGivenBooleanIsFalse() { assertConsistency(getBooleanFalse()); } @Test public void shouldBeConsistencyWhenGivenArrayIsEmpty() { assertConsistency(getEmptyArray()); } @Test public void shouldBeConsistencyWhenGivenArray() { assertConsistency(getArray()); } @Test public void shouldBeConsistencyWhenGivenObjectIsEmpty() { assertConsistency(getEmptyObject()); } @Test public void shouldBeConsistencyWhenGivenObject() { ObjectNode object = new ObjectMapper().createObjectNode(); object.set("null_field", getNull()); object.set("true_field", getBooleanTrue()); object.set("false_field", getBooleanFalse()); object.set("int_field", getNumberInt()); object.set("long_field", getNumberLong()); object.set("double_field", getNumberDouble()); object.set("string_field", getString()); assertConsistency(object); } private static void assertConsistency(JsonNode value) { JsonNode restoredValue = Driver.decode(Driver.encode(value)); assertEquals(value, restoredValue); } private static void assertEquals(JsonNode value1, JsonNode value2) { Assert.assertEquals(value1.toString(), value2.toString()); } }
package com.hubspot.jinjava; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.io.Resources; import com.hubspot.jinjava.interpret.Context; import com.hubspot.jinjava.interpret.DeferredValue; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.loader.LocationResolver; import com.hubspot.jinjava.loader.RelativePathResolver; import com.hubspot.jinjava.loader.ResourceLocator; import com.hubspot.jinjava.mode.EagerExecutionMode; import com.hubspot.jinjava.objects.collections.PyList; import com.hubspot.jinjava.random.RandomNumberGeneratorStrategy; import com.hubspot.jinjava.util.DeferredValueUtils; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class EagerTest { private JinjavaInterpreter interpreter; private final Jinjava jinjava = new Jinjava(); private ExpectedTemplateInterpreter expectedTemplateInterpreter; Context globalContext = new Context(); Context localContext; // ref to context created with global as parent @Before public void setup() { jinjava.setResourceLocator( new ResourceLocator() { private RelativePathResolver relativePathResolver = new RelativePathResolver(); @Override public String getString( String fullName, Charset encoding, JinjavaInterpreter interpreter ) throws IOException { return Resources.toString( Resources.getResource(String.format("tags/macrotag/%s", fullName)), StandardCharsets.UTF_8 ); } @Override public Optional<LocationResolver> getLocationResolver() { return Optional.of(relativePathResolver); } } ); JinjavaConfig config = JinjavaConfig .newBuilder() .withRandomNumberGeneratorStrategy(RandomNumberGeneratorStrategy.DEFERRED) .withExecutionMode(new EagerExecutionMode()) .withNestedInterpretationEnabled(true) .build(); JinjavaInterpreter parentInterpreter = new JinjavaInterpreter( jinjava, globalContext, config ); interpreter = new JinjavaInterpreter(parentInterpreter); expectedTemplateInterpreter = new ExpectedTemplateInterpreter(jinjava, interpreter, "eager"); localContext = interpreter.getContext(); localContext.put("deferred", DeferredValue.instance()); localContext.put("resolved", "resolvedValue"); localContext.put("dict", ImmutableSet.of("a", "b", "c")); localContext.put("dict2", ImmutableSet.of("e", "f", "g")); JinjavaInterpreter.pushCurrent(interpreter); } @After public void teardown() { try { assertThat(interpreter.getErrors()).isEmpty(); } finally { JinjavaInterpreter.popCurrent(); } } @Test public void checkAssumptions() { // Just checking assumptions String output = interpreter.render("deferred"); assertThat(output).isEqualTo("deferred"); output = interpreter.render("resolved"); assertThat(output).isEqualTo("resolved"); output = interpreter.render("a {{resolved}} b"); assertThat(output).isEqualTo("a resolvedValue b"); assertThat(interpreter.getErrors()).isEmpty(); assertThat(localContext.getParent()).isEqualTo(globalContext); } @Test public void itDefersSimpleExpressions() { String output = interpreter.render("a {{ deferred }} b"); assertThat(output).isEqualTo("a {{ deferred }} b"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itDefersWholeNestedExpressions() { String output = interpreter.render("a {{ deferred.nested }} b"); assertThat(output).isEqualTo("a {{ deferred.nested }} b"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itDefersAsLittleAsPossible() { String output = interpreter.render("a {{ deferred }} {{resolved}} b"); assertThat(output).isEqualTo("a {{ deferred }} resolvedValue b"); assertThat(interpreter.getErrors()).isEmpty(); } @Test @Ignore public void itPreservesIfTag() { String output = interpreter.render( "{% if deferred %}{{resolved}}{% else %}b{% endif %}" ); assertThat(output).isEqualTo("{% if deferred %}resolvedValue{% else %}b{% endif %}"); assertThat(interpreter.getErrors()).isEmpty(); } @Test @Ignore public void itEagerlyResolvesNestedIfTag() { String output = interpreter.render( "{% if deferred %}{% if resolved %}{{resolved}}{% endif %}{% else %}b{% endif %}" ); assertThat(output).isEqualTo("{% if deferred %}resolvedValue{% else %}b{% endif %}"); assertThat(interpreter.getErrors()).isEmpty(); } /** * This may or may not be desirable behaviour. */ @Test public void itDoesntPreservesElseIfTag() { String output = interpreter.render("{% if true %}a{% elif deferred %}b{% endif %}"); assertThat(output).isEqualTo("a"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itResolvesIfTagWherePossible() { String output = interpreter.render("{% if true %}{{ deferred }}{% endif %}"); assertThat(output).isEqualTo("{{ deferred }}"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itResolveEqualToInOrCondition() { String output = interpreter.render( "{% if 'a' is equalto 'b' or 'a' is equalto 'a' %}{{ deferred }}{% endif %}" ); assertThat(output).isEqualTo("{{ deferred }}"); } @Test public void itPreserveDeferredVariableResolvingEqualToInOrCondition() { String inputOutputExpected = "{% if 'a' is equalto 'b' or 'a' is equalto deferred %}preserved{% endif %}"; String output = interpreter.render(inputOutputExpected); assertThat(output).isEqualTo(inputOutputExpected); assertThat(interpreter.getErrors()).isEmpty(); } @Test @SuppressWarnings("unchecked") @Ignore public void itDoesNotResolveForTagDeferredBlockInside() { String output = interpreter.render( "{% for item in dict %}{% if item == deferred %} equal {% else %} not equal {% endif %}{% endfor %}" ); StringBuilder expected = new StringBuilder(); for (String item : (Set<String>) localContext.get("dict")) { expected .append(String.format("{%% if '%s' == deferred %%}", item)) .append(" equal {% else %} not equal {% endif %}"); } assertThat(output).isEqualTo(expected.toString()); assertThat(interpreter.getErrors()).isEmpty(); } @Test @SuppressWarnings("unchecked") public void itDoesNotResolveForTagDeferredBlockNestedInside() { String output = interpreter.render( "{% for item in dict %}{% if item == 'a' %} equal {% if item == deferred %}{% endif %}{% else %} not equal {% endif %}{% endfor %}" ); StringBuilder expected = new StringBuilder(); for (String item : (Set<String>) localContext.get("dict")) { if (item.equals("a")) { expected.append(" equal {% if 'a' == deferred %}{% endif %}"); } else { expected.append(" not equal "); } } assertThat(output).isEqualTo(expected.toString()); assertThat(interpreter.getErrors()).isEmpty(); } @Test @SuppressWarnings("unchecked") public void itDoesNotResolveNestedForTags() { String output = interpreter.render( "{% for item in dict %}{% for item2 in dict2 %}{% if item2 == 'e' %} equal {% if item2 == deferred %}{% endif %}{% else %} not equal {% endif %}{% endfor %}{% endfor %}" ); StringBuilder expected = new StringBuilder(); for (String item : (Set<String>) localContext.get("dict")) { for (String item2 : (Set<String>) localContext.get("dict2")) { if (item2.equals("e")) { expected.append(" equal {% if 'e' == deferred %}{% endif %}"); } else { expected.append(" not equal "); } } } assertThat(output).isEqualTo(expected.toString()); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itPreservesNestedExpressions() { localContext.put("nested", "some {{ deferred }} value"); String output = interpreter.render("Test {{nested}}"); assertThat(output).isEqualTo("Test some {{ deferred }} value"); assertThat(interpreter.getErrors()).isEmpty(); } @Test @Ignore public void itPreservesForTag() { String output = interpreter.render( "{% for item in deferred %}{{ item.name }}last{% endfor %}" ); assertThat(output) .isEqualTo("{% for item in deferred %}{{ item.name }}last{% endfor %}"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itPreservesFilters() { String output = interpreter.render("{{ deferred|capitalize }}"); assertThat(output).isEqualTo("{{ deferred|capitalize }}"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itPreservesFunctions() { String output = interpreter.render("{{ deferred|datetimeformat('%B %e, %Y') }}"); assertThat(output).isEqualTo("{{ deferred|datetimeformat('%B %e, %Y') }}"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itPreservesRandomness() { String output = interpreter.render("{{ [1,2,3]|shuffle }}"); assertThat(output).isEqualTo("{{ [1,2,3]|shuffle }}"); assertThat(interpreter.getErrors()).isEmpty(); } @Test public void itDefersMacro() { localContext.put("padding", 0); localContext.put("added_padding", 10); String deferredOutput = interpreter.render( expectedTemplateInterpreter.getDeferredFixtureTemplate("deferred-macro.jinja") ); Object padding = localContext.get("padding"); assertThat(padding).isInstanceOf(DeferredValue.class); assertThat(((DeferredValue) padding).getOriginalValue()).isEqualTo(10L); localContext.put("padding", ((DeferredValue) padding).getOriginalValue()); localContext.put("added_padding", 10); // not deferred anymore localContext.put("deferred", 5); localContext.remove("int"); localContext.getGlobalMacro("inc_padding").setDeferred(false); String output = interpreter.render(deferredOutput); assertThat(output.replace("\n", "")).isEqualTo("0,10,15,25"); } @Test public void itDefersAllVariablesUsedInDeferredNode() { String template = expectedTemplateInterpreter.getDeferredFixtureTemplate( "vars-in-deferred-node.jinja" ); localContext.put("deferredValue", DeferredValue.instance("resolved")); String output = interpreter.render(template); Object varInScope = localContext.get("varUsedInForScope"); assertThat(varInScope).isInstanceOf(DeferredValue.class); DeferredValue varInScopeDeferred = (DeferredValue) varInScope; assertThat(varInScopeDeferred.getOriginalValue()).isEqualTo("outside if statement"); HashMap<String, Object> deferredContext = DeferredValueUtils.getDeferredContextWithOriginalValues( localContext ); deferredContext.forEach(localContext::put); String secondRender = interpreter.render(output); assertThat(secondRender).isEqualTo("outside if statement entered if statement"); localContext.put("deferred", DeferredValue.instance()); localContext.put("resolved", "resolvedValue"); } @Test public void itDefersDependantVariables() { String template = ""; template += "{% set resolved_variable = 'resolved' %} {% set deferred_variable = deferred + '-' + resolved_variable %}"; template += "{{ deferred_variable }}"; interpreter.render(template); localContext.get("resolved_variable"); } @Test @Ignore public void itDefersVariablesComparedAgainstDeferredVals() { String template = ""; template += "{% set testVar = 'testvalue' %}"; template += "{% if deferred == testVar %} true {% else %} false {% endif %}"; localContext.put("deferred", DeferredValue.instance("testvalue")); String output = interpreter.render(template); assertThat(output.trim()) .isEqualTo("{% if deferred == 'testvalue' %} true {% else %} false {% endif %}"); HashMap<String, Object> deferredContext = DeferredValueUtils.getDeferredContextWithOriginalValues( localContext ); deferredContext.forEach(localContext::put); String secondRender = interpreter.render(output); assertThat(secondRender.trim()).isEqualTo("true"); } @Test public void itDoesNotPutDeferredVariablesOnGlobalContext() { String template = expectedTemplateInterpreter.getDeferredFixtureTemplate( "set-within-lower-scope.jinja" ); localContext.put("deferredValue", DeferredValue.instance("resolved")); interpreter.render(template); assertThat(globalContext).isEmpty(); } @Test public void itPutsDeferredVariablesOnParentScopes() { String template = expectedTemplateInterpreter.getDeferredFixtureTemplate( "set-within-lower-scope.jinja" ); localContext.put("deferredValue", DeferredValue.instance("resolved")); String output = interpreter.render(template); HashMap<String, Object> deferredContext = DeferredValueUtils.getDeferredContextWithOriginalValues( localContext ); deferredContext.forEach(localContext::put); String secondRender = interpreter.render(output); assertThat(secondRender.trim()).isEqualTo("inside first scope".trim()); } @Test public void puttingDeferredVariablesOnParentScopesDoesNotBreakSetTag() { String template = expectedTemplateInterpreter.getDeferredFixtureTemplate( "set-within-lower-scope-twice.jinja" ); localContext.put("deferredValue", DeferredValue.instance("resolved")); String output = interpreter.render(template); HashMap<String, Object> deferredContext = DeferredValueUtils.getDeferredContextWithOriginalValues( localContext ); deferredContext.forEach(localContext::put); String secondRender = interpreter.render(output); assertThat(secondRender.trim()) .isEqualTo("inside first scopeinside first scope2".trim()); } @Test public void itMarksVariablesSetInDeferredBlockAsDeferred() { String template = expectedTemplateInterpreter.getDeferredFixtureTemplate( "set-in-deferred.jinja" ); localContext.put("deferredValue", DeferredValue.instance("resolved")); String output = interpreter.render(template); Context context = localContext; assertThat(localContext).containsKey("varSetInside"); Object varSetInside = localContext.get("varSetInside"); assertThat(varSetInside).isInstanceOf(DeferredValue.class); assertThat(output).contains("{{ varSetInside }}"); assertThat(context.get("a")).isInstanceOf(DeferredValue.class); assertThat(context.get("b")).isInstanceOf(DeferredValue.class); assertThat(context.get("c")).isInstanceOf(DeferredValue.class); } @Test public void itMarksVariablesUsedAsMapKeysAsDeferred() { String template = expectedTemplateInterpreter.getDeferredFixtureTemplate( "deferred-map-access.jinja" ); localContext.put("deferredValue", DeferredValue.instance("resolved")); localContext.put("deferredValue2", DeferredValue.instance("key")); ImmutableMap<String, ImmutableMap<String, String>> map = ImmutableMap.of( "map", ImmutableMap.of("key", "value") ); localContext.put("imported", map); String output = interpreter.render(template); assertThat(localContext).containsKey("deferredValue2"); Object deferredValue2 = localContext.get("deferredValue2"); DeferredValueUtils.findAndMarkDeferredProperties(localContext); assertThat(deferredValue2).isInstanceOf(DeferredValue.class); assertThat(output) .contains("{% set varSetInside = imported.map[deferredValue2.nonexistentprop] %}"); } @Test @Ignore public void itEagerlyDefersSet() { localContext.put("bar", true); expectedTemplateInterpreter.assertExpectedOutput("eagerly-defers-set"); } @Test @Ignore public void itEvaluatesNonEagerSet() { expectedTemplateInterpreter.assertExpectedOutput("evaluates-non-eager-set"); assertThat( localContext .getEagerTokens() .stream() .flatMap(eagerToken -> eagerToken.getSetDeferredWords().stream()) .collect(Collectors.toSet()) ) .containsExactlyInAnyOrder("item"); assertThat( localContext .getEagerTokens() .stream() .flatMap(eagerToken -> eagerToken.getUsedDeferredWords().stream()) .collect(Collectors.toSet()) ) .contains("deferred"); } @Test @Ignore public void itDefersOnImmutableMode() { expectedTemplateInterpreter.assertExpectedOutput("defers-on-immutable-mode"); } @Test @Ignore public void itDoesntAffectParentFromEagerIf() { expectedTemplateInterpreter.assertExpectedOutput( "doesnt-affect-parent-from-eager-if" ); } @Test public void itDefersEagerChildScopedVars() { expectedTemplateInterpreter.assertExpectedOutput("defers-eager-child-scoped-vars"); } @Test @Ignore public void itSetsMultipleVarsDeferredInChild() { expectedTemplateInterpreter.assertExpectedOutput( "sets-multiple-vars-deferred-in-child" ); } @Test public void itSetsMultipleVarsDeferredInChildSecondPass() { localContext.put("deferred", true); expectedTemplateInterpreter.assertExpectedOutput( "sets-multiple-vars-deferred-in-child.expected" ); } @Test public void itDoesntDoubleAppendInDeferredTag() { expectedTemplateInterpreter.assertExpectedOutput( "doesnt-double-append-in-deferred-tag" ); } @Test public void itPrependsSetIfStateChanges() { expectedTemplateInterpreter.assertExpectedOutput("prepends-set-if-state-changes"); } @Test public void itHandlesLoopVarAgainstDeferredInLoop() { expectedTemplateInterpreter.assertExpectedOutput( "handles-loop-var-against-deferred-in-loop" ); } @Test public void itHandlesLoopVarAgainstDeferredInLoopSecondPass() { localContext.put("deferred", "resolved"); expectedTemplateInterpreter.assertExpectedOutput( "handles-loop-var-against-deferred-in-loop.expected" ); expectedTemplateInterpreter.assertExpectedNonEagerOutput( "handles-loop-var-against-deferred-in-loop.expected" ); } @Test public void itDefersMacroForDoAndPrint() { localContext.put("my_list", new PyList(new ArrayList<>())); localContext.put("first", 10); localContext.put("deferred2", DeferredValue.instance()); String deferredOutput = expectedTemplateInterpreter.assertExpectedOutput( "defers-macro-for-do-and-print" ); Object myList = localContext.get("my_list"); assertThat(myList).isInstanceOf(DeferredValue.class); assertThat(((DeferredValue) myList).getOriginalValue()) .isEqualTo(ImmutableList.of(10L)); localContext.put("my_list", ((DeferredValue) myList).getOriginalValue()); localContext.put("first", 10); // not deferred anymore localContext.put("deferred", 5); localContext.put("deferred2", 10); // TODO auto remove deferred localContext.getEagerTokens().clear(); localContext.getGlobalMacro("macro_append").setDeferred(false); String output = interpreter.render(deferredOutput); assertThat(output.replace("\n", "")) .isEqualTo("Is ([]),Macro: [10]Is ([10]),Is ([10,5]),Macro: [10,5,10]"); } @Test @Ignore public void itDefersMacroInFor() { localContext.put("my_list", new PyList(new ArrayList<>())); expectedTemplateInterpreter.assertExpectedOutput("defers-macro-in-for"); } @Test public void itDefersMacroInIf() { localContext.put("my_list", new PyList(new ArrayList<>())); expectedTemplateInterpreter.assertExpectedOutput("defers-macro-in-if"); } @Test public void itPutsDeferredImportedMacroInOutput() { expectedTemplateInterpreter.assertExpectedOutput( "puts-deferred-imported-macro-in-output" ); } @Test public void itPutsDeferredImportedMacroInOutputSecondPass() { localContext.put("deferred", 1); expectedTemplateInterpreter.assertExpectedOutput( "puts-deferred-imported-macro-in-output.expected" ); expectedTemplateInterpreter.assertExpectedNonEagerOutput( "puts-deferred-imported-macro-in-output.expected" ); } @Test public void itPutsDeferredFromedMacroInOutput() { expectedTemplateInterpreter.assertExpectedOutput( "puts-deferred-fromed-macro-in-output" ); } @Test @Ignore public void itEagerlyDefersMacro() { localContext.put("foo", "I am foo"); localContext.put("bar", "I am bar"); expectedTemplateInterpreter.assertExpectedOutput("eagerly-defers-macro"); } @Test public void itEagerlyDefersMacroSecondPass() { localContext.put("deferred", true); expectedTemplateInterpreter.assertExpectedOutput("eagerly-defers-macro.expected"); expectedTemplateInterpreter.assertExpectedNonEagerOutput( "eagerly-defers-macro.expected" ); } @Test public void itLoadsImportedMacroSyntax() { expectedTemplateInterpreter.assertExpectedOutput("loads-imported-macro-syntax"); } @Test public void itDefersCaller() { expectedTemplateInterpreter.assertExpectedOutput("defers-caller"); } @Test public void itDefersCallerSecondPass() { localContext.put("deferred", "foo"); expectedTemplateInterpreter.assertExpectedOutput("defers-caller.expected"); expectedTemplateInterpreter.assertExpectedNonEagerOutput("defers-caller.expected"); } @Test public void itDefersMacroInExpression() { expectedTemplateInterpreter.assertExpectedOutput("defers-macro-in-expression"); } @Test public void itDefersMacroInExpressionSecondPass() { localContext.put("deferred", 5); expectedTemplateInterpreter.assertExpectedOutput( "defers-macro-in-expression.expected" ); localContext.put("deferred", 5); expectedTemplateInterpreter.assertExpectedNonEagerOutput( "defers-macro-in-expression.expected" ); } @Test public void itHandlesDeferredInIfchanged() { expectedTemplateInterpreter.assertExpectedOutput("handles-deferred-in-ifchanged"); } @Test @Ignore public void itDefersIfchanged() { expectedTemplateInterpreter.assertExpectedOutput("defers-ifchanged"); } @Test @Ignore public void itHandlesCycleInDeferredFor() { expectedTemplateInterpreter.assertExpectedOutput("handles-cycle-in-deferred-for"); } @Test public void itHandlesCycleInDeferredForSecondPass() { localContext.put("deferred", new String[] { "foo", "bar", "foobar", "baz" }); expectedTemplateInterpreter.assertExpectedOutput( "handles-cycle-in-deferred-for.expected" ); expectedTemplateInterpreter.assertExpectedNonEagerOutput( "handles-cycle-in-deferred-for.expected" ); } @Test @Ignore public void itHandlesDeferredInCycle() { expectedTemplateInterpreter.assertExpectedOutput("handles-deferred-in-cycle"); } @Test @Ignore public void itHandlesDeferredCycleAs() { expectedTemplateInterpreter.assertExpectedOutput("handles-deferred-cycle-as"); } @Test public void itHandlesDeferredCycleAsSecondPass() { localContext.put("deferred", "hello"); expectedTemplateInterpreter.assertExpectedOutput( "handles-deferred-cycle-as.expected" ); expectedTemplateInterpreter.assertExpectedNonEagerOutput( "handles-deferred-cycle-as.expected" ); } @Test public void itHandlesNonDeferringCycles() { expectedTemplateInterpreter.assertExpectedNonEagerOutput( "handles-non-deferring-cycles" ); expectedTemplateInterpreter.assertExpectedOutput("handles-non-deferring-cycles"); } @Test public void itHandlesAutoEscape() { localContext.put("myvar", "foo < bar"); expectedTemplateInterpreter.assertExpectedOutput("handles-auto-escape"); } @Test public void itWrapsCertainOutputInRaw() { JinjavaConfig config = JinjavaConfig .newBuilder() .withRandomNumberGeneratorStrategy(RandomNumberGeneratorStrategy.DEFERRED) .withExecutionMode(new EagerExecutionMode()) .withNestedInterpretationEnabled(false) .build(); JinjavaInterpreter parentInterpreter = new JinjavaInterpreter( jinjava, globalContext, config ); JinjavaInterpreter noNestedInterpreter = new JinjavaInterpreter(parentInterpreter); JinjavaInterpreter.pushCurrent(noNestedInterpreter); try { new ExpectedTemplateInterpreter(jinjava, noNestedInterpreter, "eager") .assertExpectedOutput("wraps-certain-output-in-raw"); } finally { JinjavaInterpreter.popCurrent(); } } @Test @Ignore public void itHandlesDeferredImportVars() { expectedTemplateInterpreter.assertExpectedOutput("handles-deferred-import-vars"); } @Test public void itHandlesDeferredImportVarsSecondPass() { localContext.put("deferred", 1); expectedTemplateInterpreter.assertExpectedOutput( "handles-deferred-import-vars.expected" ); } @Test @Ignore public void itHandlesDeferredFromImportAs() { expectedTemplateInterpreter.assertExpectedOutput("handles-deferred-from-import-as"); } @Test public void itHandlesDeferredFromImportAsSecondPass() { localContext.put("deferred", 1); expectedTemplateInterpreter.assertExpectedOutput( "handles-deferred-from-import-as.expected" ); } @Test public void itPreservesValueSetInIf() { expectedTemplateInterpreter.assertExpectedOutput("preserves-value-set-in-if"); } }
package com.tamco.hack.compiler.lexical; import java.util.Arrays; import java.util.List; public class Lexical { public static final List<String> keywords = Arrays.asList("class", "constructor", "function", "method", "field", "static", "var", "int", "char", "boolean", "void", "true", "false", "null", "this", "let", "do", "if", "else", "while", "return"); public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", ",", ";", "+", "-", "*", "/", "&", "|", "<", ">", "=", "~"); public static enum Type { keyword, symbol, integerConstant, stringConstant, identifier } private Type type; private String lecical; public Lexical(Type type, String lecical) { this.type = type; this.lecical = lecical; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getLecical() { return lecical; } public void setLecical(String lecical) { this.lecical = lecical; } }
package control; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.internal.WhiteboxImpl; import org.testfx.framework.junit.ApplicationTest; import data.Camera; import data.CameraTimeline; import data.DirectorTimeline; import data.ScriptingProject; import gui.modal.DeleteCameraTypeWarningModalView; import gui.modal.EditProjectModalView; import gui.modal.StartupModalView; import gui.root.RootPane; import gui.styling.StyledButton; import javafx.application.Platform; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; @PrepareForTest(ProjectController.class) public class ProjectControllerTest extends ApplicationTest { private ProjectController projectController; private ControllerManager controllerManager; private ScriptingProject project; private RootPane rootPane; @Before public void setUp() throws Exception { rootPane = mock(RootPane.class); StartupModalView startModal = mock(StartupModalView.class); when(rootPane.getStartupModalView()).thenReturn(startModal); StyledButton buttonMock = mock(StyledButton.class); when(startModal.getNewButton()).thenReturn(buttonMock); when(startModal.getLoadButton()).thenReturn(buttonMock); when(startModal.getExitButton()).thenReturn(buttonMock); controllerManager = mock(ControllerManager.class); when(controllerManager.getRootPane()).thenReturn(rootPane); projectController = spy(new ProjectController(controllerManager)); project = mock(ScriptingProject.class); when(controllerManager.getScriptingProject()).thenReturn(project); when(controllerManager.getRootPane()).thenReturn(rootPane); when(rootPane.getControllerManager()).thenReturn(controllerManager); } @Test public void constructorTest() { assertEquals(projectController.getControllerManager(), controllerManager); } @Test public void saveTest() { when(project.getFilePath()).thenReturn(null); Mockito.doNothing().when(projectController).saveAs(); projectController.save(); Mockito.verify(projectController).saveAs(); } @Test public void saveTestWithExistingFilePath() { when(project.getFilePath()).thenReturn("Kek"); // Mockito.doNothing().when(project).write(); projectController.save(); Mockito.verify(project).write(); } @Test public void loadTest() { String oldConfigIni = ""; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("config.ini")); oldConfigIni = reader.readLine(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader!=null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ArrayList<CameraTimeline> listMock = mock(ArrayList.class); DirectorTimeline directorTimelineMock = mock(DirectorTimeline.class); when(listMock.size()).thenReturn(3); when(project.getCameraTimelines()).thenReturn(listMock); when(project.getDirectorTimeline()).thenReturn(directorTimelineMock); File file = new File("src/test/files/general_test3.scp"); TimelineController timelineController = mock(TimelineController.class); when(controllerManager.getTimelineControl()).thenReturn(timelineController); Mockito.doNothing().when(rootPane).reInitRootCenterArea(Mockito.any()); CameraTimeline timelineMock = mock(CameraTimeline.class); when(listMock.get(Mockito.anyInt())).thenReturn(timelineMock); when(timelineMock.getName()).thenReturn("A name"); projectController.load(file); PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter("config.ini")); writer.println(oldConfigIni); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (writer!=null) { writer.close(); } } Mockito.verify(timelineController).setNumTimelines(3); } @Test public void loadTestNullFile() { File file = new File("ThisDoesNotEvenExist"); Stage stage = mock(Stage.class); when(rootPane.getPrimaryStage()).thenReturn(stage); projectController.load(file); Mockito.verify(stage).close(); } @Test public void newProjectTest() throws InterruptedException { final CountDownLatch[] latch = {new CountDownLatch(1)}; Platform.runLater(() -> { projectController.newProject(); latch[0].countDown(); }); latch[0].await(); } @Test public void confirmTypeDeleteTest() throws Exception { MouseEvent event = mock(MouseEvent.class); List<Camera> camera = mock(List.class); Platform.runLater(() -> { projectController.setEditProjectModal(new EditProjectModalView(rootPane, false)); projectController.setTypeWarningModal(new DeleteCameraTypeWarningModalView(rootPane, camera)); try { WhiteboxImpl.invokeMethod(projectController, "confirmTypeDelete", event, camera, 0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }); } @Override public void start(Stage arg0) throws Exception { // TODO Auto-generated method stub } }
package de.lessvoid.nifty.loaderv2.types.helper; import java.util.regex.Pattern; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyMethodInvoker; public class OnClickType { /** * The pattern used to check */ private static final Pattern VALID_PATTERN = Pattern.compile("\\w+\\((?|\\w+(?,\\s*\\w+)*)\\)"); private String value; public OnClickType(final String valueParam) { this.value = valueParam; } public boolean isValid() { if (value == null) { return false; } return VALID_PATTERN.matcher(value).matches(); } public NiftyMethodInvoker getMethod(final Nifty nifty, final Object ... controlController) { return new NiftyMethodInvoker(nifty, value, controlController); } }
package edu.msu.nscl.olog.api; import static edu.msu.nscl.olog.api.LogBuilder.log; import static edu.msu.nscl.olog.api.LogbookBuilder.logbook; import static edu.msu.nscl.olog.api.TagBuilder.tag; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.sun.jersey.core.util.MultivaluedMapImpl; import edu.msu.nscl.olog.api.OlogClientImpl.OlogClientBuilder; //if (key.equals("search")) { // log_matches.addAll(match.getValue()); //// JcrSearch js = new JcrSearch(); //// jcr_search_ids = js.searchForIds(match.getValue().toString()); //} else if (key.equals("tag")) { // addTagMatches(match.getValue()); //} else if (key.equals("logbook")) { // addLogbookMatches(match.getValue()); //} else if (key.equals("page")) { // logPaginate_matches.putAll(key, match.getValue()); //} else if (key.equals("limit")) { // logPaginate_matches.putAll(key, match.getValue()); //} else if (key.equals("start")) { // date_matches.putAll(key, match.getValue()); //} else if (key.equals("end")) { // date_matches.putAll(key, match.getValue()); //} else { // value_matches.putAll(key, match.getValue()); public class QueryIT { private static int initialLogCount; private static OlogClient client = OlogClientBuilder.serviceURL() .withHTTPAuthentication(true).create(); // Logs static private Log pvk_01; static private Log pvk_02; static private Log pvk_03; static private Log distinctName; // Tags static TagBuilder tagA = tag("Taga", "me"); static TagBuilder tagB = tag("Tagb", "me"); static TagBuilder tagC = tag("Tagc", "me"); static TagBuilder tagStar = tag("Tag*", "me"); // Logbooks static LogbookBuilder book = logbook("book"); static LogbookBuilder book2 = logbook("book2"); @BeforeClass public static void setUpBeforeClass() throws Exception { initialLogCount = client.listLogs().size(); // Add the tags and logbooks. client.set(book.owner("me")); client.set(book2.owner("me")); client.set(tagA); client.set(tagB); client.set(tagC); client.set(tagStar); pvk_01 = client.set(log("pvk:01<first>").description("first details") .level("Info").in(book).in(book2).with(tagA)); pvk_02 = client.set(log("pvk:02<second>").description("second details") .level("Info").in(book).with(tagA).with(tagB)); pvk_03 = client.set(log("pvk:03<second>").description("some details") .level("Info").in(book).with(tagB).with(tagC)); distinctName = client.set(log("distinctName") .description("some details").level("Info").in(book) .with(tagStar)); } @AfterClass public static void tearDownAfterClass() throws Exception { client.delete(pvk_01.getId()); client.delete(pvk_02.getId()); client.delete(pvk_03.getId()); client.delete(distinctName.getId()); // clean up all the tags and logbooks client.deleteLogbook(book.build().getName()); client.deleteLogbook(book2.toXml().getName()); client.deleteTag(tagA.toXml().getName()); client.deleteTag(tagB.toXml().getName()); client.deleteTag(tagC.toXml().getName()); client.deleteTag(tagStar.toXml().getName()); assertTrue(client.listLogs().size() == initialLogCount); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } /** * check if all logs are returned */ @Test public void queryAllLogs() { Map<String, String> map = new Hashtable<String, String>(); map.put("search", "*"); Collection<Log> logs = client.findLogs(map); assertTrue(client.listLogs().size() == logs.size()); } /** * Test searching based on */ @Test public void queryLogs() { Map<String, String> map = new Hashtable<String, String>(); map.put("search", "pvk:*"); Collection<Log> logs = client.findLogs(map); assertTrue("Failed to get search based on subject pattern, expected 3 found " + logs.size(), logs.size() == 3); } /** * Test logbook query When multiple logbooks are queried, the result is a * logical OR of all the query conditions */ @Test public void queryLogsbyLogbook() { MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("logbook", "book2"); Collection<Log> logs = client.findLogs(map); assertTrue("search for all logs in logbook book2 failed ", logs.size() == 1); // Query for logs from multiple logbooks. map.add("logbook", "book"); map.add("logbook", "book2"); logs = client.findLogs(map); assertTrue("search for all logs in logbook book OR book2 failed", logs.size() == 4); } /** * Test tag query When multiple tags are queried, the result is a logical OR * of all the query conditions */ @Test public void queryLogsbyTag() { MultivaluedMap<String, String> map = new MultivaluedMapImpl(); Collection<Log> queryResult; // Search for a logs with tag 'Tag*' map.add("tag", "Tag*"); queryResult = client.findLogs(map); assertTrue(queryResult.size() == 1); // query for logs with anyone of a group of tags map.clear(); map.add("tag", "taga"); map.add("tag", "tagb"); queryResult = client.findLogs(map); assertTrue(queryResult.size() == 3); } @Test public void queryLogsbyDescription() { MultivaluedMap<String, String> map = new MultivaluedMapImpl(); // search a single log based on description. map.add("search", pvk_01.getDescription()); Collection<Log> queryResult = client.findLogs(map); assertTrue( "Failed to search based on the log descrition expected 1 found " + queryResult.size(), queryResult.size() == 1 && queryResult.contains(pvk_01)); // search for "some detail" which matches multiple logs. map.clear(); map.add("search", "some details"); queryResult = client.findLogs(map); assertTrue( "Failed to search based on the log descrition expected 2 found " + queryResult.size(), queryResult.size() == 2 && queryResult.contains(pvk_03) && queryResult.contains(distinctName)); // search for logs with one map.clear(); map.add("search", pvk_01.getDescription()); map.add("search", pvk_02.getDescription()); queryResult = client.findLogs(map); assertTrue( "Failed to search based on the log descrition expected 2 found " + queryResult.size(), queryResult.size() == 2 && queryResult.contains(pvk_01) && queryResult.contains(pvk_02)); } /** * Test the querying based on the create time * * @param first */ @Test public void queryLogsbyTime() { Log first; Log third; Collection<Log> searchResult; Map<String, String> searchParameters = new HashMap<String, String>(); try { synchronized (this) { this.wait(1000L); client.set(log("Test log1 for time") .level("info").in(book).description("test log")); System.out.println(System.currentTimeMillis()); this.wait(1000L); client.set(log("Test log2 for time").level("info").in(book) .description("test log")); System.out.println(System.currentTimeMillis()); this.wait(1000L); client.set(log("Test log3 for time") .level("info").in(book).description("test log")); System.out.println(System.currentTimeMillis()); this.wait(1000L); // XXX // A search is required because the response from the service // for a put only contains Id info and not the create time. first = client.findLogsBySearch("Test log1 for time") .iterator().next(); third = client.findLogsBySearch("Test log3 for time") .iterator().next(); } // // check the _start_ search condition // searchParameters.put("start", // String.valueOf(first.getCreatedDate().getTime() / 1000L)); // searchResult = client.findLogs(searchParameters); // assertTrue( // "failed to search based on the start time, expected 3 found " // + searchResult.size(), searchResult.size() == 3); // searchParameters.clear(); // searchParameters.put("start", // String.valueOf(third.getCreatedDate().getTime() / 1000L)); // searchResult = client.findLogs(searchParameters); // assertTrue( // "failed to search based on the start time, expect 1 found " // + searchResult.size(), searchResult.size() == 1); // // Check the _end_ search condition // searchParameters.clear(); // searchParameters.put("end", // String.valueOf(first.getCreatedDate().getTime() / 1000L)); // searchResult = client.findLogs(searchParameters); // assertTrue( // "failed to search based on the end time, expected 0 found " // + searchResult, searchResult.size() == 0); // searchParameters.clear(); // searchParameters.put("end", // String.valueOf(first.getCreatedDate().getTime() / 1000L)); // searchResult = client.findLogs(searchParameters); // assertTrue( // "failed to search based on the end time, expected 0 found " // + searchResult, searchResult.size() == 0); // searchParameters.clear(); // searchParameters.put("end", String.valueOf((third.getCreatedDate() // .getTime() / 1000L) + 1)); // searchResult = client.findLogs(searchParameters); // assertTrue( // "failed to search based on the end time, expected 3 found " // + searchResult, searchResult.size() == 3); // check the _start_ and _end_ search conditions searchParameters.clear(); searchParameters.put("start", String.valueOf(first.getCreatedDate().getTime() / 1000L)); searchParameters.put("end", String.valueOf((first.getCreatedDate().getTime() / 1000L))); searchResult = client.findLogs(searchParameters); assertTrue( "failed to search based on the start & end time, expected 1 found " + searchResult.size(), searchResult.size() == 1); searchParameters.clear(); searchParameters.put("start", String.valueOf(first.getCreatedDate().getTime() / 1000L)); searchParameters.put("end", String.valueOf((third.getCreatedDate().getTime() / 1000L))); searchResult = client.findLogs(searchParameters); assertTrue( "failed to search based on the start & end time, expected 3 found " + searchResult.size(), searchResult.size() == 3); } catch (InterruptedException e) { e.printStackTrace(); } finally { // clean up searchResult = client.findLogsBySearch("Test log* for time"); client.delete(searchResult); } } /** * Test findLogsby*() methods */ @Test public void queryTest() { // find by search assertTrue("Failed to query using findbysearch method ", client .findLogsBySearch("pvk_*").size() == 3); // find by tag assertTrue("Failed to query using the findbytag method ", client .findLogsByTag(tagA.build().getName()).size() == 2); // find by logbook assertTrue("Failed to query using the findbylogbook method", client .findLogsByLogbook(book2.build().getName()).size() == 1); } }
package guitests; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import org.junit.After; import org.junit.Test; import org.loadui.testfx.utils.FXTestUtils; import prefs.GlobalConfig; import prefs.Preferences; import ui.RepositorySelector; import java.io.*; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class UseGlobalConfigsTest extends UITest { String configFileDirectory = Preferences.DIRECTORY; String testConfigFileName = Preferences.TEST_CONFIG_FILE; @Override public void launchApp() { FXTestUtils.launchApp(TestUI.class, "--test=true", "--testconfig=true"); } @Test public void globalConfigTest() { // Cleaning up with @Before creates race condition. // Neither can we ensure test config file does not exist before starting test, // as the program automatically generates an empty config file if it does not // exist. TextField repoOwnerField = find("#repoOwnerField"); doubleClick(repoOwnerField); doubleClick(repoOwnerField); type("dummy").push(KeyCode.TAB); type("dummy").push(KeyCode.TAB); type("test").push(KeyCode.TAB); type("test"); click("Sign in"); sleep(2000); RepositorySelector repositorySelector = find("#repositorySelector"); assertEquals(repositorySelector.getText(), "dummy/dummy"); // Make a new board click("Boards"); click("Save"); type("Empty Board"); click("OK"); // Should not use ENTER here, Travis CI does not autofocus on "OK". // Load dummy2/dummy2 too press(KeyCode.CONTROL).press(KeyCode.P).release(KeyCode.P).release(KeyCode.CONTROL); click("#dummy/dummy_col1_filterTextField"); type("repo"); press(KeyCode.SHIFT).press(KeyCode.SEMICOLON).release(KeyCode.SEMICOLON).release(KeyCode.SHIFT); type("dummy2/dummy2"); press(KeyCode.ENTER).release(KeyCode.ENTER); sleep(2000); // Make a new board click("Boards"); click("Save"); type("Dummy Board"); click("OK"); // Then exit program... click("Preferences"); click("Logout"); // ...and check if the test JSON is still there... File testConfig = new File(configFileDirectory, testConfigFileName); if (!(testConfig.exists() && testConfig.isFile())) fail(); try { BufferedReader br = new BufferedReader(new FileReader(testConfig)); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { fail(); } // ...then check that the JSON file contents are correct. Preferences testPref = new Preferences(true); // Credentials assertEquals("test", testPref.getLastLoginUsername()); assertEquals("test", testPref.getLastLoginPassword()); // Last open filters List<String> lastOpenFilters = testPref.getLastOpenFilters(); assertEquals(2, lastOpenFilters.size()); assertEquals("", lastOpenFilters.get(0)); assertEquals("repo:dummy2/dummy2", lastOpenFilters.get(1)); // Last viewed repositories List<String> lastViewedRepositories = testPref.getLastViewedRepositories(); assertEquals("dummy/dummy", lastViewedRepositories.get(0)); assertEquals("dummy2/dummy2", lastViewedRepositories.get(1)); // Boards Map<String, List<String>> boards = testPref.getAllBoards(); List<String> emptyBoard = boards.get("Empty Board"); assertEquals(1, emptyBoard.size()); assertEquals("", emptyBoard.get(0)); List<String> dummyBoard = boards.get("Dummy Board"); assertEquals(2, dummyBoard.size()); assertEquals("", dummyBoard.get(0)); assertEquals("repo:dummy2/dummy2", dummyBoard.get(1)); } @After public void teardown() { File testConfig = new File(configFileDirectory, testConfigFileName); if (testConfig.exists() && testConfig.isFile()) testConfig.delete(); } }
package innovimax.mixthem; import innovimax.mixthem.MixThem; import innovimax.mixthem.Rule; import innovimax.mixthem.MixException; import java.io.*; import java.net.URL; import org.junit.Assert; import org.junit.Test; public class GenericTest { @Test public final void checkRule1() throws MixException, FileNotFoundException, IOException { URL url1 = getClass().getResource("test001_file1.txt"); URL url2 = getClass().getResource("test001_file2.txt"); File file1 = new File(url1.getFile()); File file2 = new File(url2.getFile()); ByteArrayOutputStream baos_rule_1 = new ByteArrayOutputStream(); MixThem mixThem = new MixThem(file1, file2, baos_rule_1); mixThem.process(Rule._1); Assert.assertTrue(checkFileEquals(file1, baos_rule_1.toByteArray())); ByteArrayOutputStream baos_rule_2 = new ByteArrayOutputStream(); mixThem = new MixThem(file1, file2, baos_rule_2); mixThem.process(Rule._2); Assert.assertTrue(checkFileEquals(file2, baos_rule_2.toByteArray())); } @Test public final void checkRuleAdd() throws MixException, FileNotFoundException, IOException { URL url1 = getClass().getResource("test001_file1.txt"); URL url2 = getClass().getResource("test001_file2.txt"); URL url12 = getClass().getResource("test001_output-add.txt"); File file1 = new File(url1.getFile()); File file2 = new File(url2.getFile()); File file12 = new File(url12.getFile()); ByteArrayOutputStream baos_rule_12 = new ByteArrayOutputStream(); MixThem mixThem = new MixThem(file1, file2, baos_rule_12); mixThem.process(Rule._ADD); Assert.assertTrue(checkFileEquals(file12, baos_rule_12.toByteArray())); } @Test public final void checkRuleAltLine() throws MixException, FileNotFoundException, IOException { URL url1 = getClass().getResource("test001_file1.txt"); URL url2 = getClass().getResource("test001_file2.txt"); URL urlComp = getClass().getResource("test001_output-altline.txt"); File file1 = new File(url1.getFile()); File file2 = new File(url2.getFile()); File fileComp = new File(urlComp.getFile()); ByteArrayOutputStream baos_rule = new ByteArrayOutputStream(); MixThem mixThem = new MixThem(file1, file2, baos_rule); mixThem.process(Rule._ALT_LINE); Assert.assertTrue(checkFileEquals(fileComp, baos_rule.toByteArray())); } @Test public final void checkRuleAltChar() throws MixException, FileNotFoundException, IOException { URL url1 = getClass().getResource("test002_file1.txt"); URL url2 = getClass().getResource("test002_file2.txt"); URL urlComp = getClass().getResource("test002_output-altchar.txt"); File file1 = new File(url1.getFile()); File file2 = new File(url2.getFile()); File fileComp = new File(urlComp.getFile()); ByteArrayOutputStream baos_rule = new ByteArrayOutputStream(); MixThem mixThem = new MixThem(file1, file2, baos_rule); mixThem.process(Rule._ALT_CHAR); Assert.assertTrue(checkFileEquals(fileComp, baos_rule.toByteArray())); } @Test public final void dumpRule1() throws MixException, FileNotFoundException, IOException { URL url1 = getClass().getResource("test001_file1.txt"); URL url2 = getClass().getResource("test001_file2.txt"); File file1 = new File(url1.getFile()); File file2 = new File(url2.getFile()); System.out.println("test001/File1:"); MixThem mixThem = new MixThem(file1, file2, System.out); mixThem.process(Rule._1); System.out.println("test001/File2:"); mixThem = new MixThem(file1, file2, System.out); mixThem.process(Rule._2); } @Test public final void dumpRuleAltLine() throws MixException, FileNotFoundException, IOException { URL url1 = getClass().getResource("test001_file1.txt"); URL url2 = getClass().getResource("test001_file2.txt"); URL urlComp = getClass().getResource("test001_output-altline.txt"); File file1 = new File(url1.getFile()); File file2 = new File(url2.getFile()); File fileComp = new File(urlComp.getFile()); System.out.println("test001/Mixed/alt-line:"); MixThem mixThem = new MixThem(file1, file2, System.out); mixThem.process(Rule._ALT_LINE); /* System.out.println("test001/Expected/alt-line:"); String line; BufferedReader br = new BufferedReader(new FileReader(fileComp)); while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); */ } @Test public final void dumpRuleAltChar() throws MixException, FileNotFoundException, IOException { URL url1 = getClass().getResource("test002_file1.txt"); URL url2 = getClass().getResource("test002_file2.txt"); URL urlComp = getClass().getResource("test002_output-altchar.txt"); File file1 = new File(url1.getFile()); File file2 = new File(url2.getFile()); File fileComp = new File(urlComp.getFile()); System.out.println("test002/File1:"); MixThem mixThem = new MixThem(file1, file2, System.out); mixThem.process(Rule._1); System.out.println("test002/File2:"); mixThem = new MixThem(file1, file2, System.out); mixThem.process(Rule._2); System.out.println("test002/Mixed/alt-char:"); mixThem = new MixThem(file1, file2, System.out); mixThem.process(Rule._ALT_CHAR); /* System.out.println("test002/Expected/alt-char:"); String line; BufferedReader br = new BufferedReader(new FileReader(fileComp)); while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); */ } private static boolean checkFileEquals(File fileExpected, byte[] result) throws FileNotFoundException, IOException { FileInputStream fisExpected = new FileInputStream(fileExpected); int c; int offset = 0; while ((c = fisExpected.read()) != -1) { if (offset >= result.length) return false; int d = result[offset++]; if (c != d) return false; } if (offset > result.length) return false; return true; } }
package io.javalin.routeoverview; import io.javalin.Handler; import io.javalin.core.util.RouteOverviewUtil; public class Util { static String getMetaInfo(Handler handler) { return RouteOverviewUtil.getMetaInfo(handler); } }
package org.openmrs.module.patientimage.filter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openmrs.Patient; import org.openmrs.PatientIdentifier; import org.openmrs.api.context.Context; /** * @author sunbiz */ public class PatientImageFilter implements Filter { @Override public void init(FilterConfig fc) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String requestURI = request.getRequestURI(); Boolean showOn2xDashboard = Boolean.valueOf(Context.getAdministrationService().getGlobalProperty( "patientimage.showOn2xDashboard")); if (requestURI.endsWith("patient.page") && showOn2xDashboard) { PrintWriter out = res.getWriter(); CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse) res); chain.doFilter(request, responseWrapper); String idParameter = request.getParameter("patientId"); Patient patient = Context.getPatientService().getPatientByUuid(idParameter); if (patient == null) { patient = Context.getPatientService().getPatient(Integer.parseInt(idParameter)); } PatientIdentifier id = patient.getPatientIdentifier(); String responseText = responseWrapper.toString(); if (null != id) { StringBuilder servletResponse = new StringBuilder(responseWrapper.toString()); int indexOf = servletResponse.indexOf("<div class=\"patient-header \">"); String imgUrl; if (Boolean.valueOf(Context.getAdministrationService().getGlobalProperty( "patientimage.usePersonImageEndpoint"))) { final String restEndpoint = "/ws/rest/v1/personimage"; imgUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + restEndpoint + "/" + request.getParameter("patientId"); } else { final String endpoint = "moduleServlet/patientimage"; final String servletName = "ImageServlet"; final String imageParamName = "image"; final String imageParamValue = id.getIdentifier() + ".jpg"; imgUrl = request.getContextPath() + "/" + endpoint + "/" + servletName + "?" + imageParamName + "=" + imageParamValue; } String imgTag = "<img alt=\"\" id=\"imgThumbnail\" height=\"145\" src=\"" + imgUrl + "\" style=\"border: 1px solid #8FABC7; float:right\" onError=\"this.onerror = '';this.style.display='none';\">"; responseText = servletResponse.insert(indexOf, imgTag).toString(); } out.write(responseText); } else { chain.doFilter(req, res); } } @Override public void destroy() { } }
package otognan; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.net.URI; import java.net.URL; import org.apache.http.client.HttpClient; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HttpContext; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; /* * Extra security config that opens access to test controller. * Here we extend normal WebSecurityConfig and add allowed url before * the more strict rules defined by WebSecurityConfig because spring * evaluates antMatchers in the order they are declared. * * It doesn't work to extend WebSecurityConfigurerAdapter instead of * main config for some reason. * */ @Configuration @Order(1) // default order of WebSecurityConfig is 100, so this config has a priority class TestWebSecurityConfig extends WebSecurityConfig { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/hello_to_google").permitAll(); super.configure(http); } } @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {Application.class}) @WebAppConfiguration @IntegrationTest({ "server.port=8443", "server.ssl.key-store = src/test/resources/test_keystore", "server.ssl.key-store-password = temppwd", "fb.client_id=0", "fb.secret=0", "fb.redirect_uri=null"}) public class TestHelloControllerIT { @Value("${local.server.port}") private int port; private URL base; private RestTemplate template; @Before public void setUp() throws Exception { this.base = new URL("https://localhost:" + port + "/hello"); SSLContextBuilder builder = new SSLContextBuilder(); // trust self signed certificate builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory( sslConnectionSocketFactory).build(); this.template = new TestRestTemplate(); this.template.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { HttpClientContext context = HttpClientContext.create(); RequestConfig.Builder builder = RequestConfig.custom() .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setAuthenticationEnabled(false).setRedirectsEnabled(false) .setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(1000); context.setRequestConfig(builder.build()); return context; } }); } @Test public void getHello() throws Exception { ResponseEntity<String> response = template.getForEntity(base.toString(), String.class); assertThat(response.getBody(), equalTo("Greetings from Spring Boot!")); } @Test public void getHelloToGoogle() throws Exception { //MockRestServiceServer mockServer = MockRestServiceServer.createServer(this.template); String url = new URL("https://localhost:" + port + "/hello_to_google").toString(); ResponseEntity<String> response = template.getForEntity(url, String.class); assertThat(response.getBody(), equalTo("Greetings from Spring Boot google!")); //mockServer.verify(); } }
package authoring.concretefeatures; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Double; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import authoring.abstractfeatures.PopupWindow; /** * Popup GUI element that allows the user to specify the size of the grid, * selects the tiles and returns the list of relative coordination of selected * tiles. * * @author Meng'en Huang, Jesse Ling, Jennie Ju * */ public class RangeEditor extends PopupWindow { private static final String CUSTOM = "Custom(default)"; private static final String RADIUS = "Radius"; private static final String ALL = "All"; private static final String ROW = "Row"; private static final String COLUMN = "Column"; private static final String NAME = "Range Editor"; private static final int MIN_TILE_SIZE = 30; private static final int RANGE_EDITOR_HEIGHT = 800; private static final int RANGE_EDITOR_WIDTH = 600; private static final int DEFAULT_TILE_SIZE = 40; private int myGridLength = RANGE_EDITOR_WIDTH - 100; private int myTileSize = DEFAULT_TILE_SIZE; private static final String STYLESHEET = "/resources/stylesheets/actioncreator_layout.css"; private int myGridWidthNumber; private int myGridHeightNumber; private RangeGrid mySampleGridView; public RangeEditor (List<Point2D> range) { // range.add(new Point2D.Double(1,0)); // range.add(new Point2D.Double(-1,1)); setHeight(RANGE_EDITOR_HEIGHT); setWidth(RANGE_EDITOR_WIDTH); setTitle(NAME); mySampleGridView = new RangeGrid(myGridLength, myGridLength, myTileSize, range); if (!((range == null) || (range.size() == 0))) { // cacluateGridSize(range); int initialWidth = (int) cacluateGridSize(range).getX(); int initialHeight = (int) cacluateGridSize(range).getY(); // System.out.println(initialWidth); // System.out.println(initialHeight); int initialSize = getPrefTileSize(initialWidth * 2 + 1, initialHeight * 2 + 1); mySampleGridView.update(initialWidth * 2 + 1, initialHeight * 2 + 1, initialSize); } mySampleGridView.setRange(range); initialize(); } private Point2D cacluateGridSize (List<Point2D> range) { double maxX = 0; double maxY = 0; for (Point2D point : range) { if (Math.abs(point.getX()) > maxX) { maxX = Math.abs(point.getX()); } if (Math.abs(point.getY()) > maxY) { maxY = Math.abs(point.getY()); } } return new Point2D.Double(maxX, maxY); } @Override protected void initialize () { VBox box = new VBox(); Scene scene = new Scene(box, RANGE_EDITOR_WIDTH, RANGE_EDITOR_HEIGHT); scene.getStylesheets().add(STYLESHEET); HBox specifedSelection = new HBox(); VBox selection = new VBox(); selection.setMinHeight(50); HBox sizeChooser = new HBox(); sizeChooser.setMinHeight(50); // Range Selections Label targetLabel = new Label("Select Range"); ChoiceBox<String> targetChoice = new ChoiceBox<>(); targetChoice.getItems().addAll(COLUMN, ROW, RADIUS, ALL, CUSTOM); TextField specifiedData = new TextField(); Button choose = new Button("Choose"); Button delete = new Button("Delete"); choose.setOnAction(new selectRangeHandler(targetChoice, specifiedData, choose)); delete.setOnAction(new selectRangeHandler(targetChoice, specifiedData, delete)); selection.getChildren().addAll(targetLabel, targetChoice); specifedSelection.getChildren().addAll(selection, specifiedData, choose, delete); // Select Button Button select = new Button("Select"); // Choose the Size VBox horizontal = new VBox(); VBox times = new VBox(); VBox vertical = new VBox(); Label HRadiusLabel = new Label("Horizontal Radius"); Label multiply = new Label(" X "); Label VRadiusLabel = new Label("Vertical Radius"); TextField HRadius = new TextField(); TextField VRadius = new TextField(); HRadius.setMaxWidth(120); VRadius.setMaxWidth(120); VRadius.setLayoutX(100); horizontal.getChildren().addAll(HRadiusLabel, HRadius); times.getChildren().add(multiply); vertical.getChildren().addAll(VRadiusLabel, VRadius); Button enter = new Button("Enter"); enter.setLayoutX(300); enter.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle (ActionEvent event) { myGridWidthNumber = Integer.parseInt(HRadius.getText()) * 2 + 1; myGridHeightNumber = Integer.parseInt(VRadius.getText()) * 2 + 1; myTileSize = getPrefTileSize(myGridWidthNumber, myGridHeightNumber); box.getChildren().clear(); // mySampleGridView = new RangeGrid(myGridLength, myGridLength, // myTileSize); mySampleGridView.update(myGridWidthNumber, myGridHeightNumber, myTileSize); box.getChildren().addAll(sizeChooser, enter, mySampleGridView, specifedSelection, select); } }); select.setOnAction(new SelectHandler(this)); sizeChooser.getChildren().addAll(horizontal, times, vertical); box.getChildren().addAll(sizeChooser, enter, mySampleGridView); setScene(scene); } private int getPrefTileSize (int gridWidthNumber, int gridHeightNumber) { int calculatedTileSize = Math.max(myGridLength / gridWidthNumber, myGridLength / gridHeightNumber); int tileSize = (calculatedTileSize < MIN_TILE_SIZE) ? MIN_TILE_SIZE : calculatedTileSize; return tileSize; } private class selectRangeHandler implements EventHandler<ActionEvent> { ChoiceBox<String> targetChoice; TextField specifiedData; Button button; public selectRangeHandler (ChoiceBox<String> tc, TextField sd, Button b) { targetChoice = tc; specifiedData = sd; button = b; } @Override public void handle (ActionEvent event) { String chosen = targetChoice.getValue().toString(); int parameter; try { parameter = Integer.parseInt(specifiedData.getText()); } catch (NumberFormatException e) { parameter = 0; } boolean toChoose = (button.getText().equals("Choose")) ? true : false; switch (chosen) { case COLUMN: mySampleGridView.rangeColumn(parameter, toChoose); break; case ROW: mySampleGridView.rangeRow(parameter, toChoose); break; case RADIUS: mySampleGridView.rangeRadius(parameter, toChoose); break; case ALL: mySampleGridView.rangeAll(toChoose); break; case CUSTOM: mySampleGridView.rangeSelectedList(); break; // default: // mySampleGridView.rangeCenterColumn(); } } } /** * Event Handler that Sends the Selected and then Closes the Popup */ private class SelectHandler implements EventHandler<ActionEvent> { RangeEditor current; public SelectHandler (RangeEditor re) { current = re; } @Override public void handle (ActionEvent event) { List<Point2D> range = mySampleGridView.getRange(); // myRange = range; range.addAll(mySampleGridView.rangeSelectedList()); // for (Point2D p : range) { // System.out.println(p.getX() + "," + p.getY()); current.close(); } } // Can't use this function to create all the vbox containing one label and // a textfiled because it makes impossible to get the content of the textfield. // Should think of other way to do similar things to avoid duplicated code. private VBox makeTextField (String label) { VBox vbox = new VBox(); Label labelText = new Label(label); TextField textField = new TextField(); vbox.getChildren().addAll(labelText, textField); return vbox; } }
package photopicker.imaging; import org.junit.Test; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import static org.junit.Assert.assertEquals; public class ImageTest { @Test public void testLandscapeMode() throws URISyntaxException, ImagingException, IOException { File imageFile = getFile("SAM_3977.JPG"); BufferedImage image = ImageUtils.loadImage(imageFile); assertEquals(1024, image.getWidth()); assertEquals(683, image.getHeight()); writeImage(image); } @Test public void testPortraitMode() throws IOException, URISyntaxException, ImagingException { File imageFile = getFile("SAM_3990.JPG"); BufferedImage image = ImageUtils.loadImage(imageFile); assertEquals(512, image.getWidth()); assertEquals(768, image.getHeight()); writeImage(image); } private void writeImage(BufferedImage image) throws IOException { File outputFile = File.createTempFile("photopicker-", ".jpg"); outputFile.deleteOnExit(); System.out.println(outputFile.getAbsolutePath()); ImageIO.write(image, "jpg", outputFile); // breakpoint here. Files get deleted after VM shutdown System.out.println("foo"); } private File getFile(String filename) throws URISyntaxException { URL url = getClass().getResource("/" + filename); return new File(url.toURI()); } }
package org.opennms.netmgt.ping; import java.net.InetAddress; import java.util.List; import junit.framework.TestCase; import org.opennms.core.utils.CollectionMath; public class PingTest extends TestCase { private Pinger m_pinger = null; private InetAddress m_goodHost = null; private InetAddress m_badHost = null; /** * Don't run this test unless the runPingTests property * is set to "true". */ @Override protected void runTest() throws Throwable { if (!isRunTest()) { System.err.println("Skipping test '" + getName() + "' because system property '" + getRunTestProperty() + "' is not set to 'true'"); return; } try { System.err.println(" super.runTest(); } finally { System.err.println(" } } private boolean isRunTest() { return Boolean.getBoolean(getRunTestProperty()); } private String getRunTestProperty() { return "runPingTests"; } @Override protected void setUp() throws Exception { if (!isRunTest()) { return; } super.setUp(); m_pinger = new Pinger(); m_goodHost = InetAddress.getByName("www.google.com"); m_badHost = InetAddress.getByName("1.1.1.1"); } public void testSinglePing() throws Exception { assertTrue(m_pinger.ping(m_goodHost) > 0); } public void testSinglePingFailure() throws Exception { assertNull(m_pinger.ping(m_badHost)); } public void testParallelPing() throws Exception { List<Number> items = m_pinger.parallelPing(m_goodHost, 20, Pinger.DEFAULT_TIMEOUT, 50); Thread.sleep(1000); printResponse(items); assertTrue(CollectionMath.countNotNull(items) > 0); } public void testParallelPingFailure() throws Exception { List<Number> items = m_pinger.parallelPing(m_badHost, 20, Pinger.DEFAULT_TIMEOUT, 50); Thread.sleep(1000); printResponse(items); assertTrue(CollectionMath.countNotNull(items) == 0); } private void printResponse(List<Number> items) { Long passed = CollectionMath.countNotNull(items); Long failed = CollectionMath.countNull(items); Number passedPercent = CollectionMath.percentNotNull(items); Number failedPercent = CollectionMath.percentNull(items); Number average = CollectionMath.average(items); Number median = CollectionMath.median(items); if (passedPercent == null) passedPercent = new Long(0); if (failedPercent == null) failedPercent = new Long(100); if (median == null) median = new Double(0); if (average == null) { average = new Double(0); } else { average = new Double(average.doubleValue() / 1000.0); } StringBuffer sb = new StringBuffer(); sb.append("response times = ").append(items); sb.append("\n"); sb.append("pings = ").append(items.size()); sb.append(", passed = ").append(passed).append(" (").append(passedPercent).append("%)"); sb.append(", failed = ").append(failed).append(" (").append(failedPercent).append("%)"); sb.append(", median = ").append(median); sb.append(", average = ").append(average).append("ms"); sb.append("\n"); System.out.print(sb); } }
// 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. // 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.collectd; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Collection; import java.util.LinkedList; import junit.framework.TestCase; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.opennms.mock.snmp.MockSnmpAgent; import org.opennms.netmgt.config.CollectdPackage; import org.opennms.netmgt.config.DataCollectionConfigFactory; import org.opennms.netmgt.config.DataSourceFactory; import org.opennms.netmgt.config.DatabaseSchemaConfigFactory; import org.opennms.netmgt.config.SnmpPeerFactory; import org.opennms.netmgt.config.collectd.Filter; import org.opennms.netmgt.config.collectd.Package; import org.opennms.netmgt.config.collectd.Service; import org.opennms.netmgt.dao.support.RrdTestUtils; import org.opennms.netmgt.mock.MockDatabase; import org.opennms.netmgt.mock.MockNetwork; import org.opennms.netmgt.model.OnmsIpInterface; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.rrd.RrdException; import org.opennms.netmgt.rrd.RrdUtils; import org.opennms.test.ConfigurationTestUtils; import org.opennms.test.FileAnticipator; import org.opennms.test.mock.MockLogAppender; import org.opennms.test.mock.MockUtil; import org.springframework.core.io.ClassPathResource; public class SnmpCollectorTest extends TestCase { private SnmpCollector m_snmpCollector; private MockSnmpAgent m_agent; private FileAnticipator m_fileAnticipator; private File m_snmpRrdDirectory; @Override protected void setUp() throws Exception { super.setUp(); MockUtil.println(" MockLogAppender.setupLogging(); MockNetwork m_network = new MockNetwork(); m_network.setCriticalService("ICMP"); m_network.addNode(1, "Router"); m_network.addInterface("127.0.0.1"); m_network.addService("ICMP"); MockDatabase m_db = new MockDatabase(); m_db.populate(m_network); DataSourceFactory.setInstance(m_db); m_fileAnticipator = new FileAnticipator(); } @Override public void runTest() throws Throwable { super.runTest(); MockLogAppender.assertNoWarningsOrGreater(); m_fileAnticipator.deleteExpected(); } @Override protected void tearDown() throws Exception { if (m_agent != null) { m_agent.shutDownAndWait(); } m_fileAnticipator.deleteExpected(true); m_fileAnticipator.tearDown(); MockUtil.println(" super.tearDown(); } public void testInstantiate() throws Exception { new SnmpCollector(); } public void testInitialize() throws Exception { initialize(); } public void testCollect() throws Exception { String svcName = "SNMP"; String m_snmpConfig = "<?xml version=\"1.0\"?>\n" + "<snmp-config port=\"1691\" retry=\"3\" timeout=\"800\"\n" + " read-community=\"public\"\n" + " version=\"v1\">\n" + "</snmp-config>\n"; initializeAgent(); Reader dataCollectionConfig = getDataCollectionConfigReader("/org/opennms/netmgt/config/datacollection-config.xml"); initialize(new StringReader(m_snmpConfig), dataCollectionConfig); dataCollectionConfig.close(); OnmsNode node = new OnmsNode(); node.setId(new Integer(1)); node.setSysObjectId(".1.3.6.1.4.1.1588.2.1.1.1"); OnmsIpInterface iface = new OnmsIpInterface("127.0.0.1", node); Collection outageCalendars = new LinkedList(); Package pkg = new Package(); Filter filter = new Filter(); filter.setContent("IPADDR IPLIKE *.*.*.*"); pkg.setFilter(filter); Service service = new Service(); service.setName(svcName); pkg.addService(service); CollectdPackage wpkg = new CollectdPackage(pkg, "foo", false); CollectionSpecification spec = new CollectionSpecification(wpkg, svcName, outageCalendars, m_snmpCollector); CollectionAgent agent = new CollectionAgent(iface); File nodeDir = m_fileAnticipator.expecting(getSnmpRrdDirectory(), "1"); for (String file : new String[] { "tcpActiveOpens", "tcpAttemptFails", "tcpCurrEstab", "tcpEstabResets", "tcpInErrors", "tcpInSegs", "tcpOutRsts", "tcpOutSegs", "tcpPassiveOpens", "tcpRetransSegs" }) { m_fileAnticipator.expecting(nodeDir, file + RrdUtils.getExtension()); } assertEquals("collection status", ServiceCollector.COLLECTION_SUCCEEDED, spec.collect(agent)); // Wait for any RRD writes to finish up Thread.sleep(1000); } public void testBrocadeCollect() throws Exception { String svcName = "SNMP"; String m_snmpConfig = "<?xml version=\"1.0\"?>\n" + "<snmp-config port=\"1691\" retry=\"3\" timeout=\"800\"\n" + " read-community=\"public\"\n" + " version=\"v1\">\n" + "</snmp-config>\n"; initializeAgent("/org/opennms/netmgt/snmp/brocadeTestData1.properties"); Reader dataCollectionConfig = getDataCollectionConfigReader("/org/opennms/netmgt/config/datacollection-brocade-config.xml"); initialize(new StringReader(m_snmpConfig), dataCollectionConfig); dataCollectionConfig.close(); OnmsNode node = new OnmsNode(); node.setId(new Integer(1)); node.setSysObjectId(".1.3.6.1.4.1.1588.2.1.1.1"); OnmsIpInterface iface = new OnmsIpInterface("127.0.0.1", node); Collection outageCalendars = new LinkedList(); Package pkg = new Package(); Filter filter = new Filter(); filter.setContent("IPADDR IPLIKE *.*.*.*"); pkg.setFilter(filter); Service service = new Service(); service.setName(svcName); pkg.addService(service); CollectdPackage wpkg = new CollectdPackage(pkg, "foo", false); CollectionSpecification spec = new CollectionSpecification(wpkg, svcName, outageCalendars, m_snmpCollector); CollectionAgent agent = new CollectionAgent(iface); File nodeDir = m_fileAnticipator.expecting(getSnmpRrdDirectory(), "1"); File brocadeDir = m_fileAnticipator.expecting(nodeDir, "brocadeFCPortIndex"); for (int i = 1; i <= 8; i++) { File brocadeIndexDir = m_fileAnticipator.expecting(brocadeDir, Integer.toString(i)); m_fileAnticipator.expecting(brocadeIndexDir, "strings.properties"); for (String file : new String[] { "swFCPortTxWords", "swFCPortRxWords" }) { m_fileAnticipator.expecting(brocadeIndexDir, file + RrdUtils.getExtension()); } } assertEquals("collection status", ServiceCollector.COLLECTION_SUCCEEDED, spec.collect(agent)); // Wait for any RRD writes to finish up Thread.sleep(1000); } public void initialize(Reader snmpConfig, Reader dataCollectionConfig) throws MarshalException, ValidationException, IOException, RrdException { //RrdConfig.loadProperties(new ByteArrayInputStream(s_rrdConfig.getBytes())); RrdTestUtils.initialize(); SnmpPeerFactory.setInstance(new SnmpPeerFactory(snmpConfig)); DataCollectionConfigFactory.setInstance(new DataCollectionConfigFactory(dataCollectionConfig)); Reader rdr = ConfigurationTestUtils.getReaderForResource(this, "/org/opennms/netmgt/config/test-database-schema.xml"); DatabaseSchemaConfigFactory.setInstance(new DatabaseSchemaConfigFactory(rdr)); rdr.close(); m_snmpCollector = new SnmpCollector(); m_snmpCollector.initialize(null); // no properties are passed } public void initialize() throws IOException, MarshalException, ValidationException, RrdException { Reader snmpConfig = ConfigurationTestUtils.getReaderForResource(this, "/org/opennms/netmgt/config/snmp-config.xml"); Reader dataCollectionConfig = getDataCollectionConfigReader("/org/opennms/netmgt/config/datacollection-config.xml"); initialize(snmpConfig, dataCollectionConfig); snmpConfig.close(); dataCollectionConfig.close(); } private Reader getDataCollectionConfigReader(String classPathLocation) throws IOException { return ConfigurationTestUtils.getReaderForResourceWithReplacements(this, classPathLocation, new String[] { "%rrdRepository%", getSnmpRrdDirectory().getAbsolutePath() }); } private File getSnmpRrdDirectory() throws IOException { if (m_snmpRrdDirectory == null) { m_snmpRrdDirectory = m_fileAnticipator.tempDir("snmp"); } return m_snmpRrdDirectory; } private void initializeAgent(String testData) throws InterruptedException { m_agent = MockSnmpAgent.createAgentAndRun(new ClassPathResource(testData), "127.0.0.1/1691"); } private void initializeAgent() throws InterruptedException { initializeAgent("/org/opennms/netmgt/snmp/snmpTestData1.properties"); } }
package org.python.pydev.editor.codecompletion; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.osgi.framework.Bundle; import org.python.pydev.editor.PyEdit; import org.python.pydev.editor.model.AbstractNode; import org.python.pydev.editor.model.Location; import org.python.pydev.editor.model.ModelUtils; import org.python.pydev.editor.model.Scope; import org.python.pydev.plugin.PydevPlugin; /** * @author Dmoore * @author Fabio Zadrozny */ public class PyCodeCompletion { int docBoundary = -1; // the document prior to the activation token private PythonShell pytonShell; /** * @param theDoc: * the whole document as a string. * @param documentOffset: * the cursor position */ String partialDocument(String theDoc, int documentOffset) { if (this.docBoundary < 0) { calcDocBoundary(theDoc, documentOffset); } if (this.docBoundary != -1) { String before = theDoc.substring(0, this.docBoundary); return before; } return ""; } /** * Returns a list with the tokens to use for autocompletion. * * @param edit * @param doc * @param documentOffset * * @param theActivationToken * @return * @throws CoreException */ public List autoComplete(PyEdit edit, IDocument doc, int documentOffset, java.lang.String theActivationToken) throws CoreException { List theList = new ArrayList(); PythonShell serverShell = null; try { serverShell = PythonShell.getServerShell(); } catch (Exception e) { throw new RuntimeException(e); } String docToParse = getDocToParse(doc, documentOffset); String trimmed = theActivationToken.replace('.', ' ').trim(); String importsTipper = getImportsTipperStr(theActivationToken, edit, doc, documentOffset); if (importsTipper.length()!=0) { //may be space. List completions = serverShell.getImportCompletions(importsTipper); theList.addAll(completions); } else if (trimmed.equals("") == false && theActivationToken.indexOf('.') != -1) { List completions; if (trimmed.equals("self")) { Location loc = Location.offsetToLocation(doc, documentOffset); AbstractNode closest = ModelUtils.getLessOrEqualNode(edit .getPythonModel(), loc); if(closest == null){ completions = serverShell.getTokenCompletions(trimmed, docToParse); }else{ Scope scope = closest.getScope().findContainingClass(); //null returned if self. within a method and not in a class. String token = scope.getStartNode().getName(); completions = serverShell .getClassCompletions(token, docToParse); } } else { completions = serverShell.getTokenCompletions(trimmed, docToParse); } theList.addAll(completions); } else { //go to globals List completions = serverShell.getGlobalCompletions(docToParse); theList.addAll(completions); } return theList; } /** * @param theActivationToken * @param edit * @param doc * @param documentOffset * @return */ public String getImportsTipperStr(String theActivationToken, PyEdit edit, IDocument doc, int documentOffset) { String importMsg = ""; try { IRegion region = doc.getLineInformationOfOffset(documentOffset); String string = doc.get(region.getOffset(), documentOffset-region.getOffset()); int fromIndex = string.indexOf("from"); int importIndex = string.indexOf("import"); if(fromIndex != -1 || importIndex != -1){ string = string.replaceAll("#.*", ""); //remove comments String[] strings = string.split(" "); for (int i = 0; i < strings.length; i++) { if(strings[i].equals("from")==false && strings[i].equals("import")==false){ if(importMsg.length() != 0){ importMsg += '.'; } importMsg += strings[i]; } } if(fromIndex != -1 && importIndex != -1){ if(strings.length == 3){ importMsg += '.'; } } }else{ return ""; } } catch (BadLocationException e) { e.printStackTrace(); } if (importMsg.indexOf(".") == -1){ return " "; } if (importMsg.length() > 0 && importMsg.endsWith(".") == false ){ importMsg = importMsg.substring(0, importMsg.lastIndexOf('.')); } return importMsg; } /** * @param doc * @param documentOffset * @return */ public static String getDocToParse(IDocument doc, int documentOffset) { int lineOfOffset = -1; try { lineOfOffset = doc.getLineOfOffset(documentOffset); } catch (BadLocationException e) { e.printStackTrace(); } if(lineOfOffset!=-1) return "\n"+getDocToParseFromLine(doc, lineOfOffset); else return ""; } /** * @param doc * @param documentOffset * @param lineOfOffset * @return */ public static String getDocToParseFromLine(IDocument doc, int lineOfOffset) { String wholeDoc = doc.get(); String newDoc = ""; try { IRegion lineInformation = doc.getLineInformation(lineOfOffset); int docLength = doc.getLength(); String src = doc.get(lineInformation.getOffset(), lineInformation.getLength()); String spaces = ""; for (int i = 0; i < src.length(); i++) { if (src.charAt(i) != ' ') { break; } spaces += ' '; } newDoc = wholeDoc.substring(0, lineInformation.getOffset()); newDoc += spaces + "pass"; newDoc += wholeDoc.substring(lineInformation.getOffset() + lineInformation.getLength(), docLength); } catch (BadLocationException e1) { e1.printStackTrace(); } return newDoc; } /** * * @param useSimpleTipper * @return the script to get the variables. * * @throws CoreException */ public static File getAutoCompleteScript() throws CoreException { return getScriptWithinPySrc("simpleTipper.py"); } /** * * @return the script to get the variables. * * @throws CoreException */ public static File getScriptWithinPySrc(String targetExec) throws CoreException { IPath relative = new Path("PySrc").addTrailingSeparator().append( targetExec); Bundle bundle = PydevPlugin.getDefault().getBundle(); URL bundleURL = Platform.find(bundle, relative); URL fileURL; try { fileURL = Platform.asLocalURL(bundleURL); File f = new File(fileURL.getPath()); return f; } catch (IOException e) { throw new CoreException(PydevPlugin.makeStatus(IStatus.ERROR, "Can't find python debug script", null)); } } public static File getImageWithinIcons(String icon) throws CoreException { IPath relative = new Path("icons").addTrailingSeparator().append(icon); Bundle bundle = PydevPlugin.getDefault().getBundle(); URL bundleURL = Platform.find(bundle, relative); URL fileURL; try { fileURL = Platform.asLocalURL(bundleURL); File f = new File(fileURL.getPath()); return f; } catch (IOException e) { throw new CoreException(PydevPlugin.makeStatus(IStatus.ERROR, "Can't find image", null)); } } /** * The docBoundary should get until the last line before the one we are * editing. * * @param qualifier * @param documentOffset * @param proposals */ public void calcDocBoundary(String theDoc, int documentOffset) { this.docBoundary = theDoc.substring(0, documentOffset) .lastIndexOf('\n'); } /** * Returns the activation token. * * @param theDoc * @param documentOffset * @return */ public String getActivationToken(String theDoc, int documentOffset) { if (this.docBoundary < 0) { calcDocBoundary(theDoc, documentOffset); } String str = theDoc.substring(this.docBoundary + 1, documentOffset); if (str.endsWith(" ")) { return " "; } int lastSpaceIndex = str.lastIndexOf(' '); int lastParIndex = str.lastIndexOf('('); if(lastParIndex != -1 || lastSpaceIndex != -1){ int lastIndex = lastSpaceIndex > lastParIndex ? lastSpaceIndex : lastParIndex; return str.substring(lastIndex+1, str.length()); } return str; } }
package net.lucenews.controller; import java.io.*; import java.util.*; import net.lucenews.*; import net.lucenews.model.*; import net.lucenews.model.exception.*; import net.lucenews.view.*; import net.lucenews.atom.*; import javax.xml.parsers.*; import javax.xml.transform.*; import org.apache.log4j.*; import org.xml.sax.*; import org.w3c.dom.*; public class ServiceController extends Controller { /** * Displays the service in the form of an Atom Introspection Document. * * @param c The context * @throws LuceneException * @throws IndicesNotFoundException * @throws TransformerException * @throws ParserConfigurationException * @throws IOException */ public static void doGet (LuceneContext c) throws LuceneException, IndicesNotFoundException, TransformerException, ParserConfigurationException, IOException { Logger.getLogger(ServiceController.class).trace("doGet(LuceneContext)"); LuceneWebService service = c.getService(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest request = c.getRequest(); LuceneResponse response = c.getResponse(); response.setContentType( "application/atomsvc+xml; charset=utf-8" ); AtomView.process( c, asIntrospectionDocument( c, service, request ) ); } /** * Posts a new index (or indices) to the web service. * * @param c The context * @throws IndicesAlreadyExistException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws AtomParseException * @throws LuceneException */ public static void doPost (LuceneContext c) throws IllegalActionException, IndicesAlreadyExistException, TransformerException, ParserConfigurationException, SAXException, IOException, InsufficientDataException, LuceneException, AtomParseException { Logger.getLogger(ServiceController.class).trace("doPost(LuceneContext)"); LuceneWebService service = c.getService(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest request = c.getRequest(); LuceneResponse response = c.getResponse(); StringBuffer indexNamesBuffer = new StringBuffer(); boolean created = false; Entry[] entries = getEntries( c, request ); for (int i = 0; i < entries.length; i++) { Entry entry = entries[ i ]; // Index name String name = entry.getTitle(); //Properties properties = ServletUtils.getProperties( entry.getContent() ); Properties properties = XOXOController.asProperties( c, entry ); File parentDirectory = manager.getCreatedIndicesDirectory(); File directory = new File( parentDirectory, name ); LuceneIndex index = null; // We don't want any exceptions thrown to give away // where in the file system the index was being // placed at. try { index = LuceneIndex.create( directory ); } catch (IndexAlreadyExistsException iaee) { throw new IndexAlreadyExistsException( name ); } if (properties != null) { index.setProperties( properties ); } created = true; if (i > 0) { indexNamesBuffer.append( "," ); } indexNamesBuffer.append( index.getName() ); response.setStatus( response.SC_CREATED ); } if (created) { response.addHeader( "Location", service.getIndexURI( request, indexNamesBuffer.toString() ).toString() ); } else { throw new InsufficientDataException( "No indices to be added" ); } XMLController.acknowledge( c ); } public static Entry[] getEntries (LuceneContext c, LuceneRequest request) throws TransformerConfigurationException, TransformerException, ParserConfigurationException, SAXException, IOException, AtomParseException { List<Entry> entries = new LinkedList<Entry>(); Feed feed = request.getFeed(); Entry entry = request.getEntry(); if (feed != null) { entries.addAll( feed.getEntries() ); } if (entry != null) { entries.add( entry ); } return entries.toArray( new Entry[]{} ); } /** * Converts a Lucene web service into an Atom introspection document. * * @param service The web service to be converted * @param request a Lucene request to govern URL generation * @return An Atom introspection document * @throws IndicesNotFoundException * @throws IOException */ public static IntrospectionDocument asIntrospectionDocument (LuceneContext c, LuceneWebService service, LuceneRequest request) throws IndicesNotFoundException, IOException { IntrospectionDocument d = new IntrospectionDocument(); Workspace w = new Workspace( service.getTitle() ); List<LuceneIndex> indicesList = new ArrayList<LuceneIndex>( Arrays.asList( service.getIndexManager().getIndices() ) ); Collections.sort( indicesList, new IndexComparator() ); LuceneIndex[] indices = indicesList.toArray( new LuceneIndex[]{} ); for (LuceneIndex index : indices) { // TODO: remove the adding of the empty path to make this work with Perl client! String href = service.getIndexURI( request, index ).withPath("").toString(); String title = index.getTitle(); if (title == null) { title = index.getName(); } String member_type = "entry"; String list_template = null; AtomCollection coll = new AtomCollection( title, href, member_type, list_template ); w.addCollection( coll ); } d.addWorkspace( w ); return d; } /** * Transforms a Lucene web service into an Atom feed. * * @return An Atom feed * @throws IndicesNotFoundException * @throws IOException */ public static Feed asFeed (LuceneContext c, LuceneWebService service, LuceneRequest request) throws IndicesNotFoundException, IOException { Feed feed = new Feed(); feed.setTitle( "Lucene Web Service" ); //feed.setUpdated( service.getLastModified() ); feed.setID( service.getServiceURI( request ).toString() ); //Iterator<LuceneIndex> indices = service.getIndexManager().getIndices().iterator(); //while( indices.hasNext() ) // feed.addEntry( asEntry( service, indices.next() ) ); List<LuceneIndex> list = Arrays.asList( service.getIndexManager().getIndices() ); Collections.sort( list, new IndexComparator() ); LuceneIndex[] indices = list.toArray( new LuceneIndex[]{} ); for (LuceneIndex index : indices) { feed.addEntry( asEntry( c, service, request, index ) ); } feed.addLink( Link.Alternate( service.getServiceURI( request ).toString() ) ); return feed; } /** * Transforms a Lucene web service into an Atom Entry. * * @param service The web service * @param request The request * @param index The index * @return An Atom entry * @throws IOException */ public static Entry asEntry (LuceneContext c, LuceneWebService service, LuceneRequest request, LuceneIndex index) throws IOException { Entry entry = new Entry(); entry.setTitle( index.getTitle() ); //entry.setUpdated( index.getLastModified() ); entry.setID( service.getIndexURI( request, index ).toString() ); String summary = null; try { summary = index.getSummary(); } catch (FileNotFoundException fnfe) { summary = null; } if (summary == null) { int count = index.getDocumentCount(); switch (count) { case 0: summary = "Index '" + index.getName() + "' contains no documents."; break; case 1: summary = "Index '" + index.getName() + "' contains 1 document."; break; default: summary = "Index '" + index.getName() + "' contains " + index.getDocumentCount() + " documents."; } } entry.addLink( Link.Alternate( service.getIndexURI( request, index ).toString() ) ); entry.setSummary( new net.lucenews.atom.Text( summary ) ); return entry; } } class IndexComparator implements Comparator<LuceneIndex> { public IndexComparator () { } public int compare (LuceneIndex i1, LuceneIndex i2) { try { String title1 = i1.getTitle(); String title2 = i2.getTitle(); String comparable1 = title1 == null ? i1.getName() : title1; String comparable2 = title2 == null ? i2.getName() : title2; if (comparable1 == null && comparable1 == null) { return 0; } if (comparable1 != null && comparable2 != null) { return comparable1.toLowerCase().compareTo( comparable2.toLowerCase() ); } if (comparable1 != null) { return 1; } if (comparable2 != null) { return -1; } return 0; } catch (IOException ioe) { return 0; } } }
package therapeuticpresence; import javax.media.opengl.GL; import therapeuticskeleton.Skeleton; import processing.core.*; import SimpleOpenNI.*; import processing.opengl.*; import scenes.*; import visualisations.*; /* The main application class. * TherapeuticPresence maintains interfaces to * the kinect * the scene * the skeleton in the scene * the active visualisation * the gui * It also contains the basic setup variables. It handles keyboard events. * Workflow is * setting up the kinect and the gui according to setup variables * set up a basic 3d scene * set up depth map visualisation * wait for user to enter the scene * calibrate user (automatic or pose) * set up skeleton from kinect data (skeleton updates itself) * set up chosen scene type * set up chosen visualisation and play * wait for user input */ public class TherapeuticPresence extends PApplet { private static final long serialVersionUID = 1L; public static final short MAX_USERS = 4; public static final short DEPTHMAP_VISUALISATION = 0; public static final short STICKFIGURE_VISUALISATION = 1; public static final short GENERATIVE_TREE_2D_VISUALISATION = 2; public static final short GENERATIVE_TREE_3D_VISUALISATION = 3; public static final short GEOMETRY_2D_VISUALISATION = 4; public static final short GEOMETRY_3D_VISUALISATION = 5; public static final short ELLIPSOIDAL_3D_VISUALISATION = 6; public static final short BASIC_SCENE2D = 0; public static final short BASIC_SCENE3D = 1; public static final short TUNNEL_SCENE2D = 2; public static final short TUNNEL_SCENE3D = 3; public static boolean fullBodyTracking = true; // control for full body tracking public static boolean calculateLocalCoordSys = true; // control for full body tracking public static boolean evaluatePostureAndGesture = true; // control for full body tracking public static boolean recordFlag = true; // set to false for playback public static boolean debugOutput = false; public static short initialVisualisationMethod = TherapeuticPresence.DEPTHMAP_VISUALISATION; public static short defaultVisualisationMethod = TherapeuticPresence.ELLIPSOIDAL_3D_VISUALISATION; public static short currentVisualisationMethod; public static short initialSceneType = TherapeuticPresence.BASIC_SCENE3D; public static short defaultSceneType = TherapeuticPresence.TUNNEL_SCENE3D; public static short currentSceneType; public static short mirrorTherapy = Skeleton.MIRROR_THERAPY_OFF; public static boolean autoCalibration = true; // control for auto calibration of skeleton public static boolean mirrorKinect = false; public static float maxDistanceToKinect = 2500f; // in mm public static final float DEFAULT_POSTURE_TOLERANCE = 0.5f; public static float postureTolerance = TherapeuticPresence.DEFAULT_POSTURE_TOLERANCE; public static final float DEFAULT_GESTURE_TOLERANCE = 0.7f; public static float gestureTolerance = TherapeuticPresence.DEFAULT_POSTURE_TOLERANCE; public static final float DEFAULT_SMOOTHING_SKELETON = 0.8f; public static float smoothingSkeleton = TherapeuticPresence.DEFAULT_SMOOTHING_SKELETON; // interface to talk to kinect protected SimpleOpenNI kinect = null; // interface to the Scene/Background protected AbstractScene scene = null; // interface to the chosen visualisation object protected AbstractVisualisation nextVisualisation = null; protected AbstractVisualisation visualisation = null; protected AbstractVisualisation lastVisualisation = null; // the skeleton that control the scene, only one user for now protected Skeleton skeleton = null; // user interface protected GuiHud guiHud = null; // audio interface protected AudioManager audioManager = null; // posture processing for skeleton interface protected PostureProcessing postureProcessing = null; public void setup() { size(screenWidth-16,screenHeight-128,OPENGL); // establish connection to kinect/openni setupKinect(); // start the audio interface audioManager = new AudioManager(this); audioManager.setup(); audioManager.start(); // setup Scene setupScene(TherapeuticPresence.initialSceneType); // start visualisation (default is depthMap) setupVisualisation(TherapeuticPresence.initialVisualisationMethod); // generate HUD guiHud = new GuiHud(this); } private void setupKinect () { kinect = new SimpleOpenNI(this); if (TherapeuticPresence.recordFlag) { // enable/disable mirror kinect.setMirror(mirrorKinect); // enable depthMap generation kinect.enableDepth(); if (TherapeuticPresence.fullBodyTracking) { // enable skeleton generation for all joints kinect.enableUser(SimpleOpenNI.SKEL_PROFILE_ALL); } else { // enable skeleton generation for upper joints kinect.enableUser(SimpleOpenNI.SKEL_PROFILE_UPPER); } } else { if (kinect.openFileRecording("../data/test.oni") == false) { println("fehler"); } } } public void setMirrorKinect (boolean _mirrorKinect) { // if (skeleton != null) { // kinect.stopTrackingSkeleton(skeleton.userId); // mirrorKinect = _mirrorKinect; // kinect.setMirror(mirrorKinect); // kinect.update(); // if (skeleton != null) { // kinect.startTrackingSkeleton(skeleton.userId); } public void setupScene (short _sceneType) { switch (_sceneType) { case TherapeuticPresence.BASIC_SCENE2D: scene = new BasicScene2D(this,color(0,0,0)); scene.reset(); currentSceneType = TherapeuticPresence.BASIC_SCENE2D; break; case TherapeuticPresence.TUNNEL_SCENE2D: if (audioManager != null) { scene = new TunnelScene2D(this,color(0,0,0),audioManager); scene.reset(); currentSceneType = TherapeuticPresence.TUNNEL_SCENE2D; } else { setupScene(TherapeuticPresence.BASIC_SCENE2D); debugMessage("setupScene(short): AudioManager needed for Tunnel Scene!"); } break; case TherapeuticPresence.TUNNEL_SCENE3D: if (audioManager != null) { scene = new TunnelScene3D(this,color(0,0,0),audioManager); scene.reset(); currentSceneType = TherapeuticPresence.TUNNEL_SCENE3D; } else { setupScene(TherapeuticPresence.BASIC_SCENE3D); debugMessage("setupScene(short): AudioManager needed for Tunnel Scene!"); } break; default: scene = new BasicScene3D(this,color(0,0,0)); scene.reset(); currentSceneType = TherapeuticPresence.BASIC_SCENE3D; break; } if (postureProcessing != null) { postureProcessing.setScene(scene); } } public void setupVisualisation (short _visualisationMethod) { // prepare for fade out lastVisualisation = visualisation; visualisation = null; // set up next visualisation for fade in switch (_visualisationMethod) { case TherapeuticPresence.STICKFIGURE_VISUALISATION: nextVisualisation = new StickfigureVisualisation(this,skeleton); nextVisualisation.setup(); currentVisualisationMethod = TherapeuticPresence.STICKFIGURE_VISUALISATION; break; case TherapeuticPresence.GENERATIVE_TREE_2D_VISUALISATION: nextVisualisation = new GenerativeTree2DVisualisation(this,skeleton,audioManager); nextVisualisation.setup(); currentVisualisationMethod = TherapeuticPresence.GENERATIVE_TREE_2D_VISUALISATION; break; case TherapeuticPresence.GENERATIVE_TREE_3D_VISUALISATION: nextVisualisation = new GenerativeTree3DVisualisation(this,skeleton,audioManager); nextVisualisation.setup(); currentVisualisationMethod = TherapeuticPresence.GENERATIVE_TREE_3D_VISUALISATION; break; case TherapeuticPresence.GEOMETRY_2D_VISUALISATION: nextVisualisation = new Geometry2DVisualisation(this,skeleton,audioManager); nextVisualisation.setup(); currentVisualisationMethod = TherapeuticPresence.GEOMETRY_2D_VISUALISATION; break; case TherapeuticPresence.GEOMETRY_3D_VISUALISATION: nextVisualisation = new Geometry3DVisualisation(this,skeleton,audioManager); nextVisualisation.setup(); currentVisualisationMethod = TherapeuticPresence.GEOMETRY_3D_VISUALISATION; break; case TherapeuticPresence.ELLIPSOIDAL_3D_VISUALISATION: nextVisualisation = new Ellipsoidal3DVisualisation(this,skeleton,audioManager); nextVisualisation.setup(); currentVisualisationMethod = TherapeuticPresence.ELLIPSOIDAL_3D_VISUALISATION; break; default: nextVisualisation = new DepthMapVisualisation(this,kinect); nextVisualisation.setup(); currentVisualisationMethod = TherapeuticPresence.DEPTHMAP_VISUALISATION; break; } if (postureProcessing != null) { postureProcessing.setVisualisation(nextVisualisation); } } public void draw() { if (kinect != null) { kinect.update(); } if (skeleton != null && kinect.isTrackingSkeleton(skeleton.getUserId())) { skeleton.update(); } if (audioManager != null) { audioManager.update(); } if (postureProcessing != null) { postureProcessing.updatePosture(); postureProcessing.triggerAction(); } if (scene != null) { scene.reset(); } if (lastVisualisation != null) { if (lastVisualisation.fadeOut()) { // true when visualisation has done fade out lastVisualisation = null; } } if (nextVisualisation != null) { if (nextVisualisation.fadeIn()) { // true when visualisation has done fade in visualisation = nextVisualisation; if (postureProcessing != null) { postureProcessing.setVisualisation(visualisation); } nextVisualisation = null; } } if (visualisation != null) { visualisation.draw(); } if (guiHud != null) { guiHud.draw(); } } public void debugMessage (String _message) { guiHud.sendGuiMessage(_message); println(_message); } // is triggered by SimpleOpenNI on "onEndCalibration" and by user on "loadCalibration" // starts tracking of a Skeleton private void newSkeletonFound (int _userId) { if (_userId < 0 || _userId > TherapeuticPresence.MAX_USERS) { debugMessage("newSkeletonFound: User id "+_userId+" outside range. Maximum users: "+TherapeuticPresence.MAX_USERS); } else { if (skeleton != null ) { debugMessage("Skeleton of user "+skeleton.getUserId()+" replaced with skeleton of user "+_userId+"!"); } skeleton = new Skeleton(kinect,_userId,fullBodyTracking,calculateLocalCoordSys,evaluatePostureAndGesture,mirrorTherapy); skeleton.setPostureTolerance(DEFAULT_POSTURE_TOLERANCE); skeleton.setGestureTolerance(DEFAULT_GESTURE_TOLERANCE); kinect.setSmoothingSkeleton(smoothingSkeleton); // start default scene and visualisation postureProcessing = new PostureProcessing(this,skeleton,scene,visualisation); setupScene(defaultSceneType); setupVisualisation(defaultVisualisationMethod); } } // is triggered by SimpleOpenNi on "onLostUser" private void skeletonLost (int _userId) { if (_userId < 0 || _userId > TherapeuticPresence.MAX_USERS) { debugMessage("skeletonLost: User id "+_userId+" outside range. Maximum users: "+TherapeuticPresence.MAX_USERS); } else { skeleton = null; postureProcessing = null; setupScene(initialSceneType); setupVisualisation(initialVisualisationMethod); int[] users = kinect.getUsers(); if (users.length!=0) { if(TherapeuticPresence.autoCalibration) kinect.requestCalibrationSkeleton(users[0],true); else kinect.startPoseDetection("Psi",users[0]); } } } // call back for guihud public void switchMirrorTherapy (short _mirrorTherapy) { if (_mirrorTherapy >= Skeleton.MIRROR_THERAPY_OFF && _mirrorTherapy <= Skeleton.MIRROR_THERAPY_RIGHT) { mirrorTherapy = _mirrorTherapy; } else { mirrorTherapy = Skeleton.MIRROR_THERAPY_OFF; } if (skeleton != null) { skeleton.setMirrorTherapy(mirrorTherapy); } } public void changePostureTolerance (float _postureTolerance) { if (skeleton != null) { if (_postureTolerance >= 0f && _postureTolerance <= 1.0f) { postureTolerance = _postureTolerance; skeleton.setPostureTolerance(postureTolerance); } else { postureTolerance = DEFAULT_POSTURE_TOLERANCE; skeleton.setPostureTolerance(postureTolerance); } } } public void changeGestureTolerance (float _gestureTolerance) { if (skeleton != null) { if (_gestureTolerance >= 0f && _gestureTolerance <= 1.0f) { gestureTolerance = _gestureTolerance; skeleton.setGestureTolerance(gestureTolerance); } else { gestureTolerance = DEFAULT_GESTURE_TOLERANCE; skeleton.setGestureTolerance(gestureTolerance); } } } public void changeSmoothingSkeleton (float _smoothingSkeleton) { if (_smoothingSkeleton >= 0f && _smoothingSkeleton <= 1.0f) { smoothingSkeleton = _smoothingSkeleton; kinect.setSmoothingSkeleton(smoothingSkeleton); } else { smoothingSkeleton = DEFAULT_SMOOTHING_SKELETON; kinect.setSmoothingSkeleton(smoothingSkeleton); } } // SimpleOpenNI user events public void onNewUser(int userId) { debugMessage("New User "+userId+" entered the scene."); if (skeleton == null) { debugMessage(" start pose detection"); if(TherapeuticPresence.autoCalibration) kinect.requestCalibrationSkeleton(userId,true); else kinect.startPoseDetection("Psi",userId); } else { debugMessage(" no pose detection, skeleton is already tracked"); kinect.startTrackingSkeleton(skeleton.getUserId()); } } public void onLostUser(int userId) { debugMessage("onLostUser - userId: " + userId); if (userId == skeleton.getUserId()) { this.skeletonLost(userId); } } public void onStartCalibration(int userId) { debugMessage("onStartCalibration - userId: " + userId); } public void onEndCalibration(int userId, boolean successfull) { debugMessage("onEndCalibration - userId: " + userId + ", successfull: " + successfull); if (successfull) { debugMessage(" User calibrated !!!"); kinect.startTrackingSkeleton(userId); //kinect.update(); // one update loop before going on with calculations prevents kinect to be in an unstable state this.newSkeletonFound(userId); } else { debugMessage(" Failed to calibrate user !!!"); debugMessage(" Start pose detection"); kinect.startPoseDetection("Psi",userId); } } public void onStartPose(String pose,int userId) { debugMessage("onStartdPose - userId: " + userId + ", pose: " + pose); debugMessage(" stop pose detection"); kinect.stopPoseDetection(userId); kinect.requestCalibrationSkeleton(userId, true); } public void onEndPose(String pose,int userId) { debugMessage("onEndPose - userId: " + userId + ", pose: " + pose); } // Keyboard events public void keyPressed() { switch(key) { // save user calibration data case 'o': if(skeleton != null && kinect.isTrackingSkeleton(skeleton.getUserId())){ if(kinect.saveCalibrationDataSkeleton(skeleton.getUserId(),"../data/calibration"+skeleton.getUserId()+".skel")) debugMessage("Saved current calibration for user "+skeleton.getUserId()+" to file."); else debugMessage("Can't save calibration for user "+skeleton.getUserId()+" to file."); } else { debugMessage("There is no calibration data to save. No skeleton found."); } break; // load user calibration data case 'l': IntVector userList = new IntVector(); kinect.getUsers(userList); if (userList.size() > 0) { if(kinect.loadCalibrationDataSkeleton(userList.get(0),"../data/calibration"+userList.get(0)+".skel")) { kinect.startTrackingSkeleton(userList.get(0)); kinect.stopPoseDetection(userList.get(0)); this.newSkeletonFound(userList.get(0)); debugMessage("Loaded calibration for user "+userList.get(0)+" from file."); } else { debugMessage("Can't load calibration file for user "+userList.get(0)); } } else { debugMessage("No calibration data loaded. You need at least one active user!"); } break; case 'm': setMirrorKinect(!mirrorKinect); break; } if (scene.sceneIs3D()) { switch (key) { case 'w': ((BasicScene3D)scene).translateZ -= 100.0f; break; case 'W': ((BasicScene3D)scene).translateY -= 100.0f; break; case 'a': ((BasicScene3D)scene).translateX += 100.0f; break; case 's': ((BasicScene3D)scene).translateZ += 100.0f; break; case 'S': ((BasicScene3D)scene).translateY += 100.0f; break; case 'd': ((BasicScene3D)scene).translateX -= 100.0f; break; } switch(keyCode) { case LEFT: ((BasicScene3D)scene).rotY += 100.0f; break; case RIGHT: ((BasicScene3D)scene).rotY -= 100.0f; break; case UP: if(keyEvent.isShiftDown()) ((BasicScene3D)scene).rotZ += 100.0f; else ((BasicScene3D)scene).rotX += 100.0f; break; case DOWN: if(keyEvent.isShiftDown()) ((BasicScene3D)scene).rotZ -= 100.0f; else ((BasicScene3D)scene).rotX -= 100.0f; break; } } } public static void main (String args[]) { PApplet.main(new String[] {"--present","therapeuticpresence.TherapeuticPresence"}); } }
package cc.mallet.classify.tui; import java.util.logging.*; import java.util.Iterator; import java.util.Random; import java.util.BitSet; import java.util.ArrayList; import java.util.Collections; import java.io.*; import cc.mallet.classify.*; import cc.mallet.pipe.*; import cc.mallet.pipe.iterator.*; import cc.mallet.types.*; import cc.mallet.util.*; /** A command-line tool for manipulating InstanceLists. For example, reducing the feature space by information gain. @author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a> */ public class Vectors2Vectors { private static Logger logger = MalletLogger.getLogger(Vectors2Vectors.class.getName()); static CommandOption.File inputFile = new CommandOption.File (Vectors2Vectors.class, "input", "FILE", true, new File("-"), "Read the instance list from this file; Using - indicates stdin.", null); static CommandOption.File outputFile = new CommandOption.File (Vectors2Vectors.class, "output", "FILE", true, new File("-"), "Write pruned instance list to this file (use --training-file etc. if you are splitting the list). Using - indicates stdin.", null); static CommandOption.File trainingFile = new CommandOption.File (Vectors2Vectors.class, "training-file", "FILE", true, new File("training.vectors"), "Write the training set instance list to this file (or use --output if you are only pruning features); Using - indicates stdout.", null); static CommandOption.File testFile = new CommandOption.File (Vectors2Vectors.class, "testing-file", "FILE", true, new File("test.vectors"), "Write the test set instance list to this file; Using - indicates stdout.", null); static CommandOption.File validationFile = new CommandOption.File (Vectors2Vectors.class, "validation-file", "FILE", true, new File("validation.vectors"), "Write the validation set instance list to this file; Using - indicates stdout.", null); static CommandOption.Double trainingProportion = new CommandOption.Double (Vectors2Vectors.class, "training-portion", "DECIMAL", true, 1.0, "The fraction of the instances that should be used for training.", null); static CommandOption.Double validationProportion = new CommandOption.Double (Vectors2Vectors.class, "validation-portion", "DECIMAL", true, 0.0, "The fraction of the instances that should be used for validation.", null); static CommandOption.Integer randomSeed = new CommandOption.Integer (Vectors2Vectors.class, "random-seed", "INTEGER", true, 0, "The random seed for randomly selecting a proportion of the instance list for training", null); static CommandOption.Integer pruneInfogain = new CommandOption.Integer (Vectors2Vectors.class, "prune-infogain", "N", false, 0, "Reduce features to the top N by information gain.", null); static CommandOption.Integer pruneCount = new CommandOption.Integer (Vectors2Vectors.class, "prune-count", "N", false, 0, "Reduce features to those that occur more than N times.", null); static CommandOption.Integer pruneDocFreq = new CommandOption.Integer (Vectors2Vectors.class, "prune-document-freq", "N", false, 0, "Reduce features to those that occur in more than N contexts.", null); static CommandOption.Double minIDF = new CommandOption.Double (Vectors2Vectors.class, "min-idf", "NUMBER", false, 0, "Remove features with inverse document frequency less than this value.", null); static CommandOption.Double maxIDF = new CommandOption.Double (Vectors2Vectors.class, "max-idf", "NUMBER", false, Double.POSITIVE_INFINITY, "Remove features with inverse document frequency greater than this value.", null); static CommandOption.Boolean vectorToSequence = new CommandOption.Boolean (Vectors2Vectors.class, "vector-to-sequence", "[TRUE|FALSE]", false, false, "Convert FeatureVector's to FeatureSequence's.", null); static CommandOption.Boolean hideTargets = new CommandOption.Boolean (Vectors2Vectors.class, "hide-targets", "[TRUE|FALSE]", false, false, "Hide targets.", null); static CommandOption.Boolean revealTargets = new CommandOption.Boolean (Vectors2Vectors.class, "reveal-targets", "[TRUE|FALSE]", false, false, "Reveal targets.", null); public static void main (String[] args) throws FileNotFoundException, IOException { // Process the command-line options CommandOption.setSummary (Vectors2Vectors.class, "A tool for manipulating instance lists of feature vectors."); CommandOption.process (Vectors2Vectors.class, args); // Print some helpful messages for error cases if (args.length == 0) { CommandOption.getList(Vectors2Vectors.class).printUsage(false); System.exit (-1); } Random r = randomSeed.wasInvoked() ? new Random (randomSeed.value) : new Random (); double t = trainingProportion.value; double v = validationProportion.value; logger.info ("Training portion = "+t); logger.info ("Validation portion = "+v); logger.info ("Testing portion = "+(1-v-t)); logger.info ("Prune info gain = "+pruneInfogain.value); logger.info ("Prune count = "+pruneCount.value); // Read the InstanceList InstanceList instances = InstanceList.load (inputFile.value); if (t == 1.0 && !vectorToSequence.value && ! (pruneInfogain.wasInvoked() || pruneCount.wasInvoked()) && ! (hideTargets.wasInvoked() || revealTargets.wasInvoked())) { logger.warning("Vectors2Vectors was invoked, but did not change anything"); instances.save(trainingFile.value()); System.exit(0); } if (pruneInfogain.wasInvoked() || pruneCount.wasInvoked() || minIDF.wasInvoked() || maxIDF.wasInvoked()) { // Are we also splitting the instances? // Current code doesn't want to do this, so I'm // not changing it, but I don't know a reason. -DM if (t != 1.0) { throw new UnsupportedOperationException("Infogain/count processing of test or validation lists not yet supported."); } if (pruneCount.wasInvoked() || minIDF.wasInvoked() || maxIDF.wasInvoked()) { // Check which type of data element the instances contain Instance firstInstance = instances.get(0); if (firstInstance.getData() instanceof FeatureSequence) { // Version for feature sequences Alphabet oldAlphabet = instances.getDataAlphabet(); Alphabet newAlphabet = new Alphabet(); // It's necessary to create a new instance list in // order to make sure that the data alphabet is correct. Noop newPipe = new Noop (newAlphabet, instances.getTargetAlphabet()); InstanceList newInstanceList = new InstanceList (newPipe); // Iterate over the instances in the old list, adding // up occurrences of features. int numFeatures = oldAlphabet.size(); double[] counts = new double[numFeatures]; for (int ii = 0; ii < instances.size(); ii++) { Instance instance = instances.get(ii); FeatureSequence fs = (FeatureSequence) instance.getData(); fs.addFeatureWeightsTo(counts); } Instance instance, newInstance; // Next, iterate over the same list again, adding // each instance to the new list after pruning. while (instances.size() > 0) { instance = instances.get(0); FeatureSequence fs = (FeatureSequence) instance.getData(); fs.prune(counts, newAlphabet, pruneCount.value); newInstanceList.add(newPipe.instanceFrom(new Instance(fs, instance.getTarget(), instance.getName(), instance.getSource()))); instances.remove(0); } logger.info("features: " + oldAlphabet.size() + " -> " + newAlphabet.size()); // Make the new list the official list. instances = newInstanceList; } else if (firstInstance.getData() instanceof FeatureVector) { // Version for FeatureVector Alphabet alpha2 = new Alphabet (); Noop pipe2 = new Noop (alpha2, instances.getTargetAlphabet()); InstanceList instances2 = new InstanceList (pipe2); int numFeatures = instances.getDataAlphabet().size(); double[] counts = new double[numFeatures]; for (int ii = 0; ii < instances.size(); ii++) { Instance instance = instances.get(ii); FeatureVector fv = (FeatureVector) instance.getData(); fv.addTo(counts); } BitSet bs = new BitSet(numFeatures); for (int fi = 0; fi < numFeatures; fi++) { if (counts[fi] > pruneCount.value) { bs.set(fi); } } logger.info ("Pruning "+(numFeatures-bs.cardinality())+" features out of "+numFeatures +"; leaving "+(bs.cardinality())+" features."); FeatureSelection fs = new FeatureSelection (instances.getDataAlphabet(), bs); for (int ii = 0; ii < instances.size(); ii++) { Instance instance = instances.get(ii); FeatureVector fv = (FeatureVector) instance.getData(); FeatureVector fv2 = FeatureVector.newFeatureVector (fv, alpha2, fs); instances2.add(new Instance(fv2, instance.getTarget(), instance.getName(), instance.getSource()), instances.getInstanceWeight(ii)); instance.unLock(); instance.setData(null); // So it can be freed by the garbage collector } instances = instances2; } else { throw new UnsupportedOperationException("Pruning features from " + firstInstance.getClass().getName() + " is not currently supported"); } } if (pruneInfogain.value > 0) { Alphabet alpha2 = new Alphabet (); Noop pipe2 = new Noop (alpha2, instances.getTargetAlphabet()); InstanceList instances2 = new InstanceList (pipe2); InfoGain ig = new InfoGain (instances); FeatureSelection fs = new FeatureSelection (ig, pruneInfogain.value); for (int ii = 0; ii < instances.size(); ii++) { Instance instance = instances.get(ii); FeatureVector fv = (FeatureVector) instance.getData(); FeatureVector fv2 = FeatureVector.newFeatureVector (fv, alpha2, fs); instance.unLock(); instance.setData(null); // So it can be freed by the garbage collector instances2.add(pipe2.instanceFrom(new Instance(fv2, instance.getTarget(), instance.getName(), instance.getSource())), instances.getInstanceWeight(ii)); } instances = instances2; } if (vectorToSequence.value) { // Convert FeatureVector's to FeatureSequence's by simply randomizing the order // of all the word occurrences, including repetitions due to values larger than 1. Alphabet alpha = instances.getDataAlphabet(); Noop pipe2 = new Noop (alpha, instances.getTargetAlphabet()); InstanceList instances2 = new InstanceList (pipe2); for (int ii = 0; ii < instances.size(); ii++) { Instance instance = instances.get(ii); FeatureVector fv = (FeatureVector) instance.getData(); ArrayList seq = new ArrayList(); for (int loc = 0; loc < fv.numLocations(); loc++) for (int count = 0; count < fv.valueAtLocation(loc); count++) seq.add (new Integer(fv.indexAtLocation(loc))); Collections.shuffle(seq); int[] indices = new int[seq.size()]; for (int i = 0; i < indices.length; i++) indices[i] = ((Integer)seq.get(i)).intValue(); FeatureSequence fs = new FeatureSequence (alpha, indices); instance.unLock(); instance.setData(null); // So it can be freed by the garbage collector instances2.add(pipe2.instanceFrom(new Instance(fs, instance.getTarget(), instance.getName(), instance.getSource())), instances.getInstanceWeight(ii)); } instances = instances2; } if (outputFile.wasInvoked()) { writeInstanceList (instances, outputFile.value()); } else if (trainingFile.wasInvoked()) { writeInstanceList (instances, trainingFile.value()); } else { throw new IllegalArgumentException("You must specify a file to write to, using --output [filename]"); } } else if (vectorToSequence.value) { // Convert FeatureVector's to FeatureSequence's by simply randomizing the order // of all the word occurrences, including repetitions due to values larger than 1. Alphabet alpha = instances.getDataAlphabet(); Noop pipe2 = new Noop (alpha, instances.getTargetAlphabet()); InstanceList instances2 = new InstanceList (pipe2); for (int ii = 0; ii < instances.size(); ii++) { Instance instance = instances.get(ii); FeatureVector fv = (FeatureVector) instance.getData(); ArrayList seq = new ArrayList(); for (int loc = 0; loc < fv.numLocations(); loc++) for (int count = 0; count < fv.valueAtLocation(loc); count++) seq.add (new Integer(fv.indexAtLocation(loc))); Collections.shuffle(seq); int[] indices = new int[seq.size()]; for (int i = 0; i < indices.length; i++) indices[i] = ((Integer)seq.get(i)).intValue(); FeatureSequence fs = new FeatureSequence (alpha, indices); instance.unLock(); instance.setData(null); // So it can be freed by the garbage collector instances2.add(pipe2.instanceFrom(new Instance(fs, instance.getTarget(), instance.getName(), instance.getSource())), instances.getInstanceWeight(ii)); } instances = instances2; if (outputFile.wasInvoked()) { writeInstanceList (instances, outputFile.value()); } } else if (trainingProportion.wasInvoked() || validationProportion.wasInvoked()) { // Split into three lists... InstanceList[] instanceLists = instances.split (r, new double[] {t, 1-t-v, v}); // And write them out if (instanceLists[0].size() > 0) writeInstanceList(instanceLists[0], trainingFile.value()); if (instanceLists[1].size() > 0) writeInstanceList(instanceLists[1], testFile.value()); if (instanceLists[2].size() > 0) writeInstanceList(instanceLists[2], validationFile.value()); } else if (hideTargets.wasInvoked()) { Iterator<Instance> iter = instances.iterator(); while (iter.hasNext()) { Instance instance = iter.next(); instance.unLock(); instance.setProperty("target", instance.getTarget()); instance.setTarget(null); instance.lock(); } if (outputFile.wasInvoked()) { writeInstanceList (instances, outputFile.value()); } } else if (revealTargets.wasInvoked()) { Iterator<Instance> iter = instances.iterator(); while (iter.hasNext()) { Instance instance = iter.next(); instance.unLock(); instance.setTarget(instance.getProperty("target")); instance.lock(); } if (outputFile.wasInvoked()) { writeInstanceList (instances, outputFile.value()); } } } private static void writeInstanceList(InstanceList instances, File file) throws FileNotFoundException, IOException { logger.info ("Writing instance list to "+file); instances.save(file); } }
package run.bach.toolbox; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.util.List; import java.util.Set; import java.util.StringJoiner; import java.util.function.Consumer; import run.bach.Bach; import run.bach.ToolOperator; import run.bach.internal.ModulesSupport; public record ListTool(String name) implements ToolOperator { public ListTool() { this("list"); } @Override public void run(Operation operation) { var bach = operation.bach(); if (operation.arguments().isEmpty()) { bach.info("Usage: %s {modules, tools}".formatted(name())); return; } if (operation.arguments().contains("modules")) { bach.info(toModulesString(bach)); } if (operation.arguments().contains("tools")) { bach.info(bach.tools().toString(0)); } } public String toModulesString(Bach bach) { var paths = bach.paths(); var joiner = new StringJoiner("\n"); for (var space : bach.project().spaces().list()) { var size = space.modules().list().size(); if (size == 0) continue; var name = space.name(); var spaceModules = space.modules().toModuleFinder(); joiner.add(("Project modules in %s space".formatted(name))); consumeAllNames(spaceModules, joiner::add); joiner.add(" %d %s module%s".formatted(size, name, size == 1 ? "" : "s")); } joiner.add("External modules in " + paths.externalModules().toUri()); var externalModuleFinder = ModuleFinder.of(paths.externalModules()); var externalModules = externalModuleFinder.findAll(); consumeAllNames(externalModuleFinder, joiner::add); joiner.add(" %d external modules".formatted(externalModules.size())); joiner.add("Missing external modules"); var missingModules = ModulesSupport.listMissingNames(List.of(externalModuleFinder), Set.of()); missingModules.forEach(joiner::add); joiner.add(" %d missing external modules".formatted(missingModules.size())); var systemModuleFinder = ModuleFinder.ofSystem(); joiner.add("System modules in " + paths.javaHome().resolve("lib").toUri()); var systemModules = systemModuleFinder.findAll(); if (bach.cli().verbose()) consumeAllNames(systemModuleFinder, joiner::add); joiner.add(" %d system modules".formatted(systemModules.size())); return joiner.toString(); } static void consumeAllNames(ModuleFinder finder, Consumer<String> consumer) { finder.findAll().stream() .map(ModuleReference::descriptor) .map(ModuleDescriptor::toNameAndVersion) .sorted() .map(string -> string.indent(2).stripTrailing()) .forEach(consumer); } }
package eu.stratuslab.storage.disk.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import org.restlet.data.Status; import org.restlet.resource.ResourceException; public final class ProcessUtils { public enum VerboseLevel { Normal, Debug } private static final Logger LOGGER = Logger.getLogger("org.restlet"); public static final VerboseLevel verboseLevel = VerboseLevel.Debug; private ProcessUtils() { } public static void execute(ProcessBuilder pb, String errorMsg) { int returnCode = 1; String stdout = ""; String stderr = ""; Process process; StringBuffer outputBuf = new StringBuffer(); pb.redirectErrorStream(true); if(verboseLevel == VerboseLevel.Debug) { info(pb); } try { process = pb.start(); BufferedReader stdOutErr = new BufferedReader( new InputStreamReader(process.getInputStream(), "UTF-8")); String line; while ((line = stdOutErr.readLine()) != null) { outputBuf.append(line); outputBuf.append("\n"); } processWait(process); stdOutErr.close(); returnCode = process.exitValue(); stdout = streamToString(process.getInputStream()); stderr = streamToString(process.getErrorStream()); } catch (IOException e) { String msg = "An error occurred while executing command: " + MiscUtils.join(pb.command(), " ") + ".\n" + errorMsg + "."; LOGGER.severe(msg); LOGGER.severe(e.getMessage()); throw new ResourceException(Status.SERVER_ERROR_INTERNAL, msg); } if (returnCode != 0) { process.getErrorStream(); String msg = "An error occurred while executing command: " + MiscUtils.join(pb.command(), " ") + ".\n" + outputBuf.toString() + "\n" + errorMsg + ".\nReturn code was: " + String.valueOf(returnCode); LOGGER.severe(msg); LOGGER.severe("Standard Output: \n" + stdout + "\n"); LOGGER.severe("Standard Error: \n" + stderr + "\n"); throw new ResourceException(Status.SERVER_ERROR_INTERNAL, msg); } } private static void info(ProcessBuilder processBuilder) { LOGGER.info(joinList(processBuilder.command(), " ")); } private static String joinList(List<String> list, String glue) { Iterator<String> i = list.iterator(); if(i.hasNext() == false) { return ""; } StringBuffer res = new StringBuffer(); res.append(i.next()); while (i.hasNext()) { res.append(glue + i.next()); } return res.toString(); } public static int executeGetStatus(ProcessBuilder pb) { Process process; try { process = pb.start(); return processWaitGetStatus(process); } catch (IOException e) { return -1; } } private static void processWait(Process process) { boolean blocked = true; while (blocked) { try { process.waitFor(); blocked = false; } catch (InterruptedException consumed) { // just continue to wait } } } private static int processWaitGetStatus(Process process) { int rc = -1; boolean blocked = true; while (blocked) { try { rc = process.waitFor(); blocked = false; } catch (InterruptedException consumed) { // just continue to wait } } return rc; } private static String streamToString(InputStream is) { StringBuilder sb = new StringBuilder(); char[] c = new char[1024]; Reader r = null; try { r = new InputStreamReader(is, "UTF-8"); for (int n = r.read(c); n > 0; n = r.read(c)) { sb.append(c, 0, n); } } catch (IOException consumed) { // Do nothing. } finally { if (r != null) { try { r.close(); } catch (IOException consumed) { // Do nothing. } } } return sb.toString(); } }
package org.popkit.leap.geekpen.controller; import com.alibaba.fastjson.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.popkit.core.entity.SimpleResult; import org.popkit.core.logger.LeapLogger; import org.popkit.core.utils.ResponseUtils; import org.popkit.leap.geekpen.entity.ReadRecords; import org.popkit.leap.geekpen.entity.RecordVo; import org.popkit.leap.geekpen.entity.Records; import org.popkit.leap.geekpen.entity.Users; import org.popkit.leap.geekpen.mapper.RecordsMapper; import org.popkit.leap.geekpen.mapper.UsersMapper; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; @RequestMapping(value = "geekpen/api") @Controller public class GeekpenController { @Autowired RecordsMapper recordsMapper; @Autowired UsersMapper usersMapper; @RequestMapping(value = "querylatest") public void querylatest(HttpServletResponse response) { List<Records> recordsList = recordsMapper.queryLatest(5); Map<String, Users> usersMap = new HashMap<String, Users>(); List<RecordVo> recordVos = new ArrayList<RecordVo>(); if (CollectionUtils.isNotEmpty(recordsList)) { for (Records records : recordsList) { RecordVo vo = new RecordVo(records); if (usersMap.containsKey(records.getOpenid())) { Users users = new Users(); BeanUtils.copyProperties(usersMap.get(records.getOpenid()), users); vo.setUser(users); } else { Users user = usersMapper.selectByOpenid(records.getOpenid()); if (user != null) { vo.setUser(user); usersMap.put(records.getOpenid(), user); } } recordVos.add(vo); } } JSONObject jsonObject = new JSONObject(); jsonObject.put("data", recordVos); ResponseUtils.renderJson(response, jsonObject.toJSONString()); } @RequestMapping(value = "queryrecords") public void queryrecords(String openid, HttpServletResponse response) { List<Records> result = new ArrayList<Records>(); SimpleResult<List<Records>> simpleResult = new SimpleResult<List<Records>>(); simpleResult.update(true, ""); if (StringUtils.isBlank(openid)) { simpleResult.update(false, "!"); ResponseUtils.renderJson(response, JSONObject.toJSONString(simpleResult)); } try { List<Records> recordsList = recordsMapper.queryRecords(openid); if (CollectionUtils.isNotEmpty(recordsList)) { result = recordsList; } } catch (Exception e){ simpleResult.update(false, "!"); } simpleResult.setData(result); ResponseUtils.renderJson(response, JSONObject.toJSONString(simpleResult)); } @RequestMapping(value = "record.json") public void record(@RequestBody ReadRecords records, HttpServletResponse response, HttpServletRequest request) { SimpleResult simpleResult = new SimpleResult(); if (records == null || StringUtils.isBlank(records.getOpenid()) || CollectionUtils.isEmpty(records.getRecords())) { simpleResult.update(false, "!"); } try { updateUserInfo(records.getUser()); } catch (Exception e) { LeapLogger.warn("update info exception!", e); } try { String day = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dateBeginToday = simpleDateFormat.parse(day + " 00:00:00"); List<Records> recordsList = recordsMapper.queryDatasFromTime(records.getOpenid(), dateBeginToday); Map<String, Records> recordDBMap = new HashMap<String, Records>(); if (CollectionUtils.isNotEmpty(recordsList)) { for (Records records1 : recordsList) { recordDBMap.put(buildKey(records1.getBookName(), records1.getRecordTime()), records1); } } DateTime dateTime = new DateTime(); int dayOfYear = dateTime.dayOfYear().get(); for (RecordVo vo : records.getRecords()) { Records recordsDB = new Records(); recordsDB.setOpenid(records.getOpenid()); recordsDB.setBookName(vo.getBookName()); recordsDB.setType(vo.getType()); recordsDB.setRecordTime(vo.getTime()); int recordDay = new DateTime(vo.getTime()).dayOfYear().get(); if (recordDay != dayOfYear) { continue; } recordsDB.setProgress(vo.getProgress()); String key = buildKey(recordsDB.getBookName(), recordsDB.getRecordTime()); if (recordDBMap.containsKey(key)) { recordsDB.setId(recordDBMap.get(key).getId()); recordsMapper.updateByPrimaryKey(recordsDB); } else { recordsMapper.insert(recordsDB); } } simpleResult.update(true, "!"); } catch (Exception e) { simpleResult.update(false, "!"); } ResponseUtils.renderJson(response, JSONObject.toJSONString(simpleResult)); } private boolean updateUserInfo(Users user) { if (user == null || StringUtils.isBlank(user.getOpenid())) { return false;} Users users = usersMapper.selectByOpenid(user.getOpenid()); if (users != null) { //usersMapper.updateByPrimaryKey(user); } else { usersMapper.insert(user); } return true; } private String buildKey(String bookName, Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.format(date) + bookName; } @RequestMapping(value = "mock") public String mock(HttpServletRequest request) { return "geekpen/mock"; } @RequestMapping(value = "test.json") public void test(HttpServletResponse response) { Users users = usersMapper.selectByOpenid("o6Jzu0OvdlwmcmQ2N1FtFpIfslx4"); if (users != null) { ResponseUtils.renderJson(response, JSONObject.toJSONString(users)); } } }
package com.rhomobile.rhodes.camera; import java.io.FileOutputStream; import java.io.OutputStream; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import com.rhomobile.rhodes.Logger; public class ImageCaptureCallback implements PictureCallback { private static final String TAG = "ImageCapture"; private ImageCapture mOwner; private String callbackUrl; private OutputStream osCommon; private String filePath; private int mImgWidth; private int mImgHeight; private String mImgFormat; private int dev_rotation = 0; public ImageCaptureCallback(ImageCapture owner, String u, OutputStream o, String f, int w, int h, String format,int _dev_rotation) { mOwner = owner; callbackUrl = u; osCommon = o; filePath = f; mImgWidth = w; mImgHeight = h; mImgFormat = format; dev_rotation =_dev_rotation; } /* public void onPictureTaken(byte[] data, Camera camera) { try { Logger.D(TAG, "PICTURE CALLBACK JPEG: " + data.length + " bytes"); if (osCommon != null) { osCommon.write(data); osCommon.flush(); osCommon.close(); } OutputStream osOwn = new FileOutputStream(filePath); osOwn.write(data); osOwn.flush(); osOwn.close(); com.rhomobile.rhodes.camera.Camera.doCallback(filePath, mImgWidth, mImgHeight, mImgFormat); mOwner.finish(); } catch (Exception e) { Logger.E(TAG, e); } }*/ public void onPictureTaken(byte[] data, Camera camera) { try { Logger.D(TAG, "PICTURE CALLBACK JPEG: " + data.length + " bytes"); if (osCommon != null) { // This is commented because in gallery the image was storing in landscape mode if taken in portrait mode... // osCommon.write(data); // osCommon.flush(); // osCommon.close(); } OutputStream osOwn = new FileOutputStream(filePath); osOwn.write(data); osOwn.flush(); osOwn.close(); Bitmap rotatedBitmap = null; Bitmap bm = null; try { BitmapFactory.Options bounds = new BitmapFactory.Options(); bounds.inScaled = false; bounds.inDither = false; bounds.inPreferredConfig = Bitmap.Config.ARGB_8888; bm = BitmapFactory.decodeFile(filePath, bounds); int rotationAngle = 0; if ((dev_rotation > 45) && (dev_rotation < 135)) { rotationAngle = 180; } else if ((dev_rotation > 134) && (dev_rotation < 225)) { rotationAngle = 270; } else if ((dev_rotation > 224) && (dev_rotation < 315)) { rotationAngle = 0; } else { rotationAngle = 90; } Matrix matrix = new Matrix(); matrix.postRotate(rotationAngle); rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true); } catch (Exception e) { Logger.E(TAG, e.getMessage()); } if (rotatedBitmap != null) { try { FileOutputStream out = new FileOutputStream(filePath); rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, osCommon); out.flush(); out.close(); osCommon.flush(); osCommon.close(); } catch (Exception e) { Logger.E(TAG, e.getMessage()); } } mImgWidth = rotatedBitmap.getWidth(); mImgHeight = rotatedBitmap.getHeight(); if (rotatedBitmap != null) { rotatedBitmap.recycle(); rotatedBitmap = null; } if (bm != null) { bm.recycle(); bm = null; } com.rhomobile.rhodes.camera.Camera.doCallback(filePath, mImgWidth, mImgHeight, mImgFormat); mOwner.finish(); } catch (Exception e) { Logger.E(TAG, e); } } }
package com.intellij.util.indexing; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.PersistentFSConstants; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Processor; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Collections; @ApiStatus.OverrideOnly public abstract class FileBasedIndexExtension<K, V> extends IndexExtension<K, V, FileContent> { public static final ExtensionPointName<FileBasedIndexExtension<?, ?>> EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.fileBasedIndex"); private static final int DEFAULT_CACHE_SIZE = 1024; @NotNull @Override public abstract ID<K, V> getName(); /** * @return filter for file are supposed being indexed by the {@link IndexExtension#getIndexer()}. * * Usually {@link DefaultFileTypeSpecificInputFilter} can be used here to index only files with given file-type. * Note that check only file's extension is usually error-prone way and prefer to check {@link VirtualFile#getFileType()}: * for example user can enforce language file as plain text one. */ @NotNull public abstract FileBasedIndex.InputFilter getInputFilter(); public abstract boolean dependsOnFileContent(); public boolean indexDirectories() { return false; } /** * @see FileBasedIndexExtension#DEFAULT_CACHE_SIZE */ public int getCacheSize() { return DEFAULT_CACHE_SIZE; } /** * For most indices the method should return an empty collection. * * @return collection of file types to which file size limit will not be applied when indexing. * This is the way to allow indexing of files whose limit exceeds {@link PersistentFSConstants#getMaxIntellisenseFileSize()}. * <p> * Use carefully, because indexing large files may influence index update speed dramatically. */ @NotNull public Collection<FileType> getFileTypesWithSizeLimitNotApplicable() { return Collections.emptyList(); } public boolean keyIsUniqueForIndexedFile() { return false; } /** * If true then {@code <key hash> -> <virtual file id>} mapping will be saved in the persistent index structure. * It will then be used inside {@link FileBasedIndex#processAllKeys(ID, Processor, Project)}, * accepting {@link IdFilter} as a coarse filter to exclude keys from unrelated virtual files from further processing. * Otherwise, {@link IdFilter} parameter of this method will be ignored. * <p> * This property might come useful for optimizing "Go to File/Symbol" and completion performance in case of multiple indexed projects. * * @see IdFilter#buildProjectIdFilter(Project, boolean) */ public boolean traceKeyHashToVirtualFileMapping() { return false; } public boolean hasSnapshotMapping() { return false; } /** * Whether this index needs the forward mapping to be shared along with inverted index. * * If this method returns {@code false}, it is an error to call {@link FileBasedIndex#getFileData(ID, VirtualFile, Project)} * for this {@link #getName() index}. */ @ApiStatus.Internal @ApiStatus.Experimental public boolean needsForwardIndexWhenSharing() { return true; } }
package com.intellij.codeInsight.hint; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.ide.IdeTooltip; import com.intellij.injected.editor.EditorWindow; import com.intellij.lang.ASTNode; import com.intellij.lang.parameterInfo.*; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon.Position; 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.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.HintHint; import com.intellij.ui.LightweightHint; import com.intellij.util.Alarm; import com.intellij.util.Consumer; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.LockSupport; public class ParameterInfoController extends UserDataHolderBase implements Disposable { private static final Logger LOG = Logger.getInstance(ParameterInfoController.class); private static final String WHITESPACE = " \t"; private final Project myProject; @NotNull private final Editor myEditor; private final RangeMarker myLbraceMarker; private LightweightHint myHint; private final ParameterInfoComponent myComponent; private boolean myKeepOnHintHidden; private final CaretListener myEditorCaretListener; @NotNull private final ParameterInfoHandler<PsiElement, Object> myHandler; private final MyBestLocationPointProvider myProvider; private final Alarm myAlarm = new Alarm(); private static final int DELAY = 200; private boolean mySingleParameterInfo; private boolean myDisposed; /** * Keeps Vector of ParameterInfoController's in Editor */ private static final Key<List<ParameterInfoController>> ALL_CONTROLLERS_KEY = Key.create("ParameterInfoController.ALL_CONTROLLERS_KEY"); public static ParameterInfoController findControllerAtOffset(Editor editor, int offset) { List<ParameterInfoController> allControllers = getAllControllers(editor); for (int i = 0; i < allControllers.size(); ++i) { ParameterInfoController controller = allControllers.get(i); if (controller.myLbraceMarker.getStartOffset() == offset) { if (controller.myKeepOnHintHidden || controller.myHint.isVisible()) return controller; Disposer.dispose(controller); //noinspection AssignmentToForLoopParameter --i; } } return null; } private static List<ParameterInfoController> getAllControllers(@NotNull Editor editor) { List<ParameterInfoController> array = editor.getUserData(ALL_CONTROLLERS_KEY); if (array == null){ array = new ArrayList<>(); editor.putUserData(ALL_CONTROLLERS_KEY, array); } return array; } public static boolean existsForEditor(@NotNull Editor editor) { return !getAllControllers(editor).isEmpty(); } public static boolean existsWithVisibleHintForEditor(@NotNull Editor editor, boolean anyHintType) { return getAllControllers(editor).stream().anyMatch(c -> c.isHintShown(anyHintType)); } public boolean isHintShown(boolean anyType) { return myHint.isVisible() && (!mySingleParameterInfo || anyType); } public ParameterInfoController(@NotNull Project project, @NotNull Editor editor, int lbraceOffset, Object[] descriptors, Object highlighted, PsiElement parameterOwner, @NotNull ParameterInfoHandler handler, boolean showHint, boolean requestFocus) { myProject = project; myEditor = editor; myHandler = handler; myProvider = new MyBestLocationPointProvider(editor); myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset); myComponent = new ParameterInfoComponent(descriptors, editor, handler, requestFocus, true); myHint = createHint(); myKeepOnHintHidden = !showHint; mySingleParameterInfo = !showHint; myHint.setSelectingHint(true); myComponent.setParameterOwner(parameterOwner); myComponent.setHighlightedParameter(highlighted); List<ParameterInfoController> allControllers = getAllControllers(myEditor); allControllers.add(this); myEditorCaretListener = new CaretListener(){ @Override public void caretPositionChanged(@NotNull CaretEvent e) { if (!UndoManager.getInstance(myProject).isUndoOrRedoInProgress()) { syncUpdateOnCaretMove(); rescheduleUpdate(); } } }; myEditor.getCaretModel().addCaretListener(myEditorCaretListener); myEditor.getDocument().addDocumentListener(new DocumentListener() { @Override public void documentChanged(@NotNull DocumentEvent e) { rescheduleUpdate(); } }, this); MessageBusConnection connection = project.getMessageBus().connect(this); connection.subscribe(ExternalParameterInfoChangesProvider.TOPIC, (e, offset) -> { if (e != null && (e != myEditor || myLbraceMarker.getStartOffset() != offset)) return; updateWhenAllCommitted(); }); PropertyChangeListener lookupListener = evt -> { if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())) { Lookup lookup = (Lookup)evt.getNewValue(); if (lookup != null) { adjustPositionForLookup(lookup); } } }; LookupManager.getInstance(project).addPropertyChangeListener(lookupListener, this); EditorUtil.disposeWithEditor(myEditor, this); if (showHint) { showHint(requestFocus, mySingleParameterInfo); } else { updateComponent(); } } void setDescriptors(Object[] descriptors) { myComponent.setDescriptors(descriptors); } private void syncUpdateOnCaretMove() { myHandler.syncUpdateOnCaretMove(new MyLazyUpdateParameterInfoContext()); } private LightweightHint createHint() { JPanel wrapper = new WrapperPanel(); wrapper.add(myComponent); return new LightweightHint(wrapper); } @Override public void dispose(){ if (myDisposed) return; myDisposed = true; hideHint(); myHandler.dispose(new MyDeleteParameterInfoContext()); List<ParameterInfoController> allControllers = getAllControllers(myEditor); allControllers.remove(this); myEditor.getCaretModel().removeCaretListener(myEditorCaretListener); } public void showHint(boolean requestFocus, boolean singleParameterInfo) { if (myHint.isVisible()) { myHint.getComponent().remove(myComponent); hideHint(); myHint = createHint(); } mySingleParameterInfo = singleParameterInfo && myKeepOnHintHidden; Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, myComponent.getParameterOwner(), myLbraceMarker.getStartOffset(), null, HintManager.ABOVE); HintHint hintHint = HintManagerImpl.createHintHint(myEditor, pos.getFirst(), myHint, pos.getSecond()); hintHint.setExplicitClose(true); hintHint.setRequestFocus(requestFocus); hintHint.setShowImmediately(true); hintHint.setBorderColor(ParameterInfoComponent.BORDER_COLOR); hintHint.setBorderInsets(JBUI.insets(4, 1, 4, 1)); hintHint.setComponentBorder(JBUI.Borders.empty()); int flags = HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING; if (!singleParameterInfo && myKeepOnHintHidden) flags |= HintManager.HIDE_BY_TEXT_CHANGE; Editor editorToShow = myEditor instanceof EditorWindow ? ((EditorWindow)myEditor).getDelegate() : myEditor; // is case of injection we need to calculate position for EditorWindow // also we need to show the hint in the main editor because of intention bulb HintManagerImpl.getInstanceImpl().showEditorHint(myHint, editorToShow, pos.getFirst(), flags, 0, false, hintHint); updateComponent(); } private void adjustPositionForLookup(@NotNull Lookup lookup) { if (myEditor.isDisposed()) { Disposer.dispose(this); return; } if (!myHint.isVisible()) { if (!myKeepOnHintHidden) Disposer.dispose(this); return; } IdeTooltip tooltip = myHint.getCurrentIdeTooltip(); if (tooltip != null) { JRootPane root = myEditor.getComponent().getRootPane(); if (root != null) { Point p = tooltip.getShowingPoint().getPoint(root.getLayeredPane()); if (lookup.isPositionedAboveCaret()) { if (Position.above == tooltip.getPreferredPosition()) { myHint.pack(); myHint.updatePosition(Position.below); myHint.updateLocation(p.x, p.y + tooltip.getPositionChangeY()); } } else { if (Position.below == tooltip.getPreferredPosition()) { myHint.pack(); myHint.updatePosition(Position.above); myHint.updateLocation(p.x, p.y - tooltip.getPositionChangeY()); } } } } } private void rescheduleUpdate(){ myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> updateWhenAllCommitted(), DELAY, ModalityState.stateForComponent(myEditor.getComponent())); } private void updateWhenAllCommitted() { if (!myDisposed && !myProject.isDisposed()) { PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted(() -> { try { DumbService.getInstance(myProject).withAlternativeResolveEnabled(this::updateComponent); } catch (IndexNotReadyException e) { LOG.info(e); Disposer.dispose(this); } }); } } public void updateComponent(){ if (!myKeepOnHintHidden && !myHint.isVisible() && !ApplicationManager.getApplication().isHeadlessEnvironment() || myEditor instanceof EditorWindow && !((EditorWindow)myEditor).isValid()) { Disposer.dispose(this); return; } final PsiFile file = PsiUtilBase.getPsiFileInEditor(myEditor, myProject); int caretOffset = myEditor.getCaretModel().getOffset(); final int offset = getCurrentOffset(); final MyUpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file); executeFindElementForUpdatingParameterInfo(context, elementForUpdating -> { myHandler.processFoundElementForUpdatingParameterInfo(elementForUpdating, context); if (elementForUpdating != null) { executeUpdateParameterInfo(elementForUpdating, context, () -> { boolean knownParameter = (myComponent.getObjects().length == 1 || myComponent.getHighlighted() != null) && myComponent.getCurrentParameterIndex() != -1; if (mySingleParameterInfo && !knownParameter && myHint.isVisible()) { hideHint(); } if (myKeepOnHintHidden && knownParameter && !myHint.isVisible()) { AutoPopupController.getInstance(myProject).autoPopupParameterInfo(myEditor, null); } if (!myDisposed && (myHint.isVisible() && !myEditor.isDisposed() && (myEditor.getComponent().getRootPane() != null || ApplicationManager.getApplication().isUnitTestMode()) || ApplicationManager.getApplication().isHeadlessEnvironment())) { Model result = myComponent.update(mySingleParameterInfo); result.project = myProject; result.range = myComponent.getParameterOwner().getTextRange(); result.editor = myEditor; for (ParameterInfoListener listener : ParameterInfoListener.EP_NAME.getExtensionList()) { listener.hintUpdated(result); } if (ApplicationManager.getApplication().isHeadlessEnvironment()) return; IdeTooltip tooltip = myHint.getCurrentIdeTooltip(); short position = tooltip != null ? toShort(tooltip.getPreferredPosition()) : HintManager.ABOVE; Pair<Point, Short> pos = myProvider.getBestPointPosition( myHint, elementForUpdating, caretOffset, myEditor.getCaretModel().getVisualPosition(), position); HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond()); } }); } else { hideHint(); if (!myKeepOnHintHidden) { Disposer.dispose(this); } } }); } private int getCurrentOffset() { int caretOffset = myEditor.getCaretModel().getOffset(); CharSequence chars = myEditor.getDocument().getCharsSequence(); return myHandler.isWhitespaceSensitive() ? caretOffset : CharArrayUtil.shiftBackward(chars, caretOffset - 1, WHITESPACE) + 1; } private void executeFindElementForUpdatingParameterInfo(UpdateParameterInfoContext context, @NotNull Consumer<PsiElement> elementForUpdatingConsumer) { final Component focusOwner = IdeFocusManager.getInstance(myProject).getFocusOwner(); ProgressManager.getInstance().run( new Task.Backgroundable(myProject, CodeInsightBundle.message("parameter.info.progress.title"), true) { @Override public void run(@NotNull ProgressIndicator indicator) { assert !ApplicationManager.getApplication().isDispatchThread() : "Show parameter info on dispatcher thread leads to live lock"; final VisibleAreaListener visibleAreaListener = new CancelProgressOnScrolling(indicator); myEditor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); ProgressIndicatorUtils.awaitWithCheckCanceled( ReadAction .nonBlocking(() -> { return myHandler.findElementForUpdatingParameterInfo(context); }).withDocumentsCommitted(myProject) .cancelWith(indicator) .expireWhen(() -> getCurrentOffset() != context.getOffset()) .coalesceBy(ParameterInfoController.this) .expireWith(ParameterInfoController.this) .finishOnUiThread(ModalityState.defaultModalityState(), elementForUpdating -> { if (Objects.equals(focusOwner, IdeFocusManager.getInstance(myProject).getFocusOwner())) { elementForUpdatingConsumer.consume(elementForUpdating); } }) .submit(AppExecutorUtil.getAppExecutorService()) .onProcessed(ignore -> myEditor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener))); } }); } private void executeUpdateParameterInfo(PsiElement elementForUpdating, MyUpdateParameterInfoContext context, Runnable continuation) { PsiElement parameterOwner = context.getParameterOwner(); if (parameterOwner != null && !parameterOwner.equals(elementForUpdating)) { context.removeHint(); return; } final Component focusOwner = IdeFocusManager.getInstance(myProject).getFocusOwner(); ProgressManager.getInstance().run( new Task.Backgroundable(myProject, CodeInsightBundle.message("parameter.info.progress.title"), true) { @Override public void run(@NotNull ProgressIndicator indicator) { assert !ApplicationManager.getApplication().isDispatchThread() : "Show parameter info on dispatcher thread leads to live lock"; final VisibleAreaListener visibleAreaListener = new CancelProgressOnScrolling(indicator); myEditor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); ProgressIndicatorUtils.awaitWithCheckCanceled(ReadAction .nonBlocking(() -> { try { myHandler.updateParameterInfo(elementForUpdating, context); return elementForUpdating; } catch (IndexNotReadyException e) { DumbService.getInstance(myProject) .showDumbModeNotification(CodeInsightBundle.message("parameter.info.indexing.mode.not.supported")); } return null; }) .withDocumentsCommitted(myProject) .cancelWith(indicator) .expireWhen(() -> !myKeepOnHintHidden && !myHint.isVisible() && !ApplicationManager.getApplication().isHeadlessEnvironment() || getCurrentOffset() != context.getOffset() || !elementForUpdating.isValid()) .expireWith(ParameterInfoController.this) .finishOnUiThread(ModalityState.defaultModalityState(), element -> { if (element != null && continuation != null && Objects.equals(focusOwner, IdeFocusManager.getInstance(myProject).getFocusOwner())) { context.applyUIChanges(); continuation.run(); } }) .submit(AppExecutorUtil.getAppExecutorService()) .onProcessed(ignore -> myEditor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener))); } }); } @HintManager.PositionFlags private static short toShort(Position position) { switch (position) { case above: return HintManager.ABOVE; case atLeft: return HintManager.LEFT; case atRight: return HintManager.RIGHT; default: return HintManager.UNDER; } } static boolean hasPrevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) { ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset); return controller != null && controller.getPrevOrNextParameterOffset(isNext) != -1; } static void prevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) { ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset); int newOffset = controller != null ? controller.getPrevOrNextParameterOffset(isNext) : -1; if (newOffset != -1) { controller.moveToParameterAtOffset(newOffset); } } private void moveToParameterAtOffset(int offset) { PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); PsiElement argsList = findArgumentList(file, offset, -1); if (argsList == null && !CodeInsightSettings.getInstance().SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION) return; if (!myHint.isVisible()) AutoPopupController.getInstance(myProject).autoPopupParameterInfo(myEditor, null); offset = adjustOffsetToInlay(offset); myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); myEditor.getSelectionModel().removeSelection(); if (argsList != null) { executeUpdateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file), null); } } private int adjustOffsetToInlay(int offset) { CharSequence text = myEditor.getDocument().getImmutableCharSequence(); int hostWhitespaceStart = CharArrayUtil.shiftBackward(text, offset, WHITESPACE) + 1; int hostWhitespaceEnd = CharArrayUtil.shiftForward(text, offset, WHITESPACE); Editor hostEditor = myEditor; if (myEditor instanceof EditorWindow) { hostEditor = ((EditorWindow)myEditor).getDelegate(); hostWhitespaceStart = ((EditorWindow)myEditor).getDocument().injectedToHost(hostWhitespaceStart); hostWhitespaceEnd = ((EditorWindow)myEditor).getDocument().injectedToHost(hostWhitespaceEnd); } List<Inlay> inlays = ParameterHintsPresentationManager.getInstance().getParameterHintsInRange(hostEditor, hostWhitespaceStart, hostWhitespaceEnd); for (Inlay inlay : inlays) { int inlayOffset = inlay.getOffset(); if (myEditor instanceof EditorWindow) { if (((EditorWindow)myEditor).getDocument().getHostRange(inlayOffset) == null) continue; inlayOffset = ((EditorWindow)myEditor).getDocument().hostToInjected(inlayOffset); } return inlayOffset; } return offset; } private int getPrevOrNextParameterOffset(boolean isNext) { if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport)) return -1; ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport)myHandler; IElementType delimiter = handler.getActualParameterDelimiterType(); boolean noDelimiter = delimiter == TokenType.WHITE_SPACE; int caretOffset = myEditor.getCaretModel().getOffset(); CharSequence text = myEditor.getDocument().getImmutableCharSequence(); int offset = noDelimiter ? caretOffset : CharArrayUtil.shiftBackward(text, caretOffset - 1, WHITESPACE) + 1; int lbraceOffset = myLbraceMarker.getStartOffset(); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); PsiElement argList = lbraceOffset < offset ? findArgumentList(file, offset, lbraceOffset) : null; if (argList == null) return -1; @SuppressWarnings("unchecked") PsiElement[] parameters = handler.getActualParameters(argList); int currentParameterIndex = getParameterIndex(parameters, delimiter, offset); if (CodeInsightSettings.getInstance().SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION) { if (currentParameterIndex < 0 || currentParameterIndex >= parameters.length && parameters.length > 0) return -1; if (offset >= argList.getTextRange().getEndOffset()) currentParameterIndex = isNext ? -1 : parameters.length; int prevOrNextParameterIndex = currentParameterIndex + (isNext ? 1 : -1); if (prevOrNextParameterIndex < 0 || prevOrNextParameterIndex >= parameters.length) { PsiElement parameterOwner = myComponent.getParameterOwner(); return parameterOwner != null && parameterOwner.isValid() ? parameterOwner.getTextRange().getEndOffset() : -1; } else { return getParameterNavigationOffset(parameters[prevOrNextParameterIndex], text); } } else { int prevOrNextParameterIndex = isNext && currentParameterIndex < parameters.length - 1 ? currentParameterIndex + 1 : !isNext && currentParameterIndex > 0 ? currentParameterIndex - 1 : -1; return prevOrNextParameterIndex != -1 ? parameters[prevOrNextParameterIndex].getTextRange().getStartOffset() : -1; } } private static int getParameterIndex(PsiElement @NotNull [] parameters, @NotNull IElementType delimiter, int offset) { for (int i = 0; i < parameters.length; i++) { PsiElement parameter = parameters[i]; TextRange textRange = parameter.getTextRange(); int startOffset = textRange.getStartOffset(); if (offset < startOffset) { if (i == 0) return 0; PsiElement elementInBetween = parameters[i - 1]; int currOffset = elementInBetween.getTextRange().getEndOffset(); while ((elementInBetween = PsiTreeUtil.nextLeaf(elementInBetween)) != null) { if (currOffset >= startOffset) break; ASTNode node = elementInBetween.getNode(); if (node != null && node.getElementType() == delimiter) { return offset <= currOffset ? i - 1 : i; } currOffset += elementInBetween.getTextLength(); } return i; } else if (offset <= textRange.getEndOffset()) { return i; } } return Math.max(0, parameters.length - 1); } private static int getParameterNavigationOffset(@NotNull PsiElement parameter, @NotNull CharSequence text) { int rangeStart = parameter.getTextRange().getStartOffset(); int rangeEnd = parameter.getTextRange().getEndOffset(); int offset = CharArrayUtil.shiftBackward(text, rangeEnd - 1, WHITESPACE) + 1; return offset > rangeStart ? offset : CharArrayUtil.shiftForward(text, rangeEnd, WHITESPACE); } @Nullable public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){ if (file == null) return null; ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage()); if (handlers != null) { for(ParameterInfoHandler handler:handlers) { if (handler instanceof ParameterInfoHandlerWithTabActionSupport) { final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler; // please don't remove typecast in the following line; it's required to compile the code under old JDK 6 versions final E e = ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2); if (e != null) return e; } } } return null; } public Object[] getObjects() { return myComponent.getObjects(); } public Object getHighlighted() { return myComponent.getHighlighted(); } public void setPreservedOnHintHidden(boolean value) { myKeepOnHintHidden = value; } @TestOnly public static void waitForDelayedActions(@NotNull Editor editor, long timeout, @NotNull TimeUnit unit) throws TimeoutException { long deadline = System.currentTimeMillis() + unit.toMillis(timeout); while (System.currentTimeMillis() < deadline) { List<ParameterInfoController> controllers = getAllControllers(editor); boolean hasPendingRequests = false; for (ParameterInfoController controller : controllers) { if (!controller.myAlarm.isEmpty()) { hasPendingRequests = true; break; } } if (hasPendingRequests) { LockSupport.parkNanos(10_000_000); UIUtil.dispatchAllInvocationEvents(); } else return; } throw new TimeoutException(); } /** * Returned Point is in layered pane coordinate system. * Second value is a {@link HintManager.PositionFlags position flag}. */ static Pair<Point, Short> chooseBestHintPosition(Editor editor, VisualPosition pos, LightweightHint hint, short preferredPosition, boolean showLookupHint) { if (ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment()) return Pair.pair(new Point(), HintManager.DEFAULT); HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); Dimension hintSize = hint.getComponent().getPreferredSize(); JComponent editorComponent = editor.getComponent(); JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane(); Point p1; Point p2; if (showLookupHint) { p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER); p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE); } else { p1 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.UNDER); p2 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.ABOVE); } boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight(); boolean p2Ok = p2.y >= 0; if (!showLookupHint) { if (preferredPosition != HintManager.DEFAULT) { if (preferredPosition == HintManager.ABOVE) { if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); } else if (preferredPosition == HintManager.UNDER) { if (p1Ok) return new Pair<>(p1, HintManager.UNDER); } } } if (p1Ok) return new Pair<>(p1, HintManager.UNDER); if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); int underSpace = layeredPane.getHeight() - p1.y; int aboveSpace = p2.y; return aboveSpace > underSpace ? new Pair<>(new Point(p2.x, 0), HintManager.UNDER) : new Pair<>(p1, HintManager.ABOVE); } public static boolean areParameterTemplatesEnabledOnCompletion() { return Registry.is("java.completion.argument.live.template") && !CodeInsightSettings.getInstance().SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION; } private class MyUpdateParameterInfoContext implements UpdateParameterInfoContext { private final int myOffset; private final PsiFile myFile; private final boolean[] enabled; MyUpdateParameterInfoContext(final int offset, final PsiFile file) { myOffset = offset; myFile = file; enabled = new boolean[getObjects().length]; for(int i = 0; i < enabled.length; i++) { enabled[i] = myComponent.isEnabled(i); } } @Override public int getParameterListStart() { return myLbraceMarker.getStartOffset(); } @Override public int getOffset() { return myOffset; } @Override public Project getProject() { return myProject; } @Override public PsiFile getFile() { return myFile; } @Override @NotNull public Editor getEditor() { return myEditor; } @Override public void removeHint() { ApplicationManager.getApplication().invokeLater(() -> { if (!myHint.isVisible()) return; hideHint(); if (!myKeepOnHintHidden) Disposer.dispose(ParameterInfoController.this); }); } @Override public void setParameterOwner(final PsiElement o) { myComponent.setParameterOwner(o); } @Override public PsiElement getParameterOwner() { return myComponent.getParameterOwner(); } @Override public void setHighlightedParameter(final Object method) { myComponent.setHighlightedParameter(method); } @Override public Object getHighlightedParameter() { return myComponent.getHighlighted(); } @Override public void setCurrentParameter(final int index) { myComponent.setCurrentParameterIndex(index); } @Override public boolean isUIComponentEnabled(int index) { return enabled[index]; } @Override public void setUIComponentEnabled(int index, boolean enabled) { this.enabled[index] = enabled; } @Override public Object[] getObjectsToView() { return myComponent.getObjects(); } @Override public boolean isPreservedOnHintHidden() { return myKeepOnHintHidden; } @Override public void setPreservedOnHintHidden(boolean value) { myKeepOnHintHidden = value; } @Override public boolean isInnermostContext() { PsiElement ourOwner = myComponent.getParameterOwner(); if (ourOwner == null || !ourOwner.isValid()) return false; TextRange ourRange = ourOwner.getTextRange(); if (ourRange == null) return false; List<ParameterInfoController> allControllers = getAllControllers(myEditor); for (ParameterInfoController controller : allControllers) { if (controller != ParameterInfoController.this) { PsiElement parameterOwner = controller.myComponent.getParameterOwner(); if (parameterOwner != null && parameterOwner.isValid()) { TextRange range = parameterOwner.getTextRange(); if (range != null && range.contains(myOffset) && ourRange.contains(range)) return false; } } } return true; } @Override public boolean isSingleParameterInfo() { return mySingleParameterInfo; } @Override public UserDataHolderEx getCustomContext() { return ParameterInfoController.this; } void applyUIChanges() { ApplicationManager.getApplication().assertIsDispatchThread(); for (int index = 0, len = enabled.length; index < len; index++) { if (enabled[index] != myComponent.isEnabled(index)) { myComponent.setEnabled(index, enabled[index]); } } } } private class MyLazyUpdateParameterInfoContext extends MyUpdateParameterInfoContext { private PsiFile myFile; private MyLazyUpdateParameterInfoContext() { super(myEditor.getCaretModel().getOffset(), null); } @Override public PsiFile getFile() { if (myFile == null) { myFile = PsiUtilBase.getPsiFileInEditor(myEditor, myProject); } return myFile; } } protected void hideHint() { myHint.hide(); for (ParameterInfoListener listener : ParameterInfoListener.EP_NAME.getExtensionList()) { listener.hintHidden(myProject); } } public interface SignatureItemModel { } public static class RawSignatureItem implements SignatureItemModel { public final String htmlText; RawSignatureItem(String htmlText) { this.htmlText = htmlText; } } public static class SignatureItem implements SignatureItemModel { public final String text; public final boolean deprecated; public final boolean disabled; public final List<Integer> startOffsets; public final List<Integer> endOffsets; SignatureItem(String text, boolean deprecated, boolean disabled, List<Integer> startOffsets, List<Integer> endOffsets) { this.text = text; this.deprecated = deprecated; this.disabled = disabled; this.startOffsets = startOffsets; this.endOffsets = endOffsets; } } public static class Model { public final List<SignatureItemModel> signatures = new ArrayList<>(); public int current = -1; public int highlightedSignature = -1; public TextRange range; public Editor editor; public Project project; } private static class MyBestLocationPointProvider { private final Editor myEditor; private int previousOffset = -1; private Point previousBestPoint; private Short previousBestPosition; MyBestLocationPointProvider(final Editor editor) { myEditor = editor; } @NotNull private Pair<Point, Short> getBestPointPosition(LightweightHint hint, final PsiElement list, int offset, VisualPosition pos, short preferredPosition) { if (list != null) { TextRange range = list.getTextRange(); TextRange rangeWithoutParens = TextRange.from(range.getStartOffset() + 1, Math.max(range.getLength() - 2, 0)); if (!rangeWithoutParens.contains(offset)) { offset = offset < rangeWithoutParens.getStartOffset() ? rangeWithoutParens.getStartOffset() : rangeWithoutParens.getEndOffset(); pos = null; } } if (previousOffset == offset) return Pair.create(previousBestPoint, previousBestPosition); final boolean isMultiline = list != null && StringUtil.containsAnyChar(list.getText(), "\n\r"); if (pos == null) pos = EditorUtil.inlayAwareOffsetToVisualPosition(myEditor, offset); Pair<Point, Short> position; if (!isMultiline) { position = chooseBestHintPosition(myEditor, pos, hint, preferredPosition, false); } else { Point p = HintManagerImpl.getHintPosition(hint, myEditor, pos, HintManager.ABOVE); position = new Pair<>(p, HintManager.ABOVE); } previousBestPoint = position.getFirst(); previousBestPosition = position.getSecond(); previousOffset = offset; return position; } } private static class WrapperPanel extends JPanel { WrapperPanel() { super(new BorderLayout()); setBorder(JBUI.Borders.empty()); } // foreground/background/font are used to style the popup (HintManagerImpl.createHintHint) @Override public Color getForeground() { return getComponentCount() == 0 ? super.getForeground() : getComponent(0).getForeground(); } @Override public Color getBackground() { return getComponentCount() == 0 ? super.getBackground() : getComponent(0).getBackground(); } @Override public Font getFont() { return getComponentCount() == 0 ? super.getFont() : getComponent(0).getFont(); } // for test purposes @Override public String toString() { return getComponentCount() == 0 ? "<empty>" : getComponent(0).toString(); } } private class MyDeleteParameterInfoContext implements DeleteParameterInfoContext { @Override public PsiElement getParameterOwner() { return myComponent.getParameterOwner(); } @Override public Editor getEditor() { return myEditor; } @Override public UserDataHolderEx getCustomContext() { return ParameterInfoController.this; } } }
package com.intellij.execution.ui.layout.impl; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.ui.RunContentManager; import com.intellij.execution.ui.RunnerLayoutUi; import com.intellij.execution.ui.layout.*; import com.intellij.execution.ui.layout.actions.CloseViewAction; import com.intellij.execution.ui.layout.actions.MinimizeViewAction; import com.intellij.execution.ui.layout.actions.RestoreViewAction; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.actions.CloseAction; import com.intellij.ide.actions.ShowContentAction; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.AbstractPainter; import com.intellij.openapi.ui.ShadowAction; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.ActiveRunnable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.impl.ToolWindowsPane; import com.intellij.openapi.wm.impl.content.SelectContentStep; import com.intellij.openapi.wm.impl.content.SelectContentTabStep; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.components.panels.Wrapper; import com.intellij.ui.content.*; import com.intellij.ui.docking.DockContainer; import com.intellij.ui.docking.DockManager; import com.intellij.ui.docking.DockableContent; import com.intellij.ui.docking.DragSession; import com.intellij.ui.docking.impl.DockManagerImpl; import com.intellij.ui.switcher.QuickActionProvider; import com.intellij.ui.tabs.JBTabs; import com.intellij.ui.tabs.TabInfo; import com.intellij.ui.tabs.TabsListener; import com.intellij.ui.tabs.impl.JBTabsImpl; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.AbstractLayoutManager; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.accessibility.ScreenReader; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.RoundRectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; import static com.intellij.ui.tabs.JBTabsEx.NAVIGATION_ACTIONS_KEY; public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Facade, ViewContextEx, PropertyChangeListener, QuickActionProvider, DockContainer.Dialog { public static final DataKey<RunnerContentUi> KEY = DataKey.create("DebuggerContentUI"); public static final Key<Boolean> LIGHTWEIGHT_CONTENT_MARKER = Key.create("LightweightContent"); @NonNls private static final String LAYOUT = "Runner.Layout"; @NonNls private static final String SETTINGS = "XDebugger.Settings"; @NonNls private static final String VIEW_POPUP = "Runner.View.Popup"; @NonNls static final String VIEW_TOOLBAR = "Runner.View.Toolbar"; private ShowDebugContentAction myShowDebugContentAction = null; private ContentManager myManager; private final RunnerLayout myLayoutSettings; @NotNull private final ActionManager myActionManager; private final String mySessionName; private final String myRunnerId; private NonOpaquePanel myComponent; private final Wrapper myToolbar = new Wrapper(); final MyDragOutDelegate myDragOutDelegate = new MyDragOutDelegate(); JBRunnerTabsBase myTabs; private final Comparator<TabInfo> myTabsComparator = (o1, o2) -> { TabImpl tab1 = getTabFor(o1); TabImpl tab2 = getTabFor(o2); int index1 = tab1 != null ? tab1.getIndex() : -1; int index2 = tab2 != null ? tab2.getIndex() : -1; return index1 - index2; }; private final Project myProject; private ActionGroup myTopActions = new DefaultActionGroup(); private final DefaultActionGroup myViewActions = new DefaultActionGroup(); private final Map<GridImpl, Wrapper> myMinimizedButtonsPlaceholder = new HashMap<>(); private final Map<GridImpl, Wrapper> myCommonActionsPlaceholder = new HashMap<>(); private final Map<GridImpl, AnAction[]> myContextActions = new HashMap<>(); private boolean myUiLastStateWasRestored; private final Set<Object> myRestoreStateRequestors = new HashSet<>(); private String myActionsPlace = ActionPlaces.UNKNOWN; private final IdeFocusManager myFocusManager; private boolean myMinimizeActionEnabled = true; private boolean myMoveToGridActionEnabled = true; private final RunnerLayoutUi myRunnerUi; private final Map<String, LayoutAttractionPolicy> myAttractions = new HashMap<>(); private final Map<String, LayoutAttractionPolicy> myConditionAttractions = new HashMap<>(); private ActionGroup myTabPopupActions; private ActionGroup myAdditionalFocusActions; private final ActionCallback myInitialized = new ActionCallback(); private boolean myToDisposeRemovedContent = true; private int myAttractionCount; private ActionGroup myLeftToolbarActions; private boolean myContentToolbarBefore = true; private JBTabs myCurrentOver; private Image myCurrentOverImg; private TabInfo myCurrentOverInfo; private MyDropAreaPainter myCurrentPainter; private Disposable myGlassPaneListenersDisposable = Disposer.newDisposable(); private RunnerContentUi myOriginal; private final CopyOnWriteArraySet<Listener> myDockingListeners = new CopyOnWriteArraySet<>(); private final Set<RunnerContentUi> myChildren = new TreeSet<>(Comparator.comparingInt(o -> o.myWindow)); private int myWindow; private boolean myDisposing; public RunnerContentUi(@NotNull Project project, @NotNull RunnerLayoutUi ui, @NotNull ActionManager actionManager, @NotNull IdeFocusManager focusManager, @NotNull RunnerLayout settings, @NotNull String sessionName, @NotNull String runnerId) { myProject = project; myRunnerUi = ui; myLayoutSettings = settings; myActionManager = actionManager; mySessionName = sessionName; myFocusManager = focusManager; myRunnerId = runnerId; } public RunnerContentUi(@NotNull RunnerContentUi ui, @NotNull RunnerContentUi original, int window) { this(ui.myProject, ui.myRunnerUi, ui.myActionManager, ui.myFocusManager, ui.myLayoutSettings, ui.mySessionName, original.myRunnerId); myOriginal = original; original.myChildren.add(this); myWindow = window == 0 ? original.findFreeWindow() : window; } void setTopActions(@NotNull final ActionGroup topActions, @NotNull String place) { myTopActions = topActions; myActionsPlace = place; rebuildCommonActions(); } void setTabPopupActions(ActionGroup tabPopupActions) { myTabPopupActions = tabPopupActions; rebuildTabPopup(); } void setAdditionalFocusActions(final ActionGroup group) { myAdditionalFocusActions = group; rebuildTabPopup(); } public void setLeftToolbar(ActionGroup group, String place) { final ActionToolbar tb = myActionManager.createActionToolbar(place, group, false); tb.setTargetComponent(myComponent); myToolbar.setContent(tb.getComponent()); myLeftToolbarActions = group; myComponent.revalidate(); myComponent.repaint(); } void setLeftToolbarVisible(boolean value) { myToolbar.setVisible(value); Border border = myTabs.getComponent().getBorder(); if (border instanceof JBRunnerTabs.JBRunnerTabsBorder) { ((JBRunnerTabs.JBRunnerTabsBorder)border).setSideMask(value ? SideBorder.LEFT : SideBorder.NONE); } myComponent.revalidate(); myComponent.repaint(); } void setContentToolbarBefore(boolean value) { myContentToolbarBefore = value; for (GridImpl each : getGrids()) { each.setToolbarBefore(value); } myContextActions.clear(); updateTabsUI(false); } private void initUi() { if (myTabs != null) return; myTabs = JBRunnerTabs.create(myProject, this); myTabs.setDataProvider(dataId -> { if (ViewContext.CONTENT_KEY.is(dataId)) { TabInfo info = myTabs.getTargetInfo(); if (info != null) { return getGridFor(info).getData(dataId); } } else if (ViewContext.CONTEXT_KEY.is(dataId)) { return this; } return null; }); myTabs.getPresentation() .setTabLabelActionsAutoHide(false).setInnerInsets(JBUI.emptyInsets()) .setToDrawBorderIfTabsHidden(false).setTabDraggingEnabled(isMoveToGridActionEnabled()).setUiDecorator(null); rebuildTabPopup(); myTabs.getPresentation().setPaintFocus(false).setRequestFocusOnLastFocusedComponent(true); NonOpaquePanel wrapper = new MyComponent(new BorderLayout(0, 0)); wrapper.add(myToolbar, BorderLayout.WEST); wrapper.add(myTabs.getComponent(), BorderLayout.CENTER); wrapper.setBorder(JBUI.Borders.emptyTop(-1)); myComponent = wrapper; myTabs.addListener(new TabsListener() { @Override public void beforeSelectionChanged(TabInfo oldSelection, TabInfo newSelection) { if (oldSelection != null && !isStateBeingRestored()) { final GridImpl grid = getGridFor(oldSelection); if (grid != null && getTabFor(grid) != null) { grid.saveUiState(); } } } @Override public void tabsMoved() { saveUiState(); } @Override public void selectionChanged(final TabInfo oldSelection, final TabInfo newSelection) { if (!myTabs.getComponent().isShowing()) return; if (newSelection != null) { newSelection.stopAlerting(); getGridFor(newSelection).processAddToUi(false); } if (oldSelection != null) { getGridFor(oldSelection).processRemoveFromUi(); } } }); myTabs.addTabMouseListener(new MouseAdapter() { @Override public void mousePressed(@NotNull MouseEvent e) { if (UIUtil.isCloseClick(e)) { final TabInfo tabInfo = myTabs.findInfo(e); final GridImpl grid = tabInfo == null? null : getGridFor(tabInfo); final Content[] contents = grid != null ? CONTENT_KEY.getData(grid) : null; if (contents == null) return; // see GridCellImpl.closeOrMinimize as well if (CloseViewAction.isEnabled(contents)) { CloseViewAction.perform(RunnerContentUi.this, contents[0]); } else if (MinimizeViewAction.isEnabled(RunnerContentUi.this, contents, ViewContext.TAB_TOOLBAR_PLACE)) { grid.getCellFor(contents[0]).minimize(contents[0]); } } } }); if (myOriginal != null) { final ContentManager manager = ContentFactory.SERVICE.getInstance().createContentManager(this, false, myProject); Disposer.register((Disposable)myRunnerUi, manager); manager.getComponent(); } else { final DockManager dockManager = DockManager.getInstance(myProject); if (dockManager != null) { //default project dockManager.register(this); } } updateRestoreLayoutActionVisibility(); } private void rebuildTabPopup() { initUi(); myTabs.setPopupGroup(getCellPopupGroup(TAB_POPUP_PLACE), TAB_POPUP_PLACE, true); for (GridImpl each : getGrids()) { each.rebuildTabPopup(); } } @Override public ActionGroup getCellPopupGroup(final String place) { final ActionGroup original = myTabPopupActions != null? myTabPopupActions : (ActionGroup)myActionManager.getAction(VIEW_POPUP); final ActionGroup focusPlaceholder = (ActionGroup)myActionManager.getAction("Runner.Focus"); DefaultActionGroup group = new DefaultActionGroup(VIEW_POPUP, original.isPopup()); if (myShowDebugContentAction == null && "Debug".equals(myRunnerId)) { myShowDebugContentAction = new ShowDebugContentAction(this, myTabs.getComponent(), this); } if (myShowDebugContentAction != null) { group.add(myShowDebugContentAction); } final AnActionEvent event = new AnActionEvent(null, DataManager.getInstance().getDataContext(), place, new Presentation(), ActionManager.getInstance(), 0); final AnAction[] originalActions = original.getChildren(event); for (final AnAction each : originalActions) { if (each == focusPlaceholder) { final AnAction[] focusActions = ((ActionGroup)each).getChildren(event); for (AnAction eachFocus : focusActions) { group.add(eachFocus); } if (myAdditionalFocusActions != null) { for (AnAction action : myAdditionalFocusActions.getChildren(event)) { group.add(action); } } } else { group.add(each); } } if (myViewActions.getChildrenCount() > 0) { DefaultActionGroup layoutGroup = new DefaultActionGroup(myViewActions.getChildren(null)); layoutGroup.getTemplatePresentation().setText("Layout"); layoutGroup.setPopup(true); group.addSeparator(); group.addAction(layoutGroup); } return group; } @Override public boolean isOriginal() { return myOriginal == null; } @Override public int getWindow() { return myWindow; } @Override public void propertyChange(@NotNull final PropertyChangeEvent evt) { Content content = (Content)evt.getSource(); final GridImpl grid = getGridFor(content, false); if (grid == null) return; final GridCellImpl cell = grid.findCell(content); if (cell == null) return; final String property = evt.getPropertyName(); if (Content.PROP_ALERT.equals(property)) { attract(content, true); } else if (Content.PROP_DISPLAY_NAME.equals(property) || Content.PROP_ICON.equals(property) || Content.PROP_ACTIONS.equals(property) || Content.PROP_DESCRIPTION.equals(property)) { cell.updateTabPresentation(content); updateTabsUI(false); } } void processBounce(Content content, final boolean activate) { final GridImpl grid = getGridFor(content, false); if (grid == null) return; final TabInfo tab = myTabs.findInfo(grid); if (tab == null) return; if (getSelectedGrid() != grid) { tab.setAlertIcon(content.getAlertIcon()); if (activate) { tab.fireAlert(); } else { tab.stopAlerting(); } } else { grid.processAlert(content, activate); } } @Override public ActionCallback detachTo(int window, GridCell cell) { if (myOriginal != null) { return myOriginal.detachTo(window, cell); } RunnerContentUi target = null; if (window > 0) { for (RunnerContentUi child : myChildren) { if (child.myWindow == window) { target = child; break; } } } final GridCellImpl gridCell = (GridCellImpl)cell; final Content[] contents = gridCell.getContents(); storeDefaultIndices(contents); for (Content content : contents) { content.putUserData(RunnerLayout.DROP_INDEX, getStateFor(content).getTab().getIndex()); } Dimension size = gridCell.getSize(); if (size == null) { size = JBUI.size(200, 200); } final DockableGrid content = new DockableGrid(null, null, size, Arrays.asList(contents), window); if (target != null) { target.add(content, null); } else { Point location = gridCell.getLocation(); if (location == null) { location = getComponent().getLocationOnScreen(); } location.translate(size.width / 2, size.height / 2); getDockManager().createNewDockContainerFor(content, new RelativePoint(location)); } return ActionCallback.DONE; } private void storeDefaultIndices(@NotNull Content[] contents) { //int i = 0; for (Content content : contents) { content.putUserData(RunnerLayout.DEFAULT_INDEX, getStateFor(content).getTab().getDefaultIndex()); //content.putUserData(CONTENT_NUMBER, i++); } } @Override public RelativeRectangle getAcceptArea() { return new RelativeRectangle(myTabs.getComponent()); } @Override public RelativeRectangle getAcceptAreaFallback() { return getAcceptArea(); } @NotNull @Override public ContentResponse getContentResponse(@NotNull DockableContent content, RelativePoint point) { if (!(content instanceof DockableGrid)) { return ContentResponse.DENY; } final RunnerContentUi ui = ((DockableGrid)content).getOriginalRunnerUi(); return ui.getProject() == myProject && ui.mySessionName.equals(mySessionName) ? ContentResponse.ACCEPT_MOVE : ContentResponse.DENY; } @Override public JComponent getComponent() { initUi(); return myComponent; } @Override public JComponent getContainerComponent() { initUi(); return myManager.getComponent(); } @Override public void add(@NotNull DockableContent dockable, RelativePoint dropTarget) { final DockableGrid dockableGrid = (DockableGrid)dockable; final RunnerContentUi prev = dockableGrid.getRunnerUi(); saveUiState(); final List<Content> contents = dockableGrid.getContents(); final boolean wasRestoring = myOriginal != null && myOriginal.isStateBeingRestored(); setStateIsBeingRestored(true, this); try { final Point point = dropTarget != null ? dropTarget.getPoint(myComponent) : null; boolean hadGrid = !myTabs.shouldAddToGlobal(point); for (Content content : contents) { final View view = getStateFor(content); if (view.isMinimizedInGrid()) continue; prev.myManager.removeContent(content, false); myManager.removeContent(content, false); if (hadGrid && !wasRestoring) { view.assignTab(getTabFor(getSelectedGrid())); view.setPlaceInGrid(calcPlaceInGrid(point, myComponent.getSize())); } else if (contents.size() == 1 && !wasRestoring) { view.assignTab(null); view.setPlaceInGrid(myLayoutSettings.getDefaultGridPlace(content)); } view.setWindow(myWindow); myManager.addContent(content); } } finally { setStateIsBeingRestored(false, this); } saveUiState(); updateTabsUI(true); } @Override public void closeAll() { final Content[] contents = myManager.getContents(); if (myOriginal != null) { for (Content content : contents) { getStateFor(content).setWindow(0); myOriginal.myManager.addContent(content); GridCell cell = myOriginal.findCellFor(content); if (cell != null) { myOriginal.restoreContent(content.getUserData(ViewImpl.ID)); cell.minimize(content); } } } myManager.removeAllContents(false); } @Override public void addListener(final Listener listener, Disposable parent) { myDockingListeners.add(listener); Disposer.register(parent, () -> myDockingListeners.remove(listener)); } @Override public boolean isEmpty() { return myTabs.isEmptyVisible() || myDisposing; } @Override public Image startDropOver(@NotNull DockableContent content, RelativePoint point) { return null; } @Override public Image processDropOver(@NotNull DockableContent dockable, RelativePoint dropTarget) { JBTabs current = getTabsAt(dockable, dropTarget); if (myCurrentOver != null && myCurrentOver != current) { resetDropOver(dockable); } if (myCurrentOver == null && current != null) { myCurrentOver = current; Presentation presentation = dockable.getPresentation(); myCurrentOverInfo = new TabInfo(new JLabel("")).setText(presentation.getText()).setIcon(presentation.getIcon()); myCurrentOverImg = myCurrentOver.startDropOver(myCurrentOverInfo, dropTarget); } if (myCurrentOver != null) { myCurrentOver.processDropOver(myCurrentOverInfo, dropTarget); } if (myCurrentPainter == null) { myCurrentPainter = new MyDropAreaPainter(); myGlassPaneListenersDisposable = Disposer.newDisposable("GlassPaneListeners"); Disposer.register(this, myGlassPaneListenersDisposable); IdeGlassPaneUtil.find(myComponent).addPainter(myComponent, myCurrentPainter, myGlassPaneListenersDisposable); } myCurrentPainter.processDropOver(this, dockable, dropTarget); return myCurrentOverImg; } public void toggleContentPopup(JBTabs tabs) { if (myOriginal != null) { myOriginal.toggleContentPopup(tabs); return; } List<Content> contents = getPopupContents(); final SelectContentStep step = new SelectContentStep(contents) { @Nullable @Override public PopupStep<?> onChosen(@NotNull Content value, boolean finalChoice) { boolean isMultiTabbed = value instanceof TabbedContent && ((TabbedContent)value).hasMultipleTabs(); if (!isMultiTabbed) { ContentManager manager = value.getManager(); if (manager != null) { ApplicationManager.getApplication().invokeLater(() -> { IdeFocusManager.getInstance(getProject()).doWhenFocusSettlesDown(() -> { manager.setSelectedContentCB(value, true, true); }); }); } return PopupStep.FINAL_CHOICE; } else { return new SelectContentTabStep((TabbedContent)value); } } }; final Content selectedContent = myManager.getSelectedContent(); if (selectedContent != null) { step.setDefaultOptionIndex(myManager.getIndexOfContent(selectedContent)); } final ListPopup popup = JBPopupFactory.getInstance().createListPopup(step); popup.showUnderneathOf(tabs.getTabLabel(tabs.getSelectedInfo())); if (selectedContent instanceof TabbedContent) { new Alarm(Alarm.ThreadToUse.SWING_THREAD, popup).addRequest(() -> popup.handleSelect(false), 50); } } public List<Content> getPopupContents() { if (myOriginal != null) return myOriginal.getPopupContents(); List<Content> contents = new ArrayList<>(Arrays.asList(myManager.getContents())); myChildren.stream() .flatMap(child -> Arrays.stream(child.myManager.getContents())) .forEachOrdered(contents::add); RunContentManager contentManager = RunContentManager.getInstance(myProject); RunContentDescriptor selectedDescriptor = contentManager.getSelectedContent(); Content selectedContent; if (selectedDescriptor != null) { selectedContent = selectedDescriptor.getAttachedContent(); } else { selectedContent = null; } Content[] debugTabs = ToolWindowManager.getInstance(myProject) .getToolWindow(ToolWindowId.DEBUG) .getContentManager().getContents(); for (Content content : debugTabs) { if (content != selectedContent) { contents.add(content); } } return contents; } @NotNull private static PlaceInGrid calcPlaceInGrid(Point point, Dimension size) { // 1/3 (left) | (center/bottom) | 1/3 (right) if (point.x < size.width / 3) return PlaceInGrid.left; if (point.x > size.width * 2 / 3) return PlaceInGrid.right; // 3/4 (center with tab titles) | 1/4 (bottom) if (point.y > size.height * 3 / 4) return PlaceInGrid.bottom; return PlaceInGrid.center; } @Nullable private JBTabs getTabsAt(DockableContent content, RelativePoint point) { if (content instanceof DockableGrid) { final Point p = point.getPoint(getComponent()); Component c = SwingUtilities.getDeepestComponentAt(getComponent(), p.x, p.y); while (c != null) { if (c instanceof JBRunnerTabs) { return (JBTabs)c; } c = c.getParent(); } } return null; } @Override public void resetDropOver(@NotNull DockableContent content) { if (myCurrentOver != null) { myCurrentOver.resetDropOver(myCurrentOverInfo); myCurrentOver = null; myCurrentOverInfo = null; myCurrentOverImg = null; Disposer.dispose(myGlassPaneListenersDisposable); myGlassPaneListenersDisposable = Disposer.newDisposable(); myCurrentPainter = null; } } @Override public boolean isDisposeWhenEmpty() { return myOriginal != null; } @Override public void setManager(@NotNull final ContentManager manager) { assert myManager == null; myManager = manager; myManager.addContentManagerListener(new ContentManagerListener() { @Override public void contentAdded(@NotNull final ContentManagerEvent event) { initUi(); if (event.getContent().getUserData(LIGHTWEIGHT_CONTENT_MARKER) == Boolean.TRUE) { myLayoutSettings.setLightWeight(event.getContent()); Disposer.register(event.getContent(), () -> myLayoutSettings.clearStateFor(event.getContent())); } GridImpl grid = getGridFor(event.getContent(), true); if (grid == null) { return; } grid.add(event.getContent()); if (getSelectedGrid() == grid) { grid.processAddToUi(false); } if (myManager.getComponent().isShowing() && !isStateBeingRestored()) { grid.restoreLastUiState(); } updateTabsUI(false); event.getContent().addPropertyChangeListener(RunnerContentUi.this); fireContentOpened(event.getContent()); if (myMinimizeActionEnabled) { AnAction[] actions = myViewActions.getChildren(null); for (AnAction action : actions) { if (action instanceof RestoreViewAction && ((RestoreViewAction)action).getContent() == event.getContent()) return; } myViewActions.addAction(new RestoreViewAction(RunnerContentUi.this, event.getContent())).setAsSecondary(true); List<AnAction> toAdd = new ArrayList<>(); for (AnAction anAction : myViewActions.getChildren(null)) { if (!(anAction instanceof RestoreViewAction)) { myViewActions.remove(anAction); toAdd.add(anAction); } } for (AnAction anAction : toAdd) { myViewActions.addAction(anAction).setAsSecondary(true); } } } @Override public void contentRemoved(@NotNull final ContentManagerEvent event) { final Content content = event.getContent(); content.removePropertyChangeListener(RunnerContentUi.this); GridImpl grid = (GridImpl)findGridFor(content); if (grid != null) { grid.remove(content); if (grid.isEmpty()) { grid.processRemoveFromUi(); } removeGridIfNeeded(grid); } updateTabsUI(false); fireContentClosed(content); ApplicationManager.getApplication().invokeLater(() -> { if (Disposer.isDisposed(content)) { AnAction[] actions = myViewActions.getChildren(null); for (AnAction action : actions) { if (action instanceof RestoreViewAction && ((RestoreViewAction)action).getContent() == content) { myViewActions.remove(action); break; } } } }); } @Override public void contentRemoveQuery(@NotNull final ContentManagerEvent event) { } @Override public void selectionChanged(@NotNull final ContentManagerEvent event) { if (isStateBeingRestored()) return; if (event.getOperation() == ContentManagerEvent.ContentOperation.add) { select(event.getContent(), false); } } }); } @Nullable private GridImpl getSelectedGrid() { TabInfo selection = myTabs.getSelectedInfo(); return selection != null ? getGridFor(selection) : null; } private void removeGridIfNeeded(GridImpl grid) { if (grid.isEmpty()) { myTabs.removeTab(myTabs.findInfo(grid)); myMinimizedButtonsPlaceholder.remove(grid); myCommonActionsPlaceholder.remove(grid); Disposer.dispose(grid); } } @Nullable private GridImpl getGridFor(@NotNull Content content, boolean createIfMissing) { GridImpl grid = (GridImpl)findGridFor(content); if (grid != null || !createIfMissing) return grid; grid = new GridImpl(this, mySessionName); grid.setToolbarBefore(myContentToolbarBefore); if (myCurrentOver != null || myOriginal != null) { Integer forcedDropIndex = content.getUserData(RunnerLayout.DROP_INDEX); final int index = myTabs.getDropInfoIndex() + (myOriginal != null ? myOriginal.getTabOffsetFor(this) : 0); final int dropIndex = forcedDropIndex != null ? forcedDropIndex : index; if (forcedDropIndex == null) { moveFollowingTabs(dropIndex); } final int defaultIndex = content.getUserData(RunnerLayout.DEFAULT_INDEX); final TabImpl tab = myLayoutSettings.getOrCreateTab(forcedDropIndex != null ? forcedDropIndex : -1); tab.setDefaultIndex(defaultIndex); tab.setIndex(dropIndex); getStateFor(content).assignTab(tab); content.putUserData(RunnerLayout.DROP_INDEX, null); content.putUserData(RunnerLayout.DEFAULT_INDEX, null); } TabInfo tab = new TabInfo(grid).setObject(getStateFor(content).getTab()).setText("Tab"); Wrapper left = new Wrapper(); myCommonActionsPlaceholder.put(grid, left); Wrapper minimizedToolbar = new Wrapper(); myMinimizedButtonsPlaceholder.put(grid, minimizedToolbar); final Wrapper searchComponent = new Wrapper(); if (content.getSearchComponent() != null) { searchComponent.setContent(content.getSearchComponent()); } TwoSideComponent right = new TwoSideComponent(searchComponent, minimizedToolbar); NonOpaquePanel sideComponent = new TwoSideComponent(left, right); tab.setSideComponent(sideComponent); tab.setTabLabelActions((ActionGroup)myActionManager.getAction(VIEW_TOOLBAR), TAB_TOOLBAR_PLACE); myTabs.addTab(tab); myTabs.sortTabs(myTabsComparator); return grid; } private void moveFollowingTabs(int index) { if (myOriginal != null) { myOriginal.moveFollowingTabs(index); return; } moveFollowingTabs(index, myTabs); for (RunnerContentUi child : myChildren) { moveFollowingTabs(index, child.myTabs); } } ActionGroup getSettingsActions() { return (ActionGroup)myActionManager.getAction(SETTINGS); } public ContentManager getContentManager(Content content) { if (hasContent(myManager, content)) { return myManager; } for (RunnerContentUi child : myChildren) { if (hasContent(child.myManager, content)) { return child.myManager; } } return myManager; } private static boolean hasContent(ContentManager manager, Content content) { return ArrayUtil.contains(content, manager.getContents()); } private static void moveFollowingTabs(int index, final JBTabs tabs) { for (TabInfo info : tabs.getTabs()) { TabImpl tab = getTabFor(info); if (tab != null) { int tabIndex = tab.getIndex(); if (tabIndex >= index) { tab.setIndex(tabIndex + 1); } } } } private int getTabOffsetFor(RunnerContentUi ui) { int offset = myTabs.getTabCount(); for (RunnerContentUi child : myChildren) { if (child == ui) break; offset += child.myTabs.getTabCount(); } return offset; } @Override @Nullable public GridCell findCellFor(@NotNull final Content content) { GridImpl cell = getGridFor(content, false); return cell != null ? cell.getCellFor(content) : null; } private boolean rebuildToolbar() { boolean hasToolbarContent = rebuildCommonActions(); hasToolbarContent |= rebuildMinimizedActions(); return hasToolbarContent; } private boolean rebuildCommonActions() { boolean hasToolbarContent = false; for (Map.Entry<GridImpl, Wrapper> entry : myCommonActionsPlaceholder.entrySet()) { Wrapper eachPlaceholder = entry.getValue(); List<Content> contentList = entry.getKey().getContents(); Set<Content> contents = new HashSet<>(contentList); DefaultActionGroup groupToBuild; JComponent contextComponent = null; if (isHorizontalToolbar() && contents.size() == 1) { Content content = contentList.get(0); groupToBuild = new DefaultActionGroup(); if (content.getActions() != null) { groupToBuild.addAll(content.getActions()); groupToBuild.addSeparator(); contextComponent = content.getActionsContextComponent(); } groupToBuild.addAll(myTopActions); } else { final DefaultActionGroup group = new DefaultActionGroup(); group.addAll(myTopActions); groupToBuild = group; } final AnAction[] actions = groupToBuild.getChildren(null); if (!Arrays.equals(actions, myContextActions.get(entry.getKey()))) { String adjustedPlace = myActionsPlace == ActionPlaces.UNKNOWN ? ActionPlaces.TOOLBAR : myActionsPlace; ActionToolbar tb = myActionManager.createActionToolbar(adjustedPlace, groupToBuild, true); tb.getComponent().setBorder(null); tb.setTargetComponent(contextComponent); eachPlaceholder.setContent(tb.getComponent()); } if (groupToBuild.getChildrenCount() > 0) { hasToolbarContent = true; } myContextActions.put(entry.getKey(), actions); } return hasToolbarContent; } private boolean rebuildMinimizedActions() { for (Map.Entry<GridImpl, Wrapper> entry : myMinimizedButtonsPlaceholder.entrySet()) { Wrapper eachPlaceholder = entry.getValue(); ActionToolbar tb = myActionManager.createActionToolbar(ActionPlaces.RUNNER_LAYOUT_BUTTON_TOOLBAR, myViewActions, true); tb.setSecondaryActionsIcon(AllIcons.Debugger.RestoreLayout); tb.setSecondaryActionsTooltip("Layout Settings"); tb.setTargetComponent(myComponent); tb.getComponent().setBorder(null); tb.setReservePlaceAutoPopupIcon(false); JComponent minimized = tb.getComponent(); eachPlaceholder.setContent(minimized); } myTabs.getComponent().revalidate(); myTabs.getComponent().repaint(); return myViewActions.getChildrenCount() > 0; } private void updateTabsUI(final boolean validateNow) { boolean hasToolbarContent = rebuildToolbar(); Set<String> usedNames = new HashSet<>(); List<TabInfo> tabs = myTabs.getTabs(); for (TabInfo each : tabs) { hasToolbarContent |= updateTabUI(each, usedNames); } int tabsCount = tabs.size() + myChildren.stream().mapToInt(child -> child.myTabs.getTabCount()).sum(); myTabs.getPresentation().setHideTabs(!hasToolbarContent && tabsCount <= 1 && myOriginal == null); myTabs.updateTabActions(validateNow); if (validateNow) { myTabs.sortTabs(myTabsComparator); } } private boolean updateTabUI(TabInfo tab, Set<? super String> usedNames) { TabImpl t = getTabFor(tab); if (t == null) { return false; } Icon icon = t.getIcon(); GridImpl grid = getGridFor(tab); boolean hasToolbarContent = grid.updateGridUI(); List<Content> contents = grid.getContents(); String title = contents.size() > 1 ? t.getDisplayName() : null; if (title == null) { final String name = myLayoutSettings.getDefaultDisplayName(t.getDefaultIndex()); if (name != null && contents.size() > 1 && !usedNames.contains(name)) { title = name; } else { title = StringUtil.join(contents, (NotNullFunction<Content, String>)Content::getTabName, " | "); } } usedNames.add(title); boolean hidden = true; for (Content content : contents) { if (!grid.isMinimized(content)) { hidden = false; break; } } tab.setHidden(hidden); if (icon == null && contents.size() == 1) { icon = contents.get(0).getIcon(); } tab.setDragOutDelegate(myTabs.getTabs().size() > 1 || !isOriginal() ? myDragOutDelegate : null); Tab gridTab = grid.getTab(); tab.setText(title).setIcon(gridTab != null && gridTab.isDefault() && contents.size() > 1 ? null : icon); return hasToolbarContent; } private ActionCallback restoreLastUiState() { if (isStateBeingRestored()) return ActionCallback.REJECTED; try { setStateIsBeingRestored(true, this); List<TabInfo> tabs = new ArrayList<>(myTabs.getTabs()); final ActionCallback result = new ActionCallback(tabs.size()); for (TabInfo each : tabs) { getGridFor(each).restoreLastUiState().notifyWhenDone(result); } return result; } finally { setStateIsBeingRestored(false, this); } } @Override public void saveUiState() { if (isStateBeingRestored()) return; if (myOriginal != null) { myOriginal.saveUiState(); return; } if (!myUiLastStateWasRestored) return; int offset = updateTabsIndices(myTabs, 0); for (RunnerContentUi child : myChildren) { offset = updateTabsIndices(child.myTabs, offset); } doSaveUiState(); } private static int updateTabsIndices(final JBTabs tabs, int offset) { for (TabInfo each : tabs.getTabs()) { final int index = tabs.getIndexOf(each); final TabImpl tab = getTabFor(each); if (tab != null) tab.setIndex(index >= 0 ? index + offset : index); } return offset + tabs.getTabCount(); } private void doSaveUiState() { if (isStateBeingRestored()) return; for (TabInfo each : myTabs.getTabs()) { GridImpl eachGrid = getGridFor(each); eachGrid.saveUiState(); } for (RunnerContentUi child : myChildren) { child.doSaveUiState(); } } @Override @Nullable public Tab getTabFor(final Grid grid) { TabInfo info = myTabs.findInfo((Component)grid); return getTabFor(info); } @Override public void showNotify() { final Window window = SwingUtilities.getWindowAncestor(myComponent); if (window instanceof IdeFrame.Child) { ((IdeFrame.Child)window).setFrameTitle(mySessionName); } } @Override public void hideNotify() {} @Nullable private static TabImpl getTabFor(@Nullable final TabInfo tab) { if (tab == null) { return null; } return (TabImpl)tab.getObject(); } private static GridImpl getGridFor(TabInfo tab) { return (GridImpl)tab.getComponent(); } @Override @Nullable public Grid findGridFor(@NotNull Content content) { TabImpl tab = (TabImpl)getStateFor(content).getTab(); for (TabInfo each : myTabs.getTabs()) { TabImpl t = getTabFor(each); if (t != null && t.equals(tab)) return getGridFor(each); } return null; } private ArrayList<GridImpl> getGrids() { return myTabs.getTabs().stream().map(RunnerContentUi::getGridFor).collect(Collectors.toCollection(ArrayList::new)); } public void setHorizontalToolbar(final boolean state) { myLayoutSettings.setToolbarHorizontal(state); for (GridImpl each : getGrids()) { each.setToolbarHorizontal(state); } myContextActions.clear(); updateTabsUI(false); } @Override public boolean isSingleSelection() { return false; } @Override public boolean isToSelectAddedContent() { return false; } @Override public boolean canBeEmptySelection() { return true; } @Override public void beforeDispose() { if (myOriginal != null) { myDisposing = true; fireContentClosed(null); } } @Override public boolean canChangeSelectionTo(@NotNull Content content, boolean implicit) { if (implicit) { GridImpl grid = getGridFor(content, false); if (grid != null) { return !grid.isMinimized(content); } } return true; } @NotNull @Override public String getCloseActionName() { return UIBundle.message("tabbed.pane.close.tab.action.name"); } @NotNull @Override public String getCloseAllButThisActionName() { return UIBundle.message("tabbed.pane.close.all.tabs.but.this.action.name"); } @NotNull @Override public String getPreviousContentActionName() { return "Select Previous Tab"; } @NotNull @Override public String getNextContentActionName() { return "Select Next Tab"; } @Override public void dispose() { if (myOriginal != null) { myOriginal.myChildren.remove(this); } myMinimizedButtonsPlaceholder.clear(); myCommonActionsPlaceholder.clear(); myContextActions.clear(); myOriginal = null; myTopActions = null; myAdditionalFocusActions = null; myLeftToolbarActions = null; } @Override public void restoreLayout() { final RunnerContentUi[] children = myChildren.toArray(new RunnerContentUi[0]); final LinkedHashSet<Content> contents = new LinkedHashSet<>(); Collections.addAll(contents, myManager.getContents()); for (RunnerContentUi child : children) { Collections.addAll(contents, child.myManager.getContents()); } for (AnAction action : myViewActions.getChildren(null)) { if (!(action instanceof RestoreViewAction)) continue; contents.add(((RestoreViewAction)action).getContent()); } Content[] all = contents.toArray(new Content[0]); Arrays.sort(all, Comparator.comparingInt(content -> getStateFor(content).getTab().getDefaultIndex())); setStateIsBeingRestored(true, this); try { for (RunnerContentUi child : children) { child.myManager.removeAllContents(false); } myManager.removeAllContents(false); } finally { setStateIsBeingRestored(false, this); } myLayoutSettings.resetToDefault(); for (Content each : all) { myManager.addContent(each); } updateTabsUI(true); } @Override public boolean isStateBeingRestored() { return !myRestoreStateRequestors.isEmpty(); } @Override public void setStateIsBeingRestored(final boolean restoredNow, final Object requestor) { if (restoredNow) { myRestoreStateRequestors.add(requestor); } else { myRestoreStateRequestors.remove(requestor); } } ActionGroup getLayoutActions() { return (ActionGroup)myActionManager.getAction(LAYOUT); } public void updateActionsImmediately() { StreamEx.of(myToolbar).append(myCommonActionsPlaceholder.values()) .map(Wrapper::getTargetComponent) .select(ActionToolbar.class) .distinct() .forEach(ActionToolbar::updateActionsImmediately); } void setMinimizeActionEnabled(final boolean enabled) { myMinimizeActionEnabled = enabled; updateRestoreLayoutActionVisibility(); } private void updateRestoreLayoutActionVisibility() { List<AnAction> specialActions = new ArrayList<>(); for (AnAction action : myViewActions.getChildren(null)) { if (!(action instanceof RestoreViewAction)) specialActions.add(action); } if (myMinimizeActionEnabled) { if (specialActions.isEmpty()) { myViewActions.addAction(new Separator()).setAsSecondary(true); myViewActions.addAction(ActionManager.getInstance().getAction("Runner.RestoreLayout")).setAsSecondary(true); } } else { for (AnAction action : specialActions) { myViewActions.remove(action); } } } void setMovetoGridActionEnabled(final boolean enabled) { myMoveToGridActionEnabled = enabled; if (myTabs != null) { myTabs.getPresentation().setTabDraggingEnabled(enabled); } } @Override public boolean isMinimizeActionEnabled() { return myMinimizeActionEnabled && myOriginal == null; } @Override public boolean isMoveToGridActionEnabled() { return myMoveToGridActionEnabled; } public void setPolicy(String contentId, final LayoutAttractionPolicy policy) { myAttractions.put(contentId, policy); } void setConditionPolicy(final String condition, final LayoutAttractionPolicy policy) { myConditionAttractions.put(condition, policy); } private static LayoutAttractionPolicy getOrCreatePolicyFor(String key, Map<String, LayoutAttractionPolicy> map, LayoutAttractionPolicy defaultPolicy) { return map.computeIfAbsent(key, __ -> defaultPolicy); } @Nullable public Content findContent(final String key) { final ContentManager manager = getContentManager(); if (manager == null || key == null) return null; Content[] contents = manager.getContents(); for (Content content : contents) { String kind = content.getUserData(ViewImpl.ID); if (key.equals(kind)) { return content; } } return null; } public void restoreContent(final String key) { for (AnAction action : myViewActions.getChildren(null)) { if (!(action instanceof RestoreViewAction)) continue; Content content = ((RestoreViewAction)action).getContent(); if (key.equals(content.getUserData(ViewImpl.ID))) { restore(content); return; } } } void setToDisposeRemovedContent(final boolean toDispose) { myToDisposeRemovedContent = toDispose; } @Override public boolean isToDisposeRemovedContent() { return myToDisposeRemovedContent; } private static class MyDropAreaPainter extends AbstractPainter { private Shape myBoundingBox; private final Color myColor = ColorUtil.mix(JBColor.BLUE, JBColor.WHITE, .3); @Override public boolean needsRepaint() { return myBoundingBox != null; } @Override public void executePaint(Component component, Graphics2D g) { if (myBoundingBox == null) return; GraphicsUtil.setupAAPainting(g); g.setColor(ColorUtil.toAlpha(myColor, 200)); g.setStroke(new BasicStroke(2)); g.draw(myBoundingBox); g.setColor(ColorUtil.toAlpha(myColor, 40)); g.fill(myBoundingBox); } private void processDropOver(RunnerContentUi ui, DockableContent dockable, RelativePoint dropTarget) { myBoundingBox = null; setNeedsRepaint(true); if (!(dockable instanceof DockableGrid)) return; JComponent component = ui.myComponent; Point point = dropTarget != null ? dropTarget.getPoint(component) : null; // do not paint anything if adding to the top if (ui.myTabs.shouldAddToGlobal(point)) return; // calc target place-in-grid PlaceInGrid targetPlaceInGrid = null; for (Content c : ((DockableGrid)dockable).getContents()) { View view = ui.getStateFor(c); if (view.isMinimizedInGrid()) continue; PlaceInGrid defaultGridPlace = ui.getLayoutSettings().getDefaultGridPlace(c); targetPlaceInGrid = point == null ? defaultGridPlace : calcPlaceInGrid(point, component.getSize()); break; } if (targetPlaceInGrid == null) return; // calc the default rectangle for the targetPlaceInGrid "area" Dimension size = component.getSize(); Rectangle r = new Rectangle(size); switch (targetPlaceInGrid) { case left: r.width /= 3; break; case center: r.width /= 3; r.x += r.width; break; case right: r.width /= 3; r.x += 2 * r.width; break; case bottom: r.height /= 4; r.y += 3 * r.height; break; } // adjust the rectangle if the target grid cell is already present and showing for (Content c : ui.getContentManager().getContents()) { GridCell cellFor = ui.findCellFor(c); PlaceInGrid placeInGrid = cellFor == null? null : ((GridCellImpl)cellFor).getPlaceInGrid(); if (placeInGrid != targetPlaceInGrid) continue; Wrapper wrapper = ComponentUtil.getParentOfType((Class<? extends Wrapper>)Wrapper.class, (Component)c.getComponent()); JComponent cellWrapper = wrapper == null ? null : (JComponent)wrapper.getParent(); if (cellWrapper == null || !cellWrapper.isShowing()) continue; r = new RelativeRectangle(cellWrapper).getRectangleOn(component); break; } myBoundingBox = new RoundRectangle2D.Double(r.x, r.y, r.width, r.height, 16, 16); } } private class MyComponent extends NonOpaquePanel implements DataProvider, QuickActionProvider { private boolean myWasEverAdded; MyComponent(LayoutManager layout) { super(layout); setOpaque(true); setFocusCycleRoot(!ScreenReader.isActive()); setBorder(new ToolWindow.Border(false, false, false, false)); } @Override @Nullable public Object getData(@NotNull @NonNls final String dataId) { if (QuickActionProvider.KEY.is(dataId)) { return RunnerContentUi.this; } if (CloseAction.CloseTarget.KEY.is(dataId)) { Content content = getContentManager().getSelectedContent(); if (content != null && content.isCloseable()) { ContentManager contentManager = Objects.requireNonNull(content.getManager()); if (contentManager.canCloseContents()) { return (CloseAction.CloseTarget)() -> contentManager.removeContent(content, true, true, true); } } } ContentManager originalContentManager = myOriginal == null ? null : myOriginal.getContentManager(); JComponent originalContentComponent = originalContentManager == null ? null : originalContentManager.getComponent(); if (originalContentComponent instanceof DataProvider) { return ((DataProvider)originalContentComponent).getData(dataId); } return null; } @NotNull @Override public String getName() { return RunnerContentUi.this.getName(); } @NotNull @Override public List<AnAction> getActions(boolean originalProvider) { return RunnerContentUi.this.getActions(originalProvider); } @Override public JComponent getComponent() { return RunnerContentUi.this.getComponent(); } @Override public boolean isCycleRoot() { return RunnerContentUi.this.isCycleRoot(); } @Override public void addNotify() { super.addNotify(); if (null != ComponentUtil.findParentByCondition(this, component -> UIUtil.isClientPropertyTrue(component, ToolWindowsPane.TEMPORARY_ADDED))) { return; } if (!myUiLastStateWasRestored && myOriginal == null) { myUiLastStateWasRestored = true; // [kirillk] this is done later since restoreUiState doesn't work properly in the addNotify call chain //todo to investigate and to fix (may cause extra flickering) //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> restoreLastUiState().doWhenDone(() -> { if (!myWasEverAdded) { myWasEverAdded = true; attractOnStartup(); myInitialized.setDone(); } })); } } @Override public void removeNotify() { super.removeNotify(); if (!ScreenUtil.isStandardAddRemoveNotify(this)) return; if (Disposer.isDisposed(RunnerContentUi.this)) return; saveUiState(); } } @SuppressWarnings("SSBasedInspection") // [kirillk] this is done later since "startup" attractions should be done gently, only if no explicit calls are done private void attractOnStartup() { final int currentCount = myAttractionCount; SwingUtilities.invokeLater(() -> { if (currentCount < myAttractionCount) return; attractByCondition(LayoutViewOptions.STARTUP, false); }); } public void attract(final Content content, boolean afterInitialized) { processAttraction(content.getUserData(ViewImpl.ID), myAttractions, new LayoutAttractionPolicy.Bounce(), afterInitialized, true); } void attractByCondition(@NotNull String condition, boolean afterInitialized) { processAttraction(myLayoutSettings.getToFocus(condition), myConditionAttractions, myLayoutSettings.getAttractionPolicy(condition), afterInitialized, true); } void clearAttractionByCondition(String condition, boolean afterInitialized) { processAttraction(myLayoutSettings.getToFocus(condition), myConditionAttractions, new LayoutAttractionPolicy.FocusOnce(), afterInitialized, false); } private void processAttraction(final String contentId, final Map<String, LayoutAttractionPolicy> policyMap, final LayoutAttractionPolicy defaultPolicy, final boolean afterInitialized, final boolean activate) { IdeFocusManager.getInstance(getProject()).doWhenFocusSettlesDown(() -> myInitialized.processOnDone(() -> { Content content = findContent(contentId); if (content == null) return; final LayoutAttractionPolicy policy = getOrCreatePolicyFor(contentId, policyMap, defaultPolicy); if (activate) { // See IDEA-93683, bounce attraction should not disable further focus attraction if (!(policy instanceof LayoutAttractionPolicy.Bounce)) { myAttractionCount++; } policy.attract(content, myRunnerUi); } else { policy.clearAttraction(content, myRunnerUi); } }, afterInitialized)); } public static boolean ensureValid(JComponent c) { if (c.getRootPane() == null) return false; Container eachParent = c.getParent(); while (eachParent != null && eachParent.isValid()) { eachParent = eachParent.getParent(); } if (eachParent == null) { eachParent = c.getRootPane(); } eachParent.validate(); return true; } ContentUI getContentUI() { return this; } @Override public void minimize(final Content content, final CellTransform.Restore restore) { getStateFor(content).setMinimizedInGrid(true); myManager.removeContent(content, false); saveUiState(); updateTabsUI(false); } public void restore(Content content) { final GridImpl grid = getGridFor(content, false); if (grid == null) { getStateFor(content).assignTab(myLayoutSettings.getOrCreateTab(-1)); } else { //noinspection ConstantConditions ((GridCellImpl)findCellFor(content)).restore(content); } getStateFor(content).setMinimizedInGrid(false); myManager.addContent(content); saveUiState(); select(content, true); updateTabsUI(false); } @Override public Project getProject() { return myProject; } @Override public CellTransform.Facade getCellTransform() { return this; } @Override public ContentManager getContentManager() { return myManager; } @NotNull @Override public ActionManager getActionManager() { return myActionManager; } @Override public RunnerLayout getLayoutSettings() { return myLayoutSettings; } @Override public View getStateFor(@NotNull final Content content) { return myLayoutSettings.getStateFor(content); } private boolean isHorizontalToolbar() { return myLayoutSettings.isToolbarHorizontal(); } @Override public ActionCallback select(@NotNull final Content content, final boolean requestFocus) { final GridImpl grid = (GridImpl)findGridFor(content); if (grid == null) return ActionCallback.DONE; final TabInfo info = myTabs.findInfo(grid); if (info == null) return ActionCallback.DONE; final ActionCallback result = new ActionCallback(); myTabs.select(info, false).doWhenDone(() -> grid.select(content, requestFocus).notifyWhenDone(result)); return result; } @Override public void validate(Content content, final ActiveRunnable toRestore) { final TabInfo current = myTabs.getSelectedInfo(); myTabs.getPresentation().setPaintBlocked(true, true); select(content, false).doWhenDone(() -> { myTabs.getComponent().validate(); toRestore.run().doWhenDone(() -> { assert current != null; myTabs.select(current, true); myTabs.getPresentation().setPaintBlocked(false, true); }); }); } private static class TwoSideComponent extends NonOpaquePanel { private TwoSideComponent(JComponent left, JComponent right) { setLayout(new CommonToolbarLayout(left, right)); add(left); add(right); } } private static class CommonToolbarLayout extends AbstractLayoutManager { private final JComponent myLeft; private final JComponent myRight; CommonToolbarLayout(final JComponent left, final JComponent right) { myLeft = left; myRight = right; } @Override public Dimension preferredLayoutSize(@NotNull final Container parent) { Dimension size = new Dimension(); Dimension leftSize = myLeft.getPreferredSize(); Dimension rightSize = myRight.getPreferredSize(); size.width = leftSize.width + rightSize.width; size.height = Math.max(leftSize.height, rightSize.height); return size; } @Override public void layoutContainer(@NotNull final Container parent) { Dimension size = parent.getSize(); Dimension prefSize = parent.getPreferredSize(); if (prefSize.width <= size.width) { myLeft.setBounds(0, 0, myLeft.getPreferredSize().width, parent.getHeight()); Dimension rightSize = myRight.getPreferredSize(); myRight.setBounds(parent.getWidth() - rightSize.width, 0, rightSize.width, parent.getHeight()); } else { Dimension leftMinSize = myLeft.getMinimumSize(); Dimension rightMinSize = myRight.getMinimumSize(); // see IDEA-140557, always shrink left component last int delta = 0; //int delta = (prefSize.width - size.width) / 2; myLeft.setBounds(0, 0, myLeft.getPreferredSize().width - delta, parent.getHeight()); int rightX = (int)myLeft.getBounds().getMaxX(); int rightWidth = size.width - rightX; if (rightWidth < rightMinSize.width) { Dimension leftSize = myLeft.getSize(); int diffToRightMin = rightMinSize.width - rightWidth; if (leftSize.width - diffToRightMin >= leftMinSize.width) { leftSize.width -= diffToRightMin; myLeft.setSize(leftSize); } } myRight.setBounds((int)myLeft.getBounds().getMaxX(), 0, parent.getWidth() - myLeft.getWidth(), parent.getHeight()); } toMakeVerticallyInCenter(myLeft, parent); toMakeVerticallyInCenter(myRight, parent); } private static void toMakeVerticallyInCenter(JComponent comp, Container parent) { final Rectangle compBounds = comp.getBounds(); int compHeight = comp.getPreferredSize().height; final int parentHeight = parent.getHeight(); if (compHeight > parentHeight) { compHeight = parentHeight; } int y = (int)Math.floor(parentHeight / 2.0 - compHeight / 2.0); comp.setBounds(compBounds.x, y, compBounds.width, compHeight); } } @Override public IdeFocusManager getFocusManager() { return myFocusManager; } @Override public RunnerLayoutUi getRunnerLayoutUi() { return myRunnerUi; } @NotNull @Override public String getName() { return mySessionName; } @NotNull @Override public List<AnAction> getActions(boolean originalProvider) { ArrayList<AnAction> result = new ArrayList<>(); if (myLeftToolbarActions != null) { AnAction[] kids = myLeftToolbarActions.getChildren(null); ContainerUtil.addAll(result, kids); } return result; } private int findFreeWindow() { int i; for (i = 1; i < Integer.MAX_VALUE; i++) { if (!isUsed(i)) { return i; } } return i; } private boolean isUsed(int i) { return myChildren.stream().anyMatch(child -> child.getWindow() == i); } private DockManagerImpl getDockManager() { return (DockManagerImpl)DockManager.getInstance(myProject); } class MyDragOutDelegate implements TabInfo.DragOutDelegate { private DragSession mySession; @Override public void dragOutStarted(@NotNull MouseEvent mouseEvent, @NotNull TabInfo info) { JComponent component = info.getComponent(); Content[] data = CONTENT_KEY.getData((DataProvider)component); assert data != null; storeDefaultIndices(data); final Dimension size = info.getComponent().getSize(); final Image image = JBTabsImpl.getComponentImage(info); if (component instanceof Grid) { info.setHidden(true); } Presentation presentation = new Presentation(info.getText()); presentation.setIcon(info.getIcon()); mySession = getDockManager().createDragSession(mouseEvent, new DockableGrid(image, presentation, size, Arrays.asList(data), 0)); } @Override public void processDragOut(@NotNull MouseEvent event, @NotNull TabInfo source) { mySession.process(event); } @Override public void dragOutFinished(@NotNull MouseEvent event, TabInfo source) { mySession.process(event); mySession = null; } @Override public void dragOutCancelled(TabInfo source) { source.setHidden(false); mySession.cancel(); mySession = null; } } class DockableGrid implements DockableContent<List<Content>> { private final Image myImg; private final Presentation myPresentation; private final Dimension myPreferredSize; private final List<Content> myContents; private final int myWindow; DockableGrid(Image img, Presentation presentation, final Dimension size, List<Content> contents, int window) { myImg = img; myPresentation = presentation; myPreferredSize = size; myContents = contents; myWindow = window; } @NotNull @Override public List<Content> getKey() { return myContents; } @Override public Image getPreviewImage() { return myImg; } @Override public Dimension getPreferredSize() { return myPreferredSize; } @Override public String getDockContainerType() { return DockableGridContainerFactory.TYPE; } @Override public Presentation getPresentation() { return myPresentation; } RunnerContentUi getRunnerUi() { return RunnerContentUi.this; } RunnerContentUi getOriginalRunnerUi() { return myOriginal != null ? myOriginal : RunnerContentUi.this; } @NotNull public List<Content> getContents() { return myContents; } @Override public void close() { } public int getWindow() { return myWindow; } } public static class ShowDebugContentAction extends AnAction implements DumbAware { public static final String ACTION_ID = "ShowDebugContent"; private RunnerContentUi myContentUi; @SuppressWarnings({"UnusedDeclaration"}) public ShowDebugContentAction() { } public ShowDebugContentAction(RunnerContentUi runner, JComponent component, @NotNull Disposable parentDisposable) { myContentUi = runner; AnAction original = ActionManager.getInstance().getAction(ShowContentAction.ACTION_ID); new ShadowAction(this, original, component, parentDisposable); ActionUtil.copyFrom(this, ShowContentAction.ACTION_ID); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(myContentUi != null && myContentUi.getPopupContents().size() > 1); e.getPresentation().setText("Show List of Tabs"); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myContentUi.toggleContentPopup(e.getData(NAVIGATION_ACTIONS_KEY)); } } private void fireContentOpened(@NotNull Content content) { for (Listener each : myDockingListeners) { each.contentAdded(content); } } private void fireContentClosed(Content content) { for (Listener each : myDockingListeners) { each.contentRemoved(content); } } }
package odontosoft.controller; import java.net.URL; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import odontosoft.model.dao.PacienteDAO; import odontosoft.model.database.ConexaoBanco; import odontosoft.model.domain.Paciente; /** * FXML Controller class * * @author eduardo */ public class PacientesController implements Initializable { /** * Initializes the controller class. */ @FXML private TableColumn tableColumnPacienteNome,tableColumnPacienteTelefone; @FXML private TableView<Paciente> tableViewPacientes; private final ConexaoBanco conexao = new ConexaoBanco(); private PacienteDAO pacienteDAO = new PacienteDAO(conexao); @Override public void initialize(URL url, ResourceBundle rb) { carregarTableViewPacientes(); } public void carregarTableViewPacientes(){ tableColumnPacienteNome.setCellValueFactory(new PropertyValueFactory<>("nome")); tableColumnPacienteTelefone.setCellValueFactory(new PropertyValueFactory<>("telefone")); List<Paciente> listPacientes = pacienteDAO.listar(); ObservableList<Paciente> observableListPacientes = FXCollections.observableArrayList(listPacientes); tableViewPacientes.setItems(observableListPacientes); } }
package openblocks.common.entity; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import openblocks.OpenBlocks; import openblocks.common.item.ItemHangGlider; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class EntityHangGlider extends Entity implements IEntityAdditionalSpawnData { private static Map<EntityPlayer, Integer> gliderMap = new WeakHashMap<EntityPlayer, Integer>(); private static Map<EntityPlayer, Integer> gliderClientMap = new WeakHashMap<EntityPlayer, Integer>(); public static Map<EntityPlayer, Integer> getMapForSide(boolean isRemote) { return isRemote? gliderClientMap : gliderMap; } public static boolean isEntityHoldingGlider(Entity player) { return gliderClientMap.containsKey(player); } public static boolean isPlayerOnGround(Entity player) { Integer gliderId = gliderClientMap.get(player); if (gliderId != null) { Entity glider = player.worldObj.getEntityByID(gliderId); if (glider instanceof EntityHangGlider) return ((EntityHangGlider)glider).isPlayerOnGround(); } return true; } @SideOnly(Side.CLIENT) public static void updateGliders(World worldObj) { Iterator<Entry<EntityPlayer, Integer>> it = gliderClientMap.entrySet().iterator(); while (it.hasNext()) { Entry<EntityPlayer, Integer> next = it.next(); EntityPlayer player = next.getKey(); Entity entity = worldObj.getEntityByID(next.getValue()); if (!(entity instanceof EntityHangGlider)) { continue; } EntityHangGlider glider = (EntityHangGlider) entity; if (player == null || player.isDead || glider == null || glider.isDead || player.getHeldItem() == null || !(player.getHeldItem().getItem() instanceof ItemHangGlider) || player.worldObj.provider.dimensionId != glider.worldObj.provider.dimensionId) { glider.setDead(); it.remove(); } else { glider.fixPositions(Minecraft.getMinecraft().thePlayer); } } } private EntityPlayer player; /* * Let the glider handle it's own disposal to centralize reference * management in one place. */ private boolean shouldDespawn = false; public EntityHangGlider(World world) { super(world); } public EntityHangGlider(World world, EntityPlayer player) { this(world); this.player = player; gliderMap.put(player, entityId); } @Override protected void entityInit() { this.dataWatcher.addObject(2, Byte.valueOf((byte)0)); } public void despawnGlider() { shouldDespawn = true; } public boolean isPlayerOnGround() { return this.dataWatcher.getWatchableObjectByte(2) == 1; } @Override public void onUpdate() { if (player == null) { setDead(); } else { if (!worldObj.isRemote) { this.dataWatcher.updateObject(2, Byte.valueOf((byte)(player.onGround? 1 : 0))); } ItemStack held = player.getHeldItem(); if (player.isDead || held == null || held.getItem() == null || held.getItem() != OpenBlocks.Items.hangGlider || shouldDespawn || player.dimension != this.dimension) { getMapForSide(worldObj.isRemote).remove(player); setDead(); } else { fixPositions(); double horizontalSpeed = 0.03; double verticalSpeed = 0.4; if (player.isSneaking()) { horizontalSpeed = 0.1; verticalSpeed = 0.7; } if (!player.onGround && player.motionY < 0) { player.motionY *= verticalSpeed; motionY *= verticalSpeed; double x = Math.cos(Math.toRadians(player.rotationYawHead + 90)) * horizontalSpeed; double z = Math.sin(Math.toRadians(player.rotationYawHead + 90)) * horizontalSpeed; player.motionX += x; player.motionZ += z; player.fallDistance = 0f; /* Don't like getting hurt :( */ } } } } public EntityPlayer getPlayer() { return player; } private void fixPositions(EntityPlayer thePlayer) { if (player != null) { this.lastTickPosX = prevPosX = player.prevPosX; this.lastTickPosY = prevPosY = player.prevPosY; this.lastTickPosZ = prevPosZ = player.prevPosZ; this.posX = player.posX; this.posY = player.posY; this.posZ = player.posZ; setPosition(posX, posY, posZ); this.prevRotationYaw = player.prevRenderYawOffset; this.rotationYaw = player.renderYawOffset; this.prevRotationPitch = player.prevRotationPitch; this.rotationPitch = player.rotationPitch; if (player != thePlayer) { this.posY += 1.2; this.prevPosY += 1.2; this.lastTickPosY += 1.2; } this.motionX = this.posX - this.prevPosX; this.motionY = this.posY - this.prevPosY; this.motionZ = this.posZ - this.prevPosZ; } } public void fixPositions() { fixPositions(null); } @Override protected void readEntityFromNBT(NBTTagCompound nbttagcompound) {} @Override protected void writeEntityToNBT(NBTTagCompound nbttagcompound) {} @Override public void writeSpawnData(ByteArrayDataOutput data) { if (player != null) { data.writeUTF(player.username); } else { data.writeUTF("[none]"); } } @Override public void readSpawnData(ByteArrayDataInput data) { String username = data.readUTF(); if ("[none]".equals(username)) { setDead(); } else { player = worldObj.getPlayerEntityByName(username); gliderClientMap.put(player, entityId); } } }
package com.intellij.internal.inspector; import com.google.common.base.MoreObjects; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.IntentionActionDelegate; import com.intellij.codeInspection.QuickFix; import com.intellij.codeInspection.ex.QuickFixWrapper; import com.intellij.icons.AllIcons; import com.intellij.ide.impl.DataManagerImpl; import com.intellij.ide.ui.AntialiasingType; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.customization.CustomisedActionGroup; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.notification.NotificationsManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.ActionMenuItem; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.ex.EditorGutterComponentEx; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.roots.ui.configuration.actions.IconWithTextAction; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.GraphicsConfig; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.ui.StripeTable; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.*; import com.intellij.ui.border.CustomLineBorder; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.JBTextField; import com.intellij.ui.components.panels.Wrapper; import com.intellij.ui.paint.LinePainter2D; import com.intellij.ui.paint.RectanglePainter; import com.intellij.ui.popup.PopupFactoryImpl; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.speedSearch.SpeedSearchUtil; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ExceptionUtil; import com.intellij.util.Function; import com.intellij.util.ObjectUtils; import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.*; import com.intellij.util.ui.tree.TreeUtil; import net.miginfocom.layout.*; import net.miginfocom.swing.MigLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.UIResource; import javax.swing.table.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; import java.util.*; import static com.intellij.openapi.actionSystem.ex.CustomComponentAction.ACTION_KEY; public class UiInspectorAction extends ToggleAction implements DumbAware { private static final String CLICK_INFO = "CLICK_INFO"; private static final String CLICK_INFO_POINT = "CLICK_INFO_POINT"; private static final String RENDERER_BOUNDS = "clicked renderer"; private static final int MAX_DEEPNESS_TO_DISCOVER_FIELD_NAME = 8; private UiInspector myInspector; public UiInspectorAction() { if (Boolean.getBoolean("idea.ui.debug.mode")) { ApplicationManager.getApplication().invokeLater(() -> setSelected(true)); } } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myInspector != null; } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { setSelected(state); } void setSelected(boolean state) { if (state) { if (myInspector == null) { myInspector = new UiInspector(); } UiInspectorNotification[] existing = NotificationsManager.getNotificationsManager().getNotificationsOfType(UiInspectorNotification.class, null); if (existing.length == 0) { Notifications.Bus.notify(new UiInspectorNotification(), null); } } else { UiInspector inspector = myInspector; myInspector = null; if (inspector != null) { Disposer.dispose(inspector); } } } private static class UiInspectorNotification extends Notification { private UiInspectorNotification() { super(Notifications.SYSTEM_MESSAGES_GROUP_ID, "UI Inspector", "Control-Alt-Click to view component info!", NotificationType.INFORMATION); } } private static class InspectorWindow extends JDialog { private InspectorTable myInspectorTable; @NotNull private final List<Component> myComponents = new ArrayList<>(); private List<? extends PropertyBean> myInfo; @NotNull private final Component myInitialComponent; @NotNull private final List<HighlightComponent> myHighlightComponents = new ArrayList<>(); private boolean myIsHighlighted = true; @NotNull private final HierarchyTree myHierarchyTree; @NotNull private final Wrapper myWrapperPanel; private InspectorWindow(@NotNull Component component) throws HeadlessException { super(findWindow(component)); Window window = findWindow(component); setModal(window instanceof JDialog && ((JDialog)window).isModal()); myComponents.add(component); myInitialComponent = component; getRootPane().setBorder(JBUI.Borders.empty(5)); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); setTitle(component.getClass().getName()); Dimension size = DimensionService.getInstance().getSize(getDimensionServiceKey()); Point location = DimensionService.getInstance().getLocation(getDimensionServiceKey()); if (size != null) setSize(size); if (location != null) setLocation(location); DefaultActionGroup actions = new DefaultActionGroup(); actions.addAction(new MyTextAction("Highlight") { @Override public void actionPerformed(@NotNull AnActionEvent e) { myIsHighlighted = !myIsHighlighted; updateHighlighting(); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(myInfo != null || !myComponents.isEmpty()); } }); actions.addSeparator(); actions.add(new MyTextAction("Refresh") { @Override public void actionPerformed(@NotNull AnActionEvent e) { getCurrentTable().refresh(); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(!myComponents.isEmpty()); } }); ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.CONTEXT_TOOLBAR, actions, true); add(toolbar.getComponent(), BorderLayout.NORTH); myWrapperPanel = new Wrapper(); myInspectorTable = new InspectorTable(component); myHierarchyTree = new HierarchyTree(component) { @Override public void onComponentsChanged(List<Component> components) { switchComponentsInfo(components); updateHighlighting(); } @Override public void onClickInfoChanged(List<? extends PropertyBean> info) { switchClickInfo(info); updateHighlighting(); } }; myWrapperPanel.setContent(myInspectorTable); Splitter splitPane = new JBSplitter(false, "UiInspector.splitter.proportion", 0.5f); splitPane.setSecondComponent(myWrapperPanel); splitPane.setFirstComponent(new JBScrollPane(myHierarchyTree)); add(splitPane, BorderLayout.CENTER); myHierarchyTree.expandPath(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { close(); } }); getRootPane().getActionMap().put("CLOSE", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { close(); } }); updateHighlighting(); getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "CLOSE"); } private static String getDimensionServiceKey() { return "UiInspectorWindow"; } private static Window findWindow(Component component) { DialogWrapper dialogWrapper = DialogWrapper.findInstance(component); if (dialogWrapper != null) { return dialogWrapper.getPeer().getWindow(); } return null; } private InspectorTable getCurrentTable() { return myInspectorTable; } private void switchComponentsInfo(@NotNull List<Component> components) { if (components.isEmpty()) return; myComponents.clear(); myComponents.addAll(components); myInfo = null; setTitle(components.get(0).getClass().getName()); myInspectorTable = new InspectorTable(components.get(0)); myWrapperPanel.setContent(myInspectorTable); } private void switchClickInfo(@NotNull List<? extends PropertyBean> clickInfo) { myComponents.clear(); myInfo = clickInfo; setTitle("Click Info"); myInspectorTable = new InspectorTable(clickInfo); myWrapperPanel.setContent(myInspectorTable); } @Override public void dispose() { DimensionService.getInstance().setSize(getDimensionServiceKey(), getSize()); DimensionService.getInstance().setLocation(getDimensionServiceKey(), getLocation()); super.dispose(); DialogWrapper.cleanupRootPane(rootPane); DialogWrapper.cleanupWindowListeners(this); } public void close() { if (myInitialComponent instanceof JComponent) { ((JComponent)myInitialComponent).putClientProperty(CLICK_INFO, null); } myIsHighlighted = false; myInfo = null; myComponents.clear(); updateHighlighting(); setVisible(false); dispose(); } private void updateHighlighting() { for (HighlightComponent component : myHighlightComponents) { JComponent glassPane = getGlassPane(component); if (glassPane != null) { glassPane.remove(component); glassPane.revalidate(); glassPane.repaint(); } } myHighlightComponents.clear(); if (myIsHighlighted) { for (Component component : myComponents) { ContainerUtil.addIfNotNull(myHighlightComponents, createHighlighter(component, null)); } if (myInfo != null) { Rectangle bounds = null; for (PropertyBean bean : myInfo) { if (RENDERER_BOUNDS.equals(bean.propertyName)) { bounds = (Rectangle)bean.propertyValue; break; } } ContainerUtil.addIfNotNull(myHighlightComponents, createHighlighter(myInitialComponent, bounds)); } } } @Nullable private static HighlightComponent createHighlighter(@NotNull Component component, @Nullable Rectangle bounds) { JComponent glassPane = getGlassPane(component); if (glassPane == null) return null; JBColor color = new JBColor(JBColor.GREEN, JBColor.RED); Insets insets = component instanceof JComponent ? ((JComponent)component).getInsets() : JBUI.emptyInsets(); HighlightComponent highlightComponent = new HighlightComponent(color, insets); if (bounds != null) { bounds = SwingUtilities.convertRectangle(component, bounds, glassPane); } else { Point pt = SwingUtilities.convertPoint(component, new Point(0, 0), glassPane); bounds = new Rectangle(pt.x, pt.y, component.getWidth(), component.getHeight()); } highlightComponent.setBounds(bounds); glassPane.add(highlightComponent); glassPane.revalidate(); glassPane.repaint(); return highlightComponent; } @Nullable private static JComponent getGlassPane(@NotNull Component component) { JRootPane rootPane = SwingUtilities.getRootPane(component); return rootPane == null ? null : (JComponent)rootPane.getGlassPane(); } private abstract static class MyTextAction extends IconWithTextAction implements DumbAware { private MyTextAction(String text) { super(text); } } } private static class ComponentTreeCellRenderer extends ColoredTreeCellRenderer { private final Component myInitialSelection; ComponentTreeCellRenderer(Component initialSelection) { myInitialSelection = initialSelection; setFont(JBUI.Fonts.label(11)); setBorder(JBUI.Borders.empty(0, 3)); } @Override public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Color foreground = UIUtil.getTreeForeground(selected, hasFocus); Color background = selected ? UIUtil.getTreeSelectionBackground(hasFocus) : null; if (value instanceof HierarchyTree.ComponentNode) { HierarchyTree.ComponentNode componentNode = (HierarchyTree.ComponentNode)value; Component component = componentNode.getComponent(); if (!selected) { if (!component.isVisible()) { foreground = JBColor.GRAY; } else if (component.getWidth() == 0 || component.getHeight() == 0) { foreground = new JBColor(new Color(128, 10, 0), JBColor.BLUE); } else if (component.getPreferredSize() != null && (component.getSize().width < component.getPreferredSize().width || component.getSize().height < component.getPreferredSize().height)) { foreground = PlatformColors.BLUE; } if (myInitialSelection == componentNode.getComponent()) { background = new Color(31, 128, 8, 58); } } append(getComponentName(component)); Pair<Class, String> class2field = getClassAndFieldName(component); if (class2field!= null) { append("(" + class2field.second + "@" + class2field.first.getSimpleName() + ")"); } append(": " + RectangleRenderer.toString(component.getBounds()), SimpleTextAttributes.GRAYED_ATTRIBUTES); if (component.isOpaque()) { append(", opaque", SimpleTextAttributes.GRAYED_ATTRIBUTES); } if (component.isDoubleBuffered()) { append(", double-buffered", SimpleTextAttributes.GRAYED_ATTRIBUTES); } if (DataManagerImpl.getDataProviderEx(component) != null) { append(", ", SimpleTextAttributes.GRAYED_ATTRIBUTES); append("data-provider", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); } componentNode.setText(toString()); setIcon(createColorIcon(component.getBackground(), component.getForeground())); } if (value instanceof HierarchyTree.ClickInfoNode) { append(value.toString()); setIcon(AllIcons.Ide.Rating); } setForeground(foreground); setBackground(background); SpeedSearchUtil.applySpeedSearchHighlighting(tree, this, false, selected); } } @NotNull private static String getComponentName(Component component) { String name = getClassName(component); String componentName = component.getName(); if (StringUtil.isNotEmpty(componentName)) { name += " \"" + componentName + "\""; } return name; } @Nullable private static Pair<Class, String> getClassAndFieldName(Component component) { Container parent = component.getParent(); int deepness = 1; while(parent != null && deepness <= MAX_DEEPNESS_TO_DISCOVER_FIELD_NAME) { Class<? extends Container> aClass = parent.getClass(); Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { try { field.setAccessible(true); if (field.get(parent) == component) { return Pair.create(parent.getClass(), field.getName()); } } catch (IllegalAccessException e) { //skip } } parent = parent.getParent(); deepness++; } return null; } private static TreeModel buildModel(Component c) { Component parent = c.getParent(); while (parent != null) { c = parent; parent = c.getParent();//Find root window } return new DefaultTreeModel(new UiInspectorAction.HierarchyTree.ComponentNode(c)); } private abstract static class HierarchyTree extends JTree implements TreeSelectionListener { final Component myComponent; private HierarchyTree(Component c) { myComponent = c; setModel(buildModel(c)); setCellRenderer(new ComponentTreeCellRenderer(c)); getSelectionModel().addTreeSelectionListener(this); new TreeSpeedSearch(this); if (c instanceof JComponent && ((JComponent)c).getClientProperty(CLICK_INFO) != null) { SwingUtilities.invokeLater(() -> getSelectionModel().setSelectionPath(getPathForRow(getLeadSelectionRow() + 1))); } } @Override public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof ComponentNode) { Pair<Class, String> pair = getClassAndFieldName(((HierarchyTree.ComponentNode)value).myComponent); if (pair != null) { return pair.first.getSimpleName() + '.' + pair.second; } else { return myComponent.getClass().getName(); } } return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus);//todo } public void expandPath() { TreeUtil.expandAll(this); int count = getRowCount(); ComponentNode node = new ComponentNode(myComponent); for (int i = 0; i < count; i++) { TreePath row = getPathForRow(i); if (row.getLastPathComponent().equals(node)) { setSelectionPath(row); scrollPathToVisible(getSelectionPath()); break; } } } @Override public void valueChanged(TreeSelectionEvent e) { TreePath[] paths = getSelectionPaths(); if (paths == null) { onComponentsChanged(Collections.emptyList()); return; } List<List<PropertyBean>> clickInfos = ContainerUtil.mapNotNull(paths, path -> { Object node = path.getLastPathComponent(); if (node instanceof ClickInfoNode) return ((ClickInfoNode)node).getInfo(); return null; }); if (!clickInfos.isEmpty()) { onClickInfoChanged(clickInfos.get(0)); return; } List<Component> components = ContainerUtil.mapNotNull(paths, path -> { Object node = path.getLastPathComponent(); if (node instanceof ComponentNode) return ((ComponentNode)node).getComponent(); return null; }); onComponentsChanged(components); } public abstract void onClickInfoChanged(List<? extends PropertyBean> info); public abstract void onComponentsChanged(List<Component> components); private static class ComponentNode extends DefaultMutableTreeNode { private final Component myComponent; String myText; private ComponentNode(@NotNull Component component) { super(component); myComponent = component; children = prepareChildren(myComponent); } Component getComponent() { return myComponent; } @Override public String toString() { return myText != null ? myText : myComponent.getClass().getName(); } public void setText(String value) { myText = value; } @Override public boolean equals(Object obj) { return obj instanceof ComponentNode && ((ComponentNode)obj).getComponent() == getComponent(); } @SuppressWarnings("UseOfObsoleteCollectionType") private static Vector prepareChildren(Component parent) { Vector<DefaultMutableTreeNode> result = new Vector<>(); if (parent instanceof JComponent) { Object o = ((JComponent)parent).getClientProperty(CLICK_INFO); if (o instanceof List) { //noinspection unchecked result.add(new ClickInfoNode((List<PropertyBean>)o)); } } if (parent instanceof Container) { for (Component component : ((Container)parent).getComponents()) { result.add(new ComponentNode(component)); } } if (parent instanceof Window) { Window[] children = ((Window)parent).getOwnedWindows(); for (Window child : children) { if (child instanceof InspectorWindow) continue; result.add(new ComponentNode(child)); } } return result; } } private static class ClickInfoNode extends DefaultMutableTreeNode { private final List<PropertyBean> myInfo; ClickInfoNode(List<PropertyBean> info) { myInfo = info; } @Override public String toString() { return "Clicked Info"; } public List<PropertyBean> getInfo() { return myInfo; } @Override public boolean isLeaf() { return true; } } } private static class HighlightComponent extends JComponent { @NotNull private final Color myColor; @NotNull private final Insets myInsets; private HighlightComponent(@NotNull Color c, @NotNull Insets insets) { myColor = c; myInsets = insets; } @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; Color oldColor = g2d.getColor(); Composite old = g2d.getComposite(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f)); Rectangle r = getBounds(); RectanglePainter.paint(g2d, 0, 0, r.width, r.height, 0, myColor, null); ((Graphics2D)g).setPaint(myColor.darker()); for (int i = 0; i < myInsets.left; i++) { LinePainter2D.paint(g2d, i, myInsets.top, i, r.height - myInsets.bottom - 1); } for (int i = 0; i < myInsets.right; i++) { LinePainter2D.paint(g2d, r.width - i - 1, myInsets.top, r.width - i - 1, r.height - myInsets.bottom - 1); } for (int i = 0; i < myInsets.top; i++) { LinePainter2D.paint(g2d, 0, i, r.width, i); } for (int i = 0; i < myInsets.bottom; i++) { LinePainter2D.paint(g2d, 0, r.height - i - 1, r.width, r.height - i - 1); } g2d.setComposite(old); g2d.setColor(oldColor); } } private static class InspectorTable extends JPanel { InspectorTableModel myModel; DimensionsComponent myDimensionComponent; private InspectorTable(@NotNull final List<? extends PropertyBean> clickInfo) { myModel = new InspectorTableModel(clickInfo); init(null); } private InspectorTable(@NotNull final Component component) { myModel = new InspectorTableModel(component); init(component); } private void init(@Nullable Component component) { setLayout(new BorderLayout()); StripeTable table = new StripeTable(myModel); new TableSpeedSearch(table); TableColumnModel columnModel = table.getColumnModel(); TableColumn propertyColumn = columnModel.getColumn(0); propertyColumn.setMinWidth(JBUIScale.scale(200)); propertyColumn.setMaxWidth(JBUIScale.scale(200)); propertyColumn.setResizable(false); propertyColumn.setCellRenderer(new PropertyNameRenderer()); TableColumn valueColumn = columnModel.getColumn(1); valueColumn.setMinWidth(JBUIScale.scale(200)); valueColumn.setResizable(false); valueColumn.setCellRenderer(new ValueCellRenderer()); valueColumn.setCellEditor(new DefaultCellEditor(new JBTextField()) { @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { Component comp = table.getCellRenderer(row, column).getTableCellRendererComponent(table, value, false, false, row, column); if (comp instanceof JLabel) { value = ((JLabel)comp).getText(); } Component result = super.getTableCellEditorComponent(table, value, isSelected, row, column); ((JComponent)result).setBorder(BorderFactory.createLineBorder(JBColor.GRAY, 1)); return result; } }); new DoubleClickListener(){ @Override protected boolean onDoubleClick(MouseEvent event) { int row = table.rowAtPoint(event.getPoint()); int column = table.columnAtPoint(event.getPoint()); if (row >=0 && row < table.getRowCount() && column >=0 && column < table.getColumnCount()) { Component renderer = table.getCellRenderer(row, column) .getTableCellRendererComponent(table, myModel.getValueAt(row, column), false, false, row, column); if (renderer instanceof JLabel) { //noinspection UseOfSystemOutOrSystemErr System.out.println((component != null ? getComponentName(component)+ " " : "" ) + ((JLabel)renderer).getText().replace("\r", "").replace("\tat", "\n\tat")); return true; } } return false; } }.installOn(table); table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); add(new JBScrollPane(table), BorderLayout.CENTER); if (component != null) { myDimensionComponent = new DimensionsComponent(component); add(myDimensionComponent, BorderLayout.SOUTH); } } public void refresh() { myModel.refresh(); myDimensionComponent.update(); myDimensionComponent.repaint(); } private static class PropertyNameRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final TableModel model = table.getModel(); boolean changed = false; if (model instanceof InspectorTableModel) { changed = ((InspectorTableModel)model).myProperties.get(row).changed; } final Color fg = isSelected ? table.getSelectionForeground() : changed ? JBUI.CurrentTheme.Link.linkColor() : table.getForeground(); final JBFont font = JBFont.label(); setFont(changed ? font.asBold() : font); setForeground(fg); return this; } } } private static class DimensionsComponent extends JComponent { Component myComponent; int myWidth; int myHeight; Border myBorder; Insets myInsets; private DimensionsComponent(@NotNull final Component component) { myComponent = component; setOpaque(true); setBackground(JBColor.WHITE); setBorder(JBUI.Borders.empty(5, 0)); setFont(JBUI.Fonts.label(9)); update(); } public void update() { myWidth = myComponent.getWidth(); myHeight = myComponent.getHeight(); if (myComponent instanceof JComponent) { myBorder = ((JComponent)myComponent).getBorder(); myInsets = ((JComponent)myComponent).getInsets(); } } @Override protected void paintComponent(final Graphics g) { Graphics2D g2d = (Graphics2D)g; GraphicsConfig config = new GraphicsConfig(g).setAntialiasing(UISettings.getShadowInstance().getIdeAAType() != AntialiasingType.OFF); Rectangle bounds = getBounds(); g2d.setColor(getBackground()); Insets insets = getInsets(); g2d.fillRect(insets.left, insets.top, bounds.width - insets.left - insets.right, bounds.height - insets.top - insets.bottom); final String sizeString = String.format("%d x %d", myWidth, myHeight); FontMetrics fm = g2d.getFontMetrics(); int sizeWidth = fm.stringWidth(sizeString); int fontHeight = fm.getHeight(); int innerBoxWidthGap = JBUIScale.scale(20); int innerBoxHeightGap = JBUIScale.scale(5); int boxSize = JBUIScale.scale(15); int centerX = bounds.width / 2; int centerY = bounds.height / 2; int innerX = centerX - sizeWidth / 2 - innerBoxWidthGap; int innerY = centerY - fontHeight / 2 - innerBoxHeightGap; int innerWidth = sizeWidth + innerBoxWidthGap * 2; int innerHeight = fontHeight + innerBoxHeightGap * 2; g2d.setColor(getForeground()); drawCenteredString(g2d, fm, fontHeight, sizeString, centerX, centerY); g2d.setColor(JBColor.GRAY); g2d.drawRect(innerX, innerY, innerWidth, innerHeight); Insets borderInsets = null; if (myBorder != null) borderInsets = myBorder.getBorderInsets(myComponent); UIUtil.drawDottedRectangle(g2d, innerX - boxSize, innerY - boxSize, innerX + innerWidth + boxSize, innerY + innerHeight + boxSize); drawInsets(g2d, fm, "border", borderInsets, boxSize, fontHeight, innerX, innerY, innerWidth, innerHeight); g2d.drawRect(innerX - boxSize * 2, innerY - boxSize * 2, innerWidth + boxSize * 4, innerHeight + boxSize * 4); drawInsets(g2d, fm, "insets", myInsets, boxSize * 2, fontHeight, innerX, innerY, innerWidth, innerHeight); config.restore(); } private static void drawInsets(Graphics2D g2d, FontMetrics fm, String name, Insets insets, int offset, int fontHeight, int innerX, int innerY, int innerWidth, int innerHeight) { g2d.setColor(JBColor.BLACK); g2d.drawString(name, innerX - offset + JBUIScale.scale(5), innerY - offset + fontHeight); g2d.setColor(JBColor.GRAY); int outerX = innerX - offset; int outerWidth = innerWidth + offset * 2; int outerY = innerY - offset; int outerHeight = innerHeight + offset * 2; final String top = insets != null ? Integer.toString(insets.top) : "-"; final String bottom = insets != null ? Integer.toString(insets.bottom) : "-"; final String left = insets != null ? Integer.toString(insets.left) : "-"; final String right = insets != null ? Integer.toString(insets.right) : "-"; int shift = JBUIScale.scale(7); drawCenteredString(g2d, fm, fontHeight, top, outerX + outerWidth / 2, outerY + shift); drawCenteredString(g2d, fm, fontHeight, bottom, outerX + outerWidth / 2, outerY + outerHeight - shift); drawCenteredString(g2d, fm, fontHeight, left, outerX + shift, outerY + outerHeight / 2); drawCenteredString(g2d, fm, fontHeight, right, outerX + outerWidth - shift, outerY + outerHeight / 2); } @Override public Dimension getMinimumSize() { return JBUI.size(120); } @Override public Dimension getPreferredSize() { return JBUI.size(150); } } private static void drawCenteredString(Graphics2D g2d, FontMetrics fm, int fontHeight, String text, int x, int y) { int width = fm.stringWidth(text); UIUtil.drawCenteredString(g2d, new Rectangle(x - width / 2, y - fontHeight / 2, width, fontHeight), text); } private static class ValueCellRenderer implements TableCellRenderer { private static final Map<Class, Renderer> RENDERERS = new HashMap<>(); static { RENDERERS.put(Point.class, new PointRenderer()); RENDERERS.put(Dimension.class, new DimensionRenderer()); RENDERERS.put(Insets.class, new InsetsRenderer()); RENDERERS.put(Rectangle.class, new RectangleRenderer()); RENDERERS.put(Color.class, new ColorRenderer()); RENDERERS.put(Font.class, new FontRenderer()); RENDERERS.put(Boolean.class, new BooleanRenderer()); RENDERERS.put(Icon.class, new IconRenderer()); RENDERERS.put(Border.class, new BorderRenderer()); } private static final Renderer<Object> DEFAULT_RENDERER = new ObjectRenderer(); private static final JLabel NULL_RENDERER = new JLabel("-"); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { NULL_RENDERER.setOpaque(isSelected); NULL_RENDERER.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); NULL_RENDERER.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); return NULL_RENDERER; } Renderer<Object> renderer = ObjectUtils.notNull(getRenderer(value.getClass()), DEFAULT_RENDERER); JComponent result = renderer.setValue(value); result.setOpaque(isSelected); result.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); result.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); return result; } @Nullable private static Renderer<Object> getRenderer(Class clazz) { if (clazz == null) return null; Renderer<Object> renderer = (Renderer<Object>)RENDERERS.get(clazz); if (renderer != null) return renderer; Class[] interfaces = clazz.getInterfaces(); for (Class aClass : interfaces) { renderer = getRenderer(aClass); if (renderer != null) { return renderer; } } clazz = clazz.getSuperclass(); if (clazz != null) { return getRenderer(clazz); } return null; } } private interface Renderer<T> { JComponent setValue(@NotNull T value); } private static class PointRenderer extends JLabel implements Renderer<Point> { @Override public JComponent setValue(@NotNull final Point value) { setText(String.valueOf(value.x) + ':' + value.y); return this; } } private static class DimensionRenderer extends JLabel implements Renderer<Dimension> { @Override public JComponent setValue(@NotNull final Dimension value) { setText(value.width + "x" + value.height); return this; } } private static class InsetsRenderer extends JLabel implements Renderer<Insets> { @Override public JComponent setValue(@NotNull final Insets value) { setText("top: " + value.top + " left:" + value.left + " bottom:" + value.bottom + " right:" + value.right); return this; } } private static class RectangleRenderer extends JLabel implements Renderer<Rectangle> { @Override public JComponent setValue(@NotNull final Rectangle value) { setText(toString(value)); return this; } @NotNull static String toString(@NotNull Rectangle r) { return r.width + "x" + r.height + " @ " + r.x + ":" + r.y; } } private static class ColorRenderer extends JLabel implements Renderer<Color> { @Override public JComponent setValue(@NotNull final Color value) { StringBuilder sb = new StringBuilder(); sb.append(" r:").append(value.getRed()); sb.append(" g:").append(value.getGreen()); sb.append(" b:").append(value.getBlue()); sb.append(" a:").append(value.getAlpha()); sb.append(" argb:0x"); String hex = Integer.toHexString(value.getRGB()); for (int i = hex.length(); i < 8; i++) sb.append('0'); sb.append(StringUtil.toUpperCase(hex)); if (value instanceof UIResource) sb.append(" UIResource"); setText(sb.toString()); setIcon(createColorIcon(value)); return this; } } private static class FontRenderer extends JLabel implements Renderer<Font> { @Override public JComponent setValue(@NotNull final Font value) { StringBuilder sb = new StringBuilder(); sb.append(value.getFontName()).append(" (").append(value.getFamily()).append("), ").append(value.getSize()).append("px"); if (Font.BOLD == (Font.BOLD & value.getStyle())) sb.append(" bold"); if (Font.ITALIC == (Font.ITALIC & value.getStyle())) sb.append(" italic"); if (value instanceof UIResource) sb.append(" UIResource"); setText(sb.toString()); return this; } } private static class BooleanRenderer extends JLabel implements Renderer<Boolean> { @Override public JComponent setValue(@NotNull final Boolean value) { setText(value ? "Yes" : "No"); return this; } } private static class IconRenderer extends JLabel implements Renderer<Icon> { @Override public JComponent setValue(@NotNull final Icon value) { setIcon(value); setText(getPathToIcon(value)); return this; } private static String getPathToIcon(@NotNull Icon value) { if (value instanceof RetrievableIcon) { Icon icon = ((RetrievableIcon)value).retrieveIcon(); if (icon != value) { return getPathToIcon(icon); } } String text = getToStringValue(value); if (text.startsWith("jar:") && text.contains("!")) { int index = text.lastIndexOf("!"); String jarFile = text.substring(4, index); String path = text.substring(index + 1); return path + " in " + jarFile; } return text; } } private static class BorderRenderer extends JLabel implements Renderer<Border> { @Override public JComponent setValue(@NotNull final Border value) { setText(getTextDescription(value)); if (value instanceof CompoundBorder) { Color insideColor = getBorderColor(((CompoundBorder)value).getInsideBorder()); Color outsideColor = getBorderColor(((CompoundBorder)value).getOutsideBorder()); if (insideColor != null && outsideColor != null) { setIcon(createColorIcon(insideColor, outsideColor)); } else if (insideColor != null) { setIcon(createColorIcon(insideColor)); } else if (outsideColor != null) { setIcon(createColorIcon(outsideColor)); } else { setIcon(null); } } else { Color color = getBorderColor(value); setIcon(color != null ? createColorIcon(color) : null); } return this; } @Nullable private static Color getBorderColor(@NotNull Border value) { if (value instanceof LineBorder) { return ((LineBorder)value).getLineColor(); } else if (value instanceof CustomLineBorder) { try { return (Color)ReflectionUtil.findField(CustomLineBorder.class, Color.class, "myColor").get(value); } catch (Exception ignore) { } } return null; } @NotNull private static String getTextDescription(@Nullable Border value) { if (value == null) { return "null"; } StringBuilder sb = new StringBuilder(); sb.append(getClassName(value)); Color color = getBorderColor(value); if (color != null) sb.append(" color=").append(color.toString()); if (value instanceof LineBorder) { if (((LineBorder)value).getRoundedCorners()) sb.append(" roundedCorners=true"); } if (value instanceof TitledBorder) { sb.append(" title='").append(((TitledBorder)value).getTitle()).append("'"); } if (value instanceof CompoundBorder) { sb.append(" inside={").append(getTextDescription(((CompoundBorder)value).getInsideBorder())).append("}"); sb.append(" outside={").append(getTextDescription(((CompoundBorder)value).getOutsideBorder())).append("}"); } if (value instanceof EmptyBorder) { Insets insets = ((EmptyBorder)value).getBorderInsets(); sb.append(" insets={top=").append(insets.top) .append(" left=").append(insets.left) .append(" bottom=").append(insets.bottom) .append(" right=").append(insets.right) .append("}"); } if (value instanceof UIResource) sb.append(" UIResource"); sb.append(" (").append(getToStringValue(value)).append(")"); return sb.toString(); } } private static class ObjectRenderer extends JLabel implements Renderer<Object> { { putClientProperty("html.disable", Boolean.TRUE); } @Override public JComponent setValue(@NotNull final Object value) { setText(getToStringValue(value)); return this; } } @SuppressWarnings("rawtypes") @NotNull private static String getToStringValue(@NotNull Object value) { StringBuilder sb = new StringBuilder(); if (value.getClass().getName().equals("javax.swing.ArrayTable")) { Object table = ReflectionUtil.getField(value.getClass(), value, Object.class, "table"); if (table != null) { try { if (table instanceof Object[]) { Object[] arr = (Object[])table; for (int i = 0; i < arr.length; i += 2) { if (arr[i].equals("uiInspector.addedAt")) continue; if (sb.length() > 0) sb.append(","); sb.append('[').append(arr[i]).append("->").append(arr[i + 1]).append(']'); } } else if (table instanceof Map) { Map map = (Map)table; Set<Map.Entry> set = map.entrySet(); for (Map.Entry entry : set) { if (entry.getKey().equals("uiInspector.addedAt")) continue; if (sb.length() > 0) sb.append(","); sb.append('[').append(entry.getKey()).append("->").append(entry.getValue()).append(']'); } } } catch (Exception e) { //ignore } } if (sb.length() == 0) sb.append("-"); value = sb; } if (value.getClass().isArray()) { int length = Array.getLength(value); for (int index = 0; index < length; index++) { if (sb.length() > 0) sb.append(", "); Object obj = Array.get(value, index); if (obj != null) { sb.append(obj.getClass().getName()); } } value = sb.length() == 0 ? "-" : sb; } String toString = StringUtil.notNullize(String.valueOf(value), "toString()==null"); return toString.replace('\n', ' '); } @NotNull private static String getClassName(Object value) { Class<?> clazz0 = value.getClass(); Class<?> clazz = clazz0.isAnonymousClass() ? clazz0.getSuperclass() : clazz0; return clazz.getSimpleName(); } private static ColorIcon createColorIcon(Color color) { return JBUI.scale(new ColorIcon(13, 11, color, true)); } private static Icon createColorIcon(Color color1, Color color2) { return JBUI.scale(new ColorsIcon(11, color1, color2)); } private static class PropertyBean { final String propertyName; final Object propertyValue; final boolean changed; PropertyBean(String name, Object value) { this(name, value, false); } PropertyBean(String name, Object value, boolean changed) { propertyName = name; propertyValue = value; this.changed = changed; } } private static class InspectorTableModel extends AbstractTableModel { final List<String> PROPERTIES = Arrays.asList( "ui", "getLocation", "getLocationOnScreen", "getSize", "isOpaque", "getBorder", "getForeground", "getBackground", "getFont", "getCellRenderer", "getCellEditor", "getMinimumSize", "getMaximumSize", "getPreferredSize", "getText", "isEditable", "getIcon", "getVisibleRect", "getLayout", "getAlignmentX", "getAlignmentY", "getTooltipText", "getToolTipText", "cursor", "isShowing", "isEnabled", "isVisible", "isDoubleBuffered", "isFocusable", "isFocusCycleRoot", "isFocusOwner", "isValid", "isDisplayable", "isLightweight", "getClientProperties", "getMouseListeners" ); final List<String> CHECKERS = Arrays.asList( "isForegroundSet", "isBackgroundSet", "isFontSet", "isMinimumSizeSet", "isMaximumSizeSet", "isPreferredSizeSet" ); final List<String> ACCESSIBLE_CONTEXT_PROPERTIES = Arrays.asList( "getAccessibleRole", "getAccessibleName", "getAccessibleDescription", "getAccessibleAction", "getAccessibleChildrenCount", "getAccessibleIndexInParent", "getAccessibleRelationSet", "getAccessibleStateSet", "getAccessibleEditableText", "getAccessibleTable", "getAccessibleText", "getAccessibleValue", "accessibleChangeSupport" ); final List<String> MIGLAYOUT_CC_PROPERTIES = Arrays.asList( "getHorizontal", "getVertical" ); final Component myComponent; final List<PropertyBean> myProperties = new ArrayList<>(); InspectorTableModel(@NotNull List<? extends PropertyBean> clickInfo) { myComponent = null; myProperties.addAll(clickInfo); } InspectorTableModel(@NotNull Component c) { myComponent = c; fillTable(); } void fillTable() { addProperties("", myComponent, PROPERTIES); Object addedAt = myComponent instanceof JComponent ? ((JComponent)myComponent).getClientProperty("uiInspector.addedAt") : null; myProperties.add(new PropertyBean("added-at", addedAt)); // Add properties related to Accessibility support. This is useful for manually // inspecting what kind (if any) of accessibility support components expose. boolean isAccessible = myComponent instanceof Accessible; myProperties.add(new PropertyBean("accessible", isAccessible)); AccessibleContext context = myComponent.getAccessibleContext(); myProperties.add(new PropertyBean("accessibleContext", context)); if (isAccessible) { addProperties(" ", myComponent.getAccessibleContext(), ACCESSIBLE_CONTEXT_PROPERTIES); } if (myComponent instanceof Container) { addLayoutProperties((Container)myComponent); } if (myComponent.getParent() != null) { LayoutManager layout = myComponent.getParent().getLayout(); if (layout instanceof com.intellij.ui.layout.migLayout.patched.MigLayout) { CC cc = ((com.intellij.ui.layout.migLayout.patched.MigLayout)layout).getComponentConstraints().get(myComponent); if (cc != null) { addMigLayoutComponentConstraints(cc); } } } } private void addProperties(@NotNull String prefix, @NotNull Object component, @NotNull List<String> methodNames) { Class<?> clazz = component.getClass(); myProperties.add(new PropertyBean(prefix + "class", clazz.getName())); if (clazz.isAnonymousClass()) { Class<?> superClass = clazz.getSuperclass(); if (superClass != null) { myProperties.add(new PropertyBean(prefix + "superclass", superClass.getName(), true)); } } Class<?> declaringClass = clazz.getDeclaringClass(); if (declaringClass != null) { myProperties.add(new PropertyBean(prefix + "declaringClass", declaringClass.getName())); } if (component instanceof com.intellij.ui.treeStructure.Tree) { TreeModel model = ((Tree)component).getModel(); if (model != null) { myProperties.add(new PropertyBean(prefix + "treeModelClass", model.getClass().getName(), true)); } } addActionInfo(component); addToolbarInfo(component); addGutterInfo(component); StringBuilder classHierarchy = new StringBuilder(); for (Class<?> cl = clazz.getSuperclass(); cl != null; cl = cl.getSuperclass()) { if (classHierarchy.length() > 0) classHierarchy.append(" -> "); classHierarchy.append(cl.getName()); if (JComponent.class.getName().equals(cl.getName())) break; } myProperties.add(new PropertyBean(prefix + "hierarchy", classHierarchy.toString())); if (component instanceof Component) { DialogWrapper dialog = DialogWrapper.findInstance((Component)component); if (dialog != null) { myProperties.add(new PropertyBean(prefix + "dialogWrapperClass", dialog.getClass().getName(), true)); } } addPropertiesFromMethodNames(prefix, component, methodNames); } private static List<Method> collectAllMethodsRecursively(Class<?> clazz) { ArrayList<Method> list = new ArrayList<>(); for(Class<?> cl = clazz; cl != null; cl = cl.getSuperclass()) { list.addAll(Arrays.asList(cl.getDeclaredMethods())); } return list; } private void addPropertiesFromMethodNames(@NotNull String prefix, @NotNull Object component, @NotNull List<String> methodNames) { Class<?> clazz0 = component.getClass(); Class<?> clazz = clazz0.isAnonymousClass() ? clazz0.getSuperclass() : clazz0; for (String name: methodNames) { String propertyName = ObjectUtils.notNull(StringUtil.getPropertyName(name), name); Object propertyValue; try { try { //noinspection ConstantConditions propertyValue = ReflectionUtil.findMethod(collectAllMethodsRecursively(clazz), name).invoke(component); } catch (Exception e) { propertyValue = ReflectionUtil.findField(clazz, null, name).get(component); } boolean changed = false; try { final String checkerMethodName = "is" + StringUtil.capitalize(propertyName) + "Set"; if (CHECKERS.contains(checkerMethodName)) { final Object value = ReflectionUtil.findMethod(Arrays.asList(clazz.getMethods()), checkerMethodName).invoke(component); if (value instanceof Boolean) { changed = ((Boolean)value).booleanValue(); } } } catch (Exception e) {changed = false;} myProperties.add(new PropertyBean(prefix + propertyName, propertyValue, changed)); } catch (Exception ignored) { } } } private void addGutterInfo(Object component) { if (component instanceof EditorGutterComponentEx && ((JComponent)component).getClientProperty(CLICK_INFO_POINT) instanceof Point) { Point clickPoint = (Point)((JComponent)component).getClientProperty(CLICK_INFO_POINT); GutterMark renderer = ((EditorGutterComponentEx)component).getGutterRenderer(clickPoint); if (renderer != null) { myProperties.add(new PropertyBean("gutter renderer", renderer.getClass().getName(), true)); } } } private void addActionInfo(Object component) { AnAction action = null; if (component instanceof ActionButton) { action = ((ActionButton)component).getAction(); } else if (component instanceof JComponent) { if (component instanceof ActionMenuItem) { action = ((ActionMenuItem)component).getAnAction(); } else { action = getAction( ComponentUtil.findParentByCondition((Component)component, c -> getAction(c) != null) ); } } if (action != null) { myProperties.add(new PropertyBean("action", action.getClass().getName(), true)); } } private void addToolbarInfo(Object component) { if (component instanceof ActionToolbarImpl) { ActionToolbarImpl toolbar = (ActionToolbarImpl)component; myProperties.add(new PropertyBean("Toolbar Place", toolbar.getPlace())); ActionGroup group = toolbar.getActionGroup(); String toolbarId = getActionGroupId(group); myProperties.add(new PropertyBean("Toolbar Group", toolbarId)); Set<String> ids = new HashSet<>(); recursiveCollectGroupIds(group, ids); ContainerUtil.addIfNotNull(ids, toolbarId); if (ids.size() > 1 || ids.size() == 1 && toolbarId == null) { myProperties.add(new PropertyBean("All Groups", StringUtil.join(ids, ", "))); } } } private static void recursiveCollectGroupIds(@NotNull ActionGroup group, @NotNull Set<String> result) { for (AnAction action : group.getChildren(null)) { if (action instanceof ActionGroup) { ActionGroup child = (ActionGroup)action; ContainerUtil.addIfNotNull(result, getActionGroupId(child)); recursiveCollectGroupIds(child, result); } } } private static String getActionGroupId(@NotNull ActionGroup action) { if (action instanceof CustomisedActionGroup) { action = ((CustomisedActionGroup)action).getOrigin(); } return ActionManager.getInstance().getId(action); } private void addLayoutProperties(@NotNull Container component) { String prefix = " "; LayoutManager layout = component.getLayout(); if (layout instanceof GridBagLayout) { GridBagLayout bagLayout = (GridBagLayout)layout; GridBagConstraints defaultConstraints = ReflectionUtil.getField(GridBagLayout.class, bagLayout, GridBagConstraints.class, "defaultConstraints"); myProperties.add(new PropertyBean("GridBagLayout constraints", String.format("defaultConstraints - %s", toString(defaultConstraints)))); if (bagLayout.columnWidths != null) myProperties.add(new PropertyBean(prefix + "columnWidths", Arrays.toString(bagLayout.columnWidths))); if (bagLayout.rowHeights != null) myProperties.add(new PropertyBean(prefix + "rowHeights", Arrays.toString(bagLayout.rowHeights))); if (bagLayout.columnWeights != null) myProperties.add(new PropertyBean(prefix + "columnWeights", Arrays.toString(bagLayout.columnWeights))); if (bagLayout.rowWeights != null) myProperties.add(new PropertyBean(prefix + "rowWeights", Arrays.toString(bagLayout.rowWeights))); for (Component child : component.getComponents()) { myProperties.add(new PropertyBean(prefix + getComponentName(child), toString(bagLayout.getConstraints(child)))); } } else if (layout instanceof BorderLayout) { BorderLayout borderLayout = (BorderLayout)layout; myProperties.add(new PropertyBean("BorderLayout constraints", String.format("hgap - %s, vgap - %s", borderLayout.getHgap(), borderLayout.getVgap()))); for (Component child : component.getComponents()) { myProperties.add(new PropertyBean(prefix + getComponentName(child), borderLayout.getConstraints(child))); } } else if (layout instanceof CardLayout) { CardLayout cardLayout = (CardLayout)layout; Integer currentCard = ReflectionUtil.getField(CardLayout.class, cardLayout, null, "currentCard"); //noinspection UseOfObsoleteCollectionType Vector vector = ReflectionUtil.getField(CardLayout.class, cardLayout, Vector.class, "vector"); String cardDescription = "???"; if (vector != null && currentCard != null) { Object card = vector.get(currentCard); cardDescription = ReflectionUtil.getField(card.getClass(), card, String.class, "name"); } myProperties.add(new PropertyBean("CardLayout constraints", String.format("card - %s, hgap - %s, vgap - %s", cardDescription, cardLayout.getHgap(), cardLayout.getVgap()))); if (vector != null) { for (Object card : vector) { String cardName = ReflectionUtil.getField(card.getClass(), card, String.class, "name"); Component child = ReflectionUtil.getField(card.getClass(), card, Component.class, "comp"); myProperties.add(new PropertyBean(prefix + getComponentName(child), cardName)); } } } else if (layout instanceof MigLayout) { MigLayout migLayout = (MigLayout)layout; Object constraints = migLayout.getLayoutConstraints(); if (constraints instanceof LC) { addMigLayoutLayoutConstraints((LC)constraints); } else { myProperties.add(new PropertyBean("MigLayout layout constraints", constraints)); } constraints = migLayout.getColumnConstraints(); if (constraints instanceof AC) { addMigLayoutAxisConstraints("MigLayout column constraints", (AC)constraints); } else { myProperties.add(new PropertyBean("MigLayout column constraints", constraints)); } constraints = migLayout.getRowConstraints(); if (constraints instanceof AC) { addMigLayoutAxisConstraints("MigLayout row constraints", (AC)constraints); } else { myProperties.add(new PropertyBean("MigLayout row constraints", constraints)); } for (Component child : component.getComponents()) { myProperties.add(new PropertyBean(prefix + getComponentName(child), migLayout.getComponentConstraints(child))); } } else if (layout instanceof com.intellij.ui.layout.migLayout.patched.MigLayout) { com.intellij.ui.layout.migLayout.patched.MigLayout migLayout = (com.intellij.ui.layout.migLayout.patched.MigLayout)layout; addMigLayoutLayoutConstraints(migLayout.getLayoutConstraints()); addMigLayoutAxisConstraints("MigLayout column constraints", migLayout.getColumnConstraints()); addMigLayoutAxisConstraints("MigLayout row constraints", migLayout.getRowConstraints()); } } private void addMigLayoutLayoutConstraints(LC lc) { myProperties.add(new PropertyBean("MigLayout layout constraints", lcConstraintToString(lc))); UnitValue[] insets = lc.getInsets(); if (insets != null) { myProperties.add(new PropertyBean(" lc.insets", Arrays.toString(insets))); } UnitValue alignX = lc.getAlignX(); UnitValue alignY = lc.getAlignY(); if (alignX != null || alignY != null) { myProperties.add(new PropertyBean(" lc.align", "x: " + alignX + "; y: " + alignY)); } BoundSize width = lc.getWidth(); BoundSize height = lc.getHeight(); if (width != BoundSize.NULL_SIZE || height != BoundSize.NULL_SIZE) { myProperties.add(new PropertyBean(" lc.size", "width: " + width + "; height: " + height)); } BoundSize gridX = lc.getGridGapX(); BoundSize gridY = lc.getGridGapY(); if (gridX != null || gridY != null) { myProperties.add(new PropertyBean(" lc.gridGap", "x: " + gridX + "; y: " + gridY)); } boolean fillX = lc.isFillX(); boolean fillY = lc.isFillY(); if (fillX || fillY) { myProperties.add(new PropertyBean(" lc.fill", "x: " + fillX + "; y: " + fillY)); } BoundSize packWidth = lc.getPackWidth(); BoundSize packHeight = lc.getPackHeight(); if (packWidth != BoundSize.NULL_SIZE || packHeight != BoundSize.NULL_SIZE) { myProperties.add(new PropertyBean(" lc.pack", "width: " + packWidth + "; height: " + packHeight + "; widthAlign: " + lc.getPackWidthAlign() + "; heightAlign: " + lc.getPackHeightAlign())); } } private static String lcConstraintToString(LC constraint) { return "isFlowX=" + constraint.isFlowX() + " leftToRight=" + constraint.getLeftToRight() + " noGrid=" + constraint.isNoGrid() + " hideMode=" + constraint.getHideMode() + " visualPadding=" + constraint.isVisualPadding() + " topToBottom=" + constraint.isTopToBottom() + " noCache=" + constraint.isNoCache(); } private void addMigLayoutAxisConstraints(String title, AC ac) { myProperties.add(new PropertyBean(title, ac)); DimConstraint[] constraints = ac.getConstaints(); for (int i = 0; i < constraints.length; i++) { addDimConstraintProperties(" [" + i + "]", constraints[i]); } } private void addMigLayoutComponentConstraints(CC cc) { myProperties.add(new PropertyBean("MigLayout component constraints", componentConstraintsToString(cc))); DimConstraint horizontal = cc.getHorizontal(); addDimConstraintProperties(" cc.horizontal", horizontal); DimConstraint vertical = cc.getVertical(); addDimConstraintProperties(" cc.vertical", vertical); } private void addDimConstraintProperties(String name, DimConstraint constraint) { myProperties.add(new PropertyBean(name, dimConstraintToString(constraint))); BoundSize size = constraint.getSize(); if (size != null) { myProperties.add(new PropertyBean(" " + name + ".size", size.toString())); } UnitValue align = constraint.getAlign(); if (align != null) { myProperties.add(new PropertyBean(" " + name + ".align", align.toString())); } BoundSize gapBefore = constraint.getGapBefore(); if (gapBefore != null && !gapBefore.isUnset()) { myProperties.add(new PropertyBean(" " + name + ".gapBefore", gapBefore.toString())); } BoundSize gapAfter = constraint.getGapAfter(); if (gapAfter != null && !gapAfter.isUnset()) { myProperties.add(new PropertyBean(" " + name + ".gapAfter", gapAfter.toString())); } } private static String componentConstraintsToString(CC cc) { CC newCC = new CC(); StringBuilder stringBuilder = new StringBuilder(); if (cc.getSkip() != newCC.getSkip()) { stringBuilder.append(" skip=").append(cc.getSkip()); } if (cc.getSpanX() != newCC.getSpanX()) { stringBuilder.append(" spanX=").append(cc.getSpanX() == LayoutUtil.INF ? "INF" : cc.getSpanX()); } if (cc.getSpanY() != newCC.getSpanY()) { stringBuilder.append(" spanY=").append(cc.getSpanY() == LayoutUtil.INF ? "INF" : cc.getSpanY()); } if (cc.getPushX() != null) { stringBuilder.append(" pushX=").append(cc.getPushX()); } if (cc.getPushY() != null) { stringBuilder.append(" pushY=").append(cc.getPushY()); } if (cc.getSplit() != newCC.getSplit()) { stringBuilder.append(" split=").append(cc.getSplit()); } if (cc.isWrap()) { stringBuilder.append(" wrap="); if (cc.getWrapGapSize() != null) { stringBuilder.append(cc.getWrapGapSize()); } else { stringBuilder.append("true"); } } if (cc.isNewline()) { stringBuilder.append(" newline="); if (cc.getNewlineGapSize() != null) { stringBuilder.append(cc.getNewlineGapSize()); } else { stringBuilder.append("true"); } } return stringBuilder.toString().trim(); } private static String dimConstraintToString(DimConstraint constraint) { StringBuilder stringBuilder = new StringBuilder(); DimConstraint newConstraint = new DimConstraint(); if (!Comparing.equal(constraint.getGrow(), newConstraint.getGrow())) { stringBuilder.append(" grow=").append(constraint.getGrow()); } if (constraint.getGrowPriority() != newConstraint.getGrowPriority()) { stringBuilder.append(" growPrio=").append(constraint.getGrowPriority()); } if (!Comparing.equal(constraint.getShrink(), newConstraint.getShrink())) { stringBuilder.append(" shrink=").append(constraint.getShrink()); } if (constraint.getShrinkPriority() != newConstraint.getShrinkPriority()) { stringBuilder.append(" shrinkPrio=").append(constraint.getShrinkPriority()); } if (constraint.isFill() != newConstraint.isFill()) { stringBuilder.append(" fill=").append(constraint.isFill()); } if (constraint.isNoGrid() != newConstraint.isNoGrid()) { stringBuilder.append(" noGrid=").append(constraint.isNoGrid()); } if (!Comparing.equal(constraint.getSizeGroup(), newConstraint.getSizeGroup())) { stringBuilder.append(" sizeGroup=").append(constraint.getSizeGroup()); } if (!Comparing.equal(constraint.getEndGroup(), newConstraint.getEndGroup())) { stringBuilder.append(" endGroup=").append(constraint.getEndGroup()); } return stringBuilder.toString(); } @NotNull private static String toString(@Nullable GridBagConstraints constraints) { if (constraints == null) return "null"; MoreObjects.ToStringHelper h = MoreObjects.toStringHelper(""); appendFieldValue(h, constraints, "gridx"); appendFieldValue(h, constraints, "gridy"); appendFieldValue(h, constraints, "gridwidth"); appendFieldValue(h, constraints, "gridheight"); appendFieldValue(h, constraints, "weightx"); appendFieldValue(h, constraints, "weighty"); appendFieldValue(h, constraints, "anchor"); appendFieldValue(h, constraints, "fill"); appendFieldValue(h, constraints, "insets"); appendFieldValue(h, constraints, "ipadx"); appendFieldValue(h, constraints, "ipady"); return h.toString(); } private static void appendFieldValue(@NotNull MoreObjects.ToStringHelper h, @NotNull GridBagConstraints constraints, @NotNull String field) { Object value = ReflectionUtil.getField(GridBagConstraints.class, constraints, null, field); Object defaultValue = ReflectionUtil.getField(GridBagConstraints.class, new GridBagConstraints(), null, field); if (!Comparing.equal(value, defaultValue)) h.add(field, value); } @Override @Nullable public Object getValueAt(int row, int column) { final PropertyBean bean = myProperties.get(row); if (bean != null) { return column == 0 ? bean.propertyName : bean.propertyValue; } return null; } @Override public boolean isCellEditable(int row, int col) { return col == 1 && updater(myProperties.get(row)) != null; } @Override public void setValueAt(Object value, int row, int col) { PropertyBean bean = myProperties.get(row); try { myProperties.set(row, new PropertyBean(bean.propertyName, ObjectUtils.notNull(updater(bean)).fun(value))); } catch (Exception ignored) { } } @Nullable public Function<Object, Object> updater(PropertyBean bean) { if (myComponent == null) return null; String name = bean.propertyName.trim(); try { try { Method getter; try { getter = myComponent.getClass().getMethod("get" + StringUtil.capitalize(name)); } catch (Exception e) { getter = myComponent.getClass().getMethod("is" + StringUtil.capitalize(name)); } final Method finalGetter = getter; final Method setter = myComponent.getClass().getMethod("set" + StringUtil.capitalize(name), getter.getReturnType()); setter.setAccessible(true); return o -> { try { setter.invoke(myComponent, fromObject(o, finalGetter.getReturnType())); return finalGetter.invoke(myComponent); } catch (Exception e) { throw new RuntimeException(e); } }; } catch (Exception e) { final Field field = ReflectionUtil.findField(myComponent.getClass(), null, name); if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) { return null; } return o -> { try { field.set(myComponent, fromObject(o, field.getType())); return field.get(myComponent); } catch (Exception e1) { throw new RuntimeException(e1); } }; } } catch (Exception ignored) { } return null; } @Override public int getColumnCount() { return 2; } @Override public int getRowCount() { return myProperties.size(); } @Override public String getColumnName(int columnIndex) { return columnIndex == 0 ? "Property" : "Value"; } @Override public Class<?> getColumnClass(int columnIndex) { return columnIndex == 0 ? String.class : Object.class; } public void refresh() { myProperties.clear(); fillTable(); fireTableDataChanged(); } } @Nullable private static AnAction getAction(Component c) { return UIUtil.getClientProperty(c, ACTION_KEY); } private static class UiInspector implements AWTEventListener, Disposable { UiInspector() { Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK); } @Override public void dispose() { Toolkit.getDefaultToolkit().removeAWTEventListener(this); for (Window window : Window.getWindows()) { if (window instanceof InspectorWindow) { ((InspectorWindow)window).close(); } } } public void showInspector(@NotNull Component c) { Window window = new InspectorWindow(c); if (DimensionService.getInstance().getSize(InspectorWindow.getDimensionServiceKey()) == null) { window.pack(); } window.setVisible(true); window.toFront(); } @Override public void eventDispatched(AWTEvent event) { if (event instanceof MouseEvent) { processMouseEvent((MouseEvent)event); } else if (event instanceof ContainerEvent) { processContainerEvent((ContainerEvent)event); } } private void processMouseEvent(MouseEvent me) { if (!me.isAltDown() || !me.isControlDown()) return; if (me.getClickCount() != 1 || me.isPopupTrigger()) return; me.consume(); if (me.getID() != MouseEvent.MOUSE_RELEASED) return; Component component = me.getComponent(); if (component instanceof Container) { component = ((Container)component).findComponentAt(me.getPoint()); } else if (component == null) { component = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); } if (component != null) { if (component instanceof JComponent) { ((JComponent)component).putClientProperty(CLICK_INFO, getClickInfo(me, component)); ((JComponent)component).putClientProperty(CLICK_INFO_POINT, me.getPoint()); } showInspector(component); } } private static List<PropertyBean> getClickInfo(MouseEvent me, Component component) { if (me.getComponent() == null) return null; me = SwingUtilities.convertMouseEvent(me.getComponent(), me, component); List<PropertyBean> clickInfo = new ArrayList<>(); //clickInfo.add(new PropertyBean("Click point", me.getPoint())); if (component instanceof JList) { JList list = (JList)component; int row = list.getUI().locationToIndex(list, me.getPoint()); if (row != -1) { Component rendererComponent = list.getCellRenderer() .getListCellRendererComponent(list, list.getModel().getElementAt(row), row, list.getSelectionModel().isSelectedIndex(row), list.hasFocus()); clickInfo.addAll(findActionsFor(list.getModel().getElementAt(row))); clickInfo.add(new PropertyBean(RENDERER_BOUNDS, list.getUI().getCellBounds(list, row, row))); clickInfo.addAll(new InspectorTableModel(rendererComponent).myProperties); return clickInfo; } } if (component instanceof JTable) { JTable table = (JTable)component; int row = table.rowAtPoint(me.getPoint()); int column = table.columnAtPoint(me.getPoint()); if (row != -1 && column != -1) { Component rendererComponent = table.getCellRenderer(row, column) .getTableCellRendererComponent(table, table.getValueAt(row, column), table.getSelectionModel().isSelectedIndex(row), table.hasFocus(), row, column); clickInfo.add(new PropertyBean(RENDERER_BOUNDS, table.getCellRect(row, column, true))); clickInfo.addAll(new InspectorTableModel(rendererComponent).myProperties); return clickInfo; } } if (component instanceof JTree) { JTree tree = (JTree)component; TreePath path = tree.getClosestPathForLocation(me.getX(), me.getY()); if (path != null) { Object object = path.getLastPathComponent(); Component rendererComponent = tree.getCellRenderer().getTreeCellRendererComponent( tree, object, tree.getSelectionModel().isPathSelected(path), tree.isExpanded(path), tree.getModel().isLeaf(object), tree.getRowForPath(path), tree.hasFocus()); clickInfo.add(new PropertyBean(RENDERER_BOUNDS, tree.getPathBounds(path))); clickInfo.addAll(new InspectorTableModel(rendererComponent).myProperties); return clickInfo; } } return null; } private static List<PropertyBean> findActionsFor(Object object) { if (object instanceof PopupFactoryImpl.ActionItem) { AnAction action = ((PopupFactoryImpl.ActionItem)object).getAction(); return Collections.singletonList(new PropertyBean("action", action.getClass().getName(), true)); } if (object instanceof QuickFixWrapper) { return findActionsFor(((QuickFixWrapper)object).getFix()); } else if (object instanceof IntentionActionDelegate) { IntentionAction delegate = ((IntentionActionDelegate)object).getDelegate(); if (delegate != object) { return findActionsFor(delegate); } } else if (object instanceof IntentionAction) { return Collections.singletonList(new PropertyBean("intention action", object.getClass().getName(), true)); } else if (object instanceof QuickFix) { return Collections.singletonList(new PropertyBean("quick fix", object.getClass().getName(), true)); } return Collections.emptyList(); } private static void processContainerEvent(ContainerEvent event) { Component child = event.getID() == ContainerEvent.COMPONENT_ADDED ? event.getChild() : null; if (child instanceof JComponent && !(event.getSource() instanceof CellRendererPane)) { String text = ExceptionUtil.getThrowableText(new Throwable()); int first = text.indexOf("at com.intellij", text.indexOf("at java.awt")); int last = text.indexOf("at java.awt.EventQueue"); if (last == -1) last = text.length(); String val = last > first && first > 0 ? text.substring(first, last): null; ((JComponent)child).putClientProperty("uiInspector.addedAt", val); } } } /** @noinspection UseJBColor*/ private static Object fromObject(Object o, Class<?> type) { if (o == null) return null; if (type.isAssignableFrom(o.getClass())) return o; if ("null".equals(o)) return null; String value = String.valueOf(o).trim(); if (type == int.class) return Integer.parseInt(value); if (type == boolean.class) return "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value); if (type == byte.class) return Byte.parseByte(value); if (type == short.class) return Short.parseShort(value); if (type == double.class) return Double.parseDouble(value); if (type == float.class) return Float.parseFloat(value); String[] s = value.split("(?i)\\s*(?:[x@:]|[a-z]+:)\\s*", 6); if (type == Dimension.class) { if (s.length == 2) return new Dimension(Integer.parseInt(s[0]), Integer.parseInt(s[1])); } else if (type == Point.class) { if (s.length == 2) return new Point(Integer.parseInt(s[0]), Integer.parseInt(s[1])); } else if (type == Rectangle.class) { if (s.length >= 5) { return new Rectangle(Integer.parseInt(s[3]), Integer.parseInt(s[4]), Integer.parseInt(s[1]), Integer.parseInt(s[2])); } } else if (type == Insets.class) { if (s.length >= 5) { return new Insets(Integer.parseInt(s[1]), Integer.parseInt(s[2]), Integer.parseInt(s[4]), Integer.parseInt(s[4])); } } else if (type == Color.class) { if (s.length >= 5) { return new ColorUIResource( new Color(Integer.parseInt(s[1]), Integer.parseInt(s[2]), Integer.parseInt(s[3]), Integer.parseInt(s[4]))); } } else if (type.getSimpleName().contains("ArrayTable")) { return "ArrayTable!"; } throw new UnsupportedOperationException(type.toString()); } }
package org.appwork.utils.net.ftpserver; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; /** * @author daniel * */ public class FtpServer implements Runnable { private final FtpConnectionHandler<? extends FtpFile> handler; private final int port; private ServerSocket controlSocket; private Thread controlThread = null; private ThreadGroup threadGroup = null; private boolean localhostOnly = false; public FtpServer(final FtpConnectionHandler<? extends FtpFile> handler, final int port) { this.handler = handler; this.port = port; this.threadGroup = new ThreadGroup("FTPServer"); } /** * @return */ public FtpConnectionHandler<? extends FtpFile> getFtpCommandHandler() { return this.handler; } private InetAddress getLocalHost() { InetAddress localhost = null; try { localhost = InetAddress.getByName("127.0.0.1"); } catch (final UnknownHostException e1) { } if (localhost != null) { return localhost; } try { localhost = InetAddress.getByName(null); } catch (final UnknownHostException e1) { } return localhost; } /** * @return the clientThreadGroup */ protected ThreadGroup getThreadGroup() { return this.threadGroup; } /** * @return the localhostOnly */ public boolean isLocalhostOnly() { return this.localhostOnly; } public void run() { final Thread current = this.controlThread; final ServerSocket socket = this.controlSocket; try { while (true) { try { final Socket clientSocket = socket.accept(); /* TODO: handle max client connections here */ new FtpConnection(this, clientSocket); } catch (final IOException e) { break; } if (current == null || current.isInterrupted()) { break; } } } finally { try { socket.close(); } catch (final Throwable e) { } } } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ /** * @param localhostOnly * the localhostOnly to set */ public void setLocalhostOnly(final boolean localhostOnly) { this.localhostOnly = localhostOnly; } public synchronized void start() throws IOException { this.controlSocket = new ServerSocket(this.port); if (this.isLocalhostOnly()) { /* we only want localhost bound here */ final SocketAddress socketAddress = new InetSocketAddress(this.getLocalHost(), this.port); this.controlSocket.bind(socketAddress); } this.controlThread = new Thread(this.threadGroup, this); this.controlThread.setName("FtpServerThread"); this.controlThread.start(); } public synchronized void stop() { this.threadGroup.interrupt(); try { this.controlSocket.close(); } catch (final Throwable e) { } } }
package mr_kitten; import java.util.Random; import java.util.*; import java.io.*; /** * This class is the main class of the "World of Zuul" application. * "World of Zuul" is a very simple, text based adventure game. Users * can walk around some scenery. That's all. It should really be extended * to make it more interesting! * * To play this game, create an instance of this class and call the "play" * method. * * This main class creates and initialises all the others: it creates all * rooms, creates the parser and starts the game. It also evaluates and * executes the commands that the parser returns. * * @author Michael Kolling and David J. Barnes * @version 2006.03.30 */ public class Game { private Parser parser; private Room currentRoom; private Players MrKitten; private static ArrayList<Item> items; private static ArrayList<Characters> characters; /** * Create the game and initialise its internal map. */ public Game() { items = new ArrayList<Item>(); characters = new ArrayList<Characters>(); MrKitten = new Players("Mr.Kitten"); parser = new Parser(); createRooms(); createItems(); createCharacters(); } /** * Gettor to access list of items and list of characters * @return */ public static ArrayList<Item> getListItem(){ return items; } public static ArrayList<Characters> getListCharacters(){ return characters; } /** * Create all the rooms and link their exits together. */ private void createRooms() { //Declare rooms; Room kitchen,livingRoom,bedroom,street1,street2,sewer,petshop,theGreatDescent,dory,theFishPalace; Room tavernSanRicardo,starWars,theCloset,theEnd; kitchen = new Room ("are in the Kitchen of the Master's house","kitchen"); livingRoom = new Room ("are in the Living room of the Master's house","livingRoom"); bedroom = new Room ("are in the Bedroom of the Master's house","bedroom"); street1 = new Room ("are in the Street near the entrance of the house","street1"); street2 = new Room ("are in the Street near the Petshop","street2"); sewer = new Room ("are in the Sewer under the streets","sewer"); petshop = new Room ("are in the Petshop","petshop"); theGreatDescent = new Room ("are going deep down under water","theGreatDescent"); dory = new Room ("are with Dory the great fish","dory"); theFishPalace = new Room ("are in the Fish Palace","theFishPalace"); tavernSanRicardo = new Room ("are in the magnificient Tavern Of San Ricardo","tavernSanRicardo"); starWars = new Room ("are in a Galaxy far far away...","starWars"); theCloset = new Room ("are ready to fight with lions","theCloset"); theEnd = new Room ("did it, you did it, Yeah!","theEnd"); //Declare doors and items Door doorKLr = new Door(livingRoom,kitchen); kitchen.addExit("east", doorKLr); livingRoom.addExit("west",doorKLr); Door doorBLr = new Door (bedroom, livingRoom); livingRoom.addExit("east",doorBLr); bedroom.addExit("west",doorBLr); Item keyLivingStreet = new Item("home key", "this key opens the door to exit the master's house",0); LockedDoor doorS1Lr = new LockedDoor (keyLivingStreet, street1, livingRoom); livingRoom.addExit("south",doorS1Lr);street1.addExit("north",doorS1Lr); Door doorS2S1 = new Door (street2, street1);street1.addExit("east",doorS2S1); street2.addExit("west",doorS2S1); Door doorSS1 = new Door (sewer, street1);street1.addExit("down",doorSS1);sewer.addExit("up",doorSS1); Door doorPS2 = new Door (petshop, street2);street2.addExit("south",doorPS2);petshop.addExit("north",doorPS2); Door doorSS2 = new Door (sewer, street2);street2.addExit("down",doorSS2);sewer.addExit("up",doorSS2); Door doorGdP = new Door (theGreatDescent, petshop);petshop.addExit("down", doorGdP);theGreatDescent.addExit("up",doorGdP); Door doorDGd = new Door (dory, theGreatDescent);theGreatDescent.addExit("west",doorDGd); dory.addExit("east",doorDGd); Door doorFpGd = new Door (theFishPalace, theGreatDescent);theGreatDescent.addExit("down",doorFpGd);theFishPalace.addExit("up",doorFpGd); Item keyFishTavern = new Item ("blue key","This key opens the door between the fish palace and the San Ricardo tavern",0); LockedDoor doorFpTsr = new LockedDoor (keyFishTavern, theFishPalace, tavernSanRicardo);tavernSanRicardo.addExit("north", doorFpTsr); theFishPalace.addExit("south", doorFpTsr); Door doorSwTsr = new Door (starWars, tavernSanRicardo);tavernSanRicardo.addExit("up", doorSwTsr); starWars.addExit("down",doorSwTsr); Door doorCSw = new Door (theCloset,starWars);starWars.addExit("east",doorCSw);theCloset.addExit("west",doorCSw); Door doorEC = new Door (theEnd, theCloset);theCloset.addExit("south", doorEC); currentRoom = livingRoom; // start game in master's house } /* * Create all the items in the game */ private void createItems() { Item potionCareMin = new Item ("potionCareMin","This potion heals you for a small amount of your health",5); Item potionCareMax = new Item ("potionCareMax","This potion heals you for a big amount of your health",25); Item potionCareMean = new Item("potionCareMean","This potion heals you for a medium amount of your health",20); Item algea = new Item ("algea", "This algae has revitalizing properties. It can heal wounds and restore a medium amount of your health.", 10); //A COMPLETER Item potionBonus = new Item("potionBonus", "This potion heals you for a big amount of your health", 25); //A COMPLETER Item superBite = new Item ("superBite","It's sharp and ready to rip your opponents' heads off",10); Item superPiss = new Item ("superPiss","Wow it's dirty",8); Item puppyEyes = new Item ("puppy eyes", "Use this look to charm anyone", 13); Item laserTail = new Item ("laser tail", "May the catnip be with you, young Catawan.", 20); items.add(potionCareMin); items.add(potionCareMax); items.add(potionCareMean); items.add(algea); items.add(potionBonus); items.add(superBite); items.add(superPiss); items.add(puppyEyes); items.add(laserTail); Item keyLivingStreet = new Item("home key", "this key opens the door to exit the master's house",0); items.add(keyLivingStreet); Item keyFishTavern = new Item ("blue key","This key opens the door between the fish palace and the San Ricardo tavern",0); items.add(keyFishTavern); } /** * Create all characters in the game */ public void createCharacters() { Characters goldFish = new Characters("Gold Fish", 10, 3,"Blub blub blub blob. Please don't kill me.", "livingRoom"); Characters garfield = new Characters("Garfield", 30, 5,"...", "street1"); Characters strayCat = new Characters("strayCat", 20, 5,"...", "street2"); Characters splinter = new Characters("Splinter", 25, 15,"niark niark niark", "street2"); Characters dory = new Characters("Dory", 25, 5,"Blablablabla", "dory");//A COMPLETER Characters ratatouille = new Characters("Ratatouille", 20, 5,"Hello, young cat. I have heard of you. I think you could use some help in your quest." + "I can teach you something, and I hope you will make good use of it. I also hope that this action will unite the Cats and Rats race for a very long time." + "I have a dream that our txo races can live together peacefully.", "petshop"); Characters mrRobot = new Characters("Mr.Robot", 40, 25,"", "petshop"); Characters shark = new Characters("Sharks", 20, 10,"Look at that Bruce! A furry fish! We have to taste that. Prepare to die!", "theGreatDescent");//A COMPLETER Characters darkMoule = new Characters("Dark Moule", 35, 20, "Who do you think you are?!" + "You cannot prevail, you silly kitty..." + "I will crush you!", "theFishPalace"); Characters pussInBoots = new Characters("Puss in boots", 25, 15,"Hola, Senor Gato!" + "I see you come from the portal. It has been a long time since it has been used! By another cat that looks like yoy, by the way..." + "I have heard about your quest, and I want you to know that I support you!" + "Let me teach you something that could be of a great help, for this quest and for all your life...", "tavernSanRicardo"); Characters darkVador = new Characters("Dark Vador", 40, 25,"Shhhh...Shhhh...Are you a rebel? You look like a strange Ewok..." + "Anyway, no one can enter a colonized planet like this! I will execute you!", "star wars");//A COMPLETER Characters brother = new Characters("Brother", 50, 30,"So, here you are...brother. I have been waiting for you." + "Do not look so suprised! I am an Ancient Cat, just like you." + "When I first heard about the magical Guillotine, I knew I was the only one who could use it." + "And you, you want to take it, and spread power amongst these dumb kitties!" + "This would only lead us to chaos...But if you join me, we could rule the world, together!" + "You don't want to?... You are just like Mom and Dad, to blind and stupid to see what's right!" + "I will never let you take it!", "theEnd"); characters = new ArrayList<Characters>(); characters.add(goldFish); characters.add(garfield); characters.add(strayCat); characters.add(splinter); characters.add(dory); characters.add(ratatouille); characters.add(mrRobot); characters.add(shark); characters.add(darkMoule); characters.add(pussInBoots); characters.add(darkVador); characters.add(brother); } /** * Main play routine. Loops until end of play. */ public void play() { printWelcome(); // Enter the main command loop. Here we repeatedly read commands and // execute them until the game is over. boolean finished = false; while (! finished) { Command command = parser.getCommand(); finished = processCommand(command); } System.out.println("Thank you for playing. Good bye."); } /** * Print out the opening message for the player. */ private void printWelcome() { System.out.println(); System.out.println("Welcome to the World of Zuul!"); System.out.println("World of Zuul is a new, incredibly boring adventure game."); System.out.println("Type 'help' if you need help."); System.out.println(); System.out.println("You are " + currentRoom.getDescription()); currentRoom.printExits(); } /** * Given a command, process (that is: execute) the command. * @param command The command to be processed. * @return true If the command ends the game, false otherwise. */ private boolean processCommand(Command command) { boolean wantToQuit = false; if(command.isUnknown()) { System.out.println("I don't know what you mean..."); return false; } String commandWord = command.getCommandWord(); if(commandWord.equals("help")){ printHelp(); } else if(commandWord.equals("go")){ goRoom(command); } else if(commandWord.equals("quit")){ wantToQuit = quit(command); } else if(commandWord.equals("look")){ lookRoom(command); } else if(commandWord.equals("fight")){ fightPeople(); } else if(commandWord.equals("talk")){ talkRoomPeople(); } else if(commandWord.equals("explore")){ exploreRoom(); } else if(commandWord.equals("inventory")){ inventory(); } return wantToQuit; } // implementations of user commands: /** * Print out some help information. * Here we print some stupid, cryptic message and a list of the * command words. */ private void printHelp() { System.out.println("You are lost. You are alone. You wander"); System.out.println("around at the university."); System.out.println(); System.out.println("Your command words are:"); System.out.println(" go quit fight talk explore inventory help "); System.out.println("go + direction -- deplace in the map"); System.out.println("quit -- quit the game"); System.out.println("fight -- fight a characters"); System.out.println("explore -- explore the room and realize actions"); System.out.println("inventory -- print your inventory of item"); } /** * Try to go to one direction. If there is an exit, enter * the new room, otherwise print an error message. */ private void goRoom(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we don't know where to go... System.out.println("Go where?"); return; } String direction = command.getSecondWord(); // Try to leave current room. Door nextDoor = currentRoom.getNextRoom(direction); if (nextDoor instanceof LockedDoor){ LockedDoor l = (LockedDoor)nextDoor; l.openLockedDoor(MrKitten.getInventory(),currentRoom); Room nextRoom = nextDoor.getRoom(currentRoom); currentRoom = nextRoom; System.out.println("You " + currentRoom.getDescription()); currentRoom.printExits(); } else{ try{ Room nextRoom = nextDoor.getRoom(currentRoom); currentRoom = nextRoom; System.out.println("You " + currentRoom.getDescription()); currentRoom.printExits(); } catch (Exception e){ System.out.println("Wrong direction!"); System.out.println("You " + currentRoom.getDescription()); System.out.println("You can go :"); currentRoom.printExits(); } } } /** * "Quit" was entered. Check the rest of the command to see * whether we really quit the game. * @return true, if this command quits the game, false otherwise. */ private boolean quit(Command command) { if(command.hasSecondWord()) { System.out.println("Quit what?"); return false; } else { return true; // signal that we want to quit } } /* * You can look into the room to see the description of the room or to describe an item */ private void lookRoom(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we describe the current room System.out.println("You " + currentRoom.getDescription()); currentRoom.printExits(); } else { String itemName = command.getSecondWord(); Players.getItemDescription(itemName); } } /* * You can fight peoples in the current room */ private void fightPeople() { String ennemi = ""; int ennemiHP=0; int ennemiAD=0; boolean charactersFind = false; for (int i = 0;i<characters.size();i++){ Characters currentChar = characters.get(i); if (currentChar.getRoom().equals(currentRoom.getName())) { ennemi = currentChar.getName(); ennemiHP = currentChar.getEnnemiHP(); ennemiAD = currentChar.getEnnemiAD(); charactersFind = true; break; } } if (charactersFind == false) { System.out.println("There is no character in this room"); } else { if (ennemi.equals("mrRobot")){ Actors.mrRobotDialog(); } int MrKittenHP = MrKitten.getPlayerHP(); System.out.println("Mr Kitten VS "+ ennemi); while (MrKittenHP>0 && ennemiHP>0){ System.out.println(" ********* "); System.out.println("Mr.Kitten's HP = "+MrKittenHP); System.out.println(ennemi+"'s HP = "+ennemiHP); System.out.println(" ********* "); System.out.println (" What would you like ? "); System.out.println(" a - attack "); System.out.println(" b - special attack "); System.out.println(" c - items"); System.out.println(" Enter the character please :"); Scanner keyboard = new Scanner(System.in); String answer = keyboard.nextLine(); switch (answer){ case "a": { ennemiHP=attack(ennemiHP); };break; case "b": { ennemiHP=specialAttack(ennemiHP); };break; case "c": { MrKittenHP=itemsAttack(MrKittenHP); };break; default: System.out.println("what the hell did you just say? You are fighting, you take dommage"); break; } if(ennemiHP >0){ Random nbRd = new Random(); int nextnb = nbRd.nextInt(ennemiAD)+1; MrKittenHP = MrKittenHP - nextnb; } } if (ennemiHP <= 0){ System.out.println("You win !!! It remains "+MrKittenHP+" HP"); Players.setPlayerHP(MrKittenHP); }else { System.out.println("You loose !! GAME OVER !!"); System.exit(1); } } } /** * Reduce ennemi HP by a normal attack */ public int attack (int ennemiHP) { Random nbRd = new Random(); int nextnb = nbRd.nextInt(7)+1; ennemiHP = ennemiHP - nextnb; return ennemiHP; } /** * Choose a special attack */ private int specialAttack(int ennemiHP) { boolean specialAttack = false; System.out.println(" What would you like ? "); for (int i = 0;i<MrKitten.getInventory().size();i++){ Item currentItem = MrKitten.getInventory().get(i); if (currentItem.getName().equals("superPiss")){ System.out.println(" a - superPiss "); specialAttack = true; } if (currentItem.getName().equals("superBite")){ System.out.println(" b - superBite "); specialAttack = true; } if (currentItem.getName().equals("puppyEyes")){ System.out.println(" c - puppyEyes "); specialAttack = true; } if (currentItem.getName().equals("laserTail")){ System.out.println(" d - laserTail "); specialAttack = true; } } if(specialAttack == true){ System.out.println(" Enter the character please :"); Scanner keyboard = new Scanner(System.in); String answer = keyboard.nextLine(); switch (answer){ case "a": { ennemiHP=ennemiHP-15; };break; case "b": { ennemiHP=ennemiHP-20; };break; case "c": { ennemiHP=ennemiHP-25; };break; case "d": { ennemiHP=ennemiHP-30; };break; default: System.out.println("what the hell did you just say? You are fighting, you take dommage"); break; } }else { System.out.println("You have no special attack..."); } return ennemiHP; } /** * Chosse an items in your inventory */ private int itemsAttack(int playerHP) { boolean itemsAttack = false; System.out.println(" What would you like to add your HP ? "); for (int i = 0;i<MrKitten.getInventory().size();i++){ Item currentItem = MrKitten.getInventory().get(i); if (currentItem.getName().equals("potionCareMin")){ System.out.println(" a - potionCareMin (+30HP) "); itemsAttack = true; } if (currentItem.getName().equals("potionCareMax")){ System.out.println(" b - potionCareMax (+120HP)"); itemsAttack = true; } if (currentItem.getName().equals("potionCareMean")){ System.out.println(" c - potionCareMean (+60HP)"); itemsAttack = true; } if (currentItem.getName().equals("algea")){ System.out.println(" d - algea (+35HP)"); itemsAttack = true; } if (currentItem.getName().equals("potionBonus")){ System.out.println(" e - potionBonus (+100HP)"); itemsAttack = true; } } if(itemsAttack == true){ System.out.println(" Enter the character please :"); Scanner keyboard = new Scanner(System.in); String answer = keyboard.nextLine(); switch (answer){ case "a": { playerHP=playerHP+30; MrKitten.useItem("potionCareMin"); };break; case "b": { playerHP=playerHP+120; MrKitten.useItem("potionCareMax"); };break; case "c": { playerHP=playerHP+60; MrKitten.useItem("potionCareMean"); };break; case "d": { playerHP=playerHP+35; MrKitten.useItem("algea"); };break; case "e": { playerHP=playerHP+100; MrKitten.useItem("potionBonus"); };break; default: System.out.println("what the hell did you just say? You are fighting, you take dommage"); break; } if(playerHP >120){ playerHP = 120; } }else{ System.out.println("You have no items to care..."); } return playerHP; } private void talkRoomPeople(){ if (currentRoom.getName().equals("dory")){ System.out.println("DORY :"); Actors.doryDialogue();return; } else if (currentRoom.getName().equals("petshop")){ System.out.println("RED FISH :"); Actors.redFishDialog();return; } else { for (int i=0;i < characters.size();i++){ Characters currentChar = characters.get(i); if (currentChar.getRoom().equals(currentRoom.getName())){ System.out.println(currentChar.getName()+":"); System.out.println(currentChar.getTalk());return; } } } } private void exploreRoom(){ int MrKittenHP = MrKitten.getPlayerHP(); Scanner keyboard = new Scanner(System.in); switch(currentRoom.getName()){ case "livingRoom" : System.out.println("This couch is where the master always crashes... Let's do something!"); System.out.println("Destroy the couch?"); System.out.println("a - Yes he deserves it!"); System.out.println("b - No! I may be a little dizzy but I won't turn crazy today!"); System.out.println("Enter the character please :"); String answer = keyboard.nextLine(); if (answer.equals("a")){ System.out.println("You totaly nailed it! But you noticed that a key droped on the floor... What could it be?!"); MrKitten.grabItem("home key"); } else { System.out.println("Pussycat! Without some balls you won't go to any places!"); } try { Thread.sleep(2000); } catch (Exception e) { System.out.println("Bizarre que ça marche pas..."); } System.out.println("Need to do something else..."); System.out.println("Oh! A goldfish! Seems tasty..."); System.out.println("Eat it?"); System.out.println(" a - Yes!"); System.out.println(" b - With a bit of mayonnaise... What could happen?"); System.out.println("Enter the character: "); answer = keyboard.nextLine();//Not usefull since he doesn't really have any choice System.out.println("Hum... Yum!"); break; case "kitchen" :System.out.println ("Best place of the world for all cordon bleu. Their is always something to eat."); System.out.println("It's smelling cooking food ! The kitchen table is probably full of food." + "Do you want jump on the kitchen table ?" + "a - Oh god YES ! I'm hungry guys !" + "b - No, it's better on the kitchen cupboard"); String answer_kitchen = keyboard.nextLine(); if (answer_kitchen.equals("a")){ System.out.println("Oohh, you're sad :( Their is only the half salt butter but it work. You eat it and gain 25 hp !"); MrKittenHP =MrKittenHP +25; Players.setPlayerHP(MrKittenHP); } else { System.out.println("Jackpot ! A cooked fish is on this cupboard. You eat it and gain 50 hp !"); MrKittenHP =MrKittenHP +50; Players.setPlayerHP(MrKittenHP); } if(MrKittenHP >120){ MrKittenHP = 120; Players.setPlayerHP(MrKittenHP); } break; case "bedroom" : break; case "street1" : System.out.println("You look around you and see a big old cat on the street, coming toward you."); System.out.println("He looks friendly and comes near you."); System.out.println("You may want to talk to him"); System.out.println("There is also a garbage can over here, it smells delicious..."); System.out.println("What do you want to do?"); System.out.println("a - talk to the cat"); System.out.println("b - explore the garbage can"); answer = keyboard.nextLine(); if (answer.equals("a")){ Actors.garfieldDialog(); } else if (answer.equals("b")){ System.out.println("You found a healing potion! That might be useful..."); MrKitten.grabItem("potionCareMin"); } break; case "street2" : System.out.println("Here you are! Back in the light!"); System.out.println("There is another garbage can! Sounds like you are going to make a good deal again!"); System.out.println("do you want to explore the garbage can?"); System.out.println("a - yes"); System.out.println("b - no"); answer = keyboard.nextLine(); if (answer.equals("a")){ System.out.println("Uh-Oh! There is already someone in this garbage can!"); System.out.println("This stray cat doesn't look soft!"); fightPeople(); } else if (answer.equals("b")){ System.out.println("Let us hope you will not regret it..."); } break; case "sewer" : break; case "petshop" : break; case "theGreatDescent" : break; case "dory" : break; case "theFishPalace" : break; case "tavernSanRicardo" : break; case "starWars" : break; case "theCloset" : break; case "theEnd" : break; default : System.out.println("Just... how??"); break; } } private void inventory(){ MrKitten.printInventory(); } }
package com.intellij.openapi.actionSystem.impl; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.actionholder.ActionRef; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.ui.JBPopupMenu; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.StatusBar; import com.intellij.ui.ComponentUtil; import com.intellij.ui.components.JBMenu; import com.intellij.ui.mac.foundation.NSDefaults; import com.intellij.ui.plaf.beg.IdeaMenuUI; import com.intellij.util.ReflectionUtil; import com.intellij.util.SingleAlarm; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.AWTEventListener; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public final class ActionMenu extends JBMenu { private static final boolean KEEP_MENU_HIERARCHY = SystemInfo.isMacSystemMenu && Registry.is("keep.menu.hierarchy", false); private final String myPlace; private DataContext myContext; private final ActionRef<ActionGroup> myGroup; private final PresentationFactory myPresentationFactory; private final Presentation myPresentation; private boolean myMnemonicEnabled; private MenuItemSynchronizer myMenuItemSynchronizer; private StubItem myStubItem; // A PATCH!!! Do not remove this code, otherwise you will lose all keyboard navigation in JMenuBar. private final boolean myUseDarkIcons; private Disposable myDisposable; public ActionMenu(final DataContext context, @NotNull final String place, final ActionGroup group, final PresentationFactory presentationFactory, final boolean enableMnemonics, final boolean useDarkIcons ) { myContext = context; myPlace = place; myGroup = ActionRef.fromAction(group); myPresentationFactory = presentationFactory; myPresentation = myPresentationFactory.getPresentation(group); myMnemonicEnabled = enableMnemonics; myUseDarkIcons = useDarkIcons; updateUI(); init(); // addNotify won't be called for menus in MacOS system menu if (SystemInfo.isMacSystemMenu) { installSynchronizer(); } // Triggering initialization of private field "popupMenu" from JMenu with our own JBPopupMenu getPopupMenu(); } public void updateContext(DataContext context) { myContext = context; } public AnAction getAnAction() { return myGroup.getAction(); } @Override public void addNotify() { super.addNotify(); installSynchronizer(); } private void installSynchronizer() { if (myMenuItemSynchronizer == null) { myMenuItemSynchronizer = new MenuItemSynchronizer(); myGroup.getAction().addPropertyChangeListener(myMenuItemSynchronizer); myPresentation.addPropertyChangeListener(myMenuItemSynchronizer); } } @Override public void removeNotify() { uninstallSynchronizer(); super.removeNotify(); if (myDisposable != null) { Disposer.dispose(myDisposable); myDisposable = null; } } private void uninstallSynchronizer() { if (myMenuItemSynchronizer != null) { myGroup.getAction().removePropertyChangeListener(myMenuItemSynchronizer); myPresentation.removePropertyChangeListener(myMenuItemSynchronizer); myMenuItemSynchronizer = null; } } private JPopupMenu mySpecialMenu; @Override public JPopupMenu getPopupMenu() { if (mySpecialMenu == null) { mySpecialMenu = new JBPopupMenu(); mySpecialMenu.setInvoker(this); popupListener = createWinListener(mySpecialMenu); ReflectionUtil.setField(JMenu.class, this, JPopupMenu.class, "popupMenu", mySpecialMenu); } return super.getPopupMenu(); } @Override public void updateUI() { setUI(IdeaMenuUI.createUI(this)); setFont(UIUtil.getMenuFont()); JPopupMenu popupMenu = getPopupMenu(); if (popupMenu != null) { popupMenu.updateUI(); } } private void init() { boolean macSystemMenu = SystemInfo.isMacSystemMenu && myPlace.equals(ActionPlaces.MAIN_MENU); myStubItem = macSystemMenu ? null : new StubItem(); addStubItem(); addMenuListener(new MenuListenerImpl()); setBorderPainted(false); setVisible(myPresentation.isVisible()); setEnabled(myPresentation.isEnabled()); setText(myPresentation.getText()); updateIcon(); setMnemonicEnabled(myMnemonicEnabled); } private void addStubItem() { if (myStubItem != null) { add(myStubItem); } } public void setMnemonicEnabled(boolean enable) { myMnemonicEnabled = enable; setMnemonic(myPresentation.getMnemonic()); setDisplayedMnemonicIndex(myPresentation.getDisplayedMnemonicIndex()); } @Override public void setDisplayedMnemonicIndex(final int index) throws IllegalArgumentException { super.setDisplayedMnemonicIndex(myMnemonicEnabled ? index : -1); } @Override public void setMnemonic(int mnemonic) { super.setMnemonic(myMnemonicEnabled ? mnemonic : 0); } private void updateIcon() { UISettings settings = UISettings.getInstanceOrNull(); if (settings != null && settings.getShowIconsInMenus()) { final Presentation presentation = myPresentation; Icon icon = presentation.getIcon(); if (SystemInfo.isMacSystemMenu && ActionPlaces.MAIN_MENU.equals(myPlace) && icon != null) { // JDK can't paint correctly our HiDPI icons at the system menu bar icon = IconLoader.getMenuBarIcon(icon, myUseDarkIcons); } setIcon(icon); if (presentation.getDisabledIcon() != null) { setDisabledIcon(presentation.getDisabledIcon()); } else { setDisabledIcon(icon == null ? null : IconLoader.getDisabledIcon(icon)); } } } @Override public void menuSelectionChanged(boolean isIncluded) { super.menuSelectionChanged(isIncluded); showDescriptionInStatusBar(isIncluded, this, myPresentation.getDescription()); } public static void showDescriptionInStatusBar(boolean isIncluded, Component component, String description) { IdeFrame frame = (IdeFrame)(component instanceof IdeFrame ? component : SwingUtilities.getAncestorOfClass(IdeFrame.class, component)); StatusBar statusBar; if (frame != null && (statusBar = frame.getStatusBar()) != null) { statusBar.setInfo(isIncluded ? description : null); } } private class MenuListenerImpl implements MenuListener { boolean myIsHidden = false; @Override public void menuCanceled(MenuEvent e) { onMenuHidden(); } @Override public void menuDeselected(MenuEvent e) { if (myDisposable != null) { Disposer.dispose(myDisposable); myDisposable = null; } onMenuHidden(); } private void onMenuHidden() { if (KEEP_MENU_HIERARCHY) { return; } Runnable clearSelf = () -> { clearItems(); addStubItem(); }; if (SystemInfo.isMacSystemMenu && myPlace.equals(ActionPlaces.MAIN_MENU)) { // Menu items may contain mnemonic and they can affect key-event dispatching (when Alt pressed) // To avoid influence of mnemonic it's necessary to clear items when menu was hidden. // When user selects item of system menu (under MacOs) AppKit generates such sequence: CloseParentMenu -> PerformItemAction // So we can destroy menu-item before item's action performed, and because of that action will not be executed. // Defer clearing to avoid this problem. Disposable listenerHolder = Disposer.newDisposable(); Disposer.register(ApplicationManager.getApplication(), listenerHolder); IdeEventQueue.getInstance().addDispatcher(e -> { if (e instanceof KeyEvent) { if (myIsHidden) { clearSelf.run(); } ApplicationManager.getApplication().invokeLater(() -> Disposer.dispose(listenerHolder)); } return false; }, listenerHolder); myIsHidden = true; } else { clearSelf.run(); } } @Override public void menuSelected(MenuEvent e) { UsabilityHelper helper = new UsabilityHelper(ActionMenu.this); if (myDisposable == null) { myDisposable = Disposer.newDisposable(); } Disposer.register(myDisposable, helper); if (KEEP_MENU_HIERARCHY || myIsHidden) { clearItems(); } myIsHidden = false; fillMenu(); } } public void clearItems() { if (SystemInfo.isMacSystemMenu && myPlace.equals(ActionPlaces.MAIN_MENU)) { for (Component menuComponent : getMenuComponents()) { if (menuComponent instanceof ActionMenu) { ((ActionMenu)menuComponent).clearItems(); // hideNotify is not called on Macs ((ActionMenu)menuComponent).uninstallSynchronizer(); } else if (menuComponent instanceof ActionMenuItem) { // Looks like an old-fashioned ugly workaround // JDK 1.7 on Mac works wrong with such functional keys if (!SystemInfo.isMac) { ((ActionMenuItem)menuComponent).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F24, 0)); } } } } removeAll(); validate(); } public void fillMenu() { DataContext context; if (myContext != null) { context = myContext; } else { DataManager dataManager = DataManager.getInstance(); @SuppressWarnings("deprecation") DataContext contextFromFocus = dataManager.getDataContext(); context = contextFromFocus; if (PlatformDataKeys.CONTEXT_COMPONENT.getData(context) == null) { IdeFrame frame = ComponentUtil.getParentOfType((Class<? extends IdeFrame>)IdeFrame.class, (Component)this); context = dataManager.getDataContext(IdeFocusManager.getGlobalInstance().getLastFocusedFor((Window)frame)); } } final boolean isDarkMenu = SystemInfo.isMacSystemMenu && NSDefaults.isDarkMenuBar(); Utils.fillMenu(myGroup.getAction(), this, myMnemonicEnabled, myPresentationFactory, context, myPlace, true, LaterInvocator.isInModalContext(), isDarkMenu); } private class MenuItemSynchronizer implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if (Presentation.PROP_VISIBLE.equals(name)) { setVisible(myPresentation.isVisible()); if (SystemInfo.isMacSystemMenu && myPlace.equals(ActionPlaces.MAIN_MENU)) { validate(); } } else if (Presentation.PROP_ENABLED.equals(name)) { setEnabled(myPresentation.isEnabled()); } else if (Presentation.PROP_MNEMONIC_KEY.equals(name)) { setMnemonic(myPresentation.getMnemonic()); } else if (Presentation.PROP_MNEMONIC_INDEX.equals(name)) { setDisplayedMnemonicIndex(myPresentation.getDisplayedMnemonicIndex()); } else if (Presentation.PROP_TEXT.equals(name)) { setText(myPresentation.getText()); } else if (Presentation.PROP_ICON.equals(name) || Presentation.PROP_DISABLED_ICON.equals(name)) { updateIcon(); } } } private static class UsabilityHelper implements IdeEventQueue.EventDispatcher, AWTEventListener, Disposable { private Component myComponent; private Point myLastMousePoint; private Point myUpperTargetPoint; private Point myLowerTargetPoint; private SingleAlarm myCallbackAlarm; private MouseEvent myEventToRedispatch; private long myLastEventTime = 0L; private boolean myInBounds = false; private SingleAlarm myCheckAlarm; private UsabilityHelper(Component component) { myCallbackAlarm = new SingleAlarm(() -> { Disposer.dispose(myCallbackAlarm); myCallbackAlarm = null; if (myEventToRedispatch != null) { IdeEventQueue.getInstance().dispatchEvent(myEventToRedispatch); } }, 50, ModalityState.any(), this); myCheckAlarm = new SingleAlarm(() -> { if (myLastEventTime > 0 && System.currentTimeMillis() - myLastEventTime > 1500) { if (!myInBounds && myCallbackAlarm != null && !myCallbackAlarm.isDisposed()) { myCallbackAlarm.request(); } } myCheckAlarm.request(); }, 100, ModalityState.any(), this); myComponent = component; PointerInfo info = MouseInfo.getPointerInfo(); myLastMousePoint = info != null ? info.getLocation() : null; if (myLastMousePoint != null) { Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.COMPONENT_EVENT_MASK); IdeEventQueue.getInstance().addDispatcher(this, this); } } @Override public void eventDispatched(AWTEvent event) { if (event instanceof ComponentEvent) { ComponentEvent componentEvent = (ComponentEvent)event; Component component = componentEvent.getComponent(); JPopupMenu popup = ComponentUtil.getParentOfType((Class<? extends JPopupMenu>)JPopupMenu.class, component); if (popup != null && popup.getInvoker() == myComponent && popup.isShowing()) { Rectangle bounds = popup.getBounds(); if (bounds.isEmpty()) return; bounds.setLocation(popup.getLocationOnScreen()); if (myLastMousePoint.x < bounds.x) { myUpperTargetPoint = new Point(bounds.x, bounds.y); myLowerTargetPoint = new Point(bounds.x, bounds.y + bounds.height); } if (myLastMousePoint.x > bounds.x + bounds.width) { myUpperTargetPoint = new Point(bounds.x + bounds.width, bounds.y); myLowerTargetPoint = new Point(bounds.x + bounds.width, bounds.y + bounds.height); } } } } @Override public boolean dispatch(@NotNull AWTEvent e) { if (e instanceof MouseEvent && myUpperTargetPoint != null && myLowerTargetPoint != null && myCallbackAlarm != null) { if (e.getID() == MouseEvent.MOUSE_PRESSED || e.getID() == MouseEvent.MOUSE_RELEASED || e.getID() == MouseEvent.MOUSE_CLICKED) { return false; } Point point = ((MouseEvent)e).getLocationOnScreen(); Rectangle bounds = myComponent.getBounds(); bounds.setLocation(myComponent.getLocationOnScreen()); myInBounds = bounds.contains(point); boolean isMouseMovingTowardsSubmenu = myInBounds || new Polygon( new int[]{myLastMousePoint.x, myUpperTargetPoint.x, myLowerTargetPoint.x}, new int[]{myLastMousePoint.y, myUpperTargetPoint.y, myLowerTargetPoint.y}, 3).contains(point); myEventToRedispatch = (MouseEvent)e; myLastEventTime = System.currentTimeMillis(); if (!isMouseMovingTowardsSubmenu) { myCallbackAlarm.request(); } else { myCallbackAlarm.cancel(); } myLastMousePoint = point; return true; } return false; } @Override public void dispose() { myComponent = null; myEventToRedispatch = null; myLastMousePoint = myUpperTargetPoint = myLowerTargetPoint = null; Toolkit.getDefaultToolkit().removeAWTEventListener(this); } } }
package org.broad.igv.util; import org.apache.log4j.Logger; import org.broad.igv.PreferenceManager; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.ftp.FTPClient; import org.broad.igv.util.ftp.FTPStream; import org.broad.igv.util.ftp.FTPUtils; import sun.misc.BASE64Encoder; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.awt.*; import java.io.*; import java.net.*; import java.util.HashSet; import java.util.Map; /** * Notes -- 401 => client authentication, 407 => proxy authentication, 403 => forbidden * * @author Jim Robinson * @date 9/22/11 */ public class HttpURLConnectionUtils extends HttpUtils { private static Logger log = Logger.getLogger(IGVHttpClientUtils.class); private static ProxySettings proxySettings = null; private static HttpURLConnectionUtils instance; static { synchronized (HttpURLConnectionUtils.class) { instance = new HttpURLConnectionUtils(); } } public static HttpURLConnectionUtils getInstance() { return instance; } private HttpURLConnectionUtils() { Authenticator.setDefault(new IGVAuthenticator()); } /** * Code for disabling SSL certification */ private void disableCertificateValidation() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } } public void shutdown() { //To change body of implemented methods use File | Settings | File Templates. } /** * Return the contents of the url as a String. This method should only be used for queries expected to return * a small amount of data. * * @param url * @return */ public String getContentsAsString(URL url) throws IOException { return openConnection(url, null).getContent().toString(); } public InputStream openConnectionStream(URL url) throws IOException { if (url.getProtocol().toUpperCase().equals("FTP")) { String userInfo = url.getUserInfo(); String host = url.getHost(); String file = url.getPath(); FTPClient ftp = FTPUtils.connect(host, userInfo); ftp.pasv(); ftp.retr(file); return new FTPStream(ftp); } else { return openConnectionStream(url, null); } } public InputStream openConnectionStream(URL url, boolean abortOnClose) throws IOException { return openConnection(url, null).getInputStream(); } public InputStream openConnectionStream(URL url, Map<String, String> requestProperties) throws IOException { HttpURLConnection conn = openConnection(url, requestProperties); return conn.getInputStream(); } public InputStream openConnectionStream(URL url, boolean abortOnClose, Map<String, String> requestProperties) throws IOException { HttpURLConnection conn = openConnection(url, requestProperties); return conn.getInputStream(); } public boolean resourceAvailable(URL url) { try { HttpURLConnection conn = openConnection(url, null, "HEAD"); int code = conn.getResponseCode(); return code == 200; } catch (IOException e) { return false; } } public String getHeaderField(URL url, String key) throws IOException { HttpURLConnection conn = openConnection(url, null, "HEAD"); int code = conn.getResponseCode(); // TODO -- check code return conn.getHeaderField(key); } public long getContentLength(URL url) throws IOException { String contentLengthString = ""; contentLengthString = getHeaderField(url, "Content-Length"); if (contentLengthString == null) { return -1; } else { return Long.parseLong(contentLengthString); } } public void updateProxySettings() { boolean useProxy; String proxyHost; int proxyPort = -1; boolean auth = false; String user = null; String pw = null; PreferenceManager prefMgr = PreferenceManager.getInstance(); useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY); proxyHost = prefMgr.get(PreferenceManager.PROXY_HOST, null); try { proxyPort = Integer.parseInt(prefMgr.get(PreferenceManager.PROXY_PORT, "-1")); } catch (NumberFormatException e) { proxyPort = -1; } auth = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE); user = prefMgr.get(PreferenceManager.PROXY_USER, null); String pwString = prefMgr.get(PreferenceManager.PROXY_PW, null); if (pwString != null) { pw = Utilities.base64Decode(pwString); } proxySettings = new ProxySettings(useProxy, user, pw, auth, proxyHost, proxyPort); } public boolean downloadFile(String url, File outputFile) throws IOException { log.info("Downloading " + url + " to " + outputFile.getAbsolutePath()); HttpURLConnection conn = openConnection(new URL(url), null); int code = conn.getResponseCode(); // TODO -- check code long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } log.info("Content length = " + contentLength); InputStream is = null; OutputStream out = null; try { is = conn.getInputStream(); out = new FileOutputStream(outputFile); byte[] buf = new byte[64 * 1024]; int downloaded = 0; int bytesRead = 0; while ((bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); downloaded += bytesRead; } log.info("Download complete. Total bytes downloaded = " + downloaded); } finally { if (is != null) is.close(); if (out != null) { out.flush(); out.close(); } } long fileLength = outputFile.length(); return contentLength <= 0 || contentLength == fileLength; } @Override public void uploadFile(URI uri, File localFile, Map<String, String> headers) { //To change body of implemented methods use File | Settings | File Templates. } @Override public String createDirectory(URL url, String body) { return null; //To change body of implemented methods use File | Settings | File Templates. } private static HttpURLConnection openConnection(URL url, Map<String, String> requestProperties) throws IOException { return openConnection(url, requestProperties, "GET"); } private static HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method) throws IOException { boolean useProxy = proxySettings != null && proxySettings.useProxy && proxySettings.proxyHost != null && proxySettings.proxyPort > 0; HttpURLConnection conn = null; if (useProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = (new BASE64Encoder()).encode(bytes); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } conn.setConnectTimeout(10000); conn.setReadTimeout(60000); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "close"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } return conn; } public static class ProxySettings { boolean auth = false; String user; String pw; boolean useProxy; String proxyHost; int proxyPort = -1; public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort) { this.auth = auth; this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.pw = pw; this.useProxy = useProxy; this.user = user; } } public static class IGVAuthenticator extends Authenticator { @Override protected PasswordAuthentication getPasswordAuthentication() { Authenticator.RequestorType type = getRequestorType(); URL url = this.getRequestingURL(); boolean isProxyChallenge = type == RequestorType.PROXY; if (isProxyChallenge) { if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { return new PasswordAuthentication(proxySettings.user, proxySettings.pw.toCharArray()); } } Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null; LoginDialog dlg = new LoginDialog(owner, false, url.toString(), isProxyChallenge); dlg.setVisible(true); if (dlg.isCanceled()) { return null; } else { final String userString = dlg.getUsername(); final char[] userPass = dlg.getPassword(); if(isProxyChallenge) { proxySettings.user = userString; proxySettings.pw = new String(userPass); } return new PasswordAuthentication(userString, userPass); } } } }
package org.exist.xquery.value; import java.text.Collator; import org.exist.util.Collations; import org.exist.xquery.Constants; import org.exist.xquery.XPathException; /** * @author Wolfgang Meier (wolfgang@exist-db.org) */ public class UntypedAtomicValue extends AtomicValue { private String value; public UntypedAtomicValue(String value) { this.value = value; } /* (non-Javadoc) * @see org.exist.xquery.value.AtomicValue#getType() */ public int getType() { return Type.ATOMIC; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getStringValue() */ public String getStringValue() throws XPathException { return value; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#convertTo(int) */ public AtomicValue convertTo(int requiredType) throws XPathException { switch (requiredType) { case Type.ATOMIC : case Type.ITEM : return this; case Type.STRING : return new StringValue(value); case Type.ANY_URI : return new AnyURIValue(value); case Type.BOOLEAN : if (value.equals("0")) return BooleanValue.FALSE; else if (value.equals("1")) return BooleanValue.TRUE; else if (value.equals("false")) return BooleanValue.FALSE; else if (value.equals("true")) return BooleanValue.TRUE; else throw new XPathException( "Cannot cast 'xdt:UntypeAtomic(" + value + ")' to '" + Type.getTypeName(requiredType) + "' [err:FORG0001]"); case Type.FLOAT : return new FloatValue(value); case Type.DOUBLE : return new DoubleValue(this); case Type.NUMBER : //TODO : more complicated return new DoubleValue(this); case Type.DECIMAL : return new DecimalValue(value); case Type.INTEGER : case Type.NON_POSITIVE_INTEGER : case Type.NEGATIVE_INTEGER : case Type.LONG : case Type.INT : case Type.SHORT : case Type.BYTE : case Type.NON_NEGATIVE_INTEGER : case Type.UNSIGNED_LONG : case Type.UNSIGNED_INT : case Type.UNSIGNED_SHORT : case Type.UNSIGNED_BYTE : return new IntegerValue(value, requiredType); case Type.DATE_TIME : return new DateTimeValue(value); case Type.TIME : return new TimeValue(value); case Type.DATE : return new DateValue(value); case Type.DURATION : return new DurationValue(value); case Type.YEAR_MONTH_DURATION : YearMonthDurationValue rawYMDV = new YearMonthDurationValue(value); return new YearMonthDurationValue(rawYMDV.getCanonicalDuration()); case Type.DAY_TIME_DURATION : DayTimeDurationValue rawDTDV = new DayTimeDurationValue(value); return new DayTimeDurationValue(rawDTDV.getCanonicalDuration()); default : throw new XPathException( "FORG0001: cannot cast 'xdt:UntypeAtomic(" + value + ")' to '" + Type.getTypeName(requiredType) + "'"); } } /* (non-Javadoc) * @see org.exist.xquery.value.AtomicValue#compareTo(int, org.exist.xquery.value.AtomicValue) */ public boolean compareTo(Collator collator, int operator, AtomicValue other) throws XPathException { if (Type.subTypeOf(other.getType(), Type.STRING) || Type.subTypeOf(other.getType(), Type.UNTYPED_ATOMIC)) { int cmp = Collations.compare(collator, value, other.getStringValue()); switch (operator) { case Constants.EQ : return cmp == 0; case Constants.NEQ : return cmp != 0; case Constants.LT : return cmp < 0; case Constants.LTEQ : return cmp <= 0; case Constants.GT : return cmp > 0; case Constants.GTEQ : return cmp >= 0; default : throw new XPathException("Type error: cannot apply operand to string value"); } } throw new XPathException( "Type error: operands are not comparable; expected xdt:untypedAtomic; got " + Type.getTypeName(other.getType())); } /* (non-Javadoc) * @see org.exist.xquery.value.AtomicValue#compareTo(org.exist.xquery.value.AtomicValue) */ public int compareTo(Collator collator, AtomicValue other) throws XPathException { return Collations.compare(collator, value, other.getStringValue()); } /* (non-Javadoc) * @see org.exist.xquery.value.AtomicValue#max(org.exist.xquery.value.AtomicValue) */ public AtomicValue max(Collator collator, AtomicValue other) throws XPathException { if (Type.subTypeOf(other.getType(), Type.UNTYPED_ATOMIC)) return Collations.compare(collator, value, ((UntypedAtomicValue) other).value) > 0 ? this : other; else return Collations.compare(collator, value, other.getStringValue()) > 0 ? this : other; } /* (non-Javadoc) * @see org.exist.xquery.value.AtomicValue#min(org.exist.xquery.value.AtomicValue) */ public AtomicValue min(Collator collator, AtomicValue other) throws XPathException { if (Type.subTypeOf(other.getType(), Type.UNTYPED_ATOMIC)) return Collations.compare(collator, value, ((UntypedAtomicValue) other).value) < 0 ? this : other; else return Collations.compare(collator, value, other.getStringValue()) < 0 ? this : other; } /* (non-Javadoc) * @see org.exist.xquery.value.Item#conversionPreference(java.lang.Class) */ public int conversionPreference(Class javaClass) { if (javaClass.isAssignableFrom(StringValue.class)) return 0; if (javaClass == String.class || javaClass == CharSequence.class) return 1; if (javaClass == Character.class || javaClass == char.class) return 2; if (javaClass == Double.class || javaClass == double.class) return 10; if (javaClass == Float.class || javaClass == float.class) return 11; if (javaClass == Long.class || javaClass == long.class) return 12; if (javaClass == Integer.class || javaClass == int.class) return 13; if (javaClass == Short.class || javaClass == short.class) return 14; if (javaClass == Byte.class || javaClass == byte.class) return 15; if (javaClass == Boolean.class || javaClass == boolean.class) return 16; if (javaClass == Object.class) return 20; return Integer.MAX_VALUE; } /* (non-Javadoc) * @see org.exist.xquery.value.Item#toJavaObject(java.lang.Class) */ public Object toJavaObject(Class target) throws XPathException { if (target.isAssignableFrom(UntypedAtomicValue.class)) return this; else if ( target == Object.class || target == String.class || target == CharSequence.class) return value; else if (target == double.class || target == Double.class) { DoubleValue v = (DoubleValue) convertTo(Type.DOUBLE); return new Double(v.getValue()); } else if (target == float.class || target == Float.class) { FloatValue v = (FloatValue) convertTo(Type.FLOAT); return new Float(v.value); } else if (target == long.class || target == Long.class) { IntegerValue v = (IntegerValue) convertTo(Type.LONG); return new Long(v.getInt()); } else if (target == int.class || target == Integer.class) { IntegerValue v = (IntegerValue) convertTo(Type.INT); return new Integer(v.getInt()); } else if (target == short.class || target == Short.class) { IntegerValue v = (IntegerValue) convertTo(Type.SHORT); return new Short((short) v.getInt()); } else if (target == byte.class || target == Byte.class) { IntegerValue v = (IntegerValue) convertTo(Type.BYTE); return new Byte((byte) v.getInt()); } else if (target == boolean.class || target == Boolean.class) { return Boolean.valueOf(effectiveBooleanValue()); } else if (target == char.class || target == Character.class) { if (value.length() > 1 || value.length() == 0) throw new XPathException("cannot convert string with length = 0 or length > 1 to Java character"); return new Character(value.charAt(0)); } throw new XPathException( "cannot convert value of type " + Type.getTypeName(getType()) + " to Java object of type " + target.getName()); } }
package com.intellij.openapi.editor.impl; import com.intellij.diagnostic.Dumpable; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.FoldingListener; import com.intellij.openapi.editor.ex.FoldingModelEx; import com.intellij.openapi.editor.ex.PrioritizedInternalDocumentListener; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.ModificationTracker; import com.intellij.util.DocumentUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.awt.*; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicLong; public class FoldingModelImpl implements FoldingModelEx, PrioritizedInternalDocumentListener, Dumpable, ModificationTracker { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.EditorFoldingModelImpl"); public static final Key<Boolean> SELECT_REGION_ON_CARET_NEARBY = Key.create("select.region.on.caret.nearby"); private static final Key<SavedCaretPosition> SAVED_CARET_POSITION = Key.create("saved.position.before.folding"); private static final Key<Boolean> MARK_FOR_UPDATE = Key.create("marked.for.position.update"); private final List<FoldingListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private boolean myIsFoldingEnabled; private final EditorImpl myEditor; private final RangeMarkerTree<FoldRegionImpl> myRegionTree; private final FoldRegionsTree myFoldTree; private TextAttributes myFoldTextAttributes; private boolean myIsBatchFoldingProcessing; private boolean myDoNotCollapseCaret; private boolean myFoldRegionsProcessed; private int mySavedCaretShift; private final MultiMap<FoldingGroup, FoldRegion> myGroups = new MultiMap<>(); private boolean myDocumentChangeProcessed = true; private final AtomicLong myExpansionCounter = new AtomicLong(); FoldingModelImpl(@NotNull EditorImpl editor) { myEditor = editor; myIsFoldingEnabled = true; myIsBatchFoldingProcessing = false; myDoNotCollapseCaret = false; myRegionTree = new RangeMarkerTree<FoldRegionImpl>(editor.getDocument()) { @NotNull @Override protected RMNode<FoldRegionImpl> createNewNode(@NotNull FoldRegionImpl key, int start, int end, boolean greedyToLeft, boolean greedyToRight, boolean stickingToRight, int layer) { return new RMNode<FoldRegionImpl>(this, key, start, end, greedyToLeft, greedyToRight, stickingToRight) { @Override protected Getter<FoldRegionImpl> createGetter(@NotNull FoldRegionImpl region) { // Fold region shouldn't disappear even if no one holds a reference to it, so folding tree needs a strong reference to a region return region; } }; } }; myFoldTree = new FoldRegionsTree(myRegionTree) { @Override protected boolean isFoldingEnabled() { return FoldingModelImpl.this.isFoldingEnabled(); } }; myFoldRegionsProcessed = false; refreshSettings(); } @Override @NotNull public List<FoldRegion> getGroupedRegions(@NotNull FoldingGroup group) { return (List<FoldRegion>)myGroups.get(group); } @Override public void clearDocumentRangesModificationStatus() { assertIsDispatchThreadForEditor(); myFoldTree.clearDocumentRangesModificationStatus(); } @Override public boolean hasDocumentRegionChangedFor(@NotNull FoldRegion region) { assertReadAccess(); return region instanceof FoldRegionImpl && ((FoldRegionImpl)region).hasDocumentRegionChanged(); } @NotNull FoldRegion getFirstRegion(@NotNull FoldingGroup group, @NotNull FoldRegion child) { final List<FoldRegion> regions = getGroupedRegions(group); if (regions.isEmpty()) { final boolean inAll = Arrays.asList(getAllFoldRegions()).contains(child); throw new AssertionError("Folding group without children; the known child is in all: " + inAll); } FoldRegion main = regions.get(0); for (int i = 1; i < regions.size(); i++) { FoldRegion region = regions.get(i); if (main.getStartOffset() > region.getStartOffset()) { main = region; } } return main; } public int getEndOffset(@NotNull FoldingGroup group) { final List<FoldRegion> regions = getGroupedRegions(group); int endOffset = 0; for (FoldRegion region : regions) { if (region.isValid()) { endOffset = Math.max(endOffset, region.getEndOffset()); } } return endOffset; } void refreshSettings() { myFoldTextAttributes = myEditor.getColorsScheme().getAttributes(EditorColors.FOLDED_TEXT_ATTRIBUTES); } @Override public boolean isFoldingEnabled() { return myIsFoldingEnabled; } @Override public boolean isOffsetCollapsed(int offset) { assertReadAccess(); return getCollapsedRegionAtOffset(offset) != null; } private boolean isOffsetInsideCollapsedRegion(int offset) { assertReadAccess(); FoldRegion region = getCollapsedRegionAtOffset(offset); return region != null && region.getStartOffset() < offset; } private static void assertIsDispatchThreadForEditor() { ApplicationManager.getApplication().assertIsDispatchThread(); } private static void assertReadAccess() { ApplicationManager.getApplication().assertReadAccessAllowed(); } private static void assertOurRegion(FoldRegion region) { if (!(region instanceof FoldRegionImpl)) { throw new IllegalArgumentException("Only regions created by this instance of FoldingModel are accepted"); } } @Override public void setFoldingEnabled(boolean isEnabled) { assertIsDispatchThreadForEditor(); myIsFoldingEnabled = isEnabled; } @Override public FoldRegion addFoldRegion(int startOffset, int endOffset, @NotNull String placeholderText) { return createFoldRegion(startOffset, endOffset, placeholderText, null, false); } private boolean checkIfValid(@NotNull final FoldRegion region) { assertIsDispatchThreadForEditor(); assertOurRegion(region); if (!isFoldingEnabled()) { return false; } if (!myIsBatchFoldingProcessing) { LOG.error("Fold regions must be added or removed inside batchFoldProcessing() only."); return false; } return region.isValid() && !DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), region.getStartOffset()) && !DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), region.getEndOffset()); } @Override public void runBatchFoldingOperation(@NotNull Runnable operation) { runBatchFoldingOperation(operation, false, true); } @Override public void runBatchFoldingOperation(@NotNull Runnable operation, boolean moveCaret) { runBatchFoldingOperation(operation, false, moveCaret); } private void runBatchFoldingOperation(@NotNull Runnable operation, final boolean dontCollapseCaret, final boolean moveCaret) { assertIsDispatchThreadForEditor(); boolean oldDontCollapseCaret = myDoNotCollapseCaret; myDoNotCollapseCaret |= dontCollapseCaret; boolean oldBatchFlag = myIsBatchFoldingProcessing; if (!oldBatchFlag) { ((ScrollingModelImpl)myEditor.getScrollingModel()).finishAnimation(); mySavedCaretShift = myEditor.visibleLineToY(myEditor.getCaretModel().getVisualPosition().line) - myEditor.getScrollingModel().getVerticalScrollOffset(); } myIsBatchFoldingProcessing = true; try { operation.run(); } finally { if (!oldBatchFlag) { myIsBatchFoldingProcessing = false; if (myFoldRegionsProcessed) { notifyBatchFoldingProcessingDone(moveCaret); myFoldRegionsProcessed = false; } } myDoNotCollapseCaret = oldDontCollapseCaret; } } @Override public void runBatchFoldingOperationDoNotCollapseCaret(@NotNull final Runnable operation) { runBatchFoldingOperation(operation, true, true); } /** * Disables caret position adjustment after batch folding operation is finished. * Should be called from inside batch operation runnable. */ void flushCaretShift() { mySavedCaretShift = -1; } @Override @NotNull public FoldRegion[] getAllFoldRegions() { assertReadAccess(); return myFoldTree.fetchAllRegions(); } @Override @Nullable public FoldRegion getCollapsedRegionAtOffset(int offset) { return myFoldTree.fetchOutermost(offset); } @Nullable @Override public FoldRegion getFoldRegion(int startOffset, int endOffset) { assertReadAccess(); return myFoldTree.getRegionAt(startOffset, endOffset); } @Override @Nullable public FoldRegion getFoldingPlaceholderAt(@NotNull Point p) { assertReadAccess(); LogicalPosition pos = myEditor.xyToLogicalPosition(p); int line = pos.line; if (line >= myEditor.getDocument().getLineCount()) return null; int offset = myEditor.logicalPositionToOffset(pos); return myFoldTree.fetchOutermost(offset); } @Override public void removeFoldRegion(@NotNull final FoldRegion region) { assertIsDispatchThreadForEditor(); assertOurRegion(region); if (!myIsBatchFoldingProcessing) { LOG.error("Fold regions must be added or removed inside batchFoldProcessing() only."); } ((FoldRegionImpl)region).setExpanded(true, false); notifyListenersOnFoldRegionStateChange(region); notifyListenersOnFoldRegionRemove(region); myFoldRegionsProcessed = true; region.dispose(); } void removeRegionFromTree(@NotNull FoldRegionImpl region) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!myEditor.getFoldingModel().isInBatchFoldingOperation()) { LOG.error("Fold regions must be added or removed inside batchFoldProcessing() only."); } myFoldRegionsProcessed = true; myRegionTree.removeInterval(region); removeRegionFromGroup(region); } void removeRegionFromGroup(@NotNull FoldRegion region) { myGroups.remove(region.getGroup(), region); } public void dispose() { doClearFoldRegions(); myRegionTree.dispose(); } @Override public void clearFoldRegions() { if (!myIsBatchFoldingProcessing) { LOG.error("Fold regions must be added or removed inside batchFoldProcessing() only."); return; } FoldRegion[] regions = getAllFoldRegions(); for (FoldRegion region : regions) { if (!region.isExpanded()) notifyListenersOnFoldRegionStateChange(region); notifyListenersOnFoldRegionRemove(region); region.dispose(); } doClearFoldRegions(); } private void doClearFoldRegions() { myGroups.clear(); myFoldTree.clear(); } void expandFoldRegion(@NotNull FoldRegion region, boolean notify) { assertIsDispatchThreadForEditor(); if (region.isExpanded() || region.shouldNeverExpand()) return; if (!myIsBatchFoldingProcessing) { LOG.error("Fold regions must be collapsed or expanded inside batchFoldProcessing() only."); } for (Caret caret : myEditor.getCaretModel().getAllCarets()) { SavedCaretPosition savedPosition = caret.getUserData(SAVED_CARET_POSITION); if (savedPosition != null && savedPosition.isUpToDate(myEditor)) { int savedOffset = myEditor.logicalPositionToOffset(savedPosition.position); FoldRegion[] allCollapsed = myFoldTree.fetchCollapsedAt(savedOffset); if (allCollapsed.length == 1 && allCollapsed[0] == region) { caret.putUserData(MARK_FOR_UPDATE, Boolean.TRUE); } } } myFoldRegionsProcessed = true; myExpansionCounter.incrementAndGet(); ((FoldRegionImpl) region).setExpandedInternal(true); if (notify) notifyListenersOnFoldRegionStateChange(region); } void collapseFoldRegion(@NotNull FoldRegion region, boolean notify) { assertIsDispatchThreadForEditor(); if (!region.isExpanded()) return; if (!myIsBatchFoldingProcessing) { LOG.error("Fold regions must be collapsed or expanded inside batchFoldProcessing() only."); } List<Caret> carets = myEditor.getCaretModel().getAllCarets(); for (Caret caret : carets) { LogicalPosition caretPosition = caret.getLogicalPosition(); int caretOffset = myEditor.logicalPositionToOffset(caretPosition); if (FoldRegionsTree.containsStrict(region, caretOffset)) { if (myDoNotCollapseCaret) return; } } for (Caret caret : carets) { int caretOffset = caret.getOffset(); if (FoldRegionsTree.containsStrict(region, caretOffset)) { SavedCaretPosition savedPosition = caret.getUserData(SAVED_CARET_POSITION); if (savedPosition == null || !savedPosition.isUpToDate(myEditor)) { caret.putUserData(SAVED_CARET_POSITION, new SavedCaretPosition(caret)); } } } myFoldRegionsProcessed = true; ((FoldRegionImpl) region).setExpandedInternal(false); if (notify) notifyListenersOnFoldRegionStateChange(region); } private void notifyBatchFoldingProcessingDone(final boolean moveCaretFromCollapsedRegion) { clearCachedValues(); for (FoldingListener listener : myListeners) { listener.onFoldProcessingEnd(); } myEditor.updateCaretCursor(); myEditor.recalculateSizeAndRepaint(); myEditor.getGutterComponentEx().updateSize(); myEditor.getGutterComponentEx().repaint(); myEditor.invokeDelayedErrorStripeRepaint(); for (Caret caret : myEditor.getCaretModel().getAllCarets()) { // There is a possible case that caret position is already visual position aware. But visual position depends on number of folded // logical lines as well, hence, we can't be sure that target logical position defines correct visual position because fold // regions have just changed. Hence, we use 'raw' logical position instead. LogicalPosition caretPosition = caret.getLogicalPosition().withoutVisualPositionInfo(); int caretOffset = myEditor.logicalPositionToOffset(caretPosition); int selectionStart = caret.getSelectionStart(); int selectionEnd = caret.getSelectionEnd(); LogicalPosition positionToUse = null; int offsetToUse = -1; FoldRegion collapsed = myFoldTree.fetchOutermost(caretOffset); SavedCaretPosition savedPosition = caret.getUserData(SAVED_CARET_POSITION); boolean markedForUpdate = caret.getUserData(MARK_FOR_UPDATE) != null; if (savedPosition != null && savedPosition.isUpToDate(myEditor)) { int savedOffset = myEditor.logicalPositionToOffset(savedPosition.position); FoldRegion collapsedAtSaved = myFoldTree.fetchOutermost(savedOffset); if (collapsedAtSaved == null) { positionToUse = savedPosition.position; } else { offsetToUse = collapsedAtSaved.getStartOffset(); } } if (collapsed != null && positionToUse == null) { positionToUse = myEditor.offsetToLogicalPosition(collapsed.getStartOffset()); } if ((markedForUpdate || moveCaretFromCollapsedRegion) && caret.isUpToDate()) { if (offsetToUse >= 0) { caret.moveToOffset(offsetToUse); } else if (positionToUse != null) { caret.moveToLogicalPosition(positionToUse); } else { ((CaretImpl)caret).updateVisualPosition(); } } caret.putUserData(SAVED_CARET_POSITION, savedPosition); caret.putUserData(MARK_FOR_UPDATE, null); if (isOffsetInsideCollapsedRegion(selectionStart) || isOffsetInsideCollapsedRegion(selectionEnd)) { caret.removeSelection(); } else if (selectionStart < myEditor.getDocument().getTextLength()) { caret.setSelection(selectionStart, selectionEnd); } } if (mySavedCaretShift > 0) { final ScrollingModel scrollingModel = myEditor.getScrollingModel(); scrollingModel.disableAnimation(); scrollingModel.scrollVertically(myEditor.visibleLineToY(myEditor.getCaretModel().getVisualPosition().line) - mySavedCaretShift); scrollingModel.enableAnimation(); } } @Override public void rebuild() { if (!myEditor.getDocument().isInBulkUpdate()) { myFoldTree.rebuild(); } } public boolean isInBatchFoldingOperation() { return myIsBatchFoldingProcessing; } private void updateCachedOffsets() { myFoldTree.updateCachedOffsets(); } public int getFoldedLinesCountBefore(int offset) { if (!myDocumentChangeProcessed && myEditor.getDocument().isInEventsHandling()) { // There is a possible case that this method is called on document update before fold regions are recalculated. // We return zero in such situations then. return 0; } return myFoldTree.getFoldedLinesCountBefore(offset); } int getTotalNumberOfFoldedLines() { if (!myDocumentChangeProcessed && myEditor.getDocument().isInEventsHandling()) { // There is a possible case that this method is called on document update before fold regions are recalculated. // We return zero in such situations then. return 0; } return myFoldTree.getTotalNumberOfFoldedLines(); } @Override @Nullable public FoldRegion[] fetchTopLevel() { return myFoldTree.fetchTopLevel(); } @NotNull public FoldRegion[] fetchCollapsedAt(int offset) { return myFoldTree.fetchCollapsedAt(offset); } @Override public boolean intersectsRegion (int startOffset, int endOffset) { return myFoldTree.intersectsRegion(startOffset, endOffset); } public FoldRegion[] fetchVisible() { return myFoldTree.fetchVisible(); } @Override public int getLastCollapsedRegionBefore(int offset) { return myFoldTree.getLastTopLevelIndexBefore(offset); } @Override public TextAttributes getPlaceholderAttributes() { return myFoldTextAttributes; } void flushCaretPosition(@NotNull Caret caret) { caret.putUserData(SAVED_CARET_POSITION, null); } void onBulkDocumentUpdateStarted() { clearCachedValues(); } void clearCachedValues() { myFoldTree.clearCachedValues(); } void onBulkDocumentUpdateFinished() { myFoldTree.rebuild(); } @Override public void beforeDocumentChange(DocumentEvent event) { if (myIsBatchFoldingProcessing) LOG.error("Document changes are not allowed during batch folding update"); myDocumentChangeProcessed = false; } @Override public void documentChanged(DocumentEvent event) { try { if (!((DocumentEx)event.getDocument()).isInBulkUpdate()) { updateCachedOffsets(); } } finally { myDocumentChangeProcessed = true; } } @Override public void moveTextHappened(int start, int end, int base) { if (!myEditor.getDocument().isInBulkUpdate()) { myFoldTree.rebuild(); } } @Override public int getPriority() { return EditorDocumentPriorities.FOLD_MODEL; } @Nullable @Override public FoldRegion createFoldRegion(int startOffset, int endOffset, @NotNull String placeholder, @Nullable FoldingGroup group, boolean neverExpands) { if (!myFoldTree.checkIfValidToCreate(startOffset, endOffset)) return null; FoldRegionImpl region = new FoldRegionImpl(myEditor, startOffset, endOffset, placeholder, group, neverExpands); myRegionTree.addInterval(region, startOffset, endOffset, false, false, false, 0); if (!checkIfValid(region)) { region.dispose(); return null; } myFoldRegionsProcessed = true; if (group != null) { myGroups.putValue(group, region); } notifyListenersOnFoldRegionStateChange(region); LOG.assertTrue(region.isValid()); return region; } @Override public void addListener(@NotNull final FoldingListener listener, @NotNull Disposable parentDisposable) { myListeners.add(listener); Disposer.register(parentDisposable, () -> myListeners.remove(listener)); } private void notifyListenersOnFoldRegionStateChange(@NotNull FoldRegion foldRegion) { for (FoldingListener listener : myListeners) { listener.onFoldRegionStateChange(foldRegion); } } private void notifyListenersOnFoldRegionRemove(@NotNull FoldRegion foldRegion) { for (FoldingListener listener : myListeners) { listener.beforeFoldRegionRemoved(foldRegion); } } @NotNull @Override public String dumpState() { return Arrays.toString(myFoldTree.fetchTopLevel()); } @Override public String toString() { return dumpState(); } @Override public long getModificationCount() { return myExpansionCounter.get(); } @TestOnly void validateState() { if (myEditor.getDocument().isInBulkUpdate()) return; FoldRegion[] allFoldRegions = getAllFoldRegions(); boolean[] invisibleRegions = new boolean[allFoldRegions.length]; for (int i = 0; i < allFoldRegions.length; i++) { FoldRegion r1 = allFoldRegions[i]; LOG.assertTrue(r1.isValid() && !DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), r1.getStartOffset()) && !DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), r1.getEndOffset()), "Invalid region"); for (int j = i + 1; j < allFoldRegions.length; j++) { FoldRegion r2 = allFoldRegions[j]; int r1s = r1.getStartOffset(); int r1e = r1.getEndOffset(); int r2s = r2.getStartOffset(); int r2e = r2.getEndOffset(); LOG.assertTrue(r1s < r2s && (r1e <= r2s || r1e >= r2e) || r1s == r2s && r1e != r2e || r1s > r2s && r1s < r2e && r1e <= r2e || r1s >= r2e, "Disallowed relative position of regions"); if (!r1.isExpanded() && r1s <= r2s && r1e >= r2e) invisibleRegions[j] = true; if (!r2.isExpanded() && r2s <= r1s && r2e >= r1e) invisibleRegions[i] = true; } } Set<FoldRegion> visibleRegions = new THashSet<>(FoldRegionsTree.OFFSET_BASED_HASHING_STRATEGY); List<FoldRegion> topLevelRegions = new ArrayList<>(); for (int i = 0; i < allFoldRegions.length; i++) { if (!invisibleRegions[i]) { FoldRegion region = allFoldRegions[i]; LOG.assertTrue(visibleRegions.add(region), "Duplicate visible regions"); if (!region.isExpanded()) topLevelRegions.add(region); } } Collections.sort(topLevelRegions, Comparator.comparingInt(r -> r.getStartOffset())); FoldRegion[] actualVisibles = fetchVisible(); if (actualVisibles != null) { for (FoldRegion r : actualVisibles) { LOG.assertTrue(visibleRegions.remove(r), "Unexpected visible region"); } LOG.assertTrue(visibleRegions.isEmpty(), "Missing visible region"); } FoldRegion[] actualTopLevels = fetchTopLevel(); if (actualTopLevels != null) { LOG.assertTrue(actualTopLevels.length == topLevelRegions.size(), "Wrong number of top-level regions"); for (int i = 0; i < actualTopLevels.length; i++) { LOG.assertTrue(FoldRegionsTree.OFFSET_BASED_HASHING_STRATEGY.equals(actualTopLevels[i], topLevelRegions.get(i)), "Unexpected top-level region"); } } } private static class SavedCaretPosition { private final LogicalPosition position; private final long docStamp; private SavedCaretPosition(Caret caret) { position = caret.getLogicalPosition().withoutVisualPositionInfo(); docStamp = caret.getEditor().getDocument().getModificationStamp(); } private boolean isUpToDate(Editor editor) { return docStamp == editor.getDocument().getModificationStamp(); } } }
import javax.swing.tree.DefaultMutableTreeNode; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; abstract class AbstractVertex implements Comparable<AbstractVertex> { public static final double DEFAULT_WIDTH = 1.0; public static final double DEFAULT_HEIGHT = 1.0; public Instruction inst; public static final String METADATA_MERGE_PARENT = "MERGE_PARENT"; public static final String METADATA_INSTRUCTION = "INSTRUCTION_STATEMENT"; static int idCounter = 0; // Used to assign unique id numbers to each vertex // Used to sort lines of code in a method public int compareTo(AbstractVertex o) { if(this.getMinInstructionLine() == o.getMinInstructionLine()) { return 0; } else if(this.getMinInstructionLine() < o.getMinInstructionLine()) { return -1; } return 1; } private int minInstructionLine = -1; //start with a negative value to be properly initialized later public int getMinInstructionLine() { return minInstructionLine; } public void setMinInstructionLine(int smallestInstructionLine) { this.minInstructionLine = smallestInstructionLine; } protected AbstractGraph selfGraph = null; protected AbstractGraph innerGraph = null; protected GUINode graphics = null; public GUINode getGraphics() { return graphics; } public void setGraphics(GUINode graphics) { this.graphics = graphics; } private String label; private boolean isExpanded = true; public ArrayList<Integer> tags; public enum VertexType { LINE, METHOD, METHOD_PATH, CHAIN, INSTRUCTION, ROOT } protected int id; protected String strId; protected VertexType vertexType; protected String name; protected int index, parentIndex; protected ArrayList<Vertex> neighbors; protected HashSet<AbstractVertex> abstractOutgoingNeighbors; protected HashSet<AbstractVertex> abstractIncomingNeighbors; protected HashMap<String, Object> metadata; // A location stores coordinates for a subtree. protected Location location = new Location(); boolean updateLocation = false; //children stores all of the vertices to which we have edges from this vertex //in the current display //incoming stores all of the vertices that have edges into this vertex in //the current display //The base graph is stored in the neighbors in the Vertex class. protected ArrayList<AbstractVertex> children, incoming; public void setWidth(double width) { this.location.width = width; } public void setHeight(double height) { this.location.height = height; } public void setX(double x) { this.location.x = x; } public void setY(double y) { this.location.y = y; } public double getX() { return this.location.x; } public double getY() { return this.location.y; } public double getWidth() { return this.location.width; } public double getHeight() { return this.location.height; } protected AbstractVertex parent, mergeRoot, mergeParent; protected boolean isVisible; protected boolean isSelected, isHighlighted, isIncomingHighlighted, isOutgoingHighlighted; //Select or Highlight this vertex, incoming edges, or outgoing edges protected boolean drawEdges; protected int numChildrenHighlighted, numChildrenSelected; protected int loopHeight; // TODO: Can we just use white for unvisited and black for visited? public enum VertexStatus { WHITE, GRAY, BLACK, VISITED, UNVISITED } protected VertexStatus vertexStatus = VertexStatus.WHITE; protected double[] subtreeBoundBox = {this.location.width, this.location.height}; //Subclasses must override these so that we have descriptions for each of them, //and so that our generic collapsing can work for all of them abstract String getRightPanelContent(); abstract String getShortDescription(); abstract ArrayList<? extends AbstractVertex> getMergeChildren(); abstract String getName(); abstract Method getMethod(); public AbstractVertex() { this.abstractOutgoingNeighbors = new HashSet<AbstractVertex>(); this.abstractIncomingNeighbors = new HashSet<AbstractVertex>(); this.id = idCounter++; this.strId = "vertex:"+this.id; this.metadata = new HashMap<String,Object>(); } public AbstractVertex(String label, VertexType type){ this(); this.label = label; this.innerGraph = new AbstractGraph(); this.vertexType = type; } public HashMap<String,Object> getMetaData(){ return this.metadata; } public String getLabel() { return this.label; } public AbstractGraph getInnerGraph() { return innerGraph; } public AbstractGraph getSelfGraph() { return selfGraph; } public void setInnerGraph(AbstractGraph innerGraph) { this.innerGraph = innerGraph; } public AbstractVertex getMergeParent() { return this.mergeParent; } public void setMergeParent(AbstractVertex mergeParent) { this.mergeParent = mergeParent; } public void recomputeGraphicsSize() { double pixelWidth = Parameters.stFrame.mainPanel.scaleX(this.location.width); double pixelHeight = Parameters.stFrame.mainPanel.scaleY(this.location.height); this.getGraphics().rect.setWidth(pixelWidth); this.getGraphics().rect.setHeight(pixelHeight); } public String getStrID() { return strId; } public void setDefaults() { this.setVisible(false); this.incoming = new ArrayList<AbstractVertex>(); this.children = new ArrayList<AbstractVertex>(); this.tags = new ArrayList<Integer>(); } public void setVisible(boolean isVisible) { this.isVisible = isVisible; if(this.getGraphics() != null) this.getGraphics().setVisible(isVisible); } public DefaultMutableTreeNode toDefaultMutableTreeNode() { return new DefaultMutableTreeNode(this); } public void addTag(int t) { for(Integer i : this.tags) { if(i.intValue()==t) return; } this.tags.add(new Integer(t)); } public boolean hasTag(int t) { for(Integer i : this.tags) { if(i.intValue()==t) return true; } return false; } public double distTo(double x, double y) { double xDiff = x - this.location.x; double yDiff = y - this.location.y; return Math.sqrt(xDiff * xDiff + yDiff * yDiff); } public void replaceChild(AbstractVertex ver) { int p = ver.parentIndex; double inc = ver.location.width - this.children.get(p).location.width; this.children.remove(p); this.children.add(p, ver); this.increaseWidth(ver, inc); this.calculateHeight(); } public void calculateHeight() { double h = 0; for(int i = 0; i < this.children.size(); i++) { if(this.children.get(i).location.height > h) h = this.children.get(i).location.height; } this.location.height = h + 1; this.location.bottom = this.location.top + this.location.height; if(this.parent != null) this.parent.calculateHeight(); } //Collapse a merge parent's vertices. public void collapse() { //To collapse a vertex, first we check that it contains visible merge children. if(this.mergeRoot != null && this.mergeRoot.isVisible) { this.updateLocation = true; this.children = new ArrayList<AbstractVertex>(); //Set the location for our merge parent to be the same as its first child. this.location.left = this.mergeRoot.location.left; this.location.top = this.mergeRoot.location.top; Main.graph.setMaxHeight(0); //Remove the children of our merge parent and set them invisible. double w = this.mergeRoot.disappear(this.location.left, this.location.top + 1, this); if(w > 1) this.location.width = w; else this.location.width = 1; this.location.right = this.location.left + this.location.width; this.location.x = (this.location.left + this.location.right)/2; this.location.height = Main.graph.getMaxHeight() + 1; this.location.bottom = this.location.top + this.location.height; this.location.y = this.location.top + 0.5; this.parent = this.mergeRoot.parent; this.parentIndex = this.mergeRoot.parentIndex; this.mergeRoot.parent.replaceChild(this); this.setVisible(true); } } //Collapse a vertex into its merge parent private double disappear(double left, double top, AbstractVertex mP) { double w = 0; AbstractVertex v; for(int i = 0; i < this.children.size(); i++) { v = this.children.get(i); v.updateLocation = true; // If our current vertex has the same merge parent, then it also should be collapsed, and we // recurse to its children. if(v.getMergeParent() == mP) { w = w + v.disappear(left + w, top, mP); } // Otherwise, we need to shift v. else { while(!v.isVisible && v.getMergeParent() != null) v = v.getMergeParent(); while(!v.isVisible) v = v.mergeRoot; v.shiftSubtree(left + w - v.location.left); v.shiftSubtreeY(top - v.location.top); if(v.location.height > Main.graph.getMaxHeight()) Main.graph.setMaxHeight(v.location.height); v.parent = mP; v.parentIndex = mP.children.size(); mP.children.add(v); w += v.location.width; } } this.setVisible(false); return w; } //Expand a vertex out of its merge parent. public void deCollapse() { //First check that our vertex is expandable. //It must be visible and have a valid merge root. if(this.isVisible || this.mergeRoot != null) { //If so, we set the merge start vertex to take its parent's location... this.mergeRoot.location.left = this.location.left; this.mergeRoot.location.top = this.location.top; //Show it and its children in our graph... this.mergeRoot.appear(this.location.left, this.location.top, this); //Connect its edges... this.mergeRoot.parent = this.parent; this.mergeRoot.parentIndex = this.parentIndex; this.parent.replaceChild(this.mergeRoot); //And lastly, we set our current vertex to be invisible. this.setVisible(false); } } //Beginning with our starting merge vertex, display all children of the //expanding merge parent. private void appear(double left, double top, AbstractVertex mP) { //System.out.println("Vertex appearing: " + this.getName()); double w = 0; AbstractVertex v; this.updateLocation = true; this.location.left = left; this.location.top = top; this.location.y = this.location.top + 0.5; for(int i = 0; i < this.children.size(); i++) { //Check each of our children. All merge siblings should appear. v = this.children.get(i); if(v.getMergeParent() == mP) { v.appear(left + w, top + 1, mP); w += v.location.width; } //Vertices that do not have the same merge parent do not need to be changed, //but we must recompute our edges to them. else { //We walk up our merge tree until we cannot go higher, or we reach a //vertex that is isExpanded. while(!v.isVisible && v.getMergeParent() != null) v = v.getMergeParent(); //Then we walk back down the chain of merge roots until we find one that //is visible. This should be the child to which we have an edge. while(!v.isVisible) v = v.mergeRoot; //If our current child is not correct, we replace it. This can happen when //the current child is either collapsed or isExpanded to a different level //than it was before. if(v != this.children.get(i)) { this.children.remove(i); this.children.add(i, v); } //We must shift our subtrees, since our children have changed. v.shiftSubtree(left + w - v.location.left); v.shiftSubtreeY(top + 1 - v.location.top); v.parent = this; v.parentIndex = i; w += v.location.width; } } if(w > 1) this.location.width = w; else this.location.width = 1; this.location.right = this.location.left + this.location.width; this.location.x = (this.location.left + this.location.right)/2; double h = 0; for(int i = 0; i < this.children.size(); i++) { if(this.children.get(i).location.height > h) h = this.children.get(i).location.height; } this.location.height = h + 1; this.location.bottom = this.location.top + this.location.height; this.setVisible(true); //System.out.println("Vertex has appeared!"); } public void centerizeXCoordinate() { int num = this.children.size(); for(int i=0; i<num; i++) this.children.get(i).centerizeXCoordinate(); if(this.children.size()>0) this.location.x = (this.children.get(0).location.x + this.children.get(num-1).location.x)/2; } public void rearrangeByLoopHeight() { int num = this.children.size(), pos, max; AbstractVertex rearranged[] = new AbstractVertex[num]; boolean taken[] = new boolean[num]; int sorted[] = new int[num]; // MJA todo: the next sorting is currently done by selection sort, we should convert it to counting sort for(int i=0; i< num; i++) { taken[i]=false; } for(int i=0; i<num; i++) { pos = -1; max = -1; for(int j=0; j<num; j++) { if(taken[j]) continue; if(this.children.get(j).loopHeight>=max) { max = this.children.get(j).loopHeight; pos = j; } } if(pos>=0) { taken[pos] = true; sorted[num-i-1] = pos; } } // now rearrange pos = 0; for(int j=num-2; j>=0; pos++) { rearranged[pos] = this.children.get(sorted[j]); j=j-2; } int l = 0; if(num%2==0) l = 1; while(pos<num) { rearranged[pos] = this.children.get(sorted[l]); l = l + 2; pos++; } double left = this.location.left; for(int i=0; i<num; i++) { rearranged[i].shiftSubtree(left-rearranged[i].location.left); left += rearranged[i].location.width; } this.children = new ArrayList<AbstractVertex>(); for(int i=0; i<num; i++) { rearranged[i].parentIndex = i; this.children.add(rearranged[i]); } for(int i=0; i< num; i++) this.children.get(i).rearrangeByLoopHeight(); } public void rearrangeByWidth() { int num = this.children.size(), pos; double max; AbstractVertex rearranged[] = new AbstractVertex[num]; boolean taken[] = new boolean[num]; int sorted[] = new int[num]; // MJA todo: the next sorting is currently done by selection sort, we should convert it to counting sort for(int i=0; i< num; i++) { taken[i]=false; } for(int i=0; i<num; i++) { pos = -1; max = -1; for(int j=0; j<num; j++) { if(taken[j]) continue; if(this.children.get(j).location.width > max) { max = this.children.get(j).location.width; pos = j; } } if(pos >= 0) { taken[pos] = true; sorted[num-i-1] = pos; } } // now rearrange pos = 0; for(int j=num-2; j>=0; pos++) { rearranged[pos] = this.children.get(sorted[j]); j=j-2; } int l = 0; if(num%2==0) l = 1; while(pos<num) { rearranged[pos] = this.children.get(sorted[l]); l = l + 2; pos++; } double left = this.location.left; for(int i=0; i<num; i++) { rearranged[i].shiftSubtree(left-rearranged[i].location.left); left += rearranged[i].location.width; } this.children = new ArrayList<AbstractVertex>(); for(int i=0; i<num; i++) { rearranged[i].parentIndex = i; this.children.add(rearranged[i]); } for(int i=0; i< num; i++) this.children.get(i).rearrangeByWidth(); } public void increaseWidth(AbstractVertex child, double inc) { AbstractVertex ver = this; AbstractVertex ch = child; while(ver != null) { ver.updateLocation = true; ver.location.width += inc; ver.location.right += inc; ver.location.x = (ver.location.left + ver.location.right)/2; for(int i = ch.parentIndex + 1; i < ver.children.size(); i++) { ver.children.get(i).shiftSubtree(inc); } ch = ver; ver = ver.parent; } } //Shift a tree by the given increment by DFS public void shiftSubtree(double inc) { AbstractVertex ver = this; while(true) { ver.updateLocation = true; ver.location.left += inc; ver.location.right += inc; ver.location.x += inc; if(ver.children.size() > 0) ver = ver.children.get(0); else { while(ver != this && ver.parent.children.size() == ver.parentIndex + 1) { ver = ver.parent; } if(ver == this) break; else ver = ver.parent.children.get(ver.parentIndex + 1); } } } //TODO: Why not use DFS here? public void shiftSubtreeY(double inc) { this.updateLocation = true; this.location.top += inc; this.location.bottom += inc; this.location.y += inc; for(int i = 0; i < this.children.size(); i++) this.children.get(i).shiftSubtreeY(inc); } public void increaseHeight(double inc) { this.location.height += inc; if(this.parent == null) return; if(this.location.height + 1 > this.parent.location.height) this.parent.increaseHeight(this.location.height - this.parent.location.height + 1); } public void addChild(AbstractVertex child) { child.parentIndex = this.children.size(); this.children.add(child); child.parent = this; if(this.children.size() == 1) { child.shiftSubtree(this.location.left - child.location.left); if(child.location.width > 1) this.increaseWidth(child, child.location.width - 1); } else { child.shiftSubtree(this.location.right - child.location.left); this.increaseWidth(child, child.location.width); } child.shiftSubtreeY(this.location.bottom - child.location.top); if(child.location.height + 1 > this.location.height) this.increaseHeight(child.location.height - this.location.height + 1); } public boolean checkPotentialParent() { return this != Main.graph.root; } public void setLoopHeight() { if(this.mergeRoot == null) return; this.loopHeight = 0; for(AbstractVertex v : this.getMergeChildren()) { if(v.loopHeight > this.loopHeight) this.loopHeight = v.loopHeight; } } public void toggleSelected() { this.isSelected = !this.isSelected; this.isHighlighted = !this.isHighlighted; if(this.parent != null) this.parent.isHighlighted = this.isHighlighted; } public void addHighlight(boolean select, boolean vertex, boolean to, boolean from) { //System.out.println("Highlighting vertex: " + this.getFullName()); if(select) this.isSelected = true; if(vertex) this.isHighlighted = true; if(to) this.isIncomingHighlighted = true; if(from) this.isOutgoingHighlighted = true; AbstractVertex v = this.getMergeParent(); while(v != null) { if(select) { v.numChildrenSelected++; } if(vertex) { v.numChildrenHighlighted++; //System.out.println("Adding child highlight to " + v.getFullName()); } if(to) v.isIncomingHighlighted = true; if(from) v.isOutgoingHighlighted = true; v = v.getMergeParent(); } } public boolean isCycleHighlighted() { return this.isOutgoingHighlighted && this.isIncomingHighlighted; } public boolean isHighlighted() { return this.isHighlighted; } public boolean isChildHighlighted() { //System.out.println("Highlighted children for vertex: " + this.getFullName() + " = " + this.numChildrenHighlighted); return this.numChildrenHighlighted > 0; } public boolean isParentHighlighted() { AbstractVertex ver = this; while(ver !=null) { if(ver.isHighlighted) return true; ver = ver.getMergeParent(); } return false; } public boolean isBranchHighlighted() { return this.isHighlighted() | this.isParentHighlighted() | this.isChildHighlighted(); } public boolean isSelected() { return this.isSelected; } public boolean isChildSelected() { return this.numChildrenSelected > 0; } public boolean isParentSelected() { AbstractVertex ver = this; while(ver !=null) { if(ver.isSelected) return true; ver = ver.getMergeParent(); } return false; } public boolean isBranchSelected() { return this.isSelected() | this.isParentSelected() | this.isChildSelected(); } public void clearAllHighlights() { if(this.isHighlighted) { AbstractVertex v = this.getMergeParent(); while(v != null) { v.numChildrenHighlighted v = v.getMergeParent(); } } this.isHighlighted = false; this.isIncomingHighlighted = false; this.isOutgoingHighlighted = false; } public void clearAllSelect() { if(this.isSelected) { AbstractVertex v = this.getMergeParent(); while(v != null) { v.numChildrenSelected v = v.getMergeParent(); } } this.isSelected = false; this.isIncomingHighlighted = false; this.isOutgoingHighlighted = false; } public void clearCycleHighlights() { this.isIncomingHighlighted = false; this.isOutgoingHighlighted = false; } public void changeParent(AbstractVertex newParent) { this.parent.increaseWidth(this, -1*this.location.width); for(int i = this.parentIndex + 1; i < this.parent.children.size(); i++) { this.parent.children.get(i).parentIndex } this.parent.children.remove(this.parentIndex); AbstractVertex ver = this; while(ver.parent != null) { double height = 0; for(int i=0; i< ver.parent.children.size(); i++) { if(ver.parent.children.get(i).location.height>height) height = ver.parent.children.get(i).location.height; } ver.parent.location.height = height + 1; ver = ver.parent; } newParent.addChild(this); } public void addOutgoingAbstractNeighbor(AbstractVertex neighbor) { this.abstractOutgoingNeighbors.add(neighbor); } public void addIncomingAbstractNeighbor(AbstractVertex neighbor) { this.abstractIncomingNeighbors.add(neighbor); } public HashSet<AbstractVertex> getOutgoingAbstractNeighbors() { return this.abstractOutgoingNeighbors; } public HashSet<AbstractVertex> getIncomingAbstractNeighbors() { return this.abstractIncomingNeighbors; } public void setSelfGraph(AbstractGraph abstractGraph) { this.selfGraph = abstractGraph; } public boolean isExpanded() { return isExpanded; } public void setExpanded(boolean expanded) { this.isExpanded = expanded; } public void setEdgeVisibility(boolean isEdgeVisible) { for(Edge e : this.innerGraph.getEdges().values()) e.setVisible(isEdgeVisible); } public void printCoordinates() { System.out.println("Vertex " + this.id + this.location.toString()); } public void removeOutgoingAbstractNeighbor(AbstractVertex destVertex) { this.abstractOutgoingNeighbors.remove(destVertex); } public void removeIncomingAbstractNeighbor(AbstractVertex destVertex) { this.abstractIncomingNeighbors.remove(destVertex); } public VertexType getType() { return this.vertexType; } public void toggleNodesOfType(VertexType type, boolean methodExpanded) { if(this.getType()==type){ this.setExpanded(methodExpanded); } Iterator<AbstractVertex> it = this.getInnerGraph().getVertices().values().iterator(); while(it.hasNext()){ it.next().toggleNodesOfType(type,methodExpanded); } } public void toggleEdges() { Iterator<Edge> it = this.getInnerGraph().getEdges().values().iterator(); while(it.hasNext()){ Edge e = it.next(); if(e.getGraphics()!=null){ e.getGraphics().setVisible(!e.getGraphics().isVisible()); } } Iterator<AbstractVertex> itN = this.getInnerGraph().getVertices().values().iterator(); while(itN.hasNext()){ itN.next().toggleEdges(); } } public void reset(){ this.setGraphics(null); Iterator<AbstractVertex> it = this.getInnerGraph().getVertices().values().iterator(); while(it.hasNext()){ it.next().reset(); } } public HashMap<AbstractVertex, Instruction> getInstructions(){ return this.getInstructions(new HashMap<AbstractVertex, Instruction>()); } private HashMap<AbstractVertex, Instruction> getInstructions(HashMap<AbstractVertex, Instruction> instructions){ if(this.getType().equals(AbstractVertex.VertexType.ROOT) || this.getType().equals(AbstractVertex.VertexType.METHOD) || this.getType().equals(AbstractVertex.VertexType.CHAIN)){ Iterator<AbstractVertex> it = this.getInnerGraph().getVertices().values().iterator(); while(it.hasNext()){ it.next().getInstructions(instructions); } } else if(this.getType().equals(AbstractVertex.VertexType.INSTRUCTION)){ instructions.put(this, (Instruction)this.getMetaData().get(AbstractVertex.METADATA_INSTRUCTION)); } else { System.out.println("Unrecongnized type in method getInstructions"); } return instructions; } public Instruction getRealInstruction() { return this.inst; } public void setRealInstruction(Instruction inst) {this.inst = inst; } public HashSet<AbstractVertex> getVerticesWithInstuctionID(int id, String method_name){ return getVerticesWithInstuctionID(id, method_name, new HashSet<AbstractVertex>()); } private HashSet<AbstractVertex> getVerticesWithInstuctionID(int id, String method_name, HashSet<AbstractVertex> set){ if(this.getType().equals(AbstractVertex.VertexType.ROOT) || this.getType().equals(AbstractVertex.VertexType.METHOD) || this.getType().equals(AbstractVertex.VertexType.CHAIN)){ Iterator<AbstractVertex> it = this.getInnerGraph().getVertices().values().iterator(); while(it.hasNext()){ it.next().getVerticesWithInstuctionID(id, method_name, set); } } else if(this.getType().equals(AbstractVertex.VertexType.INSTRUCTION) && this.getRealInstruction().methodName.equals(method_name) && this.getRealInstruction().jimpleIndex == id){ set.add(this); } else { System.out.println("Unrecongnized type in method getInstructions"); } return set; } }
package org.objectweb.asm.util; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.TypePath; import org.objectweb.asm.TypeReference; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.Analyzer; import org.objectweb.asm.tree.analysis.BasicValue; import org.objectweb.asm.tree.analysis.BasicVerifier; /** * A {@link MethodVisitor} that checks that its methods are properly used. More * precisely this method adapter checks each instruction individually, i.e., * each visit method checks some preconditions based <i>only</i> on its * arguments - such as the fact that the given opcode is correct for a given * visit method. This adapter can also perform some basic data flow checks (more * precisely those that can be performed without the full class hierarchy - see * {@link org.objectweb.asm.tree.analysis.BasicVerifier}). For instance in a * method whose signature is <tt>void m ()</tt>, the invalid instruction * IRETURN, or the invalid sequence IADD L2I will be detected if the data flow * checks are enabled. These checks are enabled by using the * {@link #CheckMethodAdapter(int,String,String,MethodVisitor,Map)} constructor. * They are not performed if any other constructor is used. * * @author Eric Bruneton */ public class CheckMethodAdapter extends MethodVisitor { /** * The class version number. */ public int version; /** * The access flags of the method. */ private int access; /** * <tt>true</tt> if the visitCode method has been called. */ private boolean startCode; /** * <tt>true</tt> if the visitMaxs method has been called. */ private boolean endCode; /** * <tt>true</tt> if the visitEnd method has been called. */ private boolean endMethod; /** * Number of visited instructions. */ private int insnCount; /** * The already visited labels. This map associate Integer values to pseudo * code offsets. */ private final Map<Label, Integer> labels; /** * The labels used in this method. Every used label must be visited with * visitLabel before the end of the method (i.e. should be in #labels). */ private Set<Label> usedLabels; /** * If an explicit first frame has been visited before the first instruction. */ private boolean hasExplicitFirstFrame; /** * Number of visited frames in expanded form. */ private int expandedFrames; /** * Number of visited frames in compressed form. */ private int compressedFrames; /** * The exception handler ranges. Each pair of list element contains the * start and end labels of an exception handler block. */ private List<Label> handlers; /** * Code of the visit method to be used for each opcode. */ private static final int[] TYPE; /** * The Label.status field. */ private static Field labelStatusField; static { String s = "BBBBBBBBBBBBBBBBCCIAADDDDDAAAAAAAAAAAAAAAAAAAABBBBBBBBDD" + "DDDAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "BBBBBBBBBBBBBBBBBBBJBBBBBBBBBBBBBBBBBBBBHHHHHHHHHHHHHHHHD" + "KLBBBBBBFFFFGGGGAECEBBEEBBAMHHAA"; TYPE = new int[s.length()]; for (int i = 0; i < TYPE.length; ++i) { TYPE[i] = s.charAt(i) - 'A' - 1; } } // code to generate the above string // public static void main (String[] args) { // int[] TYPE = new int[] { // 0, //NOP // 0, //ACONST_NULL // 0, //ICONST_M1 // 0, //ICONST_0 // 0, //ICONST_1 // 0, //ICONST_2 // 0, //ICONST_3 // 0, //ICONST_4 // 0, //ICONST_5 // 0, //LCONST_0 // 0, //LCONST_1 // 0, //FCONST_0 // 0, //FCONST_1 // 0, //FCONST_2 // 0, //DCONST_0 // 0, //DCONST_1 // 1, //BIPUSH // 1, //SIPUSH // 7, //LDC // -1, //LDC_W // -1, //LDC2_W // 2, //ILOAD // 2, //LLOAD // 2, //FLOAD // 2, //DLOAD // 2, //ALOAD // -1, //ILOAD_0 // -1, //ILOAD_1 // -1, //ILOAD_2 // -1, //ILOAD_3 // -1, //LLOAD_0 // -1, //LLOAD_1 // -1, //LLOAD_2 // -1, //LLOAD_3 // -1, //FLOAD_0 // -1, //FLOAD_1 // -1, //FLOAD_2 // -1, //FLOAD_3 // -1, //DLOAD_0 // -1, //DLOAD_1 // -1, //DLOAD_2 // -1, //DLOAD_3 // -1, //ALOAD_0 // -1, //ALOAD_1 // -1, //ALOAD_2 // -1, //ALOAD_3 // 0, //IALOAD // 0, //LALOAD // 0, //FALOAD // 0, //DALOAD // 0, //AALOAD // 0, //BALOAD // 0, //CALOAD // 0, //SALOAD // 2, //ISTORE // 2, //LSTORE // 2, //FSTORE // 2, //DSTORE // 2, //ASTORE // -1, //ISTORE_0 // -1, //ISTORE_1 // -1, //ISTORE_2 // -1, //ISTORE_3 // -1, //LSTORE_0 // -1, //LSTORE_1 // -1, //LSTORE_2 // -1, //LSTORE_3 // -1, //FSTORE_0 // -1, //FSTORE_1 // -1, //FSTORE_2 // -1, //FSTORE_3 // -1, //DSTORE_0 // -1, //DSTORE_1 // -1, //DSTORE_2 // -1, //DSTORE_3 // -1, //ASTORE_0 // -1, //ASTORE_1 // -1, //ASTORE_2 // -1, //ASTORE_3 // 0, //IASTORE // 0, //LASTORE // 0, //FASTORE // 0, //DASTORE // 0, //AASTORE // 0, //BASTORE // 0, //CASTORE // 0, //SASTORE // 0, //POP // 0, //POP2 // 0, //DUP // 0, //DUP_X1 // 0, //DUP_X2 // 0, //DUP2 // 0, //DUP2_X1 // 0, //DUP2_X2 // 0, //SWAP // 0, //IADD // 0, //LADD // 0, //FADD // 0, //DADD // 0, //ISUB // 0, //LSUB // 0, //FSUB // 0, //DSUB // 0, //IMUL // 0, //LMUL // 0, //FMUL // 0, //DMUL // 0, //IDIV // 0, //LDIV // 0, //FDIV // 0, //DDIV // 0, //IREM // 0, //LREM // 0, //FREM // 0, //DREM // 0, //INEG // 0, //LNEG // 0, //FNEG // 0, //DNEG // 0, //ISHL // 0, //LSHL // 0, //ISHR // 0, //LSHR // 0, //IUSHR // 0, //LUSHR // 0, //IAND // 0, //LAND // 0, //IOR // 0, //LOR // 0, //IXOR // 0, //LXOR // 8, //IINC // 0, //I2L // 0, //I2F // 0, //I2D // 0, //L2I // 0, //L2F // 0, //L2D // 0, //F2I // 0, //F2L // 0, //F2D // 0, //D2I // 0, //D2L // 0, //D2F // 0, //I2B // 0, //I2C // 0, //I2S // 0, //LCMP // 0, //FCMPL // 0, //FCMPG // 0, //DCMPL // 0, //DCMPG // 6, //IFEQ // 6, //IFNE // 6, //IFLT // 6, //IFGE // 6, //IFGT // 6, //IFLE // 6, //IF_ICMPEQ // 6, //IF_ICMPNE // 6, //IF_ICMPLT // 6, //IF_ICMPGE // 6, //IF_ICMPGT // 6, //IF_ICMPLE // 6, //IF_ACMPEQ // 6, //IF_ACMPNE // 6, //GOTO // 6, //JSR // 2, //RET // 9, //TABLESWITCH // 10, //LOOKUPSWITCH // 0, //IRETURN // 0, //LRETURN // 0, //FRETURN // 0, //DRETURN // 0, //ARETURN // 0, //RETURN // 4, //GETSTATIC // 4, //PUTSTATIC // 4, //GETFIELD // 4, //PUTFIELD // 5, //INVOKEVIRTUAL // 5, //INVOKESPECIAL // 5, //INVOKESTATIC // 5, //INVOKEINTERFACE // -1, //INVOKEDYNAMIC // 3, //NEW // 1, //NEWARRAY // 3, //ANEWARRAY // 0, //ARRAYLENGTH // 0, //ATHROW // 3, //CHECKCAST // 3, //INSTANCEOF // 0, //MONITORENTER // 0, //MONITOREXIT // -1, //WIDE // 11, //MULTIANEWARRAY // 6, //IFNULL // 6, //IFNONNULL // -1, //GOTO_W // -1 //JSR_W // for (int i = 0; i < TYPE.length; ++i) { // System.out.print((char)(TYPE[i] + 1 + 'A')); // System.out.println(); /** * Constructs a new {@link CheckMethodAdapter} object. This method adapter * will not perform any data flow check (see * {@link #CheckMethodAdapter(int,String,String,MethodVisitor,Map)}). * <i>Subclasses must not use this constructor</i>. Instead, they must use * the {@link #CheckMethodAdapter(int, MethodVisitor, Map)} version. * * @param mv * the method visitor to which this adapter must delegate calls. */ public CheckMethodAdapter(final MethodVisitor mv) { this(mv, new HashMap<Label, Integer>()); } /** * Constructs a new {@link CheckMethodAdapter} object. This method adapter * will not perform any data flow check (see * {@link #CheckMethodAdapter(int,String,String,MethodVisitor,Map)}). * <i>Subclasses must not use this constructor</i>. Instead, they must use * the {@link #CheckMethodAdapter(int, MethodVisitor, Map)} version. * * @param mv * the method visitor to which this adapter must delegate calls. * @param labels * a map of already visited labels (in other methods). */ public CheckMethodAdapter(final MethodVisitor mv, final Map<Label, Integer> labels) { this(Opcodes.ASM5, mv, labels); } /** * Constructs a new {@link CheckMethodAdapter} object. This method adapter * will not perform any data flow check (see * {@link #CheckMethodAdapter(int,String,String,MethodVisitor,Map)}). * * @param mv * the method visitor to which this adapter must delegate calls. * @param labels * a map of already visited labels (in other methods). */ protected CheckMethodAdapter(final int api, final MethodVisitor mv, final Map<Label, Integer> labels) { super(api, mv); this.labels = labels; this.usedLabels = new HashSet<Label>(); this.handlers = new ArrayList<Label>(); } /** * Constructs a new {@link CheckMethodAdapter} object. This method adapter * will perform basic data flow checks. For instance in a method whose * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the * invalid sequence IADD L2I will be detected. * * @param access * the method's access flags. * @param name * the method's name. * @param desc * the method's descriptor (see {@link Type Type}). * @param cmv * the method visitor to which this adapter must delegate calls. * @param labels * a map of already visited labels (in other methods). */ public CheckMethodAdapter(final int access, final String name, final String desc, final MethodVisitor cmv, final Map<Label, Integer> labels) { this(new MethodNode(access, name, desc, null, null) { @Override public void visitEnd() { Analyzer<BasicValue> a = new Analyzer<BasicValue>( new BasicVerifier()); try { a.analyze("dummy", this); } catch (Exception e) { if (e instanceof IndexOutOfBoundsException && maxLocals == 0 && maxStack == 0) { throw new RuntimeException( "Data flow checking option requires valid, non zero maxLocals and maxStack values."); } e.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); CheckClassAdapter.printAnalyzerResult(this, a, pw); pw.close(); throw new RuntimeException(e.getMessage() + ' ' + sw.toString()); } accept(cmv); } }, labels); this.access = access; } @Override public void visitParameter(String name, int access) { if (name != null) { checkUnqualifiedName(version, name, "name"); } CheckClassAdapter.checkAccess(access, Opcodes.ACC_FINAL + Opcodes.ACC_MANDATED + Opcodes.ACC_SYNTHETIC); } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { checkEndMethod(); checkDesc(desc, false); return new CheckAnnotationAdapter(super.visitAnnotation(desc, visible)); } @Override public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { checkEndMethod(); int sort = typeRef >>> 24; if (sort != TypeReference.METHOD_TYPE_PARAMETER && sort != TypeReference.METHOD_TYPE_PARAMETER_BOUND && sort != TypeReference.METHOD_RETURN && sort != TypeReference.METHOD_RECEIVER && sort != TypeReference.METHOD_FORMAL_PARAMETER && sort != TypeReference.THROWS) { throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(sort)); } CheckClassAdapter.checkTypeRefAndPath(typeRef, typePath); CheckMethodAdapter.checkDesc(desc, false); return new CheckAnnotationAdapter(super.visitTypeAnnotation(typeRef, typePath, desc, visible)); } @Override public AnnotationVisitor visitAnnotationDefault() { checkEndMethod(); return new CheckAnnotationAdapter(super.visitAnnotationDefault(), false); } @Override public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { checkEndMethod(); checkDesc(desc, false); return new CheckAnnotationAdapter(super.visitParameterAnnotation( parameter, desc, visible)); } @Override public void visitAttribute(final Attribute attr) { checkEndMethod(); if (attr == null) { throw new IllegalArgumentException( "Invalid attribute (must not be null)"); } super.visitAttribute(attr); } @Override public void visitCode() { if ((access & Opcodes.ACC_ABSTRACT) != 0) { throw new RuntimeException("Abstract methods cannot have code"); } startCode = true; super.visitCode(); } @Override public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { int mLocal; int mStack; switch (type) { case Opcodes.F_NEW: case Opcodes.F_FULL: mLocal = Integer.MAX_VALUE; mStack = Integer.MAX_VALUE; break; case Opcodes.F_SAME: mLocal = 0; mStack = 0; break; case Opcodes.F_SAME1: mLocal = 0; mStack = 1; break; case Opcodes.F_APPEND: case Opcodes.F_CHOP: mLocal = 3; mStack = 0; break; default: throw new IllegalArgumentException("Invalid frame type " + type); } if (nLocal > mLocal) { throw new IllegalArgumentException("Invalid nLocal=" + nLocal + " for frame type " + type); } if (nStack > mStack) { throw new IllegalArgumentException("Invalid nStack=" + nStack + " for frame type " + type); } if (type != Opcodes.F_CHOP) { if (nLocal > 0 && (local == null || local.length < nLocal)) { throw new IllegalArgumentException( "Array local[] is shorter than nLocal"); } for (int i = 0; i < nLocal; ++i) { checkFrameValue(local[i]); } } if (nStack > 0 && (stack == null || stack.length < nStack)) { throw new IllegalArgumentException( "Array stack[] is shorter than nStack"); } for (int i = 0; i < nStack; ++i) { checkFrameValue(stack[i]); } if (type == Opcodes.F_NEW) { if (insnCount == 0) { hasExplicitFirstFrame = true; } else if (!hasExplicitFirstFrame) { throw new RuntimeException( "In expanded form, a first frame must be explicitly " + "visited before the first instruction."); } ++expandedFrames; } else { ++compressedFrames; } if (expandedFrames > 0 && compressedFrames > 0) { throw new RuntimeException( "Expanded and compressed frames must not be mixed."); } super.visitFrame(type, nLocal, local, nStack, stack); } @Override public void visitInsn(final int opcode) { checkStartCode(); checkEndCode(); checkOpcode(opcode, 0); super.visitInsn(opcode); ++insnCount; } @Override public void visitIntInsn(final int opcode, final int operand) { checkStartCode(); checkEndCode(); checkOpcode(opcode, 1); switch (opcode) { case Opcodes.BIPUSH: checkSignedByte(operand, "Invalid operand"); break; case Opcodes.SIPUSH: checkSignedShort(operand, "Invalid operand"); break; // case Constants.NEWARRAY: default: if (operand < Opcodes.T_BOOLEAN || operand > Opcodes.T_LONG) { throw new IllegalArgumentException( "Invalid operand (must be an array type code T_...): " + operand); } } super.visitIntInsn(opcode, operand); ++insnCount; } @Override public void visitVarInsn(final int opcode, final int var) { checkStartCode(); checkEndCode(); checkOpcode(opcode, 2); checkUnsignedShort(var, "Invalid variable index"); super.visitVarInsn(opcode, var); ++insnCount; } @Override public void visitTypeInsn(final int opcode, final String type) { checkStartCode(); checkEndCode(); checkOpcode(opcode, 3); checkInternalName(type, "type"); if (opcode == Opcodes.NEW && type.charAt(0) == '[') { throw new IllegalArgumentException( "NEW cannot be used to create arrays: " + type); } super.visitTypeInsn(opcode, type); ++insnCount; } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { checkStartCode(); checkEndCode(); checkOpcode(opcode, 4); checkInternalName(owner, "owner"); checkUnqualifiedName(version, name, "name"); checkDesc(desc, false); super.visitFieldInsn(opcode, owner, name, desc); ++insnCount; } @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { checkStartCode(); checkEndCode(); checkOpcode(opcode, 5); if (opcode != Opcodes.INVOKESPECIAL || !"<init>".equals(name)) { checkMethodIdentifier(version, name, "name"); } checkInternalName(owner, "owner"); checkMethodDesc(desc); super.visitMethodInsn(opcode, owner, name, desc); ++insnCount; } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { checkStartCode(); checkEndCode(); checkMethodIdentifier(version, name, "name"); checkMethodDesc(desc); if (bsm.getTag() != Opcodes.H_INVOKESTATIC && bsm.getTag() != Opcodes.H_NEWINVOKESPECIAL) { throw new IllegalArgumentException("invalid handle tag " + bsm.getTag()); } for (int i = 0; i < bsmArgs.length; i++) { checkLDCConstant(bsmArgs[i]); } super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); ++insnCount; } @Override public void visitJumpInsn(final int opcode, final Label label) { checkStartCode(); checkEndCode(); checkOpcode(opcode, 6); checkLabel(label, false, "label"); checkNonDebugLabel(label); super.visitJumpInsn(opcode, label); usedLabels.add(label); ++insnCount; } @Override public void visitLabel(final Label label) { checkStartCode(); checkEndCode(); checkLabel(label, false, "label"); if (labels.get(label) != null) { throw new IllegalArgumentException("Already visited label"); } labels.put(label, new Integer(insnCount)); super.visitLabel(label); } @Override public void visitLdcInsn(final Object cst) { checkStartCode(); checkEndCode(); checkLDCConstant(cst); super.visitLdcInsn(cst); ++insnCount; } @Override public void visitIincInsn(final int var, final int increment) { checkStartCode(); checkEndCode(); checkUnsignedShort(var, "Invalid variable index"); checkSignedShort(increment, "Invalid increment"); super.visitIincInsn(var, increment); ++insnCount; } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) { checkStartCode(); checkEndCode(); if (max < min) { throw new IllegalArgumentException("Max = " + max + " must be greater than or equal to min = " + min); } checkLabel(dflt, false, "default label"); checkNonDebugLabel(dflt); if (labels == null || labels.length != max - min + 1) { throw new IllegalArgumentException( "There must be max - min + 1 labels"); } for (int i = 0; i < labels.length; ++i) { checkLabel(labels[i], false, "label at index " + i); checkNonDebugLabel(labels[i]); } super.visitTableSwitchInsn(min, max, dflt, labels); for (int i = 0; i < labels.length; ++i) { usedLabels.add(labels[i]); } ++insnCount; } @Override public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { checkEndCode(); checkStartCode(); checkLabel(dflt, false, "default label"); checkNonDebugLabel(dflt); if (keys == null || labels == null || keys.length != labels.length) { throw new IllegalArgumentException( "There must be the same number of keys and labels"); } for (int i = 0; i < labels.length; ++i) { checkLabel(labels[i], false, "label at index " + i); checkNonDebugLabel(labels[i]); } super.visitLookupSwitchInsn(dflt, keys, labels); usedLabels.add(dflt); for (int i = 0; i < labels.length; ++i) { usedLabels.add(labels[i]); } ++insnCount; } @Override public void visitMultiANewArrayInsn(final String desc, final int dims) { checkStartCode(); checkEndCode(); checkDesc(desc, false); if (desc.charAt(0) != '[') { throw new IllegalArgumentException( "Invalid descriptor (must be an array type descriptor): " + desc); } if (dims < 1) { throw new IllegalArgumentException( "Invalid dimensions (must be greater than 0): " + dims); } if (dims > desc.lastIndexOf('[') + 1) { throw new IllegalArgumentException( "Invalid dimensions (must not be greater than dims(desc)): " + dims); } super.visitMultiANewArrayInsn(desc, dims); ++insnCount; } @Override public AnnotationVisitor visitInsnAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { checkStartCode(); checkEndCode(); int sort = typeRef >>> 24; if (sort != TypeReference.INSTANCEOF && sort != TypeReference.NEW && sort != TypeReference.CONSTRUCTOR_REFERENCE && sort != TypeReference.METHOD_REFERENCE && sort != TypeReference.CAST && sort != TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT && sort != TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT && sort != TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT && sort != TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT) { throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(sort)); } CheckClassAdapter.checkTypeRefAndPath(typeRef, typePath); CheckMethodAdapter.checkDesc(desc, false); return new CheckAnnotationAdapter(super.visitInsnAnnotation(typeRef, typePath, desc, visible)); } @Override public void visitTryCatchBlock(final Label start, final Label end, final Label handler, final String type) { checkStartCode(); checkEndCode(); checkLabel(start, false, "start label"); checkLabel(end, false, "end label"); checkLabel(handler, false, "handler label"); checkNonDebugLabel(start); checkNonDebugLabel(end); checkNonDebugLabel(handler); if (labels.get(start) != null || labels.get(end) != null || labels.get(handler) != null) { throw new IllegalStateException( "Try catch blocks must be visited before their labels"); } if (type != null) { checkInternalName(type, "type"); } super.visitTryCatchBlock(start, end, handler, type); handlers.add(start); handlers.add(end); } @Override public AnnotationVisitor visitTryCatchAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { checkStartCode(); checkEndCode(); int sort = typeRef >>> 24; if (sort != TypeReference.EXCEPTION_PARAMETER) { throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(sort)); } CheckClassAdapter.checkTypeRefAndPath(typeRef, typePath); CheckMethodAdapter.checkDesc(desc, false); return new CheckAnnotationAdapter(super.visitTryCatchAnnotation( typeRef, typePath, desc, visible)); } @Override public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { checkStartCode(); checkEndCode(); checkUnqualifiedName(version, name, "name"); checkDesc(desc, false); checkLabel(start, true, "start label"); checkLabel(end, true, "end label"); checkUnsignedShort(index, "Invalid variable index"); int s = labels.get(start).intValue(); int e = labels.get(end).intValue(); if (e < s) { throw new IllegalArgumentException( "Invalid start and end labels (end must be greater than start)"); } super.visitLocalVariable(name, desc, signature, start, end, index); } @Override public AnnotationVisitor visitLocalVariableAnnotation(int typeRef, TypePath typePath, Label[] start, Label[] end, int[] index, String desc, boolean visible) { checkStartCode(); checkEndCode(); int sort = typeRef >>> 24; if (sort != TypeReference.LOCAL_VARIABLE && sort != TypeReference.RESOURCE_VARIABLE) { throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(sort)); } CheckClassAdapter.checkTypeRefAndPath(typeRef, typePath); checkDesc(desc, false); if (start == null || end == null || index == null || end.length != start.length || index.length != start.length) { throw new IllegalArgumentException( "Invalid start, end and index arrays (must be non null and of identical length"); } for (int i = 0; i < start.length; ++i) { checkLabel(start[i], true, "start label"); checkLabel(end[i], true, "end label"); checkUnsignedShort(index[i], "Invalid variable index"); int s = labels.get(start[i]).intValue(); int e = labels.get(end[i]).intValue(); if (e < s) { throw new IllegalArgumentException( "Invalid start and end labels (end must be greater than start)"); } } return super.visitLocalVariableAnnotation(typeRef, typePath, start, end, index, desc, visible); } @Override public void visitLineNumber(final int line, final Label start) { checkStartCode(); checkEndCode(); checkUnsignedShort(line, "Invalid line number"); checkLabel(start, true, "start label"); super.visitLineNumber(line, start); } @Override public void visitMaxs(final int maxStack, final int maxLocals) { checkStartCode(); checkEndCode(); endCode = true; for (Label l : usedLabels) { if (labels.get(l) == null) { throw new IllegalStateException("Undefined label used"); } } for (int i = 0; i < handlers.size();) { Integer start = labels.get(handlers.get(i++)); Integer end = labels.get(handlers.get(i++)); if (start == null || end == null) { throw new IllegalStateException( "Undefined try catch block labels"); } if (end.intValue() <= start.intValue()) { throw new IllegalStateException( "Emty try catch block handler range"); } } checkUnsignedShort(maxStack, "Invalid max stack"); checkUnsignedShort(maxLocals, "Invalid max locals"); super.visitMaxs(maxStack, maxLocals); } @Override public void visitEnd() { checkEndMethod(); endMethod = true; super.visitEnd(); } /** * Checks that the visitCode method has been called. */ void checkStartCode() { if (!startCode) { throw new IllegalStateException( "Cannot visit instructions before visitCode has been called."); } } /** * Checks that the visitMaxs method has not been called. */ void checkEndCode() { if (endCode) { throw new IllegalStateException( "Cannot visit instructions after visitMaxs has been called."); } } /** * Checks that the visitEnd method has not been called. */ void checkEndMethod() { if (endMethod) { throw new IllegalStateException( "Cannot visit elements after visitEnd has been called."); } } /** * Checks a stack frame value. * * @param value * the value to be checked. */ void checkFrameValue(final Object value) { if (value == Opcodes.TOP || value == Opcodes.INTEGER || value == Opcodes.FLOAT || value == Opcodes.LONG || value == Opcodes.DOUBLE || value == Opcodes.NULL || value == Opcodes.UNINITIALIZED_THIS) { return; } if (value instanceof String) { checkInternalName((String) value, "Invalid stack frame value"); return; } if (!(value instanceof Label)) { throw new IllegalArgumentException("Invalid stack frame value: " + value); } else { usedLabels.add((Label) value); } } /** * Checks that the type of the given opcode is equal to the given type. * * @param opcode * the opcode to be checked. * @param type * the expected opcode type. */ static void checkOpcode(final int opcode, final int type) { if (opcode < 0 || opcode > 199 || TYPE[opcode] != type) { throw new IllegalArgumentException("Invalid opcode: " + opcode); } } /** * Checks that the given value is a signed byte. * * @param value * the value to be checked. * @param msg * an message to be used in case of error. */ static void checkSignedByte(final int value, final String msg) { if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { throw new IllegalArgumentException(msg + " (must be a signed byte): " + value); } } /** * Checks that the given value is a signed short. * * @param value * the value to be checked. * @param msg * an message to be used in case of error. */ static void checkSignedShort(final int value, final String msg) { if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { throw new IllegalArgumentException(msg + " (must be a signed short): " + value); } } /** * Checks that the given value is an unsigned short. * * @param value * the value to be checked. * @param msg * an message to be used in case of error. */ static void checkUnsignedShort(final int value, final String msg) { if (value < 0 || value > 65535) { throw new IllegalArgumentException(msg + " (must be an unsigned short): " + value); } } /** * Checks that the given value is an {@link Integer}, a{@link Float}, a * {@link Long}, a {@link Double} or a {@link String}. * * @param cst * the value to be checked. */ static void checkConstant(final Object cst) { if (!(cst instanceof Integer) && !(cst instanceof Float) && !(cst instanceof Long) && !(cst instanceof Double) && !(cst instanceof String)) { throw new IllegalArgumentException("Invalid constant: " + cst); } } void checkLDCConstant(final Object cst) { if (cst instanceof Type) { int s = ((Type) cst).getSort(); if (s != Type.OBJECT && s != Type.ARRAY && s != Type.METHOD) { throw new IllegalArgumentException("Illegal LDC constant value"); } if (s != Type.METHOD && (version & 0xFFFF) < Opcodes.V1_5) { throw new IllegalArgumentException( "ldc of a constant class requires at least version 1.5"); } if (s == Type.METHOD && (version & 0xFFFF) < Opcodes.V1_7) { throw new IllegalArgumentException( "ldc of a method type requires at least version 1.7"); } } else if (cst instanceof Handle) { if ((version & 0xFFFF) < Opcodes.V1_7) { throw new IllegalArgumentException( "ldc of a handle requires at least version 1.7"); } int tag = ((Handle) cst).getTag(); if (tag < Opcodes.H_GETFIELD || tag > Opcodes.H_INVOKEINTERFACE) { throw new IllegalArgumentException("invalid handle tag " + tag); } } else { checkConstant(cst); } } /** * Checks that the given string is a valid unqualified name. * * @param version * the class version. * @param name * the string to be checked. * @param msg * a message to be used in case of error. */ static void checkUnqualifiedName(int version, final String name, final String msg) { if ((version & 0xFFFF) < Opcodes.V1_5) { checkIdentifier(name, msg); } else { for (int i = 0; i < name.length(); ++i) { if (".;[/".indexOf(name.charAt(i)) != -1) { throw new IllegalArgumentException("Invalid " + msg + " (must be a valid unqualified name): " + name); } } } } /** * Checks that the given string is a valid Java identifier. * * @param name * the string to be checked. * @param msg * a message to be used in case of error. */ static void checkIdentifier(final String name, final String msg) { checkIdentifier(name, 0, -1, msg); } /** * Checks that the given substring is a valid Java identifier. * * @param name * the string to be checked. * @param start * index of the first character of the identifier (inclusive). * @param end * index of the last character of the identifier (exclusive). -1 * is equivalent to <tt>name.length()</tt> if name is not * <tt>null</tt>. * @param msg * a message to be used in case of error. */ static void checkIdentifier(final String name, final int start, final int end, final String msg) { if (name == null || (end == -1 ? name.length() <= start : end <= start)) { throw new IllegalArgumentException("Invalid " + msg + " (must not be null or empty)"); } if (!Character.isJavaIdentifierStart(name.charAt(start))) { throw new IllegalArgumentException("Invalid " + msg + " (must be a valid Java identifier): " + name); } int max = end == -1 ? name.length() : end; for (int i = start + 1; i < max; ++i) { if (!Character.isJavaIdentifierPart(name.charAt(i))) { throw new IllegalArgumentException("Invalid " + msg + " (must be a valid Java identifier): " + name); } } } /** * Checks that the given string is a valid Java identifier. * * @param version * the class version. * @param name * the string to be checked. * @param msg * a message to be used in case of error. */ static void checkMethodIdentifier(int version, final String name, final String msg) { if (name == null || name.length() == 0) { throw new IllegalArgumentException("Invalid " + msg + " (must not be null or empty)"); } if ((version & 0xFFFF) >= Opcodes.V1_5) { for (int i = 0; i < name.length(); ++i) { if (".;[/<>".indexOf(name.charAt(i)) != -1) { throw new IllegalArgumentException("Invalid " + msg + " (must be a valid unqualified name): " + name); } } return; } if (!Character.isJavaIdentifierStart(name.charAt(0))) { throw new IllegalArgumentException( "Invalid " + msg + " (must be a '<init>', '<clinit>' or a valid Java identifier): " + name); } for (int i = 1; i < name.length(); ++i) { if (!Character.isJavaIdentifierPart(name.charAt(i))) { throw new IllegalArgumentException( "Invalid " + msg + " (must be '<init>' or '<clinit>' or a valid Java identifier): " + name); } } } /** * Checks that the given string is a valid internal class name. * * @param name * the string to be checked. * @param msg * a message to be used in case of error. */ static void checkInternalName(final String name, final String msg) { if (name == null || name.length() == 0) { throw new IllegalArgumentException("Invalid " + msg + " (must not be null or empty)"); } if (name.charAt(0) == '[') { checkDesc(name, false); } else { checkInternalName(name, 0, -1, msg); } } /** * Checks that the given substring is a valid internal class name. * * @param name * the string to be checked. * @param start * index of the first character of the identifier (inclusive). * @param end * index of the last character of the identifier (exclusive). -1 * is equivalent to <tt>name.length()</tt> if name is not * <tt>null</tt>. * @param msg * a message to be used in case of error. */ static void checkInternalName(final String name, final int start, final int end, final String msg) { int max = end == -1 ? name.length() : end; try { int begin = start; int slash; do { slash = name.indexOf('/', begin + 1); if (slash == -1 || slash > max) { slash = max; } checkIdentifier(name, begin, slash, null); begin = slash + 1; } while (slash != max); } catch (IllegalArgumentException unused) { throw new IllegalArgumentException( "Invalid " + msg + " (must be a fully qualified class name in internal form): " + name); } } /** * Checks that the given string is a valid type descriptor. * * @param desc * the string to be checked. * @param canBeVoid * <tt>true</tt> if <tt>V</tt> can be considered valid. */ static void checkDesc(final String desc, final boolean canBeVoid) { int end = checkDesc(desc, 0, canBeVoid); if (end != desc.length()) { throw new IllegalArgumentException("Invalid descriptor: " + desc); } } /** * Checks that a the given substring is a valid type descriptor. * * @param desc * the string to be checked. * @param start * index of the first character of the identifier (inclusive). * @param canBeVoid * <tt>true</tt> if <tt>V</tt> can be considered valid. * @return the index of the last character of the type decriptor, plus one. */ static int checkDesc(final String desc, final int start, final boolean canBeVoid) { if (desc == null || start >= desc.length()) { throw new IllegalArgumentException( "Invalid type descriptor (must not be null or empty)"); } int index; switch (desc.charAt(start)) { case 'V': if (canBeVoid) { return start + 1; } else { throw new IllegalArgumentException("Invalid descriptor: " + desc); } case 'Z': case 'C': case 'B': case 'S': case 'I': case 'F': case 'J': case 'D': return start + 1; case '[': index = start + 1; while (index < desc.length() && desc.charAt(index) == '[') { ++index; } if (index < desc.length()) { return checkDesc(desc, index, false); } else { throw new IllegalArgumentException("Invalid descriptor: " + desc); } case 'L': index = desc.indexOf(';', start); if (index == -1 || index - start < 2) { throw new IllegalArgumentException("Invalid descriptor: " + desc); } try { checkInternalName(desc, start + 1, index, null); } catch (IllegalArgumentException unused) { throw new IllegalArgumentException("Invalid descriptor: " + desc); } return index + 1; default: throw new IllegalArgumentException("Invalid descriptor: " + desc); } } /** * Checks that the given string is a valid method descriptor. * * @param desc * the string to be checked. */ static void checkMethodDesc(final String desc) { if (desc == null || desc.length() == 0) { throw new IllegalArgumentException( "Invalid method descriptor (must not be null or empty)"); } if (desc.charAt(0) != '(' || desc.length() < 3) { throw new IllegalArgumentException("Invalid descriptor: " + desc); } int start = 1; if (desc.charAt(start) != ')') { do { if (desc.charAt(start) == 'V') { throw new IllegalArgumentException("Invalid descriptor: " + desc); } start = checkDesc(desc, start, false); } while (start < desc.length() && desc.charAt(start) != ')'); } start = checkDesc(desc, start + 1, true); if (start != desc.length()) { throw new IllegalArgumentException("Invalid descriptor: " + desc); } } /** * Checks that the given label is not null. This method can also check that * the label has been visited. * * @param label * the label to be checked. * @param checkVisited * <tt>true</tt> to check that the label has been visited. * @param msg * a message to be used in case of error. */ void checkLabel(final Label label, final boolean checkVisited, final String msg) { if (label == null) { throw new IllegalArgumentException("Invalid " + msg + " (must not be null)"); } if (checkVisited && labels.get(label) == null) { throw new IllegalArgumentException("Invalid " + msg + " (must be visited first)"); } } /** * Checks that the given label is not a label used only for debug purposes. * * @param label * the label to be checked. */ private static void checkNonDebugLabel(final Label label) { Field f = getLabelStatusField(); int status = 0; try { status = f == null ? 0 : ((Integer) f.get(label)).intValue(); } catch (IllegalAccessException e) { throw new Error("Internal error"); } if ((status & 0x01) != 0) { throw new IllegalArgumentException( "Labels used for debug info cannot be reused for control flow"); } } /** * Returns the Field object corresponding to the Label.status field. * * @return the Field object corresponding to the Label.status field. */ private static Field getLabelStatusField() { if (labelStatusField == null) { labelStatusField = getLabelField("a"); if (labelStatusField == null) { labelStatusField = getLabelField("status"); } } return labelStatusField; } /** * Returns the field of the Label class whose name is given. * * @param name * a field name. * @return the field of the Label class whose name is given, or null. */ private static Field getLabelField(final String name) { try { Field f = Label.class.getDeclaredField(name); f.setAccessible(true); return f; } catch (NoSuchFieldException e) { return null; } } }
package com.passel; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.passel.data.Event; import java.util.ArrayList; import java.util.List; public class HomeActivity extends ActionBarActivity { private List<String> eventNames; ArrayAdapter<String> adapter; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); final List<Event> events = ((PasselApplication) getApplication()).getEvents(); eventNames = new ArrayList<>(events.size()); for (Event currentEvent: events) { eventNames.add(currentEvent.getName()); } final ListView eventListView = (ListView) findViewById(R.id.eventListView); eventListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { List<Event> eventList = ((PasselApplication) getApplication()).getEvents(); Intent intent = createEventIntent(eventList.get(position)); intent.putExtra("index", position); startActivity(intent); } }); eventListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { List<Event> eventList = ((PasselApplication) getApplication()).getEvents(); Intent intent = createEventIntent(eventList.get(position)); intent.putExtra("index", position); intent.putExtra("edit", true); startActivity(intent); return true; } }); final SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener( eventListView, new SwipeDismissListViewTouchListener.DismissCallbacks() { @Override public boolean canDismiss(int position) { return true; } @Override public void onDismiss(ListView listView, int[] reverseSortedPositions) { // TODO actually remove event // TODO: Add undo functionality and handle // AOOBException that sometimes pops up for (int position : reverseSortedPositions) { adapter.remove(adapter.getItem(position)); } adapter.notifyDataSetChanged(); } }); eventListView.setOnTouchListener(touchListener); // Setting this scroll listener is required to ensure that // during ListView scrolling, we don't look for swipes. eventListView.setOnScrollListener(touchListener.makeScrollListener()); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, eventNames); // adapter.notifyDataSetChanged(); TODO see if needed eventListView.setAdapter(adapter); final FloatingActionButton fabButton = new FloatingActionButton.Builder(this) .withDrawable(getResources().getDrawable(R.drawable.ic_action_content_add)) .withButtonColor(getResources().getColor(R.color.dark_primary_color)) .withMargins(0, 0, 8, 8) .create(); // Also adds the button to the screen fabButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(HomeActivity.this, NewEventActivity.class); HomeActivity.this.startActivityForResult(myIntent, 2); } }); } Intent createEventIntent(Event event){ Intent intent = new Intent(this, MapEventActivity.class); intent.putExtra("event_name", event.getName()); intent.putExtra("event_time", event.getStart().toString()); intent.putStringArrayListExtra("event_guests", new ArrayList<>(event.getGuests())); intent.putExtra("event_lat", event.getLocation().getLatitude()); intent.putExtra("event_lng", event.getLocation().getLongitude()); return intent; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_home, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: // openSearch(); Intent settingsIntent = new Intent(HomeActivity.this, SettingsActivity.class); HomeActivity.this.startActivity(settingsIntent); return true; /* case R.id.action_create: Intent myIntent = new Intent(HomeActivity.this, NewEventActivity.class); // myIntent.putExtra("key", value); //Optional parameters HomeActivity.this.startActivity(myIntent); return true;*/ default: return super.onOptionsItemSelected(item); } } private void refreshEvents(){ // eventList = new ArrayList<>(); // eventNameList = new ArrayList<>(); // adapter.notifyDataSetChanged(); // for (PasselEvent currentEvent: getPasselEvents()){ // Log.d("HomeActivity: ",currentEvent.getEventName()); // addEvent(currentEvent); recreate(); } /* Called when the map activity's finished */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case 2: if (resultCode == RESULT_OK) { Log.d("I'm here!", "ok"); refreshEvents(); } break; } } }
package codeOrchestra.colt.core; import codeOrchestra.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; /** * @author Alexander Eliseyev */ public class RecentProjects { private static final String RECENT_COLT_PROJECTS = "recentCOLTProjects"; private static Preferences preferences = Preferences.userNodeForPackage(RecentProjects.class); public static void addRecentProject(String path) { List<String> paths = getRecentProjectsPaths(); if (paths.contains(path)) { paths.remove(path); } paths.add(0, path); preferences.put(RECENT_COLT_PROJECTS, createList(paths)); try { preferences.sync(); } catch (BackingStoreException e) { // ignore } } public static List<String> getRecentProjectsPaths() { return parseString(preferences.get(RECENT_COLT_PROJECTS, "")); } private static String createList(List<String> list) { StringBuffer path = new StringBuffer("");//$NON-NLS-1$ for (String item : list) { path.append(item); path.append(File.pathSeparator); } return path.toString(); } private static List<String> parseString(String stringList) { List<String> result = new ArrayList<>(); if (StringUtils.isEmpty(stringList)) { return result; } StringTokenizer st = new StringTokenizer(stringList, File.pathSeparator + "\n\r"); while (st.hasMoreElements()) { result.add((String) st.nextElement()); } return result; } public static void clear(String leave) { preferences.put(RECENT_COLT_PROJECTS, leave != null ? leave : ""); } }
package org.koreader.launcher; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Locale; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import android.content.Context; import android.content.res.AssetManager; class AssetsUtils { private static final int BASE_BUFFER_SIZE = 1024; private static final String TAG = "AssetsUtils"; /* do not extract assets if the same version is already installed */ static boolean isSameVersion(Context context, String zipFile) { final String new_version = getPackageRevision(zipFile); try { String output = context.getFilesDir().getAbsolutePath(); FileReader fileReader = new FileReader(output + "/git-rev"); BufferedReader bufferedReader = new BufferedReader(fileReader); String installed_version = bufferedReader.readLine(); bufferedReader.close(); if (new_version.equals(installed_version)) { Logger.i("Skip installation for revision " + new_version); return true; } else { Logger.i("Found new package revision " + new_version); return false; } } catch (Exception e) { Logger.i("Found new package revision " + new_version); return false; } } /* get the first zip file inside the assets module */ static String getZipFile(Context context) { AssetManager assetManager = context.getAssets(); try { String[] assets = assetManager.list("module"); if (assets != null) { for (String asset : assets) { if (asset.endsWith(".zip")) { return asset; } } } return null; } catch (IOException e) { Logger.e(TAG, "error listing assets:\n" + e.toString()); return null; } } /* little programs don't need zipped assets. ie: create a file under assets/module/ called llapp_main.lua, and put there your start code. You can place other files under assets/module and they will be copied too. */ static boolean copyUncompressedAssets(Context context) { AssetManager assetManager = context.getAssets(); String assets_dir = context.getFilesDir().getAbsolutePath(); // llapp_main.lua is the entry point for frontend code. boolean entry_point = false; try { String[] assets = assetManager.list("module"); if (assets != null) { for (String asset : assets) { File file = new File(assets_dir, asset); InputStream input = assetManager.open("module/" + asset); OutputStream output = new FileOutputStream(file); Logger.d(TAG, "copying " + asset + " to " + file.getAbsolutePath()); copyFile(input, output); input.close(); output.flush(); output.close(); if ("llapp_main.lua".equals(asset)) { entry_point = true; } } } } catch (IOException e) { Logger.e(TAG, "error with raw assets:\n" + e.toString()); entry_point = false; } return entry_point; } /* unzip from stream */ static void unzip(InputStream stream, String output) { byte[] buffer = new byte[BASE_BUFFER_SIZE * 512]; int new_files = 0; int updated_files = 0; try { ZipInputStream inputStream = new ZipInputStream(stream); ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) { dirChecker(output, zipEntry.getName()); } else { File f = new File(output, zipEntry.getName()); if (f.exists()) { updated_files = ++updated_files; } else { new_files = ++new_files; boolean success = f.createNewFile(); if (!success) { Logger.w(TAG, "Failed to create file " + f.getName()); continue; } } FileOutputStream outputStream = new FileOutputStream(f); int count; while ((count = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, count); } inputStream.closeEntry(); outputStream.close(); } } inputStream.close(); Logger.i(String.format(Locale.US, "Assets extracted without errors: %d updated, %d new", updated_files, new_files)); } catch (Exception e) { Logger.e(TAG, "Error extracting assets:\n" + e.toString()); } } /* get package revision from zipFile name. Zips must use the scheme: name-revision.zip */ private static String getPackageRevision(String zipFile) { String zipName = zipFile.replace(".zip",""); String[] parts = zipName.split("-"); return zipName.replace(parts[0] + "-", ""); } /* copy files from stream */ private static void copyFile(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[BASE_BUFFER_SIZE]; int read; while((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } } /* create new folders on demand */ private static void dirChecker(String path, String file) { File f = new File(path, file); if (!f.isDirectory()) { boolean success = f.mkdirs(); if (!success) { Logger.w(TAG, "failed to create folder " + f.getName()); } } } }
package org.eclipse.xtext.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; /** * @author Moritz Eysholdt - Initial contribution and API */ public abstract class GraphvizDotBuilder { protected static final Logger log = Logger.getLogger(GraphvizDotBuilder.class); protected class Digraph extends Props { private static final long serialVersionUID = -8103262357417982098L; private List<Edge> edges = new ArrayList<Edge>(); private List<Node> nodes = new ArrayList<Node>(); public Digraph() { super(); } public void add(Props child) { if (child instanceof Node) nodes.add((Node) child); else if (child instanceof Edge) edges.add((Edge) child); else throw new RuntimeException("Unknown child type"); } @Override public void draw(PrintStream out) { out.println("digraph G {"); for (Node n : nodes) n.draw(out); for (Edge e : edges) e.draw(out); out.println("}"); out.println(); } } protected class Edge extends Props { private static final long serialVersionUID = 1941409538047058551L; private Object dst; private Object src; public Edge(Object src, Object dst) { this.src = src; this.dst = dst; } @Override public void draw(PrintStream out) { out.println(id(src) + "->" + id(dst) + " [" + this + "];"); } public void setNoConstraint() { put("constraint", "false"); } } protected class Node extends Props { private static final long serialVersionUID = 758381202465081606L; private Object obj; public Node(Object obj) { this.obj = obj; } public Node(Object obj, String label) { this(obj); setLabel(label); } public Node(Object obj, String label, String shape) { this(obj, label); setShape(shape); } @Override public void draw(PrintStream out) { out.println(id(obj) + " [" + this + "];"); } // record, diamond, etc. public void setShape(String shape) { put("shape", shape); } } protected abstract class Props extends HashMap<String, String> { private static final long serialVersionUID = 414470084198132521L; public abstract void draw(PrintStream out); protected String esc(String s) { if (noEsc.matcher(s).matches()) return s; return "\"" + s.replaceAll("\"|\\[|\\]|>|<|&", "\\\\$0") + "\""; } public void print(PrintStream out) { for (Map.Entry<String, String> e : entrySet()) out.println(e.getKey() + "=" + esc(e.getValue()) + ";"); } public void setLabel(String label) { put("label", label); } public void setStyle(String style) { put("style", style); } @Override public String toString() { if (size() == 0) return ""; StringBuffer b = new StringBuffer(); Iterator<Map.Entry<String, String>> i = entrySet().iterator(); Map.Entry<String, String> e = i.next(); b.append(e.getKey() + "=" + esc(e.getValue())); while (i.hasNext()) { e = i.next(); b.append("," + e.getKey() + "=" + esc(e.getValue())); } return b.toString(); } } private static final Pattern noEsc = Pattern.compile("[a-zA-Z0-9]+"); public String draw(Object obj) { ByteArrayOutputStream ba = new ByteArrayOutputStream(); draw(obj, new PrintStream(ba)); return ba.toString(); } public void draw(Object obj, PrintStream out) { out.println(" out.println("## You can use the command " + "'dot -Tpdf this.dot > out.pdf' to render it."); drawObject(obj).draw(out); } // example options: "-v -T png" public void draw(Object obj, String outfile, String options) throws IOException { String cmd = getGraphvizBinary() + " -o " + outfile + " " + options; draw(obj, cmd); } public void draw(Object obj, String cmd) throws IOException { log.info("Running '" + cmd + "' in '" + new File(".").getCanonicalPath() + "'"); Process p = Runtime.getRuntime().exec(cmd); PrintStream ps = new PrintStream(p.getOutputStream()); BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedInputStream err = new BufferedInputStream(p.getErrorStream()); draw(obj, ps); ps.close(); int b; ByteArrayOutputStream oerr = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((b = err.read()) >= 0) oerr.write(b); while ((b = in.read()) >= 0) out.write(b); if (oerr.size() > 0) log.info("Graphviz output to stderr: \n" + oerr.toString()); if (out.size() > 0) log.info("Graphviz output to stdout: \n" + out.toString()); } protected abstract Props drawObject(Object obj); protected String getGraphvizBinary() { return "/opt/local/bin/dot"; } protected String id(Object cls) { if (cls == null) return null; if (cls instanceof EPackage) return "cluster" + cls.hashCode(); if (cls instanceof EObject) return ((EObject) cls).eClass().getName().toLowerCase() + cls.hashCode(); return cls.getClass().getSimpleName().toLowerCase() + cls.hashCode(); } }
package com.ecyrd.jspwiki.plugin; import java.io.*; import java.net.URL; import java.util.*; import org.apache.commons.lang.ClassUtils; import org.apache.ecs.xhtml.*; import org.apache.log4j.Logger; import org.apache.oro.text.regex.*; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.modules.ModuleManager; import com.ecyrd.jspwiki.modules.WikiModuleInfo; import com.ecyrd.jspwiki.parser.PluginContent; import com.ecyrd.jspwiki.util.ClassUtil; /** * Manages plugin classes. There exists a single instance of PluginManager * per each instance of WikiEngine, that is, each JSPWiki instance. * <P> * A plugin is defined to have three parts: * <OL> * <li>The plugin class * <li>The plugin parameters * <li>The plugin body * </ol> * * For example, in the following line of code: * <pre> * [{INSERT com.ecyrd.jspwiki.plugin.FunnyPlugin foo='bar' * blob='goo' * * abcdefghijklmnopqrstuvw * 01234567890}] * </pre> * * The plugin class is "com.ecyrd.jspwiki.plugin.FunnyPlugin", the * parameters are "foo" and "blob" (having values "bar" and "goo", * respectively), and the plugin body is then * "abcdefghijklmnopqrstuvw\n01234567890". The plugin body is * accessible via a special parameter called "_body". * <p> * If the parameter "debug" is set to "true" for the plugin, * JSPWiki will output debugging information directly to the page if there * is an exception. * <P> * The class name can be shortened, and marked without the package. * For example, "FunnyPlugin" would be expanded to * "com.ecyrd.jspwiki.plugin.FunnyPlugin" automatically. It is also * possible to defined other packages, by setting the * "jspwiki.plugin.searchPath" property. See the included * jspwiki.properties file for examples. * <P> * Even though the nominal way of writing the plugin is * <pre> * [{INSERT pluginclass WHERE param1=value1...}], * </pre> * it is possible to shorten this quite a lot, by skipping the * INSERT, and WHERE words, and dropping the package name. For * example: * * <pre> * [{INSERT com.ecyrd.jspwiki.plugin.Counter WHERE name='foo'}] * </pre> * * is the same as * <pre> * [{Counter name='foo'}] * </pre> * <h3>Plugin property files</h3> * <p> * Since 2.3.25 you can also define a generic plugin XML properties file per * each JAR file. * <pre> * <modules> * <plugin class="com.ecyrd.jspwiki.foo.TestPlugin"> * <author>Janne Jalkanen</author> * <script>foo.js</script> * <stylesheet>foo.css</stylesheet> * <alias>code</alias> * </plugin> * <plugin class="com.ecyrd.jspwiki.foo.TestPlugin2"> * <author>Janne Jalkanen</author> * </plugin> * </modules> * </pre> * <h3>Plugin lifecycle</h3> * * <p>Plugin can implement multiple interfaces to let JSPWiki know at which stages they should * be invoked: * <ul> * <li>InitializablePlugin: If your plugin implements this interface, the initialize()-method is * called once for this class * before any actual execute() methods are called. You should use the initialize() for e.g. * precalculating things. But notice that this method is really called only once during the * entire WikiEngine lifetime. The InitializablePlugin is available from 2.5.30 onwards.</li> * <li>ParserStagePlugin: If you implement this interface, the executeParse() method is called * when JSPWiki is forming the DOM tree. You will receive an incomplete DOM tree, as well * as the regular parameters. However, since JSPWiki caches the DOM tree to speed up later * places, which means that whatever this method returns would be irrelevant. You can do some DOM * tree manipulation, though. The ParserStagePlugin is available from 2.5.30 onwards.</li> * <li>WikiPlugin: The regular kind of plugin which is executed at every rendering stage. Each * new page load is guaranteed to invoke the plugin, unlike with the ParserStagePlugins.</li> * </ul> * * @author Janne Jalkanen * @since 1.6.1 */ public class PluginManager extends ModuleManager { private static final String PLUGIN_INSERT_PATTERN = "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?[ \\t]*"; private static Logger log = Logger.getLogger( PluginManager.class ); /** * This is the default package to try in case the instantiation * fails. */ public static final String DEFAULT_PACKAGE = "com.ecyrd.jspwiki.plugin"; public static final String DEFAULT_FORMS_PACKAGE = "com.ecyrd.jspwiki.forms"; /** * The property name defining which packages will be searched for properties. */ public static final String PROP_SEARCHPATH = "jspwiki.plugin.searchPath"; /** * The name of the body content. Current value is "_body". */ public static final String PARAM_BODY = "_body"; /** * The name of the command line content parameter. The value is "_cmdline". */ public static final String PARAM_CMDLINE = "_cmdline"; /** * The name of the parameter containing the start and end positions in the * read stream of the plugin text (stored as a two-element int[], start * and end resp.). */ public static final String PARAM_BOUNDS = "_bounds"; /** * A special name to be used in case you want to see debug output */ public static final String PARAM_DEBUG = "debug"; private ArrayList m_searchPath = new ArrayList(); private Pattern m_pluginPattern; private boolean m_pluginsEnabled = true; /** * Keeps a list of all known plugin classes. */ private Map m_pluginClassMap = new HashMap(); /** * Create a new PluginManager. * * @param props Contents of a "jspwiki.properties" file. */ public PluginManager( WikiEngine engine, Properties props ) { super(engine); String packageNames = props.getProperty( PROP_SEARCHPATH ); if( packageNames != null ) { StringTokenizer tok = new StringTokenizer( packageNames, "," ); while( tok.hasMoreTokens() ) { m_searchPath.add( tok.nextToken().trim() ); } } registerPlugins(); // The default packages are always added. m_searchPath.add( DEFAULT_PACKAGE ); m_searchPath.add( DEFAULT_FORMS_PACKAGE ); PatternCompiler compiler = new Perl5Compiler(); try { m_pluginPattern = compiler.compile( PLUGIN_INSERT_PATTERN ); } catch( MalformedPatternException e ) { log.fatal("Internal error: someone messed with pluginmanager patterns.", e ); throw new InternalWikiException( "PluginManager patterns are broken" ); } } /** * Enables or disables plugin execution. */ public void enablePlugins( boolean enabled ) { m_pluginsEnabled = enabled; } /** * Returns plugin execution status. If false, plugins are not * executed when they are encountered on a WikiPage, and an * empty string is returned in their place. */ public boolean pluginsEnabled() { return m_pluginsEnabled; } /** * Returns true if the link is really command to insert * a plugin. * <P> * Currently we just check if the link starts with "{INSERT", * or just plain "{" but not "{$". * * @param link Link text, i.e. the contents of text between []. * @return True, if this link seems to be a command to insert a plugin here. */ public static boolean isPluginLink( String link ) { return link.startsWith("{INSERT") || (link.startsWith("{") && !link.startsWith("{$")); } /** * Attempts to locate a plugin class from the class path * set in the property file. * * @param classname Either a fully fledged class name, or just * the name of the file (that is, * "com.ecyrd.jspwiki.plugin.Counter" or just plain "Counter"). * * @return A found class. * * @throws ClassNotFoundException if no such class exists. */ private Class findPluginClass( String classname ) throws ClassNotFoundException { return ClassUtil.findClass( m_searchPath, classname ); } /** * Outputs a HTML-formatted version of a stack trace. */ private String stackTrace( Map params, Throwable t ) { div d = new div(); d.setClass("debug"); d.addElement("Plugin execution failed, stack trace follows:"); StringWriter out = new StringWriter(); t.printStackTrace( new PrintWriter(out) ); d.addElement( new pre( out.toString() ) ); d.addElement( new b( "Parameters to the plugin" ) ); ul list = new ul(); for( Iterator i = params.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry) i.next(); String key = (String)e.getKey(); list.addElement(new li( key+"'='"+e.getValue() ) ); } d.addElement( list ); return d.toString(); } /** * Executes a plugin class in the given context. * <P>Used to be private, but is public since 1.9.21. * * @param context The current WikiContext. * @param classname The name of the class. Can also be a * shortened version without the package name, since the class name is searched from the * package search path. * * @param params A parsed map of key-value pairs. * * @return Whatever the plugin returns. * * @throws PluginException If the plugin execution failed for * some reason. * * @since 2.0 */ public String execute( WikiContext context, String classname, Map params ) throws PluginException { if( !m_pluginsEnabled ) return ""; try { WikiPlugin plugin; boolean debug = TextUtil.isPositive( (String) params.get( PARAM_DEBUG ) ); WikiPluginInfo pluginInfo = (WikiPluginInfo) m_pluginClassMap.get(classname); if(pluginInfo == null) { pluginInfo = WikiPluginInfo.newInstance(findPluginClass( classname )); registerPlugin(pluginInfo); } if( !checkCompatibility(pluginInfo) ) { String msg = "Plugin '"+pluginInfo.getName()+"' not compatible with this version of JSPWiki"; log.info(msg); return msg; } // Create... try { plugin = pluginInfo.newPluginInstance(); } catch( InstantiationException e ) { throw new PluginException( "Cannot instantiate plugin "+classname, e ); } catch( IllegalAccessException e ) { throw new PluginException( "Not allowed to access plugin "+classname, e ); } catch( Exception e ) { throw new PluginException( "Instantiation of plugin "+classname+" failed.", e ); } // ...and launch. try { return plugin.execute( context, params ); } catch( PluginException e ) { if( debug ) { return stackTrace( params, e ); } // Just pass this exception onward. throw (PluginException) e.fillInStackTrace(); } catch( Throwable t ) { // But all others get captured here. log.info( "Plugin failed while executing:", t ); if( debug ) { return stackTrace( params, t ); } throw new PluginException( "Plugin failed", t ); } } catch( ClassNotFoundException e ) { throw new PluginException( "Could not find plugin "+classname, e ); } catch( ClassCastException e ) { throw new PluginException( "Class "+classname+" is not a Wiki plugin.", e ); } } /** * Parses plugin arguments. Handles quotes and all other kewl stuff. * * <h3>Special parameters</h3> * The plugin body is put into a special parameter defined by {@link #PARAM_BODY}; * the plugin's command line into a parameter defined by {@link #PARAM_CMDLINE}; * and the bounds of the plugin within the wiki page text by a parameter defined * by {@link #PARAM_BOUNDS}, whose value is stored as a two-element int[] array, * i.e., <tt>[start,end]</tt>. * * @param argstring The argument string to the plugin. This is * typically a list of key-value pairs, using "'" to escape * spaces in strings, followed by an empty line and then the * plugin body. In case the parameter is null, will return an * empty parameter list. * * @return A parsed list of parameters. * * @throws IOException If the parsing fails. */ public Map parseArgs( String argstring ) throws IOException { HashMap arglist = new HashMap(); // Protection against funny users. if( argstring == null ) return arglist; arglist.put( PARAM_CMDLINE, argstring ); StringReader in = new StringReader(argstring); StreamTokenizer tok = new StreamTokenizer(in); int type; String param = null; String value = null; tok.eolIsSignificant( true ); boolean potentialEmptyLine = false; boolean quit = false; while( !quit ) { String s; type = tok.nextToken(); switch( type ) { case StreamTokenizer.TT_EOF: quit = true; s = null; break; case StreamTokenizer.TT_WORD: s = tok.sval; potentialEmptyLine = false; break; case StreamTokenizer.TT_EOL: quit = potentialEmptyLine; potentialEmptyLine = true; s = null; break; case StreamTokenizer.TT_NUMBER: s = Integer.toString( new Double(tok.nval).intValue() ); potentialEmptyLine = false; break; case '\'': s = tok.sval; break; default: s = null; } // Assume that alternate words on the line are // parameter and value, respectively. if( s != null ) { if( param == null ) { param = s; } else { value = s; arglist.put( param, value ); // log.debug("ARG: "+param+"="+value); param = null; } } } // Now, we'll check the body. if( potentialEmptyLine ) { StringWriter out = new StringWriter(); FileUtil.copyContents( in, out ); String bodyContent = out.toString(); if( bodyContent != null ) { arglist.put( PARAM_BODY, bodyContent ); } } return arglist; } /** * Parses a plugin. Plugin commands are of the form: * [{INSERT myplugin WHERE param1=value1, param2=value2}] * myplugin may either be a class name or a plugin alias. * <P> * This is the main entry point that is used. * * @param context The current WikiContext. * @param commandline The full command line, including plugin * name, parameters and body. * * @return HTML as returned by the plugin, or possibly an error * message. */ public String execute( WikiContext context, String commandline ) throws PluginException { if( !m_pluginsEnabled ) return ""; PatternMatcher matcher = new Perl5Matcher(); try { if( matcher.contains( commandline, m_pluginPattern ) ) { MatchResult res = matcher.getMatch(); String plugin = res.group(2); String args = commandline.substring(res.endOffset(0), commandline.length() - (commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) ); Map arglist = parseArgs( args ); return execute( context, plugin, arglist ); } } catch( NoSuchElementException e ) { String msg = "Missing parameter in plugin definition: "+commandline; log.warn( msg, e ); throw new PluginException( msg ); } catch( IOException e ) { String msg = "Zyrf. Problems with parsing arguments: "+commandline; log.warn( msg, e ); throw new PluginException( msg ); } // FIXME: We could either return an empty string "", or // the original line. If we want unsuccessful requests // to be invisible, then we should return an empty string. return commandline; } public PluginContent parsePluginLine( WikiContext context, String commandline, int pos ) throws PluginException { PatternMatcher matcher = new Perl5Matcher(); try { if( matcher.contains( commandline, m_pluginPattern ) ) { MatchResult res = matcher.getMatch(); String plugin = res.group(2); String args = commandline.substring(res.endOffset(0), commandline.length() - (commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) ); Map arglist = parseArgs( args ); // set wikitext bounds of plugin as '_bounds' parameter, e.g., [345,396] if ( pos != -1 ) { int end = pos + commandline.length() + 2; int[] bounds = new int[] { pos, end }; arglist.put( PARAM_BOUNDS, bounds ); } PluginContent result = new PluginContent( plugin, arglist ); return result; } } catch( ClassCastException e ) { log.error( "Invalid type offered in parsing plugin arguments.", e ); throw new InternalWikiException("Oops, someone offered !String!"); } catch( NoSuchElementException e ) { String msg = "Missing parameter in plugin definition: "+commandline; log.warn( msg, e ); throw new PluginException( msg ); } catch( IOException e ) { String msg = "Zyrf. Problems with parsing arguments: "+commandline; log.warn( msg, e ); throw new PluginException( msg ); } return null; } /** * Register a plugin. */ private void registerPlugin(WikiPluginInfo pluginClass) { String name; // Registrar the plugin with the className without the package-part name = pluginClass.getName(); if(name != null) { log.debug("Registering plugin [name]: " + name); m_pluginClassMap.put(name, pluginClass); } // Registrar the plugin with a short convenient name. name = pluginClass.getAlias(); if(name != null) { log.debug("Registering plugin [shortName]: " + name); m_pluginClassMap.put(name, pluginClass); } // Registrar the plugin with the className with the package-part name = pluginClass.getClassName(); if(name != null) { log.debug("Registering plugin [className]: " + name); m_pluginClassMap.put(name, pluginClass); } pluginClass.initializePlugin( m_engine ); } private void registerPlugins() { log.info( "Registering plugins" ); SAXBuilder builder = new SAXBuilder(); try { // Register all plugins which have created a resource containing its properties. // Get all resources of all plugins. Enumeration resources = getClass().getClassLoader().getResources( PLUGIN_RESOURCE_LOCATION ); while( resources.hasMoreElements() ) { URL resource = (URL) resources.nextElement(); try { log.debug( "Processing XML: " + resource ); Document doc = builder.build( resource ); List plugins = XPath.selectNodes( doc, "/modules/plugin"); for( Iterator i = plugins.iterator(); i.hasNext(); ) { Element pluginEl = (Element) i.next(); String className = pluginEl.getAttributeValue("class"); WikiPluginInfo pluginInfo = WikiPluginInfo.newInstance( className, pluginEl ); if( pluginInfo != null ) { registerPlugin( pluginInfo ); } } } catch( java.io.IOException e ) { log.error( "Couldn't load " + PLUGIN_RESOURCE_LOCATION + " resources: " + resource, e ); } catch( JDOMException e ) { log.error( "Error parsing XML for plugin: "+PLUGIN_RESOURCE_LOCATION ); } } } catch( java.io.IOException e ) { log.error( "Couldn't load all " + PLUGIN_RESOURCE_LOCATION + " resources", e ); } } /** * Contains information about a bunch of plugins. * * @author Kees Kuip * @author Janne Jalkanen * * @since */ // FIXME: This class needs a better interface to return all sorts of possible // information from the plugin XML. In fact, it probably should have // some sort of a superclass system. public static final class WikiPluginInfo extends WikiModuleInfo { private String m_className; private String m_alias; private Class m_clazz; private boolean m_initialized = false; /** * Creates a new plugin info object which can be used to access a plugin. * * @param className Either a fully qualified class name, or a "short" name which is then * checked against the internal list of plugin packages. * @param el A JDOM Element containing the information about this class. * @return A WikiPluginInfo object. */ protected static WikiPluginInfo newInstance( String className, Element el ) { if( className == null || className.length() == 0 ) return null; WikiPluginInfo info = new WikiPluginInfo( className ); info.initializeFromXML( el ); return info; } /** * Initializes a plugin, if it has not yet been initialized. * * @param engine */ protected void initializePlugin( WikiEngine engine ) { if( !m_initialized ) { // This makes sure we only try once per class, even if init fails. m_initialized = true; try { WikiPlugin p = newPluginInstance(); if( p instanceof InitializablePlugin ) { ((InitializablePlugin)p).initialize( engine ); } } catch( Exception e ) { log.info( "Cannot initialize plugin "+m_className, e ); } } } protected void initializeFromXML( Element el ) { super.initializeFromXML( el ); m_alias = el.getChildText("alias"); } protected static WikiPluginInfo newInstance( Class clazz ) { WikiPluginInfo info = new WikiPluginInfo( clazz.getName() ); return info; } private WikiPluginInfo( String className ) { super(className); setClassName( className ); } private void setClassName( String fullClassName ) { m_name = ClassUtils.getShortClassName( fullClassName ); m_className = fullClassName; } /** * Returns the full class name of this object. * @return The full class name of the object. */ public String getClassName() { return m_className; } /** * Returns the alias name for this object. * @return An alias name for the plugin. */ public String getAlias() { return m_alias; } public WikiPlugin newPluginInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException { if( m_clazz == null ) { m_clazz = Class.forName(m_className); } return (WikiPlugin) m_clazz.newInstance(); } /** * Returns a text for IncludeResources. * * @param type Either "script" or "stylesheet" * @return Text, or an empty string, if there is nothing to be included. */ public String getIncludeText(String type) { try { if( type.equals("script") ) { return getScriptText(); } else if( type.equals("stylesheet") ) { return getStylesheetText(); } } catch( Exception ex ) { // We want to fail gracefully here return ex.getMessage(); } return null; } private String getScriptText() throws IOException { if( m_scriptText != null ) { return m_scriptText; } if( m_scriptLocation == null ) { return ""; } try { m_scriptText = getTextResource(m_scriptLocation); } catch( IOException ex ) { // Only throw this exception once! m_scriptText = ""; throw ex; } return m_scriptText; } private String getStylesheetText() throws IOException { if( m_stylesheetText != null ) { return m_stylesheetText; } if( m_stylesheetLocation == null ) { return ""; } try { m_stylesheetText = getTextResource(m_stylesheetLocation); } catch( IOException ex ) { // Only throw this exception once! m_stylesheetText = ""; throw ex; } return m_stylesheetText; } /** * Returns a string suitable for debugging. Don't assume that the format * would stay the same. */ public String toString() { return "Plugin :[name=" + m_name + "][className=" + m_className + "]"; } } // WikiPluginClass /** * {@inheritDoc} */ public Collection modules() { TreeSet ls = new TreeSet(); for( Iterator i = m_pluginClassMap.values().iterator(); i.hasNext(); ) { WikiModuleInfo wmi = (WikiModuleInfo)i.next(); if( !ls.contains(wmi) ) ls.add(wmi); } return ls; } // FIXME: This method needs to be reintegrated with execute() above, since they // share plenty of code. public void executeParse(PluginContent content, WikiContext context) throws PluginException { if( !m_pluginsEnabled ) return; Map params = content.getParameters(); try { WikiPlugin plugin; WikiPluginInfo pluginInfo = (WikiPluginInfo) m_pluginClassMap.get( content.getPluginName() ); if(pluginInfo == null) { pluginInfo = WikiPluginInfo.newInstance(findPluginClass( content.getPluginName() )); registerPlugin(pluginInfo); } if( !checkCompatibility(pluginInfo) ) { String msg = "Plugin '"+pluginInfo.getName()+"' not compatible with this version of JSPWiki"; log.info(msg); return; } plugin = pluginInfo.newPluginInstance(); if( plugin instanceof ParserStagePlugin ) { ((ParserStagePlugin)plugin).executeParser( content, context, params ); } } catch( InstantiationException e ) { throw new PluginException( "Cannot instantiate plugin "+content.getPluginName(), e ); } catch( IllegalAccessException e ) { throw new PluginException( "Not allowed to access plugin "+content.getPluginName(), e ); } catch( ClassNotFoundException e ) { throw new PluginException( "Could not find plugin "+content.getPluginName() ); } catch( ClassCastException e ) { throw new PluginException( "Class "+content.getPluginName()+" is not a Wiki plugin.", e ); } catch( Exception e ) { throw new PluginException( "Instantiation of plugin "+content.getPluginName()+" failed.", e ); } } }
package org.lockss.plugin.royalsocietyofchemistry; import java.net.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.lockss.test.*; import org.lockss.util.ListUtil; import org.lockss.util.PatternFloatMap; import org.lockss.util.RegexpUtil; import org.lockss.plugin.*; import org.lockss.config.Configuration; import org.lockss.daemon.*; import org.lockss.extractor.*; import org.lockss.plugin.ArchivalUnit.*; import org.lockss.plugin.definable.*; import org.lockss.plugin.wrapper.WrapperUtil; public class TestRSC2014Plugin extends LockssTestCase { static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey(); static final String RESOLVER_URL_KEY = "resolver_url"; static final String GRAPHICS_URL_KEY = "graphics_url"; static final String BASE_URL2_KEY = ConfigParamDescr.BASE_URL2.getKey(); static final String JOURNAL_CODE_KEY = "journal_code"; static final String VOLUME_NAME_KEY = ConfigParamDescr.VOLUME_NAME.getKey(); static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey(); static final String GRAPHICS_URL = "http://sod-a.img-cdn.com/"; // from au_url_poll_result_weight in plugins/src/org/lockss/plugin/royalsocietyofchemistry/RSC2014Plugin.xml // <string>"%spubs-core/", graphics_url</string> // Note diff: the funky escaped chars, there is probably a call to do the conversion // if it changes in the plugin, you will likely need to change the test, so verify static final String[] REPAIR_FROM_PEER_REGEXP = new String[] { "rsc-cdn\\.org/(pubs-core/|.*logo[.]png)", "[.](css|js)($|\\?)"}; private DefinablePlugin plugin; public TestRSC2014Plugin(String msg) { super(msg); } public void setUp() throws Exception { super.setUp(); plugin = new DefinablePlugin(); plugin.initPlugin(getMockLockssDaemon(), "org.lockss.plugin.royalsocietyofchemistry.ClockssRSC2014Plugin"); } public void testGetAuNullConfig() throws ArchivalUnit.ConfigurationException { try { plugin.configureAu(null, null); fail("Didn't throw ArchivalUnit.ConfigurationException"); } catch (ArchivalUnit.ConfigurationException e) { } } public void testCreateAu() { Properties props = new Properties(); props.setProperty(BASE_URL_KEY, "http://pubs.example.com/"); props.setProperty(RESOLVER_URL_KEY, "http://xlink.example.com/"); props.setProperty(GRAPHICS_URL_KEY, GRAPHICS_URL); props.setProperty(BASE_URL2_KEY, "http: props.setProperty(JOURNAL_CODE_KEY, "an"); props.setProperty(VOLUME_NAME_KEY, "123"); props.setProperty(YEAR_KEY, "2013"); DefinableArchivalUnit au = null; try { au = makeAuFromProps(props); } catch (ConfigurationException ex) { au = null; } au.getName(); } private DefinableArchivalUnit makeAuFromProps(Properties props) throws ArchivalUnit.ConfigurationException { Configuration config = ConfigurationUtil.fromProps(props); return (DefinableArchivalUnit)plugin.configureAu(config, null); } public void testGetAuHandlesBadUrl() throws ArchivalUnit.ConfigurationException, MalformedURLException { Properties props = new Properties(); props.setProperty(BASE_URL_KEY, "blah"); props.setProperty(RESOLVER_URL_KEY, "blah3"); props.setProperty(GRAPHICS_URL_KEY, "blah4"); props.setProperty(BASE_URL2_KEY, "blah2"); props.setProperty(JOURNAL_CODE_KEY, "an"); props.setProperty(VOLUME_NAME_KEY, "9"); props.setProperty(YEAR_KEY, "2001"); try { DefinableArchivalUnit au = makeAuFromProps(props); fail ("Didn't throw InstantiationException when given a bad url"); } catch (ArchivalUnit.ConfigurationException auie) { assertNotNull(auie.getCause()); } } public void testGetAuConstructsProperAu() throws ArchivalUnit.ConfigurationException, MalformedURLException { Properties props = new Properties(); props.setProperty(BASE_URL_KEY, "http://pubs.example.com/"); props.setProperty(RESOLVER_URL_KEY, "http://xlink.example.com/"); props.setProperty(GRAPHICS_URL_KEY, GRAPHICS_URL); props.setProperty(BASE_URL2_KEY, "http: props.setProperty(JOURNAL_CODE_KEY, "an"); props.setProperty(VOLUME_NAME_KEY, "123"); props.setProperty(YEAR_KEY, "2013"); DefinableArchivalUnit au = makeAuFromProps(props); assertEquals("Royal Society of Chemistry 2014 Plugin (CLOCKSS), " + "Base URL http://pubs.example.com/, " + "Base URL2 http: "Resolver URL http://xlink.example.com/, " + "Journal Code an, Volume 123, Year 2013", au.getName()); } public void testGetPluginId() { assertEquals("org.lockss.plugin.royalsocietyofchemistry." + "ClockssRSC2014Plugin", plugin.getPluginId()); } public void testGetArticleMetadataExtractor() { Properties props = new Properties(); props.setProperty(BASE_URL_KEY, "http://pubs.example.com/"); props.setProperty(RESOLVER_URL_KEY, "http://xlink.example.com/"); props.setProperty(GRAPHICS_URL_KEY, GRAPHICS_URL); props.setProperty(BASE_URL2_KEY, "http: props.setProperty(JOURNAL_CODE_KEY, "an"); props.setProperty(VOLUME_NAME_KEY, "123"); props.setProperty(YEAR_KEY, "2013"); DefinableArchivalUnit au = null; try { au = makeAuFromProps(props); } catch (ConfigurationException ex) { } assertTrue(""+plugin.getArticleMetadataExtractor(MetadataTarget.Any(), au), plugin.getArticleMetadataExtractor(null, au) instanceof ArticleMetadataExtractor); assertTrue(""+plugin.getFileMetadataExtractor(MetadataTarget.Any(), "text/html", au), plugin.getFileMetadataExtractor(MetadataTarget.Any(), "text/html", au) instanceof FileMetadataExtractor ); } public void testGetHashFilterFactory() { assertNull(plugin.getHashFilterFactory("BogusFilterFactory")); assertNotNull(plugin.getHashFilterFactory("application/pdf")); assertNotNull(plugin.getHashFilterFactory("text/html")); } public void testGetArticleIteratorFactory() { assertTrue(WrapperUtil.unwrap(plugin.getArticleIteratorFactory()) instanceof org.lockss.plugin.royalsocietyofchemistry.RSC2014ArticleIteratorFactory); } }
package com.example.mymusicplayer; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc319.subsystems; import java.util.Comparator; import java.util.Vector; import org.usfirst.frc319.RobotMap; import org.usfirst.frc319.commands.*; import com.ni.vision.NIVision; import com.ni.vision.NIVision.Image; import com.ni.vision.NIVision.ImageType; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class TowerCamera extends Subsystem { private boolean running = false; //Images int session; Image frame; Image binaryFrame; int imaqError; //Final Constants private static double VIEW_ANGLE = 49.4; //View angle fo camera, set to Axis m1011 by default, 64 for m1013, 51.7 for 206, 52 for HD3000 square, 60 for HD3000 640x480 //Flexible Constants private NIVision.Range RED_TARGET_R_RANGE = new NIVision.Range(100, 255); //Default red range for the red target private NIVision.Range RED_TARGET_G_RANGE = new NIVision.Range(0, 255); //Default green range for the red target private NIVision.Range RED_TARGET_B_RANGE = new NIVision.Range(0, 155); //Default blue range for the red target private NIVision.Range BLU_TARGET_R_RANGE = new NIVision.Range(0, 155); //Default red range for the blue target private NIVision.Range BLU_TARGET_G_RANGE = new NIVision.Range(0, 255); //Default green range for the blue target private NIVision.Range BLU_TARGET_B_RANGE = new NIVision.Range(100, 255); //Default blue range for the blue target private boolean RED_TEAM = false; private boolean BLU_TEAM = false; double AREA_MINIMUM = 0.5; //Default Area minimum for particle as a percentage of total image area double SCORE_MIN = 75.0; //Minimum score to be considered a tote NIVision.ParticleFilterCriteria2 criteria[] = new NIVision.ParticleFilterCriteria2[1]; NIVision.ParticleFilterOptions2 filterOptions = new NIVision.ParticleFilterOptions2(0,0,1,1); Scores scores = new Scores(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND setDefaultCommand(new PauseTowerCamera()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } public void initialize(){ // create images frame = NIVision.imaqCreateImage(ImageType.IMAGE_RGB, 0); binaryFrame = NIVision.imaqCreateImage(ImageType.IMAGE_U8, 0); criteria[0] = new NIVision.ParticleFilterCriteria2(NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA, AREA_MINIMUM, 100.0, 0, 0); // the camera name (ex "cam0") can be found through the roborio web interface session = NIVision.IMAQdxOpenCamera("cam0", NIVision.IMAQdxCameraControlMode.CameraControlModeController); this.initializeDashboard(); } public void run(){ if(!running){ //if we are not currently running, start the camera NIVision.IMAQdxStartAcquisition(session); } //grab the latest image NIVision.IMAQdxGrab(session, frame, 1); this.readDashboard(); if(BLU_TEAM == RED_TEAM){ //THIS IS AN INCOMPATIBLE STATE, SOME ACTION SHOULD BE TAKEN }else if(BLU_TEAM){ //Threshold the image looking for blue target NIVision.imaqColorThreshold(binaryFrame, frame, 255, NIVision.ColorMode.RGB, BLU_TARGET_R_RANGE, BLU_TARGET_G_RANGE, BLU_TARGET_B_RANGE); }else if(RED_TEAM){ //Threshold the image looking for red target NIVision.imaqColorThreshold(binaryFrame, frame, 255, NIVision.ColorMode.RGB, RED_TARGET_R_RANGE, RED_TARGET_G_RANGE, RED_TARGET_B_RANGE); }else{ //THIS IS AN INCOMPATIBLE STATE, SOME ACTION SHOULD BE TAKEN } //Send particle count to dashboard int numParticles = NIVision.imaqCountParticles(binaryFrame, 1); SmartDashboard.putNumber("Masked particles", numParticles); //Send masked image to dashboard to assist in tweaking mask. CameraServer.getInstance().setImage(binaryFrame); //filter out small particles //MWT: IN 2014 WE USED A WIDTH FILTER INSTEAD OF AREA float areaMin = (float)SmartDashboard.getNumber("Area min %", AREA_MINIMUM); criteria[0].lower = areaMin; imaqError = NIVision.imaqParticleFilter4(binaryFrame, binaryFrame, criteria, filterOptions, null); //Send particle count after filtering to dashboard numParticles = NIVision.imaqCountParticles(binaryFrame, 1); SmartDashboard.putNumber("Filtered particles", numParticles); boolean foundTarget = false; double distance = 0d; if(numParticles > 0){ //Measure particles and sort by particle size Vector<ParticleReport> particles = new Vector<ParticleReport>(); //MWT: IN 2014 WE USED A MAX PARTICLE COUNT TO AVOID BOGGING DOWN THE CPU for(int particleIndex = 0; particleIndex < numParticles; particleIndex++){ //MWT: IN 2014 WE USED AN ASPECT RATIO FILTER HERE ParticleReport par = new ParticleReport(); par.PercentAreaToImageArea = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA); par.Area = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_AREA); par.BoundingRectTop = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_TOP); par.BoundingRectLeft = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_LEFT); par.BoundingRectBottom = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_BOTTOM); par.BoundingRectRight = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_RIGHT); particles.add(par); } particles.sort(null); //MWT: IN 2014 WE EXPLICITLY DIDN'T USE THE SCORES MECHANISM //This example only scores the largest particle. Extending to score all particles and choosing the desired one is left as an exercise //for the reader. Note that this scores and reports information about a single particle (single L shaped target). To get accurate information //about the location of the tote (not just the distance) you will need to correlate two adjacent targets in order to find the true center of the tote. scores.Aspect = getApspectScore(particles.elementAt(0)); SmartDashboard.putNumber("Aspect", scores.Aspect); scores.Area = getAreaScore(particles.elementAt(0)); SmartDashboard.putNumber("Area", scores.Area); foundTarget= scores.Aspect > SCORE_MIN && scores.Area > SCORE_MIN; distance = computeDistance(binaryFrame, particles.elementAt(0)); } //MWT: IDEALLY WE WOULD PUT A GREEN AROUND THE IMAGE WHEN THE TARGET IS FOUND AND RED WHEN IT IS NOT //Send distance and tote status to dashboard. The bounding rect, particularly the horizontal center (left - right) may be useful for rotating/driving towards a tote SmartDashboard.putBoolean("Found Target", foundTarget); SmartDashboard.putNumber("Distance", distance); } //MWT: THIS IS NEVER REFERENCED //Comparator function for sorting particles. Returns true if particle 1 is larger static boolean compareParticleSizes(ParticleReport particle1, ParticleReport particle2) { //we want descending sort order return particle1.PercentAreaToImageArea > particle2.PercentAreaToImageArea; } /** * Converts a ratio with ideal value of 1 to a score. The resulting function is piecewise * linear going from (0,0) to (1,100) to (2,0) and is 0 for all inputs outside the range 0-2 */ double ratioToScore(double ratio) { return (Math.max(0, Math.min(100*(1-Math.abs(1-ratio)), 100))); } double getAreaScore(ParticleReport report) { double boundingArea = (report.BoundingRectBottom - report.BoundingRectTop) * (report.BoundingRectRight - report.BoundingRectLeft); //Tape is 7" edge so 49" bounding rect. With 2" wide tape it covers 24" of the rect. return ratioToScore((49/24)*report.Area/boundingArea); } /** * Method to score if the aspect ratio of the particle appears to match the retro-reflective target. Target is 7"x7" so aspect should be 1 */ double getApspectScore(ParticleReport report) { return ratioToScore(((report.BoundingRectRight-report.BoundingRectLeft)/(report.BoundingRectBottom-report.BoundingRectTop))); } /** * Computes the estimated distance to a target using the width of the particle in the image. For more information and graphics * showing the math behind this approach see the Vision Processing section of the ScreenStepsLive documentation. * * @param image The image to use for measuring the particle estimated rectangle * @param report The Particle Analysis Report for the particle * @param isLong Boolean indicating if the target is believed to be the long side of a tote * @return The estimated distance to the target in feet. */ double computeDistance (Image image, ParticleReport report) { double normalizedWidth, targetWidth; NIVision.GetImageSizeResult size; size = NIVision.imaqGetImageSize(image); normalizedWidth = 2*(report.BoundingRectRight - report.BoundingRectLeft)/size.width; targetWidth = 7; return targetWidth/(normalizedWidth*12*Math.tan(VIEW_ANGLE*Math.PI/(180*2))); } private void initializeDashboard(){ //Put default values to SmartDashboard so fields will appear SmartDashboard.putNumber("RED TARGET (R min)", RED_TARGET_R_RANGE.minValue); SmartDashboard.putNumber("RED TARGET (R max)", RED_TARGET_R_RANGE.maxValue); SmartDashboard.putNumber("RED TARGET (G min)", RED_TARGET_G_RANGE.minValue); SmartDashboard.putNumber("RED TARGET (G max)", RED_TARGET_G_RANGE.maxValue); SmartDashboard.putNumber("RED TARGET (B min)", RED_TARGET_B_RANGE.minValue); SmartDashboard.putNumber("RED TARGET (B max)", RED_TARGET_B_RANGE.maxValue); SmartDashboard.putNumber("BLUE TARGET (R min)", BLU_TARGET_R_RANGE.minValue); SmartDashboard.putNumber("BLUE TARGET (R max)", BLU_TARGET_R_RANGE.maxValue); SmartDashboard.putNumber("BLUE TARGET (G min)", BLU_TARGET_G_RANGE.minValue); SmartDashboard.putNumber("BLUE TARGET (G max)", BLU_TARGET_G_RANGE.maxValue); SmartDashboard.putNumber("BLUE TARGET (B min)", BLU_TARGET_B_RANGE.minValue); SmartDashboard.putNumber("BLUE TARGET (B max)", BLU_TARGET_B_RANGE.maxValue); SmartDashboard.putBoolean("RED TEAM", RED_TEAM); SmartDashboard.putBoolean("BLUE TEAM", BLU_TEAM); SmartDashboard.putNumber("Area min %", AREA_MINIMUM); } private void readDashboard(){ //Update threshold values from SmartDashboard. For performance reasons it is recommended to remove this after calibration is finished. RED_TARGET_R_RANGE.minValue = (int)SmartDashboard.getNumber("RED TARGET (R min)", RED_TARGET_R_RANGE.minValue); RED_TARGET_R_RANGE.maxValue = (int)SmartDashboard.getNumber("RED TARGET (R max)", RED_TARGET_R_RANGE.maxValue); RED_TARGET_G_RANGE.minValue = (int)SmartDashboard.getNumber("RED TARGET (G min)", RED_TARGET_G_RANGE.minValue); RED_TARGET_G_RANGE.maxValue = (int)SmartDashboard.getNumber("RED TARGET (G max)", RED_TARGET_G_RANGE.maxValue); RED_TARGET_B_RANGE.minValue = (int)SmartDashboard.getNumber("RED TARGET (B min)", RED_TARGET_B_RANGE.minValue); RED_TARGET_B_RANGE.maxValue = (int)SmartDashboard.getNumber("RED TARGET (B max)", RED_TARGET_B_RANGE.maxValue); BLU_TARGET_R_RANGE.minValue = (int)SmartDashboard.getNumber("BLUE TARGET (R min)", BLU_TARGET_R_RANGE.minValue); BLU_TARGET_R_RANGE.maxValue = (int)SmartDashboard.getNumber("BLUE TARGET (R max)", BLU_TARGET_R_RANGE.maxValue); BLU_TARGET_G_RANGE.minValue = (int)SmartDashboard.getNumber("BLUE TARGET (G min)", BLU_TARGET_G_RANGE.minValue); BLU_TARGET_G_RANGE.maxValue = (int)SmartDashboard.getNumber("BLUE TARGET (G max)", BLU_TARGET_G_RANGE.maxValue); BLU_TARGET_B_RANGE.minValue = (int)SmartDashboard.getNumber("BLUE TARGET (B min)", BLU_TARGET_B_RANGE.minValue); BLU_TARGET_B_RANGE.maxValue = (int)SmartDashboard.getNumber("BLUE TARGET (B max)", BLU_TARGET_B_RANGE.maxValue); } //A structure to hold measurements of a particle public class ParticleReport implements Comparator<ParticleReport>, Comparable<ParticleReport>{ double PercentAreaToImageArea; double Area; double BoundingRectLeft; double BoundingRectTop; double BoundingRectRight; double BoundingRectBottom; public int compareTo(ParticleReport r) { return (int)(r.Area - this.Area); } public int compare(ParticleReport r1, ParticleReport r2) { return (int)(r1.Area - r2.Area); } }; //Structure to represent the scores for the various tests used for target identification public class Scores { double Area; double Aspect; }; }
package org.ujoframework.gxt.server; import org.ujoframework.gxt.client.Cujo; import org.ujoframework.gxt.client.CujoProperty; import org.ujoframework.gxt.client.cquery.CBinaryCriterion; import org.ujoframework.gxt.client.cquery.CCriterion; import org.ujoframework.gxt.client.cquery.CQuery; import org.ujoframework.gxt.client.cquery.CValueCriterion; import java.util.ArrayList; import java.util.List; import org.ujoframework.UjoProperty; import org.ujoframework.core.UjoManager; import org.ujoframework.criterion.BinaryOperator; import org.ujoframework.criterion.Criterion; import org.ujoframework.criterion.Operator; import org.ujoframework.extensions.Property; import org.ujoframework.orm.OrmHandler; import org.ujoframework.orm.OrmUjo; import org.ujoframework.orm.Query; import org.ujoframework.orm.Session; import org.ujoframework.orm.metaModel.MetaTable; /** * Query translator * @author Pavel Ponec */ public class QueryTranslator<UJO extends OrmUjo> { /** Base type */ private final Class<? extends UJO> type; private final CQuery cquery; private final UjoManager manager = UjoManager.getInstance(); private final OrmHandler handler; private final IServerClassConfig config; @SuppressWarnings("unchecked") public QueryTranslator(CQuery cquery, OrmHandler handler, IServerClassConfig config) { if (!cquery.isRestored()) { try { cquery.restore(Class.forName(cquery.getTypeName())); } catch (ClassNotFoundException e) { String msg = "Can't get Class for the type: " + cquery.getTypeName(); throw new IllegalStateException(msg); } } this.cquery = cquery; this.type = (Class<UJO>) config.getServerClass(cquery.getTypeName()); this.handler = handler; this.config = config; if (type == null) { throw new IllegalStateException("Initializaton bug for type: " + cquery.getTypeName()); } } /** The query is translated without Session. Assign an open Session before excuting a database query. */ @SuppressWarnings({"unchecked"}) public Query<UJO> translate() { Criterion cn = getCriterion(); MetaTable metaTable = handler.findTableModel(type); Query<UJO> result = new Query(metaTable, cn); result.orderBy(orderBy(cquery.getOrderBy())); return result; } public Query<UJO> translate(Session session) { Query<UJO> result = translate(); result.setSession(session); return result; } public Criterion getCriterion() { return getCriterion(cquery.getCriterion()); } @SuppressWarnings("unchecked") protected Criterion getCriterion(CCriterion ccriterion) { Criterion result = null; if (ccriterion == null) { return result; } if (ccriterion.isBinary()) { final CBinaryCriterion c = (CBinaryCriterion) ccriterion; Criterion c1 = getCriterion(c.getLeftNode()); Criterion c2 = getCriterion(c.getRightNode()); BinaryOperator opt = BinaryOperator.valueOf(c.getOperator().getEnum().name()); if (c2 != null) { return c1.join(opt, c2); } else { return c1; } } else { final CValueCriterion c = (CValueCriterion) ccriterion; CujoProperty c1 = c.getLeftNode(); Object c2 = c.getRightNode(); UjoProperty p1; try { p1 = manager.findIndirectProperty(type, c1.getName()); } catch (IllegalArgumentException e) { p1 = Property.newInstance("["+c1.getName()+"]\u0020", Object.class); } Object p2; if (c2 instanceof CujoProperty) { p2 = manager.findIndirectProperty(type, ((CujoProperty) c2).getName()); } else if (c2 instanceof Cujo) { UjoTranslator translator = new UjoTranslator( ((Cujo) c2).readProperties(), UjoManager.getInstance().readProperties(p1.getType()), config); p2 = translator.translateToServer((Cujo) c2); } else { p2 = c2; } Operator opt = Operator.valueOf(c.getOperator().getEnum().name()); return Criterion.where(p1, opt, p2); } } public static <UJO extends OrmUjo> QueryTranslator<UJO> newInstance(CQuery cquery, OrmHandler handler, IServerClassConfig config) { return new QueryTranslator<UJO>(cquery, handler, config); } /** Convert from Cujo.orderBy to Ujo.orderBy */ public List<UjoProperty> orderBy(List<CujoProperty> properties) { List<UjoProperty> result = new ArrayList<UjoProperty>(); if (properties != null) { for (CujoProperty cp : properties) { UjoProperty up = manager.findIndirectProperty(type, cp.getName()); result.add(cp.isAscending() ? up : up.descending()); } } return result; } }
package com.haxademic.core.system; import java.awt.Frame; import processing.core.PApplet; import controlP5.ControlP5; @SuppressWarnings("serial") public class ControlFrame extends PApplet { Frame f; int w; int h; int x; int y; Object _parent; String _name; public void setup() { size(w, h); frameRate(30); } public void draw() { if( frameCount == 1 ) { createControlP5(_parent, _name); } if( f.isFocused() == true ) { background(0); } else { background(20); } } public ControlFrame(Object parent, int w, int h, int x, int y) { _parent = parent; _name = parent.getClass().getSimpleName(); this.w = w; this.h = h; this.x = x; this.y = y; createFrame(_name); } private void createFrame(String name) { f = new Frame(name); f.add(this); this.init(); f.setTitle(name); f.setSize(w, h); f.setLocation(x, y); f.setResizable(false); f.setVisible(true); } private void createControlP5(Object parent, String name) { ControlP5 cp5 = new ControlP5(this); cp5.addControllersFor(name, parent); } }
package com.hp.hpl.jena.rdf.arp.test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.*; import com.hp.hpl.jena.rdf.arp.*; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.vocabulary.RDF; import org.xml.sax.*; import java.io.*; /** * @author jjc * */ public class MoreTests extends TestCase implements RDFErrorHandler, ARPErrorNumbers { static private Log logger = LogFactory.getLog(MoreTests.class); static public Test suite() { TestSuite suite = new TestSuite("ARP Plus"); suite.addTest(TestErrorMsg.suite()); suite.addTest(TestScope.suite()); suite.addTest(new MoreTests("testEncodingMismatch1")); suite.addTest(new MoreTests("testEncodingMismatch2")); suite.addTest(new MoreTests("testNullBaseParamOK")); suite.addTest(new MoreTests("testNullBaseParamError")); suite.addTest(new MoreTests("testEmptyBaseParamOK")); suite.addTest(new MoreTests("testEmptyBaseParamError")); suite.addTest(new MoreTests("testWineDefaultNS")); suite.addTest(new MoreTests("testInterrupt")); return suite; } MoreTests(String s) { super(s); } protected Model createMemModel() { return ModelFactory.createDefaultModel(); } public void testWineDefaultNS() throws IOException { testWineNS(createMemModel()); testWineNS(ModelFactory.createOntologyModel()); } private void testWineNS(Model m) throws FileNotFoundException, IOException { InputStream in = new FileInputStream("testing/arp/xmlns/wine.rdf"); m.read(in, ""); in.close(); assertEquals( "http://www.w3.org/TR/2003/CR-owl-guide-20030818/wine m.getNsPrefixURI("")); } public void testEncodingMismatch1() throws IOException { Model m = createMemModel(); RDFReader rdr = m.getReader(); FileReader r = new FileReader("testing/wg/rdfms-syntax-incomplete/test001.rdf"); if (r.getEncoding().startsWith("UTF")) { System.err.println( "WARNING: Encoding mismatch tests not executed on platform with default UTF encoding."); return; } rdr.setErrorHandler(this); expected = new int[] { WARN_ENCODING_MISMATCH }; rdr.read(m, r, "http://example.org/"); //System.err.println(m.size() + " triples read."); checkExpected(); } public void testEncodingMismatch2() throws IOException { Model m = createMemModel(); RDFReader rdr = m.getReader(); FileReader r = new FileReader("testing/wg/rdf-charmod-literals/test001.rdf"); if (r.getEncoding().startsWith("UTF")) { // see above for warning message. return; } rdr.setErrorHandler(this); expected = new int[] { WARN_ENCODING_MISMATCH, ERR_ENCODING_MISMATCH }; rdr.read(m, r, "http://example.org/"); checkExpected(); } public void testNullBaseParamOK() throws IOException { Model m = createMemModel(); Model m1 = createMemModel(); RDFReader rdr = m.getReader(); FileInputStream fin = new FileInputStream("testing/wg/rdfms-identity-anon-resources/test001.rdf"); rdr.setErrorHandler(this); expected = new int[] { }; rdr.read(m, fin, "http://example.org/"); fin.close(); fin = new FileInputStream("testing/wg/rdfms-identity-anon-resources/test001.rdf"); rdr.read(m1, fin, null); fin.close(); assertTrue("Base URI should have no effect.", m.isIsomorphicWith(m1)); checkExpected(); } public void testNullBaseParamError() throws IOException { Model m = createMemModel(); RDFReader rdr = m.getReader(); FileInputStream fin = new FileInputStream("testing/wg/rdfms-difference-between-ID-and-about/test1.rdf"); rdr.setErrorHandler(this); expected = new int[] { ERR_RESOLVING_URI_AGAINST_NULL_BASE }; rdr.read(m, fin, null); fin.close(); checkExpected(); } public void testEmptyBaseParamOK() throws IOException { Model m = createMemModel(); Model m1 = createMemModel(); RDFReader rdr = m.getReader(); FileInputStream fin = new FileInputStream("testing/wg/rdfms-identity-anon-resources/test001.rdf"); rdr.setErrorHandler(this); expected = new int[] { }; rdr.read(m, fin, "http://example.org/"); fin.close(); fin = new FileInputStream("testing/wg/rdfms-identity-anon-resources/test001.rdf"); rdr.read(m1, fin, ""); fin.close(); assertTrue( "Empty base URI should have no effect.[" + m1.toString() + "]", m.isIsomorphicWith(m1)); checkExpected(); } public void testEmptyBaseParamError() throws IOException { Model m = createMemModel(); RDFReader rdr = m.getReader(); FileInputStream fin = new FileInputStream("testing/wg/rdfms-difference-between-ID-and-about/test1.rdf"); rdr.setErrorHandler(this); expected = new int[] { WARN_RESOLVING_URI_AGAINST_EMPTY_BASE }; rdr.read(m, fin, ""); fin.close(); Model m1 = createMemModel(); m1.createResource("#foo").addProperty(RDF.value, "abc"); assertTrue( "Empty base URI should produce relative URI.[" + m.toString() + "]", m.isIsomorphicWith(m1)); checkExpected(); } public void testInterrupt() throws SAXException, IOException { ARP a = new ARP(); InputStream in; long start = System.currentTimeMillis(); in = new FileInputStream("testing/wg/miscellaneous/consistent001.rdf"); a.load(in); in.close(); final long tim = (System.currentTimeMillis() - start) / 3; if (tim < 5) { logger.warn("Jena is too quick on this machine for this test"); return; } final Thread arpt = Thread.currentThread(); Thread killt = new Thread(new Runnable() { public void run() { try { Thread.sleep(tim); } catch (InterruptedException e) { } arpt.interrupt(); // System.err.println("Interrupted"); } }); try { killt.start(); in = new FileInputStream("testing/wg/miscellaneous/consistent001.rdf"); a.load(in); in.close(); fail("Thread was not interrupted."); } catch (InterruptedIOException e) { } catch (SAXParseException e) { } // System.err.println("Finished "+Thread.interrupted()); } private void checkExpected() { for (int i = 0; i < expected.length; i++) if (expected[i] != 0) { fail( "Expected error: " + JenaReader.errorCodeName(expected[i]) + " but it did not occur."); } } public void warning(Exception e) { error(0, e); } public void error(Exception e) { error(1, e); } public void fatalError(Exception e) { error(2, e); } private void error(int level, Exception e) { //System.err.println(e.getMessage()); if (e instanceof ParseException) { int eCode = ((ParseException) e).getErrorNumber(); onError(level, eCode); } else { fail("Not expecting an Exception: " + e.getMessage()); } } private int expected[]; private void println(String m) { logger.error(m); } void onError(int level, int num) { for (int i = 0; i < expected.length; i++) if (expected[i] == num) { expected[i] = 0; return; } String msg = "Parser reports unexpected " + WGTestSuite.errorLevelName[level] + ": " + JenaReader.errorCodeName(num); println(msg); fail(msg); } }
package com.msd.control.viewers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.msd.items.Appeal; import com.msd.items.Applicant; import com.msd.items.LoginInfo; import com.msd.items.Vacancy; import com.msd.pool.items.PoolApplicants; import com.msd.pool.items.PoolCompanies; import com.msd.pool.items.PoolPasswords; import com.msd.pool.items.PoolRequests; import com.msd.pool.items.PoolVacancies; @Controller @RequestMapping("user") public class UserController { @Autowired PoolPasswords poolPW; @Autowired PoolApplicants poolApplicants; @Autowired PoolVacancies poolVacancies; @Autowired PoolCompanies poolCompanies; @Autowired PoolRequests poolRequests; private @Autowired AuthenticationManager authenticationManager; @RequestMapping(value = "/login", method = RequestMethod.POST) public String logUserIn(@ModelAttribute("info") LoginInfo info, ModelMap model, RedirectAttributes redirects) { try { poolPW.makeActive(info.getUsername()); Authentication request = new UsernamePasswordAuthenticationToken(info.getUsername(), info.getPassword()); Authentication result = authenticationManager.authenticate(request); SecurityContextHolder.getContext().setAuthentication(result); redirects.addFlashAttribute("msg", "Logged in successfully!"); redirects.addFlashAttribute("css", "info"); return "redirect:/user/view/" + info.getUsername(); } catch (AuthenticationException ex) { System.out.println(ex.getMessage()); redirects.addFlashAttribute("msg", "Username or Password is wrong!"); redirects.addFlashAttribute("css", "danger"); return "redirect:/user_login"; } } @RequestMapping(value = "/view/{indexNumber}", method = RequestMethod.GET) public String userHomePage(Model model, @PathVariable("indexNumber") String indexNumber, RedirectAttributes redirects) { // Fetch the applicant Authentication auth = SecurityContextHolder.getContext().getAuthentication(); System.out.println(auth); // {indexNumber} is not required, it can be fetch from auth.getName() which is the username. That can be used to fetc data for logged in user Applicant user = poolApplicants.fetchApplicant(indexNumber); model.addAttribute("user", user); // If the user got a chance already, show the congratulation message if (user.isAwarded()) { Vacancy award = poolVacancies.fetchVacancy(user.getAwardedVacancy()); award.setCompanyName(poolCompanies.getCompanyName(award.getCompanyID())); model.addAttribute("congrats", award); } else { // Fetch the list of vacancies List<Vacancy> vacancies = poolVacancies.getVacancies(user.convertListToPref()); for (Vacancy vacancy : vacancies) { vacancy.setCompanyName(poolCompanies.getCompanyName(vacancy.getCompanyID())); } model.addAttribute("vacancies", vacancies); } return "displays/show_user"; } @RequestMapping(value = "/apply/{vacancyID}/{indexNumber}/{choice}", method = RequestMethod.POST) public String applyForVacancy(@PathVariable("vacancyID") int vacancyID, Model model, @PathVariable("indexNumber") String indexNumber, @PathVariable("choice") int choice, RedirectAttributes redirects) { // Update the vacancy table by closing the vacancy with applicant name poolVacancies.closeVacancy(vacancyID, indexNumber, choice); // Update the user table giving the choice to the applicant poolApplicants.setChoice(indexNumber, choice, vacancyID); // Pass the successful message to redirect redirects.addFlashAttribute("msg", "Application submitted succesfully!"); redirects.addFlashAttribute("css", "success"); return "redirect:/user/view/" + indexNumber; } @RequestMapping(value = "/cancel/{vacancyID}/{indexNumber}/{choice}", method = RequestMethod.POST) public String cancelVacancy(@PathVariable("vacancyID") int vacancyID, Model model, @PathVariable("indexNumber") String indexNumber, @PathVariable("choice") int choice, RedirectAttributes redirects) { // Update the vacancy table by closing the vacancy with applicant name poolVacancies.openVacancy(vacancyID); // Update the user table giving the choice to the applicant poolApplicants.removeChoice(indexNumber, choice); // Pass the successful message to redirect redirects.addFlashAttribute("msg", "Application Cancelled!"); redirects.addFlashAttribute("css", "warning"); return "redirect:/user/view/" + indexNumber; } @RequestMapping(value = "/request/{vacancyID}/{indexNumber}", method = RequestMethod.POST) public String requestVacancy(@PathVariable("vacancyID") int vacancyID, Model model, @PathVariable("indexNumber") String indexNumber, RedirectAttributes redirects) { // Generate the request Appeal appeal = new Appeal(vacancyID, indexNumber); // Add the request to the request table appeal.setGradedPoint(poolApplicants.getGPA(indexNumber)); appeal.setVacancyName(poolVacancies.getVacancyName(vacancyID)); appeal.setCurrentNumber(poolVacancies.getApplicant(vacancyID)); appeal.setCurrentGradedPoint(poolApplicants.getGPA(appeal.getCurrentNumber())); poolRequests.addRequest(appeal); poolApplicants.addRequest(indexNumber, vacancyID); // Pass the successful message to redirect redirects.addFlashAttribute("msg", "Request sent to administrator!"); redirects.addFlashAttribute("css", "info"); return "redirect:/user/view/" + indexNumber; } @RequestMapping(value = "/request/cancel/{indexNumber}", method = RequestMethod.POST) public String cancelRequestedVacancy(Model model, @PathVariable("indexNumber") String indexNumber, RedirectAttributes redirects) { // Delete the request poolApplicants.deleteRequest(indexNumber); poolRequests.deleteRequestsByUser(indexNumber); // Pass the successful message to redirect redirects.addFlashAttribute("msg", "Request cancelled!"); redirects.addFlashAttribute("css", "info"); return "redirect:/user/view/" + indexNumber; } @RequestMapping(value = "/logout/{indexNumber}", method = RequestMethod.POST) public String logOut(Model model, @PathVariable("indexNumber") String indexNumber, RedirectAttributes redirects) { // Generate the request poolPW.makeInactive(indexNumber); // Pass the successful message to redirect redirects.addFlashAttribute("msg", "Logged out!"); redirects.addFlashAttribute("css", "success"); return "redirect:/"; } }
package com.muhavision.control; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.UnknownHostException; import com.codeminders.ardrone.ARDrone; import com.codeminders.ardrone.NavData; import com.codeminders.ardrone.NavDataListener; import com.codeminders.ardrone.util.BufferedImageVideoListener; import com.muhavision.cv.OpticalFlowCalculator; import com.muhavision.cv.QuadrantFlowSpeed; import com.muhavision.cv.image.VisualRenderer; import com.muhavision.pid.PID; public class DroneController { PID roll = new PID(1, 1, 0, 10, PID.Direction.NORMAL); OpticalFlowCalculator calc = new OpticalFlowCalculator(); ARDrone drone = null; NavData data = null; BufferedImage quadImage = null; public DroneController(final VisualRenderer visual) { System.out.println("Drone controller loading..."); try { drone = new ARDrone(); drone.connect(); drone.addImageListener(new BufferedImageVideoListener() { @Override public void imageReceived(BufferedImage image) { quadImage = image; } }); drone.addNavDataListener(new NavDataListener() { @Override public void navDataReceived(NavData fdata) { data = fdata; } }); Thread t = new Thread(){ public void run(){ while(true){ long millis = System.currentTimeMillis(); QuadrantFlowSpeed speed = null; EulerAngles angle = null; if(visual.global_main.flightMode!=null) if (visual.global_main.flightMode.getMode() == FlightMode.eMode.MUHA_MODE) speed = calc.getFlowData(quadImage); else if (visual.global_main.flightMode.getMode() == FlightMode.eMode.TAG_MODE) angle = MarkerControl .getControlDataAndPictureDataBasedOnNavData(data); visual.reloadDatas(quadImage, speed, data, angle); millis = System.currentTimeMillis() - millis; try { if(millis<70) Thread.sleep(70-millis); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public ARDrone getDrone() { return drone; } }
package com.rapid.security; import java.lang.reflect.InvocationTargetException; import javax.servlet.ServletContext; import com.rapid.core.Application; import com.rapid.server.RapidRequest; public class FormSecurityAdapter extends RapidSecurityAdapter { // constructor public FormSecurityAdapter(ServletContext servletContext, Application application) throws SecurityException,IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // call the super constructor super(servletContext, application); } // overrides @Override public User getUser(RapidRequest rapidRequest) throws SecurityAdapaterException { // first try and get the user with the super method User user = super.getUser(rapidRequest); // if that didn't find anyone set to a password-less user from the session / connection adapter, unless new app if (user == null && !"newapp".equals(rapidRequest.getActionName())) user = new User(rapidRequest.getUserName(),"Public form user","", "", ""); // return return user; } @Override public boolean checkUserPassword(RapidRequest rapidRequest, String userName, String password) throws SecurityAdapaterException { // assume we don't need to check the password properly boolean check = false; // get the action String action = rapidRequest.getActionName(); // if there was one if (action != null) { // if this is an import we want to check the password properly so a fail will add the current user to the app if ("import".equals(action)) check = true; } // get the request uri String uri = rapidRequest.getRequest().getRequestURI(); // if there was one if (uri != null) { // if this was a login .jsp page we need to check if (uri.toLowerCase().contains("login") && uri.toLowerCase().endsWith(".jsp")) check = true; } // check will be true if the request to check came from a more sensitive area if (check) { // check the password properly return super.checkUserPassword(rapidRequest, userName, password); } else { // everyone is allowed return true; } } }